text stringlengths 8 4.13M |
|---|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_expression::types::DataType;
use common_expression::DataField;
use common_expression::DataSchemaRef;
use common_expression::DataSchemaRefExt;
use common_meta_app::principal::StageInfo;
use time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PresignAction {
Download,
Upload,
}
#[derive(Debug, Clone)]
pub struct PresignPlan {
pub stage: Box<StageInfo>,
pub path: String,
pub action: PresignAction,
pub expire: Duration,
pub content_type: Option<String>,
}
impl PresignPlan {
pub fn schema(&self) -> DataSchemaRef {
DataSchemaRefExt::create(vec![
DataField::new("method", DataType::String),
DataField::new("headers", DataType::Variant),
DataField::new("url", DataType::String),
])
}
}
|
use crate::*;
use std::fmt;
#[derive(Deserialize, Serialize, Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum ClearRank {
F,
E,
D,
C,
B,
A,
AA,
AAA,
Unknown,
}
impl Default for ClearRank {
fn default() -> ClearRank {
ClearRank::F
}
}
impl ClearRank {
pub fn from_notes_score(notes: i32, score: ExScore) -> ClearRank {
let max = notes * 2;
if max == 0 {
return ClearRank::F;
}
match score.ex_score() {
x if x >= max * 8 / 9 => ClearRank::AAA,
x if x >= max * 7 / 9 => ClearRank::AA,
x if x >= max * 6 / 9 => ClearRank::A,
x if x >= max * 5 / 9 => ClearRank::B,
x if x >= max * 4 / 9 => ClearRank::C,
x if x >= max * 3 / 9 => ClearRank::D,
x if x >= max * 2 / 9 => ClearRank::E,
_ => ClearRank::F,
}
}
pub fn from_integer(int: i32) -> ClearRank {
match int {
0 => ClearRank::F,
1 => ClearRank::E,
2 => ClearRank::D,
3 => ClearRank::C,
4 => ClearRank::B,
5 => ClearRank::A,
6 => ClearRank::AA,
7 => ClearRank::AAA,
_ => ClearRank::Unknown,
}
}
}
impl fmt::Display for ClearRank {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ClearRank::F => write!(f, "F"),
ClearRank::E => write!(f, "E"),
ClearRank::D => write!(f, "D"),
ClearRank::C => write!(f, "C"),
ClearRank::B => write!(f, "B"),
ClearRank::A => write!(f, "A"),
ClearRank::AA => write!(f, "AA"),
ClearRank::AAA => write!(f, "AAA"),
ClearRank::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
let obj = ClearRank::from_notes_score(450, ExScore::from_score(0));
assert_eq!(format!("{}", obj), "F");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(199));
assert_eq!(format!("{}", obj), "F");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(200));
assert_eq!(format!("{}", obj), "E");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(299));
assert_eq!(format!("{}", obj), "E");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(300));
assert_eq!(format!("{}", obj), "D");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(399));
assert_eq!(format!("{}", obj), "D");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(400));
assert_eq!(format!("{}", obj), "C");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(499));
assert_eq!(format!("{}", obj), "C");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(500));
assert_eq!(format!("{}", obj), "B");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(599));
assert_eq!(format!("{}", obj), "B");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(600));
assert_eq!(format!("{}", obj), "A");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(699));
assert_eq!(format!("{}", obj), "A");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(700));
assert_eq!(format!("{}", obj), "AA");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(799));
assert_eq!(format!("{}", obj), "AA");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(800));
assert_eq!(format!("{}", obj), "AAA");
let obj = ClearRank::from_notes_score(450, ExScore::from_score(900));
assert_eq!(format!("{}", obj), "AAA");
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use std::sync::Once;
use metrics::counter;
use metrics::decrement_gauge;
use metrics::gauge;
use metrics::histogram;
use metrics::increment_gauge;
use metrics_exporter_prometheus::PrometheusBuilder;
use metrics_exporter_prometheus::PrometheusHandle;
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use tracing::warn;
static PROMETHEUS_HANDLE: Lazy<Arc<RwLock<Option<PrometheusHandle>>>> =
Lazy::new(|| Arc::new(RwLock::new(None)));
pub const LABEL_KEY_TENANT: &str = "tenant";
pub const LABEL_KEY_CLUSTER: &str = "cluster_name";
#[inline]
pub fn label_histogram_with_val(
name: &'static str,
labels: &Vec<(&'static str, String)>,
val: f64,
) {
histogram!(name, val, labels);
}
#[inline]
pub fn label_counter_with_val_and_labels(
name: &'static str,
labels: &Vec<(&'static str, String)>,
val: u64,
) {
counter!(name, val, labels);
}
#[inline]
pub fn label_gauge_with_val_and_labels(
name: &'static str,
labels: &Vec<(&'static str, String)>,
val: f64,
) {
gauge!(name, val, labels);
}
#[inline]
pub fn label_increment_gauge_with_val_and_labels(
name: &'static str,
labels: &Vec<(&'static str, String)>,
val: f64,
) {
increment_gauge!(name, val, labels);
}
#[inline]
pub fn label_decrement_gauge_with_val_and_labels(
name: &'static str,
labels: &Vec<(&'static str, String)>,
val: f64,
) {
decrement_gauge!(name, val, labels);
}
#[inline]
pub fn label_counter(name: &'static str, tenant_id: &str, cluster_id: &str) {
label_counter_with_val(name, 1, tenant_id, cluster_id)
}
#[inline]
pub fn label_counter_with_val(name: &'static str, val: u64, tenant_id: &str, cluster_id: &str) {
let labels = [
(LABEL_KEY_TENANT, tenant_id.to_string()),
(LABEL_KEY_CLUSTER, cluster_id.to_string()),
];
counter!(name, val, &labels);
}
#[inline]
pub fn label_gauge(name: &'static str, val: f64, tenant_id: &str, cluster_id: &str) {
let labels = [
(LABEL_KEY_TENANT, tenant_id.to_string()),
(LABEL_KEY_CLUSTER, cluster_id.to_string()),
];
gauge!(name, val, &labels);
}
pub fn init_default_metrics_recorder() {
static START: Once = Once::new();
START.call_once(init_prometheus_recorder)
}
/// Init prometheus recorder.
fn init_prometheus_recorder() {
let recorder = PrometheusBuilder::new().build_recorder();
let mut h = PROMETHEUS_HANDLE.as_ref().write();
*h = Some(recorder.handle());
unsafe {
metrics::clear_recorder();
}
match metrics::set_boxed_recorder(Box::new(recorder)) {
Ok(_) => (),
Err(err) => warn!("Install prometheus recorder failed, cause: {}", err),
};
}
pub fn try_handle() -> Option<PrometheusHandle> {
PROMETHEUS_HANDLE.as_ref().read().clone()
}
|
pub mod webcam;
|
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use futures;
use futures::{Future, Poll, Stream};
use hyper::client::HttpConnector;
use hyper::{Client, Request, Uri};
use hyper_rustls::HttpsConnector;
use tokio_timer::Timeout;
use crate::batch::BatchStream;
use crate::channel::Message;
use crate::error::Error;
/// Default request timeout in seconds.
const DEFAULT_REQUEST_TIMEOUT: u64 = 5;
/// LogglyClient builder.
pub struct LogglyClientBuilder {
token: String,
tag: String,
request_timeout: Duration,
debug: bool,
connector: Option<HttpsConnector<HttpConnector>>,
}
impl LogglyClientBuilder {
/// Create a new builder. Use a given Loggly token and tag.
fn new(token: &str, tag: &str) -> LogglyClientBuilder {
let request_timeout = Duration::from_secs(DEFAULT_REQUEST_TIMEOUT);
LogglyClientBuilder {
token: token.to_string(),
tag: tag.to_string(),
request_timeout,
debug: false,
connector: None,
}
}
/// Enable or disable debug mode (it's disabled by default). In the debug
/// mode you'll be able to see some runtime info on stderr that will help
/// you with setting up the drain (e.g. failed requests). With debug mode
/// disabled, all errors will be silently ignored.
pub fn debug_mode(mut self, enable: bool) -> LogglyClientBuilder {
self.debug = enable;
self
}
/// Set Loggly request timeout (the default is 5 seconds).
pub fn request_timeout(mut self, timeout: Duration) -> LogglyClientBuilder {
self.request_timeout = timeout;
self
}
/// Use a given HttpsConnector.
pub fn connector(mut self, connector: HttpsConnector<HttpConnector>) -> LogglyClientBuilder {
self.connector = Some(connector);
self
}
/// Create the LogglyClient.
pub fn build(self) -> Result<LogglyClient, Error> {
let connector;
if let Some(c) = self.connector {
connector = c;
} else {
connector = HttpsConnector::new(1);
}
let client = Client::builder().build(connector);
let url = format!(
"https://logs-01.loggly.com/bulk/{}/tag/{}/",
self.token, self.tag
);
let url = url
.parse()
.map_err(|_| Error::from("unable to parse Loggly URL"))?;
let url = Arc::new(url);
let res = LogglyClient {
url,
timeout: self.request_timeout,
debug: self.debug,
client,
};
Ok(res)
}
}
/// Loggly client.
#[derive(Clone)]
pub struct LogglyClient {
url: Arc<Uri>,
timeout: Duration,
debug: bool,
client: Client<HttpsConnector<HttpConnector>>,
}
impl LogglyClient {
/// Create a new client builder.
pub fn builder(token: &str, tag: &str) -> LogglyClientBuilder {
LogglyClientBuilder::new(token, tag)
}
/// Send a given batch of messages.
pub fn batch_send<I>(&self, messages: I) -> impl Future<Item = (), Error = ()>
where
I: IntoIterator<Item = Bytes>,
{
let mut batch = Vec::<u8>::new();
for msg in messages {
batch.extend_from_slice(msg.as_ref());
batch.push(b'\n');
}
self.send(Bytes::from(batch))
}
/// Return a future that will ensure sending a given log message.
pub fn send(&self, msg: Bytes) -> impl Future<Item = (), Error = ()> {
let client = self.clone();
futures::stream::repeat(())
.take_while(move |_| {
client.try_send(msg.clone()).then(|res| match res {
Ok(_) => Ok(false),
Err(_) => Ok(true),
})
})
.for_each(|_| Ok(()))
}
/// Return a future that will try to send a given log message.
pub fn try_send(&self, msg: Bytes) -> impl Future<Item = (), Error = Error> {
let request = Request::post(&*self.url)
.header("Content-Type", "text/plain")
.body(msg.into())
.map_err(|_| Error::from("unable to create a request body"));
let client = self.client.clone();
let fut = futures::future::result(request)
.and_then(move |request| {
client
.request(request)
.map_err(|err| Error::from(format!("unable to send a request: {}", err)))
})
.and_then(|res| {
let status = res.status();
res.into_body()
.concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|err| Error::from(format!("unable to read a response body: {}", err)))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(())
} else {
let body = String::from_utf8_lossy(&body);
Err(Error::from(format!(
"server responded with HTTP {}:\n{}",
status, body
)))
}
});
let debug = self.debug;
Timeout::new(fut, self.timeout).map_err(move |err| {
if debug {
eprintln!("Loggly request failed: {}", err);
}
if err.is_inner() {
err.into_inner().unwrap()
} else if err.is_elapsed() {
Error::from("request timeout")
} else {
Error::from("timer error")
}
})
}
/// Consume all messages from a given stream and send them to Loggly.
pub fn send_all<S>(
self,
messages: S,
batch_size: usize,
sender_count: usize,
) -> LogglyMessageSender
where
S: 'static + Stream<Item = Message<Bytes>, Error = ()> + Send,
{
let sender = messages
.batch_stream(batch_size)
.and_then(move |messages| {
let mut batch = Vec::new();
let mut dhandles = Vec::new();
for msg in messages.into_iter() {
let (payload, dhandle) = msg.deconstruct();
batch.push(payload);
dhandles.push(dhandle);
}
let future = self.batch_send(batch).and_then(move |_| {
// mark all messages as deleted once they are sent
for mut dhandle in dhandles {
dhandle.delete();
}
Ok(())
});
Ok(future)
})
.buffered(sender_count)
.for_each(|_| Ok(()));
LogglyMessageSender {
inner: Box::new(sender),
}
}
}
/// A future driving the send of all log messages.
pub struct LogglyMessageSender {
inner: Box<Future<Item = (), Error = ()> + Send>,
}
impl Future for LogglyMessageSender {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
self.inner.poll()
}
}
|
mod auto_saver;
pub use auto_saver::{AutoSaver, SAVE_NOW};
mod command_receiver;
pub use command_receiver::CommandReceiver;
mod ticker;
pub use ticker::Ticker;
mod enter;
pub use enter::EnterController;
mod backend;
pub use backend::msg as backend_msg;
pub use backend::BackendController;
mod close;
pub use close::CloseController;
|
//我们有一系列公交路线。每一条路线 routes[i] 上都有一辆公交车在上面循环行驶。例如,有一条路线 routes[0] = [1, 5, 7],表示第一
//辆 (下标为0) 公交车会一直按照 1->5->7->1->5->7->1->... 的车站路线行驶。
//
// 假设我们从 S 车站开始(初始时不在公交车上),要去往 T 站。 期间仅可乘坐公交车,求出最少乘坐的公交车数量。返回 -1 表示不可能到达终点车站。
//
//
//示例:
//输入:
//routes = [[1, 2, 7], [3, 6, 7]]
//S = 1
//T = 6
//输出: 2
//解释:
//最优策略是先乘坐第一辆公交车到达车站 7, 然后换乘第二辆公交车到车站 6。
//
//
// 说明:
//
//
// 1 <= routes.length <= 500.
// 1 <= routes[i].length <= 500.
// 0 <= routes[i][j] < 10 ^ 6.
//
// Related Topics 广度优先搜索
//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
pub fn num_buses_to_destination(routes: Vec<Vec<i32>>, s: i32, t: i32) -> i32 {
use std::collections::*;
let mut map = HashMap::new();
for (route_idx, route) in routes.iter().enumerate() {
for x in route {
map.entry(x).or_insert(HashSet::new()).insert(route_idx);
}
}
let mut to_visited = VecDeque::new();
// (当前换乘了几次 当前所在站点 已经搭乘过的车次 )
to_visited.push_back((0, s, HashSet::new()));
while let Some(station) = to_visited.pop_front() {
if station.1 == t {
return station.0;
}
map.get(&station.1)
.unwrap()
.iter()
.filter(|it| !station.2.contains(it))
.for_each(|idx| {
routes.get(*idx).unwrap().iter().for_each(|it| {
let mut vec = station.2.clone();
vec.insert(idx);
to_visited.push_back((station.0 + 1, *it, vec));
})
})
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
struct Solution {}
fn main() {
use std::time::Instant;
let v = vec![vec![1, 2, 7], vec![3, 6, 7], vec![5, 6, 11]];
let now = Instant::now();
let s = Solution::num_buses_to_destination(v, 1, 11);
let now2 = Instant::now();
dbg!(s);
dbg!(now2 - now);
}
|
// reexport sodiumoxide
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
#![feature(use_extern_macros)]
pub extern crate sodiumoxide;
extern crate wasm_bindgen;
extern crate libc_stub; // see comments on this crate for what this is
extern crate openssl;
use openssl::sha;
fn hashopenssl() {
let mut hasher = sha::Sha256::new();
hasher.update(b"Hello, ");
hasher.update(b"world");
let hash = hasher.finish();
println!("Hashed \"Hello, world\" to {}", AsHex(hash.as_ref()));
}
use std::fmt::{self, Write};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern {
#[wasm_bindgen(js_namespace = console)]
fn log(a: &str);
}
macro_rules! console_log {
($($t:tt)*) => (log(&format!($($t)*)))
}
#[cfg(feature="wasm-tests")]
#[wasm_bindgen]
pub fn tests() {
sodium_asym();
hashopenssl();
}
fn sodium_asym() {
sodiumoxide::init().unwrap();
use sodiumoxide::crypto::sign;
let (pk, sk) = sign::gen_keypair();
let data_to_sign = b"some data";
let signed_data = sign::sign(data_to_sign, &sk);
let verified_data = sign::verify(&signed_data, &pk).unwrap();
assert!(data_to_sign == &verified_data[..]);
let (pk, sk) = sign::gen_keypair();
let data_to_sign = b"some data";
let signature = sign::sign_detached(data_to_sign, &sk);
assert!(sign::verify_detached(&signature, data_to_sign, &pk));
console_log!("assert pass for sign sample");
}
#[wasm_bindgen]
pub fn run() {
sodiumoxide::init().unwrap();
// Generate some random bytes
//
// NB the random byte generator is very low quality, it's implemented in
// the `libc-shim` crate via `read` currently.
let bytes = sodiumoxide::randombytes::randombytes(10);
console_log!("10 randomly generated bytes are {:?}", bytes);
// Generate a sha256 digest
let mut h = sodiumoxide::crypto::hash::sha256::State::new();
h.update(b"Hello, World!");
let digest = h.finalize();
console_log!("sha256(\"Hello, World!\") = {}", AsHex(digest.as_ref()));
}
struct AsHex<'a>(&'a [u8]);
impl<'a> fmt::Display for AsHex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &byte in self.0.iter() {
f.write_char(btoc(byte >> 4))?;
f.write_char(btoc(byte))?;
}
return Ok(());
fn btoc(a: u8) -> char {
let a = a & 0xf;
match a {
0...9 => (b'0' + a) as char,
_ => (b'a' + a - 10) as char,
}
}
}
}
|
use std::char;
use std::str;
use std::cmp;
use {
TextPos,
StreamError,
StrSpan,
XmlByteExt,
XmlCharExt,
};
type Result<T> = ::std::result::Result<T, StreamError>;
/// Representation of the [Reference](https://www.w3.org/TR/xml/#NT-Reference) value.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum Reference<'a> {
/// An entity reference.
///
/// <https://www.w3.org/TR/xml/#NT-EntityRef>
EntityRef(&'a str),
/// A character reference.
///
/// <https://www.w3.org/TR/xml/#NT-CharRef>
CharRef(char),
}
/// A streaming text parsing interface.
#[derive(PartialEq, Clone, Copy, Debug)]
pub struct Stream<'a> {
bytes: &'a [u8],
pos: usize,
end: usize,
span: StrSpan<'a>,
}
impl<'a> From<&'a str> for Stream<'a> {
fn from(text: &'a str) -> Self {
Stream {
bytes: text.as_bytes(),
pos: 0,
end: text.len(),
span: text.into(),
}
}
}
impl<'a> From<StrSpan<'a>> for Stream<'a> {
fn from(span: StrSpan<'a>) -> Self {
Stream {
bytes: span.to_str().as_bytes(),
pos: 0,
end: span.len(),
span,
}
}
}
impl<'a> Stream<'a> {
/// Returns an underling string span.
pub fn span(&self) -> StrSpan<'a> {
self.span
}
/// Returns current position.
pub fn pos(&self) -> usize {
self.pos
}
/// Sets current position equal to the end.
///
/// Used to indicate end of parsing on error.
pub fn jump_to_end(&mut self) {
self.pos = self.end;
}
/// Checks if the stream is reached the end.
///
/// Any [`pos()`] value larger than original text length indicates stream end.
///
/// Accessing stream after reaching end via safe methods will produce
/// an `UnexpectedEndOfStream` error.
///
/// Accessing stream after reaching end via *_unchecked methods will produce
/// a Rust's bound checking error.
///
/// [`pos()`]: #method.pos
#[inline]
pub fn at_end(&self) -> bool {
self.pos >= self.end
}
/// Returns a byte from a current stream position.
///
/// # Errors
///
/// - `UnexpectedEndOfStream`
pub fn curr_byte(&self) -> Result<u8> {
if self.at_end() {
return Err(StreamError::UnexpectedEndOfStream);
}
Ok(self.curr_byte_unchecked())
}
/// Returns a byte from a current stream position.
///
/// # Panics
///
/// - if the current position is after the end of the data
#[inline]
pub fn curr_byte_unchecked(&self) -> u8 {
self.bytes[self.pos]
}
/// Checks that current byte is equal to provided.
///
/// Returns `false` if no bytes left.
#[inline]
pub fn is_curr_byte_eq(&self, c: u8) -> bool {
if !self.at_end() {
self.curr_byte_unchecked() == c
} else {
false
}
}
/// Returns a byte from a current stream position if there is one.
#[inline]
pub fn get_curr_byte(&self) -> Option<u8> {
if !self.at_end() {
Some(self.curr_byte_unchecked())
} else {
None
}
}
/// Returns a next byte from a current stream position.
///
/// # Errors
///
/// - `UnexpectedEndOfStream`
pub fn next_byte(&self) -> Result<u8> {
if self.pos + 1 >= self.end {
return Err(StreamError::UnexpectedEndOfStream);
}
Ok(self.bytes[self.pos + 1])
}
/// Returns a char from a current stream position.
///
/// # Errors
///
/// - `UnexpectedEndOfStream`
pub fn curr_char(&self) -> Result<char> {
if self.at_end() {
return Err(StreamError::UnexpectedEndOfStream);
}
Ok(self.curr_char_unchecked())
}
#[inline]
fn curr_char_unchecked(&self) -> char {
self.span.to_str()[self.pos..].chars().next().unwrap()
}
/// Advances by `n` bytes.
///
/// # Examples
///
/// ```rust,should_panic
/// use xmlparser::Stream;
///
/// let mut s = Stream::from("text");
/// s.advance(2); // ok
/// s.advance(20); // will cause a panic via debug_assert!().
/// ```
#[inline]
pub fn advance(&mut self, n: usize) {
debug_assert!(self.pos + n <= self.end);
self.pos += n;
}
/// Skips whitespaces.
///
/// Accepted values: `' ' \n \r \t   	 
 
`.
///
/// # Examples
///
/// ```
/// use xmlparser::Stream;
///
/// let mut s = Stream::from(" \t\n\r   ");
/// s.skip_spaces();
/// assert_eq!(s.at_end(), true);
/// ```
pub fn skip_spaces(&mut self) {
while !self.at_end() {
let c = self.curr_byte_unchecked();
if c.is_xml_space() {
self.advance(1);
} else if c == b'&' {
// Check for (#x20 | #x9 | #xD | #xA).
let start = self.pos();
let mut is_space = false;
if let Ok(Reference::CharRef(ch)) = self.consume_reference() {
if (ch as u32) < 255 && (ch as u8).is_xml_space() {
is_space = true;
}
}
if !is_space {
self.pos = start;
break;
}
} else {
break;
}
}
}
/// Skips ASCII whitespaces.
///
/// Accepted values: `' ' \n \r \t`.
pub fn skip_ascii_spaces(&mut self) {
while !self.at_end() {
if self.curr_byte_unchecked().is_xml_space() {
self.advance(1);
} else {
break;
}
}
}
/// Checks that the stream starts with a selected text.
///
/// We are using `&[u8]` instead of `&str` for performance reasons.
///
/// # Examples
///
/// ```
/// use xmlparser::Stream;
///
/// let mut s = Stream::from("Some text.");
/// s.advance(5);
/// assert_eq!(s.starts_with(b"text"), true);
/// assert_eq!(s.starts_with(b"long"), false);
/// ```
#[inline]
pub fn starts_with(&self, text: &[u8]) -> bool {
self.bytes[self.pos..self.end].starts_with(text)
}
/// Checks if the stream is starts with a space.
///
/// Uses [`skip_spaces()`](#method.curr_byte) internally.
pub fn starts_with_space(&self) -> bool {
if self.at_end() {
return false;
}
let mut is_space = false;
let c = self.curr_byte_unchecked();
if c.is_xml_space() {
is_space = true;
} else if c == b'&' {
// Check for (#x20 | #x9 | #xD | #xA).
let mut s = *self;
if let Some(Reference::CharRef(v)) = s.try_consume_reference() {
if (v as u32) < 255 && (v as u8).is_xml_space() {
is_space = true;
}
}
}
is_space
}
/// Consumes whitespaces.
///
/// Like [`skip_spaces()`], but checks that first char is actually a space.
///
/// [`skip_spaces()`]: #method.skip_spaces
///
/// # Errors
///
/// - `InvalidChar`
pub fn consume_spaces(&mut self) -> Result<()> {
if !self.at_end() && !self.starts_with_space() {
let c = self.curr_byte_unchecked() as char;
let pos = self.gen_error_pos();
return Err(StreamError::InvalidSpace(c, pos));
}
self.skip_spaces();
Ok(())
}
/// Consumes current byte if it's equal to the provided byte.
///
/// # Errors
///
/// - `InvalidChar`
/// - `UnexpectedEndOfStream`
///
/// # Examples
///
/// ```
/// use xmlparser::Stream;
///
/// let mut s = Stream::from("Some text.");
/// s.consume_byte(b'S').unwrap();
/// s.consume_byte(b'o').unwrap();
/// s.consume_byte(b'm').unwrap();
/// // s.consume_byte(b'q').unwrap(); // will produce an error
/// ```
pub fn consume_byte(&mut self, c: u8) -> Result<()> {
if self.curr_byte()? != c {
return Err(
StreamError::InvalidChar(
vec![self.curr_byte_unchecked(), c],
self.gen_error_pos(),
)
);
}
self.advance(1);
Ok(())
}
/// Consumes current byte if it's equal to one of the provided bytes.
///
/// Returns a coincidental byte.
///
/// # Errors
///
/// - `InvalidChar`
/// - `UnexpectedEndOfStream`
pub fn consume_either(&mut self, list: &[u8]) -> Result<u8> {
assert!(!list.is_empty());
let c = self.curr_byte()?;
if !list.contains(&c) {
let mut v = list.to_vec();
v.insert(0, c);
return Err(StreamError::InvalidChar(v, self.gen_error_pos()));
}
self.advance(1);
Ok(c)
}
/// Consumes selected string.
///
/// # Errors
///
/// - `InvalidChar`
pub fn skip_string(&mut self, text: &[u8]) -> Result<()> {
if !self.starts_with(text) {
let len = cmp::min(text.len(), self.end - self.pos);
// Collect chars and do not slice a string,
// because the `len` can be on the char boundary.
// Which lead to a panic.
let actual = self.span.to_str()[self.pos..].chars().take(len).collect();
// Assume that all input `text` are valid UTF-8 strings, so unwrap is safe.
let expected = str::from_utf8(text).unwrap().to_owned();
let pos = self.gen_error_pos();
return Err(StreamError::InvalidString(vec![actual, expected], pos));
}
self.advance(text.len());
Ok(())
}
/// Consumes an XML name and returns it.
///
/// Consumes according to: <https://www.w3.org/TR/xml/#NT-Name>
///
/// # Errors
///
/// - `InvalidNameToken` - if name is empty or starts with an invalid char
/// - `UnexpectedEndOfStream`
pub fn consume_name(&mut self) -> Result<StrSpan<'a>> {
let start = self.pos();
self.skip_name()?;
let name = self.slice_back(start);
if name.is_empty() {
return Err(StreamError::InvalidName);
}
Ok(name)
}
/// Skips an XML name.
///
/// The same as `consume_name()`, but does not return a consumed name.
///
/// # Errors
///
/// - `InvalidNameToken` - if name is empty or starts with an invalid char
/// - `UnexpectedEndOfStream`
pub fn skip_name(&mut self) -> Result<()> {
let mut iter = self.span.to_str()[self.pos..self.end].chars();
if let Some(c) = iter.next() {
if c.is_xml_name_start() {
self.advance(c.len_utf8());
} else {
return Err(StreamError::InvalidName);
}
}
for c in iter {
if c.is_xml_name() {
self.advance(c.len_utf8());
} else {
break;
}
}
Ok(())
}
/// Consumes a qualified XML name and returns it.
///
/// Consumes according to: <https://www.w3.org/TR/xml-names/#ns-qualnames>
///
/// # Errors
///
/// - `InvalidNameToken` - if name is empty or starts with an invalid char
/// - `UnexpectedEndOfStream`
pub fn consume_qname(&mut self) -> Result<(StrSpan<'a>, StrSpan<'a>)> {
let start = self.pos();
let mut splitter = None;
let iter = self.span.to_str()[self.pos..self.end].chars();
for c in iter {
if c == ':' {
splitter = Some(self.pos());
self.advance(1);
} else if c.is_xml_name() {
self.advance(c.len_utf8());
} else {
break;
}
}
let (prefix, local) = if let Some(splitter) = splitter {
let local = self.slice_back(splitter + 1);
let pos = self.pos();
self.pos = splitter;
let prefix = self.slice_back(start);
self.pos = pos;
(prefix, local)
} else {
let local = self.slice_back(start);
("".into(), local)
};
if local.is_empty() {
return Err(StreamError::InvalidName);
}
Ok((prefix, local))
}
/// Consumes `=`.
///
/// Consumes according to: <https://www.w3.org/TR/xml/#NT-Eq>
///
/// # Errors
///
/// - `InvalidChar`
pub fn consume_eq(&mut self) -> Result<()> {
self.skip_ascii_spaces();
self.consume_byte(b'=')?;
self.skip_ascii_spaces();
Ok(())
}
/// Consumes quote.
///
/// Consumes `'` or `"` and returns it.
///
/// # Errors
///
/// - `InvalidQuote`
/// - `UnexpectedEndOfStream`
pub fn consume_quote(&mut self) -> Result<u8> {
let c = self.curr_byte()?;
if c == b'\'' || c == b'"' {
self.advance(1);
Ok(c)
} else {
Err(StreamError::InvalidQuote(c as char, self.gen_error_pos()))
}
}
/// Consumes bytes by the predicate and returns them.
///
/// The result can be empty.
pub fn consume_bytes<F>(&mut self, f: F) -> StrSpan<'a>
where F: Fn(&Stream, u8) -> bool
{
let start = self.pos();
self.skip_bytes(f);
self.slice_back(start)
}
/// Consumes bytes by the predicate.
pub fn skip_bytes<F>(&mut self, f: F)
where F: Fn(&Stream, u8) -> bool
{
while !self.at_end() {
let c = self.curr_byte_unchecked();
if f(self, c) {
self.advance(1);
} else {
break;
}
}
}
/// Consumes chars by the predicate and returns them.
///
/// The result can be empty.
pub fn consume_chars<F>(&mut self, f: F) -> StrSpan<'a>
where F: Fn(&Stream, char) -> bool
{
let start = self.pos();
self.skip_chars(f);
self.slice_back(start)
}
/// Consumes chars by the predicate.
pub fn skip_chars<F>(&mut self, f: F)
where F: Fn(&Stream, char) -> bool
{
let t = &self.span.to_str()[self.pos..self.end];
for c in t.chars() {
if f(self, c) {
self.advance(c.len_utf8());
} else {
break;
}
}
}
/// Consumes an XML character reference if there is one.
///
/// On error will reset the position to the original.
pub fn try_consume_reference(&mut self) -> Option<Reference<'a>> {
let start = self.pos();
match self.consume_reference() {
Ok(r) => Some(r),
Err(_) => {
self.pos = start;
None
}
}
}
/// Consumes an XML reference.
///
/// Consumes according to: <https://www.w3.org/TR/xml/#NT-Reference>
///
/// # Errors
///
/// - `InvalidReference`
/// - `UnexpectedEndOfStream`
pub fn consume_reference(&mut self) -> Result<Reference<'a>> {
self._consume_reference().map_err(|_| StreamError::InvalidReference)
}
fn _consume_reference(&mut self) -> Result<Reference<'a>> {
if self.curr_byte()? != b'&' {
return Err(StreamError::InvalidReference);
}
self.advance(1);
let reference = if self.curr_byte()? == b'#' {
self.advance(1);
let n = if self.curr_byte()? == b'x' {
self.advance(1);
let value = self.consume_bytes(|_, c| c.is_xml_hex_digit()).to_str();
u32::from_str_radix(value, 16).map_err(|_| StreamError::InvalidReference)
} else {
let value = self.consume_bytes(|_, c| c.is_xml_digit()).to_str();
u32::from_str_radix(value, 10).map_err(|_| StreamError::InvalidReference)
}?;
let c = char::from_u32(n).unwrap_or('\u{FFFD}');
if !c.is_xml_char() {
return Err(StreamError::InvalidReference);
}
Reference::CharRef(c)
} else {
let name = self.consume_name()?;
match name.to_str() {
"quot" => Reference::CharRef('"'),
"amp" => Reference::CharRef('&'),
"apos" => Reference::CharRef('\''),
"lt" => Reference::CharRef('<'),
"gt" => Reference::CharRef('>'),
_ => Reference::EntityRef(name.to_str()),
}
};
self.consume_byte(b';')?;
Ok(reference)
}
/// Slices data from `pos` to the current position.
pub fn slice_back(&self, pos: usize) -> StrSpan<'a> {
self.span.slice_region(pos, self.pos())
}
/// Slices data from the current position to the end.
pub fn slice_tail(&self) -> StrSpan<'a> {
self.span.slice_region(self.pos(), self.end)
}
/// Calculates a current absolute position.
///
/// This operation is very expensive. Use only for errors.
#[inline(never)]
pub fn gen_error_pos(&self) -> TextPos {
let row = self.calc_current_row();
let col = self.calc_current_col();
TextPos::new(row, col)
}
/// Calculates an absolute position at `pos`.
///
/// This operation is very expensive. Use only for errors.
#[inline(never)]
pub fn gen_error_pos_from(&self, pos: usize) -> TextPos {
// TODO: rename
let mut s = *self;
let old_pos = s.pos;
s.pos = pos;
let e = s.gen_error_pos();
s.pos = old_pos;
e
}
fn calc_current_row(&self) -> u32 {
let text = self.span.full_str();
let mut row = 1;
let end = self.pos + self.span.start();
row += text.bytes()
.take(end)
.filter(|c| *c == b'\n')
.count();
row as u32
}
fn calc_current_col(&self) -> u32 {
let text = self.span.full_str();
let bytes = text.as_bytes();
let end = self.pos + self.span.start();
let mut col = 1;
for c in bytes.iter().take(end) {
if *c == b'\n' {
col = 1;
} else {
col += 1;
}
}
col
}
}
|
use std::env;
use std::fs::File;
use std::io::Read;
fn main() {
let cmd = "check";
let mut args = env::args();
let program_name = args.next().expect("program name");
let byte: i32 =
match args.next() {
Some(byte) => byte.parse().unwrap_or(10),
None => {
eprintln!("Please provide a number (byte) to check");
return;
},
};
let mut file = File::open(program_name).expect("File open");
let mut binary = vec![];
file.read_to_end(&mut binary).expect("File read");
match cmd {
"check" if check_binary(binary, byte) => {
println!("10 bob");
},
_ => {
// Check again just to make sure.
if !check_binary(binary, byte) {
println!("Byte not find in binary");
}
},
}
}
fn check_binary(binary: Vec<u8>, byte: i32) -> bool {
let byte =
if byte == 0 {
1
}
else {
byte
} << 16;
binary.iter().any(|&program_byte| program_byte as i32 == byte)
}
|
use proconio::*;
fn main() {
input!(a:i32,b:i32);
println!("{}", a-b);
} |
use sha3::Digest as _;
use oasis_runtime_sdk::{
crypto::signature::secp256k1,
types::{
address::SignatureAddressSpec,
transaction::{AddressSpec, AuthInfo},
},
};
use crate::{types::H160, Error};
pub fn from_bytes(b: &[u8]) -> H160 {
H160::from_slice(&sha3::Keccak256::digest(b)[32 - 20..])
}
pub fn from_secp256k1_public_key(public_key: &secp256k1::PublicKey) -> H160 {
from_bytes(&public_key.to_uncompressed_untagged_bytes())
}
pub fn from_sigspec(spec: &SignatureAddressSpec) -> Result<H160, Error> {
match spec {
SignatureAddressSpec::Secp256k1Eth(pk) => Ok(from_secp256k1_public_key(pk)),
_ => Err(Error::InvalidSignerType),
}
}
pub fn from_tx_auth_info(ai: &AuthInfo) -> Result<H160, Error> {
match &ai.signer_info[0].address_spec {
AddressSpec::Signature(spec) => from_sigspec(spec),
_ => Err(Error::InvalidSignerType),
}
}
|
mod enums;
pub use enums::fieldtype_enum::FieldType;
pub use enums::messagetype_enum::MessageType;
mod field_matchers;
pub use field_matchers::get_field_offset::get_field_offset_fn;
pub use field_matchers::get_field_scale::get_field_scale_fn;
pub use field_matchers::get_field_string_value::get_field_string_value_fn;
pub use field_matchers::get_field_type::get_field_type_fn;
mod message_matchers;
pub use message_matchers::get_message_timestamp_field::get_message_timestamp_field;
pub use message_matchers::get_message_type::get_message_type;
pub type MatchScaleFn = fn(usize) -> std::option::Option<f32>;
pub type MatchOffsetFn = fn(usize) -> std::option::Option<i16>;
pub type MatchFieldTypeFn = fn(usize) -> FieldType;
|
#![allow(warnings)]
use downcast_rs::__std::ffi::{OsStr, OsString};
use log::{debug, error, info};
use spacegame::assets::sprite::{
load_texels, Packed, PackedSpriteAsset, SamplerDef, SpriteAssetMetadata,
};
use std::collections::HashMap;
use std::fs::FileType;
use std::path::PathBuf;
fn load_metadata(base_path: PathBuf, asset_name: &str) -> SpriteAssetMetadata {
let metadata_path = base_path.join(asset_name).with_extension("json");
info!(
"Will load {:?} metadata at {}",
asset_name,
metadata_path.display()
);
let metadata_str = std::fs::read_to_string(metadata_path);
match metadata_str {
Ok(metadata_str) => serde_json::from_str::<SpriteAssetMetadata>(&metadata_str)
.unwrap_or_else(|e| {
error!(
"Cannot deserialize Metadata file, will use default instead = {:?}",
e
);
SpriteAssetMetadata::default()
}),
Err(_) => {
info!(
"No metadata file for {}, Will use default instead.",
asset_name
);
SpriteAssetMetadata::default()
}
}
}
fn get_packed_sprite(asset_name: &str) -> PackedSpriteAsset {
let base_path = PathBuf::from("assets/sprites");
let asset_path = base_path.join(asset_name);
let metadata = load_metadata(base_path.clone(), asset_name);
let (w, h, data) = load_texels(asset_path).unwrap();
PackedSpriteAsset {
w,
h,
data,
sampler: metadata.sampler,
}
}
fn main() {
let dirs = vec![
// "./assets/sprites",
// "./assets/sprites/background2",
// "./assets/sprites/background3",
// "./assets/sprites/explosion4",
// "./assets/sprites/explosion4",
// "./assets/sprites/windshield_wiper",
"./assets/sprites/spaceships",
"./assets/sprites/spaceships/Projectiles",
];
let to_pack = dirs
.iter()
.flat_map(|d| {
let paths = std::fs::read_dir(d).unwrap();
paths
// only files.
.filter(|p| {
let p = p.as_ref().unwrap();
match p.file_type() {
Ok(t) => t.is_file(),
_ => false,
}
})
// only PNG
.filter(|p| {
let p = p.as_ref().unwrap();
match p.path().extension() {
Some(ext) => ext.to_os_string() == OsString::from("png"),
_ => false,
}
})
.map(|p| {
p.unwrap().path().display().to_string()["./assets/sprites/".len()..].to_string()
})
})
.collect::<Vec<_>>();
let content = {
let mut m = HashMap::new();
for n in &to_pack {
m.insert(n.clone(), get_packed_sprite(n.as_str()));
}
// let n = "spaceships/blue_05.png";
m
};
let packed = Packed { content };
let res = bincode::serialize(&packed).unwrap();
std::fs::write("packed.bin", res).unwrap();
}
|
#[macro_use]
pub mod macros;
pub mod pool_context;
use std::os::raw::{c_char, c_void};
#[repr(C)]
pub struct ByteArray {
length: usize,
data: *const u8
}
impl ByteArray {
pub fn to_vec(&self) -> Vec<u8> {
if self.data.is_null() || self.length == 0 {
Vec::new()
} else {
unsafe { std::slice::from_raw_parts(self.data, self.length).to_vec() }
}
}
}
#[repr(C)]
pub struct NymHandle {
did: *const c_char, //Fully Qualified DID
ver_key: ByteArray, //Can be null for reads
private_key: ByteArray //Can be null for reads
}
pub type Handle = i32;
pub type OutString = *const c_char;
define_bytebuffer_destructor!(indy_res_free_bytebuffer);
define_string_destructor!(indy_res_free_string);
|
extern crate cql;
extern crate eventual;
extern crate mio;
extern crate time;
use cql::*;
use std::borrow::Cow;
use time::Duration;
use std::io::Write;
use std::thread;
use eventual::*;
#[macro_use]
macro_rules! assert_response(
($resp:expr) => (
if match $resp.opcode { cql::OpcodeResponse::OpcodeError => true, _ => false } {
panic!("Test failed at assertion: {}",
match $resp.body { cql::CqlResponseBody::ResponseError(_, message) => message, _ => Cow::Borrowed("Ooops!")});
}
);
);
macro_rules! try_test(
($call: expr, $msg: expr) => {
match $call {
Ok(val) => val,
Err(ref err) => panic!("Test failed at library call: {}", err.description())
};
}
);
pub fn to_hex_string(bytes: &Vec<u8>) -> String {
let strs: Vec<String> = bytes.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect(" ")
}
fn main() {
test_client();
}
fn test_client() {
println!("Connecting ...!");
let ip = "172.17.0.2";
let port = "9042";
let ip_port = ip.to_string()+":"+port;
let mut cluster = Cluster::new();
let mut response = cluster.connect_cluster(ip_port.parse().ok().expect("Couldn't parse address"));
println!("Result: {:?} \n", response);
//cluster.show_cluster_information();
//let mut future = cluster.get_peers();
//response = future.await().unwrap();
//println!("Result peers: {:?} \n", response);
//let mut future = cluster.register();
//response = future.await().unwrap();
//println!("Result peers: {:?} \n", response);
/*
let q = "SELECT *
FROM system.compaction_history;
";
*/
let q = "SELECT keyspace_name, columnfamily_name, column_name, component_index, index_name, index_options, index_type, type, validator
FROM system.schema_columns;
";
println!("cql::Query: {}", q);
response = cluster.exec_query(q, cql::Consistency::One).await().ok().expect("Error selecting from table test");
println!("Result: {:?} \n", response);
//println!("Connected with CQL binary version v{}", cluster.version);
// let params = vec![cql::CqlVarchar(Some((Cow::Borrowed("TOPOLOGY_CHANGE")))),
// cql::CqlVarchar(Some((Cow::Borrowed("STATUS_CHANGE")))) ];
//let future = cluster.send_register(params);
//let response = try_test!(future.await().unwrap(),"Error sending register to events");
//assert_response!(response);
//println!("Result: {:?} \n", response);
// A long sleep because I'm trying to see if Cassandra sends
// any event message after a node change his status to up.
//thread::sleep_ms(Duration::minutes(1).num_milliseconds() as u32);
cluster.show_cluster_information();
}
|
use chrono::{Datelike, NaiveDate, Utc};
use minijinja::{path_loader, Environment};
pub fn get_env() -> Environment<'static> {
let mut template_env = Environment::new();
template_env.set_loader(path_loader("theme"));
template_env.add_filter("format_date", format_date);
template_env.add_function("year", year);
template_env
}
fn format_date(value: String, fmt: String) -> String {
if let Ok(parsed) = NaiveDate::parse_from_str(&value, "%Y-%m-%d") {
parsed.format(&fmt).to_string()
} else {
value
}
}
fn year() -> i32 {
let current_date = Utc::now();
current_date.year()
}
|
use anstyle_parse::state::state_change;
use anstyle_parse::state::Action;
use anstyle_parse::state::State;
/// Strip ANSI escapes from a `&str`, returning the printable content
///
/// This can be used to take output from a program that includes escape sequences and write it
/// somewhere that does not easily support them, such as a log file.
///
/// For non-contiguous data, see [`StripStr`].
///
/// # Example
///
/// ```rust
/// use std::io::Write as _;
///
/// let styled_text = "\x1b[32mfoo\x1b[m bar";
/// let plain_str = anstream::adapter::strip_str(&styled_text).to_string();
/// assert_eq!(plain_str, "foo bar");
/// ```
#[inline]
pub fn strip_str(data: &str) -> StrippedStr<'_> {
StrippedStr::new(data)
}
/// See [`strip_str`]
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct StrippedStr<'s> {
bytes: &'s [u8],
state: State,
}
impl<'s> StrippedStr<'s> {
#[inline]
fn new(data: &'s str) -> Self {
Self {
bytes: data.as_bytes(),
state: State::Ground,
}
}
/// Create a [`String`] of the printable content
#[inline]
#[allow(clippy::inherent_to_string_shadow_display)] // Single-allocation implementation
pub fn to_string(&self) -> String {
use std::fmt::Write as _;
let mut stripped = String::with_capacity(self.bytes.len());
let _ = write!(&mut stripped, "{}", self);
stripped
}
}
impl<'s> std::fmt::Display for StrippedStr<'s> {
/// **Note:** this does *not* exhaust the [`Iterator`]
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let iter = Self {
bytes: self.bytes,
state: self.state,
};
for printable in iter {
printable.fmt(f)?;
}
Ok(())
}
}
impl<'s> Iterator for StrippedStr<'s> {
type Item = &'s str;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
next_str(&mut self.bytes, &mut self.state)
}
}
/// Incrementally strip non-contiguous data
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct StripStr {
state: State,
}
impl StripStr {
/// Initial state
pub fn new() -> Self {
Default::default()
}
/// Strip the next segment of data
pub fn strip_next<'s>(&'s mut self, data: &'s str) -> StripStrIter<'s> {
StripStrIter {
bytes: data.as_bytes(),
state: &mut self.state,
}
}
}
/// See [`StripStr`]
#[derive(Debug, PartialEq, Eq)]
pub struct StripStrIter<'s> {
bytes: &'s [u8],
state: &'s mut State,
}
impl<'s> Iterator for StripStrIter<'s> {
type Item = &'s str;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
next_str(&mut self.bytes, self.state)
}
}
#[inline]
fn next_str<'s>(bytes: &mut &'s [u8], state: &mut State) -> Option<&'s str> {
let offset = bytes.iter().copied().position(|b| {
let (next_state, action) = state_change(*state, b);
if next_state != State::Anywhere {
*state = next_state;
}
is_printable_str(action, b)
});
let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
*bytes = next;
*state = State::Ground;
let offset = bytes.iter().copied().position(|b| {
let (_next_state, action) = state_change(State::Ground, b);
!is_printable_str(action, b)
});
let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
*bytes = next;
if printable.is_empty() {
None
} else {
let printable = unsafe {
from_utf8_unchecked(
printable,
"`bytes` was validated as UTF-8, the parser preserves UTF-8 continuations",
)
};
Some(printable)
}
}
#[inline]
unsafe fn from_utf8_unchecked<'b>(bytes: &'b [u8], safety_justification: &'static str) -> &'b str {
if cfg!(debug_assertions) {
// Catch problems more quickly when testing
std::str::from_utf8(bytes).expect(safety_justification)
} else {
std::str::from_utf8_unchecked(bytes)
}
}
#[inline]
fn is_printable_str(action: Action, byte: u8) -> bool {
// VT320 considered 0x7f to be `Print`able but we expect to be working in UTF-8 systems and not
// ISO Latin-1, making it DEL and non-printable
const DEL: u8 = 0x7f;
(action == Action::Print && byte != DEL)
|| action == Action::BeginUtf8
// since we know the input is valid UTF-8, the only thing we can do with
// continuations is to print them
|| is_utf8_continuation(byte)
|| (action == Action::Execute && byte.is_ascii_whitespace())
}
#[inline]
fn is_utf8_continuation(b: u8) -> bool {
matches!(b, 0x80..=0xbf)
}
/// Strip ANSI escapes from bytes, returning the printable content
///
/// This can be used to take output from a program that includes escape sequences and write it
/// somewhere that does not easily support them, such as a log file.
///
/// # Example
///
/// ```rust
/// use std::io::Write as _;
///
/// let styled_text = "\x1b[32mfoo\x1b[m bar";
/// let plain_str = anstream::adapter::strip_bytes(styled_text.as_bytes()).into_vec();
/// assert_eq!(plain_str.as_slice(), &b"foo bar"[..]);
/// ```
#[inline]
pub fn strip_bytes(data: &[u8]) -> StrippedBytes<'_> {
StrippedBytes::new(data)
}
/// See [`strip_bytes`]
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct StrippedBytes<'s> {
bytes: &'s [u8],
state: State,
utf8parser: Utf8Parser,
}
impl<'s> StrippedBytes<'s> {
/// See [`strip_bytes`]
#[inline]
pub fn new(bytes: &'s [u8]) -> Self {
Self {
bytes,
state: State::Ground,
utf8parser: Default::default(),
}
}
/// Strip the next slice of bytes
///
/// Used when the content is in several non-contiguous slices
///
/// # Panic
///
/// May panic if it is not exhausted / empty
#[inline]
pub fn extend(&mut self, bytes: &'s [u8]) {
debug_assert!(
self.is_empty(),
"current bytes must be processed to ensure we end at the right state"
);
self.bytes = bytes;
}
/// Report the bytes has been exhausted
#[inline]
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// Create a [`Vec`] of the printable content
#[inline]
pub fn into_vec(self) -> Vec<u8> {
let mut stripped = Vec::with_capacity(self.bytes.len());
for printable in self {
stripped.extend(printable);
}
stripped
}
}
impl<'s> Iterator for StrippedBytes<'s> {
type Item = &'s [u8];
#[inline]
fn next(&mut self) -> Option<Self::Item> {
next_bytes(&mut self.bytes, &mut self.state, &mut self.utf8parser)
}
}
/// Incrementally strip non-contiguous data
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct StripBytes {
state: State,
utf8parser: Utf8Parser,
}
impl StripBytes {
/// Initial state
pub fn new() -> Self {
Default::default()
}
/// Strip the next segment of data
pub fn strip_next<'s>(&'s mut self, bytes: &'s [u8]) -> StripBytesIter<'s> {
StripBytesIter {
bytes,
state: &mut self.state,
utf8parser: &mut self.utf8parser,
}
}
}
/// See [`StripBytes`]
#[derive(Debug, PartialEq, Eq)]
pub struct StripBytesIter<'s> {
bytes: &'s [u8],
state: &'s mut State,
utf8parser: &'s mut Utf8Parser,
}
impl<'s> Iterator for StripBytesIter<'s> {
type Item = &'s [u8];
#[inline]
fn next(&mut self) -> Option<Self::Item> {
next_bytes(&mut self.bytes, self.state, self.utf8parser)
}
}
#[inline]
fn next_bytes<'s>(
bytes: &mut &'s [u8],
state: &mut State,
utf8parser: &mut Utf8Parser,
) -> Option<&'s [u8]> {
let offset = bytes.iter().copied().position(|b| {
if *state == State::Utf8 {
true
} else {
let (next_state, action) = state_change(*state, b);
if next_state != State::Anywhere {
*state = next_state;
}
is_printable_bytes(action, b)
}
});
let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
*bytes = next;
let offset = bytes.iter().copied().position(|b| {
if *state == State::Utf8 {
if utf8parser.add(b) {
*state = State::Ground;
}
false
} else {
let (next_state, action) = state_change(State::Ground, b);
if next_state != State::Anywhere {
*state = next_state;
}
if *state == State::Utf8 {
utf8parser.add(b);
false
} else {
!is_printable_bytes(action, b)
}
}
});
let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
*bytes = next;
if printable.is_empty() {
None
} else {
Some(printable)
}
}
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct Utf8Parser {
utf8_parser: utf8parse::Parser,
}
impl Utf8Parser {
fn add(&mut self, byte: u8) -> bool {
let mut b = false;
let mut receiver = VtUtf8Receiver(&mut b);
self.utf8_parser.advance(&mut receiver, byte);
b
}
}
struct VtUtf8Receiver<'a>(&'a mut bool);
impl<'a> utf8parse::Receiver for VtUtf8Receiver<'a> {
fn codepoint(&mut self, _: char) {
*self.0 = true;
}
fn invalid_sequence(&mut self) {
*self.0 = true;
}
}
#[inline]
fn is_printable_bytes(action: Action, byte: u8) -> bool {
// VT320 considered 0x7f to be `Print`able but we expect to be working in UTF-8 systems and not
// ISO Latin-1, making it DEL and non-printable
const DEL: u8 = 0x7f;
// Continuations aren't included as they may also be control codes, requiring more context
(action == Action::Print && byte != DEL)
|| action == Action::BeginUtf8
|| (action == Action::Execute && byte.is_ascii_whitespace())
}
#[cfg(test)]
mod test {
use super::*;
use proptest::prelude::*;
/// Model based off full parser
fn parser_strip(bytes: &[u8]) -> String {
#[derive(Default)]
struct Strip(String);
impl Strip {
fn with_capacity(capacity: usize) -> Self {
Self(String::with_capacity(capacity))
}
}
impl anstyle_parse::Perform for Strip {
fn print(&mut self, c: char) {
self.0.push(c);
}
fn execute(&mut self, byte: u8) {
if byte.is_ascii_whitespace() {
self.0.push(byte as char);
}
}
}
let mut stripped = Strip::with_capacity(bytes.len());
let mut parser = anstyle_parse::Parser::<anstyle_parse::DefaultCharAccumulator>::new();
for byte in bytes {
parser.advance(&mut stripped, *byte);
}
stripped.0
}
/// Model verifying incremental parsing
fn strip_char(mut s: &str) -> String {
let mut result = String::new();
let mut state = StripStr::new();
while !s.is_empty() {
let mut indices = s.char_indices();
indices.next(); // current
let offset = indices.next().map(|(i, _)| i).unwrap_or_else(|| s.len());
let (current, remainder) = s.split_at(offset);
for printable in state.strip_next(current) {
result.push_str(printable);
}
s = remainder;
}
result
}
/// Model verifying incremental parsing
fn strip_byte(s: &[u8]) -> Vec<u8> {
let mut result = Vec::new();
let mut state = StripBytes::default();
for start in 0..s.len() {
let current = &s[start..=start];
for printable in state.strip_next(current) {
result.extend(printable);
}
}
result
}
#[test]
fn test_strip_bytes_multibyte() {
let bytes = [240, 145, 141, 139];
let expected = parser_strip(&bytes);
let actual = String::from_utf8(strip_bytes(&bytes).into_vec()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn test_strip_byte_multibyte() {
let bytes = [240, 145, 141, 139];
let expected = parser_strip(&bytes);
let actual = String::from_utf8(strip_byte(&bytes).to_vec()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn test_strip_str_del() {
let input = std::str::from_utf8(&[0x7f]).unwrap();
let expected = "";
let actual = strip_str(input).to_string();
assert_eq!(expected, actual);
}
#[test]
fn test_strip_byte_del() {
let bytes = [0x7f];
let expected = "";
let actual = String::from_utf8(strip_byte(&bytes).to_vec()).unwrap();
assert_eq!(expected, actual);
}
proptest! {
#[test]
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
fn strip_str_no_escapes(s in "\\PC*") {
let expected = parser_strip(s.as_bytes());
let actual = strip_str(&s).to_string();
assert_eq!(expected, actual);
}
#[test]
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
fn strip_char_no_escapes(s in "\\PC*") {
let expected = parser_strip(s.as_bytes());
let actual = strip_char(&s);
assert_eq!(expected, actual);
}
#[test]
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
fn strip_bytes_no_escapes(s in "\\PC*") {
dbg!(&s);
dbg!(s.as_bytes());
let expected = parser_strip(s.as_bytes());
let actual = String::from_utf8(strip_bytes(s.as_bytes()).into_vec()).unwrap();
assert_eq!(expected, actual);
}
#[test]
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
fn strip_byte_no_escapes(s in "\\PC*") {
dbg!(&s);
dbg!(s.as_bytes());
let expected = parser_strip(s.as_bytes());
let actual = String::from_utf8(strip_byte(s.as_bytes()).to_vec()).unwrap();
assert_eq!(expected, actual);
}
}
}
|
// Copyright 2015 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.
// compile-flags: --edition 2018
#![deny(unused_extern_crates)]
#![feature(alloc, test, libc)]
extern crate alloc;
//~^ ERROR unused extern crate
//~| HELP remove
extern crate alloc as x;
//~^ ERROR unused extern crate
//~| HELP remove
#[macro_use]
extern crate test;
pub extern crate test as y;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `pub use`
pub extern crate libc;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `pub use`
pub(crate) extern crate libc as a;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `pub(crate) use`
crate extern crate libc as b;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `crate use`
mod foo {
pub(in crate::foo) extern crate libc as c;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `pub(in crate::foo) use`
pub(super) extern crate libc as d;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `pub(super) use`
extern crate alloc;
//~^ ERROR unused extern crate
//~| HELP remove
extern crate alloc as x;
//~^ ERROR unused extern crate
//~| HELP remove
pub extern crate test;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it
pub extern crate test as y;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it
mod bar {
extern crate alloc;
//~^ ERROR unused extern crate
//~| HELP remove
extern crate alloc as x;
//~^ ERROR unused extern crate
//~| HELP remove
pub(in crate::foo::bar) extern crate libc as e;
//~^ ERROR `extern crate` is not idiomatic in the new edition
//~| HELP convert it to a `pub(in crate::foo::bar) use`
fn dummy() {
unsafe {
e::getpid();
}
}
}
fn dummy() {
unsafe {
c::getpid();
d::getpid();
}
}
}
fn main() {
unsafe { a::getpid(); }
unsafe { b::getpid(); }
}
|
use super::character::Character;
use super::background::Background;
use super::map::Map;
use super::moving_object::MovingObject;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
pub struct Camera {
min: f64,
max: f64
}
impl Camera{
pub fn new(min: f64, max: f64) -> Camera {
Camera {
min,
max
}
}
pub fn update(&mut self, objects: &mut HashMap<String, MovingObject>, map: &mut Map, _character: &mut Character, background: &mut Background, delta: f64) {
let character_object = &mut objects.get("1ad31e1d-494a-41fe-bb9c-e7b8b83e59f1").unwrap();
let position_x = character_object.position[0];
if position_x <= self.min {
if background.x >= 0.0 {
return;
}
let mut character = &mut objects.get_mut("1ad31e1d-494a-41fe-bb9c-e7b8b83e59f1").unwrap();
character.position[0] = self.min;
let move_x = delta * character.speed[0];
if background.x - move_x >= 0.0 {
background.x = 0.0;
return;
}
background.move_object(-move_x, 0.0);
map.move_object(-move_x, 0.0);
for (k, v) in objects.iter_mut() {
if k == "1ad31e1d-494a-41fe-bb9c-e7b8b83e59f1" {
continue;
}
v.move_object(-move_x, 0.0);
}
}
if position_x >= self.max {
if background.x <= -(background.combined_width / 2.0) {
return;
}
let mut character = &mut objects.get_mut("1ad31e1d-494a-41fe-bb9c-e7b8b83e59f1").unwrap();
character.position[0] = self.max;
let move_x = delta * character.speed[0];
background.move_object(-move_x, 0.0);
map.move_object(-move_x, 0.0);
for (k, v) in objects.iter_mut() {
if k == "1ad31e1d-494a-41fe-bb9c-e7b8b83e59f1" {
continue;
}
v.move_object(-move_x, 0.0);
}
}
}
}
pub trait CameraDependentObject {
fn move_object(&mut self, x: f64, y: f64);
}
|
use std::collections::hash_map::{HashMap, Entry};
use std::fmt;
use std::fs;
use std::io;
use std::iter::repeat;
use std::str;
use byteorder::{WriteBytesExt, BigEndian};
use csv::{self, ByteString};
use csv::index::Indexed;
use CliResult;
use config::{Config, Delimiter};
use select::{SelectColumns, Selection};
use util;
static USAGE: &'static str = "
Joins two sets of CSV data on the specified columns.
The default join operation is an 'inner' join. This corresponds to the
intersection of rows on the keys specified.
Joins are always done by ignoring leading and trailing whitespace. By default,
joins are done case sensitively, but this can be disabled with the --no-case
flag.
The columns arguments specify the columns to join for each input. Columns can
be referenced by name or index, starting at 1. Specify multiple columns by
separating them with a comma. Specify a range of columns with `-`. Both
columns1 and columns2 must specify exactly the same number of columns.
(See 'xsv select --help' for the full syntax.)
Usage:
xsv join [options] <columns1> <input1> <columns2> <input2>
xsv join --help
join options:
--no-case When set, joins are done case insensitively.
--left Do a 'left outer' join. This returns all rows in
first CSV data set, including rows with no
corresponding row in the second data set. When no
corresponding row exists, it is padded out with
empty fields.
--right Do a 'right outer' join. This returns all rows in
second CSV data set, including rows with no
corresponding row in the first data set. When no
corresponding row exists, it is padded out with
empty fields. (This is the reverse of 'outer left'.)
--full Do a 'full outer' join. This returns all rows in
both data sets with matching records joined. If
there is no match, the missing side will be padded
out with empty fields. (This is the combination of
'outer left' and 'outer right'.)
--cross USE WITH CAUTION.
This returns the cartesian product of the CSV
data sets given. The number of rows return is
equal to N * M, where N and M correspond to the
number of rows in the given data sets, respectively.
--nulls When set, joins will work on empty fields.
Otherwise, empty fields are completely ignored.
(In fact, any row that has an empty field in the
key specified is ignored.)
Common options:
-h, --help Display this message
-o, --output <file> Write output to <file> instead of stdout.
-n, --no-headers When set, the first row will not be interpreted
as headers. (i.e., They are not searched, analyzed,
sliced, etc.)
-d, --delimiter <arg> The field delimiter for reading CSV data.
Must be a single character. (default: ,)
";
#[derive(RustcDecodable)]
struct Args {
arg_columns1: SelectColumns,
arg_input1: String,
arg_columns2: SelectColumns,
arg_input2: String,
flag_left: bool,
flag_right: bool,
flag_full: bool,
flag_cross: bool,
flag_output: Option<String>,
flag_no_headers: bool,
flag_no_case: bool,
flag_nulls: bool,
flag_delimiter: Option<Delimiter>,
}
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = try!(util::get_args(USAGE, argv));
let mut state = try!(args.new_io_state());
match (
args.flag_left,
args.flag_right,
args.flag_full,
args.flag_cross,
) {
(true, false, false, false) => {
try!(state.write_headers());
state.outer_join(false)
}
(false, true, false, false) => {
try!(state.write_headers());
state.outer_join(true)
}
(false, false, true, false) => {
try!(state.write_headers());
state.full_outer_join()
}
(false, false, false, true) => {
try!(state.write_headers());
state.cross_join()
}
(false, false, false, false) => {
try!(state.write_headers());
state.inner_join()
}
_ => fail!("Please pick exactly one join operation.")
}
}
struct IoState<R, W: io::Write> {
wtr: csv::Writer<W>,
rdr1: csv::Reader<R>,
sel1: Selection,
rdr2: csv::Reader<R>,
sel2: Selection,
no_headers: bool,
casei: bool,
nulls: bool,
}
impl<R: io::Read + io::Seek, W: io::Write> IoState<R, W> {
fn write_headers(&mut self) -> CliResult<()> {
if !self.no_headers {
let mut headers = try!(self.rdr1.byte_headers());
headers.extend(try!(self.rdr2.byte_headers()).into_iter());
try!(self.wtr.write(headers.into_iter()));
}
Ok(())
}
fn inner_join(mut self) -> CliResult<()> {
let mut validx = try!(ValueIndex::new(self.rdr2, &self.sel2,
self.casei, self.nulls));
for row in self.rdr1.byte_records() {
let row = try!(row);
let key = get_row_key(&self.sel1, &row, self.casei);
match validx.values.get(&key) {
None => continue,
Some(rows) => {
for &rowi in rows.iter() {
try!(validx.idx.seek(rowi as u64));
let mut row1 = row.iter().map(|f| Ok(&**f));
let row2 = unsafe { validx.idx.byte_fields() };
let combined = row1.by_ref().chain(row2);
try!(self.wtr.write_iter(combined));
}
}
}
}
Ok(())
}
fn outer_join(mut self, right: bool) -> CliResult<()> {
if right {
::std::mem::swap(&mut self.rdr1, &mut self.rdr2);
::std::mem::swap(&mut self.sel1, &mut self.sel2);
}
let (_, pad2) = try!(self.get_padding());
let mut validx = try!(ValueIndex::new(self.rdr2, &self.sel2,
self.casei, self.nulls));
for row in self.rdr1.byte_records() {
let row = try!(row);
let key = get_row_key(&self.sel1, &*row, self.casei);
match validx.values.get(&key) {
None => {
let row1 = row.iter().map(|f| Ok(&**f));
let row2 = pad2.iter().map(|f| Ok(&**f));
if right {
try!(self.wtr.write_iter(row2.chain(row1)));
} else {
try!(self.wtr.write_iter(row1.chain(row2)));
}
}
Some(rows) => {
for &rowi in rows.iter() {
try!(validx.idx.seek(rowi as u64));
let row1 = row.iter().map(|f| Ok(&**f));
let row2 = unsafe {
validx.idx.byte_fields()
};
if right {
try!(self.wtr.write_iter(row2.chain(row1)));
} else {
try!(self.wtr.write_iter(row1.chain(row2)));
}
}
}
}
}
Ok(())
}
fn full_outer_join(mut self) -> CliResult<()> {
let (pad1, pad2) = try!(self.get_padding());
let mut validx = try!(ValueIndex::new(self.rdr2, &self.sel2,
self.casei, self.nulls));
// Keep track of which rows we've written from rdr2.
let mut rdr2_written: Vec<_> =
repeat(false).take(validx.num_rows).collect();
for row1 in self.rdr1.byte_records() {
let row1 = try!(row1);
let key = get_row_key(&self.sel1, &*row1, self.casei);
match validx.values.get(&key) {
None => {
let row1 = row1.iter().map(|f| Ok(&**f));
let row2 = pad2.iter().map(|f| Ok(&**f));
try!(self.wtr.write_iter(row1.chain(row2)));
}
Some(rows) => {
for &rowi in rows.iter() {
rdr2_written[rowi] = true;
try!(validx.idx.seek(rowi as u64));
let row1 = row1.iter().map(|f| Ok(&**f));
let row2 = unsafe {
validx.idx.byte_fields()
};
try!(self.wtr.write_iter(row1.chain(row2)));
}
}
}
}
// OK, now write any row from rdr2 that didn't get joined with a row
// from rdr1.
for (i, &written) in rdr2_written.iter().enumerate() {
if !written {
try!(validx.idx.seek(i as u64));
let row1 = pad1.iter().map(|f| Ok(&**f));
let row2 = unsafe {
validx.idx.byte_fields()
};
try!(self.wtr.write_iter(row1.chain(row2)));
}
}
Ok(())
}
fn cross_join(mut self) -> CliResult<()> {
for row1 in self.rdr1.byte_records() {
let row1 = try!(row1);
try!(self.rdr2.seek(0));
let mut first = true;
while !self.rdr2.done() {
// Skip the header row. The raw byte interface won't
// do it for us.
if first && !self.no_headers {
while let Some(f) =
self.rdr2.next_bytes().into_iter_result() { try!(f); }
first = false;
}
let row1 = row1.iter().map(|f| Ok(&**f));
let row2 = unsafe { self.rdr2.byte_fields() };
try!(self.wtr.write_iter(row1.chain(row2)));
}
}
Ok(())
}
fn get_padding(&mut self)
-> CliResult<(Vec<ByteString>, Vec<ByteString>)> {
let len1 = try!(self.rdr1.byte_headers()).len();
let len2 = try!(self.rdr2.byte_headers()).len();
Ok((
repeat(util::empty_field()).take(len1).collect(),
repeat(util::empty_field()).take(len2).collect(),
))
}
}
impl Args {
fn new_io_state(&self)
-> CliResult<IoState<fs::File, Box<io::Write+'static>>> {
let rconf1 = Config::new(&Some(self.arg_input1.clone()))
.delimiter(self.flag_delimiter)
.no_headers(self.flag_no_headers)
.select(self.arg_columns1.clone());
let rconf2 = Config::new(&Some(self.arg_input2.clone()))
.delimiter(self.flag_delimiter)
.no_headers(self.flag_no_headers)
.select(self.arg_columns2.clone());
let mut rdr1 = try!(rconf1.reader_file());
let mut rdr2 = try!(rconf2.reader_file());
let (sel1, sel2) = try!(self.get_selections(&rconf1, &mut rdr1,
&rconf2, &mut rdr2));
Ok(IoState {
wtr: try!(Config::new(&self.flag_output).writer()),
rdr1: rdr1,
sel1: sel1,
rdr2: rdr2,
sel2: sel2,
no_headers: rconf1.no_headers,
casei: self.flag_no_case,
nulls: self.flag_nulls,
})
}
fn get_selections<R: io::Read>
(&self,
rconf1: &Config, rdr1: &mut csv::Reader<R>,
rconf2: &Config, rdr2: &mut csv::Reader<R>)
-> CliResult<(Selection, Selection)> {
let headers1 = try!(rdr1.byte_headers());
let headers2 = try!(rdr2.byte_headers());
let select1 = try!(rconf1.selection(&*headers1));
let select2 = try!(rconf2.selection(&*headers2));
if select1.len() != select2.len() {
return fail!(format!(
"Column selections must have the same number of columns, \
but found column selections with {} and {} columns.",
select1.len(), select2.len()));
}
Ok((select1, select2))
}
}
struct ValueIndex<R> {
// This maps tuples of values to corresponding rows.
values: HashMap<Vec<ByteString>, Vec<usize>>,
idx: Indexed<R, io::Cursor<Vec<u8>>>,
num_rows: usize,
}
impl<R: io::Read + io::Seek> ValueIndex<R> {
fn new(mut rdr: csv::Reader<R>, sel: &Selection,
casei: bool, nulls: bool)
-> CliResult<ValueIndex<R>> {
let mut val_idx = HashMap::with_capacity(10000);
let mut row_idx = io::Cursor::new(Vec::with_capacity(8 * 10000));
let (mut rowi, mut count) = (0usize, 0usize);
let row_len = try!(rdr.byte_headers()).len();
// This logic is kind of tricky. Basically, we want to include
// the header row in the line index (because that's what csv::index
// does), but we don't want to include header values in the ValueIndex.
if !rdr.has_headers {
// ... so if there are no headers, we seek to the beginning and
// index everything.
try!(rdr.seek(0));
} else {
// ... and if there are headers, we make sure that we've parsed
// them, and write the offset of the header row to the index.
try!(rdr.byte_headers());
try!(row_idx.write_u64::<BigEndian>(0));
count += 1;
}
while !rdr.done() {
// This is a bit hokey. We're doing this manually instead of
// calling `csv::index::create` so we can create both indexes
// in one pass.
try!(row_idx.write_u64::<BigEndian>(rdr.byte_offset()));
let mut row = Vec::with_capacity(row_len);
while let Some(r) = rdr.next_bytes().into_iter_result() {
row.push(try!(r).to_vec());
}
let fields: Vec<_> = sel.select(&row).map(|v| transform(v, casei)).collect();
if nulls || !fields.iter().any(|f| f.is_empty()) {
match val_idx.entry(fields) {
Entry::Vacant(v) => {
let mut rows = Vec::with_capacity(4);
rows.push(rowi);
v.insert(rows);
}
Entry::Occupied(mut v) => { v.get_mut().push(rowi); }
}
}
rowi += 1;
count += 1;
}
try!(row_idx.write_u64::<BigEndian>(count as u64));
Ok(ValueIndex {
values: val_idx,
idx: try!(Indexed::open(rdr,
io::Cursor::new(row_idx.into_inner()))),
num_rows: rowi,
})
}
}
impl<R> fmt::Debug for ValueIndex<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Sort the values by order of first appearance.
let mut kvs = self.values.iter().collect::<Vec<_>>();
kvs.sort_by(|&(_, v1), &(_, v2)| v1[0].cmp(&v2[0]));
for (keys, rows) in kvs.into_iter() {
// This is just for debugging, so assume Unicode for now.
let keys = keys.iter()
.map(|k| String::from_utf8(k.to_vec()).unwrap())
.collect::<Vec<_>>();
try!(writeln!(f, "({}) => {:?}", keys.connect(", "), rows))
}
Ok(())
}
}
fn get_row_key(sel: &Selection, row: &[ByteString], casei: bool)
-> Vec<ByteString> {
sel.select(row).map(|v| transform(&v, casei)).collect()
}
fn transform(bs: &[u8], casei: bool) -> ByteString {
match str::from_utf8(bs) {
Err(_) => bs.to_vec(),
Ok(s) => {
if !casei {
s.trim().as_bytes().to_vec()
} else {
let norm: String =
s.trim().chars()
.map(|c| c.to_lowercase().next().unwrap()).collect();
norm.into_bytes()
}
}
}
}
|
use futures::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let org = "myorg";
let bucket = "mybucket";
let influx_url = "http://localhost:9999";
let token = "my-token";
let client = influxdb2_client::Client::new(influx_url, token);
let points = vec![
influxdb2_client::models::DataPoint::builder("cpu_load_short")
.tag("host", "server01")
.tag("region", "us-west")
.field("value", 0.64)
.build()?,
influxdb2_client::models::DataPoint::builder("cpu_load_short")
.tag("host", "server01")
.field("value", 27.99)
.build()?,
];
client.write(org, bucket, stream::iter(points)).await?;
Ok(())
}
|
use cargo_linked::Cargo;
use cargo::core::shell::Shell;
use structopt::StructOpt as _;
use std::io;
fn main() {
let Cargo::Linked(opt) = Cargo::from_args();
let mut config = cargo::Config::default()
.unwrap_or_else(|e| cargo::exit_with_error(e.into(), &mut Shell::new()));
if let Err(err) = opt.run(&mut config, io::stdout()) {
cargo::exit_with_error(err, &mut config.shell())
}
}
|
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{Data, DeriveInput, Fields, GenericArgument, Ident, Lit, Meta, PathArguments, Type};
pub fn get_properties(input: &DeriveInput) -> Vec<(Ident, Type)> {
let mut fields = Vec::new();
if let Data::Struct(data_struct) = &input.data {
if let Fields::Named(fields_named) = &data_struct.fields {
for field in fields_named.named.iter() {
if let Some(property_name) = &field.ident {
if let Type::Path(type_path) = &field.ty {
if let PathArguments::AngleBracketed(angle_args) =
&type_path.path.segments.first().unwrap().arguments
{
if let Some(GenericArgument::Type(property_type)) =
angle_args.args.first()
{
fields.push((property_name.clone(), property_type.clone()));
}
}
}
}
}
}
}
fields
}
pub fn get_type_name(input: &DeriveInput, type_type: &str) -> Ident {
let mut type_name_option: Option<Ident> = None;
let attrs = &input.attrs;
for option in attrs.into_iter() {
let option = option.parse_meta().unwrap();
match option {
Meta::NameValue(meta_name_value) => {
let path = meta_name_value.path;
let lit = meta_name_value.lit;
if let Some(ident) = path.get_ident() {
if ident == "type_name" {
if let Lit::Str(lit) = lit {
let ident = Ident::new(lit.value().as_str(), Span::call_site());
type_name_option = Some(ident);
}
}
}
}
_ => {}
}
}
return type_name_option.expect(
format!(
"#[derive({})] requires an accompanying #[type_name = \"{} Type Name Here\"] attribute",
type_type, type_type
)
.as_str(),
);
}
pub fn get_write_method(properties: &Vec<(Ident, Type)>) -> TokenStream {
let mut output = quote! {};
for (field_name, _) in properties.iter() {
let new_output_right = quote! {
Property::write(&self.#field_name, buffer);
};
let new_output_result = quote! {
#output
#new_output_right
};
output = new_output_result;
}
return quote! {
fn write(&self, buffer: &mut Vec<u8>) {
#output
}
};
}
|
use data_types::{NamespaceId, SequenceNumber, TableId};
use dml::DmlWrite;
use generated_types::influxdata::{
iox::wal::v1::sequenced_wal_op::Op as WalOp,
pbdata::v1::{DatabaseBatch, TableBatch},
};
use mutable_batch_lp::lines_to_batches;
use tokio::sync::watch;
use wal::{SequencedWalOp, WriteResult, WriteSummary};
#[tokio::test]
async fn crud() {
let dir = test_helpers::tmp_dir().unwrap();
let wal = wal::Wal::new(dir.path()).await.unwrap();
// Just-created WALs have no closed segments.
let closed = wal.closed_segments();
assert!(
closed.is_empty(),
"Expected empty closed segments; got {closed:?}"
);
// Can write an entry to the open segment
let op = arbitrary_sequenced_wal_op([42, 43]);
let summary = unwrap_summary(wal.write_op(op)).await;
assert_eq!(summary.total_bytes, 140);
assert_eq!(summary.bytes_written, 124);
// Can write another entry; total_bytes accumulates
let op = arbitrary_sequenced_wal_op([44, 45]);
let summary = unwrap_summary(wal.write_op(op)).await;
assert_eq!(summary.total_bytes, 264);
assert_eq!(summary.bytes_written, 124);
// Still no closed segments
let closed = wal.closed_segments();
assert!(
closed.is_empty(),
"Expected empty closed segments; got {closed:?}"
);
// Can't read entries from the open segment; have to rotate first
let (closed_segment_details, ids) = wal.rotate().unwrap();
assert_eq!(closed_segment_details.size(), 264);
assert_eq!(
ids.iter().collect::<Vec<_>>(),
[
SequenceNumber::new(42),
SequenceNumber::new(43),
SequenceNumber::new(44),
SequenceNumber::new(45)
]
);
// There's one closed segment
let closed = wal.closed_segments();
let closed_segment_ids: Vec<_> = closed.iter().map(|c| c.id()).collect();
assert_eq!(closed_segment_ids, &[closed_segment_details.id()]);
// Can read the written entries from the closed segment, ensuring that the
// per-partition sequence numbers are preserved.
let mut reader = wal.reader_for_segment(closed_segment_details.id()).unwrap();
let mut op = reader.next().unwrap().unwrap();
let mut got_sequence_numbers = op
.remove(0)
.table_write_sequence_numbers
.into_values()
.collect::<Vec<_>>();
got_sequence_numbers.sort();
assert_eq!(got_sequence_numbers, Vec::<u64>::from([42, 43]),);
let mut op = reader.next().unwrap().unwrap();
let mut got_sequence_numbers = op
.remove(0)
.table_write_sequence_numbers
.into_values()
.collect::<Vec<_>>();
got_sequence_numbers.sort();
assert_eq!(got_sequence_numbers, Vec::<u64>::from([44, 45]),);
// Can delete a segment, leaving no closed segments again
wal.delete(closed_segment_details.id()).await.unwrap();
let closed = wal.closed_segments();
assert!(
closed.is_empty(),
"Expected empty closed segments; got {closed:?}"
);
}
#[tokio::test]
async fn replay() {
let dir = test_helpers::tmp_dir().unwrap();
// Create a WAL with an entry, rotate to close the segment, create another entry, then drop the
// WAL.
{
let wal = wal::Wal::new(dir.path()).await.unwrap();
let op = arbitrary_sequenced_wal_op([42]);
let _ = unwrap_summary(wal.write_op(op)).await;
wal.rotate().unwrap();
let op = arbitrary_sequenced_wal_op([43, 44]);
let _ = unwrap_summary(wal.write_op(op)).await;
}
// Create a new WAL instance with the same directory to replay from the files
let wal = wal::Wal::new(dir.path()).await.unwrap();
// There's two closed segments -- one for the previously closed segment, one for the previously
// open segment. Replayed WALs treat all files as closed, because effectively they are.
let closed = wal.closed_segments();
let closed_segment_ids: Vec<_> = closed.iter().map(|c| c.id()).collect();
assert_eq!(closed_segment_ids.len(), 2);
// Can read the written entries from the previously closed segment
// ensuring the per-partition sequence numbers are preserved.
let mut reader = wal.reader_for_segment(closed_segment_ids[0]).unwrap();
let mut op = reader.next().unwrap().unwrap();
let mut got_sequence_numbers = op
.remove(0)
.table_write_sequence_numbers
.into_values()
.collect::<Vec<_>>();
got_sequence_numbers.sort();
assert_eq!(got_sequence_numbers, Vec::<u64>::from([42]));
// Can read the written entries from the previously open segment
let mut reader = wal.reader_for_segment(closed_segment_ids[1]).unwrap();
let mut op = reader.next().unwrap().unwrap();
let mut got_sequence_numbers = op
.remove(0)
.table_write_sequence_numbers
.into_values()
.collect::<Vec<_>>();
got_sequence_numbers.sort();
assert_eq!(got_sequence_numbers, Vec::<u64>::from([43, 44]));
}
#[tokio::test]
async fn ordering() {
let dir = test_helpers::tmp_dir().unwrap();
// Create a WAL with two closed segments and an open segment with entries, then drop the WAL
{
let wal = wal::Wal::new(dir.path()).await.unwrap();
let op = arbitrary_sequenced_wal_op([42, 43]);
let _ = unwrap_summary(wal.write_op(op)).await;
let (_, ids) = wal.rotate().unwrap();
assert_eq!(
ids.iter().collect::<Vec<_>>(),
[SequenceNumber::new(42), SequenceNumber::new(43)]
);
let op = arbitrary_sequenced_wal_op([44]);
let _ = unwrap_summary(wal.write_op(op)).await;
let (_, ids) = wal.rotate().unwrap();
assert_eq!(ids.iter().collect::<Vec<_>>(), [SequenceNumber::new(44)]);
let op = arbitrary_sequenced_wal_op([45]);
let _ = unwrap_summary(wal.write_op(op)).await;
}
// Create a new WAL instance with the same directory to replay from the files
let wal = wal::Wal::new(dir.path()).await.unwrap();
// There are 3 segments (from the 2 closed and 1 open) and they're in the order they were
// created
let closed = wal.closed_segments();
let closed_segment_ids: Vec<_> = closed.iter().map(|c| c.id().get()).collect();
assert_eq!(closed_segment_ids, &[0, 1, 2]);
// The open segment is next in order
let (closed_segment_details, ids) = wal.rotate().unwrap();
assert_eq!(closed_segment_details.id().get(), 3);
assert!(ids.is_empty());
// Creating new files after replay are later in the ordering
let (closed_segment_details, ids) = wal.rotate().unwrap();
assert_eq!(closed_segment_details.id().get(), 4);
assert!(ids.is_empty());
}
fn arbitrary_sequenced_wal_op<I: IntoIterator<Item = u64>>(sequence_numbers: I) -> SequencedWalOp {
let sequence_numbers = sequence_numbers.into_iter().collect::<Vec<_>>();
let lp = sequence_numbers
.iter()
.enumerate()
.fold(String::new(), |string, (idx, _)| {
string + &format!("m{},t=foo v=1i 1\n", idx)
});
let w = test_data(lp.as_str());
SequencedWalOp {
table_write_sequence_numbers: w
.table_batches
.iter()
.zip(sequence_numbers.iter())
.map(|(table_batch, &id)| (TableId::new(table_batch.table_id), id))
.collect(),
op: WalOp::Write(w),
}
}
fn test_data(lp: &str) -> DatabaseBatch {
let batches = lines_to_batches(lp, 0).unwrap();
let batches = batches
.into_iter()
.enumerate()
.map(|(i, (_table_name, batch))| (TableId::new(i as _), batch))
.collect();
let write = DmlWrite::new(
NamespaceId::new(42),
batches,
"bananas".into(),
Default::default(),
);
let database_batch = mutable_batch_pb::encode::encode_write(42, &write);
// `encode_write` returns tables and columns in an arbitrary order. Sort tables and columns
// to make tests deterministic.
let DatabaseBatch {
database_id,
partition_key,
table_batches,
} = database_batch;
let mut table_batches: Vec<_> = table_batches
.into_iter()
.map(|table_batch| {
let TableBatch {
table_id,
mut columns,
row_count,
} = table_batch;
columns.sort_by(|a, b| a.column_name.cmp(&b.column_name));
TableBatch {
table_id,
columns,
row_count,
}
})
.collect();
table_batches.sort_by_key(|t| t.table_id);
DatabaseBatch {
database_id,
partition_key,
table_batches,
}
}
async fn unwrap_summary(mut res: watch::Receiver<Option<WriteResult>>) -> WriteSummary {
res.changed().await.unwrap();
match res.borrow().clone().unwrap() {
WriteResult::Ok(summary) => summary,
WriteResult::Err(err) => panic!("error getting write summary: {err}"),
}
}
|
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LSION`"]
pub type LSION_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LSION`"]
pub struct LSION_W<'a> {
w: &'a mut W,
}
impl<'a> LSION_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `LSIRDY`"]
pub type LSIRDY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LSIRDY`"]
pub struct LSIRDY_W<'a> {
w: &'a mut W,
}
impl<'a> LSIRDY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `RMVF`"]
pub type RMVF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RMVF`"]
pub struct RMVF_W<'a> {
w: &'a mut W,
}
impl<'a> RMVF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `OBLRSTF`"]
pub type OBLRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OBLRSTF`"]
pub struct OBLRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> OBLRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `PINRSTF`"]
pub type PINRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PINRSTF`"]
pub struct PINRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> PINRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `PWRRSTF`"]
pub type PWRRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PWRRSTF`"]
pub struct PWRRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> PWRRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `SFTRSTF`"]
pub type SFTRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SFTRSTF`"]
pub struct SFTRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> SFTRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `IWDGRSTF`"]
pub type IWDGRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IWDGRSTF`"]
pub struct IWDGRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> IWDGRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `WWDGRSTF`"]
pub type WWDGRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WWDGRSTF`"]
pub struct WWDGRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> WWDGRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `LPWRRSTF`"]
pub type LPWRRSTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPWRRSTF`"]
pub struct LPWRRSTF_W<'a> {
w: &'a mut W,
}
impl<'a> LPWRRSTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - LSI oscillator enable"]
#[inline(always)]
pub fn lsion(&self) -> LSION_R {
LSION_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LSI oscillator ready"]
#[inline(always)]
pub fn lsirdy(&self) -> LSIRDY_R {
LSIRDY_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 23 - Remove reset flags"]
#[inline(always)]
pub fn rmvf(&self) -> RMVF_R {
RMVF_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 25 - Option byte loader reset flag"]
#[inline(always)]
pub fn oblrstf(&self) -> OBLRSTF_R {
OBLRSTF_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - Pin reset flag"]
#[inline(always)]
pub fn pinrstf(&self) -> PINRSTF_R {
PINRSTF_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - BOR or POR/PDR flag"]
#[inline(always)]
pub fn pwrrstf(&self) -> PWRRSTF_R {
PWRRSTF_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - Software reset flag"]
#[inline(always)]
pub fn sftrstf(&self) -> SFTRSTF_R {
SFTRSTF_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - Independent window watchdog reset flag"]
#[inline(always)]
pub fn iwdgrstf(&self) -> IWDGRSTF_R {
IWDGRSTF_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - Window watchdog reset flag"]
#[inline(always)]
pub fn wwdgrstf(&self) -> WWDGRSTF_R {
WWDGRSTF_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - Low-power reset flag"]
#[inline(always)]
pub fn lpwrrstf(&self) -> LPWRRSTF_R {
LPWRRSTF_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LSI oscillator enable"]
#[inline(always)]
pub fn lsion(&mut self) -> LSION_W {
LSION_W { w: self }
}
#[doc = "Bit 1 - LSI oscillator ready"]
#[inline(always)]
pub fn lsirdy(&mut self) -> LSIRDY_W {
LSIRDY_W { w: self }
}
#[doc = "Bit 23 - Remove reset flags"]
#[inline(always)]
pub fn rmvf(&mut self) -> RMVF_W {
RMVF_W { w: self }
}
#[doc = "Bit 25 - Option byte loader reset flag"]
#[inline(always)]
pub fn oblrstf(&mut self) -> OBLRSTF_W {
OBLRSTF_W { w: self }
}
#[doc = "Bit 26 - Pin reset flag"]
#[inline(always)]
pub fn pinrstf(&mut self) -> PINRSTF_W {
PINRSTF_W { w: self }
}
#[doc = "Bit 27 - BOR or POR/PDR flag"]
#[inline(always)]
pub fn pwrrstf(&mut self) -> PWRRSTF_W {
PWRRSTF_W { w: self }
}
#[doc = "Bit 28 - Software reset flag"]
#[inline(always)]
pub fn sftrstf(&mut self) -> SFTRSTF_W {
SFTRSTF_W { w: self }
}
#[doc = "Bit 29 - Independent window watchdog reset flag"]
#[inline(always)]
pub fn iwdgrstf(&mut self) -> IWDGRSTF_W {
IWDGRSTF_W { w: self }
}
#[doc = "Bit 30 - Window watchdog reset flag"]
#[inline(always)]
pub fn wwdgrstf(&mut self) -> WWDGRSTF_W {
WWDGRSTF_W { w: self }
}
#[doc = "Bit 31 - Low-power reset flag"]
#[inline(always)]
pub fn lpwrrstf(&mut self) -> LPWRRSTF_W {
LPWRRSTF_W { w: self }
}
}
|
#[macro_use]
extern crate nom;
use nom::digit;
use nom::types::CompleteStr;
use std::str::FromStr;
#[derive (Eq, PartialEq, Debug)]
struct Claim {
id: u32,
x: u32,
y: u32,
w: u32,
h: u32
}
//named!(claimi(CompleteStr) -> i32, map_res!(recognize!(nom::digit), i32::from_str));
named!(parse_claim <CompleteStr,Claim>, do_parse!(
ws!(tag!("#")) >>
id: map_res!(digit, |CompleteStr(s)| u32::from_str(s)) >>
ws!(tag!("@")) >>
x: map_res!(digit, |CompleteStr(s)| u32::from_str(s)) >>
ws!(tag!(",")) >>
y: map_res!(digit, |CompleteStr(s)| u32::from_str(s)) >>
ws!(tag!(":")) >>
w: map_res!(digit, |CompleteStr(s)| u32::from_str(s)) >>
ws!(tag!("x")) >>
h: map_res!(digit, |CompleteStr(s)| u32::from_str(s)) >>
(Claim {id,x,y,w,h})
));
#[no_mangle]
pub fn aoc_solution(star: i32, input: &str) -> String {
let mut max_x = 0u32;
let mut max_y = 0u32;
let mut claim: Vec<Claim> = Vec::new();
for line in input.lines() {
let c = parse_claim(CompleteStr(line)).unwrap().1;
if c.x + c.w - 1 > max_x {
max_x = c.x + c.w - 1;
}
if c.y + c.h - 1 > max_y {
max_y = c.y + c.h - 1;
}
claim.push(c);
}
let width = (max_x+1) as usize;
let height = (max_y+1) as usize;
let mut grid_raw = vec![0; width * height];
let mut grid_base: Vec<_> = grid_raw.as_mut_slice().chunks_mut(width).collect();
let fabric: &mut [&mut [_]] = grid_base.as_mut_slice();
for c in claim.iter() {
for y in c.y..=(c.y+c.h-1) {
for x in c.x..=(c.x+c.w-1) {
//println!("{:?}",c);
fabric[y as usize][x as usize] += 1;
}
}
}
let mut star1_count = 0u64;
for y in 0..height {
for x in 0..width {
if fabric[y as usize][x as usize] >= 2 {
star1_count += 1;
}
}
}
let mut good_claim_id = 0u32;
for c in claim.iter() {
let mut claim_pure = true;
for y in c.y..=(c.y+c.h-1) {
for x in c.x..=(c.x+c.w-1) {
if fabric[y as usize][x as usize] > 1 {
claim_pure = false;
}
}
}
if claim_pure {
good_claim_id = c.id;
break;
}
}
if 1 == star {
format!("{}",star1_count)
}
else {
format!("{}",good_claim_id)
}
}
|
extern crate libwebm;
use std::fs::File;
use libwebm::mkvmuxer::writer::MkvWriter;
mod util;
#[test]
fn test_new_writer() {
//let w = MkvWriter::new(File::create());
} |
//use Value;
//use error::Error;
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Unimplemented<'a> {
/// The input contained a boolean value that was not expected.
Keyword(&'a str),
Symbol(&'a str),
}
//pub trait EDNVisitor<'de>: Sized {
// type OutputValue;
//
// fn visit_keyword_str<E>(self, v: &str) -> Result<Self::OutputValue, E>
// where E: de::Error,
// {
// Err(Error::custom(Unimplemented::Keyword(&v), &self))
// }
//
// fn visit_keyword_string<E>(self, v: String) -> Result<Self::OutputValue, E>
// where E: de::Error,
// {
// Err(Error::custom(Unimplemented::Keyword(&v), &self))
// }
//
// fn visit_symbol_str<E>(self, v: &str) -> Result<Self::OutputValue, E>
// where E: de::Error,
// {
// Err(Error::custom(Unimplemented::Symbol(&v), &self))
// }
//
// fn visit_symbol_string<E>(self, v: String) -> Result<Self::OutputValue, E>
// where E: de::Error,
// {
// Err(Error::custom(Unimplemented::Symbol(&v), &self))
// }
////}
//
//#[inline]
//pub fn visit_keyword_str<'de, V>(v: &str, visitor:V) -> Result<V::Value, Error> {
// visit_keyword_string(visitor,String::from(v))
//}
//
//#[inline]
//pub fn visit_keyword_string<'de, V>(v: String, visitor: V) -> Result<V::Value, Error>{
////pub fn visit_keyword_string<E>(v: String) -> Result<Value, E> {
// Ok(Value::Keyword(v))
//}
//
//#[inline]
//pub fn visit_symbol_str<E>(v: &str) -> Result<Value, E> {
// visit_symbol_string(String::from(v))
//}
//
//#[inline]
//pub fn visit_symbol_string<E>(v: String) -> Result<Value, E> {
// Ok(Value::Symbol(v))
//}
|
// Copyright (C) 2020, Cloudflare, Inc.
// All rights reserved.
//
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//! Delivery rate estimation.
//!
//! This implements the algorithm for estimating delivery rate as described in
//! <https://tools.ietf.org/html/draft-cheng-iccrg-delivery-rate-estimation-00>
use std::cmp;
use std::time::Duration;
use std::time::Instant;
use crate::recovery::Sent;
#[derive(Default)]
pub struct Rate {
delivered: usize,
delivered_time: Option<Instant>,
recent_delivered_packet_sent_time: Option<Instant>,
app_limited_at_pkt: usize,
rate_sample: RateSample,
}
impl Rate {
pub fn on_packet_sent(&mut self, pkt: &mut Sent, now: Instant) {
if self.delivered_time.is_none() {
self.delivered_time = Some(now);
}
if self.recent_delivered_packet_sent_time.is_none() {
self.recent_delivered_packet_sent_time = Some(now);
}
pkt.delivered = self.delivered;
pkt.delivered_time = self.delivered_time.unwrap();
pkt.recent_delivered_packet_sent_time =
self.recent_delivered_packet_sent_time.unwrap();
pkt.is_app_limited = self.app_limited_at_pkt > 0;
}
pub fn on_packet_acked(&mut self, pkt: &Sent, now: Instant) {
self.rate_sample.prior_time = Some(pkt.delivered_time);
self.delivered += pkt.size;
self.delivered_time = Some(now);
if pkt.delivered > self.rate_sample.prior_delivered {
self.rate_sample.prior_delivered = pkt.delivered;
self.rate_sample.send_elapsed =
pkt.time_sent - pkt.recent_delivered_packet_sent_time;
self.rate_sample.ack_elapsed = self
.delivered_time
.unwrap()
.duration_since(pkt.delivered_time);
self.recent_delivered_packet_sent_time = Some(pkt.time_sent);
}
}
pub fn estimate(&mut self) {
if (self.app_limited_at_pkt > 0) &&
(self.delivered > self.app_limited_at_pkt)
{
self.app_limited_at_pkt = 0;
}
match self.rate_sample.prior_time {
Some(_) => {
self.rate_sample.delivered =
self.delivered - self.rate_sample.prior_delivered;
self.rate_sample.interval = cmp::max(
self.rate_sample.send_elapsed,
self.rate_sample.ack_elapsed,
);
},
None => return,
}
if self.rate_sample.interval.as_secs_f64() > 0.0 {
self.rate_sample.delivery_rate = (self.rate_sample.delivered as f64 /
self.rate_sample.interval.as_secs_f64())
as u64;
}
}
pub fn check_app_limited(&mut self, bytes_in_flight: usize) {
let limited = self.delivered + bytes_in_flight;
self.app_limited_at_pkt = if limited > 0 { limited } else { 1 };
}
pub fn delivery_rate(&self) -> u64 {
self.rate_sample.delivery_rate
}
}
impl std::fmt::Debug for Rate {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "delivered={:?} ", self.delivered)?;
if let Some(t) = self.delivered_time {
write!(f, "delivered_time={:?} ", t.elapsed())?;
}
if let Some(t) = self.recent_delivered_packet_sent_time {
write!(f, "recent_delivered_packet_sent_time={:?} ", t.elapsed())?;
}
write!(f, "app_limited_at_pkt={:?} ", self.app_limited_at_pkt)?;
Ok(())
}
}
#[derive(Default)]
struct RateSample {
delivery_rate: u64,
interval: Duration,
delivered: usize,
prior_delivered: usize,
prior_time: Option<Instant>,
send_elapsed: Duration,
ack_elapsed: Duration,
}
impl std::fmt::Debug for RateSample {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "delivery_rate={:?} ", self.delivery_rate)?;
write!(f, "interval={:?} ", self.interval)?;
write!(f, "delivered={:?} ", self.delivered)?;
write!(f, "prior_delivered={:?} ", self.prior_delivered)?;
write!(f, "send_elapsed={:?} ", self.send_elapsed)?;
if let Some(t) = self.prior_time {
write!(f, "prior_time={:?} ", t.elapsed())?;
}
write!(f, "ack_elapsed={:?}", self.ack_elapsed)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::recovery::*;
#[test]
fn rate_check() {
let config = Config::new(0xbabababa).unwrap();
let mut recovery = Recovery::new(&config);
let mut pkt_1 = Sent {
pkt_num: 0,
frames: vec![],
time_sent: Instant::now(),
time_acked: None,
time_lost: None,
size: 1200,
ack_eliciting: true,
in_flight: true,
delivered: 0,
delivered_time: Instant::now(),
recent_delivered_packet_sent_time: Instant::now(),
is_app_limited: false,
has_data: false,
};
recovery
.delivery_rate
.on_packet_sent(&mut pkt_1, Instant::now());
std::thread::sleep(Duration::from_millis(50));
recovery
.delivery_rate
.on_packet_acked(&pkt_1, Instant::now());
let mut pkt_2 = Sent {
pkt_num: 1,
frames: vec![],
time_sent: Instant::now(),
time_acked: None,
time_lost: None,
size: 1200,
ack_eliciting: true,
in_flight: true,
delivered: 0,
delivered_time: Instant::now(),
recent_delivered_packet_sent_time: Instant::now(),
is_app_limited: false,
has_data: false,
};
recovery
.delivery_rate
.on_packet_sent(&mut pkt_2, Instant::now());
std::thread::sleep(Duration::from_millis(50));
recovery
.delivery_rate
.on_packet_acked(&pkt_2, Instant::now());
recovery.delivery_rate.estimate();
assert!(recovery.delivery_rate() > 0);
}
#[test]
fn app_limited_check() {
let config = Config::new(0xbabababa).unwrap();
let mut recvry = Recovery::new(&config);
let mut pkt_1 = Sent {
pkt_num: 0,
frames: vec![],
time_sent: Instant::now(),
time_acked: None,
time_lost: None,
size: 1200,
ack_eliciting: true,
in_flight: true,
delivered: 0,
delivered_time: Instant::now(),
recent_delivered_packet_sent_time: Instant::now(),
is_app_limited: false,
has_data: false,
};
recvry
.delivery_rate
.on_packet_sent(&mut pkt_1, Instant::now());
std::thread::sleep(Duration::from_millis(50));
recvry.delivery_rate.on_packet_acked(&pkt_1, Instant::now());
let mut pkt_2 = Sent {
pkt_num: 1,
frames: vec![],
time_sent: Instant::now(),
time_acked: None,
time_lost: None,
size: 1200,
ack_eliciting: true,
in_flight: true,
delivered: 0,
delivered_time: Instant::now(),
recent_delivered_packet_sent_time: Instant::now(),
is_app_limited: false,
has_data: false,
};
recvry.app_limited = true;
recvry
.delivery_rate
.check_app_limited(recvry.bytes_in_flight);
recvry
.delivery_rate
.on_packet_sent(&mut pkt_2, Instant::now());
std::thread::sleep(Duration::from_millis(50));
recvry.delivery_rate.on_packet_acked(&pkt_2, Instant::now());
recvry.delivery_rate.estimate();
assert_eq!(recvry.delivery_rate.app_limited_at_pkt, 0);
}
}
|
pub mod ffi;
#[cfg(feature = "reader")]
pub mod reader;
#[cfg(all(feature = "reader", feature = "async"))]
pub mod reader_async;
#[cfg(feature = "reader")]
pub mod metadata;
#[cfg(feature = "reader")]
pub mod schema;
pub mod wasm;
#[cfg(feature = "writer")]
pub mod writer;
#[cfg(feature = "writer")]
pub mod writer_properties;
pub mod error;
|
#[cfg(any(feature = "test_go_interop", feature = "test_js_interop"))]
pub use common::{api_call, ForeignNode};
#[cfg(all(not(feature = "test_go_interop"), not(feature = "test_js_interop")))]
#[allow(dead_code)]
pub struct ForeignNode;
#[cfg(any(feature = "test_go_interop", feature = "test_js_interop"))]
pub mod common {
use libp2p::{core::PublicKey, Multiaddr, PeerId};
use rand::prelude::*;
use serde::Deserialize;
use std::{
env, fs,
path::PathBuf,
process::{Child, Command, Stdio},
};
#[derive(Debug)]
pub struct ForeignNode {
pub dir: PathBuf,
pub daemon: Child,
pub id: PeerId,
pub pk: PublicKey,
pub addrs: Vec<Multiaddr>,
pub binary_path: String,
pub api_port: u16,
}
impl ForeignNode {
#[allow(dead_code)]
pub fn new() -> ForeignNode {
use std::{io::Read, net::SocketAddr, str};
// this environment variable should point to the location of the foreign ipfs binary
#[cfg(feature = "test_go_interop")]
const ENV_IPFS_PATH: &str = "GO_IPFS_PATH";
#[cfg(feature = "test_js_interop")]
const ENV_IPFS_PATH: &str = "JS_IPFS_PATH";
// obtain the path of the foreign ipfs binary from an environment variable
let binary_path = env::vars()
.find(|(key, _val)| key == ENV_IPFS_PATH)
.unwrap_or_else(|| {
panic!("the {} environment variable was not found", ENV_IPFS_PATH)
})
.1;
// create the temporary directory for the repo etc
let mut tmp_dir = env::temp_dir();
let mut rng = rand::thread_rng();
tmp_dir.push(&format!("ipfs_test_{}", rng.gen::<u64>()));
let _ = fs::create_dir(&tmp_dir);
// initialize the node and assign the temporary directory to it
Command::new(&binary_path)
.env("IPFS_PATH", &tmp_dir)
.arg("init")
.arg("-p")
.arg("test")
.stdout(Stdio::null())
.status()
.unwrap();
#[cfg(feature = "test_go_interop")]
let daemon_args = &["daemon", "--enable-pubsub-experiment"];
#[cfg(feature = "test_js_interop")]
let daemon_args = &["daemon"];
// start the ipfs daemon
let mut daemon = Command::new(&binary_path)
.env("IPFS_PATH", &tmp_dir)
.args(daemon_args)
.stdout(Stdio::piped())
.spawn()
.unwrap();
// read the stdout of the spawned daemon...
let mut buf = vec![0; 2048];
let mut index = 0;
if let Some(ref mut stdout) = daemon.stdout {
while let Ok(read) = stdout.read(&mut buf[index..]) {
index += read;
if str::from_utf8(&buf).unwrap().contains("Daemon is ready") {
break;
}
}
}
// ...so that the randomly assigned API port can be registered
let mut api_port = None;
for line in str::from_utf8(&buf).unwrap().lines() {
if line.contains("webui") {
let addr = line.rsplitn(2, ' ').next().unwrap();
let addr = addr.strip_prefix("http://").unwrap();
let addr: SocketAddr = addr.rsplitn(2, '/').nth(1).unwrap().parse().unwrap();
api_port = Some(addr.port());
}
}
let api_port = api_port.unwrap();
// run /id in order to register the PeerId, PublicKey and Multiaddrs assigned to the node
let node_id = Command::new(&binary_path)
.env("IPFS_PATH", &tmp_dir)
.arg("id")
.output()
.unwrap()
.stdout;
let node_id_stdout = String::from_utf8_lossy(&node_id);
let ForeignNodeId {
id,
addresses,
public_key,
..
} = serde_json::de::from_str(&node_id_stdout).unwrap();
let id = id.parse().unwrap();
let pk = PublicKey::from_protobuf_encoding(
&base64::decode(public_key.into_bytes()).unwrap(),
)
.unwrap();
ForeignNode {
dir: tmp_dir,
daemon,
id,
pk,
addrs: addresses,
binary_path,
api_port,
}
}
#[allow(dead_code)]
pub async fn identity(&self) -> Result<(PublicKey, Vec<Multiaddr>), anyhow::Error> {
Ok((self.pk.clone(), self.addrs.clone()))
}
}
impl Drop for ForeignNode {
fn drop(&mut self) {
let _ = self.daemon.kill();
let _ = fs::remove_dir_all(&self.dir);
}
}
// this one is not a method on ForeignNode, as only its port number is needed and we don't
// want to restrict ourselves from calling it from spawned tasks or threads (or to make the
// internals of ForeignNode complicated by making it Clone)
#[allow(dead_code)]
pub async fn api_call<T: AsRef<str>>(api_port: u16, call: T) -> String {
let bytes = Command::new("curl")
.arg("-X")
.arg("POST")
.arg(&format!(
"http://127.0.0.1:{}/api/v0/{}",
api_port,
call.as_ref()
))
.output()
.unwrap()
.stdout;
String::from_utf8(bytes).unwrap()
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "test_go_interop", serde(rename_all = "PascalCase"))]
#[cfg_attr(feature = "test_js_interop", serde(rename_all = "camelCase"))]
pub struct ForeignNodeId {
#[cfg_attr(feature = "test_go_interop", serde(rename = "ID"))]
pub id: String,
pub public_key: String,
pub addresses: Vec<Multiaddr>,
#[serde(skip)]
agent_version: String,
#[serde(skip)]
protocol_version: String,
}
}
|
pub mod create;
pub mod tally;
pub mod verify;
|
//! # Chapter 5: Repetition
//!
//! In [`chapter_3`], we covered how to sequence different parsers into a tuple but sometimes you need to run a
//! single parser multiple times, collecting the result into a container, like [`Vec`].
//!
//! Let's collect the result of `parse_digits`:
//! ```rust
//! # use winnow::prelude::*;
//! # use winnow::token::take_while;
//! # use winnow::combinator::dispatch;
//! # use winnow::token::take;
//! # use winnow::combinator::fail;
//! use winnow::combinator::opt;
//! use winnow::combinator::repeat;
//! use winnow::combinator::terminated;
//!
//! fn parse_list(input: &mut &str) -> PResult<Vec<usize>> {
//! let mut list = Vec::new();
//! while let Some(output) = opt(terminated(parse_digits, opt(','))).parse_next(input)? {
//! list.push(output);
//! }
//! Ok(list)
//! }
//!
//! // ...
//! # fn parse_digits(input: &mut &str) -> PResult<usize> {
//! # dispatch!(take(2usize);
//! # "0b" => parse_bin_digits.try_map(|s| usize::from_str_radix(s, 2)),
//! # "0o" => parse_oct_digits.try_map(|s| usize::from_str_radix(s, 8)),
//! # "0d" => parse_dec_digits.try_map(|s| usize::from_str_radix(s, 10)),
//! # "0x" => parse_hex_digits.try_map(|s| usize::from_str_radix(s, 16)),
//! # _ => fail,
//! # ).parse_next(input)
//! # }
//! #
//! # fn parse_bin_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_oct_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_dec_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_hex_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # ('A'..='F'),
//! # ('a'..='f'),
//! # )).parse_next(input)
//! # }
//!
//! fn main() {
//! let mut input = "0x1a2b,0x3c4d,0x5e6f Hello";
//!
//! let digits = parse_list.parse_next(&mut input).unwrap();
//!
//! assert_eq!(input, " Hello");
//! assert_eq!(digits, vec![0x1a2b, 0x3c4d, 0x5e6f]);
//!
//! assert!(parse_digits(&mut "ghiWorld").is_err());
//! }
//! ```
//!
//! We can implement this declaratively with [`repeat`]:
//! ```rust
//! # use winnow::prelude::*;
//! # use winnow::token::take_while;
//! # use winnow::combinator::dispatch;
//! # use winnow::token::take;
//! # use winnow::combinator::fail;
//! use winnow::combinator::opt;
//! use winnow::combinator::repeat;
//! use winnow::combinator::terminated;
//!
//! fn parse_list(input: &mut &str) -> PResult<Vec<usize>> {
//! repeat(0..,
//! terminated(parse_digits, opt(','))
//! ).parse_next(input)
//! }
//! #
//! # fn parse_digits(input: &mut &str) -> PResult<usize> {
//! # dispatch!(take(2usize);
//! # "0b" => parse_bin_digits.try_map(|s| usize::from_str_radix(s, 2)),
//! # "0o" => parse_oct_digits.try_map(|s| usize::from_str_radix(s, 8)),
//! # "0d" => parse_dec_digits.try_map(|s| usize::from_str_radix(s, 10)),
//! # "0x" => parse_hex_digits.try_map(|s| usize::from_str_radix(s, 16)),
//! # _ => fail,
//! # ).parse_next(input)
//! # }
//! #
//! # fn parse_bin_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_oct_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_dec_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_hex_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # ('A'..='F'),
//! # ('a'..='f'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn main() {
//! # let mut input = "0x1a2b,0x3c4d,0x5e6f Hello";
//! #
//! # let digits = parse_list.parse_next(&mut input).unwrap();
//! #
//! # assert_eq!(input, " Hello");
//! # assert_eq!(digits, vec![0x1a2b, 0x3c4d, 0x5e6f]);
//! #
//! # assert!(parse_digits(&mut "ghiWorld").is_err());
//! # }
//! ```
//!
//! You'll notice that the above allows trailing `,` when we intended to not support that. We can
//! easily fix this by using [`separated0`]:
//! ```rust
//! # use winnow::prelude::*;
//! # use winnow::token::take_while;
//! # use winnow::combinator::dispatch;
//! # use winnow::token::take;
//! # use winnow::combinator::fail;
//! use winnow::combinator::separated0;
//!
//! fn parse_list(input: &mut &str) -> PResult<Vec<usize>> {
//! separated0(parse_digits, ",").parse_next(input)
//! }
//!
//! // ...
//! # fn parse_digits(input: &mut &str) -> PResult<usize> {
//! # dispatch!(take(2usize);
//! # "0b" => parse_bin_digits.try_map(|s| usize::from_str_radix(s, 2)),
//! # "0o" => parse_oct_digits.try_map(|s| usize::from_str_radix(s, 8)),
//! # "0d" => parse_dec_digits.try_map(|s| usize::from_str_radix(s, 10)),
//! # "0x" => parse_hex_digits.try_map(|s| usize::from_str_radix(s, 16)),
//! # _ => fail,
//! # ).parse_next(input)
//! # }
//! #
//! # fn parse_bin_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_oct_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_dec_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_hex_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # ('A'..='F'),
//! # ('a'..='f'),
//! # )).parse_next(input)
//! # }
//!
//! fn main() {
//! let mut input = "0x1a2b,0x3c4d,0x5e6f Hello";
//!
//! let digits = parse_list.parse_next(&mut input).unwrap();
//!
//! assert_eq!(input, " Hello");
//! assert_eq!(digits, vec![0x1a2b, 0x3c4d, 0x5e6f]);
//!
//! assert!(parse_digits(&mut "ghiWorld").is_err());
//! }
//! ```
//!
//! If you look closely at [`repeat`], it isn't collecting directly into a [`Vec`] but
//! [`Accumulate`] to gather the results. This let's us make more complex parsers than we did in
//! [`chapter_2`] by accumulating the results into a `()` and [`recognize`][Parser::recognize]-ing the captured input:
//! ```rust
//! # use winnow::prelude::*;
//! # use winnow::token::take_while;
//! # use winnow::combinator::dispatch;
//! # use winnow::token::take;
//! # use winnow::combinator::fail;
//! # use winnow::combinator::separated0;
//! #
//! fn recognize_list<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! parse_list.recognize().parse_next(input)
//! }
//!
//! fn parse_list(input: &mut &str) -> PResult<()> {
//! separated0(parse_digits, ",").parse_next(input)
//! }
//!
//! # fn parse_digits(input: &mut &str) -> PResult<usize> {
//! # dispatch!(take(2usize);
//! # "0b" => parse_bin_digits.try_map(|s| usize::from_str_radix(s, 2)),
//! # "0o" => parse_oct_digits.try_map(|s| usize::from_str_radix(s, 8)),
//! # "0d" => parse_dec_digits.try_map(|s| usize::from_str_radix(s, 10)),
//! # "0x" => parse_hex_digits.try_map(|s| usize::from_str_radix(s, 16)),
//! # _ => fail,
//! # ).parse_next(input)
//! # }
//! #
//! # fn parse_bin_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_oct_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='7'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_dec_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # )).parse_next(input)
//! # }
//! #
//! # fn parse_hex_digits<'s>(input: &mut &'s str) -> PResult<&'s str> {
//! # take_while(1.., (
//! # ('0'..='9'),
//! # ('A'..='F'),
//! # ('a'..='f'),
//! # )).parse_next(input)
//! # }
//!
//! fn main() {
//! let mut input = "0x1a2b,0x3c4d,0x5e6f Hello";
//!
//! let digits = recognize_list.parse_next(&mut input).unwrap();
//!
//! assert_eq!(input, " Hello");
//! assert_eq!(digits, "0x1a2b,0x3c4d,0x5e6f");
//!
//! assert!(parse_digits(&mut "ghiWorld").is_err());
//! }
//! ```
//! See [`combinator`] for more repetition parsers.
#![allow(unused_imports)]
use super::chapter_2;
use super::chapter_3;
use crate::combinator;
use crate::combinator::repeat;
use crate::combinator::separated0;
use crate::stream::Accumulate;
use crate::Parser;
use std::vec::Vec;
pub use super::chapter_4 as previous;
pub use super::chapter_6 as next;
pub use crate::_tutorial as table_of_content;
|
use crate::RootSchema;
use actix_web::{web, HttpResponse, Result};
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql_actix_web::{Request, Response};
pub async fn graphql(schema: web::Data<RootSchema>, req: Request) -> Response {
schema.execute(req.into_inner()).await.into()
}
pub async fn graphql_playground() -> Result<HttpResponse> {
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(playground_source(
GraphQLPlaygroundConfig::new("/graphql").subscription_endpoint("/graphql"),
)))
}
|
//! The traits defined here are implementation details of cell_gc.
//!
//! Application code does not need to use these traits. They are public only so
//! that `gc_heap_type!` can use it. Use the friendly macro!
use gcref::GcRef;
use ptr::Pointer;
/// Trait for values that can be moved into a GC heap.
///
/// Cell-gc does not support GC allocation of arbitrary values: only values of
/// types that implement `IntoHeap`. This trait is **not** meant to be
/// implemented by hand: use the `gc_heap_type!` macro instead. All primitive
/// types and many standard types support `IntoHeap`.
///
/// GC types come in pairs: an *in-heap* type, which is stored physically inside
/// the heap, and may be packed with pointer fields and unsafe methods; and an
/// `IntoHeap` type, which is safe, is used in application code, and lives on
/// the stack. Both types have the same layout, bit for bit.
///
/// (The word "safe" above means that, as with everything generally in Rust, you
/// can hack without fear. `IntoHeap` types don't expose raw Rust pointers or
/// references to GC memory, they don't expose the unsafe in-heap types, and
/// they obey Rust's safety and aliasing rules.)
///
/// Users never get a direct `&` reference to any in-heap value. All access is
/// through safe `IntoHeap` types, like the `Ref` type that is automatically
/// declared for you when you use `gc_heap_type!` to declare a struct.
///
/// * For primitive types, like `i32`, the two types are the same.
///
/// * Macro-generated "Ref" types are `IntoHeap` types; the corresponding
/// in-heap types are effectively raw pointers.
///
/// * For macro-generated structs and enums, the user specifies the names of
/// both types. Both types have identical fields or variants, but fields of
/// the in-heap type are in-heap, and fields of the `IntoHeap` type are
/// `IntoHeap`.
///
/// Implementation note: every type with `'static` lifetime should be safe to
/// store in the heap, because ref types are never `'static`. Unfortunately I
/// can't make rustc understand this. It would be *legal* to write this:
///
/// ```ignore
/// unsafe impl<'h, T: Clone + 'static> IntoHeap<'h> for T { ...trivial... }
/// ```
///
/// but alas, Rust thinks this impl conflicts with almost all others, making it
/// impossible to get the macro to work. So instead we `impl IntoHeap for` a
/// lot of individual types by hand.
///
/// **Liveness.** Some `IntoHeap` types ("Ref" types) are effectively smart
/// pointers to in-heap values. To preserve safety, if an `IntoHeap` value is
/// (or contains) a smart pointer to an in-heap value, then that value (and
/// everything reachable from it) is protected from GC.
///
/// # Safety
///
/// In-heap objects are full of pointers; if `into_heap` puts garbage into
/// them, GC will crash.
///
/// `trace` must be implemented with care in order to preserve the invariants
/// of the GC graph-walking algorithm. Bugs there are very likely to lead to
/// dangling pointers and hard-to-debug crashes down the road.
///
/// And this maybe goes without saying, but none of these methods may allocate
/// or do anything else that could trigger garbage collection.
///
pub unsafe trait IntoHeap<'h>: Sized {
/// The type of the value when it is physically stored in the heap.
type In;
/// Convert the value to the form it should have in the heap.
/// This is for macro-generated code to call.
///
/// This method must not be called while any direct Rust references to
/// heap objects exist. (However, user code never runs while such
/// references exist, so the method is not marked `unsafe`.)
fn into_heap(self) -> Self::In;
/// Extract the value from the heap. This turns any raw pointers in the
/// in-heap value into safe references, so while it's an unsafe function,
/// the result of a correct call can be safely handed out to user code.
///
/// Unsafe to call: It is impossible for ordinary users to call this
/// safely, because `self` must be a direct, unwrapped reference to a value
/// stored in the GC heap, which ordinary users cannot obtain.
unsafe fn from_heap(&Self::In) -> Self;
/// # Safety
///
/// It is impossible for ordinary users to call this safely, because `self`
/// must be a direct, unwrapped reference to a value stored in the GC heap,
/// which ordinary users cannot obtain.
unsafe fn trace<R>(&Self::In, tracer: &mut R)
where
R: Tracer;
}
/// Relate an `IntoHeap` type to the corresponding safe reference type.
pub trait IntoHeapAllocation<'h>: IntoHeap<'h> {
type Ref: IntoHeap<'h>;
fn wrap_gcref(gcref: GcRef<'h, Self>) -> Self::Ref;
}
pub trait Tracer {
fn visit<'h, T>(&mut self, Pointer<T::In>)
where
T: IntoHeapAllocation<'h>;
}
// === Provided implmentations for primitive types
macro_rules! gc_trivial_impl {
($t:ty) => {
unsafe impl<'h> IntoHeap<'h> for $t {
type In = $t;
fn into_heap(self) -> $t { self }
unsafe fn from_heap(storage: &$t) -> $t { storage.clone() }
unsafe fn trace<R>(_storage: &$t, _tracer: &mut R) where R: Tracer {}
}
}
}
gc_trivial_impl!(bool);
gc_trivial_impl!(char);
gc_trivial_impl!(i8);
gc_trivial_impl!(u8);
gc_trivial_impl!(i16);
gc_trivial_impl!(u16);
gc_trivial_impl!(i32);
gc_trivial_impl!(u32);
gc_trivial_impl!(i64);
gc_trivial_impl!(u64);
gc_trivial_impl!(isize);
gc_trivial_impl!(usize);
gc_trivial_impl!(f32);
gc_trivial_impl!(f64);
gc_trivial_impl!(String);
macro_rules! gc_generic_trivial_impl {
(@as_item $it:item) => { $it };
([$($x:tt)*] $t:ty) => {
gc_generic_trivial_impl! {
@as_item
unsafe impl<'h, $($x)*> IntoHeap<'h> for $t {
type In = $t;
fn into_heap(self) -> $t { self }
unsafe fn from_heap(storage: &$t) -> $t { (*storage).clone() }
unsafe fn trace<R>(_storage: &$t, _tracer: &mut R) where R: Tracer {}
}
}
}
}
gc_generic_trivial_impl!([T: ?Sized] &'static T);
gc_generic_trivial_impl!([T: ?Sized] ::std::marker::PhantomData<T>);
gc_generic_trivial_impl!([T: Clone + 'static] ::GCLeaf<T>);
gc_generic_trivial_impl!([T: Clone + 'static] Box<T>);
gc_generic_trivial_impl!([T: Clone + 'static] ::std::rc::Rc<T>);
// Transitive implementations ("this particular kind of struct/enum is IntoHeap
// if all its fields are") are slightly less trivial.
unsafe impl<'h, T: IntoHeap<'h>> IntoHeap<'h> for Option<T> {
type In = Option<T::In>;
fn into_heap(self) -> Option<T::In> {
self.map(|t| t.into_heap())
}
unsafe fn trace<R>(storage: &Option<T::In>, tracer: &mut R)
where
R: Tracer,
{
match storage {
&None => (),
&Some(ref u) => T::trace(u, tracer),
}
}
unsafe fn from_heap(storage: &Option<T::In>) -> Option<T> {
match storage {
&None => None,
&Some(ref u) => Some(T::from_heap(u)),
}
}
}
macro_rules! gc_trivial_tuple_impl {
(@as_item $it:item) => { $it };
($($t:ident),*) => {
gc_trivial_tuple_impl! {
@as_item
unsafe impl<'h, $($t: IntoHeap<'h>,)*> IntoHeap<'h> for ($($t,)*) {
type In = ($($t::In,)*);
#[allow(non_snake_case)] // because we use the type names as variable names (!)
fn into_heap(self) -> Self::In {
let ($($t,)*) = self;
($($t.into_heap(),)*)
}
#[allow(non_snake_case)]
unsafe fn trace<R>(storage: &Self::In, tracer: &mut R)
where R: Tracer
{
let &($(ref $t,)*) = storage;
$(
<$t as $crate::traits::IntoHeap>::trace($t, tracer);
)*
// If the above `$(...)*` expansion is empty, we need this
// to quiet unused variable warnings for `tracer`.
let _ = tracer;
}
#[allow(non_snake_case)]
unsafe fn from_heap(storage: &Self::In) -> Self {
let &($(ref $t,)*) = storage;
($( <$t as $crate::traits::IntoHeap>::from_heap($t), )*)
}
}
}
}
}
gc_trivial_tuple_impl!();
gc_trivial_tuple_impl!(T);
gc_trivial_tuple_impl!(T, U);
gc_trivial_tuple_impl!(T, U, V);
gc_trivial_tuple_impl!(T, U, V, W);
gc_trivial_tuple_impl!(T, U, V, W, X);
gc_trivial_tuple_impl!(T, U, V, W, X, Y);
gc_trivial_tuple_impl!(T, U, V, W, X, Y, Z);
|
use {Poll, Async, Future};
use sink::Sink;
/// Future for the `Sink::flush` combinator, which polls the sink until all data
/// has been flushed.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct Flush<S> {
sink: Option<S>,
}
pub fn new<S: Sink>(sink: S) -> Flush<S> {
Flush { sink: Some(sink) }
}
impl<S: Sink> Flush<S> {
/// Get a shared reference to the inner sink.
pub fn get_ref(&self) -> &S {
self.sink.as_ref().expect("Attempted `Flush::get_ref` after the flush completed")
}
/// Get a mutable reference to the inner sink.
pub fn get_mut(&mut self) -> &mut S {
self.sink.as_mut().expect("Attempted `Flush::get_mut` after the flush completed")
}
/// Consume the `Flush` and return the inner sink.
pub fn into_inner(self) -> S {
self.sink.expect("Attempted `Flush::into_inner` after the flush completed")
}
}
impl<S: Sink> Future for Flush<S> {
type Item = S;
type Error = S::SinkError;
fn poll(&mut self) -> Poll<S, S::SinkError> {
let mut sink = self.sink.take().expect("Attempted to poll Flush after it completed");
if sink.poll_complete()?.is_ready() {
Ok(Async::Ready(sink))
} else {
self.sink = Some(sink);
Ok(Async::NotReady)
}
}
}
|
use super::types::*;
lazy_static! {
pub static ref ENVIRONMENT: Environment = environment![
"gbp" to "£" is 1,
"usd" to "$" is 1,
"eur" to "€" is 1,
"gbp" to "eur" is 1.06,
"gbp" to "ron" is 5.07,
"gbp" to "usd" is 1.20,
"km" to "m" is 1000,
"m" to "dm" is 10,
"dm" to "cm" is 10,
"cm" to "mm" is 10,
"kg" to "g" is 1000,
"g" to "mg" is 1000,
"minute" to "second" is 60,
"hour" to "minute" is 60,
"day" to "hour" is 24,
"week" to "day" is 7,
"month" to "day" is 30.5,
"year" to "month" is 12,
"minute" to "minutes" is 1,
"hour" to "hours" is 1,
"day" to "days" is 1,
"week" to "weeks" is 1,
"month" to "months" is 1,
"year" to "years" is 1,
"sec" to "second" is 1,
"min" to "minute" is 1,
"s" to "second" is 1,
// m is for meters, not minutes!
"h" to "hour" is 1,
"d" to "day" is 1,
"w" to "week" is 1,
"y" to "year" is 1,
"ron" to "RON" is 1,
"gbp" to "GBP" is 1,
"usd" to "USD" is 1,
"eur" to "EUR" is 1
];
}
|
//!
//! Create `impl` blocks for functions, traits, and other objects.
//!
use serde::Serialize;
use crate::internal::Generics;
use crate::traits::SrcCode;
use crate::{internal, AssociatedTypeDefinition, Function, Generic, SrcCodeVec, Trait};
use tera::{Context, Tera};
/// Represents an `impl` block
///
/// Example
/// -------
/// ```
/// use proffer::*;
///
/// let ipl = Impl::new("FooBar")
/// .add_generic(
/// Generic::new("T").add_trait_bound("ToString").to_owned()
/// )
/// .set_impl_trait(
/// Some(Trait::new("From<T>"))
/// )
/// .add_function(
/// Function::new("from")
/// .add_parameter(Parameter::new("s", "T"))
/// .set_return_ty("Self")
/// .set_body("Self { foo: s.to_string() }")
/// .to_owned()
/// );
/// ```
#[derive(Serialize, Default, Clone)]
pub struct Impl {
generics: Vec<Generic>,
impl_trait: Option<Trait>,
functions: Vec<Function>,
obj_name: String,
associated_types: Vec<AssociatedTypeDefinition>,
}
impl Impl {
/// Create a new impl block
pub fn new(obj_name: impl ToString) -> Self {
Self {
obj_name: obj_name.to_string(),
..Self::default()
}
}
/// Set if this `impl` is implementing a `Trait` for an object.
pub fn set_impl_trait(&mut self, impl_trait: Option<Trait>) -> &mut Self {
self.impl_trait = impl_trait;
self
}
/// Add a function to this `Impl` block
pub fn add_function(&mut self, func: Function) -> &mut Self {
self.functions.push(func);
self
}
/// Add a associated type to this `Impl` block
pub fn add_associated_type(&mut self, associated_type: AssociatedTypeDefinition) -> &mut Self {
self.associated_types.push(associated_type);
self
}
}
impl internal::Generics for Impl {
fn generics_mut(&mut self) -> &mut Vec<Generic> {
&mut self.generics
}
fn generics(&self) -> &[Generic] {
self.generics.as_slice()
}
}
impl SrcCode for Impl {
fn generate(&self) -> String {
let template = r#"
impl{% if has_generics %}<{{ generic_keys | join(sep=", ") }}>{% endif %} {% if has_trait %}{{ trait_name }} for {% endif %}{{ self.obj_name }}{% if has_generics %}<{{ generic_keys | join(sep=", ") }}>{% endif %}
{% if has_generics %}
where
{% for generic in generics %}{{ generic.name }}: {{ generic.traits | join(sep=" + ") }},
{% endfor %}
{% endif %}
{
{% for associated_type in associated_types %}{{ associated_type }}{% endfor %}
{% for function in functions %}
{{ function }}
{% endfor %}
}
"#;
let mut context = Context::new();
context.insert("self", &self);
context.insert("has_trait", &self.impl_trait.is_some());
context.insert(
"trait_name",
&self.impl_trait.as_ref().map_or_else(|| "", |t| t.name()),
);
context.insert("has_generics", &!self.generics().is_empty());
context.insert("generics", &self.generics());
context.insert(
"generic_keys",
&self
.generics()
.iter()
.map(|g| g.name())
.collect::<Vec<&str>>(),
);
context.insert("functions", &self.functions.to_src_vec());
context.insert("associated_types", &self.associated_types.to_src_vec());
Tera::one_off(template, &context, false).unwrap()
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_base::base::GlobalInstance;
use common_exception::Result;
use crate::InnerConfig;
pub struct GlobalConfig;
impl GlobalConfig {
pub fn init(config: InnerConfig) -> Result<()> {
GlobalInstance::set(Arc::new(config));
Ok(())
}
pub fn instance() -> Arc<InnerConfig> {
GlobalInstance::get()
}
}
|
#![no_main]
#[macro_use]
extern crate libfuzzer_sys;
extern crate insta;
use std::io::{self, Write};
use insta::Error;
fuzz_target!(|data: &[u8]| {
match insta::fuzz(data) {
Ok(result) => panic!(format!("bzzt: {}", result)),
Err(Error::Jpeg(_err)) => print!("J"),
Err(Error::FormatMismatch) => print!("F"),
Err(Error::MetricMismatch) => print!("M"),
};
let _ = io::stdout().flush();
});
|
#[macro_use]
extern crate rosrust;
mod msg {
rosmsg_include!(sensor_msgs/Image,sensor_msgs/Imu,geometry_msgs/TransformStamped);
}
pub fn instantiate_imu_msg() {
let mut le_msg = msg::sensor_msgs::Imu::default();
le_msg.linear_acceleration_covariance[0] = 0.0f64;
println!("orientated ");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn instantiate_expected_msgs() {
instantiate_imu_msg();
assert!(true);
}
}
|
use {
std::{
cell::RefCell,
collections::HashMap,
fmt,
rc::{Rc, Weak},
},
tracing::{debug, info},
};
struct Directory {
parent: Option<Weak<RefCell<Directory>>>,
name: String,
directory_children: HashMap<String, Rc<RefCell<Directory>>>,
file_children: HashMap<String, File>,
}
impl fmt::Debug for Directory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let parent_name = match self.parent.as_ref() {
None => "<none>".to_string(),
Some(p) => p.upgrade().unwrap().as_ref().borrow().name.clone(),
};
let directory_children = self.directory_children.keys().cloned();
let file_children = self.file_children.keys().cloned();
f.debug_struct("Directory")
.field("parent", &parent_name)
.field("name", &self.name)
.field("directory_children", &directory_children)
.field("file_children", &file_children)
.finish()
}
}
impl Directory {
fn new(parent: Option<Rc<RefCell<Directory>>>, name: &str) -> Rc<RefCell<Directory>> {
let child = Rc::new(RefCell::new(Directory {
parent: parent.map(|d| Rc::downgrade(&d)),
name: String::from(name),
directory_children: HashMap::new(),
file_children: HashMap::new(),
}));
if let Some(parent) = &child.as_ref().borrow().parent {
parent
.upgrade()
.unwrap()
.borrow_mut()
.directory_children
.insert(child.as_ref().borrow().name.clone(), Rc::clone(&child));
}
child
}
fn abs_path(dir: &Rc<RefCell<Directory>>) -> String {
let dir_name = dir.as_ref().borrow().name.clone();
match &dir.as_ref().borrow().parent {
None => dir_name,
Some(parent) => format!(
"{}/{}",
Directory::abs_path(&parent.upgrade().unwrap()),
dir_name
),
}
}
fn add_child_file(parent: Rc<RefCell<Self>>, mut child: File) {
child.parent.replace(Rc::downgrade(&parent));
parent
.as_ref()
.borrow_mut()
.file_children
.insert(child.name.clone(), child);
}
fn size(parent: &Rc<RefCell<Directory>>) -> usize {
let mut total = 0;
for (_, f) in parent.as_ref().borrow().file_children.iter() {
total += f.size;
}
for (_, d) in parent.as_ref().borrow().directory_children.iter() {
total += Directory::size(d);
}
total
}
fn part1_size_tracking(
parent: &Rc<RefCell<Directory>>,
dois: &mut HashMap<String, Rc<RefCell<Directory>>>,
) -> usize {
let mut total = 0;
for (_, f) in parent.as_ref().borrow().file_children.iter() {
total += f.size;
}
for (_, d) in parent.as_ref().borrow().directory_children.iter() {
total += Directory::part1_size_tracking(d, dois);
}
if total <= 100000 {
dois.insert(Directory::abs_path(parent), parent.clone());
}
total
}
fn all_directories_and_sizes(
dir: &Rc<RefCell<Directory>>,
mut acc: HashMap<String, usize>,
) -> HashMap<String, usize> {
acc.insert(Directory::abs_path(dir), Directory::size(dir));
for (_, d) in dir.as_ref().borrow().directory_children.iter() {
acc = Directory::all_directories_and_sizes(d, acc);
}
acc
}
}
#[derive(Debug, Clone)]
struct File {
parent: Option<Weak<RefCell<Directory>>>,
name: String,
size: usize,
}
fn build_fs(input: String) -> Rc<RefCell<Directory>> {
let cd_root_regex = regex::Regex::new(r"\$ cd /").unwrap();
let cd_parent_regex = regex::Regex::new(r"\$ cd \.\.").unwrap();
let cd_regex = regex::Regex::new(r"\$ cd (.*)").unwrap();
let dir_regex = regex::Regex::new(r"dir (.*)").unwrap();
let file_regex = regex::Regex::new(r"(\d+) (.*)").unwrap();
let ls_regex = regex::Regex::new(r"\$ ls").unwrap();
let root_directory = Directory::new(None, "");
let mut current_directory = root_directory.clone();
for line in input.trim().split('\n') {
if cd_root_regex.is_match(line) {
current_directory = root_directory.clone();
continue;
}
if ls_regex.is_match(line) {
continue;
}
if cd_parent_regex.is_match(line) {
let next_directory = current_directory
.as_ref()
.borrow()
.parent
.as_ref()
.unwrap()
.clone();
current_directory = next_directory.upgrade().unwrap();
continue;
}
if let Some(cd_cap) = cd_regex.captures(line) {
//debug!("cd_cap: {:?}", cd_cap);
let next_directory = current_directory
.as_ref()
.borrow()
.directory_children
.get(cd_cap.get(1).unwrap().as_str())
.unwrap()
.clone();
current_directory = next_directory;
continue;
}
if let Some(dir_cap) = dir_regex.captures(line) {
Directory::new(
Some(current_directory.clone()),
dir_cap.get(1).unwrap().as_str(),
);
continue;
}
if let Some(file_cap) = file_regex.captures(line) {
Directory::add_child_file(
current_directory.clone(),
File {
parent: None,
name: file_cap.get(2).unwrap().as_str().to_string(),
size: file_cap.get(1).unwrap().as_str().parse::<usize>().unwrap(),
},
);
continue;
}
unreachable!()
}
debug!("Root directory: {:?}", root_directory.as_ref().borrow());
debug!("Root directory size: {}", Directory::size(&root_directory));
root_directory
}
pub fn part1(input: &str) {
let root_directory = build_fs(input.to_string());
let mut dois = HashMap::new();
Directory::part1_size_tracking(&root_directory, &mut dois);
//debug!("DOIs: {:?}", dois);
debug!("DOIs len: {}", dois.len());
let doi_sizes = dois
.iter()
.map(|(abs_path, d)| format!("{}-{}", abs_path, Directory::size(d)))
.collect::<Vec<_>>();
debug!("DOI sizes: {:?}", doi_sizes);
info!(
"Part 1 Answer: {}",
dois.iter().fold(0, |acc, (_, d)| acc + Directory::size(d))
);
}
pub fn part2(input: &str) {
let total_disk_space = 70000000;
let needed_unused_space = 30000000;
let root_directory = build_fs(input.to_string());
let required_to_free =
needed_unused_space - (total_disk_space - Directory::size(&root_directory));
let all_directories = Directory::all_directories_and_sizes(&root_directory, HashMap::new());
debug!("{:?}", all_directories);
info!(
"Part 2 Answer: {}",
all_directories
.values()
.filter(|s| **s >= required_to_free)
.map(|s| s - required_to_free)
.min()
.unwrap()
+ required_to_free
);
}
#[cfg(test)]
mod tests {
use {super::*, tracing_test::traced_test};
#[test]
#[traced_test]
fn simple_directory_construction() {
let root = Directory::new(None, "root");
debug!("{:?}", root.as_ref().borrow());
}
#[test]
#[traced_test]
fn single_file_fs() {
let f = File {
parent: None,
name: "a".to_string(),
size: 0,
};
let root = Directory::new(None, "root");
Directory::add_child_file(root.clone(), f);
assert_eq!(1, root.as_ref().borrow().file_children.len());
debug!("{:?}", root.as_ref().borrow());
}
#[test]
#[traced_test]
fn nested_file_fs() {
let f = File {
parent: None,
name: "a".to_string(),
size: 0,
};
let root = Directory::new(None, "root");
let sub_root = Directory::new(Some(root.clone()), "sub_root");
assert_eq!(0, root.as_ref().borrow().file_children.len());
assert_eq!(1, root.as_ref().borrow().directory_children.len());
Directory::add_child_file(sub_root.clone(), f);
assert_eq!(1, sub_root.as_ref().borrow().file_children.len());
assert_eq!(0, sub_root.as_ref().borrow().directory_children.len());
debug!("root: {:?}", root.as_ref().borrow());
debug!("sub_root: {:?}", sub_root.as_ref().borrow());
}
#[test]
#[traced_test]
fn duplicate_named_file_dropped() {
let f = File {
parent: None,
name: "a".to_string(),
size: 0,
};
let root = Directory::new(None, "root");
Directory::add_child_file(root.clone(), f.clone());
assert_eq!(1, root.as_ref().borrow().file_children.len());
Directory::add_child_file(root.clone(), f);
assert_eq!(1, root.as_ref().borrow().file_children.len());
debug!("root: {:?}", root.as_ref().borrow());
}
#[test]
#[traced_test]
fn simple_size() {
let f = File {
parent: None,
name: "a".to_string(),
size: 1000,
};
let root = Directory::new(None, "root");
Directory::add_child_file(root.clone(), f);
assert_eq!(1000, Directory::size(&root));
}
#[test]
#[traced_test]
fn multiple_files_size() {
let a = File {
parent: None,
name: "a".to_string(),
size: 1000,
};
let b = File {
parent: None,
name: "b".to_string(),
size: 754,
};
let root = Directory::new(None, "root");
Directory::add_child_file(root.clone(), a);
Directory::add_child_file(root.clone(), b);
assert_eq!(1754, Directory::size(&root));
}
#[test]
#[traced_test]
fn nested_file_fs_size() {
let a = File {
parent: None,
name: "a".to_string(),
size: 101,
};
let root = Directory::new(None, "root");
let sub_root = Directory::new(Some(root.clone()), "sub_root");
Directory::add_child_file(sub_root.clone(), a);
assert_eq!(101, Directory::size(&root));
assert_eq!(101, Directory::size(&sub_root));
}
}
|
//https://leetcode.com/problems/replace-all-digits-with-characters/
impl Solution {
pub fn replace_digits(s: String) -> String {
let mut replaced_string = String::from("");
let mut prev = '0';
for (mut i, mut c) in s.chars().enumerate() {
if i%2 == 1 {
c = (prev as u8 + (c as u8 - '0' as u8)) as char;
replaced_string.push(c);
} else {
replaced_string.push(c);
prev = c;
}
}
replaced_string
}
} |
use std::collections::HashMap;
use std::ffi::CString;
use std::hash::Hash;
use bytes::Buf;
use enumflags2::BitFlags;
use enumflags2::RawBitFlags;
use num_traits::FromPrimitive;
use crate::Address;
pub(crate) trait BufExt2: Buf {
fn get_address(&mut self) -> Address {
let mut arr = [0u8; 6];
self.copy_to_slice(&mut arr[..]);
Address::from(arr)
}
fn get_u8x16(&mut self) -> [u8; 16] {
let mut arr = [0u8; 16];
self.copy_to_slice(&mut arr[..]);
arr
}
fn get_vec_u8(&mut self, len: usize) -> Vec<u8> {
let mut ret = vec![0; len];
self.copy_to_slice(ret.as_mut_slice());
ret
}
fn get_bool(&mut self) -> bool {
self.get_u8() != 0
}
fn get_primitive_u8<T: FromPrimitive>(&mut self) -> T {
FromPrimitive::from_u8(self.get_u8()).unwrap()
}
fn get_primitive_u16_le<T: FromPrimitive>(&mut self) -> T {
FromPrimitive::from_u16(self.get_u16_le()).unwrap()
}
fn get_flags_u8<T: RawBitFlags<Type = u8>>(&mut self) -> BitFlags<T> {
BitFlags::from_bits_truncate(self.get_u8())
}
fn get_flags_u16_le<T: RawBitFlags<Type = u16>>(&mut self) -> BitFlags<T> {
BitFlags::from_bits_truncate(self.get_u16_le())
}
fn get_flags_u32_le<T: RawBitFlags<Type = u32>>(&mut self) -> BitFlags<T> {
BitFlags::from_bits_truncate(self.get_u32_le())
}
fn get_c_string(&mut self) -> CString {
let mut bytes = vec![];
let mut current = self.get_u8();
while current != 0 && self.has_remaining() {
bytes.push(current);
current = self.get_u8();
}
return unsafe { CString::from_vec_unchecked(bytes) };
}
/// Parses a list of Type/Length/Value entries into a map keyed by type
///
/// This parses a list of mgmt_tlv entries (as defined in mgmt.h) and converts them
/// into a map of Type => Vec<u8>.
///
/// # Bytes layout
///
/// The layout as described in the mgmt-api documentation is:
/// ```plain
/// Parameter1 {
/// Parameter_Type (2 Octet)
/// Value_Length (1 Octet)
/// Value (0-255 Octets)
/// }
/// Parameter2 { }
/// ...
/// ```
///
fn get_tlv_map<T : FromPrimitive + Eq + Hash>(&mut self) -> HashMap<T, Vec<u8>> {
let mut parameters = HashMap::new();
while self.has_remaining() {
let parameter_type: T = self.get_primitive_u16_le();
let value_size = self.get_u8() as usize;
parameters.insert(parameter_type, self.get_vec_u8(value_size));
}
parameters
}
}
impl<T: Buf> BufExt2 for T {}
|
use crate::pubkey::Pubkey;
const BPF_LOADER_PROGRAM_ID: [u8; 32] = [
2, 168, 246, 145, 78, 136, 161, 107, 189, 35, 149, 133, 95, 100, 4, 217, 180, 244, 86, 183,
130, 27, 176, 20, 87, 73, 66, 140, 0, 0, 0, 0,
];
pub fn id() -> Pubkey {
Pubkey::new(&BPF_LOADER_PROGRAM_ID)
}
|
//! As of Rust 1.30, the language supports user-defined function-like procedural
//! macros. However these can only be invoked in item position, not in
//! statements or expressions.
//!
//! This crate implements an alternative type of procedural macro that can be
//! invoked in statement or expression position.
//!
//! # Defining procedural macros
//!
//! Two crates are required to define a procedural macro.
//!
//! ## The implementation crate
//!
//! This crate must contain nothing but procedural macros. Private helper
//! functions and private modules are fine but nothing can be public.
//!
//! [> example of an implementation crate][demo-hack-impl]
//!
//! Just like you would use a #\[proc_macro\] attribute to define a natively
//! supported procedural macro, use proc-macro-hack's #\[proc_macro_hack\]
//! attribute to define a procedural macro that works in expression position.
//! The function signature is the same as for ordinary function-like procedural
//! macros.
//!
//! ```
//! extern crate proc_macro;
//!
//! use proc_macro::TokenStream;
//! use proc_macro_hack::proc_macro_hack;
//! use quote::quote;
//! use syn::{parse_macro_input, Expr};
//!
//! # const IGNORE: &str = stringify! {
//! #[proc_macro_hack]
//! # };
//! pub fn add_one(input: TokenStream) -> TokenStream {
//! let expr = parse_macro_input!(input as Expr);
//! TokenStream::from(quote! {
//! 1 + (#expr)
//! })
//! }
//! #
//! # fn main() {}
//! ```
//!
//! ## The declaration crate
//!
//! This crate is allowed to contain other public things if you need, for
//! example traits or functions or ordinary macros.
//!
//! [> example of a declaration crate][demo-hack]
//!
//! Within the declaration crate there needs to be a re-export of your
//! procedural macro from the implementation crate. The re-export also carries a
//! \#\[proc_macro_hack\] attribute.
//!
//! ```
//! use proc_macro_hack::proc_macro_hack;
//!
//! /// Add one to an expression.
//! ///
//! /// (Documentation goes here on the re-export, not in the other crate.)
//! #[proc_macro_hack]
//! pub use demo_hack_impl::add_one;
//! #
//! # fn main() {}
//! ```
//!
//! Both crates depend on `proc-macro-hack`:
//!
//! ```toml
//! [dependencies]
//! proc-macro-hack = "0.5"
//! ```
//!
//! Additionally, your implementation crate (but not your declaration crate) is
//! a proc macro crate:
//!
//! ```toml
//! [lib]
//! proc-macro = true
//! ```
//!
//! # Using procedural macros
//!
//! Users of your crate depend on your declaration crate (not your
//! implementation crate), then use your procedural macros as usual.
//!
//! [> example of a downstream crate][example]
//!
//! ```
//! use demo_hack::add_one;
//!
//! fn main() {
//! let two = 2;
//! let nine = add_one!(two) + add_one!(2 + 3);
//! println!("nine = {}", nine);
//! }
//! ```
//!
//! [demo-hack-impl]: https://github.com/dtolnay/proc-macro-hack/tree/master/demo-hack-impl
//! [demo-hack]: https://github.com/dtolnay/proc-macro-hack/tree/master/demo-hack
//! [example]: https://github.com/dtolnay/proc-macro-hack/tree/master/example
//!
//! # Limitations
//!
//! - Only proc macros in expression position are supported. Proc macros in type
//! position ([#10]) or pattern position ([#20]) are not supported.
//!
//! - By default, nested invocations are not supported i.e. the code emitted by
//! a proc-macro-hack macro invocation cannot contain recursive calls to the
//! same proc-macro-hack macro nor calls to any other proc-macro-hack macros.
//! Use [`proc-macro-nested`] if you require support for nested invocations.
//!
//! - By default, hygiene is structured such that the expanded code can't refer
//! to local variables other than those passed by name somewhere in the macro
//! input. If your macro must refer to *local* variables that don't get named
//! in the macro input, use `#[proc_macro_hack(fake_call_site)]` on the
//! re-export in your declaration crate. *Most macros won't need this.*
//!
//! [#10]: https://github.com/dtolnay/proc-macro-hack/issues/10
//! [#20]: https://github.com/dtolnay/proc-macro-hack/issues/20
//! [`proc-macro-nested`]: https://docs.rs/proc-macro-nested
#![recursion_limit = "512"]
#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
extern crate proc_macro;
use proc_macro2::{Span, TokenStream, TokenTree};
use quote::{format_ident, quote, ToTokens};
use std::fmt::Write;
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream, Result};
use syn::{braced, bracketed, parenthesized, parse_macro_input, token, Ident, LitInt, Token};
type Visibility = Option<Token![pub]>;
enum Input {
Export(Export),
Define(Define),
}
// pub use demo_hack_impl::{m1, m2 as qrst};
struct Export {
attrs: TokenStream,
vis: Visibility,
from: Ident,
macros: Vec<Macro>,
}
// pub fn m1(input: TokenStream) -> TokenStream { ... }
struct Define {
attrs: TokenStream,
name: Ident,
body: TokenStream,
}
struct Macro {
name: Ident,
export_as: Ident,
}
impl Parse for Input {
fn parse(input: ParseStream) -> Result<Self> {
let ahead = input.fork();
parse_attributes(&ahead)?;
ahead.parse::<Visibility>()?;
if ahead.peek(Token![use]) {
input.parse().map(Input::Export)
} else if ahead.peek(Token![fn]) {
input.parse().map(Input::Define)
} else {
Err(input.error("unexpected input to #[proc_macro_hack]"))
}
}
}
impl Parse for Export {
fn parse(input: ParseStream) -> Result<Self> {
let attrs = input.call(parse_attributes)?;
let vis: Visibility = input.parse()?;
input.parse::<Token![use]>()?;
input.parse::<Option<Token![::]>>()?;
let from: Ident = input.parse()?;
input.parse::<Token![::]>()?;
let mut macros = Vec::new();
if input.peek(token::Brace) {
let content;
braced!(content in input);
loop {
macros.push(content.parse()?);
if content.is_empty() {
break;
}
content.parse::<Token![,]>()?;
if content.is_empty() {
break;
}
}
} else {
macros.push(input.parse()?);
}
input.parse::<Token![;]>()?;
Ok(Export {
attrs,
vis,
from,
macros,
})
}
}
impl Parse for Define {
fn parse(input: ParseStream) -> Result<Self> {
let attrs = input.call(parse_attributes)?;
let vis: Visibility = input.parse()?;
if vis.is_none() {
return Err(input.error("functions tagged with `#[proc_macro_hack]` must be `pub`"));
}
input.parse::<Token![fn]>()?;
let name: Ident = input.parse()?;
let body: TokenStream = input.parse()?;
Ok(Define { attrs, name, body })
}
}
impl Parse for Macro {
fn parse(input: ParseStream) -> Result<Self> {
let name: Ident = input.parse()?;
let renamed: Option<Token![as]> = input.parse()?;
let export_as = if renamed.is_some() {
input.parse()?
} else {
name.clone()
};
Ok(Macro { name, export_as })
}
}
fn parse_attributes(input: ParseStream) -> Result<TokenStream> {
let mut attrs = TokenStream::new();
while input.peek(Token![#]) {
let pound: Token![#] = input.parse()?;
pound.to_tokens(&mut attrs);
let content;
let bracket_token = bracketed!(content in input);
let content: TokenStream = content.parse()?;
bracket_token.surround(&mut attrs, |tokens| content.to_tokens(tokens));
}
Ok(attrs)
}
#[proc_macro_attribute]
pub fn proc_macro_hack(
args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
proc_macro::TokenStream::from(match parse_macro_input!(input) {
Input::Export(export) => {
let args = parse_macro_input!(args as ExportArgs);
expand_export(export, args)
}
Input::Define(define) => {
parse_macro_input!(args as DefineArgs);
expand_define(define)
}
})
}
mod kw {
syn::custom_keyword!(derive);
syn::custom_keyword!(fake_call_site);
syn::custom_keyword!(internal_macro_calls);
syn::custom_keyword!(support_nested);
}
struct ExportArgs {
support_nested: bool,
internal_macro_calls: u16,
fake_call_site: bool,
}
impl Parse for ExportArgs {
fn parse(input: ParseStream) -> Result<Self> {
let mut args = ExportArgs {
support_nested: false,
internal_macro_calls: 0,
fake_call_site: false,
};
while !input.is_empty() {
let ahead = input.lookahead1();
if ahead.peek(kw::support_nested) {
input.parse::<kw::support_nested>()?;
args.support_nested = true;
} else if ahead.peek(kw::internal_macro_calls) {
input.parse::<kw::internal_macro_calls>()?;
input.parse::<Token![=]>()?;
let calls = input.parse::<LitInt>()?.base10_parse()?;
args.internal_macro_calls = calls;
} else if ahead.peek(kw::fake_call_site) {
input.parse::<kw::fake_call_site>()?;
args.fake_call_site = true;
} else {
return Err(ahead.error());
}
if input.is_empty() {
break;
}
input.parse::<Token![,]>()?;
}
Ok(args)
}
}
struct DefineArgs;
impl Parse for DefineArgs {
fn parse(_input: ParseStream) -> Result<Self> {
Ok(DefineArgs)
}
}
struct EnumHack {
token_stream: TokenStream,
}
impl Parse for EnumHack {
fn parse(input: ParseStream) -> Result<Self> {
input.parse::<Token![enum]>()?;
input.parse::<Ident>()?;
let braces;
braced!(braces in input);
braces.parse::<Ident>()?;
braces.parse::<Token![=]>()?;
let parens;
parenthesized!(parens in braces);
parens.parse::<Ident>()?;
parens.parse::<Token![!]>()?;
let inner;
braced!(inner in parens);
let token_stream: TokenStream = inner.parse()?;
parens.parse::<Token![,]>()?;
parens.parse::<TokenTree>()?;
braces.parse::<Token![.]>()?;
braces.parse::<TokenTree>()?;
braces.parse::<Token![,]>()?;
Ok(EnumHack { token_stream })
}
}
#[doc(hidden)]
#[proc_macro_derive(ProcMacroHack)]
pub fn enum_hack(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let inner = parse_macro_input!(input as EnumHack);
proc_macro::TokenStream::from(inner.token_stream)
}
struct FakeCallSite {
derive: Ident,
rest: TokenStream,
}
impl Parse for FakeCallSite {
fn parse(input: ParseStream) -> Result<Self> {
input.parse::<Token![#]>()?;
let attr;
bracketed!(attr in input);
attr.parse::<kw::derive>()?;
let path;
parenthesized!(path in attr);
Ok(FakeCallSite {
derive: path.parse()?,
rest: input.parse()?,
})
}
}
#[doc(hidden)]
#[proc_macro_attribute]
pub fn fake_call_site(
args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let args = TokenStream::from(args);
let span = match args.into_iter().next() {
Some(token) => token.span(),
None => return input,
};
let input = parse_macro_input!(input as FakeCallSite);
let mut derive = input.derive;
derive.set_span(span);
let rest = input.rest;
let expanded = quote! {
#[derive(#derive)]
#rest
};
proc_macro::TokenStream::from(expanded)
}
fn expand_export(export: Export, args: ExportArgs) -> TokenStream {
let dummy = dummy_name_for_export(&export);
let attrs = export.attrs;
let vis = export.vis;
let macro_export = match vis {
Some(_) => quote!(#[macro_export]),
None => quote!(),
};
let crate_prefix = vis.map(|_| quote!($crate::));
let enum_variant = if args.support_nested {
if args.internal_macro_calls == 0 {
quote!(Nested)
} else {
format_ident!("Nested{}", args.internal_macro_calls).to_token_stream()
}
} else {
quote!(Value)
};
let from = export.from;
let rules = export
.macros
.into_iter()
.map(|Macro { name, export_as }| {
let actual_name = actual_proc_macro_name(&name);
let dispatch = dispatch_macro_name(&name);
let call_site = call_site_macro_name(&name);
let export_dispatch = if args.support_nested {
quote! {
#[doc(hidden)]
#vis use proc_macro_nested::dispatch as #dispatch;
}
} else {
quote!()
};
let proc_macro_call = if args.support_nested {
let extra_bangs = (0..args.internal_macro_calls).map(|_| quote!(!));
quote! {
#crate_prefix #dispatch! { ($($proc_macro)*) #(#extra_bangs)* }
}
} else {
quote! {
proc_macro_call!()
}
};
let export_call_site = if args.fake_call_site {
quote! {
#[doc(hidden)]
#vis use proc_macro_hack::fake_call_site as #call_site;
}
} else {
quote!()
};
let do_derive = if !args.fake_call_site {
quote! {
#[derive(#crate_prefix #actual_name)]
}
} else if crate_prefix.is_some() {
quote! {
use #crate_prefix #actual_name;
#[#crate_prefix #call_site ($($proc_macro)*)]
#[derive(#actual_name)]
}
} else {
quote! {
#[#call_site ($($proc_macro)*)]
#[derive(#actual_name)]
}
};
quote! {
#[doc(hidden)]
#vis use #from::#actual_name;
#export_dispatch
#export_call_site
#attrs
#macro_export
macro_rules! #export_as {
($($proc_macro:tt)*) => {{
#do_derive
enum ProcMacroHack {
#enum_variant = (stringify! { $($proc_macro)* }, 0).1,
}
#proc_macro_call
}};
}
}
})
.collect();
wrap_in_enum_hack(dummy, rules)
}
fn expand_define(define: Define) -> TokenStream {
let attrs = define.attrs;
let name = define.name;
let dummy = actual_proc_macro_name(&name);
let body = define.body;
quote! {
mod #dummy {
extern crate proc_macro;
pub use self::proc_macro::*;
}
#attrs
#[proc_macro_derive(#dummy)]
pub fn #dummy(input: #dummy::TokenStream) -> #dummy::TokenStream {
use std::iter::FromIterator;
let mut iter = input.into_iter();
iter.next().unwrap(); // `enum`
iter.next().unwrap(); // `ProcMacroHack`
let mut braces = match iter.next().unwrap() {
#dummy::TokenTree::Group(group) => group.stream().into_iter(),
_ => unimplemented!(),
};
let variant = braces.next().unwrap(); // `Value` or `Nested`
let varname = variant.to_string();
let support_nested = varname.starts_with("Nested");
braces.next().unwrap(); // `=`
let mut parens = match braces.next().unwrap() {
#dummy::TokenTree::Group(group) => group.stream().into_iter(),
_ => unimplemented!(),
};
parens.next().unwrap(); // `stringify`
parens.next().unwrap(); // `!`
let inner = match parens.next().unwrap() {
#dummy::TokenTree::Group(group) => group.stream(),
_ => unimplemented!(),
};
let output: #dummy::TokenStream = #name(inner.clone());
fn count_bangs(input: #dummy::TokenStream) -> usize {
let mut count = 0;
for token in input {
match token {
#dummy::TokenTree::Punct(punct) => {
if punct.as_char() == '!' {
count += 1;
}
}
#dummy::TokenTree::Group(group) => {
count += count_bangs(group.stream());
}
_ => {}
}
}
count
}
// macro_rules! proc_macro_call {
// () => { #output }
// }
#dummy::TokenStream::from_iter(vec![
#dummy::TokenTree::Ident(
#dummy::Ident::new("macro_rules", #dummy::Span::call_site()),
),
#dummy::TokenTree::Punct(
#dummy::Punct::new('!', #dummy::Spacing::Alone),
),
#dummy::TokenTree::Ident(
#dummy::Ident::new(
&if support_nested {
let extra_bangs = if varname == "Nested" {
0
} else {
varname["Nested".len()..].parse().unwrap()
};
format!("proc_macro_call_{}", extra_bangs + count_bangs(inner))
} else {
String::from("proc_macro_call")
},
#dummy::Span::call_site(),
),
),
#dummy::TokenTree::Group(
#dummy::Group::new(#dummy::Delimiter::Brace, #dummy::TokenStream::from_iter(vec![
#dummy::TokenTree::Group(
#dummy::Group::new(#dummy::Delimiter::Parenthesis, #dummy::TokenStream::new()),
),
#dummy::TokenTree::Punct(
#dummy::Punct::new('=', #dummy::Spacing::Joint),
),
#dummy::TokenTree::Punct(
#dummy::Punct::new('>', #dummy::Spacing::Alone),
),
#dummy::TokenTree::Group(
#dummy::Group::new(#dummy::Delimiter::Brace, output),
),
])),
),
])
}
fn #name #body
}
}
fn actual_proc_macro_name(conceptual: &Ident) -> Ident {
format_ident!("proc_macro_hack_{}", conceptual)
}
fn dispatch_macro_name(conceptual: &Ident) -> Ident {
format_ident!("proc_macro_call_{}", conceptual)
}
fn call_site_macro_name(conceptual: &Ident) -> Ident {
format_ident!("proc_macro_fake_call_site_{}", conceptual)
}
fn dummy_name_for_export(export: &Export) -> String {
let mut dummy = String::new();
let from = export.from.unraw().to_string();
write!(dummy, "_{}{}", from.len(), from).unwrap();
for m in &export.macros {
let name = m.name.unraw().to_string();
write!(dummy, "_{}{}", name.len(), name).unwrap();
}
dummy
}
fn wrap_in_enum_hack(dummy: String, inner: TokenStream) -> TokenStream {
let dummy = Ident::new(&dummy, Span::call_site());
quote! {
#[derive(proc_macro_hack::ProcMacroHack)]
enum #dummy {
Value = (stringify! { #inner }, 0).1,
}
}
}
|
macro_rules! field_get_ref {
($field: ident, $func: ident, $type: ty) => {
pub fn $func(&self) -> &$type {
&self.$field
}
};
}
macro_rules! field_get_ref_mut {
($field: ident, $func: ident, $type: ty) => {
pub fn $func(&mut self) -> &mut $type {
&mut self.$field
}
}
}
// macro_rules! field_get_opt_ref {
// ($field: ident, $func: ident, $type: ty) => {
// pub fn $func(&self) -> Option<&$type> {
// self.$field.as_ref()
// }
// };
// }
// macro_rules! field_update_opt_none {
// ($field: ident, $func: ident) => {
// pub fn $func(self) -> Self {
// let $field = None;
// Self {
// $field,
// .. self
// }
// }
// }
// }
// macro_rules! field_update_opt_some {
// ($field: ident, $func: ident, $type: ty) => {
// pub fn $func(self, $field: Option<$type>) -> Self {
// Self {
// $field,
// .. self
// }
// }
// }
// }
// macro_rules! field_get_copy {
// ($field: ident, $func: ident, $type: ty) => {
// pub fn $func(&self) -> $type {
// self.$field
// }
// };
// }
macro_rules! field_update {
($field: ident, $func: ident, $type: ty) => {
pub fn $func(self, $field: $type) -> Self {
Self {
$field,
.. self
}
}
};
}
// macro_rules! enum_variant_from {
// ($target: tt, $variant: ident, $source: ty) => {
// impl From<$source> for $target {
// fn from(inner: $source) -> Self {
// $target::$variant(inner)
// }
// }
// };
// }
|
use crate::prelude::*;
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkAndroidSurfaceCreateInfoKHR<'a> {
lt: PhantomData<&'a ()>,
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkAndroidSurfaceCreateFlagBitsKHR,
pub window: *mut c_void,
}
impl<'a> VkAndroidSurfaceCreateInfoKHR<'a> {
pub fn new<T, U>(flags: T, window: &mut U) -> Self
where
T: Into<VkAndroidSurfaceCreateFlagBitsKHR>,
{
VkAndroidSurfaceCreateInfoKHR {
lt: PhantomData,
sType: VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR,
pNext: ptr::null(),
flags: flags.into(),
window: window as *mut U as *mut c_void,
}
}
}
|
pub mod decoder;
pub mod encoder;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
|
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
fn main() {
input! {
_n: usize,
a: usize,
b: usize,
k: usize,
p: [usize; k],
}
let mut set = HashSet::new();
set.insert(a);
set.insert(b);
for &pi in &p {
set.insert(pi);
}
if set.len() == k + 2 {
println!("YES");
} else {
println!("NO");
}
}
|
use game_lib::{
bevy::{ecs as bevy_ecs, prelude::*},
derive_more::{Display, From, Into},
};
use game_tiles::{EntityWorldPosition, EntityWorldRect};
/// All the components needed for an entity to be registered with the physics
/// engine.
#[derive(Bundle, Default)]
pub struct PhysicsBundle {
pub bounds: EntityWorldRect,
pub body_type: BodyType,
pub mass: Mass,
pub forces: Forces,
pub acceleration: Acceleration,
pub velocity: Velocity,
pub jump_status: JumpStatus,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Reflect)]
#[reflect(Component)]
pub enum JumpStatus {
OnGround,
InAir { jumps: u32 },
}
impl Default for JumpStatus {
fn default() -> Self {
JumpStatus::OnGround
}
}
/// How the body should be treated by the physics engine.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Reflect)]
#[reflect(Component)]
pub enum BodyType {
/// Body is affected by forces, acceleration, etc. and collisions should be
/// calculated for this body.
Kinematic,
/// Body cannot move, however other kinematic bodies can still collide with
/// it.
Static,
}
impl Default for BodyType {
fn default() -> Self {
BodyType::Kinematic
}
}
/// Velocity in `m/s`. This is **not** reset once it has been applied by the
/// physics engine.
#[derive(Clone, Copy, PartialEq, Debug, Default, From, Into, Reflect)]
#[reflect(Component)]
pub struct Velocity(pub EntityWorldPosition);
/// Acceleration in `m/s^2`. This is reset to the null vector once it has been
/// applied by the physics engine.
// TODO: get rid of this
#[derive(Clone, Copy, PartialEq, Debug, Default, From, Into, Reflect)]
#[reflect(Component)]
pub struct Acceleration(pub EntityWorldPosition);
/// Force in `kg * m/s^2`. This is cleared once it has been applied by the
/// physics engine.
// TODO: get rid of this
#[derive(Clone, PartialEq, Debug, Default, From, Into, Reflect)]
#[reflect(Component)]
pub struct Forces(pub Vec<EntityWorldPosition>);
/// Mass in `kg`. A non-positive mass is invalid and may cause the
/// simulation to panic or behave strangely.
#[derive(Clone, Copy, PartialEq, Debug, Display, From, Into, Reflect)]
#[reflect(Component)]
pub struct Mass(pub f32);
impl Default for Mass {
fn default() -> Self {
Mass(62.0)
}
}
/// Gravitational acceleration in `m/s^2`. This overrides the global
/// gravitational acceleration, allowing individual bodies to have their own
/// gravity.
#[derive(Clone, Copy, PartialEq, Debug, From, Into, Reflect)]
#[reflect(Component)]
pub struct Gravity(pub EntityWorldPosition);
impl Default for Gravity {
fn default() -> Self {
Gravity(EntityWorldPosition::Y * -9.81)
}
}
/// Drag coefficient. Since neither the shape of the body nor the density of
/// the fluid it is in are taken into account, this coefficient has the unit
/// `kg/m` (equivalent to `m^2 * kg/m^3`).
#[derive(Clone, Copy, PartialEq, Debug, Display, From, Into, Reflect)]
#[reflect(Component)]
pub struct Drag(pub f32);
impl Default for Drag {
fn default() -> Self {
Self::from_terminal_velocity(55.56, 62.0, 9.81)
}
}
impl Drag {
/// Calculates simplified drag coefficient from the expected terminal
/// velocity of a body with the given mass and gravity. Terminal velocity
/// in the range (-1.0, 1.0) will cause the drag coefficient to be too
/// large.
pub fn from_terminal_velocity(terminal_velocity: f32, mass: f32, gravity: f32) -> Self {
// v_t = sqrt((m * g) / b), where b = p * A * C_d (simplified with this engine)
// b = (m * g) / v_t^2
Drag((mass * gravity) / terminal_velocity.powi(2))
}
pub fn get_terminal_velocity(self, mass: f32, gravity: f32) -> f32 {
((mass * gravity) / self.0).sqrt()
}
}
|
#![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)]
#![allow(clippy::clone_on_ref_ptr)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
clippy::explicit_iter_loop,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::clone_on_ref_ptr,
clippy::todo,
clippy::dbg_macro,
unused_crate_dependencies
)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
pub mod bitset;
pub mod dictionary;
pub mod display;
pub mod flight;
pub mod optimize;
pub mod string;
pub mod util;
/// This has a collection of testing helper functions
pub mod test_util;
|
// Sorts a given array by insertion sort
// Input: An array a[0..n-1] of n orderable elements
// Output: Array a[0..n-1] sorted in nondecreasing order
// Note: To avoid encountering negative indices, this implementation
// sorts the array right-to-left whereas the original algorithm
// sorts left-to-right
fn insertion_sort(a: &mut [u8]) {
let n = a.len();
for i in 1..n {
let v = a[n - 1 - i];
let mut j = n - i;
while j < n && a[j] < v {
a[j - 1] = a[j];
j = j + 1;
}
a[j - 1] = v;
}
}
fn main() {
// sort example array from book
let mut a: [u8; 7] = [89, 45, 68, 90, 29, 34, 17];
println!("Array before insertion sort: {:?}", a);
// should be [17, 29, 34, 45, 68, 89, 90]
insertion_sort(&mut a);
println!("Array after insertion sort: {:?}", a);
}
|
#[doc = "Reader of register FDCAN_TURNA"]
pub type R = crate::R<u32, super::FDCAN_TURNA>;
#[doc = "Reader of field `NAV`"]
pub type NAV_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:17 - Numerator Actual Value"]
#[inline(always)]
pub fn nav(&self) -> NAV_R {
NAV_R::new((self.bits & 0x0003_ffff) as u32)
}
}
|
#[test]
fn ui() {
if !version_check::is_nightly().unwrap() {
return;
}
let mut config = compiletest::Config {
mode: compiletest::common::Mode::Ui,
src_base: std::path::PathBuf::from("tests/ui"),
target_rustcflags: Some(String::from(
"\
--edition=2018 \
-Z unstable-options \
--extern serde_repr \
",
)),
build_base: std::path::PathBuf::from("target/ui"),
..Default::default()
};
config.link_deps();
config.clean_rmeta();
compiletest::run_tests(&config);
}
|
#![feature(core_intrinsics)]
#![feature(dropck_eyepatch)]
#![feature(test)]
extern crate alloc;
#[cfg(any(test, bench))]
extern crate test;
pub mod arena;
pub mod symbol;
pub mod symbols;
pub use symbol::{Ident, InternedString, LocalInternedString, Symbol};
|
use crate::torrents::Torrent;
use crate::utils::bitfield::Bitfield;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::collections::VecDeque;
use std::fs::{remove_file, File, OpenOptions};
use std::io::{Read, Write};
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex;
pub struct Progress {
pub uploaded: usize,
pub downloaded: usize,
pub left: usize,
}
pub struct Partial<'a> {
file: Option<File>,
filename: String,
buf: Vec<u8>,
received: usize,
torrent: &'a Torrent,
num_pieces: usize,
pub progress: Arc<Mutex<Progress>>,
pub bf: Arc<Mutex<Bitfield>>,
pub done: bool,
}
impl<'a> Partial<'a> {
pub fn from(torrent: &'a Torrent, dir: &str) -> Partial<'a> {
let filename = if dir == "" {
format!("{}{}", torrent.name, ".part")
} else {
format!("{}/{}{}", dir, torrent.name, ".part")
};
let bf_len = (torrent.length - 1) / (8 * torrent.piece_length as usize) + 1;
let bf = Bitfield::new(bf_len);
let len = (torrent.length - 1) / (torrent.piece_length as usize) + 1;
Partial {
torrent,
file: None,
filename,
buf: vec![0; torrent.length],
num_pieces: len,
received: 0,
progress: Arc::new(Mutex::new(Progress {
downloaded: 0,
uploaded: 0,
left: torrent.length,
})),
bf: Arc::new(Mutex::new(bf)),
done: false,
}
}
// determines if there has been progress
pub async fn recover(&mut self) {
if Path::new(&self.filename).exists() {
let file = OpenOptions::new()
.read(true)
.append(true)
.create(true)
.open(&self.filename)
.ok();
// read in .part file
if self.read_part(file).await != None {
return;
}
// error in reading part file so erase bad file
remove_file(&self.filename).ok();
} else if let Some(true) = self.has().await {
// already have file
self.done = true;
return;
}
self.file = OpenOptions::new()
.read(true)
.append(true)
.create(true)
.open(&self.filename)
.ok();
}
// reads a .part file and updates self
// returns None if anything goes wrong indicating corrupt part file
async fn read_part(&mut self, mut file: Option<File>) -> Option<()> {
let f = file.as_mut()?;
let num_bytes = f.metadata().ok()?.len();
let n = self.torrent.piece_length as u64;
if num_bytes % (n + 4) != 0 || num_bytes > (n + 4) * self.torrent.piece_length as u64 {
return None;
}
let bf_len = (self.torrent.length - 1) / (8 * self.torrent.piece_length as usize) + 1;
let mut bf = Bitfield::new(bf_len);
let mut buf = vec![0; self.torrent.piece_length as usize];
let q = self.torrent.pieces.get_q();
let q = q.lock().await;
println!("Recovering from {}", self.filename);
let mut i = 0;
while i < num_bytes {
let idx = f.read_u32::<BigEndian>().ok()? as usize;
let start = idx * self.torrent.piece_length as usize;
// check if a double piece (would be bad)
if bf.has(idx) {
return None;
}
bf.add(idx);
f.read_exact(buf.as_mut_slice()).ok()?;
// verify
if !q.get(idx)?.verify(&buf) {
return None;
}
self.buf[start..start + n as usize].copy_from_slice(&buf);
i += n + 4;
}
drop(q);
// get rid of pieces that we now have
let mut newq = VecDeque::new();
for i in 0..self.torrent.pieces.len().await {
let piece = self.torrent.pieces.pop_block().await;
if !bf.has(i) {
newq.push_back(piece);
}
}
self.torrent.pieces.replace(newq).await;
self.bf = Arc::new(Mutex::new(bf));
self.file = file;
self.received = (num_bytes / (n + 4)) as usize;
Some(())
}
// returns None if no files exist
// Some(true) if all files exist and are verified
// Some(false) otherwise
async fn has(&mut self) -> Option<bool> {
let mut all = true;
let mut exists = false;
let mut i = 0;
let mut buf = vec![0; self.torrent.length];
for f in self.torrent.files.iter() {
let path = f.path.join("/");
let path = Path::new(path.as_str());
// see if path exist
if path.exists() {
exists = true;
let file = std::fs::read(path);
if let Ok(v) = file {
if v.len() == f.length {
buf[i..i + f.length as usize].copy_from_slice(v.as_slice());
} else {
all = false;
}
} else {
all = false;
}
} else {
all = false;
}
i += f.length;
}
if !exists {
None
} else {
if all {
// verify all pieces
{
let q = self.torrent.pieces.get_q();
let q = q.lock().await;
let mut iter = q.iter();
let mut i: u64 = 0;
let len = self.torrent.piece_length as usize;
while let Some(piece) = iter.next() {
let ceil = std::cmp::min(i as usize + len, self.torrent.length);
if !piece.verify(&buf[i as usize..ceil]) {
// bad piece
return Some(false);
} else {
if (i / (len as u64)) % 100 == 99 {
println!(
"Verified {:.2}%",
100f64 * (i + len as u64) as f64 / self.torrent.length as f64
);
}
}
i += len as u64;
}
}
// all pieces verified
self.buf = buf;
let mut p = self.progress.lock().await;
p.left = 0;
let mut bf = self.bf.lock().await;
let len = bf.len();
*bf = Bitfield::from(vec![255; len]);
self.torrent.pieces.clear().await;
}
Some(all)
}
}
// updates bitfield and writes piece to file
// returns None if already has piece
// returns Some(true) if finished
pub async fn update(&mut self, idx: u32, res: Vec<u8>) -> Option<bool> {
let mut bf = self.bf.lock().await;
// check if already has piece
if bf.has(idx as usize) {
return None;
}
// write to buffer
let start = idx as usize * self.torrent.piece_length as usize;
self.buf[start..start + res.len()].copy_from_slice(res.as_slice());
self.received += 1;
// mark bit
bf.add(idx as usize);
let mut prog = self.progress.lock().await;
prog.downloaded += res.len();
prog.left -= res.len();
// write to partial file
if let Some(f) = self.file.as_mut() {
// TODO: maybe error check this
f.write_u32::<BigEndian>(idx).ok();
f.write_all(res.as_slice()).ok();
}
if self.received == self.num_pieces {
self.done = true;
self.write_file();
Some(true)
} else {
Some(false)
}
}
// returns byte piece if present
pub async fn get(&self, idx: u32, offset: u32, len: u32) -> Option<Vec<u8>> {
let bf = self.bf.lock().await;
if !bf.has(idx as usize) {
return None;
}
let start = (offset + idx * self.torrent.piece_length) as usize;
return Some(self.buf[start..start + len as usize].to_vec());
}
fn write_file(&self) {
let mut i = 0;
for f in self.torrent.files.iter() {
let path = &f.path.join("/");
println!("Writing to {}", path);
let path = Path::new(&path);
// create directories if necessary
let prefix = path.parent().unwrap();
std::fs::create_dir_all(prefix).expect("Could not create directories");
let mut file =
File::create(&path).expect(&format!("Could not create {}", path.to_str().unwrap()));
file.write(&self.buf[i..i + f.length])
.expect("Could not write to file");
i += f.length;
}
remove_file(self.filename.clone()).ok();
println!("FINISHED");
}
}
|
//! Types and parsers for the [`SHOW TAG VALUES`][sql] statement.
//!
//! [sql]: https://docs.influxdata.com/influxdb/v1.8/query_language/explore-schema/#show-tag-values
use crate::common::{
limit_clause, offset_clause, where_clause, ws0, ws1, LimitClause, OffsetClause, OneOrMore,
WhereClause,
};
use crate::identifier::{identifier, Identifier};
use crate::internal::{expect, ParseResult};
use crate::keywords::keyword;
use crate::show::{on_clause, OnClause};
use crate::simple_from_clause::{show_from_clause, ShowFromClause};
use crate::string::{regex, Regex};
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::char;
use nom::combinator::{map, opt};
use nom::sequence::{delimited, preceded, tuple};
use std::fmt;
use std::fmt::{Display, Formatter};
/// Represents a `SHOW TAG VALUES` InfluxQL statement.
#[derive(Clone, Debug, PartialEq)]
pub struct ShowTagValuesStatement {
/// The name of the database to query. If `None`, a default
/// database will be used.
pub database: Option<OnClause>,
/// The measurement or measurements to restrict which tag keys
/// are retrieved.
pub from: Option<ShowFromClause>,
/// Represents the `WITH KEY` clause, to restrict the tag values to
/// the matching tag keys.
pub with_key: WithKeyClause,
/// A conditional expression to filter the tag keys.
pub condition: Option<WhereClause>,
/// A value to restrict the number of tag keys returned.
pub limit: Option<LimitClause>,
/// A value to specify an offset to start retrieving tag keys.
pub offset: Option<OffsetClause>,
}
impl Display for ShowTagValuesStatement {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "SHOW TAG VALUES")?;
if let Some(ref on_clause) = self.database {
write!(f, " {on_clause}")?;
}
if let Some(ref from_clause) = self.from {
write!(f, " {from_clause}")?;
}
write!(f, " {}", self.with_key)?;
if let Some(ref where_clause) = self.condition {
write!(f, " {where_clause}")?;
}
if let Some(ref limit) = self.limit {
write!(f, " {limit}")?;
}
if let Some(ref offset) = self.offset {
write!(f, " {offset}")?;
}
Ok(())
}
}
/// Parse a `SHOW TAG VALUES` statement, starting from the `VALUES` token.
pub(crate) fn show_tag_values(i: &str) -> ParseResult<&str, ShowTagValuesStatement> {
let (
remaining_input,
(
_, // "VALUES"
database,
from,
with_key,
condition,
limit,
offset,
),
) = tuple((
keyword("VALUES"),
opt(preceded(ws1, on_clause)),
opt(preceded(ws1, show_from_clause)),
expect(
"invalid SHOW TAG VALUES statement, expected WITH KEY clause",
preceded(ws1, with_key_clause),
),
opt(preceded(ws1, where_clause)),
opt(preceded(ws1, limit_clause)),
opt(preceded(ws1, offset_clause)),
))(i)?;
Ok((
remaining_input,
ShowTagValuesStatement {
database,
from,
with_key,
condition,
limit,
offset,
},
))
}
/// Represents a list of identifiers when the `WITH KEY` clause
/// specifies the `IN` operator.
pub type InList = OneOrMore<Identifier>;
impl Display for InList {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Display::fmt(self.head(), f)?;
for arg in self.tail() {
write!(f, ", {arg}")?;
}
Ok(())
}
}
/// Represents a `WITH KEY` clause.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WithKeyClause {
/// Select a single tag key that equals the identifier.
Eq(Identifier),
/// Select all tag keys that do not equal the identifier.
NotEq(Identifier),
/// Select any tag keys that pass the regular expression.
EqRegex(Regex),
/// Select the tag keys that do not pass the regular expression.
NotEqRegex(Regex),
/// Select the tag keys matching each of the identifiers in the list.
In(InList),
}
impl Display for WithKeyClause {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("WITH KEY ")?;
match self {
Self::Eq(v) => write!(f, "= {v}"),
Self::NotEq(v) => write!(f, "!= {v}"),
Self::EqRegex(v) => write!(f, "=~ {v}"),
Self::NotEqRegex(v) => write!(f, "=! {v}"),
Self::In(list) => write!(f, "IN ({list})"),
}
}
}
/// Parse an identifier list, as expected by the `WITH KEY IN` clause.
fn identifier_list(i: &str) -> ParseResult<&str, InList> {
delimited(
preceded(ws0, char('(')),
InList::separated_list1("invalid IN clause, expected identifier"),
expect(
"invalid identifier list, expected ')'",
preceded(ws0, char(')')),
),
)(i)
}
fn with_key_clause(i: &str) -> ParseResult<&str, WithKeyClause> {
preceded(
tuple((
keyword("WITH"),
ws1,
expect("invalid WITH KEY clause, expected KEY", keyword("KEY")),
)),
expect(
"invalid WITH KEY clause, expected condition",
alt((
map(
preceded(
delimited(ws0, tag("=~"), ws0),
expect(
"invalid WITH KEY clause, expected regular expression following =~",
regex,
),
),
WithKeyClause::EqRegex,
),
map(
preceded(
delimited(ws0, tag("!~"), ws0),
expect(
"invalid WITH KEY clause, expected regular expression following =!",
regex,
),
),
WithKeyClause::NotEqRegex,
),
map(
preceded(
preceded(ws0, char('=')),
expect(
"invalid WITH KEY clause, expected identifier following =",
identifier,
),
),
WithKeyClause::Eq,
),
map(
preceded(
preceded(ws0, tag("!=")),
expect(
"invalid WITH KEY clause, expected identifier following !=",
identifier,
),
),
WithKeyClause::NotEq,
),
map(
preceded(
preceded(ws1, tag("IN")),
expect(
"invalid WITH KEY clause, expected identifier list following IN",
identifier_list,
),
),
WithKeyClause::In,
),
)),
),
)(i)
}
#[cfg(test)]
mod test {
use super::*;
use crate::assert_expect_error;
#[test]
fn test_show_tag_values() {
// No optional clauses
let (_, got) = show_tag_values("VALUES WITH KEY = some_key").unwrap();
assert_eq!(got.to_string(), "SHOW TAG VALUES WITH KEY = some_key");
let (_, got) = show_tag_values("VALUES ON db WITH KEY = some_key").unwrap();
assert_eq!(got.to_string(), "SHOW TAG VALUES ON db WITH KEY = some_key");
// measurement selection using name
let (_, got) = show_tag_values("VALUES FROM db..foo WITH KEY = some_key").unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES FROM db..foo WITH KEY = some_key"
);
// measurement selection using regex
let (_, got) = show_tag_values("VALUES FROM /foo/ WITH KEY = some_key").unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES FROM /foo/ WITH KEY = some_key"
);
// measurement selection using list
let (_, got) =
show_tag_values("VALUES FROM /foo/ , bar, \"foo bar\" WITH KEY = some_key").unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES FROM /foo/, bar, \"foo bar\" WITH KEY = some_key"
);
let (_, got) = show_tag_values("VALUES WITH KEY = some_key WHERE foo = 'bar'").unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES WITH KEY = some_key WHERE foo = 'bar'"
);
let (_, got) = show_tag_values("VALUES WITH KEY = some_key LIMIT 1").unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES WITH KEY = some_key LIMIT 1"
);
let (_, got) = show_tag_values("VALUES WITH KEY = some_key OFFSET 2").unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES WITH KEY = some_key OFFSET 2"
);
// all optional clauses
let (_, got) = show_tag_values(
"VALUES ON db FROM /foo/ WITH KEY = some_key WHERE foo = 'bar' LIMIT 1 OFFSET 2",
)
.unwrap();
assert_eq!(
got.to_string(),
"SHOW TAG VALUES ON db FROM /foo/ WITH KEY = some_key WHERE foo = 'bar' LIMIT 1 OFFSET 2"
);
let (_, got) = show_tag_values("VALUES WITH KEY IN( foo )").unwrap();
assert_eq!(got.to_string(), "SHOW TAG VALUES WITH KEY IN (foo)");
// Fallible cases are tested by the various combinator functions
}
#[test]
fn test_with_key_clause() {
let (_, got) = with_key_clause("WITH KEY = foo").unwrap();
assert_eq!(got, WithKeyClause::Eq("foo".into()));
let (_, got) = with_key_clause("WITH KEY != foo").unwrap();
assert_eq!(got, WithKeyClause::NotEq("foo".into()));
let (_, got) = with_key_clause("WITH KEY =~ /foo/").unwrap();
assert_eq!(got, WithKeyClause::EqRegex("foo".into()));
let (_, got) = with_key_clause("WITH KEY !~ /foo/").unwrap();
assert_eq!(got, WithKeyClause::NotEqRegex("foo".into()));
let (_, got) = with_key_clause("WITH KEY IN (foo)").unwrap();
assert_eq!(got, WithKeyClause::In(InList::new(vec!["foo".into()])));
let (_, got) = with_key_clause("WITH KEY IN (foo, bar, \"foo bar\")").unwrap();
assert_eq!(
got,
WithKeyClause::In(InList::new(vec![
"foo".into(),
"bar".into(),
"foo bar".into()
]))
);
// Expressions are still valid when whitespace is omitted
let (_, got) = with_key_clause("WITH KEY=foo").unwrap();
assert_eq!(got, WithKeyClause::Eq("foo".into()));
// Fallible cases
assert_expect_error!(
with_key_clause("WITH = foo"),
"invalid WITH KEY clause, expected KEY"
);
assert_expect_error!(
with_key_clause("WITH KEY"),
"invalid WITH KEY clause, expected condition"
);
assert_expect_error!(
with_key_clause("WITH KEY foo"),
"invalid WITH KEY clause, expected condition"
);
assert_expect_error!(
with_key_clause("WITH KEY = /foo/"),
"invalid WITH KEY clause, expected identifier following ="
);
assert_expect_error!(
with_key_clause("WITH KEY IN = foo"),
"invalid WITH KEY clause, expected identifier list following IN"
);
}
#[test]
fn test_identifier_list() {
let (_, got) = identifier_list("(foo)").unwrap();
assert_eq!(got, InList::new(vec!["foo".into()]));
// Test first and rest as well as removing unnecessary whitespace
let (_, got) = identifier_list("( foo, bar,\"foo bar\" )").unwrap();
assert_eq!(
got,
InList::new(vec!["foo".into(), "bar".into(), "foo bar".into()])
);
// Fallible cases
assert_expect_error!(
identifier_list("(foo"),
"invalid identifier list, expected ')'"
);
assert_expect_error!(
identifier_list("(foo bar)"),
"invalid identifier list, expected ')'"
);
}
}
|
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let a1: i64 = read();
let _b1: i64 = read();
let a2: i64 = read();
let _b2: i64 = read();
let a3: i64 = read();
let _b3: i64 = read();
println!(
"{}",
if (a1 + a2 + a3) % 2 == 0 {
":-)"
} else {
":-("
}
);
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ACTIVITY_STATE(pub i32);
pub const ActivityState_Unknown: ACTIVITY_STATE = ACTIVITY_STATE(1i32);
pub const ActivityState_Stationary: ACTIVITY_STATE = ACTIVITY_STATE(2i32);
pub const ActivityState_Fidgeting: ACTIVITY_STATE = ACTIVITY_STATE(4i32);
pub const ActivityState_Walking: ACTIVITY_STATE = ACTIVITY_STATE(8i32);
pub const ActivityState_Running: ACTIVITY_STATE = ACTIVITY_STATE(16i32);
pub const ActivityState_InVehicle: ACTIVITY_STATE = ACTIVITY_STATE(32i32);
pub const ActivityState_Biking: ACTIVITY_STATE = ACTIVITY_STATE(64i32);
pub const ActivityState_Idle: ACTIVITY_STATE = ACTIVITY_STATE(128i32);
pub const ActivityState_Max: ACTIVITY_STATE = ACTIVITY_STATE(256i32);
pub const ActivityState_Force_Dword: ACTIVITY_STATE = ACTIVITY_STATE(-1i32);
impl ::core::convert::From<i32> for ACTIVITY_STATE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ACTIVITY_STATE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ACTIVITY_STATE_COUNT(pub i32);
pub const ActivityStateCount: ACTIVITY_STATE_COUNT = ACTIVITY_STATE_COUNT(8i32);
impl ::core::convert::From<i32> for ACTIVITY_STATE_COUNT {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ACTIVITY_STATE_COUNT {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AXIS(pub i32);
pub const AXIS_X: AXIS = AXIS(0i32);
pub const AXIS_Y: AXIS = AXIS(1i32);
pub const AXIS_Z: AXIS = AXIS(2i32);
pub const AXIS_MAX: AXIS = AXIS(3i32);
impl ::core::convert::From<i32> for AXIS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AXIS {
type Abi = Self;
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListAllocateBufferAndSerialize(sourcecollection: *const SENSOR_COLLECTION_LIST, ptargetbuffersizeinbytes: *mut u32, ptargetbuffer: *mut *mut u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListAllocateBufferAndSerialize(sourcecollection: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, ptargetbuffersizeinbytes: *mut u32, ptargetbuffer: *mut *mut u8) -> super::super::Foundation::NTSTATUS;
}
CollectionsListAllocateBufferAndSerialize(::core::mem::transmute(sourcecollection), ::core::mem::transmute(ptargetbuffersizeinbytes), ::core::mem::transmute(ptargetbuffer)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListCopyAndMarshall(target: *mut SENSOR_COLLECTION_LIST, source: *const SENSOR_COLLECTION_LIST) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListCopyAndMarshall(target: *mut ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, source: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::NTSTATUS;
}
CollectionsListCopyAndMarshall(::core::mem::transmute(target), ::core::mem::transmute(source)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListDeserializeFromBuffer(sourcebuffersizeinbytes: u32, sourcebuffer: *const u8, targetcollection: *mut SENSOR_COLLECTION_LIST) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListDeserializeFromBuffer(sourcebuffersizeinbytes: u32, sourcebuffer: *const u8, targetcollection: *mut ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::NTSTATUS;
}
CollectionsListDeserializeFromBuffer(::core::mem::transmute(sourcebuffersizeinbytes), ::core::mem::transmute(sourcebuffer), ::core::mem::transmute(targetcollection)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn CollectionsListGetFillableCount(buffersizebytes: u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListGetFillableCount(buffersizebytes: u32) -> u32;
}
::core::mem::transmute(CollectionsListGetFillableCount(::core::mem::transmute(buffersizebytes)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListGetMarshalledSize(collection: *const SENSOR_COLLECTION_LIST) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListGetMarshalledSize(collection: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> u32;
}
::core::mem::transmute(CollectionsListGetMarshalledSize(::core::mem::transmute(collection)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListGetMarshalledSizeWithoutSerialization(collection: *const SENSOR_COLLECTION_LIST) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListGetMarshalledSizeWithoutSerialization(collection: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> u32;
}
::core::mem::transmute(CollectionsListGetMarshalledSizeWithoutSerialization(::core::mem::transmute(collection)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListGetSerializedSize(collection: *const SENSOR_COLLECTION_LIST) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListGetSerializedSize(collection: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> u32;
}
::core::mem::transmute(CollectionsListGetSerializedSize(::core::mem::transmute(collection)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListMarshall(target: *mut SENSOR_COLLECTION_LIST) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListMarshall(target: *mut ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::NTSTATUS;
}
CollectionsListMarshall(::core::mem::transmute(target)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListSerializeToBuffer(sourcecollection: *const SENSOR_COLLECTION_LIST, targetbuffersizeinbytes: u32, targetbuffer: *mut u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListSerializeToBuffer(sourcecollection: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, targetbuffersizeinbytes: u32, targetbuffer: *mut u8) -> super::super::Foundation::NTSTATUS;
}
CollectionsListSerializeToBuffer(::core::mem::transmute(sourcecollection), ::core::mem::transmute(targetbuffersizeinbytes), ::core::mem::transmute(targetbuffer)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListSortSubscribedActivitiesByConfidence(thresholds: *const SENSOR_COLLECTION_LIST, pcollection: *mut SENSOR_COLLECTION_LIST) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListSortSubscribedActivitiesByConfidence(thresholds: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pcollection: *mut ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::NTSTATUS;
}
CollectionsListSortSubscribedActivitiesByConfidence(::core::mem::transmute(thresholds), ::core::mem::transmute(pcollection)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn CollectionsListUpdateMarshalledPointer(collection: *mut SENSOR_COLLECTION_LIST) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CollectionsListUpdateMarshalledPointer(collection: *mut ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::NTSTATUS;
}
CollectionsListUpdateMarshalledPointer(::core::mem::transmute(collection)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ELEVATION_CHANGE_MODE(pub i32);
pub const ElevationChangeMode_Unknown: ELEVATION_CHANGE_MODE = ELEVATION_CHANGE_MODE(0i32);
pub const ElevationChangeMode_Elevator: ELEVATION_CHANGE_MODE = ELEVATION_CHANGE_MODE(1i32);
pub const ElevationChangeMode_Stepping: ELEVATION_CHANGE_MODE = ELEVATION_CHANGE_MODE(2i32);
pub const ElevationChangeMode_Max: ELEVATION_CHANGE_MODE = ELEVATION_CHANGE_MODE(3i32);
pub const ElevationChangeMode_Force_Dword: ELEVATION_CHANGE_MODE = ELEVATION_CHANGE_MODE(-1i32);
impl ::core::convert::From<i32> for ELEVATION_CHANGE_MODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ELEVATION_CHANGE_MODE {
type Abi = Self;
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn EvaluateActivityThresholds(newsample: *const SENSOR_COLLECTION_LIST, oldsample: *const SENSOR_COLLECTION_LIST, thresholds: *const SENSOR_COLLECTION_LIST) -> super::super::Foundation::BOOLEAN {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn EvaluateActivityThresholds(newsample: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, oldsample: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, thresholds: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::BOOLEAN;
}
::core::mem::transmute(EvaluateActivityThresholds(::core::mem::transmute(newsample), ::core::mem::transmute(oldsample), ::core::mem::transmute(thresholds)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
pub const GNSS_CLEAR_ALL_ASSISTANCE_DATA: u32 = 1u32;
pub const GUID_DEVINTERFACE_SENSOR: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xba1bb692_9b7a_4833_9a1e_525ed134e7e2);
pub const GUID_SensorCategory_All: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc317c286_c468_4288_9975_d4c4587c442c);
pub const GUID_SensorCategory_Biometric: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca19690f_a2c7_477d_a99e_99ec6e2b5648);
pub const GUID_SensorCategory_Electrical: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb73fcd8_fc4a_483c_ac58_27b691c6beff);
pub const GUID_SensorCategory_Environmental: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x323439aa_7f66_492b_ba0c_73e9aa0a65d5);
pub const GUID_SensorCategory_Light: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x17a665c0_9063_4216_b202_5c7a255e18ce);
pub const GUID_SensorCategory_Location: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfa794e4_f964_4fdb_90f6_51056bfe4b44);
pub const GUID_SensorCategory_Mechanical: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8d131d68_8ef7_4656_80b5_cccbd93791c5);
pub const GUID_SensorCategory_Motion: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcd09daf1_3b2e_4c3d_b598_b5e5ff93fd46);
pub const GUID_SensorCategory_Orientation: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e6c04b6_96fe_4954_b726_68682a473f69);
pub const GUID_SensorCategory_Other: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2c90e7a9_f4c9_4fa2_af37_56d471fe5a3d);
pub const GUID_SensorCategory_PersonalActivity: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf1609081_1e12_412b_a14d_cbb0e95bd2e5);
pub const GUID_SensorCategory_Scanner: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb000e77e_f5b5_420f_815d_0270a726f270);
pub const GUID_SensorCategory_Unsupported: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2beae7fa_19b0_48c5_a1f6_b5480dc206b0);
pub const GUID_SensorType_Accelerometer3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc2fb0f5f_e2d2_4c78_bcd0_352a9582819d);
pub const GUID_SensorType_ActivityDetection: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9d9e0118_1807_4f2e_96e4_2ce57142e196);
pub const GUID_SensorType_AmbientLight: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x97f115c8_599a_4153_8894_d2d12899918a);
pub const GUID_SensorType_Barometer: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0e903829_ff8a_4a93_97df_3dcbde402288);
pub const GUID_SensorType_Custom: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe83af229_8640_4d18_a213_e22675ebb2c3);
pub const GUID_SensorType_FloorElevation: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xade4987f_7ac4_4dfa_9722_0a027181c747);
pub const GUID_SensorType_GeomagneticOrientation: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe77195f8_2d1f_4823_971b_1c4467556c9d);
pub const GUID_SensorType_GravityVector: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x03b52c73_bb76_463f_9524_38de76eb700b);
pub const GUID_SensorType_Gyrometer3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09485f5a_759e_42c2_bd4b_a349b75c8643);
pub const GUID_SensorType_HingeAngle: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82358065_f4c4_4da1_b272_13c23332a207);
pub const GUID_SensorType_Humidity: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5c72bf67_bd7e_4257_990b_98a3ba3b400a);
pub const GUID_SensorType_LinearAccelerometer: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x038b0283_97b4_41c8_bc24_5ff1aa48fec7);
pub const GUID_SensorType_Magnetometer3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x55e5effb_15c7_40df_8698_a84b7c863c53);
pub const GUID_SensorType_Orientation: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcdb5d8f7_3cfd_41c8_8542_cce622cf5d6e);
pub const GUID_SensorType_Pedometer: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb19f89af_e3eb_444b_8dea_202575a71599);
pub const GUID_SensorType_Proximity: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5220dae9_3179_4430_9f90_06266d2a34de);
pub const GUID_SensorType_RelativeOrientation: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x40993b51_4706_44dc_98d5_c920c037ffab);
pub const GUID_SensorType_SimpleDeviceOrientation: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x86a19291_0482_402c_bf4c_addac52b1c39);
pub const GUID_SensorType_Temperature: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x04fd0ec4_d5da_45fa_95a9_5db38ee19306);
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn GetPerformanceTime(timems: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetPerformanceTime(timems: *mut u32) -> super::super::Foundation::NTSTATUS;
}
GetPerformanceTime(::core::mem::transmute(timems)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HUMAN_PRESENCE_DETECTION_TYPE(pub i32);
pub const HumanPresenceDetectionType_VendorDefinedNonBiometric: HUMAN_PRESENCE_DETECTION_TYPE = HUMAN_PRESENCE_DETECTION_TYPE(1i32);
pub const HumanPresenceDetectionType_VendorDefinedBiometric: HUMAN_PRESENCE_DETECTION_TYPE = HUMAN_PRESENCE_DETECTION_TYPE(2i32);
pub const HumanPresenceDetectionType_FacialBiometric: HUMAN_PRESENCE_DETECTION_TYPE = HUMAN_PRESENCE_DETECTION_TYPE(4i32);
pub const HumanPresenceDetectionType_AudioBiometric: HUMAN_PRESENCE_DETECTION_TYPE = HUMAN_PRESENCE_DETECTION_TYPE(8i32);
pub const HumanPresenceDetectionType_Force_Dword: HUMAN_PRESENCE_DETECTION_TYPE = HUMAN_PRESENCE_DETECTION_TYPE(-1i32);
impl ::core::convert::From<i32> for HUMAN_PRESENCE_DETECTION_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HUMAN_PRESENCE_DETECTION_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HUMAN_PRESENCE_DETECTION_TYPE_COUNT(pub i32);
pub const HumanPresenceDetectionTypeCount: HUMAN_PRESENCE_DETECTION_TYPE_COUNT = HUMAN_PRESENCE_DETECTION_TYPE_COUNT(4i32);
impl ::core::convert::From<i32> for HUMAN_PRESENCE_DETECTION_TYPE_COUNT {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HUMAN_PRESENCE_DETECTION_TYPE_COUNT {
type Abi = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ILocationPermissions(pub ::windows::core::IUnknown);
impl ILocationPermissions {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetGlobalLocationPermission(&self) -> ::windows::core::Result<super::super::Foundation::BOOL> {
let mut result__: <super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BOOL>(result__)
}
pub unsafe fn CheckLocationCapability(&self, dwclientthreadid: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwclientthreadid)).ok()
}
}
unsafe impl ::windows::core::Interface for ILocationPermissions {
type Vtable = ILocationPermissions_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5fb0a7f_e74e_44f5_8e02_4806863a274f);
}
impl ::core::convert::From<ILocationPermissions> for ::windows::core::IUnknown {
fn from(value: ILocationPermissions) -> Self {
value.0
}
}
impl ::core::convert::From<&ILocationPermissions> for ::windows::core::IUnknown {
fn from(value: &ILocationPermissions) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ILocationPermissions {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ILocationPermissions {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ILocationPermissions_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfenabled: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwclientthreadid: u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISensor(pub ::windows::core::IUnknown);
impl ISensor {
pub unsafe fn GetID(&self) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
pub unsafe fn GetCategory(&self) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
pub unsafe fn GetType(&self) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetFriendlyName(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> {
let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
pub unsafe fn GetProperty(&self, key: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::Result<super::super::System::Com::StructuredStorage::PROPVARIANT> {
let mut result__: <super::super::System::Com::StructuredStorage::PROPVARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(key), &mut result__).from_abi::<super::super::System::Com::StructuredStorage::PROPVARIANT>(result__)
}
#[cfg(feature = "Win32_Devices_PortableDevices")]
pub unsafe fn GetProperties<'a, Param0: ::windows::core::IntoParam<'a, super::PortableDevices::IPortableDeviceKeyCollection>>(&self, pkeys: Param0) -> ::windows::core::Result<super::PortableDevices::IPortableDeviceValues> {
let mut result__: <super::PortableDevices::IPortableDeviceValues as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), pkeys.into_param().abi(), &mut result__).from_abi::<super::PortableDevices::IPortableDeviceValues>(result__)
}
#[cfg(feature = "Win32_Devices_PortableDevices")]
pub unsafe fn GetSupportedDataFields(&self) -> ::windows::core::Result<super::PortableDevices::IPortableDeviceKeyCollection> {
let mut result__: <super::PortableDevices::IPortableDeviceKeyCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::PortableDevices::IPortableDeviceKeyCollection>(result__)
}
#[cfg(feature = "Win32_Devices_PortableDevices")]
pub unsafe fn SetProperties<'a, Param0: ::windows::core::IntoParam<'a, super::PortableDevices::IPortableDeviceValues>>(&self, pproperties: Param0) -> ::windows::core::Result<super::PortableDevices::IPortableDeviceValues> {
let mut result__: <super::PortableDevices::IPortableDeviceValues as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), pproperties.into_param().abi(), &mut result__).from_abi::<super::PortableDevices::IPortableDeviceValues>(result__)
}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub unsafe fn SupportsDataField(&self, key: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::Result<i16> {
let mut result__: <i16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(key), &mut result__).from_abi::<i16>(result__)
}
pub unsafe fn GetState(&self) -> ::windows::core::Result<SensorState> {
let mut result__: <SensorState as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), &mut result__).from_abi::<SensorState>(result__)
}
pub unsafe fn GetData(&self) -> ::windows::core::Result<ISensorDataReport> {
let mut result__: <ISensorDataReport as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<ISensorDataReport>(result__)
}
pub unsafe fn SupportsEvent(&self, eventguid: *const ::windows::core::GUID) -> ::windows::core::Result<i16> {
let mut result__: <i16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(eventguid), &mut result__).from_abi::<i16>(result__)
}
pub unsafe fn GetEventInterest(&self, ppvalues: *mut *mut ::windows::core::GUID, pcount: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppvalues), ::core::mem::transmute(pcount)).ok()
}
pub unsafe fn SetEventInterest(&self, pvalues: *const ::windows::core::GUID, count: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvalues), ::core::mem::transmute(count)).ok()
}
pub unsafe fn SetEventSink<'a, Param0: ::windows::core::IntoParam<'a, ISensorEvents>>(&self, pevents: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), pevents.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for ISensor {
type Vtable = ISensor_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5fa08f80_2657_458e_af75_46f73fa6ac5c);
}
impl ::core::convert::From<ISensor> for ::windows::core::IUnknown {
fn from(value: ISensor) -> Self {
value.0
}
}
impl ::core::convert::From<&ISensor> for ::windows::core::IUnknown {
fn from(value: &ISensor) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISensor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISensor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISensor_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensorcategory: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensortype: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfriendlyname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pproperty: *mut ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem")))] usize,
#[cfg(feature = "Win32_Devices_PortableDevices")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pkeys: ::windows::core::RawPtr, ppproperties: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Devices_PortableDevices"))] usize,
#[cfg(feature = "Win32_Devices_PortableDevices")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppdatafields: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Devices_PortableDevices"))] usize,
#[cfg(feature = "Win32_Devices_PortableDevices")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pproperties: ::windows::core::RawPtr, ppresults: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Devices_PortableDevices"))] usize,
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pissupported: *mut i16) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_UI_Shell_PropertiesSystem"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstate: *mut SensorState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppdatareport: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventguid: *const ::windows::core::GUID, pissupported: *mut i16) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppvalues: *mut *mut ::windows::core::GUID, pcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvalues: *const ::windows::core::GUID, count: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pevents: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISensorCollection(pub ::windows::core::IUnknown);
impl ISensorCollection {
pub unsafe fn GetAt(&self, ulindex: u32) -> ::windows::core::Result<ISensor> {
let mut result__: <ISensor as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulindex), &mut result__).from_abi::<ISensor>(result__)
}
pub unsafe fn GetCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn Add<'a, Param0: ::windows::core::IntoParam<'a, ISensor>>(&self, psensor: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), psensor.into_param().abi()).ok()
}
pub unsafe fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ISensor>>(&self, psensor: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), psensor.into_param().abi()).ok()
}
pub unsafe fn RemoveByID(&self, sensorid: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(sensorid)).ok()
}
pub unsafe fn Clear(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for ISensorCollection {
type Vtable = ISensorCollection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x23571e11_e545_4dd8_a337_b89bf44b10df);
}
impl ::core::convert::From<ISensorCollection> for ::windows::core::IUnknown {
fn from(value: ISensorCollection) -> Self {
value.0
}
}
impl ::core::convert::From<&ISensorCollection> for ::windows::core::IUnknown {
fn from(value: &ISensorCollection) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISensorCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISensorCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISensorCollection_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulindex: u32, ppsensor: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensor: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensor: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sensorid: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISensorDataReport(pub ::windows::core::IUnknown);
impl ISensorDataReport {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetTimestamp(&self) -> ::windows::core::Result<super::super::Foundation::SYSTEMTIME> {
let mut result__: <super::super::Foundation::SYSTEMTIME as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::SYSTEMTIME>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
pub unsafe fn GetSensorValue(&self, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::Result<super::super::System::Com::StructuredStorage::PROPVARIANT> {
let mut result__: <super::super::System::Com::StructuredStorage::PROPVARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pkey), &mut result__).from_abi::<super::super::System::Com::StructuredStorage::PROPVARIANT>(result__)
}
#[cfg(feature = "Win32_Devices_PortableDevices")]
pub unsafe fn GetSensorValues<'a, Param0: ::windows::core::IntoParam<'a, super::PortableDevices::IPortableDeviceKeyCollection>>(&self, pkeys: Param0) -> ::windows::core::Result<super::PortableDevices::IPortableDeviceValues> {
let mut result__: <super::PortableDevices::IPortableDeviceValues as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pkeys.into_param().abi(), &mut result__).from_abi::<super::PortableDevices::IPortableDeviceValues>(result__)
}
}
unsafe impl ::windows::core::Interface for ISensorDataReport {
type Vtable = ISensorDataReport_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0ab9df9b_c4b5_4796_8898_0470706a2e1d);
}
impl ::core::convert::From<ISensorDataReport> for ::windows::core::IUnknown {
fn from(value: ISensorDataReport) -> Self {
value.0
}
}
impl ::core::convert::From<&ISensorDataReport> for ::windows::core::IUnknown {
fn from(value: &ISensorDataReport) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISensorDataReport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISensorDataReport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISensorDataReport_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ptimestamp: *mut super::super::Foundation::SYSTEMTIME) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pvalue: *mut ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem")))] usize,
#[cfg(feature = "Win32_Devices_PortableDevices")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pkeys: ::windows::core::RawPtr, ppvalues: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Devices_PortableDevices"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISensorEvents(pub ::windows::core::IUnknown);
impl ISensorEvents {
pub unsafe fn OnStateChanged<'a, Param0: ::windows::core::IntoParam<'a, ISensor>>(&self, psensor: Param0, state: SensorState) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), psensor.into_param().abi(), ::core::mem::transmute(state)).ok()
}
pub unsafe fn OnDataUpdated<'a, Param0: ::windows::core::IntoParam<'a, ISensor>, Param1: ::windows::core::IntoParam<'a, ISensorDataReport>>(&self, psensor: Param0, pnewdata: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), psensor.into_param().abi(), pnewdata.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Devices_PortableDevices")]
pub unsafe fn OnEvent<'a, Param0: ::windows::core::IntoParam<'a, ISensor>, Param2: ::windows::core::IntoParam<'a, super::PortableDevices::IPortableDeviceValues>>(&self, psensor: Param0, eventid: *const ::windows::core::GUID, peventdata: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), psensor.into_param().abi(), ::core::mem::transmute(eventid), peventdata.into_param().abi()).ok()
}
pub unsafe fn OnLeave(&self, id: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(id)).ok()
}
}
unsafe impl ::windows::core::Interface for ISensorEvents {
type Vtable = ISensorEvents_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d8dcc91_4641_47e7_b7c3_b74f48a6c391);
}
impl ::core::convert::From<ISensorEvents> for ::windows::core::IUnknown {
fn from(value: ISensorEvents) -> Self {
value.0
}
}
impl ::core::convert::From<&ISensorEvents> for ::windows::core::IUnknown {
fn from(value: &ISensorEvents) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISensorEvents {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISensorEvents {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISensorEvents_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensor: ::windows::core::RawPtr, state: SensorState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensor: ::windows::core::RawPtr, pnewdata: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Devices_PortableDevices")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensor: ::windows::core::RawPtr, eventid: *const ::windows::core::GUID, peventdata: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Devices_PortableDevices"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISensorManager(pub ::windows::core::IUnknown);
impl ISensorManager {
pub unsafe fn GetSensorsByCategory(&self, sensorcategory: *const ::windows::core::GUID) -> ::windows::core::Result<ISensorCollection> {
let mut result__: <ISensorCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(sensorcategory), &mut result__).from_abi::<ISensorCollection>(result__)
}
pub unsafe fn GetSensorsByType(&self, sensortype: *const ::windows::core::GUID) -> ::windows::core::Result<ISensorCollection> {
let mut result__: <ISensorCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(sensortype), &mut result__).from_abi::<ISensorCollection>(result__)
}
pub unsafe fn GetSensorByID(&self, sensorid: *const ::windows::core::GUID) -> ::windows::core::Result<ISensor> {
let mut result__: <ISensor as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(sensorid), &mut result__).from_abi::<ISensor>(result__)
}
pub unsafe fn SetEventSink<'a, Param0: ::windows::core::IntoParam<'a, ISensorManagerEvents>>(&self, pevents: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), pevents.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn RequestPermissions<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>, Param1: ::windows::core::IntoParam<'a, ISensorCollection>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, hparent: Param0, psensors: Param1, fmodal: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), hparent.into_param().abi(), psensors.into_param().abi(), fmodal.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for ISensorManager {
type Vtable = ISensorManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbd77db67_45a8_42dc_8d00_6dcf15f8377a);
}
impl ::core::convert::From<ISensorManager> for ::windows::core::IUnknown {
fn from(value: ISensorManager) -> Self {
value.0
}
}
impl ::core::convert::From<&ISensorManager> for ::windows::core::IUnknown {
fn from(value: &ISensorManager) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISensorManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISensorManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISensorManager_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sensorcategory: *const ::windows::core::GUID, ppsensorsfound: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sensortype: *const ::windows::core::GUID, ppsensorsfound: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sensorid: *const ::windows::core::GUID, ppsensor: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pevents: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hparent: super::super::Foundation::HWND, psensors: ::windows::core::RawPtr, fmodal: super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISensorManagerEvents(pub ::windows::core::IUnknown);
impl ISensorManagerEvents {
pub unsafe fn OnSensorEnter<'a, Param0: ::windows::core::IntoParam<'a, ISensor>>(&self, psensor: Param0, state: SensorState) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), psensor.into_param().abi(), ::core::mem::transmute(state)).ok()
}
}
unsafe impl ::windows::core::Interface for ISensorManagerEvents {
type Vtable = ISensorManagerEvents_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b3b0b86_266a_4aad_b21f_fde5501001b7);
}
impl ::core::convert::From<ISensorManagerEvents> for ::windows::core::IUnknown {
fn from(value: ISensorManagerEvents) -> Self {
value.0
}
}
impl ::core::convert::From<&ISensorManagerEvents> for ::windows::core::IUnknown {
fn from(value: &ISensorManagerEvents) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISensorManagerEvents {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISensorManagerEvents {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISensorManagerEvents_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psensor: ::windows::core::RawPtr, state: SensorState) -> ::windows::core::HRESULT,
);
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))]
#[inline]
pub unsafe fn InitPropVariantFromCLSIDArray(members: *const ::windows::core::GUID, size: u32) -> ::windows::core::Result<super::super::System::Com::StructuredStorage::PROPVARIANT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn InitPropVariantFromCLSIDArray(members: *const ::windows::core::GUID, size: u32, ppropvar: *mut ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT;
}
let mut result__: <super::super::System::Com::StructuredStorage::PROPVARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
InitPropVariantFromCLSIDArray(::core::mem::transmute(members), ::core::mem::transmute(size), &mut result__).from_abi::<super::super::System::Com::StructuredStorage::PROPVARIANT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))]
#[inline]
pub unsafe fn InitPropVariantFromFloat(fltval: f32) -> ::windows::core::Result<super::super::System::Com::StructuredStorage::PROPVARIANT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn InitPropVariantFromFloat(fltval: f32, ppropvar: *mut ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT;
}
let mut result__: <super::super::System::Com::StructuredStorage::PROPVARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
InitPropVariantFromFloat(::core::mem::transmute(fltval), &mut result__).from_abi::<super::super::System::Com::StructuredStorage::PROPVARIANT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn IsCollectionListSame(lista: *const SENSOR_COLLECTION_LIST, listb: *const SENSOR_COLLECTION_LIST) -> super::super::Foundation::BOOLEAN {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsCollectionListSame(lista: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, listb: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>) -> super::super::Foundation::BOOLEAN;
}
::core::mem::transmute(IsCollectionListSame(::core::mem::transmute(lista), ::core::mem::transmute(listb)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn IsGUIDPresentInList(guidarray: *const ::windows::core::GUID, arraylength: u32, guidelem: *const ::windows::core::GUID) -> super::super::Foundation::BOOLEAN {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsGUIDPresentInList(guidarray: *const ::windows::core::GUID, arraylength: u32, guidelem: *const ::windows::core::GUID) -> super::super::Foundation::BOOLEAN;
}
::core::mem::transmute(IsGUIDPresentInList(::core::mem::transmute(guidarray), ::core::mem::transmute(arraylength), ::core::mem::transmute(guidelem)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn IsKeyPresentInCollectionList(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> super::super::Foundation::BOOLEAN {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsKeyPresentInCollectionList(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> super::super::Foundation::BOOLEAN;
}
::core::mem::transmute(IsKeyPresentInCollectionList(::core::mem::transmute(plist), ::core::mem::transmute(pkey)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn IsKeyPresentInPropertyList(plist: *const SENSOR_PROPERTY_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> super::super::Foundation::BOOLEAN {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsKeyPresentInPropertyList(plist: *const SENSOR_PROPERTY_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> super::super::Foundation::BOOLEAN;
}
::core::mem::transmute(IsKeyPresentInPropertyList(::core::mem::transmute(plist), ::core::mem::transmute(pkey)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn IsSensorSubscribed<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(subscriptionlist: *const SENSOR_COLLECTION_LIST, currenttype: Param1) -> super::super::Foundation::BOOLEAN {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsSensorSubscribed(subscriptionlist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, currenttype: ::windows::core::GUID) -> super::super::Foundation::BOOLEAN;
}
::core::mem::transmute(IsSensorSubscribed(::core::mem::transmute(subscriptionlist), currenttype.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct LOCATION_DESIRED_ACCURACY(pub i32);
pub const LOCATION_DESIRED_ACCURACY_DEFAULT: LOCATION_DESIRED_ACCURACY = LOCATION_DESIRED_ACCURACY(0i32);
pub const LOCATION_DESIRED_ACCURACY_HIGH: LOCATION_DESIRED_ACCURACY = LOCATION_DESIRED_ACCURACY(1i32);
impl ::core::convert::From<i32> for LOCATION_DESIRED_ACCURACY {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for LOCATION_DESIRED_ACCURACY {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct LOCATION_POSITION_SOURCE(pub i32);
pub const LOCATION_POSITION_SOURCE_CELLULAR: LOCATION_POSITION_SOURCE = LOCATION_POSITION_SOURCE(0i32);
pub const LOCATION_POSITION_SOURCE_SATELLITE: LOCATION_POSITION_SOURCE = LOCATION_POSITION_SOURCE(1i32);
pub const LOCATION_POSITION_SOURCE_WIFI: LOCATION_POSITION_SOURCE = LOCATION_POSITION_SOURCE(2i32);
pub const LOCATION_POSITION_SOURCE_IPADDRESS: LOCATION_POSITION_SOURCE = LOCATION_POSITION_SOURCE(3i32);
pub const LOCATION_POSITION_SOURCE_UNKNOWN: LOCATION_POSITION_SOURCE = LOCATION_POSITION_SOURCE(4i32);
impl ::core::convert::From<i32> for LOCATION_POSITION_SOURCE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for LOCATION_POSITION_SOURCE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MAGNETOMETER_ACCURACY(pub i32);
pub const MagnetometerAccuracy_Unknown: MAGNETOMETER_ACCURACY = MAGNETOMETER_ACCURACY(0i32);
pub const MagnetometerAccuracy_Unreliable: MAGNETOMETER_ACCURACY = MAGNETOMETER_ACCURACY(1i32);
pub const MagnetometerAccuracy_Approximate: MAGNETOMETER_ACCURACY = MAGNETOMETER_ACCURACY(2i32);
pub const MagnetometerAccuracy_High: MAGNETOMETER_ACCURACY = MAGNETOMETER_ACCURACY(3i32);
impl ::core::convert::From<i32> for MAGNETOMETER_ACCURACY {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MAGNETOMETER_ACCURACY {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct MATRIX3X3 {
pub Anonymous: MATRIX3X3_0,
}
impl MATRIX3X3 {}
impl ::core::default::Default for MATRIX3X3 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for MATRIX3X3 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for MATRIX3X3 {}
unsafe impl ::windows::core::Abi for MATRIX3X3 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union MATRIX3X3_0 {
pub Anonymous1: MATRIX3X3_0_0,
pub Anonymous2: MATRIX3X3_0_1,
pub M: [f32; 9],
}
impl MATRIX3X3_0 {}
impl ::core::default::Default for MATRIX3X3_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for MATRIX3X3_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for MATRIX3X3_0 {}
unsafe impl ::windows::core::Abi for MATRIX3X3_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct MATRIX3X3_0_0 {
pub A11: f32,
pub A12: f32,
pub A13: f32,
pub A21: f32,
pub A22: f32,
pub A23: f32,
pub A31: f32,
pub A32: f32,
pub A33: f32,
}
impl MATRIX3X3_0_0 {}
impl ::core::default::Default for MATRIX3X3_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for MATRIX3X3_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous1_e__Struct").field("A11", &self.A11).field("A12", &self.A12).field("A13", &self.A13).field("A21", &self.A21).field("A22", &self.A22).field("A23", &self.A23).field("A31", &self.A31).field("A32", &self.A32).field("A33", &self.A33).finish()
}
}
impl ::core::cmp::PartialEq for MATRIX3X3_0_0 {
fn eq(&self, other: &Self) -> bool {
self.A11 == other.A11 && self.A12 == other.A12 && self.A13 == other.A13 && self.A21 == other.A21 && self.A22 == other.A22 && self.A23 == other.A23 && self.A31 == other.A31 && self.A32 == other.A32 && self.A33 == other.A33
}
}
impl ::core::cmp::Eq for MATRIX3X3_0_0 {}
unsafe impl ::windows::core::Abi for MATRIX3X3_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct MATRIX3X3_0_1 {
pub V1: VEC3D,
pub V2: VEC3D,
pub V3: VEC3D,
}
impl MATRIX3X3_0_1 {}
impl ::core::default::Default for MATRIX3X3_0_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for MATRIX3X3_0_1 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous2_e__Struct").field("V1", &self.V1).field("V2", &self.V2).field("V3", &self.V3).finish()
}
}
impl ::core::cmp::PartialEq for MATRIX3X3_0_1 {
fn eq(&self, other: &Self) -> bool {
self.V1 == other.V1 && self.V2 == other.V2 && self.V3 == other.V3
}
}
impl ::core::cmp::Eq for MATRIX3X3_0_1 {}
unsafe impl ::windows::core::Abi for MATRIX3X3_0_1 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MagnetometerAccuracy(pub i32);
pub const MAGNETOMETER_ACCURACY_UNKNOWN: MagnetometerAccuracy = MagnetometerAccuracy(0i32);
pub const MAGNETOMETER_ACCURACY_UNRELIABLE: MagnetometerAccuracy = MagnetometerAccuracy(1i32);
pub const MAGNETOMETER_ACCURACY_APPROXIMATE: MagnetometerAccuracy = MagnetometerAccuracy(2i32);
pub const MAGNETOMETER_ACCURACY_HIGH: MagnetometerAccuracy = MagnetometerAccuracy(3i32);
impl ::core::convert::From<i32> for MagnetometerAccuracy {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MagnetometerAccuracy {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PEDOMETER_STEP_TYPE(pub i32);
pub const PedometerStepType_Unknown: PEDOMETER_STEP_TYPE = PEDOMETER_STEP_TYPE(1i32);
pub const PedometerStepType_Walking: PEDOMETER_STEP_TYPE = PEDOMETER_STEP_TYPE(2i32);
pub const PedometerStepType_Running: PEDOMETER_STEP_TYPE = PEDOMETER_STEP_TYPE(4i32);
pub const PedometerStepType_Max: PEDOMETER_STEP_TYPE = PEDOMETER_STEP_TYPE(8i32);
pub const PedometerStepType_Force_Dword: PEDOMETER_STEP_TYPE = PEDOMETER_STEP_TYPE(-1i32);
impl ::core::convert::From<i32> for PEDOMETER_STEP_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PEDOMETER_STEP_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PEDOMETER_STEP_TYPE_COUNT(pub i32);
pub const PedometerStepTypeCount: PEDOMETER_STEP_TYPE_COUNT = PEDOMETER_STEP_TYPE_COUNT(3i32);
impl ::core::convert::From<i32> for PEDOMETER_STEP_TYPE_COUNT {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PEDOMETER_STEP_TYPE_COUNT {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PROXIMITY_TYPE(pub i32);
pub const ProximityType_ObjectProximity: PROXIMITY_TYPE = PROXIMITY_TYPE(0i32);
pub const ProximityType_HumanProximity: PROXIMITY_TYPE = PROXIMITY_TYPE(1i32);
pub const ProximityType_Force_Dword: PROXIMITY_TYPE = PROXIMITY_TYPE(-1i32);
impl ::core::convert::From<i32> for PROXIMITY_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PROXIMITY_TYPE {
type Abi = Self;
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetBool(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetBool(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut super::super::Foundation::BOOL) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetBool(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetDouble(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut f64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetDouble(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut f64) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetDouble(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetFileTime(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut super::super::Foundation::FILETIME) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetFileTime(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut super::super::Foundation::FILETIME) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetFileTime(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetFloat(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut f32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetFloat(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut f32) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetFloat(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetGuid(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut ::windows::core::GUID) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetGuid(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut ::windows::core::GUID) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetGuid(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetInt32(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut i32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetInt32(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut i32) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetInt32(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetInt64(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut i64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetInt64(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut i64) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetInt64(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetNthInt64(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, occurrence: u32, pretvalue: *mut i64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetNthInt64(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, occurrence: u32, pretvalue: *mut i64) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetNthInt64(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(occurrence), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetNthUlong(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, occurrence: u32, pretvalue: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetNthUlong(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, occurrence: u32, pretvalue: *mut u32) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetNthUlong(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(occurrence), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetNthUshort(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, occurrence: u32, pretvalue: *mut u16) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetNthUshort(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, occurrence: u32, pretvalue: *mut u16) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetNthUshort(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(occurrence), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetPropVariant<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, typecheck: Param2, pvalue: *mut super::super::System::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetPropVariant(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, typecheck: super::super::Foundation::BOOLEAN, pvalue: *mut ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetPropVariant(::core::mem::transmute(plist), ::core::mem::transmute(pkey), typecheck.into_param().abi(), ::core::mem::transmute(pvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetUlong(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetUlong(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut u32) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetUlong(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeyGetUshort(plist: *const SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut u16) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeyGetUshort(plist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pretvalue: *mut u16) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeyGetUshort(::core::mem::transmute(plist), ::core::mem::transmute(pkey), ::core::mem::transmute(pretvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropKeyFindKeySetPropVariant<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(plist: *mut SENSOR_COLLECTION_LIST, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, typecheck: Param2, pvalue: *const super::super::System::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropKeyFindKeySetPropVariant(plist: *mut ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, typecheck: super::super::Foundation::BOOLEAN, pvalue: *const ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> super::super::Foundation::NTSTATUS;
}
PropKeyFindKeySetPropVariant(::core::mem::transmute(plist), ::core::mem::transmute(pkey), typecheck.into_param().abi(), ::core::mem::transmute(pvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))]
#[inline]
pub unsafe fn PropVariantGetInformation(propvariantvalue: *const super::super::System::Com::StructuredStorage::PROPVARIANT, propvariantoffset: *mut u32, propvariantsize: *mut u32, propvariantpointer: *mut *mut ::core::ffi::c_void, remappedtype: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropVariantGetInformation(propvariantvalue: *const ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>, propvariantoffset: *mut u32, propvariantsize: *mut u32, propvariantpointer: *mut *mut ::core::ffi::c_void, remappedtype: *mut u32) -> super::super::Foundation::NTSTATUS;
}
PropVariantGetInformation(::core::mem::transmute(propvariantvalue), ::core::mem::transmute(propvariantoffset), ::core::mem::transmute(propvariantsize), ::core::mem::transmute(propvariantpointer), ::core::mem::transmute(remappedtype)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn PropertiesListCopy(target: *mut SENSOR_PROPERTY_LIST, source: *const SENSOR_PROPERTY_LIST) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropertiesListCopy(target: *mut SENSOR_PROPERTY_LIST, source: *const SENSOR_PROPERTY_LIST) -> super::super::Foundation::NTSTATUS;
}
PropertiesListCopy(::core::mem::transmute(target), ::core::mem::transmute(source)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn PropertiesListGetFillableCount(buffersizebytes: u32) -> u32 {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PropertiesListGetFillableCount(buffersizebytes: u32) -> u32;
}
::core::mem::transmute(PropertiesListGetFillableCount(::core::mem::transmute(buffersizebytes)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct QUATERNION {
pub X: f32,
pub Y: f32,
pub Z: f32,
pub W: f32,
}
impl QUATERNION {}
impl ::core::default::Default for QUATERNION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for QUATERNION {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("QUATERNION").field("X", &self.X).field("Y", &self.Y).field("Z", &self.Z).field("W", &self.W).finish()
}
}
impl ::core::cmp::PartialEq for QUATERNION {
fn eq(&self, other: &Self) -> bool {
self.X == other.X && self.Y == other.Y && self.Z == other.Z && self.W == other.W
}
}
impl ::core::cmp::Eq for QUATERNION {}
unsafe impl ::windows::core::Abi for QUATERNION {
type Abi = Self;
}
pub const SENSOR_CATEGORY_ALL: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc317c286_c468_4288_9975_d4c4587c442c);
pub const SENSOR_CATEGORY_BIOMETRIC: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca19690f_a2c7_477d_a99e_99ec6e2b5648);
pub const SENSOR_CATEGORY_ELECTRICAL: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb73fcd8_fc4a_483c_ac58_27b691c6beff);
pub const SENSOR_CATEGORY_ENVIRONMENTAL: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x323439aa_7f66_492b_ba0c_73e9aa0a65d5);
pub const SENSOR_CATEGORY_LIGHT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x17a665c0_9063_4216_b202_5c7a255e18ce);
pub const SENSOR_CATEGORY_LOCATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfa794e4_f964_4fdb_90f6_51056bfe4b44);
pub const SENSOR_CATEGORY_MECHANICAL: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8d131d68_8ef7_4656_80b5_cccbd93791c5);
pub const SENSOR_CATEGORY_MOTION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcd09daf1_3b2e_4c3d_b598_b5e5ff93fd46);
pub const SENSOR_CATEGORY_ORIENTATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e6c04b6_96fe_4954_b726_68682a473f69);
pub const SENSOR_CATEGORY_OTHER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2c90e7a9_f4c9_4fa2_af37_56d471fe5a3d);
pub const SENSOR_CATEGORY_SCANNER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb000e77e_f5b5_420f_815d_0270a726f270);
pub const SENSOR_CATEGORY_UNSUPPORTED: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2beae7fa_19b0_48c5_a1f6_b5480dc206b0);
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::clone::Clone for SENSOR_COLLECTION_LIST {
fn clone(&self) -> Self {
unimplemented!()
}
}
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
pub struct SENSOR_COLLECTION_LIST {
pub AllocatedSizeInBytes: u32,
pub Count: u32,
pub List: [SENSOR_VALUE_PAIR; 1],
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl SENSOR_COLLECTION_LIST {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::default::Default for SENSOR_COLLECTION_LIST {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::cmp::PartialEq for SENSOR_COLLECTION_LIST {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::cmp::Eq for SENSOR_COLLECTION_LIST {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
unsafe impl ::windows::core::Abi for SENSOR_COLLECTION_LIST {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SENSOR_CONNECTION_TYPES(pub i32);
pub const SensorConnectionType_Integrated: SENSOR_CONNECTION_TYPES = SENSOR_CONNECTION_TYPES(0i32);
pub const SensorConnectionType_Attached: SENSOR_CONNECTION_TYPES = SENSOR_CONNECTION_TYPES(1i32);
pub const SensorConnectionType_External: SENSOR_CONNECTION_TYPES = SENSOR_CONNECTION_TYPES(2i32);
impl ::core::convert::From<i32> for SENSOR_CONNECTION_TYPES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SENSOR_CONNECTION_TYPES {
type Abi = Self;
}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ABSOLUTE_PRESSURE_PASCAL: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ACCELERATION_X_G: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ACCELERATION_Y_G: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ACCELERATION_Z_G: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ADDRESS1: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 23u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ADDRESS2: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 24u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ALTITUDE_ANTENNA_SEALEVEL_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 36u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ALTITUDE_ELLIPSOID_ERROR_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 29u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ALTITUDE_ELLIPSOID_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ALTITUDE_SEALEVEL_ERROR_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 30u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ALTITUDE_SEALEVEL_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ANGULAR_ACCELERATION_X_DEGREES_PER_SECOND_SQUARED: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ANGULAR_ACCELERATION_Y_DEGREES_PER_SECOND_SQUARED: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 6u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ANGULAR_ACCELERATION_Z_DEGREES_PER_SECOND_SQUARED: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 7u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ANGULAR_VELOCITY_X_DEGREES_PER_SECOND: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5),
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Y_DEGREES_PER_SECOND: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5),
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Z_DEGREES_PER_SECOND: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5),
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ATMOSPHERIC_PRESSURE_BAR: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8b0aa2f1_2d57_42ee_8cc0_4d27622b46c4), pid: 4u32 };
pub const SENSOR_DATA_TYPE_BIOMETRIC_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2299288a_6d9e_4b0b_b7ec_3528f89e40af);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_BOOLEAN_SWITCH_ARRAY_STATES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df),
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_BOOLEAN_SWITCH_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CAPACITANCE_FARAD: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CITY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 25u32,
};
pub const SENSOR_DATA_TYPE_COMMON_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdb5e0cf2_cf1f_4c18_b46c_d86011d62150);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_COUNTRY_REGION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 28u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CURRENT_AMPS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_BOOLEAN_ARRAY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f), pid: 6u32 };
pub const SENSOR_DATA_TYPE_CUSTOM_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_USAGE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE1: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f), pid: 7u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE10: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 16u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE11: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 17u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE12: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 18u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE13: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE14: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 20u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE15: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 21u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE16: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 22u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE17: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 23u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE18: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 24u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE19: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 25u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE2: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE20: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 26u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE21: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 27u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE22: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 28u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE23: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 29u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE24: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 30u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE25: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 31u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE26: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 32u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE27: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 33u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE28: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 34u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE3: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f), pid: 9u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE4: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE5: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE6: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE7: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE8: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_CUSTOM_VALUE9: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0xb14c764f_07cf_41e8_9d82_ebe3d0776a6f),
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_DGPS_DATA_AGE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 35u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_DIFFERENTIAL_REFERENCE_STATION_ID: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 37u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_DISTANCE_X_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_DISTANCE_Y_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 9u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_DISTANCE_Z_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ELECTRICAL_FREQUENCY_HERTZ: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 9u32 };
pub const SENSOR_DATA_TYPE_ELECTRICAL_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ELECTRICAL_PERCENT_OF_RANGE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ELECTRICAL_POWER_WATTS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 7u32 };
pub const SENSOR_DATA_TYPE_ENVIRONMENTAL_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8b0aa2f1_2d57_42ee_8cc0_4d27622b46c4);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ERROR_RADIUS_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 22u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_FIX_QUALITY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_FIX_TYPE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_FORCE_NEWTONS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_GAUGE_PRESSURE_PASCAL: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 6u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_GEOIDAL_SEPARATION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 34u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_GPS_OPERATION_MODE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 32u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_GPS_SELECTION_MODE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 31u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_GPS_STATUS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 33u32,
};
pub const SENSOR_DATA_TYPE_GUID_MECHANICAL_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_HORIZONAL_DILUTION_OF_PRECISION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_HUMAN_PRESENCE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x2299288a_6d9e_4b0b_b7ec_3528f89e40af), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_HUMAN_PROXIMITY_METERS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x2299288a_6d9e_4b0b_b7ec_3528f89e40af), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_INDUCTANCE_HENRY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 6u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_LATITUDE_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_LIGHT_CHROMACITY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xe4c77ce2_dcb7_46e9_8439_4fec548833a6), pid: 4u32 };
pub const SENSOR_DATA_TYPE_LIGHT_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4c77ce2_dcb7_46e9_8439_4fec548833a6);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_LIGHT_LEVEL_LUX: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xe4c77ce2_dcb7_46e9_8439_4fec548833a6), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_LIGHT_TEMPERATURE_KELVIN: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xe4c77ce2_dcb7_46e9_8439_4fec548833a6), pid: 3u32 };
pub const SENSOR_DATA_TYPE_LOCATION_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_LOCATION_SOURCE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 40u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_LONGITUDE_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_FIELD_STRENGTH_X_MILLIGAUSS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_FIELD_STRENGTH_Y_MILLIGAUSS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 20u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_FIELD_STRENGTH_Z_MILLIGAUSS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 21u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_COMPENSATED_MAGNETIC_NORTH_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_COMPENSATED_TRUE_NORTH_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_MAGNETIC_NORTH_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_TRUE_NORTH_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_X_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_Y_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 6u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_HEADING_Z_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 7u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETIC_VARIATION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 9u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MAGNETOMETER_ACCURACY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 22u32,
};
pub const SENSOR_DATA_TYPE_MOTION_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MOTION_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 9u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_MULTIVALUE_SWITCH_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_NMEA_SENTENCE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 38u32,
};
pub const SENSOR_DATA_TYPE_ORIENTATION_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_POSITION_DILUTION_OF_PRECISION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_POSTALCODE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 27u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_QUADRANT_ANGLE_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_QUATERNION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 17u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_RELATIVE_HUMIDITY_PERCENT: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8b0aa2f1_2d57_42ee_8cc0_4d27622b46c4), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_RESISTANCE_OHMS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_RFID_TAG_40_BIT: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xd7a59a3c_3421_44ab_8d3a_9de8ab6c4cae), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_ROTATION_MATRIX: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 16u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_IN_VIEW: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 17u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_AZIMUTH: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 20u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_ELEVATION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_ID: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 39u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_PRNS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 18u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_IN_VIEW_STN_RATIO: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 21u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_USED_COUNT: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_USED_PRNS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 16u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SATELLITES_USED_PRNS_AND_CONSTELLATIONS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 41u32,
};
pub const SENSOR_DATA_TYPE_SCANNER_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd7a59a3c_3421_44ab_8d3a_9de8ab6c4cae);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SIMPLE_DEVICE_ORIENTATION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd),
pid: 18u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SPEED_KNOTS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 6u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_SPEED_METERS_PER_SECOND: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x3f8a69a2_07c5_4e48_a965_cd797aab56d5), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_STATE_PROVINCE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 26u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_STRAIN: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 7u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TEMPERATURE_CELSIUS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8b0aa2f1_2d57_42ee_8cc0_4d27622b46c4), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TILT_X_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TILT_Y_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TILT_Z_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x1637d8a2_4248_4275_865d_558de84aedfd), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TIMESTAMP: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xdb5e0cf2_cf1f_4c18_b46c_d86011d62150), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TOUCH_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x2299288a_6d9e_4b0b_b7ec_3528f89e40af), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_TRUE_HEADING_DEGREES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4), pid: 7u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_VERTICAL_DILUTION_OF_PRECISION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x055c74d8_ca6f_47d6_95c6_1ed3637a0ff4),
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_VOLTAGE_VOLTS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xbbb246d1_e242_4780_a2d3_cded84f35842), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_WEIGHT_KILOGRAMS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x38564a7c_f2f2_49bb_9b2b_ba60f66a58df), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_WIND_DIRECTION_DEGREES_ANTICLOCKWISE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8b0aa2f1_2d57_42ee_8cc0_4d27622b46c4), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_DATA_TYPE_WIND_SPEED_METERS_PER_SECOND: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8b0aa2f1_2d57_42ee_8cc0_4d27622b46c4), pid: 6u32 };
pub const SENSOR_ERROR_PARAMETER_COMMON_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x77112bcd_fce1_4f43_b8b8_a88256adb4b3);
pub const SENSOR_EVENT_ACCELEROMETER_SHAKE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x825f5a94_0f48_4396_9ca0_6ecb5c99d915);
pub const SENSOR_EVENT_DATA_UPDATED: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2ed0f2a4_0087_41d3_87db_6773370b3c88);
pub const SENSOR_EVENT_PARAMETER_COMMON_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64346e30_8728_4b34_bdf6_4f52442c5c28);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_EVENT_PARAMETER_EVENT_ID: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x64346e30_8728_4b34_bdf6_4f52442c5c28), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_EVENT_PARAMETER_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x64346e30_8728_4b34_bdf6_4f52442c5c28), pid: 3u32 };
pub const SENSOR_EVENT_PROPERTY_CHANGED: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2358f099_84c9_4d3d_90df_c2421e2b2045);
pub const SENSOR_EVENT_STATE_CHANGED: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfd96016_6bd7_4560_ad34_f2f6607e8f81);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_ACCURACY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 17u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_CHANGE_SENSITIVITY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 14u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_CLEAR_ASSISTANCE_DATA: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xe1e962f4_6e65_45f7_9c36_d487b7b1bd34), pid: 2u32 };
pub const SENSOR_PROPERTY_COMMON_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_CONNECTION_TYPE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 11u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 13u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_DESCRIPTION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 10u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_DEVICE_PATH: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 15u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_FRIENDLY_NAME: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 9u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_HID_USAGE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 22u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_LIGHT_RESPONSE_CURVE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 16u32,
};
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub struct SENSOR_PROPERTY_LIST {
pub AllocatedSizeInBytes: u32,
pub Count: u32,
pub List: [super::super::UI::Shell::PropertiesSystem::PROPERTYKEY; 1],
}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
impl SENSOR_PROPERTY_LIST {}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
impl ::core::default::Default for SENSOR_PROPERTY_LIST {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
impl ::core::fmt::Debug for SENSOR_PROPERTY_LIST {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SENSOR_PROPERTY_LIST").field("AllocatedSizeInBytes", &self.AllocatedSizeInBytes).field("Count", &self.Count).field("List", &self.List).finish()
}
}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
impl ::core::cmp::PartialEq for SENSOR_PROPERTY_LIST {
fn eq(&self, other: &Self) -> bool {
self.AllocatedSizeInBytes == other.AllocatedSizeInBytes && self.Count == other.Count && self.List == other.List
}
}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
impl ::core::cmp::Eq for SENSOR_PROPERTY_LIST {}
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
unsafe impl ::windows::core::Abi for SENSOR_PROPERTY_LIST {
type Abi = Self;
}
pub const SENSOR_PROPERTY_LIST_HEADER_SIZE: u32 = 8u32;
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_LOCATION_DESIRED_ACCURACY: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 19u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_MANUFACTURER: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 6u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_MIN_REPORT_INTERVAL: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 12u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_MODEL: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 7u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_PERSISTENT_UNIQUE_ID: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 5u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_RADIO_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 23u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_RADIO_STATE_PREVIOUS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 24u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_RANGE_MAXIMUM: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 21u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_RANGE_MINIMUM: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 20u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_RESOLUTION: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY {
fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920),
pid: 18u32,
};
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_SERIAL_NUMBER: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 8u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_STATE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 3u32 };
pub const SENSOR_PROPERTY_TEST_GUID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1e962f4_6e65_45f7_9c36_d487b7b1bd34);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_TURN_ON_OFF_NMEA: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0xe1e962f4_6e65_45f7_9c36_d487b7b1bd34), pid: 3u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const SENSOR_PROPERTY_TYPE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x7f8383ec_d3ec_495c_a8cf_b8bbe85c2920), pid: 2u32 };
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SENSOR_STATE(pub i32);
pub const SensorState_Initializing: SENSOR_STATE = SENSOR_STATE(0i32);
pub const SensorState_Idle: SENSOR_STATE = SENSOR_STATE(1i32);
pub const SensorState_Active: SENSOR_STATE = SENSOR_STATE(2i32);
pub const SensorState_Error: SENSOR_STATE = SENSOR_STATE(3i32);
impl ::core::convert::From<i32> for SENSOR_STATE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SENSOR_STATE {
type Abi = Self;
}
pub const SENSOR_TYPE_ACCELEROMETER_1D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc04d2387_7340_4cc2_991e_3b18cb8ef2f4);
pub const SENSOR_TYPE_ACCELEROMETER_2D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb2c517a8_f6b5_4ba6_a423_5df560b4cc07);
pub const SENSOR_TYPE_ACCELEROMETER_3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc2fb0f5f_e2d2_4c78_bcd0_352a9582819d);
pub const SENSOR_TYPE_AGGREGATED_DEVICE_ORIENTATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcdb5d8f7_3cfd_41c8_8542_cce622cf5d6e);
pub const SENSOR_TYPE_AGGREGATED_QUADRANT_ORIENTATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f81f1af_c4ab_4307_9904_c828bfb90829);
pub const SENSOR_TYPE_AGGREGATED_SIMPLE_DEVICE_ORIENTATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x86a19291_0482_402c_bf4c_addac52b1c39);
pub const SENSOR_TYPE_AMBIENT_LIGHT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x97f115c8_599a_4153_8894_d2d12899918a);
pub const SENSOR_TYPE_BARCODE_SCANNER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x990b3d8f_85bb_45ff_914d_998c04f372df);
pub const SENSOR_TYPE_BOOLEAN_SWITCH: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9c7e371f_1041_460b_8d5c_71e4752e350c);
pub const SENSOR_TYPE_BOOLEAN_SWITCH_ARRAY: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x545c8ba5_b143_4545_868f_ca7fd986b4f6);
pub const SENSOR_TYPE_CAPACITANCE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca2ffb1c_2317_49c0_a0b4_b63ce63461a0);
pub const SENSOR_TYPE_COMPASS_1D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa415f6c5_cb50_49d0_8e62_a8270bd7a26c);
pub const SENSOR_TYPE_COMPASS_2D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x15655cc0_997a_4d30_84db_57caba3648bb);
pub const SENSOR_TYPE_COMPASS_3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x76b5ce0d_17dd_414d_93a1_e127f40bdf6e);
pub const SENSOR_TYPE_CURRENT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5adc9fce_15a0_4bbe_a1ad_2d38a9ae831c);
pub const SENSOR_TYPE_CUSTOM: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe83af229_8640_4d18_a213_e22675ebb2c3);
pub const SENSOR_TYPE_DISTANCE_1D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f14ab2f_1407_4306_a93f_b1dbabe4f9c0);
pub const SENSOR_TYPE_DISTANCE_2D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5cf9a46c_a9a2_4e55_b6a1_a04aafa95a92);
pub const SENSOR_TYPE_DISTANCE_3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa20cae31_0e25_4772_9fe5_96608a1354b2);
pub const SENSOR_TYPE_ELECTRICAL_POWER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x212f10f5_14ab_4376_9a43_a7794098c2fe);
pub const SENSOR_TYPE_ENVIRONMENTAL_ATMOSPHERIC_PRESSURE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0e903829_ff8a_4a93_97df_3dcbde402288);
pub const SENSOR_TYPE_ENVIRONMENTAL_HUMIDITY: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5c72bf67_bd7e_4257_990b_98a3ba3b400a);
pub const SENSOR_TYPE_ENVIRONMENTAL_TEMPERATURE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x04fd0ec4_d5da_45fa_95a9_5db38ee19306);
pub const SENSOR_TYPE_ENVIRONMENTAL_WIND_DIRECTION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9ef57a35_9306_434d_af09_37fa5a9c00bd);
pub const SENSOR_TYPE_ENVIRONMENTAL_WIND_SPEED: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdd50607b_a45f_42cd_8efd_ec61761c4226);
pub const SENSOR_TYPE_FORCE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc2ab2b02_1a1c_4778_a81b_954a1788cc75);
pub const SENSOR_TYPE_FREQUENCY: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8cd2cbb6_73e6_4640_a709_72ae8fb60d7f);
pub const SENSOR_TYPE_GYROMETER_1D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfa088734_f552_4584_8324_edfaf649652c);
pub const SENSOR_TYPE_GYROMETER_2D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x31ef4f83_919b_48bf_8de0_5d7a9d240556);
pub const SENSOR_TYPE_GYROMETER_3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09485f5a_759e_42c2_bd4b_a349b75c8643);
pub const SENSOR_TYPE_HUMAN_PRESENCE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc138c12b_ad52_451c_9375_87f518ff10c6);
pub const SENSOR_TYPE_HUMAN_PROXIMITY: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5220dae9_3179_4430_9f90_06266d2a34de);
pub const SENSOR_TYPE_INCLINOMETER_1D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb96f98c5_7a75_4ba7_94e9_ac868c966dd8);
pub const SENSOR_TYPE_INCLINOMETER_2D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xab140f6d_83eb_4264_b70b_b16a5b256a01);
pub const SENSOR_TYPE_INCLINOMETER_3D: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb84919fb_ea85_4976_8444_6f6f5c6d31db);
pub const SENSOR_TYPE_INDUCTANCE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdc1d933f_c435_4c7d_a2fe_607192a524d3);
pub const SENSOR_TYPE_LOCATION_BROADCAST: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd26988cf_5162_4039_bb17_4c58b698e44a);
pub const SENSOR_TYPE_LOCATION_DEAD_RECKONING: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1a37d538_f28b_42da_9fce_a9d0a2a6d829);
pub const SENSOR_TYPE_LOCATION_GPS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed4ca589_327a_4ff9_a560_91da4b48275e);
pub const SENSOR_TYPE_LOCATION_LOOKUP: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3b2eae4a_72ce_436d_96d2_3c5b8570e987);
pub const SENSOR_TYPE_LOCATION_OTHER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b2d0566_0368_4f71_b88d_533f132031de);
pub const SENSOR_TYPE_LOCATION_STATIC: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x095f8184_0fa9_4445_8e6e_b70f320b6b4c);
pub const SENSOR_TYPE_LOCATION_TRIANGULATION: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x691c341a_5406_4fe1_942f_2246cbeb39e0);
pub const SENSOR_TYPE_MOTION_DETECTOR: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5c7c1a12_30a5_43b9_a4b2_cf09ec5b7be8);
pub const SENSOR_TYPE_MULTIVALUE_SWITCH: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb3ee4d76_37a4_4402_b25e_99c60a775fa1);
pub const SENSOR_TYPE_POTENTIOMETER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b3681a9_cadc_45aa_a6ff_54957c8bb440);
pub const SENSOR_TYPE_PRESSURE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x26d31f34_6352_41cf_b793_ea0713d53d77);
pub const SENSOR_TYPE_RESISTANCE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9993d2c8_c157_4a52_a7b5_195c76037231);
pub const SENSOR_TYPE_RFID_SCANNER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x44328ef5_02dd_4e8d_ad5d_9249832b2eca);
pub const SENSOR_TYPE_SCALE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc06dd92c_7feb_438e_9bf6_82207fff5bb8);
pub const SENSOR_TYPE_SPEEDOMETER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6bd73c1f_0bb4_4310_81b2_dfc18a52bf94);
pub const SENSOR_TYPE_STRAIN: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6d1ec0e_6803_4361_ad3d_85bcc58c6d29);
pub const SENSOR_TYPE_TOUCH: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x17db3018_06c4_4f7d_81af_9274b7599c27);
pub const SENSOR_TYPE_UNKNOWN: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10ba83e3_ef4f_41ed_9885_a87d6435a8e1);
pub const SENSOR_TYPE_VOLTAGE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc5484637_4fb7_4953_98b8_a56d8aa1fb1e);
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::clone::Clone for SENSOR_VALUE_PAIR {
fn clone(&self) -> Self {
unimplemented!()
}
}
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
pub struct SENSOR_VALUE_PAIR {
pub Key: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY,
pub Value: super::super::System::Com::StructuredStorage::PROPVARIANT,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl SENSOR_VALUE_PAIR {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::default::Default for SENSOR_VALUE_PAIR {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::cmp::PartialEq for SENSOR_VALUE_PAIR {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
impl ::core::cmp::Eq for SENSOR_VALUE_PAIR {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
unsafe impl ::windows::core::Abi for SENSOR_VALUE_PAIR {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SIMPLE_DEVICE_ORIENTATION(pub i32);
pub const SimpleDeviceOrientation_NotRotated: SIMPLE_DEVICE_ORIENTATION = SIMPLE_DEVICE_ORIENTATION(0i32);
pub const SimpleDeviceOrientation_Rotated90DegreesCounterclockwise: SIMPLE_DEVICE_ORIENTATION = SIMPLE_DEVICE_ORIENTATION(1i32);
pub const SimpleDeviceOrientation_Rotated180DegreesCounterclockwise: SIMPLE_DEVICE_ORIENTATION = SIMPLE_DEVICE_ORIENTATION(2i32);
pub const SimpleDeviceOrientation_Rotated270DegreesCounterclockwise: SIMPLE_DEVICE_ORIENTATION = SIMPLE_DEVICE_ORIENTATION(3i32);
pub const SimpleDeviceOrientation_Faceup: SIMPLE_DEVICE_ORIENTATION = SIMPLE_DEVICE_ORIENTATION(4i32);
pub const SimpleDeviceOrientation_Facedown: SIMPLE_DEVICE_ORIENTATION = SIMPLE_DEVICE_ORIENTATION(5i32);
impl ::core::convert::From<i32> for SIMPLE_DEVICE_ORIENTATION {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SIMPLE_DEVICE_ORIENTATION {
type Abi = Self;
}
pub const Sensor: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe97ced00_523a_4133_bf6f_d3a2dae7f6ba);
pub const SensorCollection: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79c43adb_a429_469f_aa39_2f2b74b75937);
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))]
#[inline]
pub unsafe fn SensorCollectionGetAt(index: u32, psensorslist: *const SENSOR_COLLECTION_LIST, pkey: *mut super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pvalue: *mut super::super::System::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SensorCollectionGetAt(index: u32, psensorslist: *const ::core::mem::ManuallyDrop<SENSOR_COLLECTION_LIST>, pkey: *mut super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, pvalue: *mut ::core::mem::ManuallyDrop<super::super::System::Com::StructuredStorage::PROPVARIANT>) -> super::super::Foundation::NTSTATUS;
}
SensorCollectionGetAt(::core::mem::transmute(index), ::core::mem::transmute(psensorslist), ::core::mem::transmute(pkey), ::core::mem::transmute(pvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SensorConnectionType(pub i32);
pub const SENSOR_CONNECTION_TYPE_PC_INTEGRATED: SensorConnectionType = SensorConnectionType(0i32);
pub const SENSOR_CONNECTION_TYPE_PC_ATTACHED: SensorConnectionType = SensorConnectionType(1i32);
pub const SENSOR_CONNECTION_TYPE_PC_EXTERNAL: SensorConnectionType = SensorConnectionType(2i32);
impl ::core::convert::From<i32> for SensorConnectionType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SensorConnectionType {
type Abi = Self;
}
pub const SensorDataReport: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4ea9d6ef_694b_4218_8816_ccda8da74bba);
pub const SensorManager: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x77a1c827_fcd2_4689_8915_9d613cc5fa3e);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SensorState(pub i32);
pub const SENSOR_STATE_MIN: SensorState = SensorState(0i32);
pub const SENSOR_STATE_READY: SensorState = SensorState(0i32);
pub const SENSOR_STATE_NOT_AVAILABLE: SensorState = SensorState(1i32);
pub const SENSOR_STATE_NO_DATA: SensorState = SensorState(2i32);
pub const SENSOR_STATE_INITIALIZING: SensorState = SensorState(3i32);
pub const SENSOR_STATE_ACCESS_DENIED: SensorState = SensorState(4i32);
pub const SENSOR_STATE_ERROR: SensorState = SensorState(5i32);
pub const SENSOR_STATE_MAX: SensorState = SensorState(5i32);
impl ::core::convert::From<i32> for SensorState {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SensorState {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn SerializationBufferAllocate(sizeinbytes: u32, pbuffer: *mut *mut u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SerializationBufferAllocate(sizeinbytes: u32, pbuffer: *mut *mut u8) -> super::super::Foundation::NTSTATUS;
}
SerializationBufferAllocate(::core::mem::transmute(sizeinbytes), ::core::mem::transmute(pbuffer)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn SerializationBufferFree(buffer: *const u8) {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SerializationBufferFree(buffer: *const u8);
}
::core::mem::transmute(SerializationBufferFree(::core::mem::transmute(buffer)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SimpleDeviceOrientation(pub i32);
pub const SIMPLE_DEVICE_ORIENTATION_NOT_ROTATED: SimpleDeviceOrientation = SimpleDeviceOrientation(0i32);
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_90: SimpleDeviceOrientation = SimpleDeviceOrientation(1i32);
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_180: SimpleDeviceOrientation = SimpleDeviceOrientation(2i32);
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_270: SimpleDeviceOrientation = SimpleDeviceOrientation(3i32);
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_FACE_UP: SimpleDeviceOrientation = SimpleDeviceOrientation(4i32);
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_FACE_DOWN: SimpleDeviceOrientation = SimpleDeviceOrientation(5i32);
impl ::core::convert::From<i32> for SimpleDeviceOrientation {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SimpleDeviceOrientation {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VEC3D {
pub X: f32,
pub Y: f32,
pub Z: f32,
}
impl VEC3D {}
impl ::core::default::Default for VEC3D {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VEC3D {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("VEC3D").field("X", &self.X).field("Y", &self.Y).field("Z", &self.Z).finish()
}
}
impl ::core::cmp::PartialEq for VEC3D {
fn eq(&self, other: &Self) -> bool {
self.X == other.X && self.Y == other.Y && self.Z == other.Z
}
}
impl ::core::cmp::Eq for VEC3D {}
unsafe impl ::windows::core::Abi for VEC3D {
type Abi = Self;
}
|
use std::collections::HashSet;
use std::error;
type Error = Box<dyn error::Error>;
macro_rules! error {
($fmt:literal $(, $e:expr)*) => { Err(Error::from(format!($fmt $(, $e)*))) };
}
fn main() -> Result<(), Error> {
for filename in std::env::args().skip(1) {
println!("{}", filename);
let bootcode = parse_bootcode(&std::fs::read_to_string(filename)?)?;
println!("\tpart 1: value of accelerator when code loops for the first time");
println!("\t{}", part1(&bootcode)?);
println!("\tpart 2: value of accelerator when patched code exits cleanly");
println!("\t{}", part2(bootcode)?);
}
Ok(())
}
fn part1(bootcode: &BootCode) -> Result<i32, Error> {
match simulate(bootcode) {
Ok(_) => error!("Expected code to loop, but exited cleanly"),
Err(n) => Ok(n),
}
}
fn part2(mut bootcode: BootCode) -> Result<i32, Error> {
for ix in 0..bootcode.len() {
let (orig, repl) = match bootcode[ix] {
(Acc, _) => continue,
(Jmp, _) => (Jmp, Nop),
(Nop, _) => (Nop, Jmp),
};
bootcode[ix].0 = repl;
match simulate(&bootcode) {
Err(_) => bootcode[ix].0 = orig,
Ok(n) => return Ok(n),
}
}
error!("Expected a patch to exist, but code never exited cleanly")
}
fn simulate(bootcode: &BootCode) -> Result<i32, i32> {
let mut visited = HashSet::new();
let mut acc = 0;
let mut ix = 0;
while (0..bootcode.len() as i32).contains(&ix) {
if visited.contains(&ix) {
return Err(acc);
}
visited.insert(ix);
match bootcode[ix as usize] {
(Acc, arg) => {
acc += arg;
ix += 1
}
(Jmp, arg) => ix += arg,
(Nop, _arg) => ix += 1,
}
}
return Ok(acc);
}
type BootCode = Vec<Instruction>;
type Instruction = (Operation, i32);
enum Operation {
Acc,
Jmp,
Nop,
}
use Operation::*;
fn parse_bootcode(src: &str) -> Result<BootCode, Error> {
src.lines().map(parse_instruction).collect()
}
fn parse_instruction(src: &str) -> Result<Instruction, Error> {
let (op, arg) = match src.split(" ").collect::<Vec<&str>>()[..] {
[op, arg] => Ok((op, arg)),
_ => error!("Malformed instruction: {:?}", src),
}?;
let op = match op {
"acc" => Ok(Acc),
"jmp" => Ok(Jmp),
"nop" => Ok(Nop),
op => error!("Unrecognized operation: {:?}", op),
}?;
let arg = arg.parse().expect("positive or negative integer");
Ok((op, arg))
}
|
fn part1(input: &str) -> i32 {
input.lines().filter(|line| nice(line)).count() as i32
}
fn nice(string: &str) -> bool {
let mut wovel_count = 0;
let mut prev = '\0';
let mut twice_row = false;
let mut contains_naughty = false;
for ch in string.chars() {
match ch {
'a' | 'e' | 'i' | 'o' | 'u' => wovel_count += 1,
_ => {}
}
if ch == prev {
twice_row = true;
}
if (prev == 'a' && ch == 'b')
|| (prev == 'c' && ch == 'd')
|| (prev == 'p' && ch == 'q')
|| (prev == 'x' && ch == 'y')
{
contains_naughty = true;
}
// Finally
prev = ch;
}
wovel_count >= 3 && twice_row && !contains_naughty
}
fn nice2(string: &str) -> bool {
use std::collections::HashMap;
type Pair = (char, char);
let mut last_pair: Option<Pair> = None;
let mut pair_counts = HashMap::<Pair, i32>::new();
let mut prev_ch = None;
let mut contains_repeating_letter_one_between = false;
for ch in string.chars() {
if let Some(prev) = prev_ch {
let pair = (prev, ch);
let consider_pair;
match last_pair {
Some(last_pair) => {
// Overlapping, don't consider this a pair?
if last_pair == pair {
consider_pair = false;
} else {
consider_pair = true;
}
// Check if there is repeating
if last_pair.0 == ch {
contains_repeating_letter_one_between = true;
}
}
// Can't be overlapping, no previous pair
None => consider_pair = true,
}
if consider_pair {
*pair_counts.entry(pair).or_insert(0) += 1;
last_pair = Some(pair);
} else {
last_pair = None;
}
}
prev_ch = Some(ch);
}
let contains_nonoverlapping_pair = pair_counts.iter().any(|(_k, &v)| v > 1);
contains_nonoverlapping_pair && contains_repeating_letter_one_between
}
fn part2(input: &str) -> i32 {
input.lines().filter(|line| nice2(line)).count() as i32
}
aoc::tests! {
fn nice:
"ugknbfddgicrmopn" => true;
"aaa" => true;
"jchzalrnumimnmhp" => false;
"haegwjzuvuyypxyu" => false;
"dvszwmarrgswjxmb" => false;
fn part1:
in => 236;
fn nice2:
"qjhvhtzxzqqjkmpb" => true;
"xxyxx" => true;
"uurcxstgmygtbstg" => false;
"ieodomkazucvgmuy" => false;
"xxx" => false; // Teddy :3
"yyyy" => true; // Teddy 2 :3
fn part2:
in => 51;
}
aoc::main!(part1, part2);
|
use serde_derive::{Deserialize, Serialize};
#[cfg(not(windows))]
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
mod addons;
mod tokens;
mod wow;
use crate::{error::ClientError, Result};
pub use crate::config::addons::Addons;
pub use crate::config::tokens::Tokens;
pub use crate::config::wow::{Flavor, Wow};
/// Config struct.
#[derive(Deserialize, Serialize, Debug, PartialEq, Default, Clone)]
pub struct Config {
#[serde(default)]
pub wow: Wow,
#[serde(default)]
pub addons: Addons,
#[serde(default)]
pub tokens: Tokens,
}
impl Config {
/// Returns a `Option<PathBuf>` to the directory containing the addons.
/// This will return `None` if no `wow_directory` is set in the config.
pub fn get_addon_directory(&self) -> Option<PathBuf> {
match self.wow.directory.clone() {
Some(dir) => {
// We prepend and append `_` to the formatted_client_flavor so it
// either becomes _retail_, or _classic_.
let formatted_client_flavor = format!("_{}_", self.wow.flavor.to_string());
// The path to the directory containing the addons
Some(dir.join(formatted_client_flavor).join("Interface/AddOns"))
}
None => None,
}
}
/// Returns a `Option<PathBuf>` to the directory which will hold the
/// temporary zip archives.
/// For now it will use the parent of the Addons folder.
/// This will return `None` if no `wow_directory` is set in the config.
pub fn get_temporary_addon_directory(&self) -> Option<PathBuf> {
match self.get_addon_directory() {
Some(dir) => {
// The path to the directory which hold the temporary zip archives
let dir = dir.parent().expect("Expected Addons folder has a parent.");
Some(dir.to_path_buf())
}
None => None,
}
}
}
/// Creates file at location, and copies default `Config` into it.
/// This is used if user does not have a config file, Ajour will
/// autogenerate it.
fn create_default_config<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
// Ensure we have folders created for the file.
let parent = path.as_ref().parent().expect("parent for config not found");
fs::create_dir_all(parent)?;
// Create the config file.
fs::File::create(&path)?;
// Default serialized config content.
let config = Config::default();
let default_config_content = serde_yaml::to_string(&config)?;
// Write to config.
fs::write(&path, &default_config_content)?;
Ok(path.as_ref().to_path_buf())
}
/// Returns the location of the first found config file paths
/// according to the following order:
///
/// 1. $HOME/.config/ajour/ajour.yml
/// 2. $HOME/.ajour.yml
#[cfg(not(windows))]
pub fn find_or_create_config() -> Result<PathBuf> {
let home = env::var("HOME").expect("user home directory not found.");
// Primary location path: $HOME/.config/ajour/ajour.yml.
let pri_location = PathBuf::from(&home).join(".config/ajour/ajour.yml");
if pri_location.exists() {
return Ok(pri_location);
}
// Secondary location path: $HOME/.ajour.yml.
let sec_location = PathBuf::from(&home).join(".ajour.yml");
if sec_location.exists() {
return Ok(sec_location);
}
// If no configuration file found, we create it.
Ok(create_default_config(&pri_location)?)
}
/// Returns the location of the first found config file paths
/// according to the following order:
///
/// 1. %APPDATA%\ajour\ajour.yml
/// 2. In the same directory as the executable
#[cfg(windows)]
pub fn find_or_create_config() -> Result<PathBuf> {
// Primary location path: %APPDATA%\ajour\ajour.yml.
let pri_location = dirs::config_dir()
.map(|path| path.join("ajour\\ajour.yml"))
.expect("user home directory not found.");
if pri_location.exists() {
return Ok(pri_location);
}
// Secondary location path: relative to the executable.
let sec_location = std::env::current_exe();
if let Ok(sec_location) = sec_location.as_ref().map(|p| p.parent()) {
if let Some(sec_location) = sec_location.map(|f| f.join("ajour.yml")) {
if sec_location.exists() {
return Ok(sec_location);
}
}
}
// If no configuration file found, we create it.
Ok(create_default_config(&pri_location)?)
}
/// Returns the config after the content of the file
/// has been read and correctly parsed.
fn parse_config(path: &PathBuf) -> Result<Config> {
let contents = fs::read_to_string(path)?;
match serde_yaml::from_str(&contents) {
Err(error) => {
// Prevent parsing error with an empty string and commented out file.
if error.to_string() == "EOF while parsing a value" {
Ok(Config::default())
} else {
Err(ClientError::YamlError(error))
}
}
Ok(config) => Ok(config),
}
}
/// This function will save the current `Config` to disk.
/// This is used if we have updated the `Config` from the application,
/// and want to make sure it persist.
pub fn persist_config(config: &Config) -> Result<()> {
// Find the used config.
let path = find_or_create_config()?;
// Serialize the config
let default_config_content = serde_yaml::to_string(config)?;
// Write to config.
fs::write(&path, &default_config_content)?;
Ok(())
}
/// Returns a Config.
///
/// This functions handles the initialization of a Config.
pub async fn load_config() -> Result<Config> {
let path = find_or_create_config()?;
Ok(parse_config(&path)?)
}
|
pub use crate::errors::*;
const DEFAULT_FETCH_SIZE: usize = 200;
const DEFAULT_MAX_CONNECTIONS: usize = 16;
/// The configuration used to connect to the database, see [`Graph::connect`]
#[derive(Debug, Clone)]
pub struct Config {
pub(crate) uri: String,
pub(crate) user: String,
pub(crate) password: String,
pub(crate) max_connections: usize,
pub(crate) db: String,
pub(crate) fetch_size: usize,
}
/// A builder to override default configurations and build the [`Config`]
pub struct ConfigBuilder {
uri: Option<String>,
user: Option<String>,
password: Option<String>,
db: Option<String>,
fetch_size: Option<usize>,
max_connections: Option<usize>,
}
impl ConfigBuilder {
///the uri of the neo4j server
pub fn uri(mut self, uri: &str) -> Self {
self.uri = Some(uri.to_owned());
self
}
///username for authentication
pub fn user(mut self, user: &str) -> Self {
self.user = Some(user.to_owned());
self
}
///password for authentication
pub fn password(mut self, password: &str) -> Self {
self.password = Some(password.to_owned());
self
}
///the name of the database, defaults to "neo4j" if not configured.
pub fn db(mut self, db: &str) -> Self {
self.db = Some(db.to_owned());
self
}
///fetch_size indicates the number of rows to fetch from server in one request, it is
///recommended to use a large fetch_size if you are working with large data sets.
///default fetch_size is 200
pub fn fetch_size(mut self, fetch_size: usize) -> Self {
self.fetch_size = Some(fetch_size);
self
}
///maximum number of connections in the connection pool
pub fn max_connections(mut self, max_connections: usize) -> Self {
self.max_connections = Some(max_connections);
self
}
pub fn build(self) -> Result<Config> {
if self.uri.is_none()
|| self.user.is_none()
|| self.password.is_none()
|| self.fetch_size.is_none()
|| self.max_connections.is_none()
|| self.db.is_none()
{
Err(Error::InvalidConfig("a config field was None".into()))
} else {
//The config attributes are validated before unwrapping
Ok(Config {
uri: self.uri.unwrap(),
user: self.user.unwrap(),
password: self.password.unwrap(),
fetch_size: self.fetch_size.unwrap(),
max_connections: self.max_connections.unwrap(),
db: self.db.unwrap(),
})
}
}
}
/// Creates a config builder with reasonable default values wherever appropriate.
pub fn config() -> ConfigBuilder {
ConfigBuilder {
uri: None,
user: None,
password: None,
db: Some("".to_owned()),
max_connections: Some(DEFAULT_MAX_CONNECTIONS),
fetch_size: Some(DEFAULT_FETCH_SIZE),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn should_build_config() {
let config = config()
.uri("127.0.0.1:7687")
.user("some_user")
.password("some_password")
.db("some_db")
.fetch_size(10)
.max_connections(5)
.build()
.unwrap();
assert_eq!(config.uri, "127.0.0.1:7687");
assert_eq!(config.user, "some_user");
assert_eq!(config.password, "some_password");
assert_eq!(config.db, "some_db");
assert_eq!(config.fetch_size, 10);
assert_eq!(config.max_connections, 5);
}
#[tokio::test]
async fn should_build_with_defaults() {
let config = config()
.uri("127.0.0.1:7687")
.user("some_user")
.password("some_password")
.build()
.unwrap();
assert_eq!(config.uri, "127.0.0.1:7687");
assert_eq!(config.user, "some_user");
assert_eq!(config.password, "some_password");
assert_eq!(config.db, "");
assert_eq!(config.fetch_size, 200);
assert_eq!(config.max_connections, 16);
}
#[tokio::test]
async fn should_reject_invalid_config() {
assert!(config()
.user("some_user")
.password("some_password")
.build()
.is_err());
assert!(config()
.uri("127.0.0.1:7687")
.password("some_password")
.build()
.is_err());
assert!(config()
.uri("127.0.0.1:7687")
.user("some_user")
.build()
.is_err());
}
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Activate QSPI interface"]
pub tasks_activate: TASKS_ACTIVATE,
#[doc = "0x04 - Start transfer from external flash memory to internal RAM"]
pub tasks_readstart: TASKS_READSTART,
#[doc = "0x08 - Start transfer from internal RAM to external flash memory"]
pub tasks_writestart: TASKS_WRITESTART,
#[doc = "0x0c - Start external flash memory erase operation"]
pub tasks_erasestart: TASKS_ERASESTART,
#[doc = "0x10 - Deactivate QSPI interface"]
pub tasks_deactivate: TASKS_DEACTIVATE,
_reserved5: [u8; 236usize],
#[doc = "0x100 - QSPI peripheral is ready. This event will be generated as a response to any QSPI task."]
pub events_ready: EVENTS_READY,
_reserved6: [u8; 508usize],
#[doc = "0x300 - Enable or disable interrupt"]
pub inten: INTEN,
#[doc = "0x304 - Enable interrupt"]
pub intenset: INTENSET,
#[doc = "0x308 - Disable interrupt"]
pub intenclr: INTENCLR,
_reserved9: [u8; 500usize],
#[doc = "0x500 - Enable QSPI peripheral and acquire the pins selected in PSELn registers"]
pub enable: ENABLE,
#[doc = "0x504 - Unspecified"]
pub read: READ,
#[doc = "0x510 - Unspecified"]
pub write: WRITE,
#[doc = "0x51c - Unspecified"]
pub erase: ERASE,
#[doc = "0x524 - Unspecified"]
pub psel: PSEL,
#[doc = "0x540 - Address offset into the external memory for Execute in Place operation."]
pub xipoffset: XIPOFFSET,
#[doc = "0x544 - Interface configuration."]
pub ifconfig0: IFCONFIG0,
_reserved16: [u8; 184usize],
#[doc = "0x600 - Interface configuration."]
pub ifconfig1: IFCONFIG1,
#[doc = "0x604 - Status register."]
pub status: STATUS,
_reserved18: [u8; 12usize],
#[doc = "0x614 - Set the duration required to enter/exit deep power-down mode (DPM)."]
pub dpmdur: DPMDUR,
_reserved19: [u8; 12usize],
#[doc = "0x624 - Extended address configuration."]
pub addrconf: ADDRCONF,
_reserved20: [u8; 12usize],
#[doc = "0x634 - Custom instruction configuration register."]
pub cinstrconf: CINSTRCONF,
#[doc = "0x638 - Custom instruction data register 0."]
pub cinstrdat0: CINSTRDAT0,
#[doc = "0x63c - Custom instruction data register 1."]
pub cinstrdat1: CINSTRDAT1,
#[doc = "0x640 - SPI interface timing."]
pub iftiming: IFTIMING,
}
#[doc = r" Register block"]
#[repr(C)]
pub struct READ {
#[doc = "0x00 - Flash memory source address"]
pub src: self::read::SRC,
#[doc = "0x04 - RAM destination address"]
pub dst: self::read::DST,
#[doc = "0x08 - Read transfer length"]
pub cnt: self::read::CNT,
}
#[doc = r" Register block"]
#[doc = "Unspecified"]
pub mod read;
#[doc = r" Register block"]
#[repr(C)]
pub struct WRITE {
#[doc = "0x00 - Flash destination address"]
pub dst: self::write::DST,
#[doc = "0x04 - RAM source address"]
pub src: self::write::SRC,
#[doc = "0x08 - Write transfer length"]
pub cnt: self::write::CNT,
}
#[doc = r" Register block"]
#[doc = "Unspecified"]
pub mod write;
#[doc = r" Register block"]
#[repr(C)]
pub struct ERASE {
#[doc = "0x00 - Start address of flash block to be erased"]
pub ptr: self::erase::PTR,
#[doc = "0x04 - Size of block to be erased."]
pub len: self::erase::LEN,
}
#[doc = r" Register block"]
#[doc = "Unspecified"]
pub mod erase;
#[doc = r" Register block"]
#[repr(C)]
pub struct PSEL {
#[doc = "0x00 - Pin select for serial clock SCK"]
pub sck: self::psel::SCK,
#[doc = "0x04 - Pin select for chip select signal CSN."]
pub csn: self::psel::CSN,
_reserved2: [u8; 4usize],
#[doc = "0x0c - Pin select for serial data MOSI/IO0."]
pub io0: self::psel::IO0,
#[doc = "0x10 - Pin select for serial data MISO/IO1."]
pub io1: self::psel::IO1,
#[doc = "0x14 - Pin select for serial data IO2."]
pub io2: self::psel::IO2,
#[doc = "0x18 - Pin select for serial data IO3."]
pub io3: self::psel::IO3,
}
#[doc = r" Register block"]
#[doc = "Unspecified"]
pub mod psel;
#[doc = "Activate QSPI interface"]
pub struct TASKS_ACTIVATE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Activate QSPI interface"]
pub mod tasks_activate;
#[doc = "Start transfer from external flash memory to internal RAM"]
pub struct TASKS_READSTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start transfer from external flash memory to internal RAM"]
pub mod tasks_readstart;
#[doc = "Start transfer from internal RAM to external flash memory"]
pub struct TASKS_WRITESTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start transfer from internal RAM to external flash memory"]
pub mod tasks_writestart;
#[doc = "Start external flash memory erase operation"]
pub struct TASKS_ERASESTART {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start external flash memory erase operation"]
pub mod tasks_erasestart;
#[doc = "Deactivate QSPI interface"]
pub struct TASKS_DEACTIVATE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Deactivate QSPI interface"]
pub mod tasks_deactivate;
#[doc = "QSPI peripheral is ready. This event will be generated as a response to any QSPI task."]
pub struct EVENTS_READY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "QSPI peripheral is ready. This event will be generated as a response to any QSPI task."]
pub mod events_ready;
#[doc = "Enable or disable interrupt"]
pub struct INTEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable or disable interrupt"]
pub mod inten;
#[doc = "Enable interrupt"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable interrupt"]
pub mod intenset;
#[doc = "Disable interrupt"]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Disable interrupt"]
pub mod intenclr;
#[doc = "Enable QSPI peripheral and acquire the pins selected in PSELn registers"]
pub struct ENABLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable QSPI peripheral and acquire the pins selected in PSELn registers"]
pub mod enable;
#[doc = "Address offset into the external memory for Execute in Place operation."]
pub struct XIPOFFSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Address offset into the external memory for Execute in Place operation."]
pub mod xipoffset;
#[doc = "Interface configuration."]
pub struct IFCONFIG0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interface configuration."]
pub mod ifconfig0;
#[doc = "Interface configuration."]
pub struct IFCONFIG1 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interface configuration."]
pub mod ifconfig1;
#[doc = "Status register."]
pub struct STATUS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Status register."]
pub mod status;
#[doc = "Set the duration required to enter/exit deep power-down mode (DPM)."]
pub struct DPMDUR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Set the duration required to enter/exit deep power-down mode (DPM)."]
pub mod dpmdur;
#[doc = "Extended address configuration."]
pub struct ADDRCONF {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Extended address configuration."]
pub mod addrconf;
#[doc = "Custom instruction configuration register."]
pub struct CINSTRCONF {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Custom instruction configuration register."]
pub mod cinstrconf;
#[doc = "Custom instruction data register 0."]
pub struct CINSTRDAT0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Custom instruction data register 0."]
pub mod cinstrdat0;
#[doc = "Custom instruction data register 1."]
pub struct CINSTRDAT1 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Custom instruction data register 1."]
pub mod cinstrdat1;
#[doc = "SPI interface timing."]
pub struct IFTIMING {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "SPI interface timing."]
pub mod iftiming;
|
extern crate corrosion;
use corrosion::PlayerAction;
use corrosion::utility::*;
/// Tests passing of priority and turn cycling. Currently assumes only one
/// phase.
#[test]
fn test_priority() {
let mut game = new_two_player_game();
let player1_id = game.player_turn_order[0];
let player2_id = game.player_turn_order[1];
assert_eq!(game.active_player, Some(player1_id));
assert_eq!(game.priority_player, Some(player1_id));
game.do_player_action(player1_id, &PlayerAction::PassPriority).unwrap();
assert_eq!(game.active_player, Some(player1_id));
assert_eq!(game.priority_player, Some(player2_id));
game.do_player_action(player2_id, &PlayerAction::PassPriority).unwrap();
assert_eq!(game.active_player, Some(player2_id));
assert_eq!(game.priority_player, Some(player2_id));
game.do_player_action(player2_id, &PlayerAction::PassPriority).unwrap();
assert_eq!(game.active_player, Some(player2_id));
assert_eq!(game.priority_player, Some(player1_id));
game.do_player_action(player1_id, &PlayerAction::PassPriority).unwrap();
assert_eq!(game.active_player, Some(player1_id));
assert_eq!(game.priority_player, Some(player1_id));
}
|
use std::convert::AsRef;
#[derive(Debug, PartialEq, Eq)]
pub struct RibonucleicAcid {
rna_string: String,
}
impl RibonucleicAcid {
pub fn new(rna_string: &str) -> Self {
RibonucleicAcid { rna_string: rna_string.to_string() }
}
}
impl AsRef<str> for RibonucleicAcid {
fn as_ref(&self) -> &str {
self.rna_string.as_ref()
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct DeoxyribonucleicAcid {
dna_string: String,
}
impl DeoxyribonucleicAcid {
pub fn new(dna_string: &str) -> Self {
DeoxyribonucleicAcid { dna_string: dna_string.to_string() }
}
pub fn to_rna(&self) -> RibonucleicAcid {
let mut transcribed = String::new();
for c in self.dna_string.chars() {
let next = match c {
'G' => 'C',
'C' => 'G',
'T' => 'A',
'A' => 'U',
_ => 'C',
};
transcribed.push(next);
}
RibonucleicAcid::new(&transcribed)
}
}
|
#[macro_use]
extern crate failure;
use failure::{err_msg, Error, Fail};
#[derive(Debug, Fail)]
#[fail(display = "my wrapping error")]
struct WrappingError(#[fail(cause)] Error);
fn bad_function() -> Result<(), WrappingError> {
Err(WrappingError(err_msg("this went bad")))
}
fn main() {
for cause in Fail::iter_causes(&bad_function().unwrap_err()) {
println!("{}", cause);
}
}
|
mod with_proper_list_options;
use std::sync::Arc;
use proptest::strategy::{BoxedStrategy, Just, Strategy};
use proptest::test_runner::{Config, TestRunner};
use proptest::{prop_assert, prop_assert_eq};
use liblumen_alloc::atom;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::erts::time::Milliseconds;
use crate::runtime::time::monotonic;
use crate::erlang;
use crate::erlang::start_timer_4::result;
use crate::test;
use crate::test::strategy::milliseconds;
use crate::test::{freeze_at_timeout, freeze_timeout, has_message, registered_name, strategy};
#[test]
fn without_proper_list_options_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::integer::non_negative(arc_process.clone()),
strategy::term(arc_process.clone()),
strategy::term::is_not_list(arc_process.clone()),
)
},
|(arc_process, time, message, tail)| {
let destination = arc_process.pid_term();
let option = arc_process.tuple_from_slice(&[atom!("abs"), true.into()]);
let options = arc_process.improper_list_from_slice(&[option], tail);
prop_assert_badarg!(
result(arc_process.clone(), time, destination, message, options),
"improper list"
);
Ok(())
},
);
}
|
use rand;
use rand::Rng;
command!(eightball(_ctx, msg) {
let mut responses = "It is certain/It is decidedly so/Without a doubt/Yes, definitely/You may rely on it/As I see it, yes/Most likely/Outlook good/Yes/Signs point to yes/Reply hazy try again/Ask again later/Better not tell you now/Cannot predict now/Concentrate and ask again/Don\'t count on it/My reply is no/My sources say no/Outlook not so good/Very doubtful";
let mut list = responses.split("/");
let mut list2 = responses.split("/");
let mut num = rand::thread_rng().gen_range(0, list.count());
let item = list2.nth(num).unwrap();
let _ = msg.channel_id.say(&format!("{}", item));
}); |
use db::Conn as DbConn;
use rocket_contrib::{Json, Value};
use super::robot::{Robot, NewRobot};
#[get("/robots", format = "application/json")]
fn index(conn: DbConn) -> Json {
Json(json!({
"status": 200,
"result": Robot::all(&conn)
}))
}
#[post("/robots", format = "application/json", data = "<new_robot>")]
fn new(conn: DbConn, new_robot: Json<NewRobot>) -> Json<Value> {
Json(json!({
"status": Robot::insert(new_robot.into_inner(), &conn),
"result": Robot::all(&conn).first()
}))
}
#[get("/robots/<id>", format = "application/json")]
fn show(conn: DbConn, id: i32) -> Json<Value> {
let result = Robot::show(id, &conn);
let status = if result.is_empty() { 404 } else { 200 };
Json(json!({
"status": status,
"result": result.get(0)
}))
}
/// TODO: finish UPDATE func
// #[put("/robots/<id>", data = "<new_robot>")]
// fn update(conn: DbConn, id: i32, new_robot: Json<NewRobot>) -> Result<Redirect, ()> {
// Ok(Redirect::to("/robots/<id>"))
// }
#[delete("/robots/<id>")]
fn delete(id: i32, conn: DbConn) -> Json<Value> {
let status = if Robot::delete_with_id(id, &conn) { 204 } else { 404 };
Json(json!({
"status": status,
"result": null,
}))
}
#[get("/robots/departments/<department>", format = "application/json")]
fn department(department: String, conn: DbConn) -> Json {
Json(json!(
Robot::all_in_department(department, &conn)
))
}
#[error(404)]
fn not_found() -> Json {
Json(json!({
"status": "error",
"reason": "Resource was not found."
}))
}
|
use wasm_bindgen::prelude::*;
use nalgebra_glm::Vec3;
use nalgebra_glm::sqrt;
use crate::pathtracer::camera::{Camera};
use crate::pathtracer::PathTracer;
use crate::utils::set_panic_hook;
use crate::pathtracer::material::LambertianMaterial;
use crate::pathtracer::hit::HitableShape;
use crate::pathtracer::math::saturate;
use crate::pathtracer::sphere::Sphere;
use crate::pathtracer::triangle::Triangle;
use crate::pathtracer::pointlight::PointLight;
#[wasm_bindgen]
pub struct Context {
pub camera_pos: Vector3,
pub camera_rotation: Vector3,
pub camera_fov: f32,
pub sample_per_pixel: u16,
pathtracer: PathTracer
}
#[wasm_bindgen]
impl Context {
pub fn new() -> Context {
set_panic_hook();
let camera = Camera::new(
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(0.0, 0.0, 0.0),
45.,
320,
160,
);
let pathtracer = PathTracer::new(camera, 1);
Context {
camera_pos: Vector3::new(0.0, 0.0, 0.0),
camera_rotation: Vector3::new(0.0, 0.0, 0.0),
camera_fov: 0.0,
sample_per_pixel: 1,
pathtracer
}
}
pub fn draw(
&mut self,
tile_x: u32,
tile_y: u32,
tile_size: u32,
width: u32,
height: u32,
) -> Result<Vec<u8>, JsValue> {
let camera = Camera::new(
self.camera_pos.into(),
self.camera_rotation.into(),
self.camera_fov,
width,
height,
);
self.pathtracer.camera = camera;
self.pathtracer.samples = self.sample_per_pixel;
// Call the pathtracer once per pixel and build the image
let data_size = (tile_size * tile_size) as usize;
let mut data = Vec::with_capacity(data_size);
for y in (tile_y..(tile_y + tile_size)).rev() {
for x in tile_x..(tile_x + tile_size) {
let col = self.pathtracer.compute_pixel(x, y);
let better_color = saturate(sqrt(&col));
data.push((255.99 * better_color.x) as u8);
data.push((255.99 * better_color.y) as u8);
data.push((255.99 * better_color.z) as u8);
data.push(255);
}
}
Ok(data)
}
/// Create a new light or edit an existing one.
pub fn create_or_edit_light(&mut self, id: u32, x: f32, y: f32, z: f32, intensity: f32)
{
// Check if the light already exists.
match self.pathtracer.lights.find(id) {
// Edit the light.
Some(light) => {
light.position.x = x;
light.position.y = y;
light.position.z = z;
light.intensity = intensity;
},
// Create a new light.
None => {
let light = PointLight::new(
id,
Vec3::new(x, y, z),
intensity);
self.pathtracer.lights.add(light.into());
}
}
}
pub fn remove_light(&mut self, id: u32) {
self.pathtracer.lights.remove(id);
}
pub fn add_sphere(&mut self, id: u32, x: f32, y: f32, z: f32, radius: f32) {
self.pathtracer.world.add(Sphere::new(
id,
Vec3::new(x, y, z),
radius,
LambertianMaterial {
albedo: Vec3::new(0.5, 0.5, 0.5),
}.into(),
).into());
}
pub fn update_sphere(&mut self, id: u32, x: f32, y: f32, z: f32, radius: f32) -> bool {
if let Some(shape) = self.pathtracer.world.find(id) {
match shape {
HitableShape::Sphere(sphere) => {
sphere.center.x = x;
sphere.center.y = y;
sphere.center.z = z;
sphere.radius = radius;
},
_ => ()
}
true
}
else {
false
}
}
pub fn remove_sphere(&mut self, id: u32) {
self.pathtracer.world.remove(id);
}
pub fn add_triangle(&mut self,
id: u32,
a_x: f32,
a_y: f32,
a_z: f32,
b_x: f32,
b_y: f32,
b_z: f32,
c_x: f32,
c_y: f32,
c_z: f32) {
self.pathtracer.world.add(Triangle::new(
id,
Vec3::new(a_x, a_y, a_z),
Vec3::new(b_x, b_y, b_z),
Vec3::new(c_x, c_y, c_z),
LambertianMaterial {
albedo: Vec3::new(0.5, 0.5, 0.5),
}.into(),
).into());
}
pub fn update_triangle(&mut self,
id: u32,
a_x: f32,
a_y: f32,
a_z: f32,
b_x: f32,
b_y: f32,
b_z: f32,
c_x: f32,
c_y: f32,
c_z: f32
) -> bool {
if let Some(shape) = self.pathtracer.world.find(id) {
match shape {
HitableShape::Triangle(triangle) => {
triangle.vertex_a.x = a_x;
triangle.vertex_a.y = a_y;
triangle.vertex_a.z = a_z;
triangle.vertex_b.x = b_x;
triangle.vertex_b.y = b_y;
triangle.vertex_b.z = b_z;
triangle.vertex_c.x = c_x;
triangle.vertex_c.y = c_y;
triangle.vertex_c.z = c_z;
},
_ => ()
}
true
}
else {
false
}
}
pub fn remove_triangle(&mut self, id: u32) {
self.pathtracer.world.remove(id);
}
pub fn add_model(&mut self, id: u32, x: f32, y: f32, z: f32,
vertices: Vec<f32>,
triangles: Vec<u16>) {
self.remove_model(id);
let pos = Vec3::new(x, y, z);
for vertex in vertices.chunks(9) {
assert_eq!(vertex.len(), 9);
self.pathtracer.world.add(Triangle::new(
id,
Vec3::new(vertex[0], vertex[1],vertex[2]),
Vec3::new(vertex[3], vertex[4],vertex[5]),
Vec3::new(vertex[6], vertex[7],vertex[8]),
LambertianMaterial {
albedo: Vec3::new(0.5, 0.5, 0.5),
}.into(),
).into());
}
log(self.pathtracer.world.stats().as_str());
// for triangle in triangles.chunks(3) {
// assert_eq!(triangle.len(), 3);
// self.pathtracer.world.add(Triangle::new(
// id,
// extract_triangle(&vertices, triangle[0]),
// extract_triangle(&vertices, triangle[1]),
// extract_triangle(&vertices, triangle[2]),
// LambertianMaterial {
// albedo: Vec3::new(0.5, 0.5, 0.5),
// }.into(),
// ).into());
// }
}
pub fn update_model(&mut self, id: u32, x: f32, y: f32, z: f32,
vertices: Vec<f32>,
triangles: Vec<u16>) -> bool {
self.remove_model(id);
self.add_model(id, x, y, z, vertices, triangles);
log(self.pathtracer.world.stats().as_str());
true
}
pub fn remove_model(&mut self, id: u32) {
self.pathtracer.world.remove(id);
}
pub fn set_lambert(&mut self, id: u32, r: u32, g: u32, b: u32) -> bool {
if let Some(shape) = self.pathtracer.world.find(id) {
match shape {
HitableShape::Sphere(sphere) => {
sphere.material = LambertianMaterial {
albedo: Vec3::new(r as f32 / 255.9, g as f32 / 255.9, b as f32 / 255.9),
}.into();
},
HitableShape::Triangle(triangle) => {
triangle.material = LambertianMaterial {
albedo: Vec3::new(r as f32 / 255.9, g as f32 / 255.9, b as f32 / 255.9),
}.into();
},
}
true
}
else {
false
}
}
}
fn extract_triangle(vertices: &Vec<f32>, index: u16) -> Vec3 {
let index = index as usize;
Vec3::new(
vertices[index],
vertices[index + 1],
vertices[index + 2],
)
}
/// Wraps around the Vec3 struct from nalgebra for wasm-bindgen
#[wasm_bindgen]
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Vector3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
#[wasm_bindgen]
impl Vector3 {
pub fn new(x: f32, y: f32, z: f32) -> Vector3 {
Vector3 { x, y, z }
}
}
impl From<Vec3> for Vector3 {
fn from(vec: Vec3) -> Self {
Vector3::new(vec.x, vec.y, vec.z)
}
}
impl Into<Vec3> for Vector3 {
fn into(self) -> Vec3 {
Vec3::new(self.x, self.y, self.z)
}
}
#[wasm_bindgen]
extern "C" {
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
// The `console.log` is quite polymorphic, so we can bind it with multiple
// signatures. Note that we need to use `js_name` to ensure we always call
// `log` in JS.
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_u32(a: u32);
// Multiple arguments too!
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_many(a: &str, b: &str);
}
|
//!
pub mod deciders;
pub use deciders::SimpleDecider;
/// The engine of a [`Decision`] node that decides what to do next by returning a new [`Node`]
pub trait Decider<I, A> {
/// Makes a decsion based off of the provided input.
fn decide<'a: 'c, 'b: 'c, 'c>(&'a self, input: &'b I) -> Node<'c, I, A>;
}
/// A decsion to be made. At it's core, this is essentially just a wrapper for a [`Decider`].
pub struct Decision<I, A>(Box<dyn Decider<I, A>>);
impl<I, A> Decision<I, A> {
/// Creates a new [`Decision`] using the given decider.
pub fn new<D>(decider: D) -> Self
where
D: Decider<I, A> + 'static,
{
Self(Box::new(decider))
}
/// Runs the decision, going through any child nodes if needed.
pub fn decide(&self, input: &I) -> A {
let mut decision = self;
loop {
match decision.0.decide(input) {
Node::Answer(a) => return a,
Node::Decision(d) => decision = d,
}
}
}
}
/// A node in a decision tree. This can either be a reference to a [`Decision`] or it can be an
/// answer.
pub enum Node<'a, I, A> {
Decision(&'a Decision<I, A>),
Answer(A),
}
/// A convenience enum. While similar to the [`Node`] enum, this one owns its data and references
/// to it can be converted into a [`Node`].
pub enum OwnedNode<I, A: Clone> {
Decision(Decision<I, A>),
Answer(A),
}
impl<'a, I, A: Clone> From<&'a OwnedNode<I, A>> for Node<'a, I, A> {
fn from(value: &'a OwnedNode<I, A>) -> Node<'a, I, A> {
match value {
OwnedNode::Decision(d) => Self::Decision(&d),
OwnedNode::Answer(a) => Self::Answer(a.clone()),
}
}
}
|
#![deny(warnings)]
#![deny(unsafe_code)]
#![no_main]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rt as rt;
extern crate nb;
extern crate panic_semihosting;
extern crate stm32l1xx_hal as hal;
use core::fmt::Write;
use hal::prelude::*;
use hal::rcc;
use hal::serial;
use hal::serial::SerialExt;
use hal::stm32;
use nb::block;
use rt::entry;
use core::borrow::BorrowMut;
#[entry]
fn main() -> ! {
let dp = stm32::Peripherals::take().unwrap();
let mut rcc = dp.RCC.freeze(rcc::Config::hsi());
let _gpiob = dp.GPIOB.split();
let gpioa = dp.GPIOA.split();
let tx = gpioa.pa9;
let rx = gpioa.pa10;
let mut timer = dp.TIM2.timer(1.hz(), rcc.borrow_mut());
let mut uart_cfg = serial::Config::default();
uart_cfg.baudrate =115200_u32.bps();// time::Bps(115200_u32) ; //19200_u32.bsp();
let serial = dp
.USART1
.usart((tx, rx), uart_cfg, &mut rcc)
.unwrap();
let (mut tx, mut _rx) = serial.split();
loop {
//let received = block!(rx.read()).unwrap();
//tx.write_str("\r\n").unwrap();
//block!(tx.write(received)).ok();
writeln!(tx, "hello world\n").expect("failed to send");
block!(timer.wait()).unwrap();
}
} |
use std::error::Error;
use std::io;
use std::io::Bytes;
use std::io::Read;
use std::io::Write;
use std::io::stdin;
use std::io::stdout;
use std::net::Ipv4Addr;
use std::net::SocketAddr;
use std::net::TcpStream;
use std::process::exit;
use std::thread::spawn;
use std::sync::Arc;
use parking_lot::Mutex;
use unicode_width::UnicodeWidthStr;
use termion::{event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen};
use tui::{
backend::TermionBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Span, Spans, Text},
widgets::{Block, Borders, List, ListItem, Paragraph},
Terminal,
};
use rustchat::ui::events::{Event, Events};
use rustchat::data::Message;
use rustchat::protocol::Framing;
use rustchat::protocol::Command;
use rustchat::user::User;
fn msgread_thread(mut stream: Bytes<TcpStream>, app: Arc<Mutex<App>>) {
loop {
let data = Message::decode(&mut stream).unwrap();
let mut app = app.lock();
app.messages.push(data);
}
}
enum InputMode {
Normal,
Editing,
}
/// App holds the state of the application
struct App {
username: String,
messages: Vec<Message>,
network: TcpStream
}
//1. UI 분리.
fn start_ui(app: Arc<Mutex<App>>) -> Result<(), Box<dyn Error>>{
let stdout = io::stdout().into_raw_mode()?;
let stdout = MouseTerminal::from(stdout);
let stdout = AlternateScreen::from(stdout);
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Setup event handlers
let mut events = Events::new();
let mut input_buf = String::new();
let mut input_mode = InputMode::Normal;
// Create default app state
loop {
// Draw UI
terminal.draw(|f| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(2)
.constraints(
[
Constraint::Length(1),
Constraint::Length(3),
Constraint::Min(1),
]
.as_ref(),
)
.split(f.size());
let (msg, style) = match input_mode {
InputMode::Normal => (
vec![
Span::raw("Press "),
Span::styled("q", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to exit, "),
Span::styled("e", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to start editing."),
],
Style::default().add_modifier(Modifier::RAPID_BLINK),
),
InputMode::Editing => (
vec![
Span::raw("Press "),
Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to stop editing, "),
Span::styled("Enter", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to record the message"),
],
Style::default(),
),
};
let mut text = Text::from(Spans::from(msg));
text.patch_style(style);
let help_message = Paragraph::new(text);
f.render_widget(help_message, chunks[0]);
let input = Paragraph::new(input_buf.as_ref())
.style(match input_mode {
InputMode::Normal => Style::default(),
InputMode::Editing => Style::default().fg(Color::Yellow),
})
.block(Block::default().borders(Borders::ALL).title("Input"));
f.render_widget(input, chunks[1]);
match input_mode {
InputMode::Normal =>
// Hide the cursor. `Frame` does this by default, so we don't need to do anything here
{}
InputMode::Editing => {
// Make the cursor visible and ask tui-rs to put it at the specified coordinates after rendering
f.set_cursor(
// Put cursor past the end of the input text
chunks[1].x + input_buf.width() as u16 + 1,
// Move one line down, from the border to the input line
chunks[1].y + 1,
)
}
}
let messages: Vec<ListItem> = app.lock()
.messages
.iter()
.enumerate()
.map(|(_, m)| {
let content = vec![Spans::from(Span::raw(m.to_str()))];
ListItem::new(content)
})
.collect();
let messages =
List::new(messages).block(Block::default().borders(Borders::ALL).title("Messages"));
f.render_widget(messages, chunks[2]);
})?;
// Handle input
if let Event::Input(input) = events.next()? {
match input_mode {
InputMode::Normal => match input {
Key::Char('e') => {
input_mode = InputMode::Editing;
events.disable_exit_key();
}
Key::Char('q') => {
break;
}
_ => {}
},
InputMode::Editing => match input {
Key::Char('\n') => {
let buf = input_buf.drain(..).collect::<String>();
let msg = Message::new(&app.lock().username, &buf);
app.lock().network.write(&Command::Message(msg).encode_data())?;
app.lock().network.flush()?;
}
Key::Char(c) => {
input_buf.push(c);
}
Key::Backspace => {
input_buf.pop();
}
Key::Esc => {
input_mode = InputMode::Normal;
events.enable_exit_key();
}
_ => {}
},
}
}
}
Ok(())
}
fn main() -> Result<(), Box<dyn Error>>{
let stdin = stdin();
let arguments : Vec<String> = std::env::args().collect();
if arguments.len() < 3 {
eprintln!("usage: {} ip port", arguments[0]);
exit(1);
}
let ip : Ipv4Addr = arguments[1].parse()
.expect("not a ip address!");
let port: u16 = arguments[2].parse()
.expect("not a port number!");
let mut conn = TcpStream::connect(SocketAddr::from((ip, port)))?;
let mut username = String::new();
let mut password = String::new();
print!("username: ");
stdout().flush()?;
stdin.read_line(&mut username)?;
print!("password: ");
stdout().flush()?;
stdin.read_line(&mut password)?;
let request = Command::Login(User::new(&username, &password));
conn.write(&request.encode_data())?;
let app = Arc::new(Mutex::new(App {
username,
messages: Vec::new(),
network: conn.try_clone().unwrap()
}));
let reader = conn.try_clone().unwrap().bytes();
let app_ref = Arc::clone(&app);
spawn(|| {
//reader를 빼고 app의 network에서 가져오는쪽으로 할까..
msgread_thread(reader, app_ref);
});
start_ui(Arc::clone(&app))?;
Ok(())
} |
use sourcerenderer_core::graphics::{
Backend as GraphicsBackend,
BarrierAccess,
BarrierSync,
BindingFrequency,
BufferUsage,
CommandBuffer,
Format,
PipelineBinding,
Texture,
TextureDimension,
TextureInfo,
TextureLayout,
TextureUsage,
TextureView,
TextureViewInfo,
WHOLE_BUFFER,
};
use sourcerenderer_core::{
Platform,
Vec2UI,
};
use super::ssr::SsrPass;
use crate::renderer::render_path::RenderPassParameters;
use crate::renderer::renderer_resources::{
HistoryResourceEntry,
RendererResources,
};
use crate::renderer::shader_manager::{
ComputePipelineHandle,
ShaderManager,
};
const USE_CAS: bool = true;
pub struct CompositingPass {
pipeline: ComputePipelineHandle,
}
impl CompositingPass {
pub const COMPOSITION_TEXTURE_NAME: &'static str = "Composition";
pub fn new<P: Platform>(
resolution: Vec2UI,
resources: &mut RendererResources<P::GraphicsBackend>,
shader_manager: &mut ShaderManager<P>,
) -> Self {
let pipeline = shader_manager.request_compute_pipeline("shaders/compositing.comp.spv");
resources.create_texture(
Self::COMPOSITION_TEXTURE_NAME,
&TextureInfo {
dimension: TextureDimension::Dim2D,
format: Format::RGBA8UNorm,
width: resolution.x,
height: resolution.y,
depth: 1,
mip_levels: 1,
array_length: 1,
samples: sourcerenderer_core::graphics::SampleCount::Samples1,
usage: TextureUsage::STORAGE | TextureUsage::SAMPLED,
supports_srgb: false,
},
false,
);
Self { pipeline }
}
pub fn execute<P: Platform>(
&mut self,
cmd_buffer: &mut <P::GraphicsBackend as GraphicsBackend>::CommandBuffer,
params: &RenderPassParameters<'_, P>,
input_name: &str,
) {
let input_image = params.resources.access_view(
cmd_buffer,
input_name,
BarrierSync::COMPUTE_SHADER,
BarrierAccess::SAMPLING_READ,
TextureLayout::Sampled,
false,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let ssr = params.resources.access_view(
cmd_buffer,
SsrPass::SSR_TEXTURE_NAME,
BarrierSync::COMPUTE_SHADER,
BarrierAccess::SAMPLING_READ,
TextureLayout::Sampled,
false,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let output = params.resources.access_view(
cmd_buffer,
Self::COMPOSITION_TEXTURE_NAME,
BarrierSync::COMPUTE_SHADER,
BarrierAccess::STORAGE_WRITE,
TextureLayout::Storage,
true,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
cmd_buffer.begin_label("Compositing pass");
let pipeline = params.shader_manager.get_compute_pipeline(self.pipeline);
cmd_buffer.set_pipeline(PipelineBinding::Compute(&pipeline));
#[repr(C)]
#[derive(Debug, Clone)]
struct Setup {
gamma: f32,
exposure: f32,
}
let setup_ubo = cmd_buffer.upload_dynamic_data(
&[Setup {
gamma: 2.2f32,
exposure: 0.01f32,
}],
BufferUsage::CONSTANT,
);
cmd_buffer.bind_storage_texture(BindingFrequency::VeryFrequent, 0, &output);
cmd_buffer.bind_sampling_view_and_sampler(
BindingFrequency::VeryFrequent,
1,
&input_image,
params.resources.linear_sampler(),
);
cmd_buffer.bind_sampling_view_and_sampler(
BindingFrequency::VeryFrequent,
2,
&ssr,
params.resources.linear_sampler(),
);
cmd_buffer.bind_uniform_buffer(
BindingFrequency::VeryFrequent,
3,
&setup_ubo,
0,
WHOLE_BUFFER,
);
cmd_buffer.finish_binding();
let info = output.texture().info();
cmd_buffer.dispatch((info.width + 7) / 8, (info.height + 7) / 8, 1);
cmd_buffer.end_label();
}
}
|
use day_14::{self, INPUT};
use std::env;
fn main() {
let mut parse_result = day_14::parse_input(INPUT);
match env::args().nth(1).as_deref() {
Some("all") => {
let part_one = day_14::part_one(&mut parse_result.clone());
println!("{part_one}");
let part_two = day_14::part_two(&mut parse_result);
println!("{part_two}");
}
Some("parse") => {}
Some("one") => {
let part_one = day_14::part_one(&mut parse_result);
println!("{part_one}");
}
Some("two") => {
let part_two = day_14::part_two(&mut parse_result);
println!("{part_two}");
}
_ => println!("Invalid argument: must be one of all, parse, one, or two"),
}
}
|
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;
#[derive(RustcDecodable, RustcEncodable)]
pub struct RefreshToken {
pub sub: String,
pub iss: String,
pub issued: u64,
}
impl RefreshToken {
pub fn new(user_id: &Uuid, issuer: String) -> Self {
let issued = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
RefreshToken {
iss: issuer,
sub: user_id.hyphenated().to_string(),
issued,
}
}
pub fn get_id(&self) -> Uuid {
Uuid::parse_str(&self.sub).unwrap()
}
}
|
use crate::prelude::*;
use std::fmt;
#[repr(C)]
#[derive(Copy, Clone, PartialEq)]
pub struct VkGeometryInstanceNV {
pub transform: [f32; 12],
instance_id_mask: u32,
instance_offset_flags: u32,
pub accelerationStructureHandle: u64,
}
impl VkGeometryInstanceNV {
pub fn new(
transform: [f32; 12],
instance_id: u32,
mask: u8,
instance_offset: u32,
flags: impl Into<VkGeometryInstanceFlagBitsNV>,
acceleration_tructure_handle: u64,
) -> Self {
let instance_id = Self::u24_to_u32(instance_id);
let instance_offset = Self::u24_to_u32(instance_offset);
let flags: u32 = flags.into().into();
let flags = Self::u32_to_u8(flags);
let mask = Self::u32_to_u8(mask as u32);
VkGeometryInstanceNV {
transform,
instance_id_mask: (instance_id | mask),
instance_offset_flags: (instance_offset | flags),
accelerationStructureHandle: acceleration_tructure_handle,
}
}
pub fn instance_id(&self) -> u32 {
Self::u32_to_u24(self.instance_id_mask)
}
pub fn mask(&self) -> u32 {
Self::u8_to_u32(self.instance_id_mask)
}
pub fn instance_offset(&self) -> u32 {
Self::u32_to_u24(self.instance_offset_flags)
}
pub fn flags(&self) -> VkGeometryInstanceFlagBitsNV {
Self::u8_to_u32(self.instance_offset_flags).into()
}
#[inline]
fn u32_to_u24(bits: u32) -> u32 {
bits & 0x00FF_FFFF
}
#[inline]
fn u24_to_u32(bits: u32) -> u32 {
bits & 0x00FF_FFFF
}
#[inline]
fn u32_to_u8(bits: u32) -> u32 {
(bits & 0x0000_00FF) << 24
}
#[inline]
fn u8_to_u32(bits: u32) -> u32 {
(bits & 0xFF00_0000) >> 24
}
}
impl fmt::Debug for VkGeometryInstanceNV {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VkGeometryInstanceNV {{ transform: {:?}, instanceID: {}, mask: {}, instanceOffset: {}, flags: {:?}, accelerationStructureHandle {} }}",
self.transform,
self.instance_id(),
self.mask(),
self.instance_offset(),
self.flags(),
self.accelerationStructureHandle
)
}
}
|
pub mod force_directed;
pub mod treemap;
pub use self::force_directed::force_directed_grouping;
// pub use self::radial::RadialGrouping;
pub use self::treemap::treemap_grouping;
use petgraph::graph::{Graph, IndexType, NodeIndex};
use petgraph::EdgeType;
use std::collections::HashMap;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct Group {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
impl Group {
pub fn new(x: f32, y: f32, width: f32, height: f32) -> Group {
Group {
x,
y,
width,
height,
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct GroupNode {
pub id: usize,
pub weight: f32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct GroupLink {
pub source: usize,
pub target: usize,
pub weight: f32,
}
pub fn node_group<
N,
E,
Ty: EdgeType,
Ix: IndexType,
F: FnMut(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>) -> usize,
>(
graph: &Graph<N, E, Ty, Ix>,
mut group_accessor: F,
) -> HashMap<NodeIndex<Ix>, usize> {
graph
.node_indices()
.map(|u| (u, group_accessor(graph, u)))
.collect::<HashMap<_, _>>()
}
pub fn aggregate_nodes<
N,
E,
Ty: EdgeType,
Ix: IndexType,
F: FnMut(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>) -> f32,
>(
graph: &Graph<N, E, Ty, Ix>,
groups: &HashMap<NodeIndex<Ix>, usize>,
mut weight: F,
) -> Vec<GroupNode> {
let mut result = HashMap::new();
for u in graph.node_indices() {
let g = groups[&u];
*result.entry(g).or_insert(0.) += weight(graph, u);
}
result
.iter()
.map(|(&id, &weight)| GroupNode { id, weight })
.collect::<Vec<_>>()
}
pub fn aggregate_edges<
N,
E,
Ty: EdgeType,
Ix: IndexType,
F: FnMut(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>, NodeIndex<Ix>) -> f32,
>(
graph: &Graph<N, E, Ty, Ix>,
groups: &HashMap<NodeIndex<Ix>, usize>,
mut weight: F,
) -> Vec<GroupLink> {
let mut result = HashMap::new();
for e in graph.edge_indices() {
let (u, v) = graph.edge_endpoints(e).unwrap();
let key = {
let source_group = groups[&u];
let target_group = groups[&v];
if source_group == target_group {
continue;
}
if source_group < target_group {
(source_group, target_group)
} else {
(target_group, source_group)
}
};
*result.entry(key).or_insert(0.) += weight(graph, u, v)
}
result
.iter()
.map(|(&(source, target), &weight)| GroupLink {
source,
target,
weight,
})
.collect::<Vec<_>>()
}
|
/// The key that represents an Actor in the Client's scope, that is being
/// synced to the Client
pub type LocalActorKey = u16;
|
use std::{
cmp::min,
collections::{HashMap, VecDeque},
path::Path,
str::FromStr,
sync::{Arc, Mutex, RwLock},
thread,
time::Duration,
};
use syntect::{
dumps::from_uncompressed_data,
highlighting::{
Color, HighlightState, Highlighter, RangedHighlightIterator, ScopeSelectors, StyleModifier,
Theme, ThemeItem,
},
parsing::{ParseState, ScopeStack, SyntaxSet},
};
use crate::{
piece_table::PieceTable,
renderer::{TextEffect, TextEffectKind},
};
impl From<crate::renderer::Color> for Color {
fn from(color: crate::renderer::Color) -> Self {
Self {
r: color.r_u8,
g: color.g_u8,
b: color.b_u8,
a: 255,
}
}
}
pub const SYNTECT_CACHE_FREQUENCY: usize = 100;
pub struct IndexedLine {
pub index: usize,
pub text: Vec<u8>,
}
pub struct Syntect {
pub queue: Arc<Mutex<VecDeque<IndexedLine>>>,
pub cache_updated: Arc<Mutex<bool>>,
cache: Arc<RwLock<HashMap<usize, Vec<TextEffect>>>>,
theme: Theme,
syntax_set: SyntaxSet,
extension: String,
}
impl Syntect {
pub fn new(path: &str, theme: &crate::theme::Theme) -> Option<Self> {
let queue = Arc::new(Mutex::new(VecDeque::new()));
let cache_updated = Arc::new(Mutex::new(false));
let cache = Arc::new(RwLock::new(HashMap::new()));
let theme = convert_theme(theme);
let extension = Path::new(path).extension()?.to_str()?.to_string();
let syntax_set: SyntaxSet =
from_uncompressed_data(include_bytes!("../resources/syntax_definitions.packdump"))
.unwrap();
start_highlight_thread(
path,
theme.clone(),
Arc::clone(&queue),
Arc::clone(&cache_updated),
Arc::clone(&cache),
)?;
Some(Self {
queue,
cache_updated,
cache,
theme,
syntax_set,
extension,
})
}
pub fn highlight_code_blocks(&self, text: &[u8], ranges: &[(usize, usize)]) -> Vec<TextEffect> {
let highlighter = Highlighter::new(&self.theme);
let syntax_reference = self.syntax_set.find_syntax_by_extension(&self.extension);
if syntax_reference.is_none() {
return vec![];
}
let mut effects = vec![];
let mut adjusted_text_position = vec![];
let mut number_of_non_ascii_chars = 0;
for (i, c) in text.iter().enumerate() {
if !c.is_ascii() {
number_of_non_ascii_chars += 1;
}
adjusted_text_position
.push(i.saturating_sub((number_of_non_ascii_chars as f64 / 2.0).ceil() as usize));
}
for range in ranges {
if range.0 >= text.len() {
break;
}
let mut parse_state = ParseState::new(syntax_reference.unwrap());
let mut highlight_state = HighlightState::new(&highlighter, ScopeStack::new());
let code_block = &text[range.0..min(range.1, text.len())];
let mut offset = 0;
for line in code_block.split_inclusive(|c| *c == b'\n') {
let line = unsafe { std::str::from_utf8_unchecked(line) };
let ops = parse_state.parse_line(line, &self.syntax_set).unwrap();
for highlight in
RangedHighlightIterator::new(&mut highlight_state, &ops, line, &highlighter)
{
effects.push(TextEffect {
kind: TextEffectKind::ForegroundColor(crate::renderer::Color::from_rgb(
highlight.0.foreground.r,
highlight.0.foreground.g,
highlight.0.foreground.b,
)),
start: adjusted_text_position[range.0 + offset + highlight.2.start],
length: adjusted_text_position[range.0
+ offset
+ highlight.2.start
+ highlight.2.len().saturating_sub(1)]
- adjusted_text_position[range.0 + offset + highlight.2.start]
+ 1,
});
}
offset += line.len();
}
}
effects
}
pub fn delete_rebalance(&mut self, piece_table: &PieceTable, position: usize, end: usize) {
let start_index = piece_table.line_index(position) / SYNTECT_CACHE_FREQUENCY;
if let Some(start_cache_offset) =
piece_table.char_index_from_line_col(start_index * SYNTECT_CACHE_FREQUENCY, 0)
{
let start_effects_offset = position - start_cache_offset;
if let Ok(ref mut cache) = self.cache.as_ref().write() {
if let Some(effects) = cache.get_mut(&start_index) {
for effect in effects {
if effect.start >= start_effects_offset + (end - position) {
effect.start = effect.start.saturating_sub(end - position);
}
}
}
}
}
}
pub fn insert_rebalance(&mut self, piece_table: &PieceTable, position: usize, count: usize) {
let start_index = piece_table.line_index(position) / SYNTECT_CACHE_FREQUENCY;
if let Some(start_cache_offset) =
piece_table.char_index_from_line_col(start_index * SYNTECT_CACHE_FREQUENCY, 0)
{
let start_effects_offset = position - start_cache_offset;
if let Ok(ref mut cache) = self.cache.as_ref().write() {
if let Some(effects) = cache.get_mut(&start_index) {
for effect in effects {
if effect.start >= start_effects_offset {
effect.start += count;
}
}
}
}
}
}
pub fn highlight_lines(
&self,
piece_table: &PieceTable,
start: usize,
end: usize,
) -> Vec<TextEffect> {
let start_index = start / SYNTECT_CACHE_FREQUENCY;
if let Some(start_cache_offset) =
piece_table.char_index_from_line_col(start_index * SYNTECT_CACHE_FREQUENCY, 0)
{
if let Some(start_text_offset) = piece_table.char_index_from_line_col(start, 0) {
let start_effects_offset = start_text_offset - start_cache_offset;
let mut effects = self
.cache
.try_read()
.map(|cache| cache.get(&start_index).cloned())
.unwrap_or(None)
.unwrap_or(vec![]);
effects.retain(|effect| effect.start >= start_effects_offset);
for effect in &mut effects {
effect.start -= start_effects_offset;
}
let end_index = end / SYNTECT_CACHE_FREQUENCY;
if end_index != start_index {
let end_cache_offset = piece_table
.char_index_from_line_col(end_index * SYNTECT_CACHE_FREQUENCY, 0)
.unwrap_or(piece_table.num_chars());
let end_text_offset = piece_table
.char_index_from_line_col(end, 0)
.unwrap_or(piece_table.num_chars());
let end_effects_offset = end_text_offset - end_cache_offset;
let mut end_effects = self
.cache
.try_read()
.map(|cache| cache.get(&end_index).cloned())
.unwrap_or(None)
.unwrap_or(vec![]);
end_effects.retain(|effect| effect.start < end_effects_offset);
for effect in &mut end_effects {
effect.start += (end_text_offset - start_text_offset) - end_effects_offset;
}
effects.append(&mut end_effects);
}
return effects;
}
}
vec![]
}
}
fn start_highlight_thread(
path: &str,
theme: Theme,
queue: Arc<Mutex<VecDeque<IndexedLine>>>,
cache_updated: Arc<Mutex<bool>>,
cache: Arc<RwLock<HashMap<usize, Vec<TextEffect>>>>,
) -> Option<()> {
let extension = Path::new(path).extension()?.to_str()?.to_string();
thread::spawn(move || {
let mut internal_cache = HashMap::new();
let syntax_set: SyntaxSet =
from_uncompressed_data(include_bytes!("../resources/syntax_definitions.packdump"))
.unwrap();
let highlighter = Highlighter::new(&theme);
let syntax_reference = syntax_set.find_syntax_by_extension(&extension);
if syntax_reference.is_none() {
return;
}
loop {
thread::sleep(Duration::from_micros(8333));
let (start, text) = if let Some(indexed_line) = queue.lock().unwrap().pop_front() {
(indexed_line.index, indexed_line.text)
} else {
continue;
};
let index = start / SYNTECT_CACHE_FREQUENCY;
let (mut parse_state, mut highlight_state) = if index > 0 {
internal_cache.get(&(index - 1)).cloned().unwrap_or((
ParseState::new(syntax_reference.unwrap()),
HighlightState::new(&highlighter, ScopeStack::new()),
))
} else {
(
ParseState::new(syntax_reference.unwrap()),
HighlightState::new(&highlighter, ScopeStack::new()),
)
};
let mut effects = vec![];
let mut offset = 0;
for line in text.split_inclusive(|c| *c == b'\n') {
let line = unsafe { std::str::from_utf8_unchecked(line) };
let ops = parse_state.parse_line(line, &syntax_set).unwrap();
for highlight in
RangedHighlightIterator::new(&mut highlight_state, &ops, line, &highlighter)
{
effects.push(TextEffect {
kind: TextEffectKind::ForegroundColor(crate::renderer::Color::from_rgb(
highlight.0.foreground.r,
highlight.0.foreground.g,
highlight.0.foreground.b,
)),
start: offset + highlight.2.start,
length: highlight.2.len(),
});
}
offset += line.len();
}
{
let mut cache = cache.write().unwrap();
cache.insert(index, effects);
*cache_updated.lock().unwrap() = true;
}
internal_cache.insert(index, (parse_state, highlight_state));
}
});
Some(())
}
fn convert_theme(theme: &crate::theme::Theme) -> Theme {
Theme {
name: None,
author: None,
settings: syntect::highlighting::ThemeSettings {
foreground: Some(Color::from(theme.foreground_color)),
background: Some(Color::from(theme.background_color)),
caret: Some(Color::from(theme.background_color)),
selection: Some(Color::from(theme.selection_background_color)),
selection_foreground: Some(Color::from(theme.foreground_color)),
..Default::default()
},
scopes: vec![
ThemeItem {
scope: ScopeSelectors::from_str("comment, punctuation.definition.comment").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.numbers_color)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("string").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.green)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("constant.numeric").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.orange)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("storage.type.numeric").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.pink)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("constant.language").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.red)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("constant.character, constant.other").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.pink)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("variable.member").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.red)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str(
"keyword - keyword.operator, keyword.operator.word",
)
.unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.pink)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("storage").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.red)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("storage.type").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.pink)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("entity.name.function").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.aqua)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str(
"entity.name - (entity.name.section | entity.name.tag | entity.name.label)",
)
.unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.orange)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("entity.other.inherited-class").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.blue)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("variable.parameter").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.orange)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("variable.language").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.red)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("entity.name.tag").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.red)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("entity.other.attribute-name").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.pink)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("variable.function, variable.annotation").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.blue)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("support.function, support.macro").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.blue)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("support.constant").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.pink)),
background: None,
font_style: None,
},
},
ThemeItem {
scope: ScopeSelectors::from_str("support.type, support.class").unwrap(),
style: StyleModifier {
foreground: Some(Color::from(theme.palette.blue)),
background: None,
font_style: None,
},
},
],
}
}
|
use crate::backend::c;
use crate::backend::conv::ret;
use crate::fd::OwnedFd;
use crate::io;
#[cfg(not(any(
apple,
target_os = "aix",
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "wasi"
)))]
use crate::pipe::PipeFlags;
use core::mem::MaybeUninit;
#[cfg(linux_kernel)]
use {
crate::backend::conv::{borrowed_fd, ret_c_int, ret_usize},
crate::backend::MAX_IOV,
crate::fd::BorrowedFd,
crate::pipe::{IoSliceRaw, SpliceFlags},
crate::utils::option_as_mut_ptr,
core::cmp::min,
};
#[cfg(not(target_os = "wasi"))]
pub(crate) fn pipe() -> io::Result<(OwnedFd, OwnedFd)> {
unsafe {
let mut result = MaybeUninit::<[OwnedFd; 2]>::uninit();
ret(c::pipe(result.as_mut_ptr().cast::<i32>()))?;
let [p0, p1] = result.assume_init();
Ok((p0, p1))
}
}
#[cfg(not(any(
apple,
target_os = "aix",
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "wasi"
)))]
pub(crate) fn pipe_with(flags: PipeFlags) -> io::Result<(OwnedFd, OwnedFd)> {
unsafe {
let mut result = MaybeUninit::<[OwnedFd; 2]>::uninit();
ret(c::pipe2(
result.as_mut_ptr().cast::<i32>(),
bitflags_bits!(flags),
))?;
let [p0, p1] = result.assume_init();
Ok((p0, p1))
}
}
#[cfg(linux_kernel)]
#[inline]
pub fn splice(
fd_in: BorrowedFd,
off_in: Option<&mut u64>,
fd_out: BorrowedFd,
off_out: Option<&mut u64>,
len: usize,
flags: SpliceFlags,
) -> io::Result<usize> {
let off_in = option_as_mut_ptr(off_in).cast();
let off_out = option_as_mut_ptr(off_out).cast();
unsafe {
ret_usize(c::splice(
borrowed_fd(fd_in),
off_in,
borrowed_fd(fd_out),
off_out,
len,
flags.bits(),
))
}
}
#[cfg(linux_kernel)]
#[inline]
pub unsafe fn vmsplice(
fd: BorrowedFd,
bufs: &[IoSliceRaw],
flags: SpliceFlags,
) -> io::Result<usize> {
ret_usize(c::vmsplice(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV),
flags.bits(),
))
}
#[cfg(linux_kernel)]
#[inline]
pub fn tee(
fd_in: BorrowedFd,
fd_out: BorrowedFd,
len: usize,
flags: SpliceFlags,
) -> io::Result<usize> {
unsafe {
ret_usize(c::tee(
borrowed_fd(fd_in),
borrowed_fd(fd_out),
len,
flags.bits(),
))
}
}
#[cfg(linux_kernel)]
#[inline]
pub(crate) fn fcntl_getpipe_sz(fd: BorrowedFd<'_>) -> io::Result<usize> {
unsafe { ret_c_int(c::fcntl(borrowed_fd(fd), c::F_GETPIPE_SZ)).map(|size| size as usize) }
}
#[cfg(linux_kernel)]
#[inline]
pub(crate) fn fcntl_setpipe_sz(fd: BorrowedFd<'_>, size: usize) -> io::Result<()> {
let size: c::c_int = size.try_into().map_err(|_| io::Errno::PERM)?;
unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_SETPIPE_SZ, size)) }
}
|
/// Belajar mutable borrow (reference)
///
/// Ahad, 15 Desember 2019 17:31
/// borrow = meminjam
/// mutable = data dapat dirubah
/// mutable borrow berarti meminjam data yang dapat dirubah via reference var
/// tanda mutable borrow dengan "&mut type_data"
fn main() {
// buat var name dapat dirubah (mutable)
let mut name = String::from("Hello");
// ubah name
update(&mut name, String::from(" world!, "));
// ubah name
update(&mut name, String::from(" Agus"));
update(&mut name, String::from(" Susilo."));
// cetak name
println!("{}", name);
}
/// arg name mutable ref/borrow dilihat dari tanda &mut
/// pada saat dipanggil var harus menyertakan &mut juga
fn update(name: &mut String, word: String) {
name.push_str(&word);
}
|
#![allow(non_snake_case)]
extern crate rand;
use vec3::*;
use rand::Rng;
use std::sync;
static mut PERM_X: [u8; 256] = [0; 256];
static mut PERM_Y: [u8; 256] = [0; 256];
static mut PERM_Z: [u8; 256] = [0; 256];
static mut RANFLOAT: [f64; 256] = [0.; 256];
static mut RANVEC: [Vec3<f64>; 256] = [Vec3{x:0.,y:0.,z:0.}; 256];
// Unfortunately, the lazy_static crate adds a little overhead to read from
// the static, which I find unacceptable. Instead, just use unsafe access,
// which should be fine for read-only data as long as it is initialized
// correctly. Alternatively, could package the data into a struct, or just
// precompute the values and place the literals directly in this rs file.
/// Initialize noise. Must be called once (in main).
pub fn perlin_init() {
unsafe {
static mut ONCE: sync::Once = sync::ONCE_INIT;
ONCE.call_once(|| {
PERM_X = perlin_generate_perm();
PERM_Y = perlin_generate_perm();
PERM_Z = perlin_generate_perm();
RANFLOAT = perlin_generate_float();
RANVEC = perlin_generate();
});
}
}
// Accessors to hide the unsafe blocks.
fn get_perm_x() -> &'static [u8; 256] {unsafe { &PERM_X }}
fn get_perm_y() -> &'static [u8; 256] {unsafe { &PERM_Y }}
fn get_perm_z() -> &'static [u8; 256] {unsafe { &PERM_Z }}
fn get_ranfloat() -> &'static [f64; 256] {unsafe { &RANFLOAT }}
fn get_ranvec() -> &'static [Vec3<f64>; 256] {unsafe { &RANVEC }}
fn perlin_generate_perm() -> [u8; 256] {
let mut result = [0u8; 256];
for i in 0..256 {
result[i] = i as u8;
}
// rand::thread_rng().shuffle(result)
permute(&mut result);
return result;
}
fn permute(p: &mut [u8; 256]) {
let mut rng = rand::thread_rng();
for i in (1..256).rev() {
let target: usize = rng.gen_range(0, i + 1);
let tmp = p[i];
p[i] = p[target];
p[target] = tmp;
}
}
fn perlin_generate() -> [Vec3<f64>; 256] {
let mut rng = rand::thread_rng();
let mut result = [Vec3::zero(); 256];
for i in 0..256 {
let mut v = Vec3::new(-1. + 2. * rng.gen::<f64>(),
-1. + 2. * rng.gen::<f64>(),
-1. + 2. * rng.gen::<f64>());
v.make_unit_vector();
result[i] = v;
}
return result;
}
fn perlin_generate_float() -> [f64; 256] {
let mut rng = rand::thread_rng();
let mut result = [0.; 256];
for i in 0..256 {
result[i] = rng.gen::<f64>();
}
return result;
}
pub fn old_noise1(p: &Vec3<f64>) -> f64 {
let PX = get_perm_x();
let PY = get_perm_y();
let PZ = get_perm_z();
let RF = get_ranfloat();
let i = (4. * p.x) as usize & 255;
let j = (4. * p.y) as usize & 255;
let k = (4. * p.z) as usize & 255;
return RF[(PX[i] ^ PY[j] ^ PZ[k]) as usize];
}
pub fn old_noise2(p: &Vec3<f64>) -> f64 {
let PX = get_perm_x();
let PY = get_perm_y();
let PZ = get_perm_z();
let RF = get_ranfloat();
let u = p.x - p.x.floor();
let v = p.y - p.y.floor();
let w = p.z - p.z.floor();
let i = p.x.floor() as usize;
let j = p.y.floor() as usize;
let k = p.z.floor() as usize;
let mut c = [0.; 8];
for di in 0..2 {
for dj in 0..2 {
for dk in 0..2 {
let index = PX[(i + di) & 255] ^
PY[(j + dj) & 255] ^
PZ[(k + dk) & 255];
c[di * 4 + dj * 2 + dk] = RF[index as usize];
}
}
}
let mut accum = 0.;
for i in 0..2 {
let fi = i as f64;
for j in 0..2 {
let fj = j as f64;
for k in 0..2 {
let fk = k as f64;
accum += (fi * u + (1. - fi) * (1. - u)) *
(fj * v + (1. - fj) * (1. - v)) *
(fk * w + (1. - fk) * (1. - w)) *
c[i * 4 + j * 2 + k];
}
}
}
return accum;
}
pub fn old_noise3(p: &Vec3<f64>) -> f64 {
let PX = get_perm_x();
let PY = get_perm_y();
let PZ = get_perm_z();
let RF = get_ranfloat();
let u = p.x - p.x.floor();
let v = p.y - p.y.floor();
let w = p.z - p.z.floor();
let u = u * u * (3. - 2. * u);
let v = v * v * (3. - 2. * v);
let w = w * w * (3. - 2. * w);
let i = p.x.floor() as usize;
let j = p.y.floor() as usize;
let k = p.z.floor() as usize;
let mut c = [0.; 8];
for di in 0..2 {
for dj in 0..2 {
for dk in 0..2 {
let index = PX[(i + di) & 255] ^
PY[(j + dj) & 255] ^
PZ[(k + dk) & 255];
c[di * 4 + dj * 2 + dk] = RF[index as usize];
}
}
}
let mut accum = 0.;
for i in 0..2 {
let fi = i as f64;
for j in 0..2 {
let fj = j as f64;
for k in 0..2 {
let fk = k as f64;
accum += (fi * u + (1. - fi) * (1. - u)) *
(fj * v + (1. - fj) * (1. - v)) *
(fk * w + (1. - fk) * (1. - w)) *
c[i * 4 + j * 2 + k];
}
}
}
return accum;
}
pub fn perlin_noise(p: &Vec3<f64>) -> f64 {
let PX = get_perm_x();
let PY = get_perm_y();
let PZ = get_perm_z();
let RV = get_ranvec();
let u = p.x - p.x.floor();
let v = p.y - p.y.floor();
let w = p.z - p.z.floor();
let i = p.x.floor() as usize;
let j = p.y.floor() as usize;
let k = p.z.floor() as usize;
let mut c = [Vec3::zero(); 8];
for di in 0..2 {
for dj in 0..2 {
for dk in 0..2 {
let index = PX[(i + di) & 255] ^
PY[(j + dj) & 255] ^
PZ[(k + dk) & 255];
c[di * 4 + dj * 2 + dk] = RV[index as usize];
}
}
}
// Add some interpolation to smooth the pattern using a hermite cube.
let uu = u * u * (3. - 2. * u);
let vv = v * v * (3. - 2. * v);
let ww = w * w * (3. - 2. * w);
let mut accum = 0.;
for i in 0..2 {
let fi = i as f64;
for j in 0..2 {
let fj = j as f64;
for k in 0..2 {
let fk = k as f64;
let weight_v = Vec3::new(u - fi, v - fj, w - fk);
accum += (fi * uu + (1. - fi) * (1. - uu)) *
(fj * vv + (1. - fj) * (1. - vv)) *
(fk * ww + (1. - fk) * (1. - ww)) *
dot(&c[i * 4 + j * 2 + k], &weight_v);
}
}
}
return accum;
}
/// A marbled noise texture.
pub fn turb_noise(p: &Vec3<f64>, depth: usize) -> f64 {
let mut accum = 0.;
let mut temp_p = p.clone();
let mut weight = 1.0;
for _ in 0..depth {
accum += weight * perlin_noise(&temp_p);
weight *= 0.5;
temp_p *= 2.;
}
return accum.abs();
}
|
// build.rs
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("recipients.rs");
let mut f = File::create(&dest_path).unwrap();
write!(
&mut f,
r#"
#[test]
fn verify_deps() {{
let r = Recipients::with_env("{out_dir}", "{manifest_dir}").unwrap();
r.get("dhltest").unwrap();
r.get("dhltest-dash").unwrap();
r.get("dhltest_underscore").unwrap();
}}"#,
out_dir = out_dir,
manifest_dir = manifest_dir,
).unwrap();
}
|
use std::io;
use std::io::prelude::*;
use std::fmt::{Debug,Formatter,Error};
use std::str::FromStr;
fn main() {
for n in 1.. {
print!("[{}]> ", n);
io::stdout().flush().unwrap();
let mut cmd = String::new();
io::stdin().read_line(&mut cmd).unwrap();
if cmd == "" { break; } // ^D pressed
//println!("{:?}", exec_rpn(to_rpn(tokenize(cmd.trim().to_string()))));
println!("{:?}", to_rpn(tokenize(cmd.trim().to_string())));
}
}
trait FromString<T> { fn from_string(String) -> Option<(T, usize)>; }
#[derive(PartialEq, Clone)]
enum Operator { Plus, Minus, Times, DividedBy, OpenParen, CloseParen,
OpenBracket, CloseBracket, Comma }
// apparently there's no cleaner way to do this
impl ToString for Operator {
fn to_string(&self) -> String {
match *self {
Operator::Plus => "+", Operator::Minus => "-",
Operator::Times => "*", Operator::DividedBy => "/",
Operator::OpenParen => "(", Operator::CloseParen => ")",
Operator::OpenBracket => "[", Operator::CloseBracket => "]",
Operator::Comma => ","
}.to_string()
}
}
impl FromString<Operator> for Operator {
fn from_string(s: String) -> Option<(Operator, usize)> {
match &s[0..1] {
"+" => Some((Operator::Plus, 1)),
"-" => Some((Operator::Minus, 1)),
"*" => Some((Operator::Times, 1)),
"/" => Some((Operator::DividedBy, 1)),
"(" => Some((Operator::OpenParen, 1)),
")" => Some((Operator::CloseParen, 1)),
"[" => Some((Operator::OpenBracket, 1)),
"]" => Some((Operator::CloseBracket, 1)),
"," => Some((Operator::Comma, 1)),
_ => None
}
}
}
impl Operator {
fn prec(&self) -> u8 {
match *self {
Operator::Plus => 1, Operator::Minus => 1,
Operator::Times => 2, Operator::DividedBy => 2,
_ => 0
}
}
}
#[derive(PartialEq, Clone)]
enum Function { Range, Floor, Ceil, Wrap(usize) }
impl ToString for Function {
fn to_string(&self) -> String {
match *self {
Function::Range => "range".to_string(),
Function::Floor => "floor".to_string(),
Function::Ceil => "ceil".to_string(),
Function::Wrap(n) => format!("wrap<{}>", n)
}
}
}
impl FromString<Function> for Function {
fn from_string(s: String) -> Option<(Function, usize)> {
if 5 <= s.len() && &s[0..5] == "range" {
Some((Function::Range, 5))
} else if 5 <= s.len() && &s[0..5] == "floor" {
Some((Function::Floor, 5))
} else if 4 <= s.len() && &s[0..4] == "ceil" {
Some((Function::Ceil, 4))
} else { None }
}
}
#[derive(PartialEq, Clone)]
enum Token {
XNumber(f32),
XString(String),
XArray(Vec<Token>),
XOperator(Operator),
XFunction(Function)
}
impl Debug for Token {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
match *self {
Token::XNumber(ref n) => {
try!(write!(fmt, "{}", n));
},
Token::XString(ref s) => {
try!(write!(fmt, "{}", s));
},
Token::XArray(ref a) => {
try!(write!(fmt, "{:?}", a));
},
Token::XOperator(ref o) => {
try!(write!(fmt, "{}", (*o).to_string()));
},
Token::XFunction(ref f) => {
try!(write!(fmt, "{}", (*f).to_string()));
}
}
Ok(())
}
}
fn tokenize(cmd: String) -> Vec<Token> {
let mut tokens: Vec<Token> = vec![];
let mut pos: usize = 0;
while pos < cmd.len() {
let c = cmd.chars().nth(pos).unwrap();
let op_str = Operator::from_string(cmd.chars().skip(pos)
.collect::<String>());
let func_str = Function::from_string(cmd.chars().skip(pos)
.collect::<String>());
if c.is_digit(10) || c == '.' {
let num = cmd.chars().skip(pos).take_while(|c| c.is_digit(10) ||
*c == '.').collect::<String>();
tokens.push(Token::XNumber(f32::from_str(&num).unwrap()));
pos += num.len();
} else if c == '"' {
let endquote = cmd.rfind('"').unwrap() + 1;
tokens.push(Token::XString(cmd[pos..endquote].to_string()));
pos = endquote;
} else if op_str.is_some() {
let (s, len) = op_str.unwrap();
tokens.push(Token::XOperator(s));
pos += len;
} else if func_str.is_some() {
let (s, len) = func_str.unwrap();
tokens.push(Token::XFunction(s));
pos += len;
} else if c == ' ' || c == '\t' {
pos += 1;
} else {
panic!("Syntax error");
}
}
tokens
}
fn to_rpn(tokens: Vec<Token>) -> Vec<Token> {
let mut rpn: Vec<Token> = vec![];
let mut opstack: Vec<Token> = vec![]; // must be Vec<Token> because can
// contain Functions
let mut wrap_counts: Vec<usize> = vec![];
for token in tokens {
let old_len = rpn.len();
match token {
Token::XNumber(n) => { rpn.push(Token::XNumber(n)); },
Token::XString(s) => { rpn.push(Token::XString(s)); },
Token::XArray(_) => { panic!("array in tokens in evaluate()"); },
Token::XOperator(o) => {
match o {
Operator::Comma => {
// THIS WILL PANIC on mismatched parens or misplaced comma
while opstack[opstack.len()-1] !=
Token::XOperator(Operator::OpenParen) &&
opstack[opstack.len()-1] !=
Token::XOperator(Operator::OpenBracket) {
rpn.push(opstack.pop().unwrap());
}
},
Operator::OpenParen => { opstack.push(Token::XOperator(o)); },
Operator::CloseParen => {
while let Some(_) = match opstack.last() {
Some(&Token::XOperator(Operator::OpenParen)) => None,
Some(&ref x) => Some(x),
_ => panic!("mismatched parens")} {
rpn.push(opstack.pop().unwrap());
}
opstack.pop().unwrap(); // the matching open paren
if let Some(_) = match opstack.last() {
Some(&Token::XFunction(ref f)) => Some(f),
_ => None
} {
rpn.push(opstack.pop().unwrap());
}
},
Operator::OpenBracket => {
opstack.push(Token::XOperator(o));
wrap_counts.push(0);
},
Operator::CloseBracket => {
while let Some(_) = match opstack.last() {
Some(&Token::XOperator(Operator::OpenBracket)) => None,
Some(&ref x) => Some(x),
_ => panic!("mismatched bracket")} {
rpn.push(opstack.pop().unwrap());
}
opstack.pop().unwrap(); // the matching open bracket
rpn.push(Token::XFunction(Function::Wrap(wrap_counts.pop().unwrap())));
},
_ => {
while let Some(_) = match opstack.last() {
Some(&Token::XOperator(ref o2)) =>
if o.prec() <= o2.prec() { Some(o2) }
else { None },
_ => None} {
rpn.push(opstack.pop().unwrap());
}
opstack.push(Token::XOperator(o));
}
}
},
Token::XFunction(f) => { opstack.push(Token::XFunction(f)); }
}
if !wrap_counts.is_empty() {
let idx = wrap_counts.len() - 1;
wrap_counts[idx] += rpn.len() - old_len;
}
}
while let Some(op) = opstack.pop() {
rpn.push(op);
}
rpn
}
fn exec_rpn(rpn: Vec<Token>) -> Vec<Token> {
let mut stack: Vec<Token> = vec![];
for token in rpn {
match token {
Token::XOperator(Operator::Plus) => { },
Token::XOperator(Operator::Minus) => { },
Token::XOperator(Operator::Times) => { },
Token::XOperator(Operator::DividedBy) => { },
Token::XOperator(_) => { panic!("bad operator in exec_rpn"); },
Token::XFunction(Function::Range) => { },
Token::XFunction(Function::Floor) => { },
Token::XFunction(Function::Ceil) => { },
Token::XFunction(Function::Wrap(n)) => { },
_ => { stack.push(token) }
}
}
stack
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qanimationgroup.h
// dst-file: /src/core/qanimationgroup.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::qabstractanimation::*; // 773
use std::ops::Deref;
use super::qobject::*; // 773
use super::qobjectdefs::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QAnimationGroup_Class_Size() -> c_int;
// proto: QAbstractAnimation * QAnimationGroup::animationAt(int index);
fn C_ZNK15QAnimationGroup11animationAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QAnimationGroup::~QAnimationGroup();
fn C_ZN15QAnimationGroupD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QAnimationGroup::removeAnimation(QAbstractAnimation * animation);
fn C_ZN15QAnimationGroup15removeAnimationEP18QAbstractAnimation(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QAnimationGroup::QAnimationGroup(QObject * parent);
fn C_ZN15QAnimationGroupC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: int QAnimationGroup::animationCount();
fn C_ZNK15QAnimationGroup14animationCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QAnimationGroup::addAnimation(QAbstractAnimation * animation);
fn C_ZN15QAnimationGroup12addAnimationEP18QAbstractAnimation(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QAnimationGroup::clear();
fn C_ZN15QAnimationGroup5clearEv(qthis: u64 /* *mut c_void*/);
// proto: QAbstractAnimation * QAnimationGroup::takeAnimation(int index);
fn C_ZN15QAnimationGroup13takeAnimationEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QAnimationGroup::insertAnimation(int index, QAbstractAnimation * animation);
fn C_ZN15QAnimationGroup15insertAnimationEiP18QAbstractAnimation(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: const QMetaObject * QAnimationGroup::metaObject();
fn C_ZNK15QAnimationGroup10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QAnimationGroup::indexOfAnimation(QAbstractAnimation * animation);
fn C_ZNK15QAnimationGroup16indexOfAnimationEP18QAbstractAnimation(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int;
} // <= ext block end
// body block begin =>
// class sizeof(QAnimationGroup)=1
#[derive(Default)]
pub struct QAnimationGroup {
qbase: QAbstractAnimation,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QAnimationGroup {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QAnimationGroup {
return QAnimationGroup{qbase: QAbstractAnimation::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QAnimationGroup {
type Target = QAbstractAnimation;
fn deref(&self) -> &QAbstractAnimation {
return & self.qbase;
}
}
impl AsRef<QAbstractAnimation> for QAnimationGroup {
fn as_ref(& self) -> & QAbstractAnimation {
return & self.qbase;
}
}
// proto: QAbstractAnimation * QAnimationGroup::animationAt(int index);
impl /*struct*/ QAnimationGroup {
pub fn animationAt<RetType, T: QAnimationGroup_animationAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.animationAt(self);
// return 1;
}
}
pub trait QAnimationGroup_animationAt<RetType> {
fn animationAt(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: QAbstractAnimation * QAnimationGroup::animationAt(int index);
impl<'a> /*trait*/ QAnimationGroup_animationAt<QAbstractAnimation> for (i32) {
fn animationAt(self , rsthis: & QAnimationGroup) -> QAbstractAnimation {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QAnimationGroup11animationAtEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK15QAnimationGroup11animationAtEi(rsthis.qclsinst, arg0)};
let mut ret1 = QAbstractAnimation::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QAnimationGroup::~QAnimationGroup();
impl /*struct*/ QAnimationGroup {
pub fn free<RetType, T: QAnimationGroup_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QAnimationGroup_free<RetType> {
fn free(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: void QAnimationGroup::~QAnimationGroup();
impl<'a> /*trait*/ QAnimationGroup_free<()> for () {
fn free(self , rsthis: & QAnimationGroup) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroupD2Ev()};
unsafe {C_ZN15QAnimationGroupD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QAnimationGroup::removeAnimation(QAbstractAnimation * animation);
impl /*struct*/ QAnimationGroup {
pub fn removeAnimation<RetType, T: QAnimationGroup_removeAnimation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeAnimation(self);
// return 1;
}
}
pub trait QAnimationGroup_removeAnimation<RetType> {
fn removeAnimation(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: void QAnimationGroup::removeAnimation(QAbstractAnimation * animation);
impl<'a> /*trait*/ QAnimationGroup_removeAnimation<()> for (&'a QAbstractAnimation) {
fn removeAnimation(self , rsthis: & QAnimationGroup) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroup15removeAnimationEP18QAbstractAnimation()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QAnimationGroup15removeAnimationEP18QAbstractAnimation(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QAnimationGroup::QAnimationGroup(QObject * parent);
impl /*struct*/ QAnimationGroup {
pub fn new<T: QAnimationGroup_new>(value: T) -> QAnimationGroup {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QAnimationGroup_new {
fn new(self) -> QAnimationGroup;
}
// proto: void QAnimationGroup::QAnimationGroup(QObject * parent);
impl<'a> /*trait*/ QAnimationGroup_new for (Option<&'a QObject>) {
fn new(self) -> QAnimationGroup {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroupC2EP7QObject()};
let ctysz: c_int = unsafe{QAnimationGroup_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN15QAnimationGroupC2EP7QObject(arg0)};
let rsthis = QAnimationGroup{qbase: QAbstractAnimation::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QAnimationGroup::animationCount();
impl /*struct*/ QAnimationGroup {
pub fn animationCount<RetType, T: QAnimationGroup_animationCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.animationCount(self);
// return 1;
}
}
pub trait QAnimationGroup_animationCount<RetType> {
fn animationCount(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: int QAnimationGroup::animationCount();
impl<'a> /*trait*/ QAnimationGroup_animationCount<i32> for () {
fn animationCount(self , rsthis: & QAnimationGroup) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QAnimationGroup14animationCountEv()};
let mut ret = unsafe {C_ZNK15QAnimationGroup14animationCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QAnimationGroup::addAnimation(QAbstractAnimation * animation);
impl /*struct*/ QAnimationGroup {
pub fn addAnimation<RetType, T: QAnimationGroup_addAnimation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addAnimation(self);
// return 1;
}
}
pub trait QAnimationGroup_addAnimation<RetType> {
fn addAnimation(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: void QAnimationGroup::addAnimation(QAbstractAnimation * animation);
impl<'a> /*trait*/ QAnimationGroup_addAnimation<()> for (&'a QAbstractAnimation) {
fn addAnimation(self , rsthis: & QAnimationGroup) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroup12addAnimationEP18QAbstractAnimation()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QAnimationGroup12addAnimationEP18QAbstractAnimation(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QAnimationGroup::clear();
impl /*struct*/ QAnimationGroup {
pub fn clear<RetType, T: QAnimationGroup_clear<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clear(self);
// return 1;
}
}
pub trait QAnimationGroup_clear<RetType> {
fn clear(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: void QAnimationGroup::clear();
impl<'a> /*trait*/ QAnimationGroup_clear<()> for () {
fn clear(self , rsthis: & QAnimationGroup) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroup5clearEv()};
unsafe {C_ZN15QAnimationGroup5clearEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QAbstractAnimation * QAnimationGroup::takeAnimation(int index);
impl /*struct*/ QAnimationGroup {
pub fn takeAnimation<RetType, T: QAnimationGroup_takeAnimation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.takeAnimation(self);
// return 1;
}
}
pub trait QAnimationGroup_takeAnimation<RetType> {
fn takeAnimation(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: QAbstractAnimation * QAnimationGroup::takeAnimation(int index);
impl<'a> /*trait*/ QAnimationGroup_takeAnimation<QAbstractAnimation> for (i32) {
fn takeAnimation(self , rsthis: & QAnimationGroup) -> QAbstractAnimation {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroup13takeAnimationEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN15QAnimationGroup13takeAnimationEi(rsthis.qclsinst, arg0)};
let mut ret1 = QAbstractAnimation::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QAnimationGroup::insertAnimation(int index, QAbstractAnimation * animation);
impl /*struct*/ QAnimationGroup {
pub fn insertAnimation<RetType, T: QAnimationGroup_insertAnimation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.insertAnimation(self);
// return 1;
}
}
pub trait QAnimationGroup_insertAnimation<RetType> {
fn insertAnimation(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: void QAnimationGroup::insertAnimation(int index, QAbstractAnimation * animation);
impl<'a> /*trait*/ QAnimationGroup_insertAnimation<()> for (i32, &'a QAbstractAnimation) {
fn insertAnimation(self , rsthis: & QAnimationGroup) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QAnimationGroup15insertAnimationEiP18QAbstractAnimation()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN15QAnimationGroup15insertAnimationEiP18QAbstractAnimation(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QMetaObject * QAnimationGroup::metaObject();
impl /*struct*/ QAnimationGroup {
pub fn metaObject<RetType, T: QAnimationGroup_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QAnimationGroup_metaObject<RetType> {
fn metaObject(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: const QMetaObject * QAnimationGroup::metaObject();
impl<'a> /*trait*/ QAnimationGroup_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QAnimationGroup) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QAnimationGroup10metaObjectEv()};
let mut ret = unsafe {C_ZNK15QAnimationGroup10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QAnimationGroup::indexOfAnimation(QAbstractAnimation * animation);
impl /*struct*/ QAnimationGroup {
pub fn indexOfAnimation<RetType, T: QAnimationGroup_indexOfAnimation<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfAnimation(self);
// return 1;
}
}
pub trait QAnimationGroup_indexOfAnimation<RetType> {
fn indexOfAnimation(self , rsthis: & QAnimationGroup) -> RetType;
}
// proto: int QAnimationGroup::indexOfAnimation(QAbstractAnimation * animation);
impl<'a> /*trait*/ QAnimationGroup_indexOfAnimation<i32> for (&'a QAbstractAnimation) {
fn indexOfAnimation(self , rsthis: & QAnimationGroup) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QAnimationGroup16indexOfAnimationEP18QAbstractAnimation()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK15QAnimationGroup16indexOfAnimationEP18QAbstractAnimation(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// <= body block end
|
use crate::Set;
use crate::passes;
// All optimization passes here must be in correct order.
const USER_PASSES: &[&dyn passes::Pass] = &[
&passes::ConstPropagatePass,
&passes::RemoveIneffectiveOperationsPass,
&passes::SimplifyExpressionsPass,
&passes::SimplifyCFGPass,
&passes::UndefinedPropagatePass,
&passes::RemoveDeadStoresFastPass,
&passes::RemoveDeadStoresPrecisePass,
&passes::RemoveKnownLoadsFastPass,
&passes::RemoveKnownLoadsPrecisePass,
&passes::SimplifyComparesPass,
&passes::PropagateBlockInvariantsPass,
&passes::BranchToSelectPass,
&passes::RemoveDeadCodePass,
&passes::MemoryToSsaPass,
&passes::MinimizePhisPass,
&passes::DeduplicateFastPass,
&passes::DeduplicatePrecisePass,
&passes::OptimizeKnownBitsPass,
&passes::GlobalReorderPass,
&passes::ReorderPass,
];
fn pass_to_id(pass: &'static dyn passes::Pass) -> PassID {
PassID(USER_PASSES.iter().position(|x| x.name() == pass.name()).unwrap_or_else(|| {
panic!("Tried to reference unknown pass {}.", pass.name());
}))
}
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
struct PassID(usize);
pub struct PassManager {
enabled: Set<PassID>,
}
impl Default for PassManager {
fn default() -> Self {
Self::new()
}
}
impl PassManager {
pub fn new() -> Self {
Self {
enabled: Set::default(),
}
}
pub fn with_passes(passes: &[passes::IRPass]) -> Self {
let mut pass_manager = Self::new();
pass_manager.add_passes(passes);
pass_manager
}
pub fn add_pass(&mut self, pass: passes::IRPass) {
let pass_id = pass_to_id(pass.inner);
assert!(self.enabled.insert(pass_id), "Pass {} is already enabled.", pass.name());
}
pub fn add_passes(&mut self, passes: &[passes::IRPass]) {
self.enabled.reserve(passes.len());
for &pass in passes {
self.add_pass(pass);
}
}
pub fn remove_pass(&mut self, pass: passes::IRPass) {
let pass_id = pass_to_id(pass.inner);
assert!(self.enabled.remove(&pass_id), "Pass {} wasn't enabled.", pass.name());
}
pub fn remove_passes(&mut self, passes: &[passes::IRPass]) {
for &pass in passes {
self.remove_pass(pass);
}
}
pub(super) fn build_pass_list(&self) -> Vec<&'static dyn passes::Pass> {
let mut pass_list = Vec::with_capacity(self.enabled.len());
for (index, pass) in USER_PASSES.iter().enumerate() {
if self.enabled.contains(&PassID(index)) {
pass_list.push(*pass);
}
}
pass_list
}
}
|
test_stdout!(
without_number_returns_false,
"false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n"
);
test_stdout!(with_number_returns_true, "true\ntrue\ntrue\n");
|
//! Describes the different kinds of operands an instruction can have.
use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use self::Operand::*;
use crate::ir::{self, DimMap, InstId, Instruction, Parameter, Type};
use fxhash::FxHashMap;
use itertools::Itertools;
use num::bigint::BigInt;
use num::rational::Ratio;
use num::traits::{Signed, Zero};
use serde::{Deserialize, Serialize};
use utils::unwrap;
/// Trait for representing integer literals which can be used in the IR.
///
/// This is meant to be used as a trait bound in various functions accepting literals as arguments,
/// and allows to write generic functions accepting both Rust primitive integer types and IR
/// integers.
pub trait IntLiteral<'a> {
/// Decompose `self` into a big integer and a bit width.
///
/// The resulting value should be understood as having type `Type::I(bit_width)` and thus must
/// be representable with `bit_width` bits.
fn decompose(self) -> (Cow<'a, BigInt>, u16);
}
impl<'a> IntLiteral<'a> for (BigInt, u16) {
fn decompose(self) -> (Cow<'a, BigInt>, u16) {
(Cow::Owned(self.0), self.1)
}
}
impl<'a> IntLiteral<'a> for (&'a BigInt, u16) {
fn decompose(self) -> (Cow<'a, BigInt>, u16) {
(Cow::Borrowed(self.0), self.1)
}
}
/// Trait for representing floating-point literals which can be used in the IR.
///
/// This is meant to be used as a trait bound in various functions accepting literals as arguments,
/// and allows to write generic functions accepting both Rust primitive floating-point types and IR
/// floats.
pub trait FloatLiteral<'a> {
/// Decompose `self` into a big rational and a bit width.
///
/// The resulting value should be understood as having type `Type::F(bit_width)` and thus must
/// be representable with `bit_width` bits.
fn decompose(self) -> (Cow<'a, Ratio<BigInt>>, u16);
}
impl<'a> FloatLiteral<'a> for (Ratio<BigInt>, u16) {
fn decompose(self) -> (Cow<'a, Ratio<BigInt>>, u16) {
(Cow::Owned(self.0), self.1)
}
}
impl<'a> FloatLiteral<'a> for (&'a Ratio<BigInt>, u16) {
fn decompose(self) -> (Cow<'a, Ratio<BigInt>>, u16) {
(Cow::Borrowed(self.0), self.1)
}
}
macro_rules! impl_int_literal {
($($t:ty),*) => {
$(impl<'a> IntLiteral<'a> for $t {
fn decompose(self) -> (Cow<'a, BigInt>, u16) {
(
Cow::Owned(self.into()),
8 * std::mem::size_of::<$t>() as u16,
)
}
})*
};
}
impl_int_literal!(i8, i16, i32, i64);
macro_rules! impl_float_literal {
($($t:ty),*) => {
$(impl<'a> FloatLiteral<'a> for $t {
fn decompose(self) -> (Cow<'a, Ratio<BigInt>>, u16) {
(
Cow::Owned(Ratio::from_float(self).unwrap()),
8 * std::mem::size_of::<$t>() as u16,
)
}
})*
};
}
impl_float_literal!(f32, f64);
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LoweringMap {
/// Memory ID to use for the temporary array
mem_id: ir::MemId,
/// Instruction ID to use for the `store` instruction when
/// lowering.
st_inst: ir::InstId,
/// Maps the lhs dimensions in `map` to their lowered dimension.
st_map: FxHashMap<ir::DimId, (ir::DimId, ir::DimMappingId)>,
/// Instruction ID to use for the `load` instruction when
/// lowering.
ld_inst: ir::InstId,
/// Maps the rhs dimensions in `map` to their lowered dimension.
ld_map: FxHashMap<ir::DimId, (ir::DimId, ir::DimMappingId)>,
}
impl LoweringMap {
/// Creates a new lowering map from an existing dimension map and
/// a counter. This allocates new IDs for the new
/// dimensions/instructions/memory locations that will be used
/// when lowering the DimMap.
pub fn for_dim_map(dim_map: &DimMap, cnt: &mut ir::Counter) -> LoweringMap {
let mem_id = cnt.next_mem();
let st_inst = cnt.next_inst();
let ld_inst = cnt.next_inst();
let (st_map, ld_map) = dim_map
.iter()
.cloned()
.map(|(src, dst)| {
let st_dim = cnt.next_dim();
let ld_dim = cnt.next_dim();
let st_mapping = cnt.next_dim_mapping();
let ld_mapping = cnt.next_dim_mapping();
((src, (st_dim, st_mapping)), (dst, (ld_dim, ld_mapping)))
})
.unzip();
LoweringMap {
mem_id,
st_inst,
st_map,
ld_inst,
ld_map,
}
}
/// Returns lowering information about the dim_map. The returned
/// `LoweredDimMap` object should not be used immediately: it
/// refers to fresh IDs that are not activated in the
/// ir::Function. The appropriate instructions need to be built
/// and stored with the corresponding IDs.
pub(crate) fn lower(&self, map: &DimMap) -> ir::LoweredDimMap {
let (st_dims_mapping, ld_dims_mapping) = map
.iter()
.map(|&(src, dst)| {
let &(st_dim, st_mapping) = unwrap!(self.st_map.get(&src));
let &(ld_dim, ld_mapping) = unwrap!(self.ld_map.get(&dst));
((st_mapping, [src, st_dim]), (ld_mapping, [dst, ld_dim]))
})
.unzip();
ir::LoweredDimMap {
mem: self.mem_id,
store: self.st_inst,
load: self.ld_inst,
st_dims_mapping,
ld_dims_mapping,
}
}
}
/// Indicates how dimensions can be mapped. The `L` type indicates how
/// to lower mapped dimensions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DimMapScope<L> {
/// The dimensions are mapped within registers, without producing syncthreads.
Local,
/// The dimensions are mapped within registers.
Thread,
/// The dimensions are mapped, possibly using temporary
/// memory. The parameter `L` is used to indicate how the mapping
/// should be lowered. It is `()` when building the function
/// (lowering is not possible at that time), and a `LoweringMap`
/// instance when exploring which indicates what IDs to use for
/// the new objects.
Global(L),
}
/// Represents an instruction operand.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Operand<L = LoweringMap> {
/// An integer constant, on a given number of bits.
Int(BigInt, u16),
/// A float constant, on a given number of bits.
Float(Ratio<BigInt>, u16),
/// A value produced by an instruction. The boolean indicates if the `DimMap` can be
/// lowered.
Inst(InstId, Type, DimMap, DimMapScope<L>),
/// The current index in a loop.
Index(ir::DimId),
/// A parameter of the function.
Param(Arc<Parameter>),
/// The address of a memory block.
Addr(ir::MemId),
/// The value of the current instruction at a previous iteration.
Reduce(InstId, Type, DimMap, Vec<ir::DimId>),
/// A variable increased by a fixed amount at every step of some loops.
InductionVar(ir::IndVarId, Type),
/// A variable, stored in register.
Variable(ir::VarId, Type),
}
impl<L> Operand<L> {
/// Returns the type of the `Operand`.
pub fn t(&self) -> Type {
match self {
Int(_, n_bit) => Type::I(*n_bit),
Float(_, n_bit) => Type::F(*n_bit),
Addr(mem) => ir::Type::PtrTo(*mem),
Index(..) => Type::I(32),
Param(p) => p.t,
Variable(_, t) => *t,
Inst(_, t, ..) | Reduce(_, t, ..) | InductionVar(_, t) => *t,
}
}
/// Create an operand from an instruction.
pub fn new_inst(
inst: &Instruction<L>,
dim_map: DimMap,
mut scope: DimMapScope<L>,
) -> Self {
// A temporary array can only be generated if the type size is known.
if let DimMapScope::Global(_) = scope {
if unwrap!(inst.t()).len_byte().is_none() {
scope = DimMapScope::Thread;
}
}
Inst(inst.id(), unwrap!(inst.t()), dim_map, scope)
}
/// Creates a reduce operand from an instruction and a set of dimensions to reduce on.
pub fn new_reduce(
init: &Instruction<L>,
dim_map: DimMap,
dims: Vec<ir::DimId>,
) -> Self {
Reduce(init.id(), unwrap!(init.t()), dim_map, dims)
}
/// Creates a new Int operand and checks its number of bits.
pub fn new_int<'a, T: IntLiteral<'a>>(lit: T) -> Self {
let (val, len) = lit.decompose();
assert!(num_bits(&val) <= len);
Int(val.into_owned(), len)
}
/// Creates a new Float operand.
pub fn new_float<'a, T: FloatLiteral<'a>>(lit: T) -> Self {
let (val, len) = lit.decompose();
Float(val.into_owned(), len)
}
/// Renames a basic block id.
pub fn merge_dims(&mut self, lhs: ir::DimId, rhs: ir::DimId) {
match *self {
Inst(_, _, ref mut dim_map, _) | Reduce(_, _, ref mut dim_map, _) => {
dim_map.merge_dims(lhs, rhs);
}
_ => (),
}
}
/// Indicates if a `DimMap` should be lowered if lhs and rhs are not mapped.
pub fn should_lower_map(&self, lhs: ir::DimId, rhs: ir::DimId) -> bool {
match *self {
Inst(_, _, ref dim_map, _) | Reduce(_, _, ref dim_map, _) => dim_map
.iter()
.any(|&pair| pair == (lhs, rhs) || pair == (rhs, lhs)),
_ => false,
}
}
/// If the operand is a reduction, returns the instruction initializing the reduction.
pub fn as_reduction(&self) -> Option<(InstId, &DimMap, &[ir::DimId])> {
if let Reduce(id, _, ref dim_map, ref dims) = *self {
Some((id, dim_map, dims))
} else {
None
}
}
/// Indicates if the operand stays constant during the execution.
pub fn is_constant(&self) -> bool {
match self {
Int(..) | Float(..) | Addr(..) | Param(..) => true,
Index(..) | Inst(..) | Reduce(..) | InductionVar(..) | Variable(..) => false,
}
}
/// Returns the list of dimensions mapped together by the operand.
pub fn mapped_dims(&self) -> Option<&DimMap> {
match self {
Inst(_, _, dim_map, _) | Reduce(_, _, dim_map, _) => Some(dim_map),
_ => None,
}
}
}
impl Operand<()> {
pub fn freeze(self, cnt: &mut ir::Counter) -> Operand {
match self {
Int(val, len) => Int(val, len),
Float(val, len) => Float(val, len),
Inst(id, t, dim_map, DimMapScope::Global(())) => {
let lowering_map = LoweringMap::for_dim_map(&dim_map, cnt);
Inst(id, t, dim_map, DimMapScope::Global(lowering_map))
}
Inst(id, t, dim_map, DimMapScope::Local) => {
Inst(id, t, dim_map, DimMapScope::Local)
}
Inst(id, t, dim_map, DimMapScope::Thread) => {
Inst(id, t, dim_map, DimMapScope::Thread)
}
Variable(val, t) => Variable(val, t),
Index(id) => Index(id),
Param(param) => Param(param),
Addr(id) => Addr(id),
Reduce(id, t, dim_map, dims) => Reduce(id, t, dim_map, dims),
InductionVar(id, t) => InductionVar(id, t),
}
}
}
impl<L> fmt::Display for Operand<L> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Int(val, len) => write!(fmt, "{}u{}", val, len),
Float(val, len) => write!(fmt, "{}f{}", val, len),
Inst(id, _t, dim_map, _scope) => write!(fmt, "{:?} [{}]", id, dim_map),
Index(id) => write!(fmt, "{}", id),
Param(param) => write!(fmt, "{}", param),
Addr(id) => write!(fmt, "{}", id),
Reduce(id, _t, dim_map, dims) => {
write!(fmt, "reduce({:?}, {:?}) [{}]", id, dims, dim_map)
}
InductionVar(_id, _t) => write!(fmt, "ind"),
Variable(var, t) => write!(fmt, "({}){}", t, var),
}
}
}
impl<L> ir::IrDisplay<L> for Operand<L> {
fn fmt(&self, fmt: &mut fmt::Formatter, fun: &ir::Function<L>) -> fmt::Result {
match self {
Int(val, len) => write!(fmt, "{}u{}", val, len),
Float(val, len) => write!(fmt, "{}f{}", val, len),
Inst(id, _t, dim_map, _scope) => {
let source_dims = fun
.inst(*id)
.iteration_dims()
.iter()
.sorted()
.collect::<Vec<_>>();
let mapping = dim_map.iter().cloned().collect::<FxHashMap<_, _>>();
write!(
fmt,
"{:?}[{}]",
id,
source_dims
.into_iter()
.map(|id| mapping.get(id).unwrap_or(id))
.format(", ")
)
}
Index(id) => write!(fmt, "{}", id),
Param(param) => write!(fmt, "{}", param),
Addr(id) => write!(fmt, "{}", id),
Reduce(id, _t, dim_map, dims) => {
let source_dims = fun
.inst(*id)
.iteration_dims()
.iter()
.sorted()
.collect::<Vec<_>>();
let mapping = dim_map.iter().cloned().collect::<FxHashMap<_, _>>();
write!(
fmt,
"reduce({:?}[{}], {:?})",
id,
source_dims
.into_iter()
.map(|id| mapping.get(id).unwrap_or(id))
.format(", "),
dims
)
}
InductionVar(id, _t) => {
write!(fmt, "{}", fun.induction_var(*id).display(fun))
}
Variable(var, t) => write!(fmt, "({}){}", t, var),
}
}
}
/// Returns the number of bits necessary to encode a `BigInt`.
fn num_bits(val: &BigInt) -> u16 {
let mut num_bits = if val.is_negative() { 1 } else { 0 };
let mut rem = val.abs();
while !rem.is_zero() {
rem >>= 1;
num_bits += 1;
}
num_bits
}
|
pub mod linked_list {
#[derive(Debug)]
/// A linked list
/// It is either empty or has a head and a tail
/// Box is A type for heap allocation.
pub enum List<T> {
Nil,
Cons(T, Box<List<T>>),
}
use crate::linked_list::List::{Nil, Cons};
/// Clone lists
impl<T : Clone> Clone for List<T> {
fn clone(self : &List<T>) -> List<T> {
match self {
Nil => Nil,
Cons(x, xs) => Cons(x.clone(), xs.clone()),
}
}
}
/// foldl :: (b -> a -> b) -> b -> [a] -> b
///
/// Use a reference `xs`.
pub fn foldl<A : Copy, B : Copy>(folder : fn(B, A) -> B, seed : B, xs : &List<A>) -> B {
match xs {
Nil => seed,
Cons(x, xss) => foldl(folder, folder(seed, *x), xss),
}
}
/// map :: (a -> b) -> [a] -> [b]
pub fn map<A, B, F>(f : F, xs : &List<A>) -> List<B> where
F : Fn(&A) -> B {
match xs {
Nil => Nil,
Cons(x, xss) => Cons(f(x), Box::new(map(f, xss))),
}
}
/// concat, This version reuses the lists.
pub fn concat<A>(xs : List<A>, ys : List<A>) -> List<A> {
match xs {
Nil => ys,
Cons(x, xss) => Cons(x, Box::new(concat(*xss, ys))),
}
}
/// concat_map :: (a -> [b]) -> [a] -> [b]
///
/// Creates a new list.
pub fn concat_map<A, B, F>(f : F, xs : &List<A>) -> List<B> where
F : Fn(&A) -> List<B> {
match xs {
Nil => Nil,
Cons(x, xss) => concat(f(x), concat_map(f, xss)),
}
}
/// tails :: [x] -> [[x]]
/// tails [1,2] = [[1,2],[2],[]]
///
/// Creates new lists
pub fn tails<T : Clone>(xs : &List<T>) -> List<List<T>> {
match xs {
Nil => Nil,
Cons(x, xss) => Cons(Cons(x.clone(), xss.clone()), Box::new(tails(xss))),
}
}
/// zip_with :: (a -> b -> c) -> [a] -> [b] -> [c]
pub fn zip_with<A, B, C, F>(f : F, xs : &List<A>, ys : &List<B>) -> List<C> where
F : Fn(&A, &B) -> C {
match xs {
Nil => Nil,
Cons(x, xss) => match ys {
Nil => Nil,
Cons(y, yss) => Cons(f(x, y), Box::new(zip_with(f, xss, yss))),
}
}
}
/// elem :: Eq a => a -> [a] -> Bool
pub fn elem<T : Eq>(value : T, xs : &List<T>) -> bool {
match xs {
Nil => false,
Cons(x, tail) => *x == value || elem(value, &tail),
}
}
/// Create a list with `length` elements.
pub fn range(length : i32) -> List<i32> {
if length == 0 {
return Nil;
} else {
return Cons(length, Box::new(range(length - 1)));
}
}
}
|
// Algorithm:
// 1) Declare a character stack S.
// 2) Now traverse the expression string exp.
// a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
// b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack
// and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
// 3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
// Attempt 2
pub fn brackets_are_balanced(string: &str) -> bool {
let mut brack: Vec<char> = Vec::new();
for c in string.chars() {
match c {
'(' | '{' | '[' => brack.push(c),
')' => if brack.pop() != Some('(') { return false; },
'}' => if brack.pop() != Some('{') { return false; },
']' => if brack.pop() != Some('[') { return false; },
_ => ()
}
}
brack.is_empty()
}
// Attempt # 1
// use std::collections::HashMap;
// pub fn brackets_are_balanced(string: &str) -> bool {
// let mut stack: Vec<char> = Vec::new();
// let mut matching_brackets = HashMap::new();
// matching_brackets.insert('(', ')');
// matching_brackets.insert('{', '}');
// matching_brackets.insert('[', ']');
// matching_brackets.insert(']', '[');
// matching_brackets.insert('}', '{');
// matching_brackets.insert(')', '(');
// string.chars().map(|c| match c {
// c if c == '(' || c == '{' || c == '[' => {
// stack.push(c);
// return true
// },
// c if c == ')' || c == '}' || c == ']' => match stack.pop().unwrap() {
// popped if matching_brackets[&popped] != c => return false,
// _ => return true,
// },
// _ => return false
// });
// match stack.len() {
// 0 => true,
// _ => false
// }
// }
|
use super::interconnect::Interconnect;
use super::registers::{Registers, Reg8, Reg16};
use super::opcode::{CB_OPCODE_TIMES, OPCODE_TIMES, OPCODE_COND_TIMES};
use super::GameboyType;
use super::ppu::VideoSink;
use std::u8;
use std::u16;
pub struct Cpu {
reg: Registers,
pub interconnect: Interconnect,
ime: bool,
halted: bool,
}
struct Imm8;
struct Imm16;
#[derive(Copy,Clone)]
struct ZMem<T: Src<u8>>(T);
#[derive(Copy,Clone)]
struct Mem<T: Src<u16>>(T);
enum Cond {
Uncond,
Zero,
Carry,
NotZero,
NotCarry,
}
impl Cond {
fn is_true(self, cpu: &Cpu) -> bool {
use self::Cond::*;
match self {
Uncond => true,
Zero => cpu.reg.zero,
Carry => cpu.reg.carry,
NotZero => !cpu.reg.zero,
NotCarry => !cpu.reg.carry,
}
}
}
#[derive(Debug)]
enum Timing {
Default,
Cond,
Cb(u32),
}
trait Src<T> {
fn read(self, cpu: &mut Cpu) -> T;
}
trait Dst<T> {
fn write(self, cpu: &mut Cpu, val: T);
}
impl Dst<u8> for Reg8 {
fn write(self, cpu: &mut Cpu, val: u8) {
cpu.reg.write_u8(self, val)
}
}
impl Dst<u16> for Reg16 {
fn write(self, cpu: &mut Cpu, val: u16) {
cpu.reg.write_u16(self, val)
}
}
impl Src<u8> for Reg8 {
fn read(self, cpu: &mut Cpu) -> u8 {
cpu.reg.read_u8(self)
}
}
impl Src<u8> for Imm8 {
fn read(self, cpu: &mut Cpu) -> u8 {
cpu.fetch_u8()
}
}
impl Src<u16> for Reg16 {
fn read(self, cpu: &mut Cpu) -> u16 {
cpu.reg.read_u16(self)
}
}
impl Src<u16> for Imm16 {
fn read(self, cpu: &mut Cpu) -> u16 {
cpu.fetch_u16()
}
}
impl Src<u8> for ZMem<Imm8> {
fn read(self, cpu: &mut Cpu) -> u8 {
let ZMem(imm) = self;
let offset = imm.read(cpu) as u16;
let addr = 0xff00 + offset;
cpu.interconnect.read(addr)
}
}
impl Dst<u8> for ZMem<Imm8> {
fn write(self, cpu: &mut Cpu, val: u8) {
let ZMem(imm) = self;
let offset = imm.read(cpu) as u16;
let addr = 0xff00 + offset;
cpu.interconnect.write(addr, val)
}
}
impl Src<u8> for ZMem<Reg8> {
fn read(self, cpu: &mut Cpu) -> u8 {
let ZMem(reg) = self;
let offset = reg.read(cpu) as u16;
let addr = 0xff00 + offset;
cpu.interconnect.read(addr)
}
}
impl Dst<u8> for ZMem<Reg8> {
fn write(self, cpu: &mut Cpu, val: u8) {
let ZMem(reg) = self;
let offset = reg.read(cpu) as u16;
let addr = 0xff00 + offset;
cpu.interconnect.write(addr, val)
}
}
impl Dst<u8> for Mem<Reg16> {
fn write(self, cpu: &mut Cpu, val: u8) {
let Mem(reg) = self;
let addr = reg.read(cpu);
cpu.interconnect.write(addr, val)
}
}
impl Dst<u8> for Mem<Imm16> {
fn write(self, cpu: &mut Cpu, val: u8) {
let Mem(imm) = self;
let addr = imm.read(cpu);
cpu.interconnect.write(addr, val)
}
}
impl Src<u8> for Mem<Imm16> {
fn read(self, cpu: &mut Cpu) -> u8 {
let Mem(imm) = self;
let addr = imm.read(cpu);
cpu.interconnect.read(addr)
}
}
impl Dst<u16> for Mem<Imm16> {
fn write(self, cpu: &mut Cpu, val: u16) {
let Mem(imm) = self;
let addr = imm.read(cpu);
let l = val as u8;
let h = (val >> 8) as u8;
cpu.interconnect.write(addr, l);
cpu.interconnect.write(addr + 1, h)
}
}
impl Src<u8> for Mem<Reg16> {
fn read(self, cpu: &mut Cpu) -> u8 {
let Mem(reg) = self;
let addr = reg.read(cpu);
cpu.interconnect.read(addr)
}
}
impl Cpu {
pub fn new(gb_type: GameboyType, interconnect: Interconnect) -> Cpu {
Cpu {
reg: Registers::new(gb_type),
interconnect: interconnect,
ime: true,
halted: false,
}
}
pub fn step(&mut self, video_sink: &mut dyn VideoSink) -> u32 {
let elapsed_cycles = {
self.handle_interrupt() + self.execute_instruction()
};
self.interconnect.cycle_flush(elapsed_cycles, video_sink);
elapsed_cycles
}
fn handle_interrupt(&mut self) -> u32 {
let ints = self.interconnect.int_flags & self.interconnect.int_enable;
if self.halted {
self.halted = ints == 0;
}
if !self.ime {
return 0;
}
if ints == 0 {
return 0;
}
self.ime = false;
let int = ints.trailing_zeros();
let int_handler = {
match int {
0 => 0x40,// VBLANK
1 => 0x48,// LCDC STATUS
2 => 0x50,// TIMER OVERFLOW
3 => 0x58,// SERIAL TRANSFER COMPLETE
4 => 0x60,// P10-P13 INPUT SIGNAL
_ => panic!("Invalid interrupt {:x}", int),
}
};
self.interconnect.int_flags &= 0xff << (int + 1);
let pc = self.reg.pc;
self.push_u16(pc);
self.reg.pc = int_handler;
20
}
fn execute_instruction(&mut self) -> u32 {
let opcode = if !self.halted { self.fetch_u8() } else { 0 };
use super::registers::Reg8::*;
use super::registers::Reg16::*;
use self::Cond::*;
let timing = {
match opcode {
0x00 => Timing::Default,
0x01 => self.ld(BC, Imm16),
0x02 => self.ld(Mem(BC), A),
0x03 => self.inc_16(BC),
0x04 => self.inc_8(B),
0x05 => self.dec_8(B),
0x06 => self.ld(B, Imm8),
0x07 => self.rlca(),
0x08 => self.ld(Mem(Imm16), SP),
0x09 => self.add_16(HL, BC),
0x0a => self.ld(A, Mem(BC)),
0x0b => self.dec_16(BC),
0x0c => self.inc_8(C),
0x0d => self.dec_8(C),
0x0e => self.ld(C, Imm8),
0x0f => self.rrca(),
0x10 => self.stop(),
0x11 => self.ld(DE, Imm16),
0x12 => self.ld(Mem(DE), A),
0x13 => self.inc_16(DE),
0x14 => self.inc_8(D),
0x15 => self.dec_8(D),
0x16 => self.ld(D, Imm8),
0x17 => self.rla(),
0x18 => self.jr(Uncond, Imm8),
0x19 => self.add_16(HL, DE),
0x1a => self.ld(A, Mem(DE)),
0x1b => self.dec_16(DE),
0x1c => self.inc_8(E),
0x1d => self.dec_8(E),
0x1e => self.ld(E, Imm8),
0x1f => self.rra(),
0x20 => self.jr(NotZero, Imm8),
0x21 => self.ld(HL, Imm16),
0x22 => self.ldi(Mem(HL), A, HL),
0x23 => self.inc_16(HL),
0x24 => self.inc_8(H),
0x25 => self.dec_8(H),
0x26 => self.ld(H, Imm8),
0x27 => self.daa(),
0x28 => self.jr(Zero, Imm8),
0x29 => self.add_16(HL, HL),
0x2a => self.ldi(A, Mem(HL), HL),
0x2b => self.dec_16(HL),
0x2c => self.inc_8(L),
0x2d => self.dec_8(L),
0x2e => self.ld(L, Imm8),
0x2f => self.cpl(),
0x30 => self.jr(NotCarry, Imm8),
0x31 => self.ld(SP, Imm16),
0x32 => self.ldd(Mem(HL), A, HL),
0x33 => self.inc_16(SP),
0x34 => self.inc_8(Mem(HL)),
0x35 => self.dec_8(Mem(HL)),
0x36 => self.ld(Mem(HL), Imm8),
0x37 => self.scf(),
0x38 => self.jr(Carry, Imm8),
0x39 => self.add_16(HL, SP),
0x3a => self.ldd(A, Mem(HL), HL),
0x3b => self.dec_16(SP),
0x3c => self.inc_8(A),
0x3d => self.dec_8(A),
0x3e => self.ld(A, Imm8),
0x3f => self.ccf(),
0x40 => self.ld(B, B),
0x41 => self.ld(B, C),
0x42 => self.ld(B, D),
0x43 => self.ld(B, E),
0x44 => self.ld(B, H),
0x45 => self.ld(B, L),
0x46 => self.ld(B, Mem(HL)),
0x47 => self.ld(B, A),
0x48 => self.ld(C, B),
0x49 => self.ld(C, C),
0x4a => self.ld(C, D),
0x4b => self.ld(C, E),
0x4c => self.ld(C, H),
0x4d => self.ld(C, L),
0x4e => self.ld(C, Mem(HL)),
0x4f => self.ld(C, A),
0x50 => self.ld(D, B),
0x51 => self.ld(D, C),
0x52 => self.ld(D, D),
0x53 => self.ld(D, E),
0x54 => self.ld(D, H),
0x55 => self.ld(D, L),
0x56 => self.ld(D, Mem(HL)),
0x57 => self.ld(D, A),
0x58 => self.ld(E, B),
0x59 => self.ld(E, C),
0x5a => self.ld(E, D),
0x5b => self.ld(E, E),
0x5c => self.ld(E, H),
0x5d => self.ld(E, L),
0x5e => self.ld(E, Mem(HL)),
0x5f => self.ld(E, A),
0x60 => self.ld(H, B),
0x61 => self.ld(H, C),
0x62 => self.ld(H, D),
0x63 => self.ld(H, E),
0x64 => self.ld(H, H),
0x65 => self.ld(H, L),
0x66 => self.ld(H, Mem(HL)),
0x67 => self.ld(H, A),
0x68 => self.ld(L, B),
0x69 => self.ld(L, C),
0x6a => self.ld(L, D),
0x6b => self.ld(L, E),
0x6c => self.ld(L, H),
0x6d => self.ld(L, L),
0x6e => self.ld(L, Mem(HL)),
0x6f => self.ld(L, A),
0x70 => self.ld(Mem(HL), B),
0x71 => self.ld(Mem(HL), C),
0x72 => self.ld(Mem(HL), D),
0x73 => self.ld(Mem(HL), E),
0x74 => self.ld(Mem(HL), H),
0x75 => self.ld(Mem(HL), L),
0x76 => self.halt(),
0x77 => self.ld(Mem(HL), A),
0x78 => self.ld(A, B),
0x79 => self.ld(A, C),
0x7a => self.ld(A, D),
0x7b => self.ld(A, E),
0x7c => self.ld(A, H),
0x7d => self.ld(A, L),
0x7e => self.ld(A, Mem(HL)),
0x7f => self.ld(A, A),
0x80 => self.add_8(A, B),
0x81 => self.add_8(A, C),
0x82 => self.add_8(A, D),
0x83 => self.add_8(A, E),
0x84 => self.add_8(A, H),
0x85 => self.add_8(A, L),
0x86 => self.add_8(A, Mem(HL)),
0x87 => self.add_8(A, A),
0x88 => self.adc(A, B),
0x89 => self.adc(A, C),
0x8a => self.adc(A, D),
0x8b => self.adc(A, E),
0x8c => self.adc(A, H),
0x8d => self.adc(A, L),
0x8e => self.adc(A, Mem(HL)),
0x8f => self.adc(A, A),
0x90 => self.sub_8(A, B),
0x91 => self.sub_8(A, C),
0x92 => self.sub_8(A, D),
0x93 => self.sub_8(A, E),
0x94 => self.sub_8(A, H),
0x95 => self.sub_8(A, L),
0x96 => self.sub_8(A, Mem(HL)),
0x97 => self.sub_8(A, A),
0x98 => self.sbc(A, B),
0x99 => self.sbc(A, C),
0x9a => self.sbc(A, D),
0x9b => self.sbc(A, E),
0x9c => self.sbc(A, H),
0x9d => self.sbc(A, L),
0x9e => self.sbc(A, Mem(HL)),
0x9f => self.sbc(A, A),
0xa0 => self.and(B),
0xa1 => self.and(C),
0xa2 => self.and(D),
0xa3 => self.and(E),
0xa4 => self.and(H),
0xa5 => self.and(L),
0xa6 => self.and(Mem(HL)),
0xa7 => self.and(A),
0xa8 => self.xor(B),
0xa9 => self.xor(C),
0xaa => self.xor(D),
0xab => self.xor(E),
0xac => self.xor(H),
0xad => self.xor(L),
0xae => self.xor(Mem(HL)),
0xaf => self.xor(A),
0xb0 => self.or(B),
0xb1 => self.or(C),
0xb2 => self.or(D),
0xb3 => self.or(E),
0xb4 => self.or(H),
0xb5 => self.or(L),
0xb6 => self.or(Mem(HL)),
0xb7 => self.or(A),
0xb8 => self.cp(B),
0xb9 => self.cp(C),
0xba => self.cp(D),
0xbb => self.cp(E),
0xbc => self.cp(H),
0xbd => self.cp(L),
0xbe => self.cp(Mem(HL)),
0xbf => self.cp(A),
0xc0 => self.ret(NotZero),
0xc1 => self.pop(BC),
0xc2 => self.jp(NotZero, Imm16),
0xc3 => self.jp(Uncond, Imm16),
0xc4 => self.call(NotZero, Imm16),
0xc5 => self.push(BC),
0xc6 => self.add_8(A, Imm8),
0xc7 => self.rst(00),
0xc8 => self.ret(Zero),
0xc9 => self.ret(Uncond),
0xca => self.jp(Zero, Imm16),
0xcb => self.execute_cb_instruction(),
0xcc => self.call(Zero, Imm16),
0xcd => self.call(Uncond, Imm16),
0xce => self.adc(A, Imm8),
0xcf => self.rst(0x08),
0xd0 => self.ret(NotCarry),
0xd1 => self.pop(DE),
0xd2 => self.jp(NotCarry, Imm16),
0xd4 => self.call(NotCarry, Imm16),
0xd5 => self.push(DE),
0xd6 => self.sub_8(A, Imm8),
0xd7 => self.rst(0x10),
0xd8 => self.ret(Carry),
0xd9 => self.reti(),
0xda => self.jp(Carry, Imm16),
0xdc => self.call(Carry, Imm16),
0xde => self.sbc(A, Imm8),
0xdf => self.rst(0x18),
0xe0 => self.ld(ZMem(Imm8), A),
0xe1 => self.pop(HL),
0xe2 => self.ld(ZMem(C), A),
0xe5 => self.push(HL),
0xe6 => self.and(Imm8),
0xe7 => self.rst(0x20),
0xe8 => self.add_sp(),
0xe9 => self.jp(Uncond, HL),
0xea => self.ld(Mem(Imm16), A),
0xee => self.xor(Imm8),
0xef => self.rst(0x28),
0xf0 => self.ld(A, ZMem(Imm8)),
0xf1 => self.pop(AF),
0xf2 => self.ld(A, ZMem(C)),
0xf3 => self.di(),
0xf5 => self.push(AF),
0xf6 => self.or(Imm8),
0xf7 => self.rst(0x30),
0xf8 => self.ld_hl_sp(),
0xf9 => self.ld(SP, HL),
0xfa => self.ld(A, Mem(Imm16)),
0xfb => self.ei(),
0xfe => self.cp(Imm8),
0xff => self.rst(0x38),
_ => panic!("Invalid opcode: 0x{:x}\n{:#?}", opcode, self.reg),
}
};
let cycles = match timing {
Timing::Default => OPCODE_TIMES[opcode as usize] as u32,
Timing::Cond => OPCODE_COND_TIMES[opcode as usize] as u32,
Timing::Cb(x) => x,
};
cycles * 4
}
fn execute_cb_instruction(&mut self) -> Timing {
let opcode = self.fetch_u8();
use super::registers::Reg8::*;
use super::registers::Reg16::*;
match opcode {
0x00 => self.rlc(B),
0x01 => self.rlc(C),
0x02 => self.rlc(D),
0x03 => self.rlc(E),
0x04 => self.rlc(H),
0x05 => self.rlc(L),
0x06 => self.rlc(Mem(HL)),
0x07 => self.rlc(A),
0x08 => self.rrc(B),
0x09 => self.rrc(C),
0x0a => self.rrc(D),
0x0b => self.rrc(E),
0x0c => self.rrc(H),
0x0d => self.rrc(L),
0x0e => self.rrc(Mem(HL)),
0x0f => self.rrc(A),
0x10 => self.rl(B),
0x11 => self.rl(C),
0x12 => self.rl(D),
0x13 => self.rl(E),
0x14 => self.rl(H),
0x15 => self.rl(L),
0x16 => self.rl(Mem(HL)),
0x17 => self.rl(A),
0x18 => self.rr(B),
0x19 => self.rr(C),
0x1a => self.rr(D),
0x1b => self.rr(E),
0x1c => self.rr(H),
0x1d => self.rr(L),
0x1e => self.rr(Mem(HL)),
0x1f => self.rr(A),
0x20 => self.sla(B),
0x21 => self.sla(C),
0x22 => self.sla(D),
0x23 => self.sla(E),
0x24 => self.sla(H),
0x25 => self.sla(L),
0x26 => self.sla(Mem(HL)),
0x27 => self.sla(A),
0x28 => self.sra(B),
0x29 => self.sra(C),
0x2a => self.sra(D),
0x2b => self.sra(E),
0x2c => self.sra(H),
0x2d => self.sra(L),
0x2e => self.sra(Mem(HL)),
0x2f => self.sra(A),
0x30 => self.swap_8(B),
0x31 => self.swap_8(C),
0x32 => self.swap_8(D),
0x33 => self.swap_8(E),
0x34 => self.swap_8(H),
0x35 => self.swap_8(L),
0x36 => self.swap_8(Mem(HL)),
0x37 => self.swap_8(A),
0x38 => self.srl(B),
0x39 => self.srl(C),
0x3a => self.srl(D),
0x3b => self.srl(E),
0x3c => self.srl(H),
0x3d => self.srl(L),
0x3e => self.srl(Mem(HL)),
0x3f => self.srl(A),
0x40 => self.bit(0, B),
0x41 => self.bit(0, C),
0x42 => self.bit(0, D),
0x43 => self.bit(0, E),
0x44 => self.bit(0, H),
0x45 => self.bit(0, L),
0x46 => self.bit(0, Mem(HL)),
0x47 => self.bit(0, A),
0x48 => self.bit(1, B),
0x49 => self.bit(1, C),
0x4a => self.bit(1, D),
0x4b => self.bit(1, E),
0x4c => self.bit(1, H),
0x4d => self.bit(1, L),
0x4e => self.bit(1, Mem(HL)),
0x4f => self.bit(1, A),
0x50 => self.bit(2, B),
0x51 => self.bit(2, C),
0x52 => self.bit(2, D),
0x53 => self.bit(2, E),
0x54 => self.bit(2, H),
0x55 => self.bit(2, L),
0x56 => self.bit(2, Mem(HL)),
0x57 => self.bit(2, A),
0x58 => self.bit(3, B),
0x59 => self.bit(3, C),
0x5a => self.bit(3, D),
0x5b => self.bit(3, E),
0x5c => self.bit(3, H),
0x5d => self.bit(3, L),
0x5e => self.bit(3, Mem(HL)),
0x5f => self.bit(3, A),
0x60 => self.bit(4, B),
0x61 => self.bit(4, C),
0x62 => self.bit(4, D),
0x63 => self.bit(4, E),
0x64 => self.bit(4, H),
0x65 => self.bit(4, L),
0x66 => self.bit(4, Mem(HL)),
0x67 => self.bit(4, A),
0x68 => self.bit(5, B),
0x69 => self.bit(5, C),
0x6a => self.bit(5, D),
0x6b => self.bit(5, E),
0x6c => self.bit(5, H),
0x6d => self.bit(5, L),
0x6e => self.bit(5, Mem(HL)),
0x6f => self.bit(5, A),
0x70 => self.bit(6, B),
0x71 => self.bit(6, C),
0x72 => self.bit(6, D),
0x73 => self.bit(6, E),
0x74 => self.bit(6, H),
0x75 => self.bit(6, L),
0x76 => self.bit(6, Mem(HL)),
0x77 => self.bit(6, A),
0x78 => self.bit(7, B),
0x79 => self.bit(7, C),
0x7a => self.bit(7, D),
0x7b => self.bit(7, E),
0x7c => self.bit(7, H),
0x7d => self.bit(7, L),
0x7e => self.bit(7, Mem(HL)),
0x7f => self.bit(7, A),
0x80 => self.res(0, B),
0x81 => self.res(0, C),
0x82 => self.res(0, D),
0x83 => self.res(0, E),
0x84 => self.res(0, H),
0x85 => self.res(0, L),
0x86 => self.res(0, Mem(HL)),
0x87 => self.res(0, A),
0x88 => self.res(1, B),
0x89 => self.res(1, C),
0x8a => self.res(1, D),
0x8b => self.res(1, E),
0x8c => self.res(1, H),
0x8d => self.res(1, L),
0x8e => self.res(1, Mem(HL)),
0x8f => self.res(1, A),
0x90 => self.res(2, B),
0x91 => self.res(2, C),
0x92 => self.res(2, D),
0x93 => self.res(2, E),
0x94 => self.res(2, H),
0x95 => self.res(2, L),
0x96 => self.res(2, Mem(HL)),
0x97 => self.res(2, A),
0x98 => self.res(3, B),
0x99 => self.res(3, C),
0x9a => self.res(3, D),
0x9b => self.res(3, E),
0x9c => self.res(3, H),
0x9d => self.res(3, L),
0x9e => self.res(3, Mem(HL)),
0x9f => self.res(3, A),
0xa0 => self.res(4, B),
0xa1 => self.res(4, C),
0xa2 => self.res(4, D),
0xa3 => self.res(4, E),
0xa4 => self.res(4, H),
0xa5 => self.res(4, L),
0xa6 => self.res(4, Mem(HL)),
0xa7 => self.res(4, A),
0xa8 => self.res(5, B),
0xa9 => self.res(5, C),
0xaa => self.res(5, D),
0xab => self.res(5, E),
0xac => self.res(5, H),
0xad => self.res(5, L),
0xae => self.res(5, Mem(HL)),
0xaf => self.res(5, A),
0xb0 => self.res(6, B),
0xb1 => self.res(6, C),
0xb2 => self.res(6, D),
0xb3 => self.res(6, E),
0xb4 => self.res(6, H),
0xb5 => self.res(6, L),
0xb6 => self.res(6, Mem(HL)),
0xb7 => self.res(6, A),
0xb8 => self.res(7, B),
0xb9 => self.res(7, C),
0xba => self.res(7, D),
0xbb => self.res(7, E),
0xbc => self.res(7, H),
0xbd => self.res(7, L),
0xbe => self.res(7, Mem(HL)),
0xbf => self.res(7, A),
0xc0 => self.set(0, B),
0xc1 => self.set(0, C),
0xc2 => self.set(0, D),
0xc3 => self.set(0, E),
0xc4 => self.set(0, H),
0xc5 => self.set(0, L),
0xc6 => self.set(0, Mem(HL)),
0xc7 => self.set(0, A),
0xc8 => self.set(1, B),
0xc9 => self.set(1, C),
0xca => self.set(1, D),
0xcb => self.set(1, E),
0xcc => self.set(1, H),
0xcd => self.set(1, L),
0xce => self.set(1, Mem(HL)),
0xcf => self.set(1, A),
0xd0 => self.set(2, B),
0xd1 => self.set(2, C),
0xd2 => self.set(2, D),
0xd3 => self.set(2, E),
0xd4 => self.set(2, H),
0xd5 => self.set(2, L),
0xd6 => self.set(2, Mem(HL)),
0xd7 => self.set(2, A),
0xd8 => self.set(3, B),
0xd9 => self.set(3, C),
0xda => self.set(3, D),
0xdb => self.set(3, E),
0xdc => self.set(3, H),
0xdd => self.set(3, L),
0xde => self.set(3, Mem(HL)),
0xdf => self.set(3, A),
0xe0 => self.set(4, B),
0xe1 => self.set(4, C),
0xe2 => self.set(4, D),
0xe3 => self.set(4, E),
0xe4 => self.set(4, H),
0xe5 => self.set(4, L),
0xe6 => self.set(4, Mem(HL)),
0xe7 => self.set(4, A),
0xe8 => self.set(5, B),
0xe9 => self.set(5, C),
0xea => self.set(5, D),
0xeb => self.set(5, E),
0xec => self.set(5, H),
0xed => self.set(5, L),
0xee => self.set(5, Mem(HL)),
0xef => self.set(5, A),
0xf0 => self.set(6, B),
0xf1 => self.set(6, C),
0xf2 => self.set(6, D),
0xf3 => self.set(6, E),
0xf4 => self.set(6, H),
0xf5 => self.set(6, L),
0xf6 => self.set(6, Mem(HL)),
0xf7 => self.set(6, A),
0xf8 => self.set(7, B),
0xf9 => self.set(7, C),
0xfa => self.set(7, D),
0xfb => self.set(7, E),
0xfc => self.set(7, H),
0xfd => self.set(7, L),
0xfe => self.set(7, Mem(HL)),
0xff => self.set(7, A),
_ => panic!("CB opcode out of range: 0x{:x}\n{:#?}", opcode, self.reg),
};
Timing::Cb(CB_OPCODE_TIMES[opcode as usize] as u32)
}
fn stop(&self) -> Timing {
// http://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html
//
// Instruction STOP has according to manuals opcode 10 00 and
// thus is 2 bytes long. Anyhow it seems there is no reason for
// it so some assemblers code it simply as one byte instruction 10
//
Timing::Default
}
fn halt(&mut self) -> Timing {
self.halted = true;
Timing::Default
}
fn call<S: Src<u16>>(&mut self, cond: Cond, src: S) -> Timing {
let new_pc = src.read(self);
if cond.is_true(self) {
let ret = self.reg.pc;
self.push_u16(ret);
self.reg.pc = new_pc;
Timing::Cond
} else {
Timing::Default
}
}
fn ret(&mut self, cond: Cond) -> Timing {
if cond.is_true(self) {
let new_pc = self.pop_u16();
self.reg.pc = new_pc;
Timing::Cond
} else {
Timing::Default
}
}
fn reti(&mut self) -> Timing {
self.ei();
self.ret(Cond::Uncond)
}
fn rst(&mut self, p: u8) -> Timing {
let pc = self.reg.pc;
self.push_u16(pc);
self.reg.pc = p as u16;
Timing::Default
}
fn ld<T, D: Dst<T>, S: Src<T>>(&mut self, dst: D, src: S) -> Timing {
let value = src.read(self);
dst.write(self, value);
Timing::Default
}
fn ldi<T, D: Dst<T>, S: Src<T>>(&mut self, dst: D, src: S, inc: Reg16) -> Timing {
let t = self.ld(dst, src);
self.inc_16(inc);
t
}
fn ldd<T, D: Dst<T>, S: Src<T>>(&mut self, dst: D, src: S, dec: Reg16) -> Timing {
let t = self.ld(dst, src);
self.dec_16(dec);
t
}
fn jp<S: Src<u16>>(&mut self, cond: Cond, src: S) -> Timing {
let new_pc = src.read(self);
if cond.is_true(self) {
self.reg.pc = new_pc;
Timing::Cond
} else {
Timing::Default
}
}
fn jr<S: Src<u8>>(&mut self, cond: Cond, src: S) -> Timing {
let offset = (src.read(self) as i8) as i16;
if cond.is_true(self) {
let pc = self.reg.pc as i16;
let new_pc = (pc + offset) as u16;
self.reg.pc = new_pc;
Timing::Cond
} else {
Timing::Default
}
}
fn and<S: Src<u8>>(&mut self, src: S) -> Timing {
let a = src.read(self);
let r = a & self.reg.a;
self.reg.a = r;
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = true;
self.reg.carry = false;
Timing::Default
}
fn sbc<D: Dst<u8> + Src<u8> + Copy, S: Src<u8>>(&mut self, dst: D, src: S) -> Timing {
let a = dst.read(self) as i16;
let b = src.read(self) as i16;
let c = if self.reg.carry { 1 } else { 0 };
let r = a.wrapping_sub(b).wrapping_sub(c);
dst.write(self, r as u8);
self.reg.zero = (r as u8) == 0;
self.reg.subtract = true;
self.reg.carry = r < 0;
self.reg.half_carry = ((a & 0x0f) - (b & 0x0f) - c) < 0;
Timing::Default
}
fn adc<D: Dst<u8> + Src<u8> + Copy, S: Src<u8>>(&mut self, dst: D, src: S) -> Timing {
let a = dst.read(self) as u16;
let b = src.read(self) as u16;
let c = if self.reg.carry { 1 } else { 0 };
let r = a + b + c;
dst.write(self, r as u8);
self.reg.zero = (r as u8) == 0;
self.reg.subtract = false;
self.reg.half_carry = ((a & 0x0f) + (b & 0x0f) + c) > 0x0f;
self.reg.carry = r > 0x00ff;
Timing::Default
}
fn add_sp(&mut self) -> Timing {
let new_sp = self.offset_sp();
self.reg.sp = new_sp;
Timing::Default
}
fn ld_hl_sp(&mut self) -> Timing {
let sp = self.offset_sp();
self.reg.h = (sp >> 8) as u8;
self.reg.l = sp as u8;
Timing::Default
}
fn offset_sp(&mut self) -> u16 {
let offset = (Imm8.read(self) as i8) as i32;
let sp = (self.reg.sp as i16) as i32;
let r = sp + offset;
self.reg.zero = false;
self.reg.subtract = false;
self.reg.carry = ((sp ^ offset ^ (r & 0xffff)) & 0x100) == 0x100;
self.reg.half_carry = ((sp ^ offset ^ (r & 0xffff)) & 0x10) == 0x10;
r as u16
}
fn add_8<D: Dst<u8> + Src<u8> + Copy, S: Src<u8>>(&mut self, dst: D, src: S) -> Timing {
let a = dst.read(self) as u16;
let b = src.read(self) as u16;
let r = a + b;
let c = a ^ b ^ r;
dst.write(self, r as u8);
self.reg.zero = (r as u8) == 0;
self.reg.subtract = false;
self.reg.half_carry = (c & 0x0010) != 0;
self.reg.carry = (c & 0x0100) != 0;
Timing::Default
}
fn add_16<D: Dst<u16> + Src<u16> + Copy, S: Src<u16>>(&mut self, dst: D, src: S) -> Timing {
let a = dst.read(self) as u32;
let b = src.read(self) as u32;
let r = a + b;
dst.write(self, r as u16);
self.reg.subtract = false;
self.reg.carry = (r & 0x10000) != 0;
self.reg.half_carry = ((a ^ b ^ (r & 0xffff)) & 0x1000) != 0;
Timing::Default
}
fn sub_8<D: Dst<u8> + Src<u8> + Copy, S: Src<u8>>(&mut self, dst: D, src: S) -> Timing {
let a = dst.read(self) as u16;
let b = src.read(self) as u16;
let r = a.wrapping_sub(b);
let c = a ^ b ^ r;
dst.write(self, r as u8);
self.reg.zero = (r as u8) == 0;
self.reg.subtract = true;
self.reg.half_carry = (c & 0x0010) != 0;
self.reg.carry = (c & 0x0100) != 0;
Timing::Default
}
fn rrca(&mut self) -> Timing {
self.rrc(Reg8::A);
self.reg.zero = false;
Timing::Default
}
fn rla(&mut self) -> Timing {
self.rl(Reg8::A);
self.reg.zero = false;
Timing::Default
}
fn rra(&mut self) -> Timing {
self.rr(Reg8::A);
self.reg.zero = false;
Timing::Default
}
fn rlca(&mut self) -> Timing {
self.rlc(Reg8::A);
self.reg.zero = false;
Timing::Default
}
fn rlc<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a.rotate_left(1);
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x80) != 0
}
fn rl<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a << 1;
let r = if self.reg.carry { r | 0x01 } else { r };
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x80) != 0
}
fn rr<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a >> 1;
let r = if self.reg.carry { r | 0x80 } else { r };
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x01) != 0;
}
fn rrc<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a.rotate_right(1);
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x01) != 0
}
fn sla<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a << 1;
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x80) != 0
}
fn sra<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a >> 1;
let r = (a & 0x80) | r;
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x01) != 0
}
fn daa(&mut self) -> Timing {
let mut a = self.reg.a as u16;
let n = self.reg.subtract;
let c = self.reg.carry;
let h = self.reg.half_carry;
if n {
if c {
a = a.wrapping_sub(0x60)
}
if h {
a = a.wrapping_sub(0x06)
}
} else {
if c || ((a & 0xff) > 0x99) {
a = a + 0x60;
self.reg.carry = true
}
if h || ((a & 0x0f) > 0x09) {
a = a + 0x06
}
}
self.reg.zero = (a as u8) == 0;
self.reg.half_carry = false;
self.reg.a = a as u8;
Timing::Default
}
fn scf(&mut self) -> Timing {
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = true;
Timing::Default
}
fn ccf(&mut self) -> Timing {
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = !self.reg.carry;
Timing::Default
}
fn bit<S: Src<u8>>(&mut self, bit: u8, src: S) {
let a = src.read(self) >> bit;
self.reg.zero = (a & 0x01) == 0;
self.reg.subtract = false;
self.reg.half_carry = true;
}
fn srl<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = a >> 1;
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = (a & 0x01) != 0;
}
fn res<L: Src<u8> + Dst<u8> + Copy>(&mut self, bit: u8, loc: L) {
let a = loc.read(self);
let r = a & !(0x01 << bit);
loc.write(self, r)
}
fn set<L: Src<u8> + Dst<u8> + Copy>(&mut self, bit: u8, loc: L) {
let a = loc.read(self);
let r = a | (0x01 << bit);
loc.write(self, r)
}
fn swap_8<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) {
let a = loc.read(self);
let r = (a << 4) | (a >> 4);
loc.write(self, r);
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = false
}
fn xor<S: Src<u8>>(&mut self, src: S) -> Timing {
let a = src.read(self);
let r = self.reg.a ^ a;
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = false;
self.reg.a = r;
Timing::Default
}
fn or<S: Src<u8>>(&mut self, src: S) -> Timing {
let a = src.read(self);
let r = self.reg.a | a;
self.reg.zero = r == 0;
self.reg.subtract = false;
self.reg.half_carry = false;
self.reg.carry = false;
self.reg.a = r;
Timing::Default
}
fn cpl(&mut self) -> Timing {
let a = self.reg.a;
self.reg.a = !a;
self.reg.subtract = true;
self.reg.half_carry = true;
Timing::Default
}
fn cp<S: Src<u8>>(&mut self, src: S) -> Timing {
let a = self.reg.a;
let value = src.read(self);
self.reg.subtract = true;
self.reg.carry = a < value;
self.reg.zero = a == value;
self.reg.half_carry = (a.wrapping_sub(value) & 0xf) > (a & 0xf);
Timing::Default
}
fn inc_8<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) -> Timing {
let value = loc.read(self);
let result = value.wrapping_add(1);
loc.write(self, result);
self.reg.zero = result == 0;
self.reg.subtract = false;
self.reg.half_carry = (result & 0x0f) == 0x00;
Timing::Default
}
fn inc_16<L: Dst<u16> + Src<u16> + Copy>(&mut self, loc: L) -> Timing {
// No condition bits are affected for 16 bit inc
let value = loc.read(self);
loc.write(self, value.wrapping_add(1));
Timing::Default
}
fn dec_8<L: Dst<u8> + Src<u8> + Copy>(&mut self, loc: L) -> Timing {
let value = loc.read(self);
let result = value.wrapping_sub(1);
loc.write(self, result);
self.reg.zero = result == 0;
self.reg.subtract = true;
self.reg.half_carry = (result & 0x0f) == 0x0f;
Timing::Default
}
fn dec_16<L: Dst<u16> + Src<u16> + Copy>(&mut self, loc: L) -> Timing {
// No condition bits are affected for 16 bit dec
let value = loc.read(self);
loc.write(self, value.wrapping_sub(1));
Timing::Default
}
fn push<S: Src<u16>>(&mut self, src: S) -> Timing {
let value = src.read(self);
self.push_u16(value);
Timing::Default
}
fn pop<D: Dst<u16>>(&mut self, dst: D) -> Timing {
let value = self.pop_u16();
dst.write(self, value);
Timing::Default
}
fn di(&mut self) -> Timing {
self.ime = false;
Timing::Default
}
fn ei(&mut self) -> Timing {
self.ime = true;
Timing::Default
}
fn fetch_u8(&mut self) -> u8 {
let pc = self.reg.pc;
let value = self.interconnect.read(pc);
self.reg.pc = pc.wrapping_add(1);
value
}
fn fetch_u16(&mut self) -> u16 {
let low = self.fetch_u8() as u16;
let high = self.fetch_u8() as u16;
(high << 8) | low
}
fn push_u8(&mut self, value: u8) {
let sp = self.reg.sp.wrapping_sub(1);
self.interconnect.write(sp, value);
self.reg.sp = sp
}
fn push_u16(&mut self, value: u16) {
self.push_u8((value >> 8) as u8);
self.push_u8(value as u8);
}
fn pop_u8(&mut self) -> u8 {
let sp = self.reg.sp;
let value = self.interconnect.read(sp);
self.reg.sp = sp.wrapping_add(1);
value
}
fn pop_u16(&mut self) -> u16 {
let low = self.pop_u8() as u16;
let high = self.pop_u8() as u16;
(high << 8) | low
}
}
|
//! ChaCha20Poly1305 test vectors.
//!
//! From RFC 8439 Section 2.8.2:
//! <https://tools.ietf.org/html/rfc8439#section-2.8.2>
use ring_compat::{
aead::{Aead, ChaCha20Poly1305, KeyInit, Payload},
generic_array::GenericArray,
};
const KEY: &[u8; 32] = &[
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
];
const AAD: &[u8; 12] = &[
0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
];
const PLAINTEXT: &[u8] = b"Ladies and Gentlemen of the class of '99: \
If I could offer you only one tip for the future, sunscreen would be it.";
const NONCE: &[u8; 12] = &[
0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
];
const CIPHERTEXT: &[u8] = &[
0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2,
0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6,
0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b,
0x1a, 0x71, 0xde, 0x0a, 0x9e, 0x06, 0x0b, 0x29, 0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36,
0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x03, 0xae, 0xe3, 0x28, 0x09, 0x1b, 0x58,
0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc,
0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,
0x61, 0x16,
];
const TAG: &[u8] = &[
0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91,
];
#[test]
fn encrypt() {
let key = GenericArray::from_slice(KEY);
let nonce = GenericArray::from_slice(NONCE);
let payload = Payload {
msg: PLAINTEXT,
aad: AAD,
};
let cipher = ChaCha20Poly1305::new(key);
let ciphertext = cipher.encrypt(nonce, payload).unwrap();
let tag_begins = ciphertext.len() - 16;
assert_eq!(CIPHERTEXT, &ciphertext[..tag_begins]);
assert_eq!(TAG, &ciphertext[tag_begins..]);
}
#[test]
fn decrypt() {
let key = GenericArray::from_slice(KEY);
let nonce = GenericArray::from_slice(NONCE);
let mut ciphertext = Vec::from(CIPHERTEXT);
ciphertext.extend_from_slice(TAG);
let payload = Payload {
msg: &ciphertext,
aad: AAD,
};
let cipher = ChaCha20Poly1305::new(key);
let plaintext = cipher.decrypt(nonce, payload).unwrap();
assert_eq!(PLAINTEXT, plaintext.as_slice());
}
#[test]
fn decrypt_modified() {
let key = GenericArray::from_slice(KEY);
let nonce = GenericArray::from_slice(NONCE);
let mut ciphertext = Vec::from(CIPHERTEXT);
ciphertext.extend_from_slice(TAG);
// Tweak the first byte
ciphertext[0] ^= 0xaa;
let payload = Payload {
msg: &ciphertext,
aad: AAD,
};
let cipher = ChaCha20Poly1305::new(key);
assert!(cipher.decrypt(nonce, payload).is_err());
}
|
#![feature(alloc_layout_extra)]
#![feature(termination_trait_lib)]
#![feature(process_exitcode_placeholder)]
#![feature(thread_local)]
#![feature(core_intrinsics)]
#![feature(c_unwind)]
#![feature(once_cell)]
#[cfg(not(all(unix, any(target_arch = "x86_64", target_arch = "aarch64"))))]
compile_error!("lumen_rt_minimal does not currently support this architecture!");
extern crate liblumen_crt;
#[macro_use]
mod macros;
mod builtins;
mod config;
pub mod env;
mod logging;
pub mod process;
pub mod scheduler;
pub mod sys;
use liblumen_alloc::erts::process::alloc::default_heap_size;
pub use lumen_rt_core::{
base, binary_to_string, context, distribution, integer_to_string, proplist, registry, send,
time, timer,
};
use anyhow::anyhow;
use bus::Bus;
use log::Level;
use self::config::Config;
use self::sys::break_handler::{self, Signal};
#[liblumen_core::entry]
fn main() -> i32 {
use std::process::Termination;
let name = env!("CARGO_PKG_NAME");
let version = env!("CARGO_PKG_VERSION");
main_internal(name, version, Vec::new()).report().to_i32()
}
fn main_internal(name: &str, version: &str, argv: Vec<String>) -> anyhow::Result<()> {
self::env::init_argv_from_slice(std::env::args_os()).unwrap();
// Load system configuration
let _config = match Config::from_argv(name.to_string(), version.to_string(), argv) {
Ok(config) => config,
Err(err) => {
return Err(anyhow!(err));
}
};
// This bus is used to receive signals across threads in the system
let mut bus: Bus<break_handler::Signal> = Bus::new(1);
// Each thread needs a reader
let mut rx1 = bus.add_rx();
// Initialize the break handler with the bus, which will broadcast on it
break_handler::init(bus);
// Start logger
let level_filter = Level::Info.to_level_filter();
logging::init(level_filter).expect("Unexpected failure initializing logger");
let scheduler = scheduler::current();
scheduler.spawn_init(default_heap_size()).unwrap();
loop {
// Run the scheduler for a cycle
let scheduled = scheduler.run_once();
// Check for system signals, and terminate if needed
if let Ok(sig) = rx1.try_recv() {
match sig {
// For now, SIGINT initiates a controlled shutdown
Signal::INT => {
// If an error occurs, report it before shutdown
if let Err(err) = scheduler.shutdown() {
return Err(anyhow!(err));
} else {
break;
}
}
// Technically, we may never see these signals directly,
// we may just be terminated out of hand; but just in case,
// we handle them explicitly by immediately terminating, so
// that we are good citizens of the operating system
sig if sig.should_terminate() => {
return Ok(());
}
// All other signals can be surfaced to other parts of the
// system for custom use, e.g. SIGCHLD, SIGALRM, SIGUSR1/2
_ => (),
}
}
// If the scheduler scheduled a process this cycle, then we're busy
// and should keep working until we have an idle period
if scheduled {
continue;
}
break;
}
match scheduler.shutdown() {
Ok(_) => Ok(()),
Err(err) => Err(anyhow!(err)),
}
}
|
mod create;
mod delete;
mod read;
mod write;
pub use create::FileCreate;
pub use delete::FileDelete;
pub use read::FileRead;
pub use write::FileWrite;
|
use crate::{Force, Point};
use petgraph::graph::{EdgeIndex, Graph, IndexType, NodeIndex};
use petgraph::EdgeType;
use petgraph_layout_force::link_force::{LinkArgument, LinkForce};
use std::collections::HashMap;
pub struct GroupLinkForce {
link_force: LinkForce,
}
impl GroupLinkForce {
pub fn new<
N,
E,
Ty: EdgeType,
Ix: IndexType,
F1: FnMut(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>) -> usize,
F2: FnMut(&Graph<N, E, Ty, Ix>, EdgeIndex<Ix>) -> LinkArgument,
F3: FnMut(&Graph<N, E, Ty, Ix>, EdgeIndex<Ix>) -> LinkArgument,
>(
graph: &Graph<N, E, Ty, Ix>,
mut group_accessor: F1,
mut inter_link_accessor: F2,
mut intra_link_accessor: F3,
) -> GroupLinkForce {
let groups = graph
.node_indices()
.map(|u| (u, group_accessor(graph, u)))
.collect::<HashMap<_, _>>();
GroupLinkForce {
link_force: LinkForce::new_with_accessor(graph, |graph, e| {
let (u, v) = graph.edge_endpoints(e).unwrap();
if groups[&u] == groups[&v] {
intra_link_accessor(graph, e)
} else {
inter_link_accessor(graph, e)
}
}),
}
}
}
impl Force for GroupLinkForce {
fn apply(&self, points: &mut [Point], alpha: f32) {
self.link_force.apply(points, alpha);
}
}
|
//! manage reading the verb shortcuts from the configuration file,
//! initializing if if it doesn't yet exist
use {
super::*,
crate::{
display::ColsConf,
errors::ProgramError,
skin::SkinEntry,
path::{Glob, SpecialHandling},
},
crossterm::style::Attribute,
ahash::AHashMap,
fnv::FnvHashMap,
serde::Deserialize,
std::{
fs, io,
path::{Path, PathBuf},
},
};
macro_rules! overwrite {
($dst: ident, $prop: ident, $src: ident) => {
if $src.$prop.is_some() {
$dst.$prop = $src.$prop.take();
}
};
}
macro_rules! overwrite_map {
($dst: ident, $prop: ident, $src: ident) => {
for (k, v) in $src.$prop {
$dst.$prop.insert(k, v);
}
};
}
/// The configuration read from conf.toml or conf.hjson file(s)
#[derive(Default, Clone, Debug, Deserialize)]
pub struct Conf {
/// the files used to load this configuration
#[serde(skip)]
pub files: Vec<PathBuf>,
#[serde(alias="default-flags")]
pub default_flags: Option<String>, // the flags to apply before cli ones
#[serde(alias="date-time-format")]
pub date_time_format: Option<String>,
#[serde(default)]
pub verbs: Vec<VerbConf>,
pub skin: Option<AHashMap<String, SkinEntry>>,
#[serde(default, alias="special-paths")]
pub special_paths: AHashMap<Glob, SpecialHandling>,
#[serde(alias="search-modes")]
pub search_modes: Option<FnvHashMap<String, String>>,
#[serde(alias="disable-mouse-capture")]
pub disable_mouse_capture: Option<bool>,
#[serde(alias="cols-order")]
pub cols_order: Option<ColsConf>,
#[serde(alias="show-selection-mark")]
pub show_selection_mark: Option<bool>,
#[serde(default, alias="ext-colors")]
pub ext_colors: AHashMap<String, String>,
#[serde(alias="syntax-theme")]
pub syntax_theme: Option<String>,
#[serde(alias="true-colors")]
pub true_colors: Option<bool>,
#[serde(alias="icon-theme")]
pub icon_theme: Option<String>,
pub modal: Option<bool>,
pub max_panels_count: Option<usize>,
#[serde(alias="quit-on-last-cancel")]
pub quit_on_last_cancel: Option<bool>,
pub file_sum_threads_count: Option<usize>,
}
impl Conf {
/// return the path to the default conf.toml file.
/// If there's no conf.hjson file in the default conf directory,
/// and if there's a toml file, return this toml file.
pub fn default_location() -> PathBuf {
let hjson_file = super::dir().join("conf.hjson");
if !hjson_file.exists() {
let toml_file = super::dir().join("conf.toml");
if toml_file.exists() {
return toml_file;
}
}
// neither file exists, we return the default one
hjson_file
}
/// read the configuration file from the default OS specific location.
/// Create it if it doesn't exist
pub fn from_default_location() -> Result<Conf, ProgramError> {
let conf_filepath = Conf::default_location();
if !conf_filepath.exists() {
Conf::write_sample(&conf_filepath)?;
println!(
"New Configuration file written in {}{:?}{}.",
Attribute::Bold,
&conf_filepath,
Attribute::Reset,
);
println!("You should have a look at it.");
}
let mut conf = Conf::default();
match conf.read_file(conf_filepath) {
Err(e) => Err(e),
_ => Ok(conf),
}
}
/// assume the file doesn't yet exist
pub fn write_sample(filepath: &Path) -> Result<(), io::Error> {
fs::create_dir_all(filepath.parent().unwrap())?;
fs::write(filepath, DEFAULT_CONF_FILE)?;
Ok(())
}
/// read the configuration from a given path. Assume it exists.
/// Values set in the read file replace the ones of self.
/// Errors are printed on stderr (assuming this function is called
/// before terminal alternation).
pub fn read_file(&mut self, path: PathBuf) -> Result<(), ProgramError> {
let mut conf: Conf = SerdeFormat::read_file(&path)?;
overwrite!(self, default_flags, conf);
overwrite!(self, date_time_format, conf);
overwrite!(self, icon_theme, conf);
overwrite!(self, syntax_theme, conf);
overwrite!(self, disable_mouse_capture, conf);
overwrite!(self, true_colors, conf);
overwrite!(self, show_selection_mark, conf);
overwrite!(self, cols_order, conf);
overwrite!(self, skin, conf);
overwrite!(self, search_modes, conf);
overwrite!(self, max_panels_count, conf);
overwrite!(self, modal, conf);
overwrite!(self, quit_on_last_cancel, conf);
overwrite!(self, file_sum_threads_count, conf);
self.verbs.append(&mut conf.verbs);
// the following maps are "additive": we can add entries from several
// config files and they still make sense
overwrite_map!(self, special_paths, conf);
overwrite_map!(self, ext_colors, conf);
self.files.push(path);
Ok(())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.