text
stringlengths
8
4.13M
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use day_17::{self, INPUT}; fn criterion_benchmark(c: &mut Criterion) { let parse_result = day_17::parse_input(INPUT); c.bench_function("day_17::parse_input", |b| { b.iter(|| day_17::parse_input(black_box(INPUT))); }); c.bench_function("day_17::part_one", |b| { b.iter(|| day_17::part_one(black_box(&parse_result))); }); c.bench_function("day_17::part_two", |b| { b.iter(|| day_17::part_two(black_box(&parse_result))); }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
pub mod get_instrument_candles { #[allow(unused_imports)] use chrono::prelude::*; #[allow(unused_imports)] use fxoanda_definitions::*; use std::error::Error; use Client; #[derive(Debug, Serialize, Deserialize)] struct RequestHead { #[serde(rename = "Authorization", skip_serializing_if = "Option::is_none")] pub authorization: Option<String>, #[serde( rename = "AcceptDatetimeFormat", skip_serializing_if = "Option::is_none" )] pub accept_datetime_format: Option<String>, } impl RequestHead { fn new() -> RequestHead { RequestHead { authorization: None, accept_datetime_format: None, } } } #[derive(Debug, Serialize, Deserialize)] struct RequestPath { #[serde(rename = "instrument", skip_serializing_if = "Option::is_none")] pub instrument: Option<String>, } impl RequestPath { fn new() -> RequestPath { RequestPath { instrument: None } } } #[derive(Debug, Serialize, Deserialize)] struct RequestBody {} impl RequestBody { fn new() -> RequestBody { RequestBody {} } } #[derive(Debug, Serialize, Deserialize)] struct RequestQuery { #[serde(rename = "price", skip_serializing_if = "Option::is_none")] pub price: Option<String>, #[serde(rename = "granularity", skip_serializing_if = "Option::is_none")] pub granularity: Option<CandlestickGranularity>, #[serde(rename = "count", skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[serde( rename = "from", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub from: Option<DateTime<Utc>>, #[serde( rename = "to", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub to: Option<DateTime<Utc>>, #[serde(rename = "smooth", skip_serializing_if = "Option::is_none")] pub smooth: Option<bool>, #[serde(rename = "includeFirst", skip_serializing_if = "Option::is_none")] pub include_first: Option<bool>, #[serde(rename = "dailyAlignment", skip_serializing_if = "Option::is_none")] pub daily_alignment: Option<i32>, #[serde(rename = "alignmentTimezone", skip_serializing_if = "Option::is_none")] pub alignment_timezone: Option<String>, #[serde(rename = "weeklyAlignment", skip_serializing_if = "Option::is_none")] pub weekly_alignment: Option<String>, } impl RequestQuery { fn new() -> RequestQuery { RequestQuery { price: None, granularity: None, count: None, from: None, to: None, smooth: None, include_first: None, daily_alignment: None, alignment_timezone: None, weekly_alignment: None, } } } /// Get Candlesticks /// Fetch candlestick data for an instrument. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentCandlesRequest { #[serde(skip_serializing)] uri: String, header: RequestHead, body: RequestBody, path: RequestPath, query: RequestQuery, } impl GetInstrumentCandlesRequest { pub fn new() -> GetInstrumentCandlesRequest { GetInstrumentCandlesRequest { uri: String::from("/v3/instruments/{instrument}/candles"), header: RequestHead::new(), body: RequestBody::new(), path: RequestPath::new(), query: RequestQuery::new(), } } pub fn with_uri(mut self, x: String) -> Self { self.uri = x; self } /// Name of the Instrument /// format: A string containing the base currency and quote currency delimited by /// a "_". /// - param String /// - return GetInstrumentCandlesRequest pub fn with_instrument(mut self, x: String) -> Self { self.path.instrument = Some(x); self } /// The authorization bearer token previously obtained by the client /// format: The string 'Bearer ' followed by the token. /// - param String /// - return GetInstrumentCandlesRequest pub fn with_authorization(mut self, x: String) -> Self { self.header.authorization = Some(x); self } /// Format of DateTime fields in the request and response. /// - param String /// - return GetInstrumentCandlesRequest pub fn with_accept_datetime_format(mut self, x: String) -> Self { self.header.accept_datetime_format = Some(x); self } /// The Price component(s) to get candlestick data for. Can contain any /// combination of the characters "M" (midpoint candles) "B" (bid candles) /// and "A" (ask candles). /// - param String /// - return GetInstrumentCandlesRequest pub fn with_price(mut self, x: String) -> Self { self.query.price = Some(x); self } /// The granularity of the candlesticks to fetch /// - param CandlestickGranularity /// - return GetInstrumentCandlesRequest pub fn with_granularity(mut self, x: CandlestickGranularity) -> Self { self.query.granularity = Some(x); self } /// The number of candlesticks to return in the reponse. Count should not /// be specified if both the start and end parameters are provided, as the /// time range combined with the graularity will determine the number of /// candlesticks to return. /// - param i32 /// - return GetInstrumentCandlesRequest pub fn with_count(mut self, x: i32) -> Self { self.query.count = Some(x); self } /// The start of the time range to fetch candlesticks for. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetInstrumentCandlesRequest pub fn with_from(mut self, x: DateTime<Utc>) -> Self { self.query.from = Some(x); self } /// The end of the time range to fetch candlesticks for. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetInstrumentCandlesRequest pub fn with_to(mut self, x: DateTime<Utc>) -> Self { self.query.to = Some(x); self } /// A flag that controls whether the candlestick is "smoothed" or not. A /// smoothed candlestick uses the previous candle's close price as its /// open price, while an unsmoothed candlestick uses the first price from /// its time range as its open price. /// - param bool /// - return GetInstrumentCandlesRequest pub fn with_smooth(mut self, x: bool) -> Self { self.query.smooth = Some(x); self } /// A flag that controls whether the candlestick that is covered by the /// from time should be included in the results. This flag enables clients /// to use the timestamp of the last completed candlestick received to /// poll for future candlesticks but avoid receiving the previous /// candlestick repeatedly. /// - param bool /// - return GetInstrumentCandlesRequest pub fn with_include_first(mut self, x: bool) -> Self { self.query.include_first = Some(x); self } /// The hour of the day (in the specified timezone) to use for /// granularities that have daily alignments. /// - param i32 /// - return GetInstrumentCandlesRequest pub fn with_daily_alignment(mut self, x: i32) -> Self { self.query.daily_alignment = Some(x); self } /// The timezone to use for the dailyAlignment parameter. Candlesticks /// with daily alignment will be aligned to the dailyAlignment hour within /// the alignmentTimezone. Note that the returned times will still be /// represented in UTC. /// - param String /// - return GetInstrumentCandlesRequest pub fn with_alignment_timezone(mut self, x: String) -> Self { self.query.alignment_timezone = Some(x); self } /// The day of the week used for granularities that have weekly alignment. /// - param String /// - return GetInstrumentCandlesRequest pub fn with_weekly_alignment(mut self, x: String) -> Self { self.query.weekly_alignment = Some(x); self } pub fn remote( self, client: &Client, ) -> Result<GetInstrumentCandlesResponse, Box<dyn Error>> { let uri = self .uri .clone() .replace("{instrument}", &self.path.instrument.unwrap()); let url = format!("https://{host}{uri}", host = client.host, uri = uri); let res = client .reqwest .get(&url) .query(&self.query) .bearer_auth(&client.authentication) .send(); match res { Err(e) => Err(Box::new(e)), Ok(response) => match response.json::<GetInstrumentCandlesResponse>() { Err(e) => Err(Box::new(e)), Ok(j) => Ok(j), }, } } } pub type GetInstrumentCandlesResponse = GetInstrumentCandlesResponse200Body; /// Pricing information has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentCandlesResponse200Header { /// The unique identifier generated for the request #[serde(rename = "RequestID", skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, } /// Pricing information has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentCandlesResponse200Body { /// The instrument whose Prices are represented by the candlesticks. /// format: A string containing the base currency and quote currency delimited by /// a "_". #[serde(rename = "instrument", skip_serializing_if = "Option::is_none")] pub instrument: Option<String>, /// The granularity of the candlesticks provided. #[serde(rename = "granularity", skip_serializing_if = "Option::is_none")] pub granularity: Option<CandlestickGranularity>, /// The list of candlesticks that satisfy the request. #[serde(rename = "candles", skip_serializing_if = "Option::is_none")] pub candles: Option<Vec<Candlestick>>, } } pub mod get_instrument_price { #[allow(unused_imports)] use chrono::prelude::*; #[allow(unused_imports)] use fxoanda_definitions::*; use std::error::Error; use Client; #[derive(Debug, Serialize, Deserialize)] struct RequestHead { #[serde(rename = "Authorization", skip_serializing_if = "Option::is_none")] pub authorization: Option<String>, #[serde( rename = "AcceptDatetimeFormat", skip_serializing_if = "Option::is_none" )] pub accept_datetime_format: Option<String>, } impl RequestHead { fn new() -> RequestHead { RequestHead { authorization: None, accept_datetime_format: None, } } } #[derive(Debug, Serialize, Deserialize)] struct RequestPath { #[serde(rename = "instrument", skip_serializing_if = "Option::is_none")] pub instrument: Option<String>, } impl RequestPath { fn new() -> RequestPath { RequestPath { instrument: None } } } #[derive(Debug, Serialize, Deserialize)] struct RequestBody {} impl RequestBody { fn new() -> RequestBody { RequestBody {} } } #[derive(Debug, Serialize, Deserialize)] struct RequestQuery { #[serde( rename = "time", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub time: Option<DateTime<Utc>>, } impl RequestQuery { fn new() -> RequestQuery { RequestQuery { time: None } } } /// Price /// Fetch a price for an instrument. Accounts are not associated in any /// way with this endpoint. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentPriceRequest { #[serde(skip_serializing)] uri: String, header: RequestHead, body: RequestBody, path: RequestPath, query: RequestQuery, } impl GetInstrumentPriceRequest { pub fn new() -> GetInstrumentPriceRequest { GetInstrumentPriceRequest { uri: String::from("/v3/instruments/{instrument}/price"), header: RequestHead::new(), body: RequestBody::new(), path: RequestPath::new(), query: RequestQuery::new(), } } pub fn with_uri(mut self, x: String) -> Self { self.uri = x; self } /// Name of the Instrument /// format: A string containing the base currency and quote currency delimited by /// a "_". /// - param String /// - return GetInstrumentPriceRequest pub fn with_instrument(mut self, x: String) -> Self { self.path.instrument = Some(x); self } /// The authorization bearer token previously obtained by the client /// format: The string 'Bearer ' followed by the token. /// - param String /// - return GetInstrumentPriceRequest pub fn with_authorization(mut self, x: String) -> Self { self.header.authorization = Some(x); self } /// Format of DateTime fields in the request and response. /// - param String /// - return GetInstrumentPriceRequest pub fn with_accept_datetime_format(mut self, x: String) -> Self { self.header.accept_datetime_format = Some(x); self } /// The time at which the desired price is in effect. The current price is /// returned if no time is provided. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetInstrumentPriceRequest pub fn with_time(mut self, x: DateTime<Utc>) -> Self { self.query.time = Some(x); self } pub fn remote(self, client: &Client) -> Result<GetInstrumentPriceResponse, Box<dyn Error>> { let uri = self .uri .clone() .replace("{instrument}", &self.path.instrument.unwrap()); let url = format!("https://{host}{uri}", host = client.host, uri = uri); let res = client .reqwest .get(&url) .query(&self.query) .bearer_auth(&client.authentication) .send(); match res { Err(e) => Err(Box::new(e)), Ok(response) => match response.json::<GetInstrumentPriceResponse>() { Err(e) => Err(Box::new(e)), Ok(j) => Ok(j), }, } } } pub type GetInstrumentPriceResponse = GetInstrumentPriceResponse200Body; /// Pricing information has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentPriceResponse200Header { /// The unique identifier generated for the request #[serde(rename = "RequestID", skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, } /// Pricing information has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentPriceResponse200Body { /// The Price representation #[serde(rename = "price", skip_serializing_if = "Option::is_none")] pub price: Option<Price>, } } pub mod get_instrument_price_range { #[allow(unused_imports)] use chrono::prelude::*; #[allow(unused_imports)] use fxoanda_definitions::*; use std::error::Error; use Client; #[derive(Debug, Serialize, Deserialize)] struct RequestHead { #[serde(rename = "Authorization", skip_serializing_if = "Option::is_none")] pub authorization: Option<String>, #[serde( rename = "AcceptDatetimeFormat", skip_serializing_if = "Option::is_none" )] pub accept_datetime_format: Option<String>, } impl RequestHead { fn new() -> RequestHead { RequestHead { authorization: None, accept_datetime_format: None, } } } #[derive(Debug, Serialize, Deserialize)] struct RequestPath { #[serde(rename = "instrument", skip_serializing_if = "Option::is_none")] pub instrument: Option<String>, } impl RequestPath { fn new() -> RequestPath { RequestPath { instrument: None } } } #[derive(Debug, Serialize, Deserialize)] struct RequestBody {} impl RequestBody { fn new() -> RequestBody { RequestBody {} } } #[derive(Debug, Serialize, Deserialize)] struct RequestQuery { #[serde( rename = "from", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub from: Option<DateTime<Utc>>, #[serde( rename = "to", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub to: Option<DateTime<Utc>>, } impl RequestQuery { fn new() -> RequestQuery { RequestQuery { from: None, to: None, } } } /// Get Prices /// Fetch a range of prices for an instrument. Accounts are not associated /// in any way with this endpoint. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentPriceRangeRequest { #[serde(skip_serializing)] uri: String, header: RequestHead, body: RequestBody, path: RequestPath, query: RequestQuery, } impl GetInstrumentPriceRangeRequest { pub fn new() -> GetInstrumentPriceRangeRequest { GetInstrumentPriceRangeRequest { uri: String::from("/v3/instruments/{instrument}/price/range"), header: RequestHead::new(), body: RequestBody::new(), path: RequestPath::new(), query: RequestQuery::new(), } } pub fn with_uri(mut self, x: String) -> Self { self.uri = x; self } /// Name of the Instrument /// format: A string containing the base currency and quote currency delimited by /// a "_". /// - param String /// - return GetInstrumentPriceRangeRequest pub fn with_instrument(mut self, x: String) -> Self { self.path.instrument = Some(x); self } /// The authorization bearer token previously obtained by the client /// format: The string 'Bearer ' followed by the token. /// - param String /// - return GetInstrumentPriceRangeRequest pub fn with_authorization(mut self, x: String) -> Self { self.header.authorization = Some(x); self } /// Format of DateTime fields in the request and response. /// - param String /// - return GetInstrumentPriceRangeRequest pub fn with_accept_datetime_format(mut self, x: String) -> Self { self.header.accept_datetime_format = Some(x); self } /// The start of the time range to fetch prices for. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetInstrumentPriceRangeRequest pub fn with_from(mut self, x: DateTime<Utc>) -> Self { self.query.from = Some(x); self } /// The end of the time range to fetch prices for. The current time is /// used if this parameter is not provided. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetInstrumentPriceRangeRequest pub fn with_to(mut self, x: DateTime<Utc>) -> Self { self.query.to = Some(x); self } pub fn remote( self, client: &Client, ) -> Result<GetInstrumentPriceRangeResponse, Box<dyn Error>> { let uri = self .uri .clone() .replace("{instrument}", &self.path.instrument.unwrap()); let url = format!("https://{host}{uri}", host = client.host, uri = uri); let res = client .reqwest .get(&url) .query(&self.query) .bearer_auth(&client.authentication) .send(); match res { Err(e) => Err(Box::new(e)), Ok(response) => match response.json::<GetInstrumentPriceRangeResponse>() { Err(e) => Err(Box::new(e)), Ok(j) => Ok(j), }, } } } pub type GetInstrumentPriceRangeResponse = GetInstrumentPriceRangeResponse200Body; /// Pricing information has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentPriceRangeResponse200Header { /// The unique identifier generated for the request #[serde(rename = "RequestID", skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, /// A link to the next page of results if the results were paginated #[serde(rename = "Link", skip_serializing_if = "Option::is_none")] pub link: Option<String>, } /// Pricing information has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetInstrumentPriceRangeResponse200Body { /// The list of prices that satisfy the request. #[serde(rename = "prices", skip_serializing_if = "Option::is_none")] pub prices: Option<Vec<Price>>, } } pub mod get_order_book { #[allow(unused_imports)] use chrono::prelude::*; #[allow(unused_imports)] use fxoanda_definitions::*; use std::error::Error; use Client; #[derive(Debug, Serialize, Deserialize)] struct RequestHead { #[serde(rename = "Authorization", skip_serializing_if = "Option::is_none")] pub authorization: Option<String>, #[serde( rename = "AcceptDatetimeFormat", skip_serializing_if = "Option::is_none" )] pub accept_datetime_format: Option<String>, } impl RequestHead { fn new() -> RequestHead { RequestHead { authorization: None, accept_datetime_format: None, } } } #[derive(Debug, Serialize, Deserialize)] struct RequestPath { #[serde(rename = "instrument", skip_serializing_if = "Option::is_none")] pub instrument: Option<String>, } impl RequestPath { fn new() -> RequestPath { RequestPath { instrument: None } } } #[derive(Debug, Serialize, Deserialize)] struct RequestBody {} impl RequestBody { fn new() -> RequestBody { RequestBody {} } } #[derive(Debug, Serialize, Deserialize)] struct RequestQuery { #[serde( rename = "time", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub time: Option<DateTime<Utc>>, } impl RequestQuery { fn new() -> RequestQuery { RequestQuery { time: None } } } /// Get Order Book /// Fetch an order book for an instrument. #[derive(Debug, Serialize, Deserialize)] pub struct GetOrderBookRequest { #[serde(skip_serializing)] uri: String, header: RequestHead, body: RequestBody, path: RequestPath, query: RequestQuery, } impl GetOrderBookRequest { pub fn new() -> GetOrderBookRequest { GetOrderBookRequest { uri: String::from("/v3/instruments/{instrument}/orderBook"), header: RequestHead::new(), body: RequestBody::new(), path: RequestPath::new(), query: RequestQuery::new(), } } pub fn with_uri(mut self, x: String) -> Self { self.uri = x; self } /// Name of the Instrument /// format: A string containing the base currency and quote currency delimited by /// a "_". /// - param String /// - return GetOrderBookRequest pub fn with_instrument(mut self, x: String) -> Self { self.path.instrument = Some(x); self } /// The authorization bearer token previously obtained by the client /// format: The string 'Bearer ' followed by the token. /// - param String /// - return GetOrderBookRequest pub fn with_authorization(mut self, x: String) -> Self { self.header.authorization = Some(x); self } /// Format of DateTime fields in the request and response. /// - param String /// - return GetOrderBookRequest pub fn with_accept_datetime_format(mut self, x: String) -> Self { self.header.accept_datetime_format = Some(x); self } /// The time of the snapshot to fetch. If not specified, then the most /// recent snapshot is fetched. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetOrderBookRequest pub fn with_time(mut self, x: DateTime<Utc>) -> Self { self.query.time = Some(x); self } pub fn remote(self, client: &Client) -> Result<GetOrderBookResponse, Box<dyn Error>> { let uri = self .uri .clone() .replace("{instrument}", &self.path.instrument.unwrap()); let url = format!("https://{host}{uri}", host = client.host, uri = uri); let res = client .reqwest .get(&url) .query(&self.query) .bearer_auth(&client.authentication) .send(); match res { Err(e) => Err(Box::new(e)), Ok(response) => match response.json::<GetOrderBookResponse>() { Err(e) => Err(Box::new(e)), Ok(j) => Ok(j), }, } } } pub type GetOrderBookResponse = GetOrderBookResponse200Body; /// The order book has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetOrderBookResponse200Header { /// Value will be "gzip" regardless of provided Accept-Encoding header #[serde(rename = "ContentEncoding", skip_serializing_if = "Option::is_none")] pub content_encoding: Option<String>, /// A link to the next/previous order book snapshot. #[serde(rename = "Link", skip_serializing_if = "Option::is_none")] pub link: Option<String>, /// The unique identifier generated for the request #[serde(rename = "RequestID", skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, } /// The order book has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetOrderBookResponse200Body { /// The representation of an instrument's order book at a point in time #[serde(rename = "orderBook", skip_serializing_if = "Option::is_none")] pub order_book: Option<OrderBook>, } } pub mod get_position_book { #[allow(unused_imports)] use chrono::prelude::*; #[allow(unused_imports)] use fxoanda_definitions::*; use std::error::Error; use Client; #[derive(Debug, Serialize, Deserialize)] struct RequestHead { #[serde(rename = "Authorization", skip_serializing_if = "Option::is_none")] pub authorization: Option<String>, #[serde( rename = "AcceptDatetimeFormat", skip_serializing_if = "Option::is_none" )] pub accept_datetime_format: Option<String>, } impl RequestHead { fn new() -> RequestHead { RequestHead { authorization: None, accept_datetime_format: None, } } } #[derive(Debug, Serialize, Deserialize)] struct RequestPath { #[serde(rename = "instrument", skip_serializing_if = "Option::is_none")] pub instrument: Option<String>, } impl RequestPath { fn new() -> RequestPath { RequestPath { instrument: None } } } #[derive(Debug, Serialize, Deserialize)] struct RequestBody {} impl RequestBody { fn new() -> RequestBody { RequestBody {} } } #[derive(Debug, Serialize, Deserialize)] struct RequestQuery { #[serde( rename = "time", skip_serializing_if = "Option::is_none", with = "fxoanda_serdes::serdates" )] pub time: Option<DateTime<Utc>>, } impl RequestQuery { fn new() -> RequestQuery { RequestQuery { time: None } } } /// Get Position Book /// Fetch a position book for an instrument. #[derive(Debug, Serialize, Deserialize)] pub struct GetPositionBookRequest { #[serde(skip_serializing)] uri: String, header: RequestHead, body: RequestBody, path: RequestPath, query: RequestQuery, } impl GetPositionBookRequest { pub fn new() -> GetPositionBookRequest { GetPositionBookRequest { uri: String::from("/v3/instruments/{instrument}/positionBook"), header: RequestHead::new(), body: RequestBody::new(), path: RequestPath::new(), query: RequestQuery::new(), } } pub fn with_uri(mut self, x: String) -> Self { self.uri = x; self } /// Name of the Instrument /// format: A string containing the base currency and quote currency delimited by /// a "_". /// - param String /// - return GetPositionBookRequest pub fn with_instrument(mut self, x: String) -> Self { self.path.instrument = Some(x); self } /// The authorization bearer token previously obtained by the client /// format: The string 'Bearer ' followed by the token. /// - param String /// - return GetPositionBookRequest pub fn with_authorization(mut self, x: String) -> Self { self.header.authorization = Some(x); self } /// Format of DateTime fields in the request and response. /// - param String /// - return GetPositionBookRequest pub fn with_accept_datetime_format(mut self, x: String) -> Self { self.header.accept_datetime_format = Some(x); self } /// The time of the snapshot to fetch. If not specified, then the most /// recent snapshot is fetched. /// format: The RFC 3339 representation is a string conforming to /// https://tools.ietf.org/rfc/rfc3339.txt. The Unix representation is a /// string representing the number of seconds since the Unix Epoch /// (January 1st, 1970 at UTC). The value is a fractional number, where /// the fractional part represents a fraction of a second (up to nine /// decimal places). /// - param DateTime<Utc> /// - return GetPositionBookRequest pub fn with_time(mut self, x: DateTime<Utc>) -> Self { self.query.time = Some(x); self } pub fn remote(self, client: &Client) -> Result<GetPositionBookResponse, Box<dyn Error>> { let uri = self .uri .clone() .replace("{instrument}", &self.path.instrument.unwrap()); let url = format!("https://{host}{uri}", host = client.host, uri = uri); let res = client .reqwest .get(&url) .query(&self.query) .bearer_auth(&client.authentication) .send(); match res { Err(e) => Err(Box::new(e)), Ok(response) => match response.json::<GetPositionBookResponse>() { Err(e) => Err(Box::new(e)), Ok(j) => Ok(j), }, } } } pub type GetPositionBookResponse = GetPositionBookResponse200Body; /// The position book has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetPositionBookResponse200Header { /// Value will be "gzip" regardless of provided Accept-Encoding header #[serde(rename = "ContentEncoding", skip_serializing_if = "Option::is_none")] pub content_encoding: Option<String>, /// A link to the next/previous position book snapshot. #[serde(rename = "Link", skip_serializing_if = "Option::is_none")] pub link: Option<String>, /// The unique identifier generated for the request #[serde(rename = "RequestID", skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, } /// The position book has been successfully provided. #[derive(Debug, Serialize, Deserialize)] pub struct GetPositionBookResponse200Body { /// The representation of an instrument's position book at a point in time #[serde(rename = "positionBook", skip_serializing_if = "Option::is_none")] pub position_book: Option<PositionBook>, } } pub use get_instrument_candles::*; pub use get_instrument_price::*; pub use get_instrument_price_range::*; pub use get_order_book::*; pub use get_position_book::*;
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::IM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct UART_IM_RIMIMR { bits: bool, } impl UART_IM_RIMIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_RIMIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_RIMIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_CTSMIMR { bits: bool, } impl UART_IM_CTSMIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_CTSMIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_CTSMIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_DCDMIMR { bits: bool, } impl UART_IM_DCDMIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_DCDMIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_DCDMIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_DSRMIMR { bits: bool, } impl UART_IM_DSRMIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_DSRMIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_DSRMIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_RXIMR { bits: bool, } impl UART_IM_RXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_RXIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_RXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_TXIMR { bits: bool, } impl UART_IM_TXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_TXIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_TXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_RTIMR { bits: bool, } impl UART_IM_RTIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_RTIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_RTIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_FEIMR { bits: bool, } impl UART_IM_FEIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_FEIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_FEIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_PEIMR { bits: bool, } impl UART_IM_PEIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_PEIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_PEIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_BEIMR { bits: bool, } impl UART_IM_BEIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_BEIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_BEIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_OEIMR { bits: bool, } impl UART_IM_OEIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_OEIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_OEIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_EOTIMR { bits: bool, } impl UART_IM_EOTIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_EOTIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_EOTIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_9BITIMR { bits: bool, } impl UART_IM_9BITIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_9BITIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_9BITIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 12); self.w.bits |= ((value as u32) & 1) << 12; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_DMARXIMR { bits: bool, } impl UART_IM_DMARXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_DMARXIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_DMARXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 16); self.w.bits |= ((value as u32) & 1) << 16; self.w } } #[doc = r"Value of the field"] pub struct UART_IM_DMATXIMR { bits: bool, } impl UART_IM_DMATXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _UART_IM_DMATXIMW<'a> { w: &'a mut W, } impl<'a> _UART_IM_DMATXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 17); self.w.bits |= ((value as u32) & 1) << 17; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - UART Ring Indicator Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_rimim(&self) -> UART_IM_RIMIMR { let bits = ((self.bits >> 0) & 1) != 0; UART_IM_RIMIMR { bits } } #[doc = "Bit 1 - UART Clear to Send Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_ctsmim(&self) -> UART_IM_CTSMIMR { let bits = ((self.bits >> 1) & 1) != 0; UART_IM_CTSMIMR { bits } } #[doc = "Bit 2 - UART Data Carrier Detect Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_dcdmim(&self) -> UART_IM_DCDMIMR { let bits = ((self.bits >> 2) & 1) != 0; UART_IM_DCDMIMR { bits } } #[doc = "Bit 3 - UART Data Set Ready Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_dsrmim(&self) -> UART_IM_DSRMIMR { let bits = ((self.bits >> 3) & 1) != 0; UART_IM_DSRMIMR { bits } } #[doc = "Bit 4 - UART Receive Interrupt Mask"] #[inline(always)] pub fn uart_im_rxim(&self) -> UART_IM_RXIMR { let bits = ((self.bits >> 4) & 1) != 0; UART_IM_RXIMR { bits } } #[doc = "Bit 5 - UART Transmit Interrupt Mask"] #[inline(always)] pub fn uart_im_txim(&self) -> UART_IM_TXIMR { let bits = ((self.bits >> 5) & 1) != 0; UART_IM_TXIMR { bits } } #[doc = "Bit 6 - UART Receive Time-Out Interrupt Mask"] #[inline(always)] pub fn uart_im_rtim(&self) -> UART_IM_RTIMR { let bits = ((self.bits >> 6) & 1) != 0; UART_IM_RTIMR { bits } } #[doc = "Bit 7 - UART Framing Error Interrupt Mask"] #[inline(always)] pub fn uart_im_feim(&self) -> UART_IM_FEIMR { let bits = ((self.bits >> 7) & 1) != 0; UART_IM_FEIMR { bits } } #[doc = "Bit 8 - UART Parity Error Interrupt Mask"] #[inline(always)] pub fn uart_im_peim(&self) -> UART_IM_PEIMR { let bits = ((self.bits >> 8) & 1) != 0; UART_IM_PEIMR { bits } } #[doc = "Bit 9 - UART Break Error Interrupt Mask"] #[inline(always)] pub fn uart_im_beim(&self) -> UART_IM_BEIMR { let bits = ((self.bits >> 9) & 1) != 0; UART_IM_BEIMR { bits } } #[doc = "Bit 10 - UART Overrun Error Interrupt Mask"] #[inline(always)] pub fn uart_im_oeim(&self) -> UART_IM_OEIMR { let bits = ((self.bits >> 10) & 1) != 0; UART_IM_OEIMR { bits } } #[doc = "Bit 11 - End of Transmission Interrupt Mask"] #[inline(always)] pub fn uart_im_eotim(&self) -> UART_IM_EOTIMR { let bits = ((self.bits >> 11) & 1) != 0; UART_IM_EOTIMR { bits } } #[doc = "Bit 12 - 9-Bit Mode Interrupt Mask"] #[inline(always)] pub fn uart_im_9bitim(&self) -> UART_IM_9BITIMR { let bits = ((self.bits >> 12) & 1) != 0; UART_IM_9BITIMR { bits } } #[doc = "Bit 16 - Receive DMA Interrupt Mask"] #[inline(always)] pub fn uart_im_dmarxim(&self) -> UART_IM_DMARXIMR { let bits = ((self.bits >> 16) & 1) != 0; UART_IM_DMARXIMR { bits } } #[doc = "Bit 17 - Transmit DMA Interrupt Mask"] #[inline(always)] pub fn uart_im_dmatxim(&self) -> UART_IM_DMATXIMR { let bits = ((self.bits >> 17) & 1) != 0; UART_IM_DMATXIMR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - UART Ring Indicator Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_rimim(&mut self) -> _UART_IM_RIMIMW { _UART_IM_RIMIMW { w: self } } #[doc = "Bit 1 - UART Clear to Send Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_ctsmim(&mut self) -> _UART_IM_CTSMIMW { _UART_IM_CTSMIMW { w: self } } #[doc = "Bit 2 - UART Data Carrier Detect Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_dcdmim(&mut self) -> _UART_IM_DCDMIMW { _UART_IM_DCDMIMW { w: self } } #[doc = "Bit 3 - UART Data Set Ready Modem Interrupt Mask"] #[inline(always)] pub fn uart_im_dsrmim(&mut self) -> _UART_IM_DSRMIMW { _UART_IM_DSRMIMW { w: self } } #[doc = "Bit 4 - UART Receive Interrupt Mask"] #[inline(always)] pub fn uart_im_rxim(&mut self) -> _UART_IM_RXIMW { _UART_IM_RXIMW { w: self } } #[doc = "Bit 5 - UART Transmit Interrupt Mask"] #[inline(always)] pub fn uart_im_txim(&mut self) -> _UART_IM_TXIMW { _UART_IM_TXIMW { w: self } } #[doc = "Bit 6 - UART Receive Time-Out Interrupt Mask"] #[inline(always)] pub fn uart_im_rtim(&mut self) -> _UART_IM_RTIMW { _UART_IM_RTIMW { w: self } } #[doc = "Bit 7 - UART Framing Error Interrupt Mask"] #[inline(always)] pub fn uart_im_feim(&mut self) -> _UART_IM_FEIMW { _UART_IM_FEIMW { w: self } } #[doc = "Bit 8 - UART Parity Error Interrupt Mask"] #[inline(always)] pub fn uart_im_peim(&mut self) -> _UART_IM_PEIMW { _UART_IM_PEIMW { w: self } } #[doc = "Bit 9 - UART Break Error Interrupt Mask"] #[inline(always)] pub fn uart_im_beim(&mut self) -> _UART_IM_BEIMW { _UART_IM_BEIMW { w: self } } #[doc = "Bit 10 - UART Overrun Error Interrupt Mask"] #[inline(always)] pub fn uart_im_oeim(&mut self) -> _UART_IM_OEIMW { _UART_IM_OEIMW { w: self } } #[doc = "Bit 11 - End of Transmission Interrupt Mask"] #[inline(always)] pub fn uart_im_eotim(&mut self) -> _UART_IM_EOTIMW { _UART_IM_EOTIMW { w: self } } #[doc = "Bit 12 - 9-Bit Mode Interrupt Mask"] #[inline(always)] pub fn uart_im_9bitim(&mut self) -> _UART_IM_9BITIMW { _UART_IM_9BITIMW { w: self } } #[doc = "Bit 16 - Receive DMA Interrupt Mask"] #[inline(always)] pub fn uart_im_dmarxim(&mut self) -> _UART_IM_DMARXIMW { _UART_IM_DMARXIMW { w: self } } #[doc = "Bit 17 - Transmit DMA Interrupt Mask"] #[inline(always)] pub fn uart_im_dmatxim(&mut self) -> _UART_IM_DMATXIMW { _UART_IM_DMATXIMW { w: self } } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::Result; use failure::ResultExt; use fidl::encoding::Decodable; use fidl::endpoints::create_endpoints; use fidl_fuchsia_media_sessions2::*; use fuchsia_async as fasync; use fuchsia_component as comp; use fuchsia_zircon::{self as zx, AsHandleRef}; use futures::stream::TryStreamExt; const MEDIASESSION_URL: &str = "fuchsia-pkg://fuchsia.com/mediasession#meta/mediasession.cmx"; struct TestService { // This needs to stay alive to keep the service running. #[allow(unused)] app: comp::client::App, publisher: PublisherProxy, discovery: DiscoveryProxy, } impl TestService { fn new() -> Result<Self> { let launcher = comp::client::launcher().context("Connecting to launcher")?; let mediasession = comp::client::launch(&launcher, String::from(MEDIASESSION_URL), None) .context("Launching mediasession")?; let publisher = mediasession .connect_to_service::<PublisherMarker>() .context("Connecting to Publisher")?; let discovery = mediasession .connect_to_service::<DiscoveryMarker>() .context("Connecting to Discovery")?; Ok(Self { app: mediasession, publisher, discovery }) } fn new_watcher(&self, watch_options: WatchOptions) -> Result<TestWatcher> { let (watcher_client, watcher_server) = create_endpoints()?; self.discovery.watch_sessions(watch_options, watcher_client)?; Ok(TestWatcher { watcher: watcher_server.into_stream()? }) } } struct TestWatcher { watcher: SessionsWatcherRequestStream, } impl TestWatcher { async fn wait_for_n_updates(&mut self, n: usize) -> Result<Vec<(u64, SessionInfoDelta)>> { let mut updates: Vec<(u64, SessionInfoDelta)> = vec![]; for i in 0..n { let (id, delta, responder) = self .watcher .try_next() .await? .and_then(|r| r.into_session_updated()) .expect(&format!("Unwrapping watcher request {:?}", i)); responder.send()?; updates.push((id, delta)); } Ok(updates) } async fn wait_for_removal(&mut self) -> Result<u64> { let (id, responder) = self .watcher .try_next() .await? .and_then(|r| r.into_session_removed()) .expect("Unwrapping watcher request"); responder.send()?; Ok(id) } } struct TestPlayer { requests: PlayerRequestStream, } impl TestPlayer { fn new(service: &TestService) -> Result<Self> { let (player_client, player_server) = create_endpoints()?; service .publisher .publish_player(player_client, PlayerRegistration { domain: Some(test_domain()) })?; let requests = player_server.into_stream()?; Ok(Self { requests }) } async fn emit_delta(&mut self, delta: PlayerInfoDelta) -> Result<()> { match self.requests.try_next().await? { Some(PlayerRequest::WatchInfoChange { responder }) => responder.send(delta)?, _ => { panic!("Expected status change request."); } } Ok(()) } async fn wait_for_request(&mut self, predicate: impl Fn(PlayerRequest) -> bool) -> Result<()> { while let Some(request) = self.requests.try_next().await? { if predicate(request) { return Ok(()); } } panic!("Did not receive request that matched predicate. ") } } fn test_domain() -> String { String::from("domain://TEST") } fn delta_with_state(state: PlayerState) -> PlayerInfoDelta { PlayerInfoDelta { player_status: Some(PlayerStatus { player_state: Some(state), repeat_mode: Some(RepeatMode::Off), shuffle_on: Some(false), content_type: Some(ContentType::Audio), ..Decodable::new_empty() }), ..Decodable::new_empty() } } #[fasync::run_singlethreaded] #[test] async fn can_publish_players() -> Result<()> { let service = TestService::new()?; let mut player = TestPlayer::new(&service)?; let mut watcher = service.new_watcher(Decodable::new_empty())?; player.emit_delta(delta_with_state(PlayerState::Playing)).await?; let mut sessions = watcher.wait_for_n_updates(1).await?; let (_id, delta) = sessions.remove(0); assert_eq!(delta.domain, Some(test_domain())); Ok(()) } #[fasync::run_singlethreaded] #[test] async fn can_receive_deltas() -> Result<()> { let service = TestService::new()?; let mut player1 = TestPlayer::new(&service)?; let mut player2 = TestPlayer::new(&service)?; let mut watcher = service.new_watcher(Decodable::new_empty())?; player1.emit_delta(delta_with_state(PlayerState::Playing)).await?; player2.emit_delta(delta_with_state(PlayerState::Playing)).await?; let _ = watcher.wait_for_n_updates(2).await?; player2 .emit_delta(PlayerInfoDelta { player_capabilities: Some(PlayerCapabilities { flags: Some(PlayerCapabilityFlags::Play), }), ..Decodable::new_empty() }) .await?; let mut updates = watcher.wait_for_n_updates(1).await?; let (_id, delta) = updates.remove(0); assert_eq!( delta.player_capabilities, Some(PlayerCapabilities { flags: Some(PlayerCapabilityFlags::Play) }) ); player1 .emit_delta(PlayerInfoDelta { player_capabilities: Some(PlayerCapabilities { flags: Some(PlayerCapabilityFlags::Pause), }), ..Decodable::new_empty() }) .await?; let mut updates = watcher.wait_for_n_updates(1).await?; let (_id, delta) = updates.remove(0); assert_eq!( delta.player_capabilities, Some(PlayerCapabilities { flags: Some(PlayerCapabilityFlags::Pause) }) ); Ok(()) } #[fasync::run_singlethreaded] #[test] async fn active_status() -> Result<()> { let service = TestService::new()?; let mut player1 = TestPlayer::new(&service)?; let mut player2 = TestPlayer::new(&service)?; let mut watcher = service.new_watcher(Decodable::new_empty())?; player1.emit_delta(delta_with_state(PlayerState::Idle)).await?; player2.emit_delta(delta_with_state(PlayerState::Idle)).await?; let _ = watcher.wait_for_n_updates(2).await?; player1.emit_delta(delta_with_state(PlayerState::Playing)).await?; let mut updates = watcher.wait_for_n_updates(1).await?; let (active_id, delta) = updates.remove(0); assert_eq!(delta.is_locally_active, Some(true)); player2.emit_delta(delta_with_state(PlayerState::Paused)).await?; let mut updates = watcher.wait_for_n_updates(1).await?; let (new_active_id, delta) = updates.remove(0); assert_eq!(delta.is_locally_active, Some(false)); assert_ne!(new_active_id, active_id); Ok(()) } #[fasync::run_singlethreaded] #[test] async fn player_controls_are_proxied() -> Result<()> { let service = TestService::new()?; let mut player = TestPlayer::new(&service)?; let mut watcher = service.new_watcher(Decodable::new_empty())?; player.emit_delta(delta_with_state(PlayerState::Playing)).await?; let mut updates = watcher.wait_for_n_updates(1).await?; let (id, _) = updates.remove(0); // We take the watch request from the player's queue and don't answer it, so that // the stream of requests coming in that we match on down below doesn't contain it. let _watch_request = player.requests.try_next().await?; let (session_client, session_server) = create_endpoints()?; let session: SessionControlProxy = session_client.into_proxy()?; session.play()?; service.discovery.connect_to_session(id, session_server)?; player .wait_for_request(|request| match request { PlayerRequest::Play { .. } => true, _ => false, }) .await?; let (_volume_client, volume_server) = create_endpoints()?; session.bind_volume_control(volume_server)?; player .wait_for_request(|request| match request { PlayerRequest::BindVolumeControl { .. } => true, _ => false, }) .await } #[fasync::run_singlethreaded] #[test] async fn player_disconnection_propagates() -> Result<()> { let service = TestService::new()?; let mut player = TestPlayer::new(&service)?; let mut watcher = service.new_watcher(Decodable::new_empty())?; player.emit_delta(delta_with_state(PlayerState::Playing)).await?; let mut updates = watcher.wait_for_n_updates(1).await?; let (id, _) = updates.remove(0); let (session_client, session_server) = create_endpoints()?; let session: SessionControlProxy = session_client.into_proxy()?; service.discovery.connect_to_session(id, session_server)?; drop(player); watcher.wait_for_removal().await?; let session_channel = session.into_channel().expect("Taking channel from proxy").into_zx_channel(); session_channel.wait_handle(zx::Signals::CHANNEL_PEER_CLOSED, zx::Time::INFINITE)?; Ok(()) } #[fasync::run_singlethreaded] #[test] async fn watch_filter_active() -> Result<()> { let service = TestService::new()?; let mut player1 = TestPlayer::new(&service)?; let mut player2 = TestPlayer::new(&service)?; let _player3 = TestPlayer::new(&service)?; let mut active_watcher = service.new_watcher(WatchOptions { only_active: Some(true), ..Decodable::new_empty() })?; player1.emit_delta(delta_with_state(PlayerState::Playing)).await?; player2.emit_delta(delta_with_state(PlayerState::Playing)).await?; let updates = active_watcher.wait_for_n_updates(2).await?; assert_eq!(updates.len(), 2); assert_eq!(updates[0].1.is_locally_active, Some(true), "Update: {:?}", updates[0]); assert_eq!(updates[1].1.is_locally_active, Some(true), "Update: {:?}", updates[1]); player1.emit_delta(delta_with_state(PlayerState::Paused)).await?; let updates = active_watcher.wait_for_n_updates(1).await?; assert_eq!(updates.len(), 1); assert_eq!(updates[0].1.is_locally_active, Some(false)); Ok(()) } #[fasync::run_singlethreaded] #[test] async fn disconnected_player_results_in_removal_event() -> Result<()> { let service = TestService::new()?; let mut player1 = TestPlayer::new(&service)?; let _player2 = TestPlayer::new(&service)?; let mut watcher = service.new_watcher(Decodable::new_empty())?; player1.emit_delta(delta_with_state(PlayerState::Playing)).await?; player1.emit_delta(delta_with_state(PlayerState::Playing)).await?; let _updates = watcher.wait_for_n_updates(2).await?; player1.emit_delta(delta_with_state(PlayerState::Playing)).await?; let mut updates = watcher.wait_for_n_updates(1).await?; assert_eq!(updates.len(), 1); let (player1_id, _) = updates.remove(0); drop(player1); let removed_id = watcher.wait_for_removal().await?; assert_eq!(player1_id, removed_id); Ok(()) }
mod buf_ext; mod buf_mut_ext; pub use buf_ext::BufExt; pub use buf_mut_ext::BufMutExt;
// Copyright 2017 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. // To work around #46855 // compile-flags: -Z mir-opt-level=0 // Regression test for the inhabitedness of unions with uninhabited variants, issue #46845 use std::mem; #[derive(Copy, Clone)] enum Never { } // A single uninhabited variant shouldn't make the whole union uninhabited. union Foo { a: u64, _b: Never } // If all the variants are uninhabited, however, the union should be uninhabited. // NOTE(#49298) the union being uninhabited shouldn't change its size. union Bar { _a: (Never, u64), _b: (u64, Never) } fn main() { assert_eq!(mem::size_of::<Foo>(), 8); // See the note on `Bar`'s definition for why this isn't `0`. assert_eq!(mem::size_of::<Bar>(), 8); let f = [Foo { a: 42 }, Foo { a: 10 }]; println!("{}", unsafe { f[0].a }); assert_eq!(unsafe { f[1].a }, 10); }
use serde::{Serialize, Deserialize}; use std::iter::Iterator; use std::fmt::Debug; use chrono::prelude::*; #[derive(Serialize, Deserialize, Debug)] pub struct Task { pub id: usize, pub title: String, pub tags: Vec<String>, pub deadline: i64, pub deadline_includes_time: bool, pub repeats: bool, } impl Task { pub fn new() -> Task { return Task { id: 0, title: "".to_owned(), tags: vec![], deadline: -1, deadline_includes_time: false, repeats: false, } } pub fn get_tags(&self, user_data: &UserData) -> Vec::<Tag> { let mut tags = Vec::<Tag>::new(); for tag_name in &self.tags { match user_data.tags.iter().find(| x | *tag_name == (*x).name) { Some(tag) => tags.push(tag.clone()), None => tags.push(Tag::from_str(&tag_name)) } } return tags; } pub fn get_deadline_str(&self) -> String { if self.deadline < 0 { return "".to_owned(); } let naive_date_time = NaiveDateTime::from_timestamp(self.deadline / 1000, 0); let now = Local::now(); let timezone = now.timezone(); let date_time = timezone.from_utc_datetime(&naive_date_time); let date_str = date_time.format("%b %e"); let day = date_time.day(); let day_suffix; if day == 1 || day == 21 || day == 31 { day_suffix = "st"; } else if day == 2 || day == 22 { day_suffix = "nd"; } else if day == 3 || day == 23 { day_suffix = "rd"; } else { day_suffix = "th"; } let time_str = date_time.format("%R"); let mut year_str = "".to_owned(); if date_time.year() != now.year() { year_str = date_time.year().to_string(); } return format!("{}{} {} {}", date_str, day_suffix, year_str, time_str); } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Tag { pub name: String, pub style_and_color: String, pub is_status: bool, } impl Tag { pub fn from_str(string: &String) -> Tag { return Tag { name: string.clone(), style_and_color: "".to_owned(), is_status: false, }; } } #[derive(Serialize, Deserialize, Debug)] pub struct UserData { pub tasks: Vec<Task>, pub tags: Vec<Tag>, } impl UserData { pub fn add_task(&mut self, mut task: Task) { task.id = self.tasks.len(); self.tasks.push(task); } pub fn delete_task(&mut self, id: usize) { self.tasks.retain(| task | task.id != id); } pub fn create_tag(&mut self, tag: Tag) { self.tags.retain(| x | tag.name != x.name); self.tags.push(tag); } pub fn delete_tag(&mut self, name: &str) { self.tags.retain(| tag | tag.name != name); } pub fn get_status_tags(&self) -> Vec<Tag> { return self.tags.iter().filter_map(| x | -> Option<Tag> { if x.is_status { return Some(x.clone()) } else { return None; } }) .collect(); } }
use crate::ast::*; use crate::pretty::*; use heck::{CamelCase, SnakeCase}; use im::hashmap::HashMap; use itertools::Itertools; use std::char; use std::default::Default; const INDENT: isize = 4; #[derive(Debug, Clone, Default)] struct Env { vars: HashMap<String, usize>, } impl Env { pub fn local_var_name(&mut self, name: String) -> Document { match self.vars.get(&name) { None => { self.vars.insert(name.clone(), 0); name.to_camel_case().to_doc() } Some(0) => name.to_camel_case().to_doc(), Some(n) => name.to_camel_case().to_doc().append(*n), } } pub fn next_local_var_name(&mut self, name: String) -> Document { self.vars .insert(name.clone(), self.vars.get(&name).map_or(0, |i| i + 1)); self.local_var_name(name) } } pub fn module(module: TypedModule) -> String { let exports: Vec<_> = module .statements .iter() .flat_map(|s| match s { Statement::Fn { public: true, name, args, .. } => Some((name.clone(), args.len())), Statement::ExternalFn { public: true, name, args, .. } => Some((name.clone(), args.len())), _ => None, }) .map(|(n, a)| n.to_doc().append("/").append(a)) .intersperse(", ".to_doc()) .collect(); format!("-module({}).", module.name) .to_doc() .append(line()) .append("-compile(no_auto_import).") .append(lines(2)) .append("-export([") .append(exports) .append("]).") .append(lines(2)) .append( module .statements .into_iter() .flat_map(statement) .intersperse(lines(2)) .collect::<Vec<_>>(), ) .append(line()) .format(80) } fn statement(statement: TypedStatement) -> Option<Document> { match statement { Statement::Enum { .. } => None, Statement::Import { .. } => None, Statement::ExternalType { .. } => None, Statement::Fn { args, name, body, .. } => Some(mod_fun(name, args, body)), Statement::ExternalFn { fun, module, args, name, .. } => Some(external_fun(name, module, fun, args.len())), } } fn mod_fun(name: String, args: Vec<Arg>, body: TypedExpr) -> Document { let body_doc = expr(body, &mut Env::default()); name.to_doc() .append(fun_args(args)) .append(" ->") .append(line().append(body_doc).nest(INDENT).group()) .append(".") } fn fun_args(args: Vec<Arg>) -> Document { wrap_args(args.into_iter().map(|a| match a.name { None => "_".to_doc(), Some(name) => name.to_camel_case().to_doc(), })) } fn call_args(args: Vec<TypedExpr>, env: &mut Env) -> Document { wrap_args(args.into_iter().map(|e| wrap_expr(e, env))) } fn wrap_args<I>(args: I) -> Document where I: Iterator<Item = Document>, { args.intersperse(delim(",")) .collect::<Vec<_>>() .to_doc() .nest_current() .surround("(", ")") .group() } fn atom(value: String) -> Document { use regex::Regex; lazy_static! { static ref RE: Regex = Regex::new(r"^[a-z_\$]+$").unwrap(); } if RE.is_match(&value) { value.to_doc() } else { value.to_doc().surround("'", "'") } } fn string(value: String) -> Document { value.to_doc().surround("<<\"", "\">>") } fn tuple(elems: Vec<Document>) -> Document { elems .into_iter() .intersperse(delim(",")) .collect::<Vec<_>>() .to_doc() .nest_current() .surround("{", "}") .group() } fn seq(first: TypedExpr, then: TypedExpr, env: &mut Env) -> Document { force_break() .append(expr(first, env)) .append(",") .append(line()) .append(expr(then, env)) } // TODO: Surround left or right in parens if required // TODO: Group nested bin_ops i.e. a |> b |> c fn bin_op(name: BinOp, left: TypedExpr, right: TypedExpr, env: &mut Env) -> Document { let op = match name { BinOp::Pipe => return pipe(left, right, env), BinOp::Lt => "<", BinOp::And => "andalso", BinOp::Or => "orelse", BinOp::LtEq => "=<", BinOp::Eq => "=:=", BinOp::NotEq => "/=", BinOp::GtEq => ">=", BinOp::Gt => ">", BinOp::AddInt => "+", BinOp::AddFloat => "+", BinOp::SubInt => "-", BinOp::SubFloat => "-", BinOp::MultInt => "*", BinOp::MultFloat => "*", BinOp::DivInt => "div", BinOp::DivFloat => "/", BinOp::ModuloInt => "rem", }; expr(left, env) .append(break_("", " ")) .append(op) .append(" ") .append(expr(right, env)) } fn pipe(value: TypedExpr, fun: TypedExpr, env: &mut Env) -> Document { call(fun, vec![value], env) } fn let_(value: TypedExpr, pat: Pattern, then: TypedExpr, env: &mut Env) -> Document { let body = expr(value, env); pattern(pat, env) .append(" = ") .append(body) .append(",") .append(line()) .append(expr(then, env)) } fn pattern(p: Pattern, env: &mut Env) -> Document { match p { Pattern::Nil { .. } => "[]".to_doc(), Pattern::Cons { head, tail, .. } => pattern_cons(*head, *tail, env), Pattern::Discard { .. } => "_".to_doc(), // Pattern::Map { .. } => unimplemented!(), Pattern::Var { name, .. } => env.next_local_var_name(name), Pattern::Int { value, .. } => value.to_doc(), Pattern::Float { value, .. } => value.to_doc(), Pattern::Tuple { elems, .. } => tuple(elems.into_iter().map(|p| pattern(p, env)).collect()), Pattern::String { value, .. } => string(value), Pattern::Constructor { name, args, .. } => enum_pattern(name, args, env), } } fn pattern_cons(head: Pattern, tail: Pattern, env: &mut Env) -> Document { cons(head, tail, env, pattern, |expr| match expr { Pattern::Nil { .. } => ListType::Nil, Pattern::Cons { head, tail, .. } => ListType::Cons { head: *head, tail: *tail, }, other => ListType::NotList(other), }) } fn expr_cons(head: TypedExpr, tail: TypedExpr, env: &mut Env) -> Document { cons(head, tail, env, wrap_expr, |expr| match expr { Expr::Nil { .. } => ListType::Nil, Expr::Cons { head, tail, .. } => ListType::Cons { head: *head, tail: *tail, }, other => ListType::NotList(other), }) } fn cons<ToDoc, Categorise, Elem>( head: Elem, tail: Elem, env: &mut Env, to_doc: ToDoc, categorise_element: Categorise, ) -> Document where ToDoc: Fn(Elem, &mut Env) -> Document, Categorise: Fn(Elem) -> ListType<Elem>, { let mut elems = vec![head]; let final_tail = collect_list(tail, &mut elems, categorise_element); let mut elems = elems .into_iter() .map(|e| to_doc(e, env)) .intersperse(delim(",")) .collect::<Vec<_>>(); if let Some(final_tail) = final_tail { elems.push(delim(" |")); elems.push(to_doc(final_tail, env)) }; elems.to_doc().nest_current().surround("[", "]").group() } fn collect_list<F, E>(e: E, elems: &mut Vec<E>, f: F) -> Option<E> where F: Fn(E) -> ListType<E>, { match f(e) { ListType::Nil => None, ListType::Cons { head, tail } => { elems.push(head); collect_list(tail, elems, f) } ListType::NotList(other) => Some(other), } } enum ListType<E> { Nil, Cons { head: E, tail: E }, NotList(E), } fn expr_map_cons(label: String, value: TypedExpr, tail: TypedExpr, env: &mut Env) -> Document { map_cons(expr, "=>".to_string(), label, value, tail, env) } fn map_cons<F, E>(f: F, sep: String, label: String, value: E, tail: E, env: &mut Env) -> Document where F: Fn(E, &mut Env) -> Document, { // TODO: Flatten nested cons into a map i.e. X#{a=>1, b=>2} // TODO: Break, indent, etc f(tail, env) .append("#{") .append(atom(label)) .append(" ") .append(sep) .append(" ") .append(f(value, env)) .append("}") } fn var(name: String, scope: TypedScope, env: &mut Env) -> Document { match scope { Scope::Enum { .. } => atom(name.to_snake_case()), Scope::Local => env.local_var_name(name), Scope::Import { module } => module.to_doc(), Scope::Module { arity, .. } => "fun ".to_doc().append(name).append("/").append(arity), Scope::Constant { value } => expr(*value, env), } } fn enum_pattern(name: String, args: Vec<Pattern>, env: &mut Env) -> Document { if args.is_empty() { atom(name.to_snake_case()) } else { let mut args: Vec<_> = args.into_iter().map(|p| pattern(p, env)).collect(); // FIXME: O(n), insert at start shuffles the elemes forward by one place args.insert(0, atom(name.to_snake_case())); tuple(args) } } fn clause(clause: TypedClause, env: &mut Env) -> Document { pattern(clause.pattern, env) .append(" ->") .append(line().append(expr(clause.then, env)).nest(INDENT).group()) } fn clauses(cs: Vec<TypedClause>, env: &mut Env) -> Document { cs.into_iter() .map(|c| clause(c, env)) .intersperse(";".to_doc().append(lines(2))) .collect::<Vec<_>>() .to_doc() } fn case(subject: TypedExpr, cs: Vec<TypedClause>, env: &mut Env) -> Document { "case " .to_doc() .append(wrap_expr(subject, env).group()) .append(" of") .append(line().append(clauses(cs, env)).nest(INDENT)) .append(line()) .append("end") .group() } fn enum_(name: String, args: Vec<TypedExpr>, env: &mut Env) -> Document { let mut args: Vec<_> = args.into_iter().map(|e| expr(e, env)).collect(); // FIXME: O(n), insert at start shuffles the elemes forward by one place args.insert(0, atom(name.to_snake_case())); tuple(args) } fn call(fun: TypedExpr, args: Vec<TypedExpr>, env: &mut Env) -> Document { match fun { Expr::Var { scope: Scope::Enum { .. }, name, .. } => enum_(name, args, env), Expr::Var { scope: Scope::Module { .. }, name, .. } => name.to_doc().append(call_args(args, env)), Expr::ModuleSelect { module, label, .. } => { // TODO: So here we don't have a good way to tell if it is an enum constructor or not, // we have to rely on the case of the variable. A bit lackluster. Perhaps enum // constructors should be recorded differently on the module type somehow. let is_constructor = label .chars() .next() .map(|c| c.is_uppercase()) .unwrap_or(false); if is_constructor { enum_(label, args, env) } else { match *module { Expr::Var { .. } => expr(*module, env) .append(":") .append(label) .append(call_args(args, env)), _ => expr(*module, env) .surround("(", ")") .append(":") .append(label) .append(call_args(args, env)), } } } call @ Expr::Call { .. } => expr(call, env) .surround("(", ")") .append(call_args(args, env)), Expr::Fn { is_capture: true, body, .. } => { if let Expr::Call { fun, args: inner_args, .. } = *body { let mut args = args; let merged_args = inner_args .into_iter() .map(|a| { if let Expr::Var { name, .. } = a.clone() { if name == "capture@1" { return args.pop().unwrap(); } } a }) .collect(); call(*fun, merged_args, env) } else { unreachable!() } } fun @ Expr::Fn { .. } => expr(fun, env) .surround("(", ")") .append(call_args(args, env)), other => expr(other, env).append(call_args(args, env)), } } /// Wrap a document in begin end /// fn begin_end(document: Document) -> Document { force_break() .append("begin") .append(line().append(document).nest(INDENT)) .append(line()) .append("end") } /// Same as expr, expect it wraps seq, let, etc in begin end /// fn wrap_expr(expression: TypedExpr, env: &mut Env) -> Document { match &expression { Expr::Seq { .. } => begin_end(expr(expression, env)), Expr::Let { .. } => begin_end(expr(expression, env)), _ => expr(expression, env), } } fn expr(expression: TypedExpr, env: &mut Env) -> Document { match expression { Expr::Nil { .. } => "[]".to_doc(), Expr::MapNil { .. } => "#{}".to_doc(), Expr::Int { value, .. } => value.to_doc(), Expr::Float { value, .. } => value.to_doc(), Expr::String { value, .. } => string(value), Expr::Seq { first, then, .. } => seq(*first, *then, env), Expr::Var { name, scope, .. } => var(name, scope, env), Expr::Fn { args, body, .. } => fun(args, *body, env), Expr::Cons { head, tail, .. } => expr_cons(*head, *tail, env), Expr::Call { fun, args, .. } => call(*fun, args, env), Expr::MapSelect { label, map, .. } => map_select(*map, label, env), Expr::ModuleSelect { typ, label, module, .. } => module_select(typ, *module, label, env), Expr::Tuple { elems, .. } => tuple(elems.into_iter().map(|e| wrap_expr(e, env)).collect()), Expr::Let { value, pattern, then, .. } => let_(*value, pattern, *then, env), Expr::MapCons { label, value, tail, .. } => expr_map_cons(label, *value, *tail, env), Expr::Case { subject, clauses, .. } => case(*subject, clauses, env), Expr::BinOp { name, left, right, .. } => bin_op(name, *left, *right, env), } } fn module_select( typ: crate::typ::Type, module: TypedExpr, label: String, env: &mut Env, ) -> Document { match typ.collapse_links() { crate::typ::Type::Fn { args, .. } => "fun " .to_doc() .append(expr(module, env)) .append(":") .append(label) .append("/") .append(args.len()), _ => expr(module, env).append(":").append(label).append("()"), } } // TODO: Nest, break, etc fn map_select(map: TypedExpr, label: String, env: &mut Env) -> Document { "maps:get(" .to_doc() .append(atom(label)) .append(", ") .append(wrap_expr(map, env)) .append(")") } fn fun(args: Vec<Arg>, body: TypedExpr, env: &mut Env) -> Document { "fun" .to_doc() .append(fun_args(args).append(" ->")) .append(break_("", " ").append(expr(body, env)).nest(INDENT)) .append(break_("", " ")) .append("end") .group() } fn external_fun(name: String, module: String, fun: String, arity: usize) -> Document { let chars: String = (65..(65 + arity)) .map(|x| x as u8 as char) .map(|c| c.to_string()) .intersperse(", ".to_string()) .collect(); format!("{}({}) ->", name, chars) .to_doc() .append(line()) .append(atom(module)) .append(format!(":{}({}).", fun, chars)) .nest(INDENT) } #[test] fn module_test() { let m = Module { typ: crate::typ::int(), name: "magic".to_string(), statements: vec![ Statement::ExternalType { meta: default(), public: true, name: "Any".to_string(), args: vec![], }, Statement::Enum { meta: default(), public: true, name: "Any".to_string(), args: vec![], constructors: vec![EnumConstructor { meta: default(), name: "Ok".to_string(), args: vec![], }], }, Statement::Import { meta: default(), module: "result".to_string(), }, Statement::ExternalFn { meta: default(), args: vec![ Type::Constructor { meta: default(), module: None, args: vec![], name: "Int".to_string(), }, Type::Constructor { meta: default(), module: None, args: vec![], name: "Int".to_string(), }, ], name: "add_ints".to_string(), fun: "add".to_string(), module: "int".to_string(), public: false, retrn: Type::Constructor { meta: default(), module: None, args: vec![], name: "Int".to_string(), }, }, Statement::ExternalFn { meta: default(), args: vec![], name: "map".to_string(), fun: "new".to_string(), module: "maps".to_string(), public: true, retrn: Type::Constructor { meta: default(), module: None, args: vec![], name: "Map".to_string(), }, }, ], }; let expected = "-module(magic). -compile(no_auto_import). -export([map/0]). add_ints(A, B) -> int:add(A, B). map() -> maps:new(). " .to_string(); assert_eq!(expected, module(m)); let m = Module { typ: crate::typ::int(), name: "term".to_string(), statements: vec![ Statement::Fn { meta: default(), public: false, args: vec![], name: "int".to_string(), body: Expr::Int { typ: crate::typ::int(), meta: default(), value: 176, }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "float".to_string(), body: Expr::Float { meta: default(), typ: crate::typ::float(), value: 11177.324401, }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "nil".to_string(), body: Expr::Nil { meta: default(), typ: crate::typ::int(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "map_nil".to_string(), body: Expr::MapNil { meta: default(), typ: crate::typ::map_nil(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "tup".to_string(), body: Expr::Tuple { meta: default(), typ: crate::typ::int(), elems: vec![ Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, Expr::Float { meta: default(), typ: crate::typ::float(), value: 2.0, }, ], }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "string".to_string(), body: Expr::String { meta: default(), typ: crate::typ::string(), value: "Hello there!".to_string(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "seq".to_string(), body: Expr::Seq { meta: default(), typ: crate::typ::int(), first: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }), then: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 2, }), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "bin_op".to_string(), body: Expr::BinOp { meta: default(), typ: crate::typ::int(), name: BinOp::AddInt, left: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }), right: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 2, }), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "enum1".to_string(), body: Expr::Var { meta: default(), typ: crate::typ::int(), scope: Scope::Enum { arity: 0 }, name: "Nil".to_string(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "let".to_string(), body: Expr::Let { meta: default(), typ: crate::typ::int(), value: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }), pattern: Pattern::Var { meta: default(), name: "OneTwo".to_string(), }, then: Box::new(Expr::Var { meta: default(), typ: crate::typ::int(), scope: Scope::Local, name: "one_two".to_string(), }), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "conny".to_string(), body: Expr::Cons { meta: default(), typ: crate::typ::int(), head: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 12, }), tail: Box::new(Expr::Cons { meta: default(), typ: crate::typ::int(), head: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 34, }), tail: Box::new(Expr::Nil { meta: default(), typ: crate::typ::int(), }), }), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "retcon".to_string(), body: Expr::MapCons { meta: default(), typ: crate::typ::int(), label: "size".to_string(), value: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }), tail: Box::new(Expr::MapNil { meta: default(), typ: crate::typ::map_nil(), }), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "funny".to_string(), body: Expr::Fn { meta: default(), is_capture: false, typ: crate::typ::int(), args: vec![ Arg { name: Some("one_really_long_arg_to_cause_wrapping".to_string()), }, Arg { name: Some("also_really_quite_long".to_string()), }, ], body: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 100000000000, }), }, }, ], }; let expected = "-module(term). -compile(no_auto_import). -export([]). int() -> 176. float() -> 11177.324401. nil() -> []. map_nil() -> #{}. tup() -> {1, 2.0}. string() -> <<\"Hello there!\">>. seq() -> 1, 2. bin_op() -> 1 + 2. enum1() -> nil. let() -> OneTwo = 1, OneTwo. conny() -> [12, 34]. retcon() -> #{}#{size => 1}. funny() -> fun(OneReallyLongArgToCauseWrapping, AlsoReallyQuiteLong) -> 100000000000 end. " .to_string(); assert_eq!(expected, module(m)); let m = Module { typ: crate::typ::int(), name: "term".to_string(), statements: vec![Statement::Fn { meta: default(), public: false, name: "some_function".to_string(), args: vec![ Arg { name: Some("arg_one".to_string()), }, Arg { name: Some("arg_two".to_string()), }, Arg { name: Some("arg_3".to_string()), }, Arg { name: Some("arg4".to_string()), }, Arg { name: Some("arg_four".to_string()), }, Arg { name: Some("arg__five".to_string()), }, Arg { name: Some("arg_six".to_string()), }, Arg { name: Some("arg_that_is_long".to_string()), }, ], body: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }], }; let expected = "-module(term). -compile(no_auto_import). -export([]). some_function(ArgOne, ArgTwo, Arg3, Arg4, ArgFour, ArgFive, ArgSix, ArgThatIsLong) -> 1. " .to_string(); assert_eq!(expected, module(m)); let m = Module { typ: crate::typ::int(), name: "vars".to_string(), statements: vec![ Statement::Fn { meta: default(), public: false, args: vec![], name: "arg".to_string(), body: Expr::Var { typ: crate::typ::int(), meta: default(), name: "some_arg".to_string(), scope: Scope::Local, }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "some_arg".to_string(), body: Expr::Var { typ: crate::typ::int(), meta: default(), name: "some_arg".to_string(), scope: Scope::Constant { value: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }), }, }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "another".to_string(), body: Expr::Var { typ: crate::typ::int(), meta: default(), name: "run_task".to_string(), scope: Scope::Module { arity: 6 }, }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "moddy".to_string(), body: Expr::ModuleSelect { typ: crate::typ::Type::Fn { args: vec![], retrn: Box::new(crate::typ::int()), }, meta: default(), module: Box::new(Expr::Var { meta: default(), name: "zero".to_string(), scope: Scope::Import { module: "one".to_string(), }, typ: crate::typ::int(), }), label: "two".to_string(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "moddy2".to_string(), body: Expr::ModuleSelect { typ: crate::typ::Type::Fn { args: vec![crate::typ::int(), crate::typ::int()], retrn: Box::new(crate::typ::int()), }, meta: default(), module: Box::new(Expr::Var { meta: default(), name: "zero".to_string(), scope: Scope::Import { module: "one".to_string(), }, typ: crate::typ::int(), }), label: "two".to_string(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "moddy3".to_string(), body: Expr::ModuleSelect { typ: crate::typ::int(), meta: default(), module: Box::new(Expr::Var { meta: default(), name: "zero".to_string(), scope: Scope::Import { module: "one".to_string(), }, typ: crate::typ::int(), }), label: "two".to_string(), }, }, Statement::Fn { meta: default(), public: false, args: vec![], name: "moddy4".to_string(), body: Expr::Call { meta: default(), typ: crate::typ::int(), args: vec![Expr::Int { meta: default(), typ: crate::typ::int(), value: 1, }], fun: Box::new(Expr::ModuleSelect { typ: crate::typ::int(), meta: default(), module: Box::new(Expr::Var { meta: default(), name: "zero".to_string(), scope: Scope::Import { module: "one".to_string(), }, typ: crate::typ::int(), }), label: "two".to_string(), }), }, }, ], }; let expected = "-module(vars). -compile(no_auto_import). -export([]). arg() -> SomeArg. some_arg() -> 1. another() -> fun run_task/6. moddy() -> fun one:two/0. moddy2() -> fun one:two/2. moddy3() -> one:two(). moddy4() -> one:two(1). " .to_string(); assert_eq!(expected, module(m)); let m = Module { typ: crate::typ::int(), name: "my_mod".to_string(), statements: vec![Statement::Fn { meta: default(), public: false, args: vec![], name: "go".to_string(), body: Expr::Case { meta: default(), typ: crate::typ::int(), subject: Box::new(Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }), clauses: vec![ Clause { meta: default(), pattern: Pattern::Int { meta: default(), value: 1, }, then: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }, Clause { meta: default(), pattern: Pattern::Float { meta: default(), value: 1.0, }, then: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }, Clause { meta: default(), pattern: Pattern::String { meta: default(), value: "hello".to_string(), }, then: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }, Clause { meta: default(), pattern: Pattern::Tuple { meta: default(), elems: vec![ Pattern::Int { meta: default(), value: 1, }, Pattern::Int { meta: default(), value: 2, }, ], }, then: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }, Clause { meta: default(), pattern: Pattern::Nil { meta: default() }, then: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }, Clause { meta: default(), pattern: Pattern::Constructor { meta: default(), module: None, name: "Error".to_string(), args: vec![Pattern::Int { meta: default(), value: 2, }], }, then: Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }, }, ], }, }], }; let expected = "-module(my_mod). -compile(no_auto_import). -export([]). go() -> case 1 of 1 -> 1; 1.0 -> 1; <<\"hello\">> -> 1; {1, 2} -> 1; [] -> 1; {error, 2} -> 1 end. " .to_string(); assert_eq!(expected, module(m)); let m = Module { typ: crate::typ::int(), name: "funny".to_string(), statements: vec![ Statement::Fn { meta: default(), args: vec![], name: "one".to_string(), public: false, body: Expr::Call { meta: default(), typ: crate::typ::int(), args: vec![Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }], fun: Box::new(Expr::Var { meta: default(), scope: Scope::Module { arity: 1 }, typ: crate::typ::int(), name: "one_two".to_string(), }), }, }, Statement::Fn { meta: default(), args: vec![], name: "two".to_string(), public: false, body: Expr::Call { meta: default(), typ: crate::typ::int(), args: vec![Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }], fun: Box::new(Expr::Var { meta: default(), scope: Scope::Local, typ: crate::typ::int(), name: "one_two".to_string(), }), }, }, Statement::Fn { meta: default(), args: vec![], name: "three".to_string(), public: false, body: Expr::Call { meta: default(), typ: crate::typ::int(), args: vec![Expr::Int { typ: crate::typ::int(), meta: default(), value: 2, }], fun: Box::new(Expr::Call { meta: default(), typ: crate::typ::int(), args: vec![Expr::Int { typ: crate::typ::int(), meta: default(), value: 1, }], fun: Box::new(Expr::Var { meta: default(), scope: Scope::Module { arity: 2 }, typ: crate::typ::int(), name: "one_two".to_string(), }), }), }, }, ], }; let expected = "-module(funny). -compile(no_auto_import). -export([]). one() -> one_two(1). two() -> OneTwo(1). three() -> (one_two(1))(2). " .to_string(); assert_eq!(expected, module(m)); } #[test] fn integration_test() { struct Case { src: &'static str, erl: &'static str, } let cases = [ Case { src: r#"fn go() { let x = {100000000000000000, {2000000000, 3000000000000, 40000000000}, 50000, 6000000000} x }"#, erl: r#"-module(). -compile(no_auto_import). -export([]). go() -> X = {100000000000000000, {2000000000, 3000000000000, 40000000000}, 50000, 6000000000}, X. "#, }, Case { src: r#"fn go() { let y = 1 let y = 2 y }"#, erl: r#"-module(). -compile(no_auto_import). -export([]). go() -> Y = 1, Y1 = 2, Y1. "#, }, Case { src: r#"pub fn t() { True }"#, erl: r#"-module(). -compile(no_auto_import). -export([t/0]). t() -> true. "#, }, Case { src: r#"pub enum Money = | Pound(Int) fn pound(x) { Pound(x) }"#, erl: r#"-module(). -compile(no_auto_import). -export([]). pound(X) -> {pound, X}. "#, }, Case { src: r#"fn loop() { loop() }"#, erl: r#"-module(). -compile(no_auto_import). -export([]). loop() -> loop(). "#, }, Case { src: r#"external fn run() -> Int = "Elixir.MyApp" "run""#, erl: r#"-module(). -compile(no_auto_import). -export([]). run() -> 'Elixir.MyApp':run(). "#, }, Case { src: r#"fn inc(x) { x + 1 } pub fn go() { 1 |> inc |> inc |> inc }"#, erl: r#"-module(). -compile(no_auto_import). -export([go/0]). inc(X) -> X + 1. go() -> inc(inc(inc(1))). "#, }, Case { src: r#"fn add(x, y) { x + y } pub fn go() { 1 |> add(_, 1) |> add(2, _) |> add(_, 3) }"#, erl: r#"-module(). -compile(no_auto_import). -export([go/0]). add(X, Y) -> X + Y. go() -> add(add(2, add(1, 1)), 3). "#, }, Case { src: r#"fn and(x, y) { x && y } fn or(x, y) { x || y } fn modulo(x, y) { x % y } "#, erl: r#"-module(). -compile(no_auto_import). -export([]). and(X, Y) -> X andalso Y. or(X, Y) -> X orelse Y. modulo(X, Y) -> X rem Y. "#, }, Case { src: r#"fn second(list) { case list { | [x, y] -> y | z -> 1 } } fn tail(list) { case list { | [x | xs] -> xs | z -> list } } "#, erl: r#"-module(). -compile(no_auto_import). -export([]). second(List) -> case List of [X, Y] -> Y; Z -> 1 end. tail(List) -> case List of [X | Xs] -> Xs; Z -> List end. "#, }, Case { src: r#"fn age(x) { x.age }"#, erl: r#"-module(). -compile(no_auto_import). -export([]). age(X) -> maps:get(age, X). "#, }, Case { src: r#"fn x() { let x = 1 let x = x + 1 x }"#, erl: r#"-module(). -compile(no_auto_import). -export([]). x() -> X = 1, X1 = X + 1, X1. "#, }, // TODO: Check that var num is incremented for args // TODO: Check that var num is incremented for nested patterns // TODO: Check that var num is reset after a closure that increments ]; for Case { src, erl } in cases.into_iter() { let ast = crate::grammar::ModuleParser::new() .parse(src) .expect("syntax error"); let (ast, _) = crate::typ::infer_module(ast, &std::collections::HashMap::new()) .expect("should successfully infer"); let output = module(ast); assert_eq!((src, output), (src, erl.to_string())); } } #[cfg(test)] fn default<T>() -> T where T: Default, { Default::default() }
mod send_can; use std::io::Result; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; use std::io::{BufReader, BufRead}; fn server_driver(path: &str) -> Result<UnixListener> { std::fs::remove_file(path)?; let socket_file = path; let socket = Path::new(socket_file); UnixListener::bind(&socket) } fn handle_client(stream: UnixStream) { let stream = BufReader::new(stream); for line in stream.lines() { println!("{}", line.unwrap()) } } fn main () { // to be replaced let path = "/home/majortom/tmp/can.sock"; let listener = match server_driver(path) { Ok(sock) => sock, Err(e) => { println!("Could not bind socket! {:?}", e); return } }; println!("Server started, waiting for clients"); for client in listener.incoming() { let stream = client.unwrap(); handle_client(stream); } }
use yew::prelude::*; use yew_functional::*; #[function_component(YewStack)] pub fn yewstack() -> Html { html! { <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 75 82" fill="none" class="head-icon"> <circle cx="38" cy="40" r="25" fill="#FFEFB8"/> <path d="M38.2373 41.0339L14 14" stroke="#444444" stroke-width="6" stroke-linecap="round"/> <path d="M38.2373 41.0339L62.4746 14" stroke="#444444" stroke-width="6" stroke-linecap="round"/> <path d="M38.2373 41.0339L38.2373 69" stroke="#444444" stroke-width="6" stroke-linecap="round"/> <circle cx="38" cy="41" r="7" fill="#FFD707" stroke="#444444" stroke-width="4"/> <script xmlns=""/> </svg> } }
use std::{ io::{ErrorKind, Read, Write}, net::{Shutdown, TcpStream, ToSocketAddrs, UdpSocket}, }; use crate::{ common::{NetProtocol, SocketId}, IpAddress, Port, SocketAddress, }; /// 1MB default buffer size pub const DEFAULT_BUFFER_SIZE: usize = 1_000_000; pub trait Socket: Send + Sync { /// Establish a new connection. /// Optionally, specify the socket ID, socket port (for UDP, leave empty for a random port), and size of the internal buffer fn connect<A: ToSocketAddrs>( address: A, socket_id: Option<SocketId>, socket_port: Option<Port>, buffer_size: Option<usize>, ) -> Result<Self, ()> where Self: Sized; /// Send data over the socket fn send(&mut self, data: &[u8]) -> Result<usize, ()>; /// Retrieve any data received. /// Limits the size of the returned buffer to the value of buf_size fn receive(&mut self) -> Result<Vec<u8>, ()>; /// Check whether a connection error has occurred fn check_err(&mut self) -> Result<(), ()>; /// Returns whether the socket was shutdown successfully fn close(&mut self) -> Result<(), ()>; /// Retrieve socket ID fn get_id(&self) -> SocketId; /// Set socket ID fn set_id(&mut self, id: SocketId); /// Retrieve maximum internal buffer size (used to store received data) fn get_buf_size(&self) -> usize; /// Set maximum internal buffer size fn set_buf_size(&mut self, buf_size: usize); /// Get socket protocol fn get_type(&self) -> NetProtocol; /// Get remote address fn get_remote_address(&self) -> Result<SocketAddress, ()>; } /// TCP socket type pub struct SocketTcp { id: SocketId, buf: Vec<u8>, socket: TcpStream, } impl Socket for SocketTcp { fn connect<A: ToSocketAddrs>( address: A, socket_id: Option<SocketId>, _: Option<Port>, buffer_size: Option<usize>, ) -> Result<Self, ()> { let socket = TcpStream::connect(address).map_err(|_| ())?; socket.set_nonblocking(true).map_err(|_| ())?; Ok(SocketTcp { id: socket_id.unwrap_or(SocketId::new()), buf: vec![0; buffer_size.unwrap_or(DEFAULT_BUFFER_SIZE)], socket, }) } fn send(&mut self, data: &[u8]) -> Result<usize, ()> { self.socket.write(data).map_err(|_| ()) } fn receive(&mut self) -> Result<Vec<u8>, ()> { match self.socket.read(&mut self.buf[..]) { Ok(c) => Ok(Vec::from(&self.buf[0..c])), Err(e) => { if e.kind() == ErrorKind::WouldBlock { Ok(vec![]) } else { Err(()) } } } } fn check_err(&mut self) -> Result<(), ()> { if let Ok(e) = self.socket.take_error() { if let Some(_) = e { Err(()) } else { Ok(()) } } else { Err(()) } } fn close(&mut self) -> Result<(), ()> { self.socket.shutdown(Shutdown::Both).map_err(|_| ()) } fn get_id(&self) -> SocketId { self.id } fn set_id(&mut self, id: SocketId) { self.id = id; } fn get_buf_size(&self) -> usize { self.buf.len() } fn set_buf_size(&mut self, buf_size: usize) { self.buf = vec![0; buf_size]; } fn get_type(&self) -> NetProtocol { NetProtocol::Tcp } fn get_remote_address(&self) -> Result<SocketAddress, ()> { self.socket.peer_addr().map_err(|_| ()) } } impl SocketTcp { /// Creates a socket from an existing TCP connection pub fn from_existing(socket: TcpStream) -> Self { Self { id: SocketId::new(), buf: vec![0; DEFAULT_BUFFER_SIZE], socket, } } } /// UDP socket type pub struct SocketUdp { id: SocketId, buf: Vec<u8>, socket: UdpSocket, } impl Socket for SocketUdp { /// If no port is specified, a random port is chosen (UDP) fn connect<A: ToSocketAddrs>( address: A, socket_id: Option<SocketId>, socket_port: Option<Port>, buffer_size: Option<usize>, ) -> Result<Self, ()> { // The default port 0 will result in a random port being chosen let socket = UdpSocket::bind(SocketAddress::new( IpAddress::from([127, 0, 0, 1]), // If unspecified set the port to 0 for a random port socket_port.unwrap_or(0), )) .map_err(|_| ())?; socket.connect(address).map_err(|_| ())?; socket.set_nonblocking(true).map_err(|_| ())?; Ok(SocketUdp { id: socket_id.unwrap_or(SocketId::new()), buf: vec![0; buffer_size.unwrap_or(DEFAULT_BUFFER_SIZE)], socket, }) } fn send(&mut self, data: &[u8]) -> Result<usize, ()> { self.socket.send(data).map_err(|_| ()) } fn receive(&mut self) -> Result<Vec<u8>, ()> { match self.socket.recv(&mut self.buf[..]) { Ok(c) => Ok(Vec::from(&self.buf[0..c])), Err(e) => { if e.kind() == ErrorKind::WouldBlock { Ok(vec![]) } else { Err(()) } } } } fn check_err(&mut self) -> Result<(), ()> { if let Ok(e) = self.socket.take_error() { if let Some(_) = e { Err(()) } else { Ok(()) } } else { Err(()) } } fn close(&mut self) -> Result<(), ()> { Ok(()) } fn get_id(&self) -> SocketId { self.id } fn set_id(&mut self, id: SocketId) { self.id = id; } fn get_buf_size(&self) -> usize { self.buf.len() } fn set_buf_size(&mut self, buf_size: usize) { self.buf = vec![0; buf_size]; } fn get_type(&self) -> NetProtocol { NetProtocol::Udp } fn get_remote_address(&self) -> Result<SocketAddress, ()> { self.socket.peer_addr().map_err(|_| ()) } }
use synacor::memory::{MAX_ADDR, MAX_INT}; type Cache = Vec<Vec<Option<u16>>>; fn main() { for h in 0..MAX_INT { let mut cache = vec![vec![None; MAX_ADDR]; 5]; let res = check(&mut cache, 4, 1, h) % MAX_INT; println!("Running for {}, {}", h, res); if res % MAX_INT == 6 { println!("Sol: {}", res) } } } fn check(cache: &mut Cache, a: u16, b: u16, h: u16) -> u16 { let res = if let Some(v) = cache[a as usize][b as usize] { v } else { if a == 0 { (b + 1) % MAX_INT } else if b == 0 { check(cache, a - 1, h, h) } else { let b = check(cache, a, b - 1, h); check(cache, a - 1, b, h) } }; cache[a as usize][b as usize] = Some(res); res }
use std::error::Error; use std::fmt; #[derive(Debug)] pub enum InitializationError { NodeInitializationError, RPCInitializationError, } impl fmt::Display for InitializationError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { InitializationError::NodeInitializationError => write!(f, "Initializing Node Error"), InitializationError::RPCInitializationError => write!(f, "Initializing RPC Error"), } } } impl Error for InitializationError {}
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::SHORTS { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `READY_START`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum READY_STARTR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl READY_STARTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { READY_STARTR::DISABLED => false, READY_STARTR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> READY_STARTR { match value { false => READY_STARTR::DISABLED, true => READY_STARTR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == READY_STARTR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == READY_STARTR::ENABLED } } #[doc = "Possible values of the field `END_DISABLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum END_DISABLER { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl END_DISABLER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { END_DISABLER::DISABLED => false, END_DISABLER::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> END_DISABLER { match value { false => END_DISABLER::DISABLED, true => END_DISABLER::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == END_DISABLER::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == END_DISABLER::ENABLED } } #[doc = "Possible values of the field `DISABLED_TXEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DISABLED_TXENR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl DISABLED_TXENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { DISABLED_TXENR::DISABLED => false, DISABLED_TXENR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> DISABLED_TXENR { match value { false => DISABLED_TXENR::DISABLED, true => DISABLED_TXENR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == DISABLED_TXENR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == DISABLED_TXENR::ENABLED } } #[doc = "Possible values of the field `DISABLED_RXEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DISABLED_RXENR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl DISABLED_RXENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { DISABLED_RXENR::DISABLED => false, DISABLED_RXENR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> DISABLED_RXENR { match value { false => DISABLED_RXENR::DISABLED, true => DISABLED_RXENR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == DISABLED_RXENR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == DISABLED_RXENR::ENABLED } } #[doc = "Possible values of the field `ADDRESS_RSSISTART`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADDRESS_RSSISTARTR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl ADDRESS_RSSISTARTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ADDRESS_RSSISTARTR::DISABLED => false, ADDRESS_RSSISTARTR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ADDRESS_RSSISTARTR { match value { false => ADDRESS_RSSISTARTR::DISABLED, true => ADDRESS_RSSISTARTR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ADDRESS_RSSISTARTR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ADDRESS_RSSISTARTR::ENABLED } } #[doc = "Possible values of the field `END_START`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum END_STARTR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl END_STARTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { END_STARTR::DISABLED => false, END_STARTR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> END_STARTR { match value { false => END_STARTR::DISABLED, true => END_STARTR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == END_STARTR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == END_STARTR::ENABLED } } #[doc = "Possible values of the field `ADDRESS_BCSTART`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADDRESS_BCSTARTR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl ADDRESS_BCSTARTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ADDRESS_BCSTARTR::DISABLED => false, ADDRESS_BCSTARTR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ADDRESS_BCSTARTR { match value { false => ADDRESS_BCSTARTR::DISABLED, true => ADDRESS_BCSTARTR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ADDRESS_BCSTARTR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ADDRESS_BCSTARTR::ENABLED } } #[doc = "Possible values of the field `DISABLED_RSSISTOP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DISABLED_RSSISTOPR { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl DISABLED_RSSISTOPR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { DISABLED_RSSISTOPR::DISABLED => false, DISABLED_RSSISTOPR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> DISABLED_RSSISTOPR { match value { false => DISABLED_RSSISTOPR::DISABLED, true => DISABLED_RSSISTOPR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == DISABLED_RSSISTOPR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == DISABLED_RSSISTOPR::ENABLED } } #[doc = "Values that can be written to the field `READY_START`"] pub enum READY_STARTW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl READY_STARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { READY_STARTW::DISABLED => false, READY_STARTW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _READY_STARTW<'a> { w: &'a mut W, } impl<'a> _READY_STARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: READY_STARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(READY_STARTW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(READY_STARTW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `END_DISABLE`"] pub enum END_DISABLEW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl END_DISABLEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { END_DISABLEW::DISABLED => false, END_DISABLEW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _END_DISABLEW<'a> { w: &'a mut W, } impl<'a> _END_DISABLEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: END_DISABLEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(END_DISABLEW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(END_DISABLEW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `DISABLED_TXEN`"] pub enum DISABLED_TXENW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl DISABLED_TXENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { DISABLED_TXENW::DISABLED => false, DISABLED_TXENW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _DISABLED_TXENW<'a> { w: &'a mut W, } impl<'a> _DISABLED_TXENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: DISABLED_TXENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(DISABLED_TXENW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(DISABLED_TXENW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `DISABLED_RXEN`"] pub enum DISABLED_RXENW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl DISABLED_RXENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { DISABLED_RXENW::DISABLED => false, DISABLED_RXENW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _DISABLED_RXENW<'a> { w: &'a mut W, } impl<'a> _DISABLED_RXENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: DISABLED_RXENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(DISABLED_RXENW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(DISABLED_RXENW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ADDRESS_RSSISTART`"] pub enum ADDRESS_RSSISTARTW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl ADDRESS_RSSISTARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ADDRESS_RSSISTARTW::DISABLED => false, ADDRESS_RSSISTARTW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _ADDRESS_RSSISTARTW<'a> { w: &'a mut W, } impl<'a> _ADDRESS_RSSISTARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ADDRESS_RSSISTARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(ADDRESS_RSSISTARTW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(ADDRESS_RSSISTARTW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `END_START`"] pub enum END_STARTW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl END_STARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { END_STARTW::DISABLED => false, END_STARTW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _END_STARTW<'a> { w: &'a mut W, } impl<'a> _END_STARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: END_STARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(END_STARTW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(END_STARTW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ADDRESS_BCSTART`"] pub enum ADDRESS_BCSTARTW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl ADDRESS_BCSTARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ADDRESS_BCSTARTW::DISABLED => false, ADDRESS_BCSTARTW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _ADDRESS_BCSTARTW<'a> { w: &'a mut W, } impl<'a> _ADDRESS_BCSTARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ADDRESS_BCSTARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(ADDRESS_BCSTARTW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(ADDRESS_BCSTARTW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `DISABLED_RSSISTOP`"] pub enum DISABLED_RSSISTOPW { #[doc = "Shortcut disabled."] DISABLED, #[doc = "Shortcut enabled."] ENABLED, } impl DISABLED_RSSISTOPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { DISABLED_RSSISTOPW::DISABLED => false, DISABLED_RSSISTOPW::ENABLED => true, } } } #[doc = r" Proxy"] pub struct _DISABLED_RSSISTOPW<'a> { w: &'a mut W, } impl<'a> _DISABLED_RSSISTOPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: DISABLED_RSSISTOPW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Shortcut disabled."] #[inline] pub fn disabled(self) -> &'a mut W { self.variant(DISABLED_RSSISTOPW::DISABLED) } #[doc = "Shortcut enabled."] #[inline] pub fn enabled(self) -> &'a mut W { self.variant(DISABLED_RSSISTOPW::ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Shortcut between READY event and START task."] #[inline] pub fn ready_start(&self) -> READY_STARTR { READY_STARTR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 1 - Shortcut between END event and DISABLE task."] #[inline] pub fn end_disable(&self) -> END_DISABLER { END_DISABLER::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 2 - Shortcut between DISABLED event and TXEN task."] #[inline] pub fn disabled_txen(&self) -> DISABLED_TXENR { DISABLED_TXENR::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 3 - Shortcut between DISABLED event and RXEN task."] #[inline] pub fn disabled_rxen(&self) -> DISABLED_RXENR { DISABLED_RXENR::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 4 - Shortcut between ADDRESS event and RSSISTART task."] #[inline] pub fn address_rssistart(&self) -> ADDRESS_RSSISTARTR { ADDRESS_RSSISTARTR::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 5 - Shortcut between END event and START task."] #[inline] pub fn end_start(&self) -> END_STARTR { END_STARTR::_from({ const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 6 - Shortcut between ADDRESS event and BCSTART task."] #[inline] pub fn address_bcstart(&self) -> ADDRESS_BCSTARTR { ADDRESS_BCSTARTR::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 8 - Shortcut between DISABLED event and RSSISTOP task."] #[inline] pub fn disabled_rssistop(&self) -> DISABLED_RSSISTOPR { DISABLED_RSSISTOPR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Shortcut between READY event and START task."] #[inline] pub fn ready_start(&mut self) -> _READY_STARTW { _READY_STARTW { w: self } } #[doc = "Bit 1 - Shortcut between END event and DISABLE task."] #[inline] pub fn end_disable(&mut self) -> _END_DISABLEW { _END_DISABLEW { w: self } } #[doc = "Bit 2 - Shortcut between DISABLED event and TXEN task."] #[inline] pub fn disabled_txen(&mut self) -> _DISABLED_TXENW { _DISABLED_TXENW { w: self } } #[doc = "Bit 3 - Shortcut between DISABLED event and RXEN task."] #[inline] pub fn disabled_rxen(&mut self) -> _DISABLED_RXENW { _DISABLED_RXENW { w: self } } #[doc = "Bit 4 - Shortcut between ADDRESS event and RSSISTART task."] #[inline] pub fn address_rssistart(&mut self) -> _ADDRESS_RSSISTARTW { _ADDRESS_RSSISTARTW { w: self } } #[doc = "Bit 5 - Shortcut between END event and START task."] #[inline] pub fn end_start(&mut self) -> _END_STARTW { _END_STARTW { w: self } } #[doc = "Bit 6 - Shortcut between ADDRESS event and BCSTART task."] #[inline] pub fn address_bcstart(&mut self) -> _ADDRESS_BCSTARTW { _ADDRESS_BCSTARTW { w: self } } #[doc = "Bit 8 - Shortcut between DISABLED event and RSSISTOP task."] #[inline] pub fn disabled_rssistop(&mut self) -> _DISABLED_RSSISTOPW { _DISABLED_RSSISTOPW { w: self } } }
use crate::api; use std::panic; /// Sets a custom panic hook, uses debug.trace pub fn set_panic_hook() { panic::set_hook(Box::new(|info| { let file = info.location().unwrap().file(); let line = info.location().unwrap().line(); let col = info.location().unwrap().column(); let msg = match info.payload().downcast_ref::<&'static str>() { Some(s) => *s, None => match info.payload().downcast_ref::<String>() { Some(s) => &s[..], None => "Box<Any>", }, }; let err_info = format!("Panicked at '{}', {}:{}:{}", msg, file, line, col); api::print(&err_info); })); } /// Sets stdout, stderr, and a custom panic hook pub fn hook() { set_panic_hook(); }
use data_types::NamespaceName; use std::{fmt::Debug, sync::Arc}; /// A [`Sharder`] implementation is responsible for mapping an opaque payload /// for a given table name & namespace to an output type. /// /// [`Sharder`] instances can be generic over any payload type (in which case, /// the implementation operates exclusively on the table name and/or namespace) /// or they can be implemented for, and inspect, a specific payload type while /// sharding. /// /// NOTE: It is a system invariant that deletes are routed to (all of) the same /// shards as a write for the same table. pub trait Sharder<P>: Debug + Send + Sync { /// The type returned by a sharder. /// /// This could be a shard ID, a shard index, an array of multiple shards, /// etc. type Item: Debug + Send + Sync; /// Map the specified `payload` to a shard. fn shard(&self, table: &str, namespace: &NamespaceName<'_>, payload: &P) -> Self::Item; } impl<T, P> Sharder<P> for Arc<T> where T: Sharder<P>, { type Item = T::Item; fn shard(&self, table: &str, namespace: &NamespaceName<'_>, payload: &P) -> Self::Item { (**self).shard(table, namespace, payload) } } #[cfg(test)] mod tests { use mutable_batch::MutableBatch; use crate::JumpHash; use super::*; #[test] fn test_arc_wrapped_sharder() { let hasher: Arc<dyn Sharder<MutableBatch, Item = Arc<u32>>> = Arc::new(JumpHash::new((0..10_u32).map(Arc::new))); let _ = hasher.shard( "table", &NamespaceName::try_from("namespace").unwrap(), &MutableBatch::default(), ); } }
// 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. // run-pass pub trait Parameters { type SelfRef; } struct RP<'a> { _marker: std::marker::PhantomData<&'a ()> } struct BP; impl<'a> Parameters for RP<'a> { type SelfRef = &'a X<RP<'a>>; } impl Parameters for BP { type SelfRef = Box<X<BP>>; } pub struct Y; pub enum X<P: Parameters> { Nothing, SameAgain(P::SelfRef, Y) } fn main() { let bnil: Box<X<BP>> = Box::new(X::Nothing); let bx: Box<X<BP>> = Box::new(X::SameAgain(bnil, Y)); let rnil: X<RP> = X::Nothing; let rx: X<RP> = X::SameAgain(&rnil, Y); }
use std::env; use std::fs; use std::os::windows::prelude::*; use std::path::Path; fn main() { let src_path: String = r#"\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets"#.to_string(); let dst: String = r#"d:\var\tmp\wallpaper"#.to_owned(); let user_profile = match env::var("USERPROFILE") { Ok(val) => val, Err(_e) => "".to_owned(), }; if !Path::new(&dst).exists() { let _ = fs::create_dir(&dst); } let src = format!("{}{}", user_profile, &src_path); if let Ok(files) = get_files(&src) { for file in files { let meta = fs::metadata(&file).expect("error meta"); if meta.file_size() >= 200_000 { let file_name = Path::new(&file).file_name().unwrap().to_str().unwrap(); let dst_name = format!("{}\\{}.jpg", &dst, &file_name); println!("Menyalin file `{}`..", &file_name); let _ = fs::copy(&file, &dst_name); } } } } fn get_files(dirname: &String) -> std::io::Result<Vec<String>> { let mut res: Vec<String> = Vec::new(); for entry in fs::read_dir(dirname)? { let dir = entry?; res.push(dir.path().display().to_string()); } Ok(res) }
// Copyright 2023 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_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::types::BooleanType; use common_expression::types::NumberDataType; use common_expression::types::StringType; use common_expression::types::UInt64Type; use common_expression::DataBlock; use common_expression::FromData; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_storages_result_cache::gen_result_cache_prefix; use common_storages_result_cache::ResultCacheMetaManager; use common_users::UserApiProvider; use itertools::Itertools; use crate::table::AsyncOneBlockSystemTable; use crate::table::AsyncSystemTable; pub struct QueryCacheTable { table_info: TableInfo, } #[async_trait::async_trait] impl AsyncSystemTable for QueryCacheTable { const NAME: &'static str = "system.query_cache"; fn get_table_info(&self) -> &TableInfo { &self.table_info } async fn get_full_data(&self, ctx: Arc<dyn TableContext>) -> Result<DataBlock> { let meta_client = UserApiProvider::instance().get_meta_store_client(); let result_cache_mgr = ResultCacheMetaManager::create(meta_client, 0); let tenant = ctx.get_tenant(); let prefix = gen_result_cache_prefix(&tenant); let cached_values = result_cache_mgr.list(prefix.as_str()).await?; let mut sql_vec: Vec<&str> = Vec::with_capacity(cached_values.len()); let mut query_id_vec: Vec<&str> = Vec::with_capacity(cached_values.len()); let mut result_size_vec = Vec::with_capacity(cached_values.len()); let mut num_rows_vec = Vec::with_capacity(cached_values.len()); let mut partitions_sha_vec = Vec::with_capacity(cached_values.len()); let mut location_vec = Vec::with_capacity(cached_values.len()); let mut active_result_scan: Vec<bool> = Vec::with_capacity(cached_values.len()); cached_values.iter().for_each(|x| { sql_vec.push(x.sql.as_str()); query_id_vec.push(x.query_id.as_str()); result_size_vec.push(x.result_size as u64); num_rows_vec.push(x.num_rows as u64); partitions_sha_vec.push(x.partitions_shas.clone()); location_vec.push(x.location.as_str()); }); let active_query_ids = ctx.get_query_id_history(); for qid in query_id_vec.iter() { if active_query_ids.contains(*qid) { active_result_scan.push(true) } else { active_result_scan.push(false) } } let partitions_sha_vec: Vec<String> = partitions_sha_vec .into_iter() .map(|part| part.into_iter().join(", ")) .collect(); Ok(DataBlock::new_from_columns(vec![ StringType::from_data(sql_vec), StringType::from_data(query_id_vec), UInt64Type::from_data(result_size_vec), UInt64Type::from_data(num_rows_vec), StringType::from_data( partitions_sha_vec .iter() .map(|part_sha| part_sha.as_str()) .collect::<Vec<_>>(), ), StringType::from_data(location_vec), BooleanType::from_data(active_result_scan), ])) } } impl QueryCacheTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let schema = TableSchemaRefExt::create(vec![ TableField::new("sql", TableDataType::String), TableField::new("query_id", TableDataType::String), TableField::new("result_size", TableDataType::Number(NumberDataType::UInt64)), TableField::new("num_rows", TableDataType::Number(NumberDataType::UInt64)), TableField::new( "partitions_sha", TableDataType::Array(Box::new(TableDataType::String)), ), TableField::new("location", TableDataType::String), TableField::new("active_result_scan", TableDataType::Boolean), ]); let table_info = TableInfo { desc: "'system'.'query_cache'".to_string(), name: "query_cache".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { schema, engine: "SystemQueryCache".to_string(), ..Default::default() }, ..Default::default() }; AsyncOneBlockSystemTable::create(QueryCacheTable { table_info }) } }
extern crate tuix; use tuix::widgets::Button; use tuix::Application; use tuix::events::BuildHandler; use tuix::PropSet; use tuix::style::themes::DEFAULT_THEME; fn main() { let app = Application::new(|win_desc, state, window| { state.insert_theme(DEFAULT_THEME); Button::new().build(state, window, |builder| { builder.set_text("Button") }); win_desc.with_title("Hello GUI") }); app.run(); }
use std::cmp::{max, min}; use std::collections::HashSet; use itertools::Itertools; use whiteread::parse_line; fn main() { let s: String = parse_line().unwrap(); let oo = s .char_indices() .filter(|(_, c)| c == &'o') .map(|(i, _)| i as u64) .collect_vec(); let xx = s .char_indices() .filter(|(_, c)| c == &'x') .map(|(i, _)| i as u64) .collect_vec(); let hh = s .char_indices() .filter(|(_, c)| c == &'?') .map(|(i, _)| i as u64) .collect_vec(); if oo.len() > 4 { println!("0"); return; } let c = 4 - oo.len(); let mut options = HashSet::new(); let mut hhoo = hh.clone(); hhoo.extend(oo.clone().into_iter()); for mut bits in 0..(hh.len() + oo.len()).pow(c as u32) { let mut additional = vec![]; for _ in 0..c { additional.push(hhoo[bits % (hh.len() + oo.len())]); bits /= hh.len() + oo.len(); } let mut narabi = oo.clone(); narabi.extend(additional.iter()); for option in narabi.into_iter().permutations(4) { options.insert(option); } } println!("{}", options.len()); } fn factorial(n: u64) -> u64 { let mut ans = 1; for i in 1..=n { ans *= n; } return ans; }
use super::exp; /* k is such that k*ln2 has minimal relative error and x - kln2 > log(FLT_MIN) */ const K: i32 = 2043; /* expf(x)/2 for x >= log(FLT_MAX), slightly better than 0.5f*expf(x/2)*expf(x/2) */ #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub(crate) fn k_expo2(x: f64) -> f64 { let k_ln2 = f64::from_bits(0x40962066151add8b); /* note that k is odd and scale*scale overflows */ let scale = f64::from_bits(((((0x3ff + K / 2) as u32) << 20) as u64) << 32); /* exp(x - k ln2) * 2**(k-1) */ exp(x - k_ln2) * scale * scale }
#[macro_use] extern crate cfg_if; extern crate log; cfg_if! { if #[cfg(target_arch = "wasm32")] { mod app; mod loop_wasm; use wasm_bindgen::prelude::*; use crate::app::App; #[wasm_bindgen(start)] pub fn main_js() { // Uncomment the line below to enable logging. You don't need it if something else (e.g. quicksilver) is logging for you wasm_logger::init(wasm_logger::Config::default()); let app = App::new(); loop_wasm::start_loop(app); } } else {} }
use std::collections::BTreeSet; pub fn binary_search() { let mut bstree = BTreeSet::new(); bstree.insert(32); }
/* Project Euler Problem 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ fn main() { for i in 1.. { for j in 1..21 { if i % j != 0 { break; } if j == 20 { println!("{:?}", i); return; } } } }
pub struct LightSegment {}
use std::fmt::Debug; #[derive(PartialEq, Clone)] struct State(Vec<Vec<u8>>); fn rules_p1(state: &State, col: usize, row: usize) -> u8 { let mut occupied = 0; let x_min = col.saturating_sub(1); let x_max = (col + 1).min(state.0[0].len() - 1); let y_min = row.saturating_sub(1); let y_max = (row + 1).min(state.0.len() - 1); for x in x_min..=x_max { for y in y_min..=y_max { occupied += ((x != col || y != row) && state.0[y][x] == b'#') as usize; } } if state.0[row][col] == b'L' && occupied == 0 { b'#' } else if occupied >= 4 { b'L' } else { state.0[row][col] } } fn rules_p2(state: &State, col: usize, row: usize) -> u8 { let mut occupied = 0; for dir in &[ (1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1), ] { for step in 1.. { let x = col as isize + dir.0 * step as isize; let y = row as isize + dir.1 * step as isize; if x < 0 || y < 0 || x >= state.0[0].len() as isize || y >= state.0.len() as isize { break; } if state.0[y as usize][x as usize] != b'.' { occupied += (state.0[y as usize][x as usize] == b'#') as usize; break; } } } if state.0[row][col] == b'L' && occupied == 0 { b'#' } else if occupied >= 5 { b'L' } else { state.0[row][col] } } impl State { fn next(&self, rules: &impl Fn(&State, usize, usize) -> u8) -> State { let mut state = self.0.clone(); for row in 0..self.0.len() { for col in 0..self.0[0].len() { if state[row][col] == b'.' { continue; }; state[row][col] = rules(self, col, row) } } State(state) } fn fix_point(&self, rules: &impl Fn(&State, usize, usize) -> u8) -> State { let mut state = self.clone(); loop { let next_state = state.next(rules); if state == next_state { break; } state = next_state; } state } fn count(&self) -> usize { self.0.iter().flatten().filter(|b| **b == b'#').count() } fn parse(input: &str) -> State { let seats = input .lines() .map(|s| s.as_bytes().to_vec()) .collect::<Vec<Vec<u8>>>(); State(seats.clone()) } } impl Debug for State { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.iter().try_for_each(|line| { writeln!(f, "{}", line.iter().map(|b| *b as char).collect::<String>()) }) } } fn main() { let input = std::fs::read_to_string("input").unwrap(); dbg!(State::parse(&input).fix_point(&rules_p1).count()); dbg!(State::parse(&input).fix_point(&rules_p2).count()); } #[cfg(test)] #[test] fn test_1() { let input = State::parse( r#"L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL"#, ); assert_eq!( input.next(&rules_p1), State::parse( "#.##.##.## #######.## #.#.#..#.. ####.##.## #.##.##.## #.#####.## ..#.#..... ########## #.######.# #.#####.##" ) ); assert_eq!( input.next(&rules_p1).next(&rules_p1), State::parse( "#.LL.L#.## #LLLLLL.L# L.L.L..L.. #LLL.LL.L# #.LL.LL.LL #.LLLL#.## ..L.L..... #LLLLLLLL# #.LLLLLL.L #.#LLLL.##" ) ); assert_eq!(input.fix_point(&rules_p1).count(), 37); } #[cfg(test)] #[test] fn test_2() { let input = State::parse( r#"L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL"#, ); let state = input.next(&rules_p2); assert_eq!( state, State::parse( "#.##.##.## #######.## #.#.#..#.. ####.##.## #.##.##.## #.#####.## ..#.#..... ########## #.######.# #.#####.##" ) ); let state = state.next(&rules_p2); assert_eq!( state, State::parse( "#.LL.LL.L# #LLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLL# #.LLLLLL.L #.LLLLL.L#" ) ); let state = state.next(&rules_p2); assert_eq!( state, State::parse( "#.L#.##.L# #L#####.LL L.#.#..#.. ##L#.##.## #.##.#L.## #.#####.#L ..#.#..... LLL####LL# #.L#####.L #.L####.L#" ) ); assert_eq!(input.fix_point(&rules_p2).count(), 26); }
use std::io::{self, Bytes, Read}; pub struct Decoder<R> { bytes: Bytes<R>, control_bits: u8, control_idx: u32, } impl<R> Decoder<R> where R: Read { pub fn new(read: R) -> Decoder<R> { Decoder { bytes: read.bytes(), control_bits: 0, control_idx: 8, } } pub fn decode_to_vec(&mut self) -> io::Result<Vec<u8>> { let mut buffer = Vec::new(); loop { if self.read_control_bit()? { buffer.push(self.read_u8()?); } else { let sequence_len; let offset; if self.read_control_bit()? { let lower_byte = self.read_u8()? as u16; let higher_byte = self.read_u8()? as u16; let control_data = higher_byte << 8 | lower_byte; if control_data == 0 { return Ok(buffer); } let raw_sequence_len = control_data & 0b0111; let raw_offset = control_data >> 3; if raw_sequence_len == 0 { sequence_len = self.read_u8()? as usize + 1; } else { sequence_len = raw_sequence_len as usize + 2; } offset = (raw_offset as i32 | 0xFFFFE000u32 as i32) as isize; } else { let upper_bit = self.read_control_bit()? as u32; let lower_bit = self.read_control_bit()? as u32; let raw_sequence_len = upper_bit << 1 | lower_bit; let raw_offset = self.read_u8()?; sequence_len = raw_sequence_len as usize + 2; offset = (raw_offset as i32 | 0xFFFFFF00u32 as i32) as isize; } let range_start = (buffer.len() as isize + offset) as usize; let range_end = range_start + sequence_len; for idx in range_start..range_end { let byte = *buffer.get(idx).unwrap(); buffer.push(byte); } } } } fn read_control_bit(&mut self) -> io::Result<bool> { if self.control_idx == 8 { self.control_idx = 0; self.control_bits = self.bytes.next().unwrap()?; } self.control_idx += 1; let bit = self.control_bits & 1; self.control_bits >>= 1; Ok(bit == 1) } fn read_u8(&mut self) -> io::Result<u8> { self.bytes.next().unwrap() } }
use fileutil; use std::collections::{HashMap, HashSet, BinaryHeap}; use std::iter::Map; use std::str::Split; use petgraph::{Graph, Undirected}; use petgraph::graph::NodeIndex; use petgraph::algo::dijkstra; fn transitive_orbits(object: &str, orbit_map: &HashMap<&str, HashSet<&str>>) -> u32 { match orbit_map.get(object) { Some(orbitees) => { let mut orbits: u32 = orbitees.len() as u32; for orbitee in orbitees { orbits += transitive_orbits(orbitee, orbit_map); } return orbits; }, None => 0 } } fn parse_orbits(lines: &Vec<String>, undirected: bool) -> HashMap<&str, HashSet<&str>> { // object -> direct orbitees let mut orbit_map: HashMap<&str, HashSet<&str>> = HashMap::new(); let parsed_orbits = lines.iter() .map(|l| { let mut split: Split<&str> = l.split(")"); return (split.next().unwrap(), split.next().unwrap()); }); for (orbitee, orbiter) in parsed_orbits { orbit_map .entry(orbiter) .or_insert(HashSet::new()) .insert(orbitee); if undirected { orbit_map .entry(orbitee) .or_insert(HashSet::new()) .insert(orbiter); } } return orbit_map; } pub fn part1(lines: &Vec<String>) -> u32 { let orbitee_map: HashMap<&str, HashSet<&str>> = parse_orbits(lines, false); let mut total_orbits: u32 = 0; for object in orbitee_map.keys() { total_orbits += transitive_orbits(object, &orbitee_map); } return total_orbits; } fn goto_target(start: &str, target: &str, orbitee_map: &HashMap<&str, HashSet<&str>>) -> u32 { let mut unique_nodes: HashSet<&str> = HashSet::new(); unique_nodes.insert(start); unique_nodes.insert(target); for key in orbitee_map.keys() { unique_nodes.insert(key); } for orbitees in orbitee_map.values() { for orbitee in orbitees { unique_nodes.insert(orbitee); } } let mut object_index: HashMap<&str, NodeIndex<u32>> = HashMap::new(); let mut graph: Graph<&str, i32, Undirected> = Graph::new_undirected(); for node in &unique_nodes { object_index.insert(node, graph.add_node(node)); } for node in &unique_nodes { let node_idx = object_index.get(node).unwrap(); match orbitee_map.get(node) { Some(orbitees) => { for orbitee in orbitees { let orbitee_idx = object_index.get(orbitee).unwrap(); graph.add_edge(*node_idx, *orbitee_idx, 1); } }, None => () } } let start_idx = object_index.get(start).unwrap(); let target_idx = object_index.get(target).unwrap(); let path_costs: HashMap<NodeIndex<u32>, u32> = dijkstra(&graph, *start_idx, Some(*target_idx), |e| 1); return *path_costs.get(target_idx).unwrap(); } pub fn part2(lines: &Vec<String>) -> u32 { let orbitee_map: HashMap<&str, HashSet<&str>> = parse_orbits(lines, true); let current = orbitee_map.get("YOU").unwrap().iter().next().unwrap(); let target = orbitee_map.get("SAN").unwrap().iter().next().unwrap(); return goto_target(current, target, &orbitee_map); } pub fn run() -> () { match fileutil::read_lines("./data/2019/06.txt") { Ok(lines) => { println!("{}", part2(&lines)); } Err(e) => println!("{}", e) } }
mod main; mod command; pub use self::main::reasonable_main; pub use self::command::Command;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub struct AdaptiveCardBuilder {} impl AdaptiveCardBuilder { pub fn CreateAdaptiveCardFromJson<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(value: Param0) -> ::windows::core::Result<IAdaptiveCard> { Self::IAdaptiveCardBuilderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<IAdaptiveCard>(result__) }) } pub fn IAdaptiveCardBuilderStatics<R, F: FnOnce(&IAdaptiveCardBuilderStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AdaptiveCardBuilder, IAdaptiveCardBuilderStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for AdaptiveCardBuilder { const NAME: &'static str = "Windows.UI.Shell.AdaptiveCardBuilder"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IAdaptiveCard(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAdaptiveCard { type Vtable = IAdaptiveCard_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x72d0568c_a274_41cd_82a8_989d40b9b05e); } impl IAdaptiveCard { pub fn ToJson(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for IAdaptiveCard { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{72d0568c-a274-41cd-82a8-989d40b9b05e}"); } impl ::core::convert::From<IAdaptiveCard> for ::windows::core::IUnknown { fn from(value: IAdaptiveCard) -> Self { value.0 .0 } } impl ::core::convert::From<&IAdaptiveCard> for ::windows::core::IUnknown { fn from(value: &IAdaptiveCard) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAdaptiveCard { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAdaptiveCard { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IAdaptiveCard> for ::windows::core::IInspectable { fn from(value: IAdaptiveCard) -> Self { value.0 } } impl ::core::convert::From<&IAdaptiveCard> for ::windows::core::IInspectable { fn from(value: &IAdaptiveCard) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IAdaptiveCard { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IAdaptiveCard { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IAdaptiveCard_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IAdaptiveCardBuilderStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAdaptiveCardBuilderStatics { type Vtable = IAdaptiveCardBuilderStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x766d8f08_d3fe_4347_a0bc_b9ea9a6dc28e); } impl IAdaptiveCardBuilderStatics { pub fn CreateAdaptiveCardFromJson<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<IAdaptiveCard> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<IAdaptiveCard>(result__) } } } unsafe impl ::windows::core::RuntimeType for IAdaptiveCardBuilderStatics { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{766d8f08-d3fe-4347-a0bc-b9ea9a6dc28e}"); } impl ::core::convert::From<IAdaptiveCardBuilderStatics> for ::windows::core::IUnknown { fn from(value: IAdaptiveCardBuilderStatics) -> Self { value.0 .0 } } impl ::core::convert::From<&IAdaptiveCardBuilderStatics> for ::windows::core::IUnknown { fn from(value: &IAdaptiveCardBuilderStatics) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAdaptiveCardBuilderStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAdaptiveCardBuilderStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IAdaptiveCardBuilderStatics> for ::windows::core::IInspectable { fn from(value: IAdaptiveCardBuilderStatics) -> Self { value.0 } } impl ::core::convert::From<&IAdaptiveCardBuilderStatics> for ::windows::core::IInspectable { fn from(value: &IAdaptiveCardBuilderStatics) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IAdaptiveCardBuilderStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IAdaptiveCardBuilderStatics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IAdaptiveCardBuilderStatics_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ISecurityAppManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISecurityAppManager { type Vtable = ISecurityAppManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96ac500c_aed4_561d_bde8_953520343a2d); } #[repr(C)] #[doc(hidden)] pub struct ISecurityAppManager_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, kind: SecurityAppKind, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, detailsuri: ::windows::core::RawPtr, registerperuser: bool, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, kind: SecurityAppKind, guidregistration: ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, kind: SecurityAppKind, guidregistration: ::windows::core::GUID, state: SecurityAppState, substatus: SecurityAppSubstatus, detailsuri: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IShareWindowCommandEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IShareWindowCommandEventArgs { type Vtable = IShareWindowCommandEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4578dc09_a523_5756_a995_e4feb991fff0); } #[repr(C)] #[doc(hidden)] pub struct IShareWindowCommandEventArgs_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::WindowId) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ShareWindowCommand) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ShareWindowCommand) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IShareWindowCommandSource(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IShareWindowCommandSource { type Vtable = IShareWindowCommandSource_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcb3b7ae3_6b9c_561e_bccc_61e68e0abfef); } #[repr(C)] #[doc(hidden)] pub struct IShareWindowCommandSource_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IShareWindowCommandSourceStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IShareWindowCommandSourceStatics { type Vtable = IShareWindowCommandSourceStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0eb6656_9cac_517c_b6c7_8ef715084295); } #[repr(C)] #[doc(hidden)] pub struct IShareWindowCommandSourceStatics_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITaskbarManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITaskbarManager { type Vtable = ITaskbarManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x87490a19_1ad9_49f4_b2e8_86738dc5ac40); } #[repr(C)] #[doc(hidden)] pub struct ITaskbarManager_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applistentry: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "ApplicationModel_Core", feature = "Foundation")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applistentry: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "ApplicationModel_Core", feature = "Foundation")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITaskbarManager2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITaskbarManager2 { type Vtable = ITaskbarManager2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79f0a06e_7b02_4911_918c_dee0bbd20ba4); } #[repr(C)] #[doc(hidden)] pub struct ITaskbarManager2_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_StartScreen"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, secondarytile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_StartScreen")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITaskbarManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITaskbarManagerStatics { type Vtable = ITaskbarManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdb32ab74_de52_4fe6_b7b6_95ff9f8395df); } #[repr(C)] #[doc(hidden)] pub struct ITaskbarManagerStatics_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, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SecurityAppKind(pub i32); impl SecurityAppKind { pub const WebProtection: SecurityAppKind = SecurityAppKind(0i32); } impl ::core::convert::From<i32> for SecurityAppKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SecurityAppKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for SecurityAppKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Shell.SecurityAppKind;i4)"); } impl ::windows::core::DefaultType for SecurityAppKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SecurityAppManager(pub ::windows::core::IInspectable); impl SecurityAppManager { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SecurityAppManager, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Register<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, kind: SecurityAppKind, displayname: Param1, detailsuri: Param2, registerperuser: bool) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), kind, displayname.into_param().abi(), detailsuri.into_param().abi(), registerperuser, &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn Unregister<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, kind: SecurityAppKind, guidregistration: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), kind, guidregistration.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn UpdateState<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, kind: SecurityAppKind, guidregistration: Param1, state: SecurityAppState, substatus: SecurityAppSubstatus, detailsuri: Param4) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), kind, guidregistration.into_param().abi(), state, substatus, detailsuri.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for SecurityAppManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Shell.SecurityAppManager;{96ac500c-aed4-561d-bde8-953520343a2d})"); } unsafe impl ::windows::core::Interface for SecurityAppManager { type Vtable = ISecurityAppManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96ac500c_aed4_561d_bde8_953520343a2d); } impl ::windows::core::RuntimeName for SecurityAppManager { const NAME: &'static str = "Windows.UI.Shell.SecurityAppManager"; } impl ::core::convert::From<SecurityAppManager> for ::windows::core::IUnknown { fn from(value: SecurityAppManager) -> Self { value.0 .0 } } impl ::core::convert::From<&SecurityAppManager> for ::windows::core::IUnknown { fn from(value: &SecurityAppManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecurityAppManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecurityAppManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SecurityAppManager> for ::windows::core::IInspectable { fn from(value: SecurityAppManager) -> Self { value.0 } } impl ::core::convert::From<&SecurityAppManager> for ::windows::core::IInspectable { fn from(value: &SecurityAppManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecurityAppManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecurityAppManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SecurityAppManager {} unsafe impl ::core::marker::Sync for SecurityAppManager {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SecurityAppState(pub i32); impl SecurityAppState { pub const Disabled: SecurityAppState = SecurityAppState(0i32); pub const Enabled: SecurityAppState = SecurityAppState(1i32); } impl ::core::convert::From<i32> for SecurityAppState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SecurityAppState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for SecurityAppState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Shell.SecurityAppState;i4)"); } impl ::windows::core::DefaultType for SecurityAppState { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SecurityAppSubstatus(pub i32); impl SecurityAppSubstatus { pub const Undetermined: SecurityAppSubstatus = SecurityAppSubstatus(0i32); pub const NoActionNeeded: SecurityAppSubstatus = SecurityAppSubstatus(1i32); pub const ActionRecommended: SecurityAppSubstatus = SecurityAppSubstatus(2i32); pub const ActionNeeded: SecurityAppSubstatus = SecurityAppSubstatus(3i32); } impl ::core::convert::From<i32> for SecurityAppSubstatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SecurityAppSubstatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for SecurityAppSubstatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Shell.SecurityAppSubstatus;i4)"); } impl ::windows::core::DefaultType for SecurityAppSubstatus { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ShareWindowCommand(pub i32); impl ShareWindowCommand { pub const None: ShareWindowCommand = ShareWindowCommand(0i32); pub const StartSharing: ShareWindowCommand = ShareWindowCommand(1i32); pub const StopSharing: ShareWindowCommand = ShareWindowCommand(2i32); } impl ::core::convert::From<i32> for ShareWindowCommand { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ShareWindowCommand { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ShareWindowCommand { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Shell.ShareWindowCommand;i4)"); } impl ::windows::core::DefaultType for ShareWindowCommand { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ShareWindowCommandEventArgs(pub ::windows::core::IInspectable); impl ShareWindowCommandEventArgs { pub fn WindowId(&self) -> ::windows::core::Result<super::WindowId> { let this = self; unsafe { let mut result__: super::WindowId = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::WindowId>(result__) } } pub fn Command(&self) -> ::windows::core::Result<ShareWindowCommand> { let this = self; unsafe { let mut result__: ShareWindowCommand = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ShareWindowCommand>(result__) } } pub fn SetCommand(&self, value: ShareWindowCommand) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for ShareWindowCommandEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Shell.ShareWindowCommandEventArgs;{4578dc09-a523-5756-a995-e4feb991fff0})"); } unsafe impl ::windows::core::Interface for ShareWindowCommandEventArgs { type Vtable = IShareWindowCommandEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4578dc09_a523_5756_a995_e4feb991fff0); } impl ::windows::core::RuntimeName for ShareWindowCommandEventArgs { const NAME: &'static str = "Windows.UI.Shell.ShareWindowCommandEventArgs"; } impl ::core::convert::From<ShareWindowCommandEventArgs> for ::windows::core::IUnknown { fn from(value: ShareWindowCommandEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&ShareWindowCommandEventArgs> for ::windows::core::IUnknown { fn from(value: &ShareWindowCommandEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ShareWindowCommandEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ShareWindowCommandEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ShareWindowCommandEventArgs> for ::windows::core::IInspectable { fn from(value: ShareWindowCommandEventArgs) -> Self { value.0 } } impl ::core::convert::From<&ShareWindowCommandEventArgs> for ::windows::core::IInspectable { fn from(value: &ShareWindowCommandEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ShareWindowCommandEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ShareWindowCommandEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ShareWindowCommandEventArgs {} unsafe impl ::core::marker::Sync for ShareWindowCommandEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ShareWindowCommandSource(pub ::windows::core::IInspectable); impl ShareWindowCommandSource { pub fn Start(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn Stop(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() } } pub fn ReportCommandChanged(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn CommandRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<ShareWindowCommandSource, ShareWindowCommandEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveCommandRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn CommandInvoked<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<ShareWindowCommandSource, ShareWindowCommandEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveCommandInvoked<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn GetForCurrentView() -> ::windows::core::Result<ShareWindowCommandSource> { Self::IShareWindowCommandSourceStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ShareWindowCommandSource>(result__) }) } pub fn IShareWindowCommandSourceStatics<R, F: FnOnce(&IShareWindowCommandSourceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ShareWindowCommandSource, IShareWindowCommandSourceStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for ShareWindowCommandSource { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Shell.ShareWindowCommandSource;{cb3b7ae3-6b9c-561e-bccc-61e68e0abfef})"); } unsafe impl ::windows::core::Interface for ShareWindowCommandSource { type Vtable = IShareWindowCommandSource_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcb3b7ae3_6b9c_561e_bccc_61e68e0abfef); } impl ::windows::core::RuntimeName for ShareWindowCommandSource { const NAME: &'static str = "Windows.UI.Shell.ShareWindowCommandSource"; } impl ::core::convert::From<ShareWindowCommandSource> for ::windows::core::IUnknown { fn from(value: ShareWindowCommandSource) -> Self { value.0 .0 } } impl ::core::convert::From<&ShareWindowCommandSource> for ::windows::core::IUnknown { fn from(value: &ShareWindowCommandSource) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ShareWindowCommandSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ShareWindowCommandSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ShareWindowCommandSource> for ::windows::core::IInspectable { fn from(value: ShareWindowCommandSource) -> Self { value.0 } } impl ::core::convert::From<&ShareWindowCommandSource> for ::windows::core::IInspectable { fn from(value: &ShareWindowCommandSource) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ShareWindowCommandSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ShareWindowCommandSource { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ShareWindowCommandSource {} unsafe impl ::core::marker::Sync for ShareWindowCommandSource {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TaskbarManager(pub ::windows::core::IInspectable); impl TaskbarManager { pub fn IsSupported(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsPinningAllowed(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn IsCurrentAppPinnedAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))] pub fn IsAppListEntryPinnedAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::ApplicationModel::Core::AppListEntry>>(&self, applistentry: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), applistentry.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestPinCurrentAppAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))] pub fn RequestPinAppListEntryAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::ApplicationModel::Core::AppListEntry>>(&self, applistentry: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), applistentry.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } pub fn GetDefault() -> ::windows::core::Result<TaskbarManager> { Self::ITaskbarManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TaskbarManager>(result__) }) } #[cfg(feature = "Foundation")] pub fn IsSecondaryTilePinnedAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, tileid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<ITaskbarManager2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), tileid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_StartScreen"))] pub fn RequestPinSecondaryTileAsync<'a, Param0: ::windows::core::IntoParam<'a, super::StartScreen::SecondaryTile>>(&self, secondarytile: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<ITaskbarManager2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), secondarytile.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryUnpinSecondaryTileAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, tileid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<ITaskbarManager2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), tileid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } pub fn ITaskbarManagerStatics<R, F: FnOnce(&ITaskbarManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TaskbarManager, ITaskbarManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TaskbarManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Shell.TaskbarManager;{87490a19-1ad9-49f4-b2e8-86738dc5ac40})"); } unsafe impl ::windows::core::Interface for TaskbarManager { type Vtable = ITaskbarManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x87490a19_1ad9_49f4_b2e8_86738dc5ac40); } impl ::windows::core::RuntimeName for TaskbarManager { const NAME: &'static str = "Windows.UI.Shell.TaskbarManager"; } impl ::core::convert::From<TaskbarManager> for ::windows::core::IUnknown { fn from(value: TaskbarManager) -> Self { value.0 .0 } } impl ::core::convert::From<&TaskbarManager> for ::windows::core::IUnknown { fn from(value: &TaskbarManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TaskbarManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TaskbarManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TaskbarManager> for ::windows::core::IInspectable { fn from(value: TaskbarManager) -> Self { value.0 } } impl ::core::convert::From<&TaskbarManager> for ::windows::core::IInspectable { fn from(value: &TaskbarManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TaskbarManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TaskbarManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TaskbarManager {} unsafe impl ::core::marker::Sync for TaskbarManager {}
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_synthetic_add_layer_version_permission_input_body( input: &crate::input::AddLayerVersionPermissionInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::AddLayerVersionPermissionInputBody { statement_id: &input.statement_id, action: &input.action, principal: &input.principal, organization_id: &input.organization_id, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_add_permission_input_body( input: &crate::input::AddPermissionInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::AddPermissionInputBody { statement_id: &input.statement_id, action: &input.action, principal: &input.principal, source_arn: &input.source_arn, source_account: &input.source_account, event_source_token: &input.event_source_token, revision_id: &input.revision_id, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_alias_input_body( input: &crate::input::CreateAliasInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateAliasInputBody { name: &input.name, function_version: &input.function_version, description: &input.description, routing_config: &input.routing_config, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_code_signing_config_input_body( input: &crate::input::CreateCodeSigningConfigInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateCodeSigningConfigInputBody { description: &input.description, allowed_publishers: &input.allowed_publishers, code_signing_policies: &input.code_signing_policies, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_event_source_mapping_input_body( input: &crate::input::CreateEventSourceMappingInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateEventSourceMappingInputBody { event_source_arn: &input.event_source_arn, function_name: &input.function_name, enabled: &input.enabled, batch_size: &input.batch_size, maximum_batching_window_in_seconds: &input.maximum_batching_window_in_seconds, parallelization_factor: &input.parallelization_factor, starting_position: &input.starting_position, starting_position_timestamp: &input.starting_position_timestamp, destination_config: &input.destination_config, maximum_record_age_in_seconds: &input.maximum_record_age_in_seconds, bisect_batch_on_function_error: &input.bisect_batch_on_function_error, maximum_retry_attempts: &input.maximum_retry_attempts, tumbling_window_in_seconds: &input.tumbling_window_in_seconds, topics: &input.topics, queues: &input.queues, source_access_configurations: &input.source_access_configurations, self_managed_event_source: &input.self_managed_event_source, function_response_types: &input.function_response_types, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_function_input_body( input: &crate::input::CreateFunctionInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateFunctionInputBody { function_name: &input.function_name, runtime: &input.runtime, role: &input.role, handler: &input.handler, code: &input.code, description: &input.description, timeout: &input.timeout, memory_size: &input.memory_size, publish: &input.publish, vpc_config: &input.vpc_config, package_type: &input.package_type, dead_letter_config: &input.dead_letter_config, environment: &input.environment, kms_key_arn: &input.kms_key_arn, tracing_config: &input.tracing_config, tags: &input.tags, layers: &input.layers, file_system_configs: &input.file_system_configs, image_config: &input.image_config, code_signing_config_arn: &input.code_signing_config_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn ser_payload_invoke_input( payload: std::option::Option<smithy_types::Blob>, ) -> Result<smithy_http::body::SdkBody, smithy_http::operation::BuildError> { let payload = match payload { Some(t) => t, None => return Ok(smithy_http::body::SdkBody::from("")), }; #[allow(clippy::useless_conversion)] Ok(smithy_http::body::SdkBody::from(payload.into_inner())) } pub fn ser_payload_invoke_async_input( payload: smithy_http::byte_stream::ByteStream, ) -> Result<smithy_http::body::SdkBody, smithy_http::operation::BuildError> { #[allow(clippy::useless_conversion)] Ok(smithy_http::body::SdkBody::from(payload.into_inner())) } pub fn serialize_synthetic_publish_layer_version_input_body( input: &crate::input::PublishLayerVersionInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PublishLayerVersionInputBody { description: &input.description, content: &input.content, compatible_runtimes: &input.compatible_runtimes, license_info: &input.license_info, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_publish_version_input_body( input: &crate::input::PublishVersionInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PublishVersionInputBody { code_sha256: &input.code_sha256, description: &input.description, revision_id: &input.revision_id, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_put_function_code_signing_config_input_body( input: &crate::input::PutFunctionCodeSigningConfigInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PutFunctionCodeSigningConfigInputBody { code_signing_config_arn: &input.code_signing_config_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_put_function_concurrency_input_body( input: &crate::input::PutFunctionConcurrencyInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PutFunctionConcurrencyInputBody { reserved_concurrent_executions: &input.reserved_concurrent_executions, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_put_function_event_invoke_config_input_body( input: &crate::input::PutFunctionEventInvokeConfigInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PutFunctionEventInvokeConfigInputBody { maximum_retry_attempts: &input.maximum_retry_attempts, maximum_event_age_in_seconds: &input.maximum_event_age_in_seconds, destination_config: &input.destination_config, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_put_provisioned_concurrency_config_input_body( input: &crate::input::PutProvisionedConcurrencyConfigInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PutProvisionedConcurrencyConfigInputBody { provisioned_concurrent_executions: &input.provisioned_concurrent_executions, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_tag_resource_input_body( input: &crate::input::TagResourceInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::TagResourceInputBody { tags: &input.tags }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_alias_input_body( input: &crate::input::UpdateAliasInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateAliasInputBody { function_version: &input.function_version, description: &input.description, routing_config: &input.routing_config, revision_id: &input.revision_id, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_code_signing_config_input_body( input: &crate::input::UpdateCodeSigningConfigInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateCodeSigningConfigInputBody { description: &input.description, allowed_publishers: &input.allowed_publishers, code_signing_policies: &input.code_signing_policies, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_event_source_mapping_input_body( input: &crate::input::UpdateEventSourceMappingInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateEventSourceMappingInputBody { function_name: &input.function_name, enabled: &input.enabled, batch_size: &input.batch_size, maximum_batching_window_in_seconds: &input.maximum_batching_window_in_seconds, destination_config: &input.destination_config, maximum_record_age_in_seconds: &input.maximum_record_age_in_seconds, bisect_batch_on_function_error: &input.bisect_batch_on_function_error, maximum_retry_attempts: &input.maximum_retry_attempts, parallelization_factor: &input.parallelization_factor, source_access_configurations: &input.source_access_configurations, tumbling_window_in_seconds: &input.tumbling_window_in_seconds, function_response_types: &input.function_response_types, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_function_code_input_body( input: &crate::input::UpdateFunctionCodeInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateFunctionCodeInputBody { zip_file: &input.zip_file, s3_bucket: &input.s3_bucket, s3_key: &input.s3_key, s3_object_version: &input.s3_object_version, image_uri: &input.image_uri, publish: &input.publish, dry_run: &input.dry_run, revision_id: &input.revision_id, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_function_configuration_input_body( input: &crate::input::UpdateFunctionConfigurationInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateFunctionConfigurationInputBody { role: &input.role, handler: &input.handler, description: &input.description, timeout: &input.timeout, memory_size: &input.memory_size, vpc_config: &input.vpc_config, environment: &input.environment, runtime: &input.runtime, dead_letter_config: &input.dead_letter_config, kms_key_arn: &input.kms_key_arn, tracing_config: &input.tracing_config, revision_id: &input.revision_id, layers: &input.layers, file_system_configs: &input.file_system_configs, image_config: &input.image_config, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_function_event_invoke_config_input_body( input: &crate::input::UpdateFunctionEventInvokeConfigInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateFunctionEventInvokeConfigInputBody { maximum_retry_attempts: &input.maximum_retry_attempts, maximum_event_age_in_seconds: &input.maximum_event_age_in_seconds, destination_config: &input.destination_config, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) }
extern crate criterion_ex; use criterion::{criterion_group, criterion_main, Criterion}; use criterion_ex::*; fn fibonacci_benchmark(c: &mut Criterion) { c.bench_function("fibonacci 7", |b| { b.iter(|| recursive_process_fibancci(7, 0, 1)) }); } criterion_group!(bench, fibonacci_benchmark); criterion_main!(bench);
//! The RegexFilter allows the formatted or unformatted message to be compared against a regular //! expression. use Filter; use config::filter::MatchAction; use config::filter::MatchAction::*; use log::{LogLevelFilter, LogRecord}; use regex::Regex; #[cfg_attr(test, derive(PartialEq))] #[derive(Clone, Debug)] /// Regex Filter Configuration pub struct RegexFilter { /// Optional minimal level of messages to be filtered. Anything at or above this level will be /// filtered out if `regex` has been matched. The default is `Warn` meaning any messages that /// are lower than `Warn` (i.e. `Error`) will be logged regardless of match. level: Option<LogLevelFilter>, /// Regex regex: String, // Use the raw messge. The default `false` indicates the formatted message will be used. use_raw: Option<bool>, /// The action to take when the filter matches. Defaults to `Neutral`. on_match: Option<MatchAction>, /// The action to take when the filter does not match. Defaults to `Deny`. on_mismatch: Option<MatchAction>, } impl RegexFilter { /// Create a new RegexFilter with the given name. pub fn new(regex: String) -> RegexFilter { RegexFilter { level: None, regex: regex, use_raw: None, on_match: None, on_mismatch: None, } } /// Set the minimum level to be filtered if the regex matches. Anything lower will always be /// logged. pub fn level(mut self, level: Option<LogLevelFilter>) -> RegexFilter { self.level = level; self } /// Use the raw message to compare to the regex, rather than the formatted message. pub fn use_raw(mut self, use_raw: Option<bool>) -> RegexFilter { self.use_raw = use_raw; self } /// Set the on match MatchAction. Default is Neutral. pub fn on_match(mut self, action: Option<MatchAction>) -> RegexFilter { self.on_match = action; self } /// Set the on mis-match MatchAction. Default is Deny. pub fn on_mismatch(mut self, action: Option<MatchAction>) -> RegexFilter { self.on_mismatch = action; self } } impl Filter for RegexFilter { fn filter(&self, record: &LogRecord) -> MatchAction { let level = match self.level { Some(l) => l, None => LogLevelFilter::Warn, }; let use_raw = match self.use_raw { Some(ur) => ur, None => false, }; let matched = match Regex::new(&self.regex[..]) { Ok(re) => { if use_raw { re.is_match(&format!("{}", record.args())[..]) } else { // TODO: match against formatted message when pattern is implemented. true } } Err(_) => true, }; // Check for a match, or if the record level is less that the configured minimum level. if matched || record.level() < level { // Return on_match result. match self.on_match { Some(ref m) => m.clone(), None => Neutral, } } else { // Return on_mismatch result. match self.on_mismatch { Some(ref m) => m.clone(), None => Deny, } } } } #[cfg(feature = "rustc-serialize")] mod rs { use config::rs::read_llf_opt; use rustc_serialize::{Decodable, Decoder}; use super::*; impl Decodable for RegexFilter { fn decode<D: Decoder>(d: &mut D) -> Result<RegexFilter, D::Error> { d.read_struct("RegexFilter", 5, |d| { let level = try!(d.read_struct_field("level", 1, |d| d.read_option(read_llf_opt))); let regex = try!(d.read_struct_field("regex", 2, |d| Decodable::decode(d))); let use_raw = try!(d.read_struct_field("use_raw", 3, |d| Decodable::decode(d))); let on_match = try!(d.read_struct_field("on_match", 4, |d| Decodable::decode(d))); let on_mismatch = try!(d.read_struct_field("on_mismatch", 5, |d| Decodable::decode(d))); let rf = RegexFilter::new(regex) .level(level) .use_raw(use_raw) .on_match(on_match) .on_mismatch(on_mismatch); Ok(rf) }) } } } #[cfg(feature = "serde")] mod serde { use config::serde::LogLevelFilterField; use config::filter::serde::MatchActionField; use super::*; use serde::{Deserialize, Deserializer}; use serde::de::{MapVisitor, Visitor}; enum RegexFilterField { Level, Regex, UseRaw, OnMatch, OnMismatch, } impl Deserialize for RegexFilterField { fn deserialize<D>(deserializer: &mut D) -> Result<RegexFilterField, D::Error> where D: Deserializer { struct RegexFilterFieldVisitor; impl Visitor for RegexFilterFieldVisitor { type Value = RegexFilterField; fn visit_str<E>(&mut self, value: &str) -> Result<RegexFilterField, E> where E: ::serde::de::Error { match value { "level" => Ok(RegexFilterField::Level), "regex" => Ok(RegexFilterField::Regex), "use_raw" => Ok(RegexFilterField::UseRaw), "on_match" => Ok(RegexFilterField::OnMatch), "on_mismatch" => Ok(RegexFilterField::OnMismatch), _ => Err(::serde::de::Error::syntax("Unexpected field!")), } } } deserializer.visit(RegexFilterFieldVisitor) } } impl Deserialize for RegexFilter { fn deserialize<D>(deserializer: &mut D) -> Result<RegexFilter, D::Error> where D: Deserializer { static FIELDS: &'static [&'static str] = &["level", "regex", "use_raw", "on_match", "on_mismatch"]; deserializer.visit_struct("RegexFilter", FIELDS, RegexFilterVisitor) } } struct RegexFilterVisitor; impl Visitor for RegexFilterVisitor { type Value = RegexFilter; fn visit_map<V>(&mut self, mut visitor: V) -> Result<RegexFilter, V::Error> where V: MapVisitor { let mut level: Option<LogLevelFilterField> = None; let mut regex: Option<String> = None; let mut use_raw: Option<bool> = None; let mut on_match: Option<MatchActionField> = None; let mut on_mismatch: Option<MatchActionField> = None; loop { match try!(visitor.visit_key()) { Some(RegexFilterField::Level) => { level = Some(try!(visitor.visit_value())); } Some(RegexFilterField::Regex) => { regex = Some(try!(visitor.visit_value())); } Some(RegexFilterField::UseRaw) => { use_raw = Some(try!(visitor.visit_value())); } Some(RegexFilterField::OnMatch) => { on_match = Some(try!(visitor.visit_value())); } Some(RegexFilterField::OnMismatch) => { on_mismatch = Some(try!(visitor.visit_value())); } None => { break; } } } let lvl = match level { Some(l) => Some(l.level()), None => None, }; let re = match regex { Some(r) => r, None => return visitor.missing_field("regex"), }; let omma = match on_match { Some(om) => Some(om.match_action()), None => None, }; let ommma = match on_mismatch { Some(omm) => Some(omm.match_action()), None => None, }; try!(visitor.end()); let rf = RegexFilter::new(re) .level(lvl) .use_raw(use_raw) .on_match(omma) .on_mismatch(ommma); Ok(rf) } } } #[cfg(test)] mod test { use decode; use super::*; const BASE_CONFIG: &'static str = r#" regex = "^Blah" "#; const ALL_CONFIG: &'static str = r#" regex = "^Blah" level = "Debug" use_raw = true on_match = "Accept" on_mismatch = "Neutral" "#; static VALIDS: &'static [&'static str] = &[BASE_CONFIG, ALL_CONFIG]; const INVALID_CONFIG_0: &'static str = r#""#; const INVALID_CONFIG_1: &'static str = r#" regex = 1 "#; const INVALID_CONFIG_2: &'static str = r#" regex = "" level = "NOt A LeVel" "#; const INVALID_CONFIG_3: &'static str = r#" regex = "" use_raw = "NOT A BOOL" "#; const INVALID_CONFIG_4: &'static str = r#" regex = "" on_match = 1 "#; const INVALID_CONFIG_5: &'static str = r#" regex = "" on_mismatch = 1 "#; const INVALID_CONFIG_6: &'static str = r#" invalid = 1 "#; static INVALIDS: &'static [&'static str] = &[INVALID_CONFIG_0, INVALID_CONFIG_1, INVALID_CONFIG_2, INVALID_CONFIG_3, INVALID_CONFIG_4, INVALID_CONFIG_5, INVALID_CONFIG_6]; #[test] fn test_valid_configs() { let mut results = Vec::new(); for valid in VALIDS { match decode::<RegexFilter>(valid) { Ok(_) => results.push(true), Err(_) => assert!(false), }; } assert!(results.iter().all(|x| *x)); } #[test] fn test_invalid_configs() { let mut results = Vec::new(); for invalid in INVALIDS { match decode::<RegexFilter>(invalid) { Ok(_) => assert!(false), Err(_) => results.push(true), }; } assert!(results.iter().all(|x| *x)); } }
extern crate assert_cli; extern crate wppr; use std::path::PathBuf; #[path = "./testfns.rs"] mod testfns; #[test] fn test_app_config_works() { let cfg_file: PathBuf = testfns::get_tests_dir("data/libtestwppr.toml"); let mut binpath: PathBuf = testfns::get_cwd(); binpath.push("target/debug/wppr"); let bin = binpath.to_str().unwrap(); assert_cli::Assert::command(&[bin, "help"]) .succeeds() .stdout() .contains("list") .unwrap(); assert_cli::Assert::command(&[bin, "--configuration", cfg_file.to_str().unwrap(), "list"]) .succeeds() .stdout() .contains("plugin.php") .stdout() .contains("0.1.2") .unwrap(); assert_cli::Assert::command(&[bin, "list"]).fails().unwrap(); assert_cli::Assert::command(&[bin, "--configuration", "./relative/path.toml", "list"]) .fails() .stderr() .contains("given as an absolute path") .unwrap(); }
use crate::utils; use std::collections::HashMap; const TEST_MODE: bool = false; fn read_problem_data() -> Vec<i64> { let mut result = Vec::new(); let path = if TEST_MODE { "data/day9.test.txt" } else { "data/day9.txt" }; if let Ok(lines) = utils::read_lines(path) { for line in lines { if let Ok(s) = line { result.push(s.parse::<i64>().unwrap()); } } } result } fn has_sum(data: &[i64], sum: i64) -> bool { let mut map = HashMap::new(); for v in data { if let Some(_) = map.get(v) { return true; } let diff = i64::abs(sum - v); map.insert(diff, v); } return false; } fn find_first_without_sum(data: &Vec<i64>, preamble_len: usize) -> i64 { let mut start = 0; let mut idx = preamble_len; while idx < data.len() { let sum = data[idx]; if !has_sum(&data[start..start + preamble_len], sum) { return sum; } start += 1; idx += 1; } return 0; } #[allow(dead_code)] pub fn problem1() { println!("running problem 9.1:"); let data = read_problem_data(); if TEST_MODE { println!("Found: {}", find_first_without_sum(&data, 5)); } else { println!("Found: {}", find_first_without_sum(&data, 25)); } } #[allow(dead_code)] pub fn problem2() { println!("running problem 9.2:"); let invalid_num = if TEST_MODE { 127 } else { 14360655 }; // let invalid_num = 14360655; let data = read_problem_data(); let mut start = 0; let mut end = 1; while end < data.len() { let sum: i64 = data[start..end].iter().sum(); if sum == invalid_num { let mut sorted = data[start..end].to_vec(); sorted.sort(); println!( "Found {}, {}; sum: {}", sorted.first().unwrap(), sorted.last().unwrap(), sorted.first().unwrap() + sorted.last().unwrap(), ); break; } else if sum < invalid_num { end += 1; } else { start += 1; end = start; } } }
use super::{io, PinBuilder, Runner, SubCommand}; use crate::AlfredError; use std::io::Write; use super::browser_info; impl<'api, 'pin> Runner<'api, 'pin> { pub fn post(&mut self, cmd: SubCommand) { match self.perform_post(cmd) { Ok(s) => { io::stdout() .write_all(s.as_bytes()) .expect("Couldn't write to stdout"); if self.config.as_ref().unwrap().auto_update_cache { self.update_cache(false); } } Err(e) => { let msg = ["Error: ", e.to_string().as_str()].concat(); io::stdout() .write_all(msg.as_bytes()) .expect("Couldn't write to stdout"); } } } fn perform_post(&mut self, cmd: SubCommand) -> Result<String, Box<dyn std::error::Error>> { debug!("Starting in perform_post"); let input_tags: Vec<String>; let input_desc; let toread; let shared; match cmd { SubCommand::Post { tags, description, shared: shared_flag, toread: toread_flag, } => { debug!( "tags: {:?}, description: {:?}, toread_flag: {:?}, shared_flag: {:?}", tags, description, toread_flag, shared_flag ); input_tags = tags; input_desc = description; toread = toread_flag.unwrap_or_else(|| self.config.as_ref().unwrap().toread_new_pin); shared = shared_flag.unwrap_or_else(|| !self.config.as_ref().unwrap().private_new_pin); // toread.map(|f| self.config.as_mut().map(|config| config.toread_new_pin = f)); // shared.map(|f| { // self.config // .as_mut() // .map(|config| config.private_new_pin = !f) // }); } _ => unreachable!(), } let browser_tab_info = browser_info::get().map_err(|e| { error!("{}", e.to_string()); AlfredError::Post2PinboardFailed("cannot get browser's info".to_string()) })?; // let browser_tab_info = browser_info::get().unwrap_or_else(|e| { // let _ = io::stdout() // .write(format!("Error: {}", e).as_ref()) // .expect("Couldn't write to stdout"); // process::exit(1); // }); let mut pin_builder = PinBuilder::new(&browser_tab_info.url, &browser_tab_info.title); pin_builder = pin_builder .tags(input_tags.join(" ")) // .shared(if self.config.as_ref().unwrap().private_new_pin { .shared(if shared { "yes" } else { "no" }) // .toread(if self.config.as_ref().unwrap().toread_new_pin { .toread(if toread { "yes" } else { "no" }); if let Some(desc) = input_desc { pin_builder = pin_builder.description(desc); } self.pinboard .as_mut() .unwrap() .add_pin(pin_builder.into_pin()) .map_err(|e| { error!("{}", e.to_string()); AlfredError::Post2PinboardFailed("Could not post to Pinboard.".to_string()) })?; Ok(format!("Successfully posted: {}\n", browser_tab_info.title)) // if let Err(e) = self // .pinboard // .as_mut() // .unwrap() // .add_pin(pin_builder.into_pin()) // { // if let Err(io_err) = io::stdout().write(format!("Error: {}", e).as_ref()) { // error!( // "Failed to post to Pinboard AND to notify user: {}", // io_err.to_string() // ); // } // } else { // if let Err(io_err) = io::stdout() // .write(format!("Successfully posted: {}\n", browser_tab_info.title).as_ref()) // { // error!( // "Failed to notify user about posting to Pinboard successfully: {}", // io_err.to_string() // ); // } // if self.config.as_ref().unwrap().auto_update_cache { // self.update_cache(); // } // } } }
mod asset_view; pub use asset_view::AssetView;
use bevy::{ prelude::Mesh, render::mesh::Indices, render::mesh::VertexAttribute, render::pipeline::PrimitiveTopology, }; use hexasphere::Hexasphere; use crate::plugin::reverse_triangles; /// A sphere made from a subdivided Icosahedron. pub struct SkySphere { /// The radius of the sphere. pub radius: f32, /// The number of subdivisions applied. pub subdivisions: usize, } impl Default for SkySphere { fn default() -> Self { Self { radius: 1.0, subdivisions: 5, } } } impl From<SkySphere> for Mesh { fn from(sphere: SkySphere) -> Self { if sphere.subdivisions >= 80 { let temp_sphere = Hexasphere::new(sphere.subdivisions, |_| ()); panic!( "Cannot create an icosphere of {} subdivisions due to there being too many vertices being generated: {} (Limited to 65535 vertices or 79 subdivisions)", sphere.subdivisions, temp_sphere.raw_points().len() ); } let hexasphere = Hexasphere::new(sphere.subdivisions, |point| { let inclination = point.z().acos(); let azumith = point.y().atan2(point.x()); let norm_inclination = 1.0 - (inclination / std::f32::consts::PI); let mut norm_azumith = (azumith / std::f32::consts::PI) * 0.5; if norm_azumith < 0.0 { norm_azumith += 1.0 } [norm_inclination, norm_azumith] }); let raw_points = hexasphere.raw_points(); let points = raw_points .iter() .map(|&p| (p * sphere.radius).into()) .collect::<Vec<[f32; 3]>>(); let normals = raw_points .iter() .copied() .map(Into::into) .collect::<Vec<[f32; 3]>>(); let uvs = hexasphere.raw_data().to_owned(); let mut indices = Vec::with_capacity(hexasphere.indices_per_main_triangle() * 20); for i in 0..20 { hexasphere.get_indices(i, &mut indices); } let indices = Indices::U32(indices); Mesh { primitive_topology: PrimitiveTopology::TriangleList, attributes: vec![ VertexAttribute::position(points), VertexAttribute::normal(normals), VertexAttribute::uv(uvs), ], indices: reverse_triangles(Some(indices)), } } }
use std::iter::FromIterator; #[derive(Clone, Default)] pub struct Buffer { pub buffer: Vec<char>, pub buffer_pos: usize, } impl Buffer { pub fn new() -> Self { Self { ..Self::default() } } pub fn insert(&mut self, c: char) { self.buffer.insert(self.buffer_pos, c); self.move_forward(); } pub fn insert_str(&mut self, s: &str) { s.chars().for_each(|c| self.insert(c)); } pub fn set_buffer_pos(&mut self, pos: usize) { self.buffer_pos = pos; } pub fn remove_current_char(&mut self) -> Option<char> { if !self.is_empty() && self.buffer_pos < self.buffer.len() { let character = self.buffer.remove(self.buffer_pos); Some(character) } else { None } } pub fn next_char(&self) -> Option<&char> { self.buffer.get(self.buffer_pos + 1) } pub fn current_char(&self) -> Option<&char> { self.buffer.get(self.buffer_pos) } pub fn previous_char(&self) -> Option<&char> { if self.buffer_pos > 0 { self.buffer.get(self.buffer_pos - 1) } else { None } } pub fn move_forward(&mut self) { self.buffer_pos += 1; } pub fn move_backward(&mut self) { if self.buffer_pos != 0 { self.buffer_pos -= 1; } } pub fn clear(&mut self) { self.buffer.clear(); self.buffer_pos = 0; } pub fn len(&self) -> usize { self.buffer.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn is_at_string_line_start(&self) -> bool { self.is_empty() || self.buffer[..self.buffer_pos] .rsplitn(2, |d| d == &'\n') .next() .unwrap_or_default() .iter() .all(|c| c.is_whitespace()) } pub fn is_at_start(&self) -> bool { self.buffer_pos == 0 } pub fn is_at_end(&self) -> bool { self.buffer_pos == self.buffer.len() } pub fn goto_start(&mut self) { self.buffer_pos = 0; } pub fn goto_end(&mut self) { self.buffer_pos = self.buffer.len(); } pub fn _push_str(&mut self, str: &str) { self.buffer.extend(str.chars()); self.buffer_pos = self.buffer.len(); } pub fn get(&self, idx: usize) -> Option<&char> { self.buffer.get(idx) } pub fn _last(&self) -> Option<&char> { self.buffer.last() } pub fn iter(&self) -> impl Iterator<Item = &char> { self.buffer.iter() } pub fn take(&mut self) -> Vec<char> { let buffer = std::mem::take(&mut self.buffer); self.clear(); self.goto_start(); buffer } } impl ToString for Buffer { fn to_string(&self) -> String { self.buffer.iter().collect() } } impl From<&str> for Buffer { fn from(string: &str) -> Self { Self { buffer: string.chars().collect(), buffer_pos: 0, } } } impl From<String> for Buffer { fn from(string: String) -> Self { Self { buffer: string.chars().collect(), buffer_pos: 0, } } } impl From<Vec<char>> for Buffer { fn from(buffer: Vec<char>) -> Self { Self { buffer, buffer_pos: 0, } } } impl FromIterator<char> for Buffer { fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Buffer { let mut buffer = Buffer::new(); for c in iter { buffer.buffer.push(c); } buffer } }
#![allow(unsafe_code)] use crate::backend::c; use core::num::NonZeroI32; /// A process identifier as a raw integer. pub type RawPid = c::pid_t; /// `pid_t`—A non-zero Unix process ID. /// /// This is a pid, and not a pidfd. It is not a file descriptor, and the /// process it refers to could disappear at any time and be replaced by /// another, unrelated, process. #[repr(transparent)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub struct Pid(NonZeroI32); impl Pid { /// A `Pid` corresponding to the init process (pid 1). pub const INIT: Self = Self( // SAFETY: One is non-zero. unsafe { NonZeroI32::new_unchecked(1) }, ); /// Converts a `RawPid` into a `Pid`. /// /// Returns `Some` for strictly positive `RawPid`s. Otherwise, returns /// `None`. /// /// This is always safe because a `Pid` is a number without any guarantees /// for the kernel. Non-child `Pid`s are always racy for any syscalls, /// but can only cause logic errors. If you want race-free access or /// control to non-child processes, please consider other mechanisms /// like [pidfd] on Linux. /// /// [pidfd]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html #[inline] pub const fn from_raw(raw: RawPid) -> Option<Self> { if raw > 0 { // SAFETY: raw > 0. unsafe { Some(Self::from_raw_unchecked(raw)) } } else { None } } /// Converts a known strictly positive `RawPid` into a `Pid`. /// /// # Safety /// /// The caller must guarantee `raw` is strictly positive. #[inline] pub const unsafe fn from_raw_unchecked(raw: RawPid) -> Self { debug_assert!(raw > 0); Self(NonZeroI32::new_unchecked(raw)) } /// Creates a `Pid` holding the ID of the given child process. #[cfg(feature = "std")] #[inline] pub fn from_child(child: &std::process::Child) -> Self { let id = child.id(); // SAFETY: We know the returned ID is valid because it came directly // from an OS API. unsafe { Self::from_raw_unchecked(id as i32) } } /// Converts a `Pid` into a `NonZeroI32`. #[inline] pub const fn as_raw_nonzero(self) -> NonZeroI32 { self.0 } /// Converts an `Option<Pid>` into a `RawPid`. #[inline] pub fn as_raw(pid: Option<Self>) -> RawPid { pid.map_or(0, |pid| pid.0.get()) } /// Test whether this pid represents the init process (pid 1). #[inline] pub const fn is_init(self) -> bool { self.0.get() == Self::INIT.0.get() } } #[test] fn test_sizes() { use core::mem::transmute; assert_eq_size!(RawPid, NonZeroI32); assert_eq_size!(RawPid, Pid); assert_eq_size!(RawPid, Option<Pid>); // Rustix doesn't depend on `Option<Pid>` matching the ABI of a raw integer // for correctness, but it should work nonetheless. const_assert_eq!(0 as RawPid, unsafe { transmute::<Option<Pid>, RawPid>(None) }); const_assert_eq!(4567 as RawPid, unsafe { transmute::<Option<Pid>, RawPid>(Some(Pid::from_raw_unchecked(4567))) }); }
pub use n3_machine_ffi::{Error as MachineError, QueryError}; use n3_machine_ffi::{Query, WorkId}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { LoadError(LoadError), WorkError(WorkError), MachineError(MachineError), } #[derive(Debug)] pub enum LoadError { NoSuchMachine { query: Query }, } #[derive(Debug)] pub enum WorkError { NoSuchWork { id: WorkId }, } impl From<LoadError> for Error { fn from(error: LoadError) -> Self { Self::LoadError(error) } } impl From<WorkError> for Error { fn from(error: WorkError) -> Self { Self::WorkError(error) } } impl From<QueryError> for Error { fn from(error: QueryError) -> Self { Self::MachineError(error.into()) } } impl From<MachineError> for Error { fn from(error: MachineError) -> Self { Self::MachineError(error) } } impl<T> From<LoadError> for Result<T> { fn from(error: LoadError) -> Self { Err(Error::from(error)) } } impl<T> From<WorkError> for Result<T> { fn from(error: WorkError) -> Self { Err(Error::from(error)) } }
use sdl2::EventPump; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::video::{Window, WindowContext}; use sdl2::render::{Canvas, TextureCreator, Texture}; use sdl2::image::{self, LoadTexture, InitFlag}; use sdl2::rect::Rect; use sdl2::pixels::Color; use std::time::Duration; struct Dillo { position: Rect, x_speed: i32, y_speed: i32, collision_rect: Option<Rect> } impl Dillo { fn new(x: i32, y: i32) -> Dillo { Dillo { position: Rect::from((x, y, 63, 85)), x_speed: 0, y_speed: 0, collision_rect: None } } fn update_position(& mut self) { self.position.set_x(self.position.x + self.x_speed); self.position.set_y(self.position.y + self.y_speed); } } trait Collider { fn new(x: i32, y: i32, width: u32, heigh: u32) -> Self; fn get_rect(&self) -> Rect; } struct Ground { rect: Rect } impl Collider for Ground { fn new(x: i32, y: i32, width: u32, height: u32) -> Ground { Ground { rect: Rect::new(x, y, width, height) } } fn get_rect(&self) -> Rect { return self.rect } } fn collide<T: Collider>(colliding_objects: &Vec<&T>, dillo: &mut Dillo) { let mut colliding_objects_count = 0; for colliding_object in colliding_objects { let collision: Option<Rect> = colliding_object.get_rect().intersection(dillo.position); if let Some(current_collision) = collision { if let Some(previous_collision) = dillo.collision_rect { // there's a previous intersect, see if the height or width has changed // if height changed, set y_speed to 0, if width changed, reverse direction if current_collision.height() != previous_collision.height() { // we must be colliding on the y axis dillo.y_speed = 0; break } } else { // no previous intersect, just updated the intersect on the ground object dillo.collision_rect = Some(current_collision); } } colliding_objects_count += 1; } if colliding_objects_count == colliding_objects.len() { // nothing collided dillo.y_speed = 5; } } fn main() -> Result<(), String> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window: Window = video_subsystem.window("Dillos", 2436, 1125) .position_centered() .build() .expect("could not initialize video subsystem"); let _image_context = image::init(InitFlag::PNG)?; let mut canvas: Canvas<Window> = window.into_canvas().build() .expect("could not make a canvas"); let texture_creator: TextureCreator<WindowContext> = canvas.texture_creator(); let dillo_texture: Texture = texture_creator.load_texture("assets/dillo/dwf/dwf1.png")?; let mut dillo1 = Dillo::new(0, 0); // x, y, width, height let g1 = Ground::new(0, 700, 650, 200); let g2 = Ground::new(250, 800, 650, 200); let colliders = vec!(&g1, &g2); let mut event_pump: EventPump = sdl_context.event_pump()?; let mut start_game: bool = false; let mut start_speed_set: bool = false; 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => { break 'running; }, Event::MouseButtonDown {..} | Event::FingerDown {..} => { start_game = true; } _ => {} } } if start_game { if !start_speed_set { dillo1.y_speed = 5; dillo1.x_speed = 3; start_speed_set = true; } dillo1.update_position(); collide(&colliders, &mut dillo1); } canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); canvas.set_draw_color(Color::RGB(255, 0, 0)); canvas.draw_rect(g1.rect)?; canvas.draw_rect(g2.rect)?; canvas.copy(&dillo_texture, None, dillo1.position)?; canvas.present(); ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60)); } Ok(()) }
use crate::app::Args; use anyhow::{Context, Result}; use clap::Parser; use icon::Icon; use maple_core::process::shell_command; use maple_core::process::{CacheableCommand, ShellCommand}; use maple_core::tools::rg::Match; use rayon::prelude::*; use std::convert::TryFrom; use std::path::PathBuf; /// Invoke the rg executable and return the raw output of rg. /// /// The search result won't be shown until the stream is complete. #[derive(Parser, Debug, Clone)] pub struct LiveGrep { /// Specify the query string for GREP_CMD. #[clap(index = 1)] grep_query: String, /// Delegate to -g option of rg #[clap(long)] glob: Option<String>, /// Specify the grep command to run, normally rg will be used. /// /// Incase of clap can not reconginize such option: --cmd "rg --vimgrep ... "fn ul"". /// |-----------------| /// this can be seen as an option by mistake. #[clap(long, required_if_eq("sync", "true"))] grep_cmd: Option<String>, /// Specify the working directory of CMD #[clap(long, value_parser)] cmd_dir: Option<PathBuf>, /// Read input from a cached grep tempfile, only absolute file path is supported. #[clap(long, value_parser)] input: Option<PathBuf>, } impl LiveGrep { /// Runs grep command and returns until its output stream is completed. /// /// Write the output to the cache file if neccessary. pub fn run( &self, Args { number, winwidth, icon, .. }: Args, ) -> Result<()> { let mut grep_cmd = self .grep_cmd .clone() .context("--grep-cmd is required when --sync is on")?; if let Some(ref g) = self.glob { grep_cmd.push_str(" -g "); grep_cmd.push_str(g); } // Force using json format. grep_cmd.push_str(" --json "); grep_cmd.push_str(&self.grep_query); // currently vim-clap only supports rg. // Ref https://github.com/liuchengxu/vim-clap/pull/60 grep_cmd.push_str(" ."); // Shell command avoids https://github.com/liuchengxu/vim-clap/issues/595 let mut std_cmd = shell_command(&grep_cmd); if let Some(ref dir) = self.cmd_dir { std_cmd.current_dir(dir); } let shell_cmd = ShellCommand::new(grep_cmd, std::env::current_dir()?); let execute_info = CacheableCommand::new(&mut std_cmd, shell_cmd, number, Default::default(), None) .execute()?; let enable_icon = !matches!(icon, Icon::Null); let (lines, indices): (Vec<String>, Vec<Vec<usize>>) = execute_info .lines .par_iter() .filter_map(|s| { Match::try_from(s.as_str()) .ok() .map(|mat| mat.build_grep_line(enable_icon)) }) .unzip(); let total = lines.len(); let (lines, indices, truncated_map) = printer::truncate_grep_lines( lines, indices, winwidth.unwrap_or(80), if enable_icon { Some(2) } else { None }, ); if truncated_map.is_empty() { printer::println_json!(total, lines, indices); } else { let icon_added = enable_icon; printer::println_json!(total, lines, indices, truncated_map, icon_added); } Ok(()) } }
use crate::component_registry::ComponentRegistry; use crate::spatial_reader::ResourcesSystemData; use crate::system_commands::SystemCommandSender; use spatialos_sdk::worker::connection::WorkerConnection; use specs::prelude::{Resources, System, SystemData, WriteExpect}; /// A system which replicates changes in the local world to SpatialOS. /// /// This system should run at the end of each frame. /// /// This system **must not run in parallel with other systems**, or you may /// get a runtime panic. You can ensure this by creating a barrier before the system. /// /// ## Example /// /// ``` /// # use specs::prelude::*; /// # use spatialos_specs::*; /// # /// # struct MovePlayerSys; /// # impl<'a> System<'a> for MovePlayerSys{ /// # type SystemData = (); /// # /// # fn run(&mut self, _sys: ()) {} /// # } /// # /// let mut world = World::new(); /// /// let mut dispatcher = DispatcherBuilder::new() /// .with(SpatialReaderSystem, "reader", &[]) /// .with_barrier() /// /// .with(MovePlayerSys, "", &[]) /// /// .with_barrier() /// .with(SpatialWriterSystem, "writer", &[]) /// .build(); /// /// dispatcher.setup(&mut world.res); /// ``` pub struct SpatialWriterSystem; impl<'a> System<'a> for SpatialWriterSystem { type SystemData = ( WriteExpect<'a, WorkerConnection>, SystemCommandSender<'a>, ResourcesSystemData<'a>, ); fn setup(&mut self, res: &mut Resources) { Self::SystemData::setup(res); } fn run(&mut self, (mut connection, mut system_command_sender, res): Self::SystemData) { for interface in ComponentRegistry::interfaces_iter() { interface.replicate(&res.res, &mut connection); } system_command_sender.flush_requests(&mut connection); } }
use std::thread; fn main() { let top = 100 * 1000 * 1000; let each = top / 10; let mut kids = vec![]; for tt in 0..10 { let local_tt = tt.clone(); kids.push(thread::spawn(move || { let i0 = local_tt * each as i64; let i1 = i0 + each as i64; let mut sum = 0i64; for ii in i0..i1 { sum += ii; } sum })); } let mut sum = 0i64; for tt in kids { sum += tt.join().unwrap(); } println!("sum = {}", sum); }
use std::cmp::Ordering; pub fn find<T: Ord, U: AsRef<[T]>>(arr: U, key: T) -> Option<usize> { let array = arr.as_ref(); let mid = array.len() / 2; match key.cmp(array.get(mid)?) { Ordering::Equal => Some(mid), Ordering::Less => find(&array[..mid], key), Ordering::Greater => find(&array[mid + 1..], key).map(|n| n + mid + 1), } }
use super::error_types::XpsError; use super::material::RenderGroup; use std::ffi::CString; pub struct ImportParameters { pub flip_uv: bool, pub reverse_winding: bool, } pub struct Bone { pub id: i16, pub name: CString, pub co: [f32; 3], pub parent_id: i16, } pub struct BonePose { pub name: String, pub coordinate_delta: [f32; 3], pub rotation_delta: [f32; 3], pub scale: [f32; 3], } pub struct Mesh { pub name: CString, pub textures: Vec<Texture>, pub vertices: Vec<Vertex>, pub faces: Vec<u32>, pub uv_count: u16, pub render_group: RenderGroup, } #[derive(Default, Copy, Clone)] pub struct BoneWeight { pub id: i16, pub weight: f32, } #[derive(Default, Clone, Copy)] pub struct Vertex { pub position: [f32; 3], pub normal: [f32; 3], pub color: [u8; 4], pub uv: [[f32; 2]; 3], pub bone_weights: [BoneWeight; 4], pub merged: bool, } pub struct Texture { pub id: u16, pub file: CString, pub uv_layer: u16, } #[derive(Default)] pub struct Data { pub header: Header, pub bones: Vec<Bone>, pub meshes: Vec<Mesh>, pub error: XpsError, } pub struct Header { pub magic_number: u32, pub version_mayor: u16, pub version_minor: u16, pub aral: String, pub settings_length: u32, pub machine: String, pub user: String, pub file: String, pub settings: String, pub pose: String, } impl Default for Header { fn default() -> Header { Header { magic_number: 323232, version_mayor: 2, version_minor: 15, aral: String::from("XNAaraL"), settings_length: 275, machine: String::default(), user: String::default(), file: String::default(), settings: String::default(), pose: String::default(), } } }
use proconio::input; fn f(a: u64, x: u64, m: u64) -> u64 { assert!(x >= 1); if x == 1 { return 1 % m; } if x % 2 == 0 { (1 + a) * f(a * a % m, x / 2, m) % m } else { assert!(x >= 3); (1 + a * (1 + a) % m * f(a * a % m, (x - 1) / 2, m) % m) % m } } fn main() { input! { a: u64, x: u64, m: u64, }; let ans = f(a, x, m); println!("{}", ans); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::model::*, fidl::endpoints::ServerEnd, fidl_fuchsia_io::NodeMarker, fuchsia_vfs_pseudo_fs::directory::{self, entry::DirectoryEntry}, futures::future::BoxFuture, }; /// Trait that attempts to add an entry to a pseudo-fs directory, without waiting for a result. /// This wraps the `add_entry` method of structs that implement DirectoryEntry, streamlining /// the error type to `ModelError`. pub trait AddableDirectory<'entries> { /// Adds an entry to a directory. Named `add_node` instead of `add_entry` to avoid conflicts. fn add_node<Entry>( &mut self, name: &str, entry: Entry, moniker: &AbsoluteMoniker, ) -> Result<(), ModelError> where Entry: DirectoryEntry + 'entries; } /// Trait that attempts to add an entry to a pseudo-fs directory, waiting for a result. /// This wraps the `add_entry_res` method of structs that implement Controller, streamlining /// the error type to `ModelError`. pub trait AddableDirectoryWithResult<'entries> { /// Adds an entry to a directory. Named `add_node` instead of `add_entry_res` to avoid conflicts. fn add_node<'a, Entry>( &'a self, name: &'a str, entry: Entry, moniker: &'a AbsoluteMoniker, ) -> BoxFuture<Result<(), ModelError>> where Entry: DirectoryEntry + 'entries; fn remove_node<'a>( &'a self, name: &'a str, ) -> BoxFuture<Result<Option<Box<dyn DirectoryEntry + 'entries>>, ModelError>>; // Adds a connection to a directory. Nameed 'open_node' instead of 'open' to avoid conflicts. fn open_node<'a>( &'a self, flags: u32, mode: u32, path: Vec<String>, server_end: ServerEnd<NodeMarker>, moniker: &'a AbsoluteMoniker, ) -> BoxFuture<Result<(), ModelError>>; } impl<'entries> AddableDirectory<'entries> for directory::simple::Simple<'entries> { fn add_node<Entry>( &mut self, name: &str, entry: Entry, moniker: &AbsoluteMoniker, ) -> Result<(), ModelError> where Entry: DirectoryEntry + 'entries, { self.add_entry(name, entry).map_err(|_| ModelError::add_entry_error(moniker.clone(), name)) } } impl<'entries> AddableDirectory<'entries> for directory::controlled::Controlled<'entries> { fn add_node<Entry>( &mut self, name: &str, entry: Entry, moniker: &AbsoluteMoniker, ) -> Result<(), ModelError> where Entry: DirectoryEntry + 'entries, { self.add_entry(name, entry).map_err(|_| ModelError::add_entry_error(moniker.clone(), name)) } } impl<'entries> AddableDirectoryWithResult<'entries> for directory::controlled::Controller<'entries> { fn add_node<'a, Entry>( &'a self, name: &'a str, entry: Entry, moniker: &'a AbsoluteMoniker, ) -> BoxFuture<Result<(), ModelError>> where Entry: DirectoryEntry + 'entries, { Box::pin(async move { self.add_entry_res(String::from(name), entry) .await .map_err(|_| ModelError::add_entry_error(moniker.clone(), name)) }) } fn remove_node<'a>( &'a self, name: &'a str, ) -> BoxFuture<Result<Option<Box<dyn DirectoryEntry + 'entries>>, ModelError>> { Box::pin(async move { self.remove_entry_res(String::from(name)) .await .map_err(|_| ModelError::remove_entry_error(name)) }) } fn open_node<'a>( &'a self, flags: u32, mode: u32, path: Vec<String>, server_end: ServerEnd<NodeMarker>, moniker: &'a AbsoluteMoniker, ) -> BoxFuture<Result<(), ModelError>> { let relative_path = path.join("/"); Box::pin(async move { self.open(flags, mode, path, server_end) .await .map_err(|_| ModelError::open_directory_error(moniker.clone(), relative_path)) }) } }
use crate::{ASPECT_RATIO, HEIGHT, WIDTH}; use macroquad::prelude::*; /// Make a Color from an RRGGBBAA hex code. pub fn hexcolor(code: u32) -> Color { let [r, g, b, a] = code.to_be_bytes(); Color::from_rgba(r, g, b, a) } pub fn mouse_position_pixel() -> (f32, f32) { let (mx, my) = mouse_position(); let (wd, hd) = width_height_deficit(); let mx = (mx - wd / 2.0) / ((screen_width() - wd) / WIDTH); let my = (my - hd / 2.0) / ((screen_height() - hd) / HEIGHT); (mx, my) } pub fn width_height_deficit() -> (f32, f32) { if (screen_width() / screen_height()) > ASPECT_RATIO { // it's too wide! put bars on the sides! // the height becomes the authority on how wide to draw let expected_width = screen_height() * ASPECT_RATIO; (screen_width() - expected_width, 0.0f32) } else { // it's too tall! put bars on the ends! // the width is the authority let expected_height = screen_width() / ASPECT_RATIO; (0.0f32, screen_height() - expected_height) } }
use std::{ error::Error as StdError, fmt::{ Formatter, Result as FmtRes, Display }, sync::mpsc::{ RecvError }, num::ParseIntError as IError, }; use serde::{ Serialize, Serializer, ser::{ SerializeMap }, }; use serde_json::Error as JsonError; use amqp::AMQPError; use bincode; use postgres::Error as PError; use uuid::ParseError as UError; #[derive(Debug)] pub enum Error { Bin(bincode::Error), Json(JsonError), Mq(AMQPError), Other(String), Pg(PError), Recv(RecvError), Uuid(UError), U8(IError), } impl Error { pub fn new(msg: &str) -> Self { Error::Other(msg.to_owned()) } } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> FmtRes { match self { Error::Bin(e) => e.fmt(f), Error::Json(e) => e.fmt(f), Error::Mq(e) => e.fmt(f), Error::Other(msg) => msg.fmt(f), Error::Pg(e) => e.fmt(f), Error::Recv(e) => e.fmt(f), Error::Uuid(e) => e.fmt(f), Error::U8(e) => e.fmt(f), } } } impl StdError for Error { fn cause(&self) -> Option<&StdError> { match self { Error::Bin(ref e) => Some(e), Error::Json(ref e) => Some(e), Error::Mq(ref e) => Some(e), Error::Other(_) => None, Error::Pg(ref e) => Some(e), Error::Recv(ref e) => Some(e), Error::Uuid(ref e) => Some(e), Error::U8(ref e) => Some(e), } } } impl From<AMQPError> for Error { fn from(other: AMQPError) -> Self { Error::Mq(other) } } impl From<bincode::Error> for Error { fn from(other: bincode::Error) -> Self { Error::Bin(other) } } impl From<PError> for Error { fn from(other: PError) -> Self { Error::Pg(other) } } impl From<RecvError> for Error { fn from(other: RecvError) -> Self { Error::Recv(other) } } impl From<JsonError> for Error { fn from(other: JsonError) -> Self { Error::Json(other) } } impl From<UError> for Error { fn from(other: UError) -> Self { Error::Uuid(other) } } impl From<IError> for Error { fn from(other: IError) -> Self { Error::U8(other) } } impl Serialize for Error { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let mut map = serializer.serialize_map(Some(1))?; map.serialize_entry("message", &format!("{}", self))?; map.end() } }
use std::io; use std::io::prelude::*; fn main() { let mut input = String::new(); io::stdin().read_line(&mut input) .ok() .expect("read error"); let data = parse_input(input); render(&data); } fn parse_input(input: String) -> Vec<i32> { let numbers: Vec<i32> = input .split_whitespace() .map(|s| s.parse().ok().expect("Invalid data set")) .collect(); numbers } fn render(data: &Vec<i32>) { let mut height = data .iter() .fold(0, |x, &num| if num > x {num} else {x}); while height > -1 { let line = data.iter() .map(|n| if *n > height {"█ "} else {" "}) .collect::<String>(); println!("{}", line); height = height - 1; } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct GameServiceGameOutcome(pub i32); impl GameServiceGameOutcome { pub const None: Self = Self(0i32); pub const Win: Self = Self(1i32); pub const Loss: Self = Self(2i32); pub const Tie: Self = Self(3i32); } impl ::core::marker::Copy for GameServiceGameOutcome {} impl ::core::clone::Clone for GameServiceGameOutcome { fn clone(&self) -> Self { *self } } pub type GameServicePropertyCollection = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GameServiceScoreKind(pub i32); impl GameServiceScoreKind { pub const Number: Self = Self(0i32); pub const Time: Self = Self(1i32); } impl ::core::marker::Copy for GameServiceScoreKind {} impl ::core::clone::Clone for GameServiceScoreKind { fn clone(&self) -> Self { *self } }
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script_manager::ScriptManager; use super::options::Options; pub mod script_manager; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn before_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn input_event_hook( &mut self, _global_variables: &GlobalVariables, _event: Event, ) -> Option<Command>; fn after_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn output_event_hook( &mut self, _input: &str, _global_variables: &GlobalVariables, ) -> Option<Command>; fn list(&self) -> Option<String>; fn activate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn deactivate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn trigger_set_title_hook(&mut self) -> Option<String>; fn trigger_set_msg_hook(&mut self) -> Option<String>; fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; } // Scripts impl super::IRust { pub fn update_input_prompt(&mut self) { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.input_prompt(&self.global_variables) { self.printer.set_prompt(prompt); } } } pub fn get_output_prompt(&mut self) -> String { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.get_output_prompt(&self.global_variables) { return prompt; } } //Default self.options.output_prompt.clone() } pub fn before_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.before_compiling(&self.global_variables); } } pub fn input_event_hook(&mut self, event: Event) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.input_event_hook(&self.global_variables, event); } None } pub fn after_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.after_compiling(&self.global_variables); } } pub fn output_event_hook(&mut self, input: &str) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.output_event_hook(input, &self.global_variables); } None } pub fn trigger_set_title_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_title_hook(); } None } pub fn trigger_set_msg_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_msg_hook(); } None } pub fn scripts_list(&self) -> Option<String> { if let Some(ref script_mg) = self.script_mg { return script_mg.list(); } None } pub fn activate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.activate(script); } Ok(None) } pub fn deactivate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.deactivate(script); } Ok(None) } // internal /////////// /// pub fn choose_script_mg(options: &Options) -> Option<Box<dyn Script>> { if options.activate_scripting { ScriptManager::new().map(|script_mg| Box::new(script_mg) as Box<dyn Script>) } else { None } } pub fn update_script_state(&mut self) { self.global_variables.prompt_position = self.printer.cursor.starting_pos(); self.global_variables.cursor_position = self.printer.cursor.current_pos(); self.global_variables.is_racer_suggestion_active = self .racer .as_ref() .and_then(|r| r.active_suggestion.as_ref()) .is_some(); } pub fn run_scripts_startup_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.startup_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } pub fn run_scripts_shutdown_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.shutdown_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } }
pub fn main() { cc::Build::new() .files(&["softfp/softfp.c"]) .compile("softfp"); }
use amethyst::{ prelude::*, core::SystemDesc, derive::SystemDesc, input::{ InputHandler, VirtualKeyCode, StringBindings }, } #[derivce(SystemDesc)] struct GameSystem; impl<'s> System<'s> for GameSystem { type SystemData = Read<'s, InputHandler<StringBindings>>; fn run(&mut self, input: Self::SystemData) { if let Some((x,y)) = input. } } }
use crate::config; /// A clock mask. /// /// The format looks like this /// /// ``` /// 0b00000<1><0><2x> /// ``` /// /// Where /// /// * `1` is the value of the `SPR1` bit /// * `0` is the value of the `SPR0` bit /// * `2x` indicates if double speed mode is enabled #[derive(Copy, Clone)] pub struct ClockMask(pub u8); impl ClockMask { /// Gets the clock mask for a specific baute rate. pub fn with_clock(spi_clock: u32) -> ClockMask { let mut divider_bits = if spi_clock >= config::CPU_FREQUENCY_HZ / 2 { 0 } else if spi_clock >= config::CPU_FREQUENCY_HZ / 4 { 1 } else if spi_clock >= config::CPU_FREQUENCY_HZ / 8 { 2 } else if spi_clock >= config::CPU_FREQUENCY_HZ / 16 { 3 } else if spi_clock >= config::CPU_FREQUENCY_HZ / 32 { 4 } else if spi_clock >= config::CPU_FREQUENCY_HZ / 64 { 5 } else { 6 }; // Invert the SPI2X bit divider_bits ^= 0x1; // Compensate for the duplicate F_osc/64 if divider_bits == 6 { divider_bits = 7; } ClockMask(divider_bits) } pub fn control_register_mask(self) -> u8 { // SPR1 and SPR0 // These both form bits 1 and 0 of the control register. (self.0 & 0b110) >> 1 } pub fn status_register_mask(self) -> u8 { // SPI2x // This forms bit 0 of the status register. self.0 & 0b1 } }
// Copyright (c) 2016 The Rouille developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::str; use Request; use Response; // The AsciiExt import is needed for Rust older than 1.23.0. These two lines can // be removed when supporting older Rust is no longer needed. #[allow(unused_imports)] use std::ascii::AsciiExt; /// Applies content encoding to the response. /// /// Analyzes the `Accept-Encoding` header of the request. If one of the encodings is recognized and /// supported by rouille, it adds a `Content-Encoding` header to the `Response` and encodes its /// body. /// /// If the response already has a `Content-Encoding` header, this function is a no-op. /// If the response has a `Content-Type` header that isn't textual content, this function is a /// no-op. /// /// The gzip encoding is supported only if you enable the `gzip` feature of rouille (which is /// enabled by default). /// /// # Example /// /// ```rust /// use rouille::content_encoding; /// use rouille::Request; /// use rouille::Response; /// /// fn handle(request: &Request) -> Response { /// content_encoding::apply(request, Response::text("hello world")) /// } /// ``` pub fn apply(request: &Request, response: Response) -> Response { // Only text should be encoded. Otherwise just return. if !response_is_text(&response) { return response; } // If any of the response's headers is equal to `Content-Encoding`, ignore the function // call and return immediately. if response.headers.iter().any(|&(ref key, _)| key.eq_ignore_ascii_case("Content-Encoding")) { return response; } // Put the response in an Option for later. let mut response = Some(response); // Now let's get the list of content encodings accepted by the request. // The list should be ordered from the most desired to the list desired. // TODO: use input::priority_header_preferred instead for encoding in accepted_content_encodings(request) { // Try the brotli encoding. if brotli(encoding, &mut response) { return response.take().unwrap(); } // Try the gzip encoding. if gzip(encoding, &mut response) { return response.take().unwrap(); } // The identity encoding is always supported. if encoding.eq_ignore_ascii_case("identity") { return response.take().unwrap(); } } // No encoding accepted, don't do anything. response.take().unwrap() } // Returns true if the Content-Type of the response is a type that should be encoded. // Since encoding is purely an optimisation, it's not a problem if the function sometimes has // false positives or false negatives. fn response_is_text(response: &Response) -> bool { response.headers.iter().any(|&(ref key, ref value)| { if !key.eq_ignore_ascii_case("Content-Type") { return false; } // TODO: perform case-insensitive comparison value.starts_with("text/") || value.contains("javascript") || value.contains("json") || value.contains("xml") || value.contains("font") }) } /// Returns an iterator of the list of content encodings accepted by the request. /// /// # Example /// /// ``` /// use rouille::{Request, Response}; /// use rouille::content_encoding; /// /// fn handle(request: &Request) -> Response { /// for encoding in content_encoding::accepted_content_encodings(request) { /// // ... /// } /// /// // ... /// # panic!() /// } /// ``` pub fn accepted_content_encodings(request: &Request) -> AcceptedContentEncodingsIter { let elems = request.header("Accept-Encoding").unwrap_or("").split(','); AcceptedContentEncodingsIter { elements: elems } } /// Iterator to the list of content encodings accepted by a request. pub struct AcceptedContentEncodingsIter<'a> { elements: str::Split<'a, char> } impl<'a> Iterator for AcceptedContentEncodingsIter<'a> { type Item = &'a str; #[inline] fn next(&mut self) -> Option<&'a str> { loop { match self.elements.next() { None => return None, Some(e) => { let e = e.trim(); if !e.is_empty() { return Some(e); } } } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (_, max) = self.elements.size_hint(); (0, max) } } #[cfg(feature = "gzip")] fn gzip(e: &str, response: &mut Option<Response>) -> bool { use ResponseBody; use std::mem; use std::io; use deflate::deflate_bytes_gzip; if !e.eq_ignore_ascii_case("gzip") { return false; } let response = response.as_mut().unwrap(); response.headers.push(("Content-Encoding".into(), "gzip".into())); let previous_body = mem::replace(&mut response.data, ResponseBody::empty()); let (mut raw_data, size) = previous_body.into_reader_and_size(); let mut src = match size { Some(size) => Vec::with_capacity(size), None => Vec::new(), }; io::copy(&mut raw_data, &mut src).expect("Failed reading response body while gzipping"); let zipped = deflate_bytes_gzip(&src); response.data = ResponseBody::from_data(zipped); true } #[cfg(not(feature = "gzip"))] #[inline] fn gzip(e: &str, response: &mut Option<Response>) -> bool { false } #[cfg(feature = "brotli")] fn brotli(e: &str, response: &mut Option<Response>) -> bool { use ResponseBody; use std::mem; use brotli2::read::BrotliEncoder; if !e.eq_ignore_ascii_case("br") { return false; } let response = response.as_mut().unwrap(); response.headers.push(("Content-Encoding".into(), "br".into())); let previous_body = mem::replace(&mut response.data, ResponseBody::empty()); let (raw_data, _) = previous_body.into_reader_and_size(); response.data = ResponseBody::from_reader(BrotliEncoder::new(raw_data, 6)); true } #[cfg(not(feature = "brotli"))] #[inline] fn brotli(e: &str, response: &mut Option<Response>) -> bool { false } #[cfg(test)] mod tests { use Request; use content_encoding; #[test] fn no_req_encodings() { let request = Request::fake_http("GET", "/", vec![], vec![]); assert_eq!(content_encoding::accepted_content_encodings(&request).count(), 0); } #[test] fn empty_req_encodings() { let request = { let h = vec![("Accept-Encoding".to_owned(), "".to_owned())]; Request::fake_http("GET", "/", h, vec![]) }; assert_eq!(content_encoding::accepted_content_encodings(&request).count(), 0); } #[test] fn one_req_encoding() { let request = { let h = vec![("Accept-Encoding".to_owned(), "foo".to_owned())]; Request::fake_http("GET", "/", h, vec![]) }; let mut list = content_encoding::accepted_content_encodings(&request); assert_eq!(list.next().unwrap(), "foo"); assert_eq!(list.next(), None); } #[test] fn multi_req_encoding() { let request = { let h = vec![("Accept-Encoding".to_owned(), "foo, bar".to_owned())]; Request::fake_http("GET", "/", h, vec![]) }; let mut list = content_encoding::accepted_content_encodings(&request); assert_eq!(list.next().unwrap(), "foo"); assert_eq!(list.next().unwrap(), "bar"); assert_eq!(list.next(), None); } // TODO: more tests for encoding stuff }
pub mod standard;
// https://adventofcode.com/2018/day/4 use std::fs::File; use std::io::{BufRead, BufReader}; use chrono::prelude::*; use regex::Regex; use std::collections::HashMap; pub fn puzzle1() { let filename = "input/4.txt"; let file = File::open(filename).expect("There was a problem opening the file:"); let re = Regex::new(r"\[(\d*-\d*-\d* \d*:\d*)].*?(\w{5}) #?(\d{0,4})").unwrap(); let mut current_guard: u32 = 0; let mut start: DateTime<Utc> = Utc::now(); let mut times: HashMap<u32, i64> = HashMap::new(); let mut guards: HashMap<u32, HashMap<u32, u32>> = HashMap::new(); for line in BufReader::new(file).lines() { let line: String = line.expect("Reading line from buffer failed").parse().unwrap(); for cap in re.captures_iter(line.as_str()) { let date = Utc.datetime_from_str(&cap[1], "%Y-%m-%d %H:%M") .expect("Unable to parse datetime"); match &cap[2] { "Guard" => { current_guard = cap[3].parse().expect("Unable to parse guard id"); } "falls" => { start = date; } "wakes" => { let guard = guards.entry(current_guard).or_default(); for min in start.minute()..date.minute() { *guard.entry(min).or_default() += 1; } *times.entry(current_guard).or_default() += date.signed_duration_since(start) .num_seconds(); } _ => println!("Not matching format"), } } } let (guard_id, _) = times.iter().max_by_key(|x| x.1).unwrap(); let (minute, _) = guards.get(&guard_id).expect("").iter().max_by_key(|x| x.1).unwrap(); print!("Guard you chose multiplied by the minute you chose: {}", minute * guard_id); } pub fn puzzle2() { let filename = "input/4.txt"; let file = File::open(filename).expect("There was a problem opening the file:"); let re = Regex::new(r"\[(\d*-\d*-\d* \d*:\d*)].*?(\w{5}) #?(\d{0,4})").unwrap(); let mut current_guard: u32 = 0; let mut start: DateTime<Utc> = Utc::now(); let mut times: HashMap<u32, i64> = HashMap::new(); let mut guards: HashMap<u32, HashMap<u32, u32>> = HashMap::new(); for line in BufReader::new(file).lines() { let line: String = line.expect("Reading line from buffer failed").parse().unwrap(); for cap in re.captures_iter(line.as_str()) { let date = Utc.datetime_from_str(&cap[1], "%Y-%m-%d %H:%M") .expect("Unable to parse datetime"); match &cap[2] { "Guard" => { current_guard = cap[3].parse().expect("Unable to parse guard id"); } "falls" => { start = date; } "wakes" => { let guard = guards.entry(current_guard).or_default(); for min in start.minute()..date.minute() { *guard.entry(min).or_default() += 1; } *times.entry(current_guard).or_default() += date.signed_duration_since(start) .num_seconds(); } _ => println!("Not matching format"), } } } let mut guard_id: u32 = 0; let mut max_minute: u32 = 0; let mut max_count: u32 = 0; for guard in guards.iter() { for time in guard.1.iter() { if *time.1 > max_count { guard_id = *guard.0; max_minute = *time.0; max_count = *time.1; } } }; println!("Guard you chose multiplied by the minute you chose: {}", guard_id*max_minute); }
use json::json; use crate::authorize::ApplicationCredentials; /// Legacy function, allowing to generate short-lived tokens without using OAuth. #[allow(dead_code)] pub(crate) fn generate_token( endpoint: &str, creds: &ApplicationCredentials, ) -> Result<String, jwt::Error> { let current_time = chrono::Utc::now(); let max_age = chrono::Duration::seconds(3600); let header = json!({ "alg": "RS256", "typ": "JWT", "kid": creds.private_key_id.as_str(), }); let payload = json!({ "iss": creds.client_email.as_str(), "sub": creds.client_email.as_str(), "aud": endpoint, "iat": current_time.timestamp(), "exp": (current_time + max_age).timestamp(), }); let token = jwt::encode(header, &creds.private_key, &payload, jwt::Algorithm::RS256)?; Ok(token) }
use crate::matcher::WildcardMatcher; use crate::util; use std::net::IpAddr; #[derive(Debug, Clone)] pub struct IpMatcher { allow: Vec<MatchMode>, deny: Vec<MatchMode>, } #[derive(Debug, Clone)] enum MatchMode { Ip(IpAddr), Wildcard(WildcardMatcher), } impl MatchMode { fn new(s: &str) -> Result<Self, String> { if s.contains('*') { Ok(Self::Wildcard(WildcardMatcher::new(s))) } else { Ok(Self::Ip(util::to_ip_addr(s)?)) } } fn is_match(&self, ip: &IpAddr) -> bool { match self { MatchMode::Ip(m) => m == ip, MatchMode::Wildcard(m) => m.is_match(&ip.to_string()), } } } impl IpMatcher { pub fn new(allow: Vec<&str>, deny: Vec<&str>) -> Result<Self, String> { let mut a = vec![]; for item in allow { a.push(MatchMode::new(item)?); } let mut d = vec![]; for item in deny { d.push(MatchMode::new(item)?); } Ok(Self { allow: a, deny: d }) } pub fn is_pass(&self, ip: IpAddr) -> bool { if !self.allow.is_empty() { return self.allow.iter().any(|m| m.is_match(&ip)); } self.deny.iter().all(|m| !m.is_match(&ip)) } } #[cfg(test)] mod test { // use super::*; #[test] fn ip() {} }
use super::prelude::*; pub struct Counter { get: AtomicUsize, post: AtomicUsize, } impl Counter { pub fn new() -> Self { Self { get: AtomicUsize::new(0), post: AtomicUsize::new(0), } } } impl Fairing for Counter { fn info(&self) -> Info { Info { name: "GET/POST Requests Counter", kind: Kind::Request | Kind::Response, } } fn on_request(&self, request: &mut Request, _: &Data) { match request.method() { Method::Get => self.get.fetch_add(1, Ordering::Relaxed), Method::Post => self.post.fetch_add(1, Ordering::Relaxed), _ => return, }; } fn on_response(&self, request: &Request, response: &mut Response) { if response.status() != Status::NotFound { return; } if request.method() == Method::Get && request.uri().path() == "/counts" { let get_count = self.get.load(Ordering::Relaxed); let post_count = self.post.load(Ordering::Relaxed); let body = format!("Get: {}\nPost: {}", get_count, post_count); response.set_status(Status::Ok); response.set_header(ContentType::Plain); response.set_sized_body(Cursor::new(body)); } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use clap::{App, AppSettings, SubCommand, ArgMatches, Arg}; use alloc::string::String; use super::super::super::qlib::common::*; use super::super::cmd::config::*; use super::super::container::container::*; use super::command::*; #[derive(Debug)] pub struct WaitCmd { pub id: String, pub pid: i32, pub rootPid: i32, } impl WaitCmd { pub fn Init(cmd_matches: &ArgMatches) -> Result<Self> { let pidStr = cmd_matches.value_of("pid").unwrap().to_string(); let rootPidStr = cmd_matches.value_of("rootpid").unwrap().to_string(); let pid = match pidStr.parse::<i32>() { Err(_e) => return Err(Error::Common(format!("pid {} cant not be parsed as int type", pidStr))), Ok(v) => v, }; let rootPid = match rootPidStr.parse::<i32>() { Err(_e) => return Err(Error::Common(format!("root {} cant not be parsed as int type", rootPidStr))), Ok(v) => v, }; return Ok(Self { id: cmd_matches.value_of("id").unwrap().to_string(), pid: pid, rootPid: rootPid, }) } pub fn SubCommand<'a, 'b>(common: &CommonArgs<'a, 'b>) -> App<'a, 'b> { return SubCommand::with_name("wait") .setting(AppSettings::ColoredHelp) .arg(&common.id_arg) .arg( Arg::with_name("rootpid") .default_value("-1") .long("rootpid") .required(true) .takes_value(true) .help("Signal to send to container"), ) .arg( Arg::with_name("pid") .default_value("-1") .long("pid") .takes_value(true) .help("send the specified signal to a specific process"), ) .about("wait a container"); } pub fn Run(&self, gCfg: &GlobalConfig) -> Result<()> { info!("Container:: Wait ...."); let id = &self.id; let rootPid = self.rootPid; let pid = self.pid; if rootPid != -1 && pid != -1 { panic!("only one of -pid and -rootPid can be set") } let mut container = Container::Load(&gCfg.RootDir, id)?; let res; if rootPid == -1 && pid == -1 { res = container.Wait()?; } else if rootPid != -1 { res = container.WaitRootPID(rootPid, true)?; } else { //pid != -1 res = container.WaitPid(pid, true)?; } let ret = waitResult { id: id.to_string(), exitStatus: res, }; println!("{:?}", ret); return Ok(()) } } #[derive(Debug)] pub struct waitResult { pub id: String, pub exitStatus: u32, }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::chain::BlockChain; use actix::prelude::*; use anyhow::{format_err, Error, Result}; use bus::{Broadcast, BusActor}; use config::NodeConfig; use crypto::HashValue; use logger::prelude::*; use network::{get_unix_ts, NetworkAsyncService}; use network_api::NetworkService; use parking_lot::RwLock; use starcoin_statedb::ChainStateDB; use starcoin_sync_api::SyncMetadata; use starcoin_txpool_api::TxPoolAsyncService; use std::collections::HashMap; use std::sync::Arc; use storage::Store; use traits::Consensus; use traits::{is_ok, ChainReader, ChainService, ChainWriter, ConnectBlockError, ConnectResult}; use types::{ account_address::AccountAddress, block::{Block, BlockDetail, BlockHeader, BlockInfo, BlockNumber, BlockTemplate}, startup_info::{ChainInfo, StartupInfo}, system_events::SystemEvents, transaction::{SignedUserTransaction, TransactionInfo}, }; pub struct BlockChainCollection<C, S, P> where C: Consensus, P: TxPoolAsyncService + 'static, S: Store + 'static, { master: RwLock<Vec<BlockChain<C, S, P>>>, branches: RwLock<HashMap<HashValue, BlockChain<C, S, P>>>, } impl<C, S, P> Drop for BlockChainCollection<C, S, P> where C: Consensus, P: TxPoolAsyncService + 'static, S: Store + 'static, { fn drop(&mut self) { debug!("drop BlockChainCollection"); &self.master.write().pop(); self.branches.write().clear(); } } impl<C, S, P> BlockChainCollection<C, S, P> where C: Consensus, P: TxPoolAsyncService + 'static, S: Store + 'static, { pub fn new() -> Self { BlockChainCollection { master: RwLock::new(Vec::new()), branches: RwLock::new(HashMap::new()), } } pub fn insert_branch(&self, branch: BlockChain<C, S, P>) { self.branches .write() .insert(branch.get_chain_info().branch_id(), branch); } pub fn update_master(&self, new_master: BlockChain<C, S, P>) { self.master.write().insert(0, new_master) } pub fn get_branch_id(&self, branch_id: &HashValue, number: BlockNumber) -> Option<HashValue> { let mut chain_info = None; let master = self .master .read() .get(0) .expect("master is none.") .get_chain_info(); if master.branch_id() == branch_id.clone() { chain_info = Some(master) } else { for branch in self.branches.read().values() { if branch.get_chain_info().branch_id() == branch_id.clone() { chain_info = Some(branch.get_chain_info()); break; } } } if let Some(tmp) = chain_info { if number >= tmp.start_number() { return Some(tmp.branch_id()); } else { if let Some(parent_branch) = tmp.parent_branch() { return self.get_branch_id(&parent_branch, number); } } } return None; } pub fn remove_branch(&self, branch_id: &HashValue) { self.branches.write().remove(branch_id); } pub fn fork(&self, block_header: &BlockHeader) -> Option<ChainInfo> { let mut chain_info = self .master .read() .get(0) .expect("master is none.") .fork(block_header); if chain_info.is_none() { for branch in self.branches.read().values() { chain_info = branch.fork(block_header); if chain_info.is_some() { break; } } } chain_info } pub fn block_exist(&self, block_id: HashValue) -> bool { let mut exist = self .master .read() .get(0) .expect("master is none.") .exist_block(block_id); if !exist { for branch in self.branches.read().values() { exist = branch.exist_block(block_id); if exist { break; } } } exist } pub fn create_block_template( &self, author: AccountAddress, auth_key_prefix: Option<Vec<u8>>, block_id: HashValue, user_txns: Vec<SignedUserTransaction>, ) -> Result<BlockTemplate> { if self .master .read() .get(0) .expect("master is none.") .exist_block(block_id) { self.master .read() .get(0) .expect("master is none.") .create_block_template(author, auth_key_prefix, Some(block_id), user_txns) } else { // just for test let mut tmp = None; for branch in self.branches.read().values() { if branch.exist_block(block_id) { tmp = Some(branch.create_block_template( author, auth_key_prefix.clone(), Some(block_id), user_txns.clone(), )); } } Ok(tmp.unwrap().unwrap()) } } pub fn to_startup_info(&self) -> StartupInfo { let head = self .master .read() .get(0) .expect("master is none.") .get_chain_info(); let mut branches = Vec::new(); for branch in self.branches.read().values() { branches.push(branch.get_chain_info()); } StartupInfo::new(head, branches) } pub fn get_master_chain_info(&self) -> ChainInfo { self.master.read().get(0).unwrap().get_chain_info() } } pub struct ChainServiceImpl<C, S, P> where C: Consensus, P: TxPoolAsyncService + 'static, S: Store + 'static, { config: Arc<NodeConfig>, collection: Arc<BlockChainCollection<C, S, P>>, storage: Arc<S>, network: Option<NetworkAsyncService>, txpool: P, bus: Addr<BusActor>, sync_metadata: SyncMetadata, } impl<C, S, P> ChainServiceImpl<C, S, P> where C: Consensus, P: TxPoolAsyncService + 'static, S: Store + 'static, { pub fn new( config: Arc<NodeConfig>, startup_info: StartupInfo, storage: Arc<S>, network: Option<NetworkAsyncService>, txpool: P, bus: Addr<BusActor>, sync_metadata: SyncMetadata, ) -> Result<Self> { let collection = to_block_chain_collection( config.clone(), startup_info, storage.clone(), txpool.clone(), )?; Ok(Self { config, collection, storage, network, txpool, bus, sync_metadata, }) } pub fn find_or_fork( &mut self, header: &BlockHeader, ) -> Result<(bool, Option<BlockChain<C, S, P>>)> { debug!("{:?}:{:?}", header.parent_hash(), header.id()); let chain_info = self.collection.fork(header); if chain_info.is_some() { let block_exist = self.collection.block_exist(header.id()); let branch = BlockChain::new( self.config.clone(), chain_info.unwrap(), self.storage.clone(), self.txpool.clone(), Arc::downgrade(&self.collection), )?; Ok((block_exist, Some(branch))) } else { Ok((false, None)) } } pub fn state_at(&self, _root: HashValue) -> ChainStateDB { unimplemented!() } fn select_head(&mut self, new_branch: BlockChain<C, S, P>) -> Result<()> { let block = new_branch.head_block(); let total_difficulty = new_branch.get_total_difficulty()?; if total_difficulty > self .collection .master .read() .get(0) .expect("master is none.") .get_total_difficulty()? { let mut enacted: Vec<SignedUserTransaction> = Vec::new(); let mut retracted = Vec::new(); let mut rollback = false; if new_branch.get_chain_info().branch_id() == self .collection .master .read() .get(0) .expect("master is none.") .get_chain_info() .branch_id() { enacted.append(&mut block.transactions().clone().to_vec()); } else { debug!("rollback branch."); self.collection.insert_branch(BlockChain::new( self.config.clone(), self.collection .master .read() .get(0) .expect("master is none.") .get_chain_info(), self.storage.clone(), self.txpool.clone(), Arc::downgrade(&self.collection), )?); rollback = true; } let _ = self .collection .remove_branch(&new_branch.get_chain_info().branch_id()); self.collection.update_master(BlockChain::new( self.config.clone(), new_branch.get_chain_info(), self.storage.clone(), self.txpool.clone(), Arc::downgrade(&self.collection), )?); if rollback { let (mut enacted_tmp, mut retracted_tmp) = self.find_ancestors(&new_branch)?; enacted.append(&mut enacted_tmp); retracted.append(&mut retracted_tmp); } self.commit_2_txpool(enacted, retracted); if self.sync_metadata.is_sync_done() { let block_detail = BlockDetail::new(block, total_difficulty); self.broadcast_2_bus(block_detail.clone()); self.broadcast_2_network(block_detail); } } else { self.collection.insert_branch(new_branch); } self.save_startup() } fn save_startup(&self) -> Result<()> { let startup_info = self.collection.to_startup_info(); debug!("save startup info : {:?}", startup_info); self.storage.save_startup_info(startup_info) } fn commit_2_txpool( &self, enacted: Vec<SignedUserTransaction>, retracted: Vec<SignedUserTransaction>, ) { let txpool = self.txpool.clone(); Arbiter::spawn(async move { if let Err(e) = txpool.rollback(enacted, retracted).await { warn!("rollback err : {:?}", e); } }); } fn find_ancestors( &self, new_branch: &BlockChain<C, S, P>, ) -> Result<(Vec<SignedUserTransaction>, Vec<SignedUserTransaction>)> { let mut enacted: Vec<Block> = Vec::new(); let mut retracted: Vec<Block> = Vec::new(); let block_enacted = &new_branch.current_header().id(); let block_retracted = &self .collection .master .read() .get(0) .expect("master is none.") .current_header() .id(); let ancestor = self .storage .get_common_ancestor(block_enacted.clone(), block_retracted.clone())? .unwrap(); let mut block_enacted_tmp = block_enacted.clone(); debug!("ancestor block is : {:?}", ancestor); loop { if block_enacted_tmp == ancestor { break; }; debug!("get block 1 {:?}.", block_enacted_tmp); let block_tmp = new_branch .get_block(block_enacted_tmp.clone()) .unwrap() .expect("block is none 1."); block_enacted_tmp = block_tmp.header().parent_hash(); enacted.push(block_tmp); } let mut block_retracted_tmp = block_retracted.clone(); loop { if block_retracted_tmp == ancestor { break; }; debug!("get block 2 {:?}.", block_retracted_tmp); let block_tmp = self .collection .master .read() .get(0) .expect("master is none.") .get_block(block_retracted_tmp)? .expect("block is none 2."); block_retracted_tmp = block_tmp.header().parent_hash(); retracted.push(block_tmp); } retracted.reverse(); enacted.reverse(); let mut tx_enacted: Vec<SignedUserTransaction> = Vec::new(); let mut tx_retracted: Vec<SignedUserTransaction> = Vec::new(); enacted.iter().for_each(|b| { tx_enacted.append(&mut b.transactions().clone().to_vec()); }); retracted.iter().for_each(|b| { tx_retracted.append(&mut b.transactions().clone().to_vec()); }); debug!( "commit size:{}, rollback size:{}", tx_enacted.len(), tx_retracted.len() ); Ok((tx_enacted, tx_retracted)) } pub fn broadcast_2_bus(&self, block: BlockDetail) { let bus = self.bus.clone(); Arbiter::spawn(async move { let _ = bus .send(Broadcast { msg: SystemEvents::NewHeadBlock(block), }) .await; }); } pub fn broadcast_2_network(&self, block: BlockDetail) { if let Some(network) = self.network.clone() { Arbiter::spawn(async move { debug!("broadcast system event : {:?}", block.header().id()); network .broadcast_system_event(SystemEvents::NewHeadBlock(block)) .await .expect("broadcast new head block failed."); }); }; } } impl<C, S, P> ChainService for ChainServiceImpl<C, S, P> where C: Consensus, P: TxPoolAsyncService, S: Store, { //TODO define connect result. fn try_connect(&mut self, block: Block, pivot_sync: bool) -> Result<ConnectResult<()>> { let connect_begin_time = get_unix_ts(); if !self.sync_metadata.state_syncing() || pivot_sync { if !self.sync_metadata.state_syncing() || (pivot_sync && self.sync_metadata.state_done()) { let (block_exist, fork) = self.find_or_fork(block.header())?; if block_exist { Ok(ConnectResult::Err(ConnectBlockError::DuplicateConn)) } else { if let Some(mut branch) = fork { let fork_end_time = get_unix_ts(); debug!("fork used time: {}", (fork_end_time - connect_begin_time)); let connected = branch.apply(block.clone())?; let apply_end_time = get_unix_ts(); debug!("apply used time: {}", (apply_end_time - fork_end_time)); if !connected { Ok(ConnectResult::Err(ConnectBlockError::VerifyFailed)) } else { self.select_head(branch)?; let select_head_end_time = get_unix_ts(); debug!( "select head used time: {}", (select_head_end_time - apply_end_time) ); self.collection .master .read() .get(0) .expect("master is none.") .latest_blocks(10); Ok(ConnectResult::Ok(())) } } else { Ok(ConnectResult::Err(ConnectBlockError::FutureBlock)) } } } else { Ok(ConnectResult::Err(ConnectBlockError::FutureBlock)) } } else { Ok(ConnectResult::Err(ConnectBlockError::Other( "error connect type.".to_string(), ))) } } fn try_connect_with_block_info( &mut self, block: Block, block_info: BlockInfo, ) -> Result<ConnectResult<()>> { if self.sync_metadata.state_syncing() { let pivot = self.sync_metadata.get_pivot()?; let latest_sync_number = self.sync_metadata.get_latest(); if pivot.is_some() && latest_sync_number.is_some() { let pivot_number = pivot.unwrap(); let latest_number = latest_sync_number.unwrap(); let current_block_number = block.header().number(); if pivot_number >= current_block_number { //todo:1. verify block header / verify accumulator / total difficulty let (block_exist, fork) = self.find_or_fork(block.header())?; if block_exist { Ok(ConnectResult::Err(ConnectBlockError::DuplicateConn)) } else { if let Some(mut branch) = fork { if let Ok(_) = C::verify_header(self.config.clone(), &branch, block.header()) { // 2. commit block branch.commit(block, block_info)?; self.select_head(branch)?; Ok(ConnectResult::Ok(())) } else { Ok(ConnectResult::Err(ConnectBlockError::VerifyFailed)) } } else { Ok(ConnectResult::Err(ConnectBlockError::FutureBlock)) } } } else if latest_number >= current_block_number { let connect_result = self.try_connect(block, true)?; // 3. update sync metadata info!( "connect block : {}, {}, {:?}", latest_number, current_block_number, connect_result ); if latest_number == current_block_number && is_ok(&connect_result) { if let Err(err) = self.sync_metadata.block_sync_done() { warn!("err:{:?}", err); } } Ok(connect_result) } else { Ok(ConnectResult::Err(ConnectBlockError::Other( "block number > pivot.".to_string(), ))) } } else { Ok(ConnectResult::Err(ConnectBlockError::Other( "pivot is none.".to_string(), ))) } } else { self.try_connect(block, false) } } fn master_head_block(&self) -> Block { self.collection .master .read() .get(0) .expect("master is none.") .head_block() } fn master_head_header(&self) -> BlockHeader { self.collection .master .read() .get(0) .expect("master is none.") .current_header() } fn get_header_by_hash(&self, hash: HashValue) -> Result<Option<BlockHeader>> { self.storage.get_block_header_by_hash(hash) } fn master_block_by_number(&self, number: u64) -> Result<Option<Block>> { self.collection .master .read() .get(0) .expect("master is none.") .get_block_by_number(number) } fn get_block_by_hash(&self, hash: HashValue) -> Result<Option<Block>> { self.storage.get_block_by_hash(hash) } fn get_block_info_by_hash(&self, hash: HashValue) -> Result<Option<BlockInfo>> { self.storage.get_block_info(hash) } fn create_block_template( &self, author: AccountAddress, auth_key_prefix: Option<Vec<u8>>, parent_hash: Option<HashValue>, user_txns: Vec<SignedUserTransaction>, ) -> Result<BlockTemplate> { let block_id = match parent_hash { Some(hash) => hash, None => self .collection .master .read() .get(0) .expect("master is none.") .current_header() .id(), }; if let Ok(Some(_)) = self.get_block_by_hash(block_id) { self.collection .create_block_template(author, auth_key_prefix, block_id, user_txns) } else { Err(format_err!("Block {:?} not exist.", block_id)) } } fn gen_tx(&self) -> Result<()> { self.collection .master .read() .get(0) .expect("master is none.") .gen_tx() } fn master_startup_info(&self) -> StartupInfo { self.collection.to_startup_info() } fn master_blocks_by_number(&self, number: u64, count: u64) -> Result<Vec<Block>> { self.collection .master .read() .get(0) .expect("master is none.") .get_blocks_by_number(number, count) } fn get_transaction(&self, hash: HashValue) -> Result<Option<TransactionInfo>, Error> { self.collection .master .read() .get(0) .expect("master is none.") .get_transaction_info(hash) } fn get_block_txn_ids(&self, block_id: HashValue) -> Result<Vec<TransactionInfo>, Error> { self.collection .master .read() .get(0) .expect("master is none.") .get_block_transactions(block_id) } } pub fn to_block_chain_collection<C, S, P>( config: Arc<NodeConfig>, startup_info: StartupInfo, storage: Arc<S>, txpool: P, ) -> Result<Arc<BlockChainCollection<C, S, P>>> where C: Consensus, P: TxPoolAsyncService + 'static, S: Store + 'static, { let collection = Arc::new(BlockChainCollection::new()); let master = BlockChain::new( config.clone(), startup_info.master, storage.clone(), txpool.clone(), Arc::downgrade(&collection), )?; collection.update_master(master); for branch_info in startup_info.branches { collection.insert_branch(BlockChain::new( config.clone(), branch_info, storage.clone(), txpool.clone(), Arc::downgrade(&collection), )?); } Ok(collection) }
use std::io::{self, BufRead}; struct Scanner { depth: u32, range: u32, } impl Scanner { fn hits(&self) -> bool { self.depth % self.period() == 0 } fn period(&self) -> u32 { 2 * self.range - 2 } fn severity(&self) -> u32 { self.depth * self.range } } fn get_input() -> Vec<Scanner> { let stdin = io::stdin(); let stdin = stdin.lock(); let result = stdin.lines() .map(|l| { let l = l.expect("could not read stdin"); let mut ints = l.split(':').map(|s| s.trim().parse().expect("could not parse integer")); Scanner {depth: ints.next().expect("missing depth"), range: ints.next().expect("missing range")} }) .collect(); result } fn solve(data: &[Scanner]) -> u32 { data.iter().filter(|s| s.hits()).fold(0, |sum, s| sum + s.severity()) } fn main() { let data = get_input(); let result = solve(&data); println!("Solution: {}", result); }
use crate::{ HistogramObservation, MakeMetricObserver, MetricKind, MetricObserver, Observation, ObservationBucket, }; use parking_lot::Mutex; use std::sync::Arc; /// Determines the bucketing used by the `U64Histogram` #[derive(Debug, Clone)] pub struct U64HistogramOptions { buckets: Vec<u64>, } impl U64HistogramOptions { /// Create a new `U64HistogramOptions` with a list of thresholds to delimit the buckets pub fn new(thresholds: impl IntoIterator<Item = u64>) -> Self { let mut buckets: Vec<_> = thresholds.into_iter().collect(); buckets.sort_unstable(); Self { buckets } } } /// A `U64Histogram` provides bucketed observations of u64 values /// /// This provides insight into the distribution of values beyond a simple count or total #[derive(Debug, Clone)] pub struct U64Histogram { shared: Arc<Mutex<HistogramObservation<u64>>>, } impl U64Histogram { pub(crate) fn new(sorted_buckets: impl Iterator<Item = u64>) -> Self { let buckets = sorted_buckets .map(|le| ObservationBucket { le, count: Default::default(), }) .collect(); Self { shared: Arc::new(Mutex::new(HistogramObservation { total: Default::default(), buckets, })), } } pub fn fetch(&self) -> HistogramObservation<u64> { self.shared.lock().clone() } pub fn record(&self, value: u64) { self.record_multiple(value, 1) } pub fn record_multiple(&self, value: u64, count: u64) { let mut state = self.shared.lock(); if let Some(bucket) = state .buckets .iter_mut() .find(|bucket| value <= bucket.le) .as_mut() { bucket.count = bucket.count.wrapping_add(count); state.total = state.total.wrapping_add(value * count); } } } impl MakeMetricObserver for U64Histogram { type Options = U64HistogramOptions; fn create(options: &U64HistogramOptions) -> Self { Self::new(options.buckets.iter().cloned()) } } impl MetricObserver for U64Histogram { type Recorder = Self; fn kind() -> MetricKind { MetricKind::U64Histogram } fn recorder(&self) -> Self::Recorder { self.clone() } fn observe(&self) -> Observation { Observation::U64Histogram(self.fetch()) } } /// A concise helper to assert the value of a metric histogram, regardless of underlying type. #[macro_export] macro_rules! assert_histogram { ( $metrics:ident, $hist:ty, $name:expr, $(labels = $attr:expr,)* $(samples = $samples:expr,)* $(sum = $sum:expr,)* ) => { // Default to an empty set of attributes if not specified. #[allow(unused)] let mut attr = None; $(attr = Some($attr);)* let attr = attr.unwrap_or_else(|| metric::Attributes::from(&[])); let hist = $metrics .get_instrument::<metric::Metric<$hist>>($name) .expect("failed to find metric with provided name") .get_observer(&attr) .expect("failed to find metric with provided attributes") .fetch(); $(assert_eq!(hist.sample_count(), $samples, "sample count mismatch");)* $(assert_eq!(hist.total, $sum, "sum value mismatch");)* }; } #[cfg(test)] mod tests { use super::*; use crate::HistogramObservation; #[test] fn test_histogram() { let buckets = [20, 40, 50]; let options = U64HistogramOptions::new(buckets); let histogram = U64Histogram::create(&options); let buckets = |expected: &[u64; 3], total: u64| -> Observation { Observation::U64Histogram(HistogramObservation { total, buckets: expected .iter() .cloned() .zip(buckets) .map(|(count, le)| ObservationBucket { le, count }) .collect(), }) }; assert_eq!(histogram.observe(), buckets(&[0, 0, 0], 0)); histogram.record(30); assert_eq!(histogram.observe(), buckets(&[0, 1, 0], 30)); histogram.record(50); assert_eq!(histogram.observe(), buckets(&[0, 1, 1], 80)); histogram.record(51); // Exceeds max bucket - ignored assert_eq!(histogram.observe(), buckets(&[0, 1, 1], 80)); histogram.record(0); histogram.record(0); assert_eq!(histogram.observe(), buckets(&[2, 1, 1], 80)); } }
use std::collections::HashMap; pub fn run(path: &str) { let input = std::fs::read_to_string(path).expect("Couldn't read data file."); let part_1_solution = react(&input); println!("day 5, part 1: {:?}", part_1_solution.len()); let part_2_solution = part_2(&input); println!("day 5, part 2: {:?}", part_2_solution); } fn units_react(c1: char, c2: char) -> bool { c1.to_ascii_lowercase() == c2.to_ascii_lowercase() && c1 != c2 } fn react(polymer: &str) -> String { let mut out = String::new(); let mut last_c = None; for c2 in polymer.chars() { match last_c { None => last_c = Some(c2), Some(c1) => { if units_react(c1, c2) { // Discard c1 and c2, and go back one char last_c = out.pop(); } else { out.push(c1); last_c = Some(c2); } } } } if let Some(c1) = last_c { out.push(c1); } out } fn part_2(polymer: &str) -> Option<(char, usize)> { let mut map: HashMap<char, usize> = HashMap::new(); let chars = "abcdefghijklmnopqrstuvwxyz"; for c in chars.chars() { let input = polymer.replace(c, "").replace(c.to_ascii_uppercase(), ""); let result = react(&input); map.insert(c, result.len()); } let ans = map .iter() .min_by(|(_, v1), (_, v2)| v1.cmp(v2)) .map(|(&c, &len)| (c, len)); ans } #[cfg(test)] mod test { use super::*; #[test] fn test_react() { assert_eq!(react("aA"), "".to_string()); assert_eq!(react("abBA"), "".to_string()); assert_eq!(react("abAB"), "abAB".to_string()); assert_eq!(react("aabAAB"), "aabAAB".to_string()); assert_eq!(react("dabAcCaCBAcCcaDA"), "dabCBAcaDA".to_string()); } #[test] fn test_part2() { assert_eq!(part_2("dabAcCaCBAcCcaDA"), Some(('c', 4))); } }
//! # Deadpool for SQLite [![Latest Version](https://img.shields.io/crates/v/deadpool-sqlite.svg)](https://crates.io/crates/deadpool-sqlite) //! //! Deadpool is a dead simple async pool for connections and objects //! of any type. //! //! This crate implements a [`deadpool`](https://crates.io/crates/deadpool) //! manager for [`rusqlite`](https://crates.io/crates/rusqlite) //! and provides a wrapper that ensures correct use of the connection //! inside a separate thread. //! //! ## Features //! //! | Feature | Description | Extra dependencies | Default | //! | ------- | ----------- | ------------------ | ------- | //! | `config` | Enable support for [config](https://crates.io/crates/config) crate | `config`, `serde/derive` | yes | //! | `rt_tokio_1` | Enable support for [tokio](https://crates.io/crates/tokio) crate | `deadpool/rt_tokio_1` | yes | //! | `rt_async-std_1` | Enable support for [async-std](https://crates.io/crates/config) crate | `deadpool/rt_async-std_1` | no | //! //! ## Example //! //! ```rust //! use deadpool_sqlite::{Config, Runtime}; //! //! #[tokio::main] //! async fn main() { //! let mut cfg = Config::new("db.sqlite3"); //! let pool = cfg.create_pool(Runtime::Tokio1).unwrap(); //! let conn = pool.get().await.unwrap(); //! let result: i64 = conn //! .interact(|conn| { //! let mut stmt = conn.prepare("SELECT 1")?; //! let mut rows = stmt.query([])?; //! let row = rows.next()?.unwrap(); //! row.get(0) //! }) //! .await //! .unwrap(); //! assert_eq!(result, 1); //! } //! ``` //! //! ## License //! //! Licensed under either of //! //! - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) //! - MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) //! //! at your option. #![warn(missing_docs, unreachable_pub)] use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use deadpool::managed::sync::SyncWrapper; use deadpool::managed::RecycleError; use rusqlite::Error; mod config; pub use config::Config; pub use deadpool::managed::sync::InteractError; pub use deadpool::managed::PoolConfig; pub use deadpool::Runtime; /// A type alias for using `deadpool::Pool` with `rusqlite` pub type Pool = deadpool::managed::Pool<Manager>; /// A type alias for using `deadpool::PoolError` with `rusqlite` pub type PoolError = deadpool::managed::PoolError<Error>; /// A type alias for using `deadpool::Object` with `rusqlite` pub type Connection = deadpool::managed::Object<Manager>; /// The manager for creating and recyling SQLite connections pub struct Manager { config: Config, recycle_count: AtomicUsize, runtime: Runtime, } impl Manager { /// Create manager using a `deadpool_sqlite::Config` pub fn from_config(config: &Config, runtime: Runtime) -> Self { Self { config: config.clone(), recycle_count: AtomicUsize::new(0), runtime, } } } #[async_trait::async_trait] impl deadpool::managed::Manager for Manager { type Type = SyncWrapper<rusqlite::Connection, rusqlite::Error>; type Error = Error; async fn create(&self) -> Result<Self::Type, Self::Error> { let path = self.config.path.clone(); SyncWrapper::new(self.runtime.clone(), move || { rusqlite::Connection::open(path) }) .await } async fn recycle( &self, conn: &mut Self::Type, ) -> deadpool::managed::RecycleResult<Self::Error> { if conn.is_mutex_poisoned() { return Err(RecycleError::Message( "Mutex is poisoned. Connection is considered unusable.".to_string(), )); } let recycle_count = self.recycle_count.fetch_add(1, Ordering::Relaxed); let n: usize = conn .interact(move |conn| conn.query_row("SELECT $1", [recycle_count], |row| row.get(0))) .await .map_err(|e| RecycleError::Message(format!("{}", e)))?; if n == recycle_count { Ok(()) } else { Err(RecycleError::Message(String::from( "Recycle count mismatch", ))) } } }
#[derive(Clone,Copy,Debug)] struct Match { offset: isize, length: usize, } #[derive(Clone,Debug)] pub struct Encoder<'a> { data: &'a [u8], buffer: Vec<u8>, control_byte_idx: usize, control_byte_bit: u32, } impl<'a> Encoder<'a> { pub fn new(data: &[u8]) -> Encoder { Encoder { data: data, buffer: Vec::new(), control_byte_idx: 0, control_byte_bit: 8, } } pub fn encode(mut self) -> Vec<u8> { let mut encode_idx = 0; while encode_idx < self.data.len() { let bytes_encoded; let best_match_opt = self.get_best_match(encode_idx); if let Some(best_match) = best_match_opt { if best_match.length <= 5 && best_match.offset > -0x100 { self.encode_shortcopy(best_match); } else { self.encode_longcopy(best_match); } bytes_encoded = best_match.length; } else { let byte = self.data[encode_idx]; self.encode_literal(byte); bytes_encoded = 1; } encode_idx += bytes_encoded; } self.encode_finish(); self.buffer } fn get_best_match(&self, idx: usize) -> Option<Match> { let mut best_match: Option<Match> = None; let mut search_idx = if idx < 0x1FFF { 0 } else { idx - 0x1FFF }; while search_idx < idx { let mut match_len = 0; while idx + match_len < self.data.len() && match_len < 0x100 && self.data[search_idx + match_len] == self.data[idx + match_len] { match_len += 1; } if match_len >= 3 && (best_match.is_none() || best_match.unwrap().length < match_len) { best_match = Some( Match { offset: search_idx as isize - idx as isize, length: match_len, } ) } search_idx += 1; } best_match } fn encode_literal(&mut self, literal: u8) { self.encode_control(1); self.buffer.push(literal); } fn encode_shortcopy(&mut self, best_match: Match) { assert!(best_match.length >= 2 && best_match.length < 6); assert!(best_match.offset >= -0x100 && best_match.offset < 0); self.encode_control(0); self.encode_control(0); self.encode_control((((best_match.length - 2) >> 1) & 1) as u32); self.encode_control(((best_match.length - 2) & 1) as u32); self.buffer.push(best_match.offset as u8); } fn encode_longcopy(&mut self, best_match: Match) { assert!(best_match.length >= 3 && best_match.length < 0x101); assert!(best_match.offset >= -0x1FFF && best_match.offset < 0); self.encode_control(0); self.encode_control(1); if best_match.length > 9 { self.buffer.push((best_match.offset << 3) as u8); self.buffer.push((best_match.offset >> 5) as u8); self.buffer.push((best_match.length - 1) as u8); } else { self.buffer.push((best_match.offset << 3) as u8 | (best_match.length - 2) as u8); self.buffer.push((best_match.offset >> 5) as u8); } } fn encode_finish(&mut self) { self.encode_control(0); self.encode_control(1); self.buffer.push(0); self.buffer.push(0); } fn encode_control(&mut self, bit: u32) { assert!(bit < 2); // If control byte is filled, make a new one if self.control_byte_bit == 8 { // Reset control byte index self.control_byte_idx = self.buffer.len(); // Push an empty control byte self.buffer.push(0); // Reset current bit self.control_byte_bit = 0; } // Push new bit let control_byte = self.buffer.get_mut(self.control_byte_idx).unwrap(); *control_byte |= (bit as u8) << self.control_byte_bit; self.control_byte_bit += 1; } }
use crate::error::UnexpectedNullError; use crate::postgres::{PgTypeInfo, Postgres}; use crate::value::RawValue; use std::str::from_utf8; #[derive(Debug, Copy, Clone)] pub enum PgData<'c> { Binary(&'c [u8]), Text(&'c str), } #[derive(Debug)] pub struct PgValue<'c> { type_info: Option<PgTypeInfo>, data: Option<PgData<'c>>, } impl<'c> PgValue<'c> { /// Gets the binary or text data for this value; or, `UnexpectedNullError` if this /// is a `NULL` value. pub(crate) fn try_get(&self) -> crate::Result<PgData<'c>> { match self.data { Some(data) => Ok(data), None => Err(crate::Error::decode(UnexpectedNullError)), } } /// Gets the binary or text data for this value; or, `None` if this /// is a `NULL` value. #[inline] pub fn get(&self) -> Option<PgData<'c>> { self.data } pub(crate) fn null() -> Self { Self { type_info: None, data: None, } } pub(crate) fn bytes(type_info: PgTypeInfo, buf: &'c [u8]) -> Self { Self { type_info: Some(type_info), data: Some(PgData::Binary(buf)), } } pub(crate) fn utf8(type_info: PgTypeInfo, buf: &'c [u8]) -> crate::Result<Self> { Ok(Self { type_info: Some(type_info), data: Some(PgData::Text(from_utf8(&buf).map_err(crate::Error::decode)?)), }) } #[cfg(test)] pub(crate) fn from_bytes(buf: &'c [u8]) -> Self { Self { type_info: None, data: Some(PgData::Binary(buf)), } } pub(crate) fn from_str(s: &'c str) -> Self { Self { type_info: None, data: Some(PgData::Text(s)), } } } impl<'c> RawValue<'c> for PgValue<'c> { type Database = Postgres; // The public type_info is used for type compatibility checks fn type_info(&self) -> Option<PgTypeInfo> { // For TEXT encoding the type defined on the value is unreliable if matches!(self.data, Some(PgData::Binary(_))) { self.type_info.clone() } else { None } } }
use std::io; struct Menu { list_menu: Vec<String>, answer: i32, } impl Menu { fn show_menu(&mut self) { print!("{}[2J", 27 as char); for menu in &self.list_menu { println!("{}", menu); } let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); if let Ok(answer) = input.trim().parse::<i32>() { self.answer = answer; } else { self.answer = 0; } } fn run(&mut self) { while self.answer != 4 { self.show_menu(); } } } fn main() { let list_menu = vec![ "1. User".to_owned(), "2. Menu".to_owned(), "3. Help".to_owned(), "4. Quit".to_owned() ]; let mut menu: Menu = Menu{ list_menu: list_menu, answer: 0, }; menu.run(); }
use crate::vec3::*; pub struct ONB { pub u: Vec3, pub v: Vec3, pub w: Vec3, } impl ONB { pub fn build_from_w(n: Vec3) -> Self { let w = n.unit(); let a = if w.x.abs() > 0.9 { vec3(0.0, 1.0, 0.0) } else { vec3(1.0, 0.0, 0.0) }; let v = w.cross(a).unit(); let u = w.cross(v); Self { u, v, w } } pub fn local(&self, a: Vec3) -> Vec3 { scalar(a.x) * self.u + scalar(a.y) * self.v + scalar(a.z) * self.w } } // TODO: Indexable?
// 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 common_exception::ErrorCode; use common_exception::Range; use common_exception::Result; use logos::Lexer; use logos::Logos; use strum::IntoEnumIterator; use strum_macros::EnumIter; pub use self::TokenKind::*; #[derive(Clone, PartialEq, Eq)] pub struct Token<'a> { pub source: &'a str, pub kind: TokenKind, pub span: Range, } impl<'a> Token<'a> { pub fn new_eoi(source: &'a str) -> Self { Token { source, kind: TokenKind::EOI, span: (source.len()..source.len()).into(), } } pub fn text(&self) -> &'a str { &self.source[std::ops::Range::from(self.span)] } } impl<'a> std::fmt::Debug for Token<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}({:?})", self.kind, self.span) } } pub struct Tokenizer<'a> { source: &'a str, lexer: Lexer<'a, TokenKind>, eoi: bool, } impl<'a> Tokenizer<'a> { pub fn new(source: &'a str) -> Self { Tokenizer { source, lexer: TokenKind::lexer(source), eoi: false, } } } impl<'a> Iterator for Tokenizer<'a> { type Item = Result<Token<'a>>; fn next(&mut self) -> Option<Self::Item> { match self.lexer.next() { Some(kind) if kind == TokenKind::Error => Some(Err(ErrorCode::SyntaxException( "unable to recognize the rest tokens".to_string(), ) .set_span(Some((self.lexer.span().start..self.source.len()).into())))), Some(kind) => Some(Ok(Token { source: self.source, kind, span: self.lexer.span().into(), })), None if !self.eoi => { self.eoi = true; Some(Ok(Token::new_eoi(self.source))) } None => None, } } } #[allow(non_camel_case_types)] #[derive(Logos, EnumIter, Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum TokenKind { #[error] Error, EOI, #[regex(r"[ \t\r\n\f]+", logos::skip)] Whitespace, #[regex(r"--[^\t\n\f]*", logos::skip)] Comment, #[regex(r"/\*([^\*]|(\*[^/]))*\*/", logos::skip)] CommentBlock, #[regex(r#"[_a-zA-Z][_$a-zA-Z0-9]*"#)] Ident, #[regex(r#"`[^`]*`"#)] #[regex(r#""([^"\\]|\\.|"")*""#)] #[regex(r#"'([^'\\]|\\.|'')*'"#)] QuotedString, #[regex(r#"@([^\s`;'"])+"#)] AtString, #[regex(r"[xX]'[a-fA-F0-9]*'")] PGLiteralHex, #[regex(r"0[xX][a-fA-F0-9]+")] MySQLLiteralHex, #[regex(r"[0-9]+")] LiteralInteger, #[regex(r"[0-9]+[eE][+-]?[0-9]+")] #[regex(r"([0-9]*\.[0-9]+([eE][+-]?[0-9]+)?)|([0-9]+\.[0-9]*([eE][+-]?[0-9]+)?)")] LiteralFloat, // Symbols #[token("==")] DoubleEq, #[token("=")] Eq, #[token("<>")] #[token("!=")] NotEq, #[token("<")] Lt, #[token(">")] Gt, #[token("<=")] Lte, #[token(">=")] Gte, #[token("<=>")] Spaceship, #[token("+")] Plus, #[token("-")] Minus, #[token("*")] Multiply, #[token("/")] Divide, #[token("%")] Modulo, #[token("||")] StringConcat, #[token("(")] LParen, #[token(")")] RParen, #[token(",")] Comma, #[token(".")] Period, #[token(":")] Colon, #[token("::")] DoubleColon, #[token(";")] SemiColon, #[token("\\")] Backslash, #[token("[")] LBracket, #[token("]")] RBracket, #[token("^")] Caret, #[token("{")] LBrace, #[token("}")] RBrace, #[token("->")] RArrow, #[token("=>")] FatRArrow, /// A case insensitive match regular expression operator in PostgreSQL #[token("~*")] TildeAsterisk, /// A case sensitive not match regular expression operator in PostgreSQL #[token("!*")] ExclamationMarkTilde, /// A case insensitive not match regular expression operator in PostgreSQL #[token("!~*")] ExclamationMarkTildeAsterisk, /// A bitwise and operator in PostgreSQL #[token("&")] BitWiseAnd, /// A bitwise or operator in PostgreSQL #[token("|")] BitWiseOr, /// A bitwise xor operator in PostgreSQL #[token("#")] BitWiseXor, /// A bitwise not operator in PostgreSQL #[token("~")] BitWiseNot, /// A bitwise shift left operator in PostgreSQL #[token("<<")] ShiftLeft, /// A bitwise shift right operator in PostgreSQL #[token(">>")] ShiftRight, /// Exclamation Mark `!` used for PostgreSQL factorial operator #[token("!")] Factorial, /// Double Exclamation Mark `!!` used for PostgreSQL prefix factorial operator #[token("!!")] DoubleExclamationMark, /// AtSign `@` used for PostgreSQL abs operator #[token("@")] Abs, /// A square root math operator in PostgreSQL #[token("|/")] SquareRoot, /// A cube root math operator in PostgreSQL #[token("||/")] CubeRoot, /// Placeholder used in prepared stmt #[token("?")] Placeholder, // Keywords // // Steps to add keyword: // 1. Add the keyword to token kind variants by alphabetical order. // 2. Search in this file to see if the new keyword is a commented // out reserved keyword. If so, uncomment the keyword in the // reserved list. #[token("ALL", ignore(ascii_case))] ALL, #[token("ADD", ignore(ascii_case))] ADD, #[token("ANY", ignore(ascii_case))] ANY, #[token("AUTO", ignore(ascii_case))] AUTO, #[token("SOME", ignore(ascii_case))] SOME, #[token("ALTER", ignore(ascii_case))] ALTER, #[token("ANALYZE", ignore(ascii_case))] ANALYZE, #[token("AND", ignore(ascii_case))] AND, #[token("ARRAY", ignore(ascii_case))] ARRAY, #[token("AS", ignore(ascii_case))] AS, #[token("AST", ignore(ascii_case))] AST, #[token("AT", ignore(ascii_case))] AT, #[token("ASC", ignore(ascii_case))] ASC, #[token("ANTI", ignore(ascii_case))] ANTI, #[token("BEFORE", ignore(ascii_case))] BEFORE, #[token("BETWEEN", ignore(ascii_case))] BETWEEN, #[token("BIGINT", ignore(ascii_case))] BIGINT, #[token("BOOL", ignore(ascii_case))] BOOL, #[token("BOOLEAN", ignore(ascii_case))] BOOLEAN, #[token("BOTH", ignore(ascii_case))] BOTH, #[token("BY", ignore(ascii_case))] BY, #[token("BROTLI", ignore(ascii_case))] BROTLI, #[token("BZ2", ignore(ascii_case))] BZ2, #[token("CALL", ignore(ascii_case))] CALL, #[token("CASE", ignore(ascii_case))] CASE, #[token("CAST", ignore(ascii_case))] CAST, #[token("CATALOG", ignore(ascii_case))] CATALOG, #[token("CATALOGS", ignore(ascii_case))] CATALOGS, #[token("CENTURY", ignore(ascii_case))] CENTURY, #[token("CLUSTER", ignore(ascii_case))] CLUSTER, #[token("COMMENT", ignore(ascii_case))] COMMENT, #[token("COMMENTS", ignore(ascii_case))] COMMENTS, #[token("COMPACT", ignore(ascii_case))] COMPACT, #[token("CONNECTION", ignore(ascii_case))] CONNECTION, #[token("CONTENT_TYPE", ignore(ascii_case))] CONTENT_TYPE, #[token("CHAR", ignore(ascii_case))] CHAR, #[token("COLUMN", ignore(ascii_case))] COLUMN, #[token("COLUMNS", ignore(ascii_case))] COLUMNS, #[token("CHARACTER", ignore(ascii_case))] CHARACTER, #[token("CONFLICT", ignore(ascii_case))] CONFLICT, #[token("COMPRESSION", ignore(ascii_case))] COMPRESSION, #[token("COPY_OPTIONS", ignore(ascii_case))] COPY_OPTIONS, #[token("COPY", ignore(ascii_case))] COPY, #[token("COUNT", ignore(ascii_case))] COUNT, #[token("CREATE", ignore(ascii_case))] CREATE, #[token("CREDENTIALS", ignore(ascii_case))] CREDENTIALS, #[token("CROSS", ignore(ascii_case))] CROSS, #[token("CSV", ignore(ascii_case))] CSV, #[token("CURRENT", ignore(ascii_case))] CURRENT, #[token("CURRENT_TIMESTAMP", ignore(ascii_case))] CURRENT_TIMESTAMP, #[token("DATABASE", ignore(ascii_case))] DATABASE, #[token("DATABASES", ignore(ascii_case))] DATABASES, #[token("DATE", ignore(ascii_case))] DATE, #[token("DATE_ADD", ignore(ascii_case))] DATE_ADD, #[token("DATE_SUB", ignore(ascii_case))] DATE_SUB, #[token("DATE_TRUNC", ignore(ascii_case))] DATE_TRUNC, #[token("DATETIME", ignore(ascii_case))] DATETIME, #[token("DAY", ignore(ascii_case))] DAY, #[token("DECADE", ignore(ascii_case))] DECADE, #[token("DECIMAL", ignore(ascii_case))] DECIMAL, #[token("DEFAULT", ignore(ascii_case))] DEFAULT, #[token("DEFLATE", ignore(ascii_case))] DEFLATE, #[token("DELETE", ignore(ascii_case))] DELETE, #[token("DESC", ignore(ascii_case))] DESC, #[token("DESCRIBE", ignore(ascii_case))] DESCRIBE, #[token("DISTINCT", ignore(ascii_case))] DISTINCT, #[token("DIV", ignore(ascii_case))] DIV, #[token("DOUBLE_SHA1_PASSWORD", ignore(ascii_case))] DOUBLE_SHA1_PASSWORD, #[token("DOUBLE", ignore(ascii_case))] DOUBLE, #[token("DOW", ignore(ascii_case))] DOW, #[token("DOY", ignore(ascii_case))] DOY, #[token("DOWNLOAD", ignore(ascii_case))] DOWNLOAD, #[token("DROP", ignore(ascii_case))] DROP, #[token("EXCEPT", ignore(ascii_case))] EXCEPT, #[token("EXCLUDE", ignore(ascii_case))] EXCLUDE, #[token("ELSE", ignore(ascii_case))] ELSE, #[token("ENABLE_VIRTUAL_HOST_STYLE", ignore(ascii_case))] ENABLE_VIRTUAL_HOST_STYLE, #[token("END", ignore(ascii_case))] END, #[token("ENGINE", ignore(ascii_case))] ENGINE, #[token("ENGINES", ignore(ascii_case))] ENGINES, #[token("EPOCH", ignore(ascii_case))] EPOCH, #[token("ESCAPE", ignore(ascii_case))] ESCAPE, #[token("EXISTS", ignore(ascii_case))] EXISTS, #[token("EXPLAIN", ignore(ascii_case))] EXPLAIN, #[token("EXPIRE", ignore(ascii_case))] EXPIRE, #[token("EXTRACT", ignore(ascii_case))] EXTRACT, #[token("FALSE", ignore(ascii_case))] FALSE, #[token("FIELDS", ignore(ascii_case))] FIELDS, #[token("FIELD_DELIMITER", ignore(ascii_case))] FIELD_DELIMITER, #[token("NAN_DISPLAY", ignore(ascii_case))] NAN_DISPLAY, #[token("FILE_FORMAT", ignore(ascii_case))] FILE_FORMAT, #[token("FILE", ignore(ascii_case))] FILE, #[token("FILES", ignore(ascii_case))] FILES, #[token("FINAL", ignore(ascii_case))] FINAL, #[token("FLASHBACK", ignore(ascii_case))] FLASHBACK, #[token("FLOAT", ignore(ascii_case))] FLOAT, #[token("FLOAT32", ignore(ascii_case))] FLOAT32, #[token("FLOAT64", ignore(ascii_case))] FLOAT64, #[token("FOR", ignore(ascii_case))] FOR, #[token("FORCE", ignore(ascii_case))] FORCE, #[token("FORMAT", ignore(ascii_case))] FORMAT, #[token("FOLLOWING", ignore(ascii_case))] FOLLOWING, #[token("FORMAT_NAME", ignore(ascii_case))] FORMAT_NAME, #[token("FORMATS", ignore(ascii_case))] FORMATS, #[token("FRAGMENTS", ignore(ascii_case))] FRAGMENTS, #[token("FROM", ignore(ascii_case))] FROM, #[token("FULL", ignore(ascii_case))] FULL, #[token("FUNCTION", ignore(ascii_case))] FUNCTION, #[token("FUNCTIONS", ignore(ascii_case))] FUNCTIONS, #[token("TABLE_FUNCTIONS", ignore(ascii_case))] TABLE_FUNCTIONS, #[token("FUSE", ignore(ascii_case))] FUSE, #[token("GLOBAL", ignore(ascii_case))] GLOBAL, #[token("GRAPH", ignore(ascii_case))] GRAPH, #[token("GROUP", ignore(ascii_case))] GROUP, #[token("GZIP", ignore(ascii_case))] GZIP, #[token("HAVING", ignore(ascii_case))] HAVING, #[token("HISTORY", ignore(ascii_case))] HISTORY, #[token("HIVE", ignore(ascii_case))] HIVE, #[token("HOUR", ignore(ascii_case))] HOUR, #[token("ICEBERG", ignore(ascii_case))] ICEBERG, #[token("INTERSECT", ignore(ascii_case))] INTERSECT, #[token("IDENTIFIED", ignore(ascii_case))] IDENTIFIED, #[token("IF", ignore(ascii_case))] IF, #[token("IN", ignore(ascii_case))] IN, #[token("INNER", ignore(ascii_case))] INNER, #[token("INSERT", ignore(ascii_case))] INSERT, #[token("INT", ignore(ascii_case))] INT, #[token("INT16", ignore(ascii_case))] INT16, #[token("INT32", ignore(ascii_case))] INT32, #[token("INT64", ignore(ascii_case))] INT64, #[token("INT8", ignore(ascii_case))] INT8, #[token("INTEGER", ignore(ascii_case))] INTEGER, #[token("INTERVAL", ignore(ascii_case))] INTERVAL, #[token("INTO", ignore(ascii_case))] INTO, #[token("IS", ignore(ascii_case))] IS, #[token("ISODOW", ignore(ascii_case))] ISODOW, #[token("ISOYEAR", ignore(ascii_case))] ISOYEAR, #[token("JOIN", ignore(ascii_case))] JOIN, #[token("JSON", ignore(ascii_case))] JSON, #[token("JULIAN", ignore(ascii_case))] JULIAN, #[token("JWT", ignore(ascii_case))] JWT, #[token("KEY", ignore(ascii_case))] KEY, #[token("KILL", ignore(ascii_case))] KILL, #[token("LOCATION_PREFIX", ignore(ascii_case))] LOCATION_PREFIX, #[token("ROLES", ignore(ascii_case))] ROLES, #[token("LEADING", ignore(ascii_case))] LEADING, #[token("LEFT", ignore(ascii_case))] LEFT, #[token("LIKE", ignore(ascii_case))] LIKE, #[token("LIMIT", ignore(ascii_case))] LIMIT, #[token("LIST", ignore(ascii_case))] LIST, #[token("LZO", ignore(ascii_case))] LZO, #[token("MAP", ignore(ascii_case))] MAP, #[token("MAX_FILE_SIZE", ignore(ascii_case))] MAX_FILE_SIZE, #[token("MASTER_KEY", ignore(ascii_case))] MASTER_KEY, #[token("MEMO", ignore(ascii_case))] MEMO, #[token("MEMORY", ignore(ascii_case))] MEMORY, #[token("METRICS", ignore(ascii_case))] METRICS, #[token("MICROSECONDS", ignore(ascii_case))] MICROSECONDS, #[token("MILLENNIUM", ignore(ascii_case))] MILLENNIUM, #[token("MILLISECONDS", ignore(ascii_case))] MILLISECONDS, #[token("MINUTE", ignore(ascii_case))] MINUTE, #[token("MONTH", ignore(ascii_case))] MONTH, #[token("NON_DISPLAY", ignore(ascii_case))] NON_DISPLAY, #[token("NATURAL", ignore(ascii_case))] NATURAL, #[token("NDJSON", ignore(ascii_case))] NDJSON, #[token("NO_PASSWORD", ignore(ascii_case))] NO_PASSWORD, #[token("NONE", ignore(ascii_case))] NONE, #[token("NOT", ignore(ascii_case))] NOT, #[token("NOTENANTSETTING", ignore(ascii_case))] NOTENANTSETTING, #[token("NULL", ignore(ascii_case))] NULL, #[token("NULLABLE", ignore(ascii_case))] NULLABLE, #[token("OBJECT", ignore(ascii_case))] OBJECT, #[token("OF", ignore(ascii_case))] OF, #[token("OFFSET", ignore(ascii_case))] OFFSET, #[token("ON", ignore(ascii_case))] ON, #[token("OPTIMIZE", ignore(ascii_case))] OPTIMIZE, #[token("OR", ignore(ascii_case))] OR, #[token("ORDER", ignore(ascii_case))] ORDER, #[token("OUTER", ignore(ascii_case))] OUTER, #[token("ON_ERROR", ignore(ascii_case))] ON_ERROR, #[token("OVER", ignore(ascii_case))] OVER, #[token("OVERWRITE", ignore(ascii_case))] OVERWRITE, #[token("PARTITION", ignore(ascii_case))] PARTITION, #[token("PARQUET", ignore(ascii_case))] PARQUET, #[token("PATTERN", ignore(ascii_case))] PATTERN, #[token("PIPELINE", ignore(ascii_case))] PIPELINE, #[token("PLAINTEXT_PASSWORD", ignore(ascii_case))] PLAINTEXT_PASSWORD, #[token("POSITION", ignore(ascii_case))] POSITION, #[token("PROCESSLIST", ignore(ascii_case))] PROCESSLIST, #[token("PURGE", ignore(ascii_case))] PURGE, #[token("QUARTER", ignore(ascii_case))] QUARTER, #[token("QUERY", ignore(ascii_case))] QUERY, #[token("QUOTE", ignore(ascii_case))] QUOTE, #[token("RANGE", ignore(ascii_case))] RANGE, #[token("RAWDEFLATE", ignore(ascii_case))] RAWDEFLATE, #[token("RECLUSTER", ignore(ascii_case))] RECLUSTER, #[token("RECORD_DELIMITER", ignore(ascii_case))] RECORD_DELIMITER, #[token("REFERENCE_USAGE", ignore(ascii_case))] REFERENCE_USAGE, #[token("REGEXP", ignore(ascii_case))] REGEXP, #[token("RENAME", ignore(ascii_case))] RENAME, #[token("REPLACE", ignore(ascii_case))] REPLACE, #[token("ROW", ignore(ascii_case))] ROW, #[token("ROWS", ignore(ascii_case))] ROWS, #[token("ROW_TAG", ignore(ascii_case))] ROW_TAG, #[token("GRANT", ignore(ascii_case))] GRANT, #[token("ROLE", ignore(ascii_case))] ROLE, #[token("PRECEDING", ignore(ascii_case))] PRECEDING, #[token("PRECISION", ignore(ascii_case))] PRECISION, #[token("PRESIGN", ignore(ascii_case))] PRESIGN, #[token("PRIVILEGES", ignore(ascii_case))] PRIVILEGES, #[token("REMOVE", ignore(ascii_case))] REMOVE, #[token("REVOKE", ignore(ascii_case))] REVOKE, #[token("RECURSIVE", ignore(ascii_case))] RECURSIVE, #[token("GRANTS", ignore(ascii_case))] GRANTS, #[token("RIGHT", ignore(ascii_case))] RIGHT, #[token("RLIKE", ignore(ascii_case))] RLIKE, #[token("RAW", ignore(ascii_case))] RAW, #[token("SCHEMA", ignore(ascii_case))] SCHEMA, #[token("SCHEMAS", ignore(ascii_case))] SCHEMAS, #[token("SECOND", ignore(ascii_case))] SECOND, #[token("SELECT", ignore(ascii_case))] SELECT, #[token("PIVOT", ignore(ascii_case))] PIVOT, #[token("UNPIVOT", ignore(ascii_case))] UNPIVOT, #[token("SEGMENT", ignore(ascii_case))] SEGMENT, #[token("SET", ignore(ascii_case))] SET, #[token("UNSET", ignore(ascii_case))] UNSET, #[token("SETTINGS", ignore(ascii_case))] SETTINGS, #[token("STAGES", ignore(ascii_case))] STAGES, #[token("STATISTIC", ignore(ascii_case))] STATISTIC, #[token("SHA256_PASSWORD", ignore(ascii_case))] SHA256_PASSWORD, #[token("SHOW", ignore(ascii_case))] SHOW, #[token("SIGNED", ignore(ascii_case))] SIGNED, #[token("SINGLE", ignore(ascii_case))] SINGLE, #[token("SIZE_LIMIT", ignore(ascii_case))] SIZE_LIMIT, #[token("SKIP_HEADER", ignore(ascii_case))] SKIP_HEADER, #[token("SMALLINT", ignore(ascii_case))] SMALLINT, #[token("SNAPPY", ignore(ascii_case))] SNAPPY, #[token("SNAPSHOT", ignore(ascii_case))] SNAPSHOT, #[token("SPLIT_SIZE", ignore(ascii_case))] SPLIT_SIZE, #[token("STAGE", ignore(ascii_case))] STAGE, #[token("SYNTAX", ignore(ascii_case))] SYNTAX, #[token("USAGE", ignore(ascii_case))] USAGE, #[token("UPDATE", ignore(ascii_case))] UPDATE, #[token("UPLOAD", ignore(ascii_case))] UPLOAD, #[token("SHARE", ignore(ascii_case))] SHARE, #[token("SHARES", ignore(ascii_case))] SHARES, #[token("SUPER", ignore(ascii_case))] SUPER, #[token("STATUS", ignore(ascii_case))] STATUS, #[token("STRING", ignore(ascii_case))] STRING, #[token("SUBSTRING", ignore(ascii_case))] SUBSTRING, #[token("SUBSTR", ignore(ascii_case))] SUBSTR, #[token("SEMI", ignore(ascii_case))] SEMI, #[token("TABLE", ignore(ascii_case))] TABLE, #[token("TABLES", ignore(ascii_case))] TABLES, #[token("TEXT", ignore(ascii_case))] TEXT, #[token("TENANTSETTING", ignore(ascii_case))] TENANTSETTING, #[token("TENANTS", ignore(ascii_case))] TENANTS, #[token("THEN", ignore(ascii_case))] THEN, #[token("TIMESTAMP", ignore(ascii_case))] TIMESTAMP, #[token("TIMEZONE_HOUR", ignore(ascii_case))] TIMEZONE_HOUR, #[token("TIMEZONE_MINUTE", ignore(ascii_case))] TIMEZONE_MINUTE, #[token("TIMEZONE", ignore(ascii_case))] TIMEZONE, #[token("TINYINT", ignore(ascii_case))] TINYINT, #[token("TO", ignore(ascii_case))] TO, #[token("TOKEN", ignore(ascii_case))] TOKEN, #[token("TRAILING", ignore(ascii_case))] TRAILING, #[token("TRANSIENT", ignore(ascii_case))] TRANSIENT, #[token("TRIM", ignore(ascii_case))] TRIM, #[token("ARRAY_SORT", ignore(ascii_case))] ARRAY_SORT, #[token("TRUE", ignore(ascii_case))] TRUE, #[token("TRUNCATE", ignore(ascii_case))] TRUNCATE, #[token("TRY_CAST", ignore(ascii_case))] TRY_CAST, #[token("TSV", ignore(ascii_case))] TSV, #[token("TUPLE", ignore(ascii_case))] TUPLE, #[token("TYPE", ignore(ascii_case))] TYPE, #[token("UNBOUNDED", ignore(ascii_case))] UNBOUNDED, #[token("UNION", ignore(ascii_case))] UNION, #[token("UINT16", ignore(ascii_case))] UINT16, #[token("UINT32", ignore(ascii_case))] UINT32, #[token("UINT64", ignore(ascii_case))] UINT64, #[token("UINT8", ignore(ascii_case))] UINT8, #[token("UNDROP", ignore(ascii_case))] UNDROP, #[token("UNSIGNED", ignore(ascii_case))] UNSIGNED, #[token("URL", ignore(ascii_case))] URL, #[token("USE", ignore(ascii_case))] USE, #[token("USER", ignore(ascii_case))] USER, #[token("USERS", ignore(ascii_case))] USERS, #[token("USING", ignore(ascii_case))] USING, #[token("VALUES", ignore(ascii_case))] VALUES, #[token("VALIDATION_MODE", ignore(ascii_case))] VALIDATION_MODE, #[token("VARCHAR", ignore(ascii_case))] VARCHAR, #[token("VARIANT", ignore(ascii_case))] VARIANT, #[token("VIEW", ignore(ascii_case))] VIEW, #[token("WEEK", ignore(ascii_case))] WEEK, #[token("WHEN", ignore(ascii_case))] WHEN, #[token("WHERE", ignore(ascii_case))] WHERE, #[token("WITH", ignore(ascii_case))] WITH, #[token("XML", ignore(ascii_case))] XML, #[token("XOR", ignore(ascii_case))] XOR, #[token("XZ", ignore(ascii_case))] XZ, #[token("YEAR", ignore(ascii_case))] YEAR, #[token("ZSTD", ignore(ascii_case))] ZSTD, #[token("NULLIF", ignore(ascii_case))] NULLIF, #[token("COALESCE", ignore(ascii_case))] COALESCE, #[token("RANDOM", ignore(ascii_case))] RANDOM, #[token("IFNULL", ignore(ascii_case))] IFNULL, #[token("NULLS", ignore(ascii_case))] NULLS, #[token("FIRST", ignore(ascii_case))] FIRST, #[token("LAST", ignore(ascii_case))] LAST, #[token("IGNORE_RESULT", ignore(ascii_case))] IGNORE_RESULT, #[token("GROUPING", ignore(ascii_case))] GROUPING, #[token("SETS", ignore(ascii_case))] SETS, #[token("CUBE", ignore(ascii_case))] CUBE, #[token("ROLLUP", ignore(ascii_case))] ROLLUP, } // Reference: https://www.postgresql.org/docs/current/sql-keywords-appendix.html impl TokenKind { pub fn is_keyword(&self) -> bool { !matches!( self, Ident | QuotedString | PGLiteralHex | MySQLLiteralHex | LiteralInteger | LiteralFloat | DoubleEq | Eq | NotEq | Lt | Gt | Lte | Gte | Spaceship | Plus | Minus | Multiply | Divide | Modulo | StringConcat | LParen | RParen | Comma | Period | Colon | DoubleColon | SemiColon | Backslash | LBracket | RBracket | BitWiseAnd | BitWiseOr | Caret | Factorial | LBrace | RBrace | RArrow | FatRArrow | BitWiseXor | BitWiseNot | TildeAsterisk | ExclamationMarkTilde | ExclamationMarkTildeAsterisk | ShiftLeft | ShiftRight | DoubleExclamationMark | Abs | SquareRoot | CubeRoot | EOI ) } pub fn is_reserved_function_name(&self, after_as: bool) -> bool { match self { | TokenKind::ALL // | TokenKind::ANALYSE | TokenKind::ANALYZE | TokenKind::AND // | TokenKind::ANY | TokenKind::ASC // | TokenKind::ASYMMETRIC | TokenKind::BETWEEN | TokenKind::BIGINT // | TokenKind::BIT | TokenKind::BOOLEAN | TokenKind::BOTH | TokenKind::CASE | TokenKind::CAST // | TokenKind::CHECK // | TokenKind::COALESCE // | TokenKind::COLLATE // | TokenKind::COLUMN // | TokenKind::CONSTRAINT // | TokenKind::CURRENT_CATALOG // | TokenKind::CURRENT_DATE // | TokenKind::CURRENT_ROLE // | TokenKind::CURRENT_TIME | TokenKind::CURRENT_TIMESTAMP // | TokenKind::CURRENT_USER // | TokenKind::DEC // | TokenKind::DECIMAL | TokenKind::DEFAULT // | TokenKind::DEFERRABLE | TokenKind::DESC | TokenKind::DISTINCT // | TokenKind::DO | TokenKind::ELSE | TokenKind::END | TokenKind::EXISTS | TokenKind::EXTRACT | TokenKind::FALSE | TokenKind::FLOAT // | TokenKind::FOREIGN // | TokenKind::GREATEST // | TokenKind::GROUPING | TokenKind::CUBE | TokenKind::ROLLUP // | TokenKind::IFNULL | TokenKind::IN // | TokenKind::INITIALLY // | TokenKind::INOUT | TokenKind::INT | TokenKind::INTEGER | TokenKind::INTERVAL // | TokenKind::LATERAL | TokenKind::LEADING // | TokenKind::LEAST // | TokenKind::LOCALTIME // | TokenKind::LOCALTIMESTAMP // | TokenKind::NATIONAL // | TokenKind::NCHAR // | TokenKind::NONE // | TokenKind::NORMALIZE | TokenKind::NOT | TokenKind::NULL // | TokenKind::NULLIF // | TokenKind::NUMERIC // | TokenKind::ONLY | TokenKind::OR // | TokenKind::OUT // | TokenKind::OVERLAY // | TokenKind::PLACING | TokenKind::POSITION // | TokenKind::PRIMARY // | TokenKind::REAL // | TokenKind::REFERENCES // | TokenKind::ROW | TokenKind::SELECT // | TokenKind::SESSION_USER // | TokenKind::SETOF | TokenKind::SHARE | TokenKind::SHARES | TokenKind::SMALLINT | TokenKind::SOME | TokenKind::SUBSTRING | TokenKind::SUBSTR // | TokenKind::SYMMETRIC | TokenKind::TABLE | TokenKind::THEN // | TokenKind::TIME | TokenKind::TIMESTAMP | TokenKind::TRAILING // | TokenKind::TREAT | TokenKind::TRIM | TokenKind::ARRAY_SORT | TokenKind::TRUE | TokenKind::TRY_CAST // | TokenKind::UNIQUE //| TokenKind::USER | TokenKind::USING | TokenKind::VALUES | TokenKind::VARCHAR // | TokenKind::VARIADIC // | TokenKind::XMLATTRIBUTES // | TokenKind::XMLCONCAT // | TokenKind::XMLELEMENT // | TokenKind::XMLEXISTS // | TokenKind::XMLFOREST // | TokenKind::XMLNAMESPACES // | TokenKind::XMLPARSE // | TokenKind::XMLPI // | TokenKind::XMLROOT // | TokenKind::XMLSERIALIZE // | TokenKind::XMLTABLE | TokenKind::WHEN => true, | TokenKind::ARRAY | TokenKind::AS // | TokenKind::CHAR | TokenKind::CHARACTER | TokenKind::CREATE | TokenKind::EXCEPT // | TokenKind::FETCH | TokenKind::FOR | TokenKind::FROM // | TokenKind::GRANT | TokenKind::GROUP | TokenKind::HAVING | TokenKind::INTERSECT | TokenKind::INTO | TokenKind::LIMIT | TokenKind::OFFSET | TokenKind::ON | TokenKind::OF | TokenKind::ORDER | TokenKind::OVER | TokenKind::ROWS | TokenKind::RANGE // | TokenKind::PRECISION // | TokenKind::RETURNING | TokenKind::TO | TokenKind::UNION | TokenKind::WHERE // | TokenKind::WINDOW | TokenKind::WITH | TokenKind::DATE_ADD | TokenKind::DATE_SUB | TokenKind::DATE_TRUNC | TokenKind::IGNORE_RESULT if !after_as => true, _ => false } } pub fn is_reserved_ident(&self, after_as: bool) -> bool { match self { | TokenKind::ALL // | TokenKind::ANALYSE | TokenKind::ANALYZE | TokenKind::AND | TokenKind::ANY | TokenKind::ASC | TokenKind::ANTI // | TokenKind::ASYMMETRIC // | TokenKind::AUTHORIZATION // | TokenKind::BINARY | TokenKind::BOTH | TokenKind::CASE | TokenKind::CAST // | TokenKind::CHECK // | TokenKind::COLLATE // | TokenKind::COLLATION // | TokenKind::COLUMN // | TokenKind::CONCURRENTLY // | TokenKind::CONSTRAINT | TokenKind::CROSS // | TokenKind::CURRENT_CATALOG // | TokenKind::CURRENT_DATE // | TokenKind::CURRENT_ROLE // | TokenKind::CURRENT_SCHEMA // | TokenKind::CURRENT_TIME | TokenKind::CURRENT_TIMESTAMP // | TokenKind::CURRENT_USER // | TokenKind::DEFERRABLE | TokenKind::DESC | TokenKind::DISTINCT // | TokenKind::DO | TokenKind::ELSE | TokenKind::END | TokenKind::FALSE // | TokenKind::FOREIGN // | TokenKind::FREEZE | TokenKind::FULL // | TokenKind::ILIKE | TokenKind::IN // | TokenKind::INITIALLY | TokenKind::INNER | TokenKind::IS | TokenKind::JOIN // | TokenKind::LATERAL | TokenKind::LEADING | TokenKind::LEFT | TokenKind::LIKE // | TokenKind::LOCALTIME // | TokenKind::LOCALTIMESTAMP | TokenKind::NATURAL | TokenKind::NOT | TokenKind::NULL // | TokenKind::ONLY | TokenKind::OR | TokenKind::OUTER // | TokenKind::PLACING // | TokenKind::PRIMARY // | TokenKind::REFERENCES | TokenKind::RIGHT | TokenKind::SELECT | TokenKind::PIVOT | TokenKind::UNPIVOT // | TokenKind::SESSION_USER // | TokenKind::SIMILAR | TokenKind::SOME | TokenKind::SEMI // | TokenKind::SYMMETRIC // | TokenKind::TABLE // | TokenKind::TABLESAMPLE | TokenKind::THEN | TokenKind::TRAILING | TokenKind::TRUE // | TokenKind::UNIQUE //| TokenKind::USER | TokenKind::USING // | TokenKind::VARIADIC // | TokenKind::VERBOSE | TokenKind::WHEN => true, | TokenKind::ARRAY | TokenKind::AS | TokenKind::CREATE | TokenKind::EXCEPT // | TokenKind::FETCH | TokenKind::FOR | TokenKind::FROM // | TokenKind::GRANT | TokenKind::GROUP | TokenKind::HAVING | TokenKind::INTERSECT | TokenKind::INTO // | TokenKind::ISNULL | TokenKind::LIMIT | TokenKind::FORMAT // | TokenKind::NOTNULL | TokenKind::OFFSET | TokenKind::ON | TokenKind::OF | TokenKind::ORDER | TokenKind::OVER | TokenKind::ROWS | TokenKind::RANGE // | TokenKind::OVERLAPS // | TokenKind::RETURNING | TokenKind::STAGE | TokenKind::SHARE | TokenKind::SHARES | TokenKind::TO | TokenKind::UNION | TokenKind::WHERE // | TokenKind::WINDOW | TokenKind::WITH | TokenKind::IGNORE_RESULT if !after_as => true, _ => false } } } pub fn all_reserved_keywords() -> Vec<String> { let mut result = Vec::new(); for token in TokenKind::iter() { result.push(format!("{:?}", token)); } result }
use proconio::input; use std::cmp::Ordering; fn main() { input! { n: usize, a: i32, wxv: [(u32, i32, i32); n], }; let mut ans = 0; for i in 0..n { let (_, x, v) = wxv[i]; let mut events = Vec::new(); #[derive(Debug, PartialEq)] enum E { In(f64, usize), Out(f64, usize), } impl PartialOrd for E { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match (self, other) { (E::In(t, _), E::In(tt, _)) => t.partial_cmp(tt), (E::Out(t, _), E::Out(tt, _)) => t.partial_cmp(tt), // 有理数で比較したほうがよい? (E::In(t, _), E::Out(tt, _)) => t .partial_cmp(tt) .map(|ord| ord.then_with(|| Ordering::Less)), (E::Out(t, _), E::In(tt, _)) => t .partial_cmp(tt) .map(|ord| ord.then_with(|| Ordering::Greater)), } } } for j in 0..n { let (_, xx, vv) = wxv[j]; if vv > v { events.push(E::In((x - xx) as f64 / (vv - v) as f64, j)); events.push(E::Out((x + a - xx) as f64 / (vv - v) as f64, j)); } else if vv == v { if x <= xx && xx <= x + a { events.push(E::In(0.0, j)); } } else { // vv < v events.push(E::In((xx - (x + a)) as f64 / (v - vv) as f64, j)); events.push(E::Out((xx - x) as f64 / (v - vv) as f64, j)); } } events.sort_by(|e1, e2| e1.partial_cmp(e2).unwrap()); let mut sum = 0; for e in events { match e { E::In(t, j) => { let (ww, _, _) = wxv[j]; sum += ww; if t >= 0.0 { ans = ans.max(sum); } } E::Out(t, j) => { let (ww, _, _) = wxv[j]; assert!(sum >= ww); sum -= ww; if t >= 0.0 { ans = ans.max(sum); } } } } } println!("{}", ans); }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod convert; use { crate::{device::IfaceMap, telemetry::convert::*}, fidl_fuchsia_cobalt::HistogramBucket, fidl_fuchsia_wlan_stats as fidl_stats, fidl_fuchsia_wlan_stats::MlmeStats::{ApMlmeStats, ClientMlmeStats}, fuchsia_async as fasync, fuchsia_cobalt::CobaltSender, fuchsia_zircon as zx, fuchsia_zircon::DurationNum, futures::prelude::*, futures::stream::FuturesUnordered, log::{error, warn}, parking_lot::Mutex, std::cmp::PartialOrd, std::collections::hash_map::Entry, std::collections::HashMap, std::default::Default, std::ops::Sub, std::sync::Arc, wlan_common::{ bss::{BssDescriptionExt, Standard}, format::MacFmt, }, wlan_metrics_registry::{ self as metrics, NeighborNetworksWlanStandardsCountMetricDimensionWlanStandardType as NeighborNetworksMetricStandardLabel, }, wlan_sme::client::{ info::{ ConnectStats, ConnectionLostInfo, ConnectionMilestone, ConnectionPingInfo, ScanStats, }, ConnectFailure, ConnectResult, }, }; type StatsRef = Arc<Mutex<fidl_stats::IfaceStats>>; /// How often to request RSSI stats and dispatcher packet counts from MLME. const REPORT_PERIOD_MINUTES: i64 = 1; /// Mapping of WLAN standard type to the corresponding metric label used for Cobalt. const NEIGHBOR_NETWORKS_STANDARD_MAPPING: [(Standard, NeighborNetworksMetricStandardLabel); 5] = [ (Standard::Dot11B, NeighborNetworksMetricStandardLabel::_802_11b), (Standard::Dot11G, NeighborNetworksMetricStandardLabel::_802_11g), (Standard::Dot11A, NeighborNetworksMetricStandardLabel::_802_11a), (Standard::Dot11N, NeighborNetworksMetricStandardLabel::_802_11n), (Standard::Dot11Ac, NeighborNetworksMetricStandardLabel::_802_11ac), ]; // Export MLME stats to Cobalt every REPORT_PERIOD_MINUTES. pub async fn report_telemetry_periodically(ifaces_map: Arc<IfaceMap>, mut sender: CobaltSender) { // TODO(NET-1386): Make this module resilient to Wlanstack2 downtime. let mut last_reported_stats: HashMap<u16, StatsRef> = HashMap::new(); let mut interval_stream = fasync::Interval::new(REPORT_PERIOD_MINUTES.minutes()); while let Some(_) = interval_stream.next().await { let mut futures = FuturesUnordered::new(); for (id, iface) in ifaces_map.get_snapshot().iter() { let id = *id; let iface = Arc::clone(iface); let fut = iface.stats_sched.get_stats().map(move |r| (id, iface, r)); futures.push(fut); } while let Some((id, iface, stats_result)) = futures.next().await { match stats_result { Ok(current_stats) => match last_reported_stats.entry(id) { Entry::Vacant(entry) => { entry.insert(current_stats); } Entry::Occupied(mut value) => { let last_stats = value.get_mut(); report_stats(&last_stats.lock(), &current_stats.lock(), &mut sender); let _dropped = std::mem::replace(value.get_mut(), current_stats); } }, Err(e) => { last_reported_stats.remove(&id); error!( "Failed to get the stats for iface '{:?}': {}", match &iface.device { Some(device) => device.path().to_string_lossy().into_owned(), None => "TODO(WLAN-927)".to_string(), }, e ); } }; } } } fn report_stats( last_stats: &fidl_stats::IfaceStats, current_stats: &fidl_stats::IfaceStats, sender: &mut CobaltSender, ) { report_mlme_stats(&last_stats.mlme_stats, &current_stats.mlme_stats, sender); report_dispatcher_stats(&last_stats.dispatcher_stats, &current_stats.dispatcher_stats, sender); } fn report_dispatcher_stats( last_stats: &fidl_stats::DispatcherStats, current_stats: &fidl_stats::DispatcherStats, sender: &mut CobaltSender, ) { report_dispatcher_packets( metrics::DispatcherPacketCountsMetricDimensionPacketType::In, get_diff(last_stats.any_packet.in_.count, current_stats.any_packet.in_.count), sender, ); report_dispatcher_packets( metrics::DispatcherPacketCountsMetricDimensionPacketType::Out, get_diff(last_stats.any_packet.out.count, current_stats.any_packet.out.count), sender, ); report_dispatcher_packets( metrics::DispatcherPacketCountsMetricDimensionPacketType::Dropped, get_diff(last_stats.any_packet.drop.count, current_stats.any_packet.drop.count), sender, ); } fn report_dispatcher_packets( packet_type: metrics::DispatcherPacketCountsMetricDimensionPacketType, packet_count: u64, sender: &mut CobaltSender, ) { sender.log_event_count( metrics::DISPATCHER_PACKET_COUNTS_METRIC_ID, packet_type as u32, 0, packet_count as i64, ); } fn report_mlme_stats( last: &Option<Box<fidl_stats::MlmeStats>>, current: &Option<Box<fidl_stats::MlmeStats>>, sender: &mut CobaltSender, ) { if let (Some(ref last), Some(ref current)) = (last, current) { match (last.as_ref(), current.as_ref()) { (ClientMlmeStats(last), ClientMlmeStats(current)) => { report_client_mlme_stats(&last, &current, sender) } (ApMlmeStats(_), ApMlmeStats(_)) => {} _ => error!("Current MLME stats type is different from the last MLME stats type"), }; } } fn report_client_mlme_stats( last_stats: &fidl_stats::ClientMlmeStats, current_stats: &fidl_stats::ClientMlmeStats, sender: &mut CobaltSender, ) { report_rssi_stats( metrics::CLIENT_ASSOC_RSSI_METRIC_ID, &last_stats.assoc_data_rssi, &current_stats.assoc_data_rssi, sender, ); report_rssi_stats( metrics::CLIENT_BEACON_RSSI_METRIC_ID, &last_stats.beacon_rssi, &current_stats.beacon_rssi, sender, ); report_client_mlme_rx_tx_frames(&last_stats, &current_stats, sender); } fn report_client_mlme_rx_tx_frames( last_stats: &fidl_stats::ClientMlmeStats, current_stats: &fidl_stats::ClientMlmeStats, sender: &mut CobaltSender, ) { sender.log_event_count( metrics::MLME_RX_TX_FRAME_COUNTS_METRIC_ID, metrics::MlmeRxTxFrameCountsMetricDimensionFrameType::Rx as u32, 0, get_diff(last_stats.rx_frame.in_.count, current_stats.rx_frame.in_.count) as i64, ); sender.log_event_count( metrics::MLME_RX_TX_FRAME_COUNTS_METRIC_ID, metrics::MlmeRxTxFrameCountsMetricDimensionFrameType::Tx as u32, 0, get_diff(last_stats.tx_frame.out.count, current_stats.tx_frame.out.count) as i64, ); sender.log_event_count( metrics::MLME_RX_TX_FRAME_BYTES_METRIC_ID, metrics::MlmeRxTxFrameBytesMetricDimensionFrameType::Rx as u32, 0, get_diff(last_stats.rx_frame.in_bytes.count, current_stats.rx_frame.in_bytes.count) as i64, ); sender.log_event_count( metrics::MLME_RX_TX_FRAME_BYTES_METRIC_ID, metrics::MlmeRxTxFrameBytesMetricDimensionFrameType::Tx as u32, 0, get_diff(last_stats.tx_frame.out_bytes.count, current_stats.tx_frame.out_bytes.count) as i64, ); } fn report_rssi_stats( rssi_metric_id: u32, last_stats: &fidl_stats::RssiStats, current_stats: &fidl_stats::RssiStats, sender: &mut CobaltSender, ) { // In the internal stats histogram, hist[x] represents the number of frames // with RSSI -x. For the Cobalt representation, buckets from -128 to 0 are // used. When data is sent to Cobalt, the concept of index is utilized. // // Shortly, for Cobalt: // Bucket -128 -> index 0 // Bucket -127 -> index 1 // ... // Bucket 0 -> index 128 // // The for loop below converts the stats internal representation to the // Cobalt representation and prepares the histogram that will be sent. let mut histogram = Vec::new(); for bin in 0..current_stats.hist.len() { let diff = get_diff(last_stats.hist[bin], current_stats.hist[bin]); if diff > 0 { let entry = HistogramBucket { index: (fidl_stats::RSSI_BINS - (bin as u8) - 1).into(), count: diff.into(), }; histogram.push(entry); } } if !histogram.is_empty() { sender.log_int_histogram(rssi_metric_id, (), histogram); } } pub fn report_scan_delay( sender: &mut CobaltSender, scan_started_time: zx::Time, scan_finished_time: zx::Time, ) { let delay_micros = (scan_finished_time - scan_started_time).into_micros(); sender.log_elapsed_time(metrics::SCAN_DELAY_METRIC_ID, (), delay_micros); } pub fn report_connection_delay( sender: &mut CobaltSender, conn_started_time: zx::Time, conn_finished_time: zx::Time, result: &ConnectResult, ) { use wlan_metrics_registry::ConnectionDelayMetricDimensionConnectionResult::{Fail, Success}; let delay_micros = (conn_finished_time - conn_started_time).into_micros(); let connection_result_cobalt = match result { ConnectResult::Success => Some(Success), ConnectResult::Canceled => Some(Fail), ConnectResult::Failed(failure) => convert_connect_failure(&failure), }; if let Some(connection_result_cobalt) = connection_result_cobalt { sender.log_elapsed_time( metrics::CONNECTION_DELAY_METRIC_ID, connection_result_cobalt as u32, delay_micros, ); } } pub fn report_assoc_success_delay( sender: &mut CobaltSender, assoc_started_time: zx::Time, assoc_finished_time: zx::Time, ) { let delay_micros = (assoc_finished_time - assoc_started_time).into_micros(); sender.log_elapsed_time(metrics::ASSOCIATION_DELAY_METRIC_ID, 0, delay_micros); } pub fn report_rsna_established_delay( sender: &mut CobaltSender, rsna_started_time: zx::Time, rsna_finished_time: zx::Time, ) { let delay_micros = (rsna_finished_time - rsna_started_time).into_micros(); sender.log_elapsed_time(metrics::RSNA_DELAY_METRIC_ID, 0, delay_micros); } pub fn report_neighbor_networks_count( sender: &mut CobaltSender, bss_count: usize, ess_count: usize, ) { sender.log_event_count( metrics::NEIGHBOR_NETWORKS_COUNT_METRIC_ID, metrics::NeighborNetworksCountMetricDimensionNetworkType::Bss as u32, 0, bss_count as i64, ); sender.log_event_count( metrics::NEIGHBOR_NETWORKS_COUNT_METRIC_ID, metrics::NeighborNetworksCountMetricDimensionNetworkType::Ess as u32, 0, ess_count as i64, ); } pub fn report_standards( sender: &mut CobaltSender, mut num_bss_by_standard: HashMap<Standard, usize>, ) { NEIGHBOR_NETWORKS_STANDARD_MAPPING.into_iter().for_each(|(standard, label)| { let count = match num_bss_by_standard.entry(standard.clone()) { Entry::Vacant(_) => 0 as i64, Entry::Occupied(e) => *e.get() as i64, }; sender.log_event_count( metrics::NEIGHBOR_NETWORKS_WLAN_STANDARDS_COUNT_METRIC_ID, label.clone() as u32, 0, count, ) }); } pub fn report_channels(sender: &mut CobaltSender, num_bss_by_channel: HashMap<u8, usize>) { num_bss_by_channel.into_iter().for_each(|(channel, count)| { sender.log_event_count( metrics::NEIGHBOR_NETWORKS_PRIMARY_CHANNELS_COUNT_METRIC_ID, channel as u32, 0, count as i64, ); }); } fn get_diff<T>(last_stat: T, current_stat: T) -> T where T: Sub<Output = T> + PartialOrd + Default, { if current_stat >= last_stat { current_stat - last_stat } else { Default::default() } } pub fn log_scan_stats(sender: &mut CobaltSender, scan_stats: &ScanStats, is_join_scan: bool) { let (scan_result_dim, error_code_dim) = convert_scan_result(&scan_stats.result); let scan_type_dim = convert_scan_type(scan_stats.scan_type); let is_join_scan_dim = convert_bool_dim(is_join_scan); let client_state_dim = match scan_stats.scan_start_while_connected { true => metrics::ScanResultMetricDimensionClientState::Connected, false => metrics::ScanResultMetricDimensionClientState::Idle, }; sender.log_event_count( metrics::SCAN_RESULT_METRIC_ID, [ scan_result_dim as u32, scan_type_dim as u32, is_join_scan_dim as u32, client_state_dim as u32, ], // Elapsed time during which the count of event has been gathered. We log 0 since // we don't keep track of this. 0, // Log one count of scan result. 1, ); if let Some(error_code_dim) = error_code_dim { sender.log_event_count( metrics::SCAN_FAILURE_METRIC_ID, [ error_code_dim as u32, scan_type_dim as u32, is_join_scan_dim as u32, client_state_dim as u32, ], 0, 1, ) } let scan_time = scan_stats.scan_time().into_micros(); sender.log_elapsed_time(metrics::SCAN_TIME_METRIC_ID, (), scan_time); sender.log_elapsed_time( metrics::SCAN_TIME_PER_RESULT_METRIC_ID, scan_result_dim as u32, scan_time, ); sender.log_elapsed_time( metrics::SCAN_TIME_PER_SCAN_TYPE_METRIC_ID, scan_type_dim as u32, scan_time, ); sender.log_elapsed_time( metrics::SCAN_TIME_PER_JOIN_OR_DISCOVERY_METRIC_ID, is_join_scan_dim as u32, scan_time, ); sender.log_elapsed_time( metrics::SCAN_TIME_PER_CLIENT_STATE_METRIC_ID, client_state_dim as u32, scan_time, ); } pub fn log_connect_stats(sender: &mut CobaltSender, connect_stats: &ConnectStats) { if let Some(scan_stats) = connect_stats.join_scan_stats() { log_scan_stats(sender, &scan_stats, true); } log_connect_attempts_stats(sender, connect_stats); log_connect_result_stats(sender, connect_stats); log_time_to_connect_stats(sender, connect_stats); log_connection_gap_time_stats(sender, connect_stats); } fn log_connect_attempts_stats(sender: &mut CobaltSender, connect_stats: &ConnectStats) { // Only log attempts for successful connect. If connect is not successful, or if the expected // fields for successful connect attempts are not there, early return. match connect_stats.result { ConnectResult::Success => (), _ => return, } let is_multi_bss = match &connect_stats.scan_end_stats { Some(stats) => stats.bss_count > 1, None => return, }; let bss = match &connect_stats.candidate_network { Some(bss) => bss, None => return, }; use metrics::ConnectionSuccessWithAttemptsBreakdownMetricDimensionAttempts::*; let attempts_dim = match connect_stats.attempts { 0 => { warn!("unexpected 0 attempts in connect stats"); return; } 1 => One, 2 => Two, 3 => Three, 4 => Four, 5 => Five, _ => MoreThanFive, }; let is_multi_bss_dim = convert_bool_dim(is_multi_bss); let protection_dim = convert_protection(&bss.get_protection()); let channel_band_dim = convert_channel_band(bss.chan.primary); sender.log_event_count( metrics::CONNECTION_ATTEMPTS_METRIC_ID, (), // no dimension 0, connect_stats.attempts as i64, ); sender.log_event_count( metrics::CONNECTION_SUCCESS_WITH_ATTEMPTS_BREAKDOWN_METRIC_ID, [ attempts_dim as u32, is_multi_bss_dim as u32, protection_dim as u32, channel_band_dim as u32, ], 0, 1, ); } fn log_connect_result_stats(sender: &mut CobaltSender, connect_stats: &ConnectStats) { let oui = connect_stats.candidate_network.as_ref().map(|bss| bss.bssid.to_oui_uppercase("")); let result_dim = convert_connection_result(&connect_stats.result); sender.with_component().log_event_count::<_, String, _>( metrics::CONNECTION_RESULT_METRIC_ID, result_dim as u32, oui.clone(), 0, 1, ); if let ConnectResult::Failed(failure) = &connect_stats.result { let fail_at_dim = convert_to_fail_at_dim(failure); let timeout_dim = convert_bool_dim(failure.is_timeout()); sender.with_component().log_event_count::<_, String, _>( metrics::CONNECTION_FAILURE_METRIC_ID, [fail_at_dim as u32, timeout_dim as u32], oui.clone(), 0, 1, ); if let ConnectFailure::SelectNetwork(select_network_failure) = failure { let error_reason_dim = convert_select_network_failure(&select_network_failure); sender.with_component().log_event_count::<_, String, _>( metrics::NETWORK_SELECTION_FAILURE_METRIC_ID, error_reason_dim as u32, oui, 0, 1, ); } } // For the remaining metrics, we expect scan result and candidate network to have been found let is_multi_bss = match &connect_stats.scan_end_stats { Some(stats) => stats.bss_count > 1, None => return, }; let bss = match &connect_stats.candidate_network { Some(bss) => bss, None => return, }; let oui = bss.bssid.to_oui_uppercase(""); let is_multi_bss_dim = convert_bool_dim(is_multi_bss); let protection_dim = convert_protection(&bss.get_protection()); let channel_band_dim = convert_channel_band(bss.chan.primary); let rssi_dim = convert_rssi(bss.rssi_dbm); sender.with_component().log_event_count( metrics::CONNECTION_RESULT_POST_NETWORK_SELECTION_METRIC_ID, [ result_dim as u32, is_multi_bss_dim as u32, protection_dim as u32, channel_band_dim as u32, ], oui.clone(), 0, 1, ); sender.with_component().log_event_count( metrics::CONNECTION_RESULT_PER_RSSI_METRIC_ID, [result_dim as u32, rssi_dim as u32], oui.clone(), 0, 1, ); match &connect_stats.result { ConnectResult::Failed(failure) => match failure { ConnectFailure::AuthenticationFailure(code) => { let error_code_dim = convert_auth_error_code(*code); sender.with_component().log_event_count( metrics::AUTHENTICATION_FAILURE_METRIC_ID, [ error_code_dim as u32, is_multi_bss_dim as u32, channel_band_dim as u32, protection_dim as u32, ], oui.clone(), 0, 1, ); sender.with_component().log_event_count( metrics::AUTHENTICATION_FAILURE_PER_RSSI_METRIC_ID, [error_code_dim as u32, rssi_dim as u32, channel_band_dim as u32], oui, 0, 1, ); } ConnectFailure::AssociationFailure(code) => { let error_code_dim = convert_assoc_error_code(*code); sender.with_component().log_event_count( metrics::ASSOCIATION_FAILURE_METRIC_ID, [error_code_dim as u32, protection_dim as u32], oui.clone(), 0, 1, ); sender.with_component().log_event_count( metrics::ASSOCIATION_FAILURE_PER_RSSI_METRIC_ID, [error_code_dim as u32, rssi_dim as u32, channel_band_dim as u32], oui, 0, 1, ); } ConnectFailure::EstablishRsna(..) => { sender.with_component().log_event_count( metrics::ESTABLISH_RSNA_FAILURE_METRIC_ID, protection_dim as u32, oui, 0, 1, ); } // Scan failure is already logged as part of scan stats. // Select network failure is already logged above. _ => (), }, _ => (), } } fn log_time_to_connect_stats(sender: &mut CobaltSender, connect_stats: &ConnectStats) { let connect_result_dim = convert_connection_result(&connect_stats.result); let rssi_dim = connect_stats.candidate_network.as_ref().map(|bss| convert_rssi(bss.rssi_dbm)); let connect_time = connect_stats.connect_time().into_micros(); sender.log_elapsed_time(metrics::CONNECTION_SETUP_TIME_METRIC_ID, (), connect_time); sender.log_elapsed_time( metrics::CONNECTION_SETUP_TIME_PER_RESULT_METRIC_ID, connect_result_dim as u32, connect_time, ); if let Some(connect_time_without_scan) = connect_stats.connect_time_without_scan() { sender.log_elapsed_time( metrics::CONNECTION_SETUP_TIME_WITHOUT_SCAN_METRIC_ID, (), connect_time_without_scan.into_micros(), ); sender.log_elapsed_time( metrics::CONNECTION_SETUP_TIME_WITHOUT_SCAN_PER_RESULT_METRIC_ID, connect_result_dim as u32, connect_time_without_scan.into_micros(), ); if let Some(rssi_dim) = rssi_dim { sender.log_elapsed_time( metrics::CONNECTION_SETUP_TIME_WITHOUT_SCAN_PER_RSSI_METRIC_ID, rssi_dim as u32, connect_time_without_scan.into_micros(), ) } } if let Some(time) = connect_stats.connect_queued_time() { sender.log_elapsed_time(metrics::CONNECTION_QUEUED_TIME_METRIC_ID, (), time.into_micros()); } if let Some(auth_time) = connect_stats.auth_time() { sender.log_elapsed_time( metrics::AUTHENTICATION_TIME_METRIC_ID, (), auth_time.into_micros(), ); if let Some(rssi_dim) = rssi_dim { sender.log_elapsed_time( metrics::AUTHENTICATION_TIME_PER_RSSI_METRIC_ID, rssi_dim as u32, auth_time.into_micros(), ) } } if let Some(assoc_time) = connect_stats.assoc_time() { sender.log_elapsed_time(metrics::ASSOCIATION_TIME_METRIC_ID, (), assoc_time.into_micros()); if let Some(rssi_dim) = rssi_dim { sender.log_elapsed_time( metrics::ASSOCIATION_TIME_PER_RSSI_METRIC_ID, rssi_dim as u32, assoc_time.into_micros(), ) } } if let Some(rsna_time) = connect_stats.rsna_time() { sender.log_elapsed_time( metrics::ESTABLISH_RSNA_TIME_METRIC_ID, (), rsna_time.into_micros(), ); if let Some(rssi_dim) = rssi_dim { sender.log_elapsed_time( metrics::ESTABLISH_RSNA_TIME_PER_RSSI_METRIC_ID, rssi_dim as u32, rsna_time.into_micros(), ) } } } pub fn log_connection_gap_time_stats(sender: &mut CobaltSender, connect_stats: &ConnectStats) { if connect_stats.result != ConnectResult::Success { return; } let ssid = match &connect_stats.candidate_network { Some(bss) => &bss.ssid, None => { warn!("No candidate_network in successful connect stats"); return; } }; if let Some(previous_disconnect_info) = &connect_stats.previous_disconnect_info { let duration = connect_stats.connect_end_at - previous_disconnect_info.disconnect_at; let ssids_dim = if ssid == &previous_disconnect_info.ssid { metrics::ConnectionGapTimeBreakdownMetricDimensionSsids::SameSsid } else { metrics::ConnectionGapTimeBreakdownMetricDimensionSsids::DifferentSsids }; let previous_disconnect_cause_dim = convert_disconnect_cause(&previous_disconnect_info.disconnect_cause); sender.log_elapsed_time(metrics::CONNECTION_GAP_TIME_METRIC_ID, (), duration.into_micros()); sender.log_elapsed_time( metrics::CONNECTION_GAP_TIME_BREAKDOWN_METRIC_ID, [ssids_dim as u32, previous_disconnect_cause_dim as u32], duration.into_micros(), ) } } pub fn log_connection_ping(sender: &mut CobaltSender, info: &ConnectionPingInfo) { for milestone in ConnectionMilestone::all().iter() { if info.connected_duration() >= milestone.min_duration() { let dur_dim = convert_connected_milestone(milestone); sender.log_event(metrics::CONNECTION_UPTIME_PING_METRIC_ID, dur_dim as u32); } } if info.reaches_new_milestone() { let dur_dim = convert_connected_milestone(&info.get_milestone()); sender.log_event_count( metrics::CONNECTION_COUNT_BY_DURATION_METRIC_ID, dur_dim as u32, 0, 1, ); } } pub fn log_connection_lost(sender: &mut CobaltSender, info: &ConnectionLostInfo) { use metrics::LostConnectionCountMetricDimensionConnectedTime::*; let duration_dim = match &info.connected_duration { x if x < &1.minutes() => LessThanOneMinute, x if x < &10.minutes() => LessThanTenMinutes, x if x < &30.minutes() => LessThanThirtyMinutes, x if x < &1.hour() => LessThanOneHour, x if x < &3.hours() => LessThanThreeHours, x if x < &6.hours() => LessThanSixHours, _ => AtLeastSixHours, }; let rssi_dim = convert_rssi(info.last_rssi); sender.with_component().log_event_count( metrics::LOST_CONNECTION_COUNT_METRIC_ID, [duration_dim as u32, rssi_dim as u32], info.bssid.to_oui_uppercase(""), 0, 1, ); } #[cfg(test)] mod tests { use { super::*, crate::{ device::{self, IfaceDevice}, mlme_query_proxy::MlmeQueryProxy, stats_scheduler::{self, StatsRequest}, }, fidl::endpoints::create_proxy, fidl_fuchsia_cobalt::{CobaltEvent, CountEvent, EventPayload}, fidl_fuchsia_wlan_common as fidl_common, fidl_fuchsia_wlan_mlme::{self as fidl_mlme, MlmeMarker}, fidl_fuchsia_wlan_stats::{Counter, DispatcherStats, IfaceStats, PacketCounter}, futures::channel::mpsc, maplit::hashset, pin_utils::pin_mut, std::collections::HashSet, wlan_common::assert_variant, wlan_sme::client::{ info::{ ConnectStats, ConnectionLostInfo, DisconnectCause, PreviousDisconnectInfo, ScanEndStats, ScanResult, ScanStartStats, SupplicantProgress, }, ConnectFailure, ConnectResult, EstablishRsnaFailure, SelectNetworkFailure, }, }; const IFACE_ID: u16 = 1; #[test] fn test_report_telemetry_periodically() { let mut exec = fasync::Executor::new().expect("Failed to create an executor"); let (ifaces_map, stats_requests) = fake_iface_map(); let (cobalt_sender, mut cobalt_receiver) = fake_cobalt_sender(); let telemetry_fut = report_telemetry_periodically(Arc::new(ifaces_map), cobalt_sender); pin_mut!(telemetry_fut); // Schedule the first stats request let _ = exec.run_until_stalled(&mut telemetry_fut); assert!(exec.wake_next_timer().is_some()); let _ = exec.run_until_stalled(&mut telemetry_fut); // Provide stats response let mut nth_req = 0; let mut stats_server = stats_requests.for_each(move |req| { nth_req += 1; future::ready(req.reply(fake_iface_stats(nth_req))) }); let _ = exec.run_until_stalled(&mut stats_server); // TODO(WLAN-1113): For some reason, telemetry skips logging the first stats response // Schedule the next stats request let _ = exec.run_until_stalled(&mut telemetry_fut); assert!(exec.wake_next_timer().is_some()); let _ = exec.run_until_stalled(&mut telemetry_fut); // Provide stats response let _ = exec.run_until_stalled(&mut stats_server); // Verify that stats are sent to Cobalt let _ = exec.run_until_stalled(&mut telemetry_fut); let mut expected_metrics = vec![ CobaltEvent { metric_id: metrics::DISPATCHER_PACKET_COUNTS_METRIC_ID, event_codes: vec![0], // in component: None, payload: event_count(1), }, CobaltEvent { metric_id: metrics::DISPATCHER_PACKET_COUNTS_METRIC_ID, event_codes: vec![1], // out component: None, payload: event_count(2), }, CobaltEvent { metric_id: metrics::DISPATCHER_PACKET_COUNTS_METRIC_ID, event_codes: vec![2], // dropped component: None, payload: event_count(3), }, CobaltEvent { metric_id: metrics::MLME_RX_TX_FRAME_COUNTS_METRIC_ID, event_codes: vec![0], // rx component: None, payload: event_count(1), }, CobaltEvent { metric_id: metrics::MLME_RX_TX_FRAME_COUNTS_METRIC_ID, event_codes: vec![1], // tx component: None, payload: event_count(2), }, CobaltEvent { metric_id: metrics::MLME_RX_TX_FRAME_BYTES_METRIC_ID, event_codes: vec![0], // rx component: None, payload: event_count(4), }, CobaltEvent { metric_id: metrics::MLME_RX_TX_FRAME_BYTES_METRIC_ID, event_codes: vec![1], // tx component: None, payload: event_count(5), }, CobaltEvent { metric_id: metrics::CLIENT_ASSOC_RSSI_METRIC_ID, event_codes: vec![], component: None, payload: EventPayload::IntHistogram(vec![HistogramBucket { index: 128, count: 1 }]), }, CobaltEvent { metric_id: metrics::CLIENT_BEACON_RSSI_METRIC_ID, event_codes: vec![], component: None, payload: EventPayload::IntHistogram(vec![HistogramBucket { index: 128, count: 1 }]), }, ]; while let Ok(Some(event)) = cobalt_receiver.try_next() { let index = expected_metrics.iter().position(|e| *e == event); assert!(index.is_some(), "unexpected event: {:?}", event); expected_metrics.remove(index.unwrap()); } assert!(expected_metrics.is_empty(), "some metrics not logged: {:?}", expected_metrics); } #[test] fn test_log_connect_stats_success() { let (mut cobalt_sender, mut cobalt_receiver) = fake_cobalt_sender(); log_connect_stats(&mut cobalt_sender, &fake_connect_stats()); let mut expected_metrics = hashset! { metrics::CONNECTION_ATTEMPTS_METRIC_ID, metrics::CONNECTION_SUCCESS_WITH_ATTEMPTS_BREAKDOWN_METRIC_ID, metrics::CONNECTION_RESULT_METRIC_ID, metrics::CONNECTION_RESULT_POST_NETWORK_SELECTION_METRIC_ID, metrics::CONNECTION_RESULT_PER_RSSI_METRIC_ID, metrics::SCAN_RESULT_METRIC_ID, metrics::CONNECTION_SETUP_TIME_METRIC_ID, metrics::CONNECTION_SETUP_TIME_PER_RESULT_METRIC_ID, metrics::CONNECTION_SETUP_TIME_WITHOUT_SCAN_METRIC_ID, metrics::CONNECTION_SETUP_TIME_WITHOUT_SCAN_PER_RESULT_METRIC_ID, metrics::CONNECTION_SETUP_TIME_WITHOUT_SCAN_PER_RSSI_METRIC_ID, metrics::SCAN_TIME_METRIC_ID, metrics::SCAN_TIME_PER_RESULT_METRIC_ID, metrics::SCAN_TIME_PER_SCAN_TYPE_METRIC_ID, metrics::SCAN_TIME_PER_JOIN_OR_DISCOVERY_METRIC_ID, metrics::SCAN_TIME_PER_CLIENT_STATE_METRIC_ID, metrics::AUTHENTICATION_TIME_METRIC_ID, metrics::AUTHENTICATION_TIME_PER_RSSI_METRIC_ID, metrics::ASSOCIATION_TIME_METRIC_ID, metrics::ASSOCIATION_TIME_PER_RSSI_METRIC_ID, metrics::ESTABLISH_RSNA_TIME_METRIC_ID, metrics::ESTABLISH_RSNA_TIME_PER_RSSI_METRIC_ID, metrics::CONNECTION_QUEUED_TIME_METRIC_ID, metrics::CONNECTION_GAP_TIME_METRIC_ID, metrics::CONNECTION_GAP_TIME_BREAKDOWN_METRIC_ID, }; while let Ok(Some(event)) = cobalt_receiver.try_next() { assert!(expected_metrics.contains(&event.metric_id), "unexpected event: {:?}", event); expected_metrics.remove(&event.metric_id); } assert!(expected_metrics.is_empty(), "some metrics not logged: {:?}", expected_metrics); } #[test] fn test_log_connect_stats_scan_failure() { // Note: This mock is not completely correct (e.g. we would not expect time stats for // later steps to be filled out if connect fails at scan), but for our testing // purpose, it's sufficient. The same applies for other connect stats failure // test cases. let connect_stats = ConnectStats { result: ConnectFailure::ScanFailure(fidl_mlme::ScanResultCodes::InvalidArgs).into(), scan_end_stats: Some(ScanEndStats { scan_end_at: now(), result: ScanResult::Failed(fidl_mlme::ScanResultCodes::InvalidArgs), bss_count: 1, }), ..fake_connect_stats() }; let expected_metrics_subset = hashset! { metrics::CONNECTION_RESULT_METRIC_ID, metrics::CONNECTION_FAILURE_METRIC_ID, metrics::SCAN_RESULT_METRIC_ID, metrics::SCAN_FAILURE_METRIC_ID, }; // These metrics are only logged when connection attempt succeeded. let unexpected_metrics = hashset! { metrics::CONNECTION_ATTEMPTS_METRIC_ID, metrics::CONNECTION_SUCCESS_WITH_ATTEMPTS_BREAKDOWN_METRIC_ID, }; test_metric_subset(&connect_stats, expected_metrics_subset, unexpected_metrics); } #[test] fn test_log_connect_stats_select_network_failure() { let connect_stats = ConnectStats { result: SelectNetworkFailure::NoCompatibleNetwork.into(), ..fake_connect_stats() }; let expected_metrics_subset = hashset! { metrics::CONNECTION_RESULT_METRIC_ID, metrics::CONNECTION_FAILURE_METRIC_ID, metrics::NETWORK_SELECTION_FAILURE_METRIC_ID, }; test_metric_subset(&connect_stats, expected_metrics_subset, hashset! {}); } #[test] fn test_log_connect_stats_auth_failure() { let connect_stats = ConnectStats { result: ConnectFailure::AuthenticationFailure( fidl_mlme::AuthenticateResultCodes::Refused, ) .into(), ..fake_connect_stats() }; let expected_metrics_subset = hashset! { metrics::CONNECTION_RESULT_METRIC_ID, metrics::CONNECTION_FAILURE_METRIC_ID, metrics::AUTHENTICATION_FAILURE_METRIC_ID, }; test_metric_subset(&connect_stats, expected_metrics_subset, hashset! {}); } #[test] fn test_log_connect_stats_assoc_failure() { let connect_stats = ConnectStats { result: ConnectFailure::AssociationFailure( fidl_mlme::AssociateResultCodes::RefusedReasonUnspecified, ) .into(), ..fake_connect_stats() }; let expected_metrics_subset = hashset! { metrics::CONNECTION_RESULT_METRIC_ID, metrics::CONNECTION_FAILURE_METRIC_ID, metrics::ASSOCIATION_FAILURE_METRIC_ID, }; test_metric_subset(&connect_stats, expected_metrics_subset, hashset! {}); } #[test] fn test_log_connect_stats_establish_rsna_failure() { let connect_stats = ConnectStats { result: EstablishRsnaFailure::OverallTimeout.into(), ..fake_connect_stats() }; let expected_metrics_subset = hashset! { metrics::CONNECTION_RESULT_METRIC_ID, metrics::CONNECTION_FAILURE_METRIC_ID, metrics::ESTABLISH_RSNA_FAILURE_METRIC_ID, }; test_metric_subset(&connect_stats, expected_metrics_subset, hashset! {}); } #[test] fn test_log_connection_ping() { use metrics::ConnectionCountByDurationMetricDimensionConnectedTime::*; let (mut cobalt_sender, mut cobalt_receiver) = fake_cobalt_sender(); let start = now(); let ping = ConnectionPingInfo::first_connected(start); log_connection_ping(&mut cobalt_sender, &ping); assert_ping_metrics(&mut cobalt_receiver, &[Connected as u32]); assert_variant!(cobalt_receiver.try_next(), Ok(Some(event)) => { assert_eq!(event.metric_id, metrics::CONNECTION_COUNT_BY_DURATION_METRIC_ID); assert_eq!(event.event_codes, vec![Connected as u32]) }); let ping = ping.next_ping(start + 1.minute()); log_connection_ping(&mut cobalt_sender, &ping); assert_ping_metrics(&mut cobalt_receiver, &[Connected as u32, ConnectedOneMinute as u32]); assert_variant!(cobalt_receiver.try_next(), Ok(Some(event)) => { assert_eq!(event.metric_id, metrics::CONNECTION_COUNT_BY_DURATION_METRIC_ID); assert_eq!(event.event_codes, vec![ConnectedOneMinute as u32]) }); let ping = ping.next_ping(start + 3.minutes()); log_connection_ping(&mut cobalt_sender, &ping); assert_ping_metrics(&mut cobalt_receiver, &[Connected as u32, ConnectedOneMinute as u32]); // check that CONNECTION_COUNT_BY_DURATION isn't logged since new milestone is not reached assert_variant!(cobalt_receiver.try_next(), Ok(None) | Err(..)); let ping = ping.next_ping(start + 10.minutes()); log_connection_ping(&mut cobalt_sender, &ping); assert_ping_metrics( &mut cobalt_receiver, &[Connected as u32, ConnectedOneMinute as u32, ConnectedTenMinute as u32], ); assert_variant!(cobalt_receiver.try_next(), Ok(Some(event)) => { assert_eq!(event.metric_id, metrics::CONNECTION_COUNT_BY_DURATION_METRIC_ID); assert_eq!(event.event_codes, vec![ConnectedTenMinute as u32]) }); } fn assert_ping_metrics(cobalt_receiver: &mut mpsc::Receiver<CobaltEvent>, milestones: &[u32]) { for milestone in milestones { assert_variant!(cobalt_receiver.try_next(), Ok(Some(event)) => { assert_eq!(event.metric_id, metrics::CONNECTION_UPTIME_PING_METRIC_ID); assert_eq!(event.event_codes, vec![*milestone]); }); } } #[test] fn test_log_connection_lost_info() { let (mut cobalt_sender, mut cobalt_receiver) = fake_cobalt_sender(); let connection_lost_info = ConnectionLostInfo { connected_duration: 30.seconds(), bssid: [1u8; 6], last_rssi: -90, }; log_connection_lost(&mut cobalt_sender, &connection_lost_info); assert_variant!(cobalt_receiver.try_next(), Ok(Some(event)) => { assert_eq!(event.metric_id, metrics::LOST_CONNECTION_COUNT_METRIC_ID); }); } fn test_metric_subset( connect_stats: &ConnectStats, mut expected_metrics_subset: HashSet<u32>, unexpected_metrics: HashSet<u32>, ) { let (mut cobalt_sender, mut cobalt_receiver) = fake_cobalt_sender(); log_connect_stats(&mut cobalt_sender, connect_stats); while let Ok(Some(event)) = cobalt_receiver.try_next() { assert!( !unexpected_metrics.contains(&event.metric_id), "unexpected event: {:?}", event ); if expected_metrics_subset.contains(&event.metric_id) { expected_metrics_subset.remove(&event.metric_id); } } assert!( expected_metrics_subset.is_empty(), "some metrics not logged: {:?}", expected_metrics_subset ); } fn now() -> zx::Time { zx::Time::get(zx::ClockId::Monotonic) } fn fake_connect_stats() -> ConnectStats { let now = now(); ConnectStats { connect_start_at: now, connect_end_at: now, scan_start_stats: Some(ScanStartStats { scan_start_at: now, scan_type: fidl_mlme::ScanTypes::Passive, scan_start_while_connected: false, }), scan_end_stats: Some(ScanEndStats { scan_end_at: now, result: ScanResult::Success, bss_count: 1, }), auth_start_at: Some(now), auth_end_at: Some(now), assoc_start_at: Some(now), assoc_end_at: Some(now), rsna_start_at: Some(now), rsna_end_at: Some(now), supplicant_error: None, supplicant_progress: Some(SupplicantProgress { pmksa_established: true, ptksa_established: true, gtksa_established: true, esssa_established: true, }), num_rsna_key_frame_exchange_timeout: 0, result: ConnectResult::Success, candidate_network: Some(fake_bss_description()), attempts: 1, last_ten_failures: vec![], previous_disconnect_info: Some(PreviousDisconnectInfo { ssid: fake_bss_description().ssid, disconnect_cause: DisconnectCause::Manual, disconnect_at: now - 10.seconds(), }), } } fn fake_bss_description() -> fidl_mlme::BssDescription { fidl_mlme::BssDescription { bssid: [7, 1, 2, 77, 53, 8], ssid: b"foo".to_vec(), bss_type: fidl_mlme::BssTypes::Infrastructure, beacon_period: 100, dtim_period: 100, timestamp: 0, local_time: 0, cap: wlan_common::mac::CapabilityInfo(0).0, rates: vec![], country: None, rsne: None, vendor_ies: None, rcpi_dbmh: 0, rsni_dbh: 0, ht_cap: None, ht_op: None, vht_cap: None, vht_op: None, chan: fidl_common::WlanChan { primary: 1, secondary80: 0, cbw: fidl_common::Cbw::Cbw20, }, rssi_dbm: 0, } } fn event_count(count: i64) -> EventPayload { EventPayload::EventCount(CountEvent { period_duration_micros: 0, count }) } fn fake_iface_stats(nth_req: u64) -> IfaceStats { IfaceStats { dispatcher_stats: DispatcherStats { any_packet: fake_packet_counter(nth_req), mgmt_frame: fake_packet_counter(nth_req), ctrl_frame: fake_packet_counter(nth_req), data_frame: fake_packet_counter(nth_req), }, mlme_stats: Some(Box::new(ClientMlmeStats(fidl_stats::ClientMlmeStats { svc_msg: fake_packet_counter(nth_req), data_frame: fake_packet_counter(nth_req), mgmt_frame: fake_packet_counter(nth_req), tx_frame: fake_packet_counter(nth_req), rx_frame: fake_packet_counter(nth_req), assoc_data_rssi: fake_rssi(nth_req), beacon_rssi: fake_rssi(nth_req), }))), } } fn fake_packet_counter(nth_req: u64) -> PacketCounter { PacketCounter { in_: Counter { count: 1 * nth_req, name: "in".to_string() }, out: Counter { count: 2 * nth_req, name: "out".to_string() }, drop: Counter { count: 3 * nth_req, name: "drop".to_string() }, in_bytes: Counter { count: 4 * nth_req, name: "in_bytes".to_string() }, out_bytes: Counter { count: 5 * nth_req, name: "out_bytes".to_string() }, drop_bytes: Counter { count: 6 * nth_req, name: "drop_bytes".to_string() }, } } fn fake_rssi(nth_req: u64) -> fidl_stats::RssiStats { fidl_stats::RssiStats { hist: vec![nth_req] } } fn fake_iface_map() -> (IfaceMap, impl Stream<Item = StatsRequest>) { let (ifaces_map, _watcher) = IfaceMap::new(); let (iface_device, stats_requests) = fake_iface_device(); ifaces_map.insert(IFACE_ID, iface_device); (ifaces_map, stats_requests) } fn fake_iface_device() -> (IfaceDevice, impl Stream<Item = StatsRequest>) { let (sme_sender, _sme_receiver) = mpsc::unbounded(); let (stats_sched, stats_requests) = stats_scheduler::create_scheduler(); let (proxy, _server) = create_proxy::<MlmeMarker>().expect("Error creating proxy"); let mlme_query = MlmeQueryProxy::new(proxy); let device_info = fake_device_info(); let iface_device = IfaceDevice { phy_ownership: device::DirectMlmeChannel::NotSupported, sme_server: device::SmeServer::Client(sme_sender), stats_sched, device: None, mlme_query, device_info, }; (iface_device, stats_requests) } fn fake_device_info() -> fidl_mlme::DeviceInfo { fidl_mlme::DeviceInfo { role: fidl_mlme::MacRole::Client, bands: vec![], mac_addr: [0xAC; 6], driver_features: vec![], } } fn fake_cobalt_sender() -> (CobaltSender, mpsc::Receiver<CobaltEvent>) { const BUFFER_SIZE: usize = 100; let (sender, receiver) = mpsc::channel(BUFFER_SIZE); (CobaltSender::new(sender), receiver) } }
extern crate enet; use enet::*; use std::net::Ipv4Addr; use std::time::Duration; fn main() { let enet = Enet::new().expect("could not initialize ENet"); let local_addr = Address::new(Ipv4Addr::LOCALHOST, 9001); let mut host = enet .create_host::<()>( Some(&local_addr), 10, ChannelLimit::Maximum, BandwidthLimit::Unlimited, BandwidthLimit::Unlimited, ) .expect("could not create host"); loop { // Wait 500 ms for any events. if let Some(Event { kind, .. }) = host .service(Duration::from_millis(500)) .expect("service failed") { match kind { EventKind::Connect => println!("new connection!"), EventKind::Disconnect { .. } => println!("disconnect!"), EventKind::Receive { channel_id, packet } => println!( "got packet on channel {}, content: '{}'", channel_id, std::str::from_utf8(packet.data()).unwrap() ), } } } }
#![doc(html_logo_url = "https://raw.githubusercontent.com/georust/meta/master/logo/logo.png")] //! The `geo-types` library provides geospatial primitive types and traits to the [`GeoRust`](https://github.com/georust) //! crate ecosystem. //! //! In most cases, you will only need to use this crate if you're a crate author and want compatibility //! with other `GeoRust` crates. Otherwise, the [`geo`](https://crates.io/crates/geo) crate re-exports these types and //! provides geospatial algorithms, while the [`geojson`](https://crates.io/crates/geojson) crate allows serialising //! and de-serialising `geo-types` primitives to GeoJSON. extern crate num_traits; #[cfg(feature = "serde")] #[macro_use] extern crate serde; #[cfg(feature = "rstar")] extern crate rstar; use num_traits::{Num, NumCast}; /// The type of an x or y value of a point/coordinate. /// /// Floats (`f32` and `f64`) and Integers (`u8`, `i32` etc.) implement this. Many algorithms only /// make sense for Float types (like area, or length calculations). pub trait CoordinateType: Num + Copy + NumCast + PartialOrd {} // Little bit of a hack to make to make this work impl<T: Num + Copy + NumCast + PartialOrd> CoordinateType for T {} mod coordinate; pub use crate::coordinate::Coordinate; mod point; pub use crate::point::Point; mod multi_point; pub use crate::multi_point::MultiPoint; mod line; pub use crate::line::Line; mod line_string; pub use crate::line_string::{LineString, PointsIter}; mod multi_line_string; pub use crate::multi_line_string::MultiLineString; mod polygon; pub use crate::polygon::Polygon; mod multi_polygon; pub use crate::multi_polygon::MultiPolygon; mod geometry; pub use crate::geometry::Geometry; mod geometry_collection; pub use crate::geometry_collection::GeometryCollection; mod triangle; pub use crate::triangle::Triangle; mod rect; pub use crate::rect::Rect; #[macro_use] mod macros; #[doc(hidden)] pub mod private_utils; #[cfg(test)] #[macro_use] extern crate approx; #[cfg(test)] mod tests { use super::*; use std::convert::TryFrom; #[test] fn type_test() { let c = Coordinate { x: 40.02f64, y: 116.34, }; let p = Point(c); let Point(c2) = p; assert_eq!(c, c2); assert_relative_eq!(c.x, c2.x); assert_relative_eq!(c.y, c2.y); let p: Point<f32> = (0f32, 1f32).into(); assert_relative_eq!(p.x(), 0.); assert_relative_eq!(p.y(), 1.); } #[test] fn convert_types() { let p: Point<f32> = Point::new(0., 0.); let p1 = p.clone(); let g: Geometry<f32> = p.into(); let p2 = Point::try_from(g).unwrap(); assert_eq!(p1, p2); } #[test] fn polygon_new_test() { let exterior = LineString(vec![ Coordinate { x: 0., y: 0. }, Coordinate { x: 1., y: 1. }, Coordinate { x: 1., y: 0. }, Coordinate { x: 0., y: 0. }, ]); let interiors = vec![LineString(vec![ Coordinate { x: 0.1, y: 0.1 }, Coordinate { x: 0.9, y: 0.9 }, Coordinate { x: 0.9, y: 0.1 }, Coordinate { x: 0.1, y: 0.1 }, ])]; let p = Polygon::new(exterior.clone(), interiors.clone()); assert_eq!(p.exterior(), &exterior); assert_eq!(p.interiors(), &interiors[..]); } #[test] fn iters() { let _: MultiPoint<_> = vec![(0., 0.), (1., 2.)].into(); let _: MultiPoint<_> = vec![(0., 0.), (1., 2.)].into_iter().collect(); let mut l1: LineString<_> = vec![(0., 0.), (1., 2.)].into(); assert_eq!(l1[1], Coordinate { x: 1., y: 2. }); // index into linestring let _: LineString<_> = vec![(0., 0.), (1., 2.)].into_iter().collect(); // index mutably into a linestring l1[0] = Coordinate { x: 1., y: 1. }; assert_eq!(l1, vec![(1., 1.), (1., 2.)].into()); } #[test] fn test_coordinate_types() { let p: Point<u8> = Point::new(0, 0); assert_eq!(p.x(), 0u8); let p: Point<i64> = Point::new(1_000_000, 0); assert_eq!(p.x(), 1_000_000i64); } #[cfg(feature = "rstar")] #[test] /// ensure Line's SpatialObject impl is correct fn line_test() { use rstar::primitives::Line as RStarLine; use rstar::{PointDistance, RTreeObject}; let rl = RStarLine::new(Point::new(0.0, 0.0), Point::new(5.0, 5.0)); let l = Line::new(Coordinate { x: 0.0, y: 0.0 }, Coordinate { x: 5., y: 5. }); assert_eq!(rl.envelope(), l.envelope()); // difference in 15th decimal place assert_relative_eq!(26.0, rl.distance_2(&Point::new(4.0, 10.0))); assert_relative_eq!(25.999999999999996, l.distance_2(&Point::new(4.0, 10.0))); } #[test] fn test_rects() { let r = Rect::new(Coordinate { x: -1., y: -1. }, Coordinate { x: 1., y: 1. }); let p: Polygon<_> = r.into(); assert_eq!( p, Polygon::new( vec![(-1., -1.), (1., -1.), (1., 1.), (-1., 1.), (-1., -1.)].into(), vec![] ) ); } }
//! An abstraction for a source of [`PartitionData`]. //! //! This abstraction allows code that uses a set of [`PartitionData`] to be //! decoupled from the source/provider of that data. use parking_lot::Mutex; use std::{fmt::Debug, sync::Arc}; use crate::buffer_tree::partition::PartitionData; /// An abstraction over any type that can yield an iterator of (potentially /// empty) [`PartitionData`]. pub trait PartitionIter: Send + Debug { /// Return the set of partitions in `self`. fn partition_iter(&self) -> Box<dyn Iterator<Item = Arc<Mutex<PartitionData>>> + Send>; } impl<T> PartitionIter for Arc<T> where T: PartitionIter + Send + Sync, { fn partition_iter(&self) -> Box<dyn Iterator<Item = Arc<Mutex<PartitionData>>> + Send> { (**self).partition_iter() } } impl PartitionIter for Vec<Arc<Mutex<PartitionData>>> { fn partition_iter(&self) -> Box<dyn Iterator<Item = Arc<Mutex<PartitionData>>> + Send> { Box::new(self.clone().into_iter()) } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![macro_use] use alloc::string::String; use super::task::*; use super::qlib::vcpu_mgr::*; use super::asm::*; pub const SCALE : i64 = 2_000; pub fn PrintPrefix() -> String { return format!("[{}/{:x}|{}] ", CPULocal::CpuId() , Task::TaskId().Addr(), Rdtsc()/SCALE); } #[macro_export] macro_rules! print { ($($arg:tt)*) => ({ if $crate::SHARESPACE.config.DebugLevel >= $crate::qlib::config::DebugLevel::Error { //$crate::qlib::perf_tunning::PerfGoto($crate::qlib::perf_tunning::PerfType::Print); let mut s = $crate::print::PrintPrefix(); s += &format!($($arg)*); //s += "\n"; $crate::Kernel::HostSpace::SlowPrint($crate::qlib::config::DebugLevel::Error, &s); //$crate::qlib::perf_tunning::PerfGofrom($crate::qlib::perf_tunning::PerfType::Print); } }); } #[macro_export] macro_rules! error { ($($arg:tt)*) => ({ if $crate::SHARESPACE.config.DebugLevel >= $crate::qlib::config::DebugLevel::Error { //$crate::qlib::perf_tunning::PerfGoto($crate::qlib::perf_tunning::PerfType::Print); let mut s = $crate::print::PrintPrefix(); s += &format!($($arg)*); if $crate::SHARESPACE.config.SlowPrint { $crate::Kernel::HostSpace::SlowPrint($crate::qlib::config::DebugLevel::Error, &s); } else { $crate::Kernel::HostSpace::Kprint($crate::qlib::config::DebugLevel::Error, &s); } //$crate::qlib::perf_tunning::PerfGofrom($crate::qlib::perf_tunning::PerfType::Print); } }); } #[macro_export] macro_rules! info { ($($arg:tt)*) => ({ if $crate::SHARESPACE.config.DebugLevel >= $crate::qlib::config::DebugLevel::Info { //$crate::qlib::perf_tunning::PerfGoto($crate::qlib::perf_tunning::PerfType::Print); let mut s = $crate::print::PrintPrefix(); s += &format!($($arg)*); if $crate::SHARESPACE.config.SlowPrint { $crate::Kernel::HostSpace::SlowPrint($crate::qlib::config::DebugLevel::Error, &s); } else { $crate::Kernel::HostSpace::Kprint($crate::qlib::config::DebugLevel::Error, &s); } //$crate::qlib::perf_tunning::PerfGofrom($crate::qlib::perf_tunning::PerfType::Print); } }); } #[macro_export] macro_rules! debug { ($($arg:tt)*) => ({ if $crate::SHARESPACE.config.DebugLevel >= $crate::qlib::config::DebugLevel::Debug { //$crate::qlib::perf_tunning::PerfGoto($crate::qlib::perf_tunning::PerfType::Print); let mut s = $crate::print::PrintPrefix(); s += &format!($($arg)*); if $crate::SHARESPACE.config.SlowPrint { $crate::Kernel::HostSpace::SlowPrint($crate::qlib::config::DebugLevel::Error, &s); } else { $crate::Kernel::HostSpace::Kprint($crate::qlib::config::DebugLevel::Error, &s); } //$crate::qlib::perf_tunning::PerfGofrom($crate::qlib::perf_tunning::PerfType::Print); } }); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Clock control register"] pub cr: CR, #[doc = "0x04 - Clock configuration register (RCC_CFGR)"] pub cfgr: CFGR, #[doc = "0x08 - Clock interrupt register (RCC_CIR)"] pub cir: CIR, #[doc = "0x0c - APB2 peripheral reset register (RCC_APB2RSTR)"] pub apb2rstr: APB2RSTR, #[doc = "0x10 - APB1 peripheral reset register (RCC_APB1RSTR)"] pub apb1rstr: APB1RSTR, #[doc = "0x14 - AHB Peripheral Clock enable register (RCC_AHBENR)"] pub ahbenr: AHBENR, #[doc = "0x18 - APB2 peripheral clock enable register (RCC_APB2ENR)"] pub apb2enr: APB2ENR, #[doc = "0x1c - APB1 peripheral clock enable register (RCC_APB1ENR)"] pub apb1enr: APB1ENR, #[doc = "0x20 - Backup domain control register (RCC_BDCR)"] pub bdcr: BDCR, #[doc = "0x24 - Control/status register (RCC_CSR)"] pub csr: CSR, #[doc = "0x28 - AHB peripheral clock reset register (RCC_AHBRSTR)"] pub ahbrstr: AHBRSTR, #[doc = "0x2c - Clock configuration register2 (RCC_CFGR2)"] pub cfgr2: CFGR2, } #[doc = "Clock control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"] pub type CR = crate::Reg<u32, _CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CR; #[doc = "`read()` method returns [cr::R](cr::R) reader structure"] impl crate::Readable for CR {} #[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"] impl crate::Writable for CR {} #[doc = "Clock control register"] pub mod cr; #[doc = "Clock configuration register (RCC_CFGR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cfgr](cfgr) module"] pub type CFGR = crate::Reg<u32, _CFGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFGR; #[doc = "`read()` method returns [cfgr::R](cfgr::R) reader structure"] impl crate::Readable for CFGR {} #[doc = "`write(|w| ..)` method takes [cfgr::W](cfgr::W) writer structure"] impl crate::Writable for CFGR {} #[doc = "Clock configuration register (RCC_CFGR)"] pub mod cfgr; #[doc = "Clock interrupt register (RCC_CIR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cir](cir) module"] pub type CIR = crate::Reg<u32, _CIR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CIR; #[doc = "`read()` method returns [cir::R](cir::R) reader structure"] impl crate::Readable for CIR {} #[doc = "`write(|w| ..)` method takes [cir::W](cir::W) writer structure"] impl crate::Writable for CIR {} #[doc = "Clock interrupt register (RCC_CIR)"] pub mod cir; #[doc = "APB2 peripheral reset register (RCC_APB2RSTR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb2rstr](apb2rstr) module"] pub type APB2RSTR = crate::Reg<u32, _APB2RSTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB2RSTR; #[doc = "`read()` method returns [apb2rstr::R](apb2rstr::R) reader structure"] impl crate::Readable for APB2RSTR {} #[doc = "`write(|w| ..)` method takes [apb2rstr::W](apb2rstr::W) writer structure"] impl crate::Writable for APB2RSTR {} #[doc = "APB2 peripheral reset register (RCC_APB2RSTR)"] pub mod apb2rstr; #[doc = "APB1 peripheral reset register (RCC_APB1RSTR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1rstr](apb1rstr) module"] pub type APB1RSTR = crate::Reg<u32, _APB1RSTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB1RSTR; #[doc = "`read()` method returns [apb1rstr::R](apb1rstr::R) reader structure"] impl crate::Readable for APB1RSTR {} #[doc = "`write(|w| ..)` method takes [apb1rstr::W](apb1rstr::W) writer structure"] impl crate::Writable for APB1RSTR {} #[doc = "APB1 peripheral reset register (RCC_APB1RSTR)"] pub mod apb1rstr; #[doc = "AHB Peripheral Clock enable register (RCC_AHBENR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahbenr](ahbenr) module"] pub type AHBENR = crate::Reg<u32, _AHBENR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _AHBENR; #[doc = "`read()` method returns [ahbenr::R](ahbenr::R) reader structure"] impl crate::Readable for AHBENR {} #[doc = "`write(|w| ..)` method takes [ahbenr::W](ahbenr::W) writer structure"] impl crate::Writable for AHBENR {} #[doc = "AHB Peripheral Clock enable register (RCC_AHBENR)"] pub mod ahbenr; #[doc = "APB2 peripheral clock enable register (RCC_APB2ENR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb2enr](apb2enr) module"] pub type APB2ENR = crate::Reg<u32, _APB2ENR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB2ENR; #[doc = "`read()` method returns [apb2enr::R](apb2enr::R) reader structure"] impl crate::Readable for APB2ENR {} #[doc = "`write(|w| ..)` method takes [apb2enr::W](apb2enr::W) writer structure"] impl crate::Writable for APB2ENR {} #[doc = "APB2 peripheral clock enable register (RCC_APB2ENR)"] pub mod apb2enr; #[doc = "APB1 peripheral clock enable register (RCC_APB1ENR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1enr](apb1enr) module"] pub type APB1ENR = crate::Reg<u32, _APB1ENR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _APB1ENR; #[doc = "`read()` method returns [apb1enr::R](apb1enr::R) reader structure"] impl crate::Readable for APB1ENR {} #[doc = "`write(|w| ..)` method takes [apb1enr::W](apb1enr::W) writer structure"] impl crate::Writable for APB1ENR {} #[doc = "APB1 peripheral clock enable register (RCC_APB1ENR)"] pub mod apb1enr; #[doc = "Backup domain control register (RCC_BDCR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdcr](bdcr) module"] pub type BDCR = crate::Reg<u32, _BDCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BDCR; #[doc = "`read()` method returns [bdcr::R](bdcr::R) reader structure"] impl crate::Readable for BDCR {} #[doc = "`write(|w| ..)` method takes [bdcr::W](bdcr::W) writer structure"] impl crate::Writable for BDCR {} #[doc = "Backup domain control register (RCC_BDCR)"] pub mod bdcr; #[doc = "Control/status register (RCC_CSR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [csr](csr) module"] pub type CSR = crate::Reg<u32, _CSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CSR; #[doc = "`read()` method returns [csr::R](csr::R) reader structure"] impl crate::Readable for CSR {} #[doc = "`write(|w| ..)` method takes [csr::W](csr::W) writer structure"] impl crate::Writable for CSR {} #[doc = "Control/status register (RCC_CSR)"] pub mod csr; #[doc = "AHB peripheral clock reset register (RCC_AHBRSTR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahbrstr](ahbrstr) module"] pub type AHBRSTR = crate::Reg<u32, _AHBRSTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _AHBRSTR; #[doc = "`read()` method returns [ahbrstr::R](ahbrstr::R) reader structure"] impl crate::Readable for AHBRSTR {} #[doc = "`write(|w| ..)` method takes [ahbrstr::W](ahbrstr::W) writer structure"] impl crate::Writable for AHBRSTR {} #[doc = "AHB peripheral clock reset register (RCC_AHBRSTR)"] pub mod ahbrstr; #[doc = "Clock configuration register2 (RCC_CFGR2)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cfgr2](cfgr2) module"] pub type CFGR2 = crate::Reg<u32, _CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFGR2; #[doc = "`read()` method returns [cfgr2::R](cfgr2::R) reader structure"] impl crate::Readable for CFGR2 {} #[doc = "`write(|w| ..)` method takes [cfgr2::W](cfgr2::W) writer structure"] impl crate::Writable for CFGR2 {} #[doc = "Clock configuration register2 (RCC_CFGR2)"] pub mod cfgr2;
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qcommandlinkbutton.h // dst-file: /src/widgets/qcommandlinkbutton.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::qpushbutton::*; // 773 use std::ops::Deref; use super::super::core::qstring::*; // 771 use super::qwidget::*; // 773 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QCommandLinkButton_Class_Size() -> c_int; // proto: void QCommandLinkButton::QCommandLinkButton(const QString & text, const QString & description, QWidget * parent); fn C_ZN18QCommandLinkButtonC2ERK7QStringS2_P7QWidget(arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> u64; // proto: const QMetaObject * QCommandLinkButton::metaObject(); fn C_ZNK18QCommandLinkButton10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCommandLinkButton::~QCommandLinkButton(); fn C_ZN18QCommandLinkButtonD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QCommandLinkButton::QCommandLinkButton(QWidget * parent); fn C_ZN18QCommandLinkButtonC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: QString QCommandLinkButton::description(); fn C_ZNK18QCommandLinkButton11descriptionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCommandLinkButton::QCommandLinkButton(const QString & text, QWidget * parent); fn C_ZN18QCommandLinkButtonC2ERK7QStringP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64; // proto: void QCommandLinkButton::setDescription(const QString & description); fn C_ZN18QCommandLinkButton14setDescriptionERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QCommandLinkButton)=1 #[derive(Default)] pub struct QCommandLinkButton { qbase: QPushButton, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QCommandLinkButton { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QCommandLinkButton { return QCommandLinkButton{qbase: QPushButton::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QCommandLinkButton { type Target = QPushButton; fn deref(&self) -> &QPushButton { return & self.qbase; } } impl AsRef<QPushButton> for QCommandLinkButton { fn as_ref(& self) -> & QPushButton { return & self.qbase; } } // proto: void QCommandLinkButton::QCommandLinkButton(const QString & text, const QString & description, QWidget * parent); impl /*struct*/ QCommandLinkButton { pub fn new<T: QCommandLinkButton_new>(value: T) -> QCommandLinkButton { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QCommandLinkButton_new { fn new(self) -> QCommandLinkButton; } // proto: void QCommandLinkButton::QCommandLinkButton(const QString & text, const QString & description, QWidget * parent); impl<'a> /*trait*/ QCommandLinkButton_new for (&'a QString, &'a QString, Option<&'a QWidget>) { fn new(self) -> QCommandLinkButton { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLinkButtonC2ERK7QStringS2_P7QWidget()}; let ctysz: c_int = unsafe{QCommandLinkButton_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = (if self.2.is_none() {0} else {self.2.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN18QCommandLinkButtonC2ERK7QStringS2_P7QWidget(arg0, arg1, arg2)}; let rsthis = QCommandLinkButton{qbase: QPushButton::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: const QMetaObject * QCommandLinkButton::metaObject(); impl /*struct*/ QCommandLinkButton { pub fn metaObject<RetType, T: QCommandLinkButton_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QCommandLinkButton_metaObject<RetType> { fn metaObject(self , rsthis: & QCommandLinkButton) -> RetType; } // proto: const QMetaObject * QCommandLinkButton::metaObject(); impl<'a> /*trait*/ QCommandLinkButton_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QCommandLinkButton) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLinkButton10metaObjectEv()}; let mut ret = unsafe {C_ZNK18QCommandLinkButton10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCommandLinkButton::~QCommandLinkButton(); impl /*struct*/ QCommandLinkButton { pub fn free<RetType, T: QCommandLinkButton_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QCommandLinkButton_free<RetType> { fn free(self , rsthis: & QCommandLinkButton) -> RetType; } // proto: void QCommandLinkButton::~QCommandLinkButton(); impl<'a> /*trait*/ QCommandLinkButton_free<()> for () { fn free(self , rsthis: & QCommandLinkButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLinkButtonD2Ev()}; unsafe {C_ZN18QCommandLinkButtonD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QCommandLinkButton::QCommandLinkButton(QWidget * parent); impl<'a> /*trait*/ QCommandLinkButton_new for (Option<&'a QWidget>) { fn new(self) -> QCommandLinkButton { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLinkButtonC2EP7QWidget()}; let ctysz: c_int = unsafe{QCommandLinkButton_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_ZN18QCommandLinkButtonC2EP7QWidget(arg0)}; let rsthis = QCommandLinkButton{qbase: QPushButton::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QString QCommandLinkButton::description(); impl /*struct*/ QCommandLinkButton { pub fn description<RetType, T: QCommandLinkButton_description<RetType>>(& self, overload_args: T) -> RetType { return overload_args.description(self); // return 1; } } pub trait QCommandLinkButton_description<RetType> { fn description(self , rsthis: & QCommandLinkButton) -> RetType; } // proto: QString QCommandLinkButton::description(); impl<'a> /*trait*/ QCommandLinkButton_description<QString> for () { fn description(self , rsthis: & QCommandLinkButton) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK18QCommandLinkButton11descriptionEv()}; let mut ret = unsafe {C_ZNK18QCommandLinkButton11descriptionEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCommandLinkButton::QCommandLinkButton(const QString & text, QWidget * parent); impl<'a> /*trait*/ QCommandLinkButton_new for (&'a QString, Option<&'a QWidget>) { fn new(self) -> QCommandLinkButton { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLinkButtonC2ERK7QStringP7QWidget()}; let ctysz: c_int = unsafe{QCommandLinkButton_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN18QCommandLinkButtonC2ERK7QStringP7QWidget(arg0, arg1)}; let rsthis = QCommandLinkButton{qbase: QPushButton::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QCommandLinkButton::setDescription(const QString & description); impl /*struct*/ QCommandLinkButton { pub fn setDescription<RetType, T: QCommandLinkButton_setDescription<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDescription(self); // return 1; } } pub trait QCommandLinkButton_setDescription<RetType> { fn setDescription(self , rsthis: & QCommandLinkButton) -> RetType; } // proto: void QCommandLinkButton::setDescription(const QString & description); impl<'a> /*trait*/ QCommandLinkButton_setDescription<()> for (&'a QString) { fn setDescription(self , rsthis: & QCommandLinkButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN18QCommandLinkButton14setDescriptionERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN18QCommandLinkButton14setDescriptionERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // <= body block end
use crate::io_utils::{MemMap, Writer}; use crate::mapper::{Kind, Mapper, RwLockExt}; use crate::sstable::SSTable; use crate::Result; use memmap::Mmap; use rand::{rngs::SmallRng, seq::SliceRandom, FromEntropy, Rng}; use std::collections::HashMap; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufReader, BufWriter}; use std::path::{Path, PathBuf}; use std::sync::{Arc, RwLock}; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] struct Id { id: u32, kind: Kind, } #[derive(Debug)] pub struct Disk { rng: RwLock<SmallRng>, mappings: RwLock<HashMap<Id, PathInfo>>, storage_dirs: RwLock<Vec<PathBuf>>, } impl Disk { pub fn single(dir: &Path) -> Self { Disk::new(&[dir]) } pub fn new<P: AsRef<Path>>(storage_dirs: &[P]) -> Self { if storage_dirs.is_empty() { panic!("Disk Mapper requires at least one storage director"); } let storage_dirs = storage_dirs .iter() .map(AsRef::as_ref) .map(Path::to_path_buf) .collect(); Disk { storage_dirs: RwLock::new(storage_dirs), mappings: RwLock::new(HashMap::new()), rng: RwLock::new(SmallRng::from_entropy()), } } } #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] pub struct PathInfo { pub data: PathBuf, pub index: PathBuf, } impl Disk { #[inline] fn choose_storage(&self) -> PathBuf { let mut rng = rand::thread_rng(); let path = self .storage_dirs .read_as(|storage| storage.choose(&mut rng).unwrap().to_path_buf()); if !path.exists() { fs::create_dir_all(&path).expect("couldn't create table storage directory"); } path } #[inline] fn add_mapping(&self, tref: Id, paths: PathInfo) { let mut map = self.mappings.write().unwrap(); map.insert(tref, paths); } } impl Mapper for Disk { fn make_table(&self, kind: Kind, func: &mut FnMut(Writer, Writer)) -> Result<SSTable> { let storage = self.choose_storage(); let id = next_id(kind); let paths = mk_paths(id, &storage); let (data, index) = mk_writers(&paths)?; func(data, index); self.add_mapping(id, paths.clone()); let (data, index) = mk_maps(&paths)?; let sst = SSTable::from_parts(Arc::new(data), Arc::new(index))?; Ok(sst) } fn rotate_tables(&self) -> Result<()> { let mut map = self.mappings.write().unwrap(); let mut new_map = HashMap::new(); for (tref, paths) in map.drain() { let new_kind = match tref.kind { Kind::Active => Kind::Garbage, Kind::Compaction => Kind::Active, k => k, }; let new_ref = next_id(new_kind); new_map.insert(new_ref, paths); } *map = new_map; Ok(()) } fn empty_trash(&self) -> Result<()> { self.mappings.write_as(|map| { let to_rm = map .keys() .filter(|tref| tref.kind == Kind::Garbage) .cloned() .collect::<Vec<_>>(); for tref in to_rm { let paths = map.remove(&tref).unwrap(); fs::remove_file(&paths.index)?; fs::remove_file(&paths.data)?; } Ok(()) }) } fn active_set(&self) -> Result<Vec<SSTable>> { let map = self.mappings.read().unwrap(); let active = map.iter().filter(|(tref, _)| tref.kind == Kind::Active); let mut vec = Vec::new(); for (_, paths) in active { let (data, index): (MemMap, MemMap) = mk_maps(paths)?; let sst = SSTable::from_parts(Arc::new(data), Arc::new(index))?; vec.push(sst); } Ok(vec) } fn serialize_state_to(&self, path: &Path) -> Result<()> { let file = OpenOptions::new() .create(true) .write(true) .truncate(true) .open(path)?; let wtr = BufWriter::new(file); self.mappings.read_as(|mappings| { self.storage_dirs .read_as(|storage| bincode::serialize_into(wtr, &(storage, mappings))) })?; Ok(()) } fn load_state_from(&self, path: &Path) -> Result<()> { let rdr = BufReader::new(File::open(path)?); let (new_storage, new_mappings) = bincode::deserialize_from(rdr)?; self.storage_dirs.write_as(|storage| { self.mappings.write_as(|mappings| { *storage = new_storage; *mappings = new_mappings; }) }); Ok(()) } } fn mk_writers(paths: &PathInfo) -> io::Result<(Writer, Writer)> { let mut opts = OpenOptions::new(); opts.create(true).append(true); let data = BufWriter::new(opts.open(&paths.data)?); let index = BufWriter::new(opts.open(&paths.index)?); Ok((Writer::Disk(data), Writer::Disk(index))) } fn mk_maps(paths: &PathInfo) -> io::Result<(MemMap, MemMap)> { let (data_file, index_file) = (File::open(&paths.data)?, File::open(&paths.index)?); let (data, index) = unsafe { (Mmap::map(&data_file)?, Mmap::map(&index_file)?) }; Ok((MemMap::Disk(data), MemMap::Disk(index))) } fn mk_paths(tref: Id, dir: &Path) -> PathInfo { let (data_name, index_name) = mk_filenames(tref.id); PathInfo { data: dir.join(data_name), index: dir.join(index_name), } } #[inline] fn mk_filenames(n: u32) -> (String, String) { let data = format!("{}.sstable", n,); let index = format!("{}.index", n,); (data, index) } #[inline] fn next_id(kind: Kind) -> Id { Id { id: rand::thread_rng().gen(), kind, } } #[cfg(test)] mod test { use super::*; use crate::mapper::Kind; use crate::sstable::{Key, Value}; use crate::test::gen; use std::collections::BTreeMap; use std::sync::Arc; use std::thread; use tempfile::tempdir; const DATA_SIZE: usize = 128; #[test] fn test_table_management() { let tempdir = tempdir().unwrap(); let mapper = Arc::new(Disk::single(tempdir.path())); let records: BTreeMap<_, _> = gen_records().take(1024).collect(); let mut threads = vec![]; let mut number_of_tables = 4; for kind in [Kind::Active, Kind::Garbage, Kind::Compaction].iter() { let records = records.clone(); let mapper = Arc::clone(&mapper); let child = thread::spawn(move || { for _ in 0..number_of_tables { mapper .make_table(*kind, &mut |mut data_writer, mut index_writer| { SSTable::create( &mut records.iter(), 0, &mut data_writer, &mut index_writer, ); }) .unwrap(); } }); number_of_tables *= 2; threads.push(child); } threads.into_iter().for_each(|child| child.join().unwrap()); let count_kind = |kind, mapper: &Disk| { mapper .mappings .read() .unwrap() .keys() .filter(|id| id.kind == kind) .count() }; assert_eq!(count_kind(Kind::Active, &mapper), 4); assert_eq!(count_kind(Kind::Garbage, &mapper), 8); assert_eq!(count_kind(Kind::Compaction, &mapper), 16); mapper.empty_trash().unwrap(); assert_eq!(count_kind(Kind::Garbage, &mapper), 0); mapper.rotate_tables().unwrap(); assert_eq!(count_kind(Kind::Active, &mapper), 16); assert_eq!(count_kind(Kind::Garbage, &mapper), 4); assert_eq!(count_kind(Kind::Compaction, &mapper), 0); let active_set = mapper.active_set().unwrap(); assert_eq!(active_set.len(), 16); } #[test] fn test_state() { let tempdir = tempdir().unwrap(); let dirs_1: Vec<_> = (0..4).map(|i| tempdir.path().join(i.to_string())).collect(); let dirs_2: Vec<_> = (4..8).map(|i| tempdir.path().join(i.to_string())).collect(); let mapper_1 = Arc::new(Disk::new(&dirs_1)); let records: BTreeMap<_, _> = gen_records().take(1024).collect(); for (i, &kind) in [Kind::Active, Kind::Compaction, Kind::Garbage] .iter() .enumerate() { for _ in 0..(i * 3) { mapper_1 .make_table(kind, &mut |mut data_writer, mut index_writer| { SSTable::create( &mut records.iter(), 0, &mut data_writer, &mut index_writer, ); }) .unwrap(); } } let state_path = tempdir.path().join("state"); mapper_1.serialize_state_to(&state_path).unwrap(); assert!(state_path.exists()); let mapper_2 = Arc::new(Disk::new(&dirs_2)); mapper_2.load_state_from(&state_path).unwrap(); assert_eq!( &*mapper_1.mappings.read().unwrap(), &*mapper_2.mappings.read().unwrap() ); assert_eq!( &*mapper_1.storage_dirs.read().unwrap(), &*mapper_2.storage_dirs.read().unwrap() ); } fn gen_records() -> impl Iterator<Item = (Key, Value)> { gen::pairs(DATA_SIZE).map(|(key, data)| (key, Value::new(0, Some(data)))) } }
// xfail-stage3 fn start(c: chan[chan[str]]) { let p: port[str] = port(); c <| chan(p); } fn main() { let p: port[chan[str]] = port(); let child = spawn start(chan(p)); let c; p |> c; }
//! Stakes serve as a cache of stake and vote accounts to derive //! node stakes use hashbrown::HashMap; use morgan_interface::account::Account; use morgan_interface::pubkey::Pubkey; use morgan_stake_api::stake_state::StakeState; #[derive(Default, Clone)] pub struct Stakes { /// vote accounts vote_accounts: HashMap<Pubkey, (u64, Account)>, /// stake_accounts stake_accounts: HashMap<Pubkey, Account>, } impl Stakes { // sum the stakes that point to the given voter_pubkey fn calculate_stake(&self, voter_pubkey: &Pubkey) -> u64 { self.stake_accounts .iter() .filter(|(_, stake_account)| { Some(*voter_pubkey) == StakeState::voter_pubkey_from(stake_account) }) .map(|(_, stake_account)| stake_account.difs) .sum() } pub fn is_stake(account: &Account) -> bool { morgan_vote_api::check_id(&account.owner) || morgan_stake_api::check_id(&account.owner) } pub fn store(&mut self, pubkey: &Pubkey, account: &Account) { if morgan_vote_api::check_id(&account.owner) { if account.difs == 0 { self.vote_accounts.remove(pubkey); } else { // update the stake of this entry let stake = self .vote_accounts .get(pubkey) .map_or_else(|| self.calculate_stake(pubkey), |v| v.0); self.vote_accounts.insert(*pubkey, (stake, account.clone())); } } else if morgan_stake_api::check_id(&account.owner) { // old_stake is stake difs and voter_pubkey from the pre-store() version let old_stake = self.stake_accounts.get(pubkey).and_then(|old_account| { StakeState::voter_pubkey_from(old_account) .map(|old_voter_pubkey| (old_account.difs, old_voter_pubkey)) }); let stake = StakeState::voter_pubkey_from(account) .map(|voter_pubkey| (account.difs, voter_pubkey)); // if adjustments need to be made... if stake != old_stake { if let Some((old_stake, old_voter_pubkey)) = old_stake { self.vote_accounts .entry(old_voter_pubkey) .and_modify(|e| e.0 -= old_stake); } if let Some((stake, voter_pubkey)) = stake { self.vote_accounts .entry(voter_pubkey) .and_modify(|e| e.0 += stake); } } if account.difs == 0 { self.stake_accounts.remove(pubkey); } else { self.stake_accounts.insert(*pubkey, account.clone()); } } } pub fn vote_accounts(&self) -> &HashMap<Pubkey, (u64, Account)> { &self.vote_accounts } } #[cfg(test)] mod tests { use super::*; use morgan_interface::pubkey::Pubkey; use morgan_stake_api::stake_state; use morgan_vote_api::vote_state::{self, VoteState}; // set up some dummies for a staked node (( vote ) ( stake )) fn create_staked_node_accounts(stake: u64) -> ((Pubkey, Account), (Pubkey, Account)) { let vote_pubkey = Pubkey::new_rand(); let vote_account = vote_state::create_account(&vote_pubkey, &Pubkey::new_rand(), 0, 1); ( (vote_pubkey, vote_account), create_stake_account(stake, &vote_pubkey), ) } // add stake to a vote_pubkey ( stake ) fn create_stake_account(stake: u64, vote_pubkey: &Pubkey) -> (Pubkey, Account) { ( Pubkey::new_rand(), stake_state::create_delegate_stake_account(&vote_pubkey, &VoteState::default(), stake), ) } #[test] fn test_stakes_basic() { let mut stakes = Stakes::default(); let ((vote_pubkey, vote_account), (stake_pubkey, mut stake_account)) = create_staked_node_accounts(10); stakes.store(&vote_pubkey, &vote_account); stakes.store(&stake_pubkey, &stake_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10); } stake_account.difs = 42; stakes.store(&stake_pubkey, &stake_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 42); } stake_account.difs = 0; stakes.store(&stake_pubkey, &stake_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 0); } } #[test] fn test_stakes_vote_account_disappear_reappear() { let mut stakes = Stakes::default(); let ((vote_pubkey, mut vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); stakes.store(&vote_pubkey, &vote_account); stakes.store(&stake_pubkey, &stake_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10); } vote_account.difs = 0; stakes.store(&vote_pubkey, &vote_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_none()); } vote_account.difs = 1; stakes.store(&vote_pubkey, &vote_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10); } } #[test] fn test_stakes_change_delegate() { let mut stakes = Stakes::default(); let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); let ((vote_pubkey2, vote_account2), (_stake_pubkey2, stake_account2)) = create_staked_node_accounts(10); stakes.store(&vote_pubkey, &vote_account); stakes.store(&vote_pubkey2, &vote_account2); // delegates to vote_pubkey stakes.store(&stake_pubkey, &stake_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10); assert!(vote_accounts.get(&vote_pubkey2).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey2).unwrap().0, 0); } // delegates to vote_pubkey2 stakes.store(&stake_pubkey, &stake_account2); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 0); assert!(vote_accounts.get(&vote_pubkey2).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey2).unwrap().0, 10); } } #[test] fn test_stakes_multiple_stakers() { let mut stakes = Stakes::default(); let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); let (stake_pubkey2, stake_account2) = create_stake_account(10, &vote_pubkey); stakes.store(&vote_pubkey, &vote_account); // delegates to vote_pubkey stakes.store(&stake_pubkey, &stake_account); stakes.store(&stake_pubkey2, &stake_account2); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 20); } } #[test] fn test_stakes_not_delegate() { let mut stakes = Stakes::default(); let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) = create_staked_node_accounts(10); stakes.store(&vote_pubkey, &vote_account); stakes.store(&stake_pubkey, &stake_account); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10); } // not a stake account, and whacks above entry stakes.store(&stake_pubkey, &Account::new(1, 0, 0, &morgan_stake_api::id())); { let vote_accounts = stakes.vote_accounts(); assert!(vote_accounts.get(&vote_pubkey).is_some()); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 0); } } }
//! Modified from https://github.com/diesel-rs/diesel/blob/master/examples/postgres/advanced-blog-cli/src/pagination.rs use diesel::{ query_builder::{AstPass, Query, QueryFragment, QueryId}, query_dsl::methods::LoadQuery, sql_types::BigInt, QueryResult, RunQueryDsl, }; use super::{DBConn, DB}; pub trait Paginate: Sized { /// page_index: zero based page index fn paginate(self, page_index: i64) -> Paginated<Self>; } impl<T> Paginate for T { fn paginate(self, page_index: i64) -> Paginated<Self> { Paginated { query: self, page_index: page_index, page_size: DEFAULT_PAGE_SIZE, } } } const DEFAULT_PAGE_SIZE: i64 = 10; #[derive(Debug, Clone, Copy, QueryId)] pub struct Paginated<T> { query: T, page_index: i64, page_size: i64, } impl<T> Paginated<T> { pub fn page_size(self, page_size: i64) -> Self { Paginated { page_size, ..self } } /// return (records, total) pub fn load_and_count<U>(self, conn: &DBConn) -> QueryResult<(Vec<U>, i64)> where Self: LoadQuery<DBConn, (U, i64)>, { let results = self.load::<(U, i64)>(conn)?; let total = results.get(0).map(|x| x.1).unwrap_or(0); let records = results.into_iter().map(|x| x.0).collect(); Ok((records, total)) } } impl<T: Query> Query for Paginated<T> { type SqlType = (T::SqlType, BigInt); } impl<T> RunQueryDsl<DBConn> for Paginated<T> {} impl<T> QueryFragment<DB> for Paginated<T> where T: QueryFragment<DB>, { fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> { out.push_sql("SELECT *, COUNT(*) OVER () FROM ("); self.query.walk_ast(out.reborrow())?; out.push_sql(") t LIMIT "); out.push_bind_param::<BigInt, _>(&self.page_size)?; out.push_sql(" OFFSET "); let offset = self.page_index * self.page_size; out.push_bind_param::<BigInt, _>(&offset)?; Ok(()) } }
pub mod events; pub mod utils; pub mod settings;
pub mod renderer_ascii;
extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; use gtk::{ Application, ApplicationWindow, Button, WindowPosition, WindowType, Window, HeaderBar, }; use std::process; pub struct App { pub window: Window, pub header: Header, } pub struct Header { pub container: HeaderBar, } impl App { fn new() -> App { let window = Window::new(WindowType::Toplevel); let header = Header::new(); window.set_titlebar(Some(&header.container)); window.set_title("App Name"); window.set_wmclass("app-name", "App Name"); Window::set_default_icon_name("iconname"); window.connect_delete_event(move |_, _| { gtk::main_quit(); Inhibit(false) }); App { window, header} } } impl Header { fn new() -> Header { let container = HeaderBar::new(); container.set_title(Some("App Name")); container.set_show_close_button(true); Header { container } } } fn main() { // let winapp = Application::new( // Some("com.github.gtk-rs.example.basic"), // Default::default() // ).expect("faield"); // winapp.connect_activate(|app| { // let window = ApplicationWindow::new(app); // window.set_title("Gtk"); // window.set_position(WindowPosition::CenterAlways); // window.set_default_size(350, 70); // let button = Button::new_with_label("Click me!"); // button.connect_clicked(|_| { // println!("Clicked!"); // }); // window.add(&button); // window.show_all(); // }); // winapp.run(&[]); if gtk::init().is_err() { eprintln!("Gagal menginisiali Aplikasi GTK"); process::exit(1); } let app = App::new(); app.window.show_all(); gtk::main(); }
/// Helper methods to act on hyper::Body use futures::stream::{Stream, StreamExt}; use hyper::body::Bytes; /// Additional function for hyper::Body pub trait BodyExt { /// Raw body type type Raw; /// Error if we can't gather up the raw body type Error; /// Collect the body into a raw form fn into_raw(self) -> futures::future::BoxFuture<'static, Result<Self::Raw, Self::Error>>; } impl<T, E> BodyExt for T where T: Stream<Item = Result<Bytes, E>> + Unpin + Send + 'static, { type Raw = Vec<u8>; type Error = E; fn into_raw(mut self) -> futures::future::BoxFuture<'static, Result<Self::Raw, Self::Error>> { Box::pin(async { let mut raw = Vec::new(); while let (Some(chunk), rest) = self.into_future().await { raw.extend_from_slice(&chunk?); self = rest; } Ok(raw) }) } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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.. #![crate_name = "helloworldsampleenclave"] #![crate_type = "staticlib"] #![cfg_attr(not(target_env = "sgx"), no_std)] #![cfg_attr(target_env = "sgx", feature(rustc_private))] extern crate sgx_trts; extern crate sgx_types; #[cfg(not(target_env = "sgx"))] #[macro_use] extern crate sgx_tstd as std; extern crate io_uring; extern crate io_uring_callback; extern crate lazy_static; extern crate slab; use sgx_trts::libc; use sgx_types::*; use std::collections::VecDeque; use std::os::unix::io::RawFd; use std::prelude::v1::*; use std::ptr; use std::sync::SgxMutex as Mutex; use io_uring::opcode::types; use io_uring_callback::{Builder, Handle, IoUring}; use lazy_static::lazy_static; use slab::Slab; lazy_static! { static ref TOKEN_QUEUE: Mutex<VecDeque<(Token, i32)>> = Mutex::new(VecDeque::new()); static ref HANDLE_SLAB: Mutex<slab::Slab<Handle>> = Mutex::new(slab::Slab::new()); } #[derive(Clone, Debug)] enum Token { Accept, Poll { fd: RawFd, }, Read { fd: RawFd, buf_index: usize, }, Write { fd: RawFd, buf_index: usize, offset: usize, len: usize, }, } pub struct AcceptCount { fd: types::Fd, count: usize, } impl AcceptCount { fn new(fd: RawFd, count: usize) -> AcceptCount { AcceptCount { fd: types::Fd(fd), count: count, } } pub fn try_push_accept(&mut self, ring: &IoUring) { while self.count > 0 { let to_complete_token = Token::Accept; let mut handle_slab = HANDLE_SLAB.lock().unwrap(); let slab_entry = handle_slab.vacant_entry(); let slab_key = slab_entry.key(); let complete_fn = move |retval: i32| { let mut queue = TOKEN_QUEUE.lock().unwrap(); queue.push_back((to_complete_token, retval)); HANDLE_SLAB.lock().unwrap().remove(slab_key); }; let handle = unsafe { ring.accept(self.fd, ptr::null_mut(), ptr::null_mut(), 0, complete_fn) }; slab_entry.insert(handle); self.count -= 1; } } } #[no_mangle] pub extern "C" fn run_sgx_example() -> sgx_status_t { // std::backtrace::enable_backtrace("enclave.signed.so", std::backtrace::PrintFormat::Full); println!("[ECALL] run_sgx_example"); let ring = Builder::new().build(256).unwrap(); unsafe { ring.start_enter_syscall_thread(); } let socket_fd = { let socket_fd = unsafe { libc::ocall::socket(libc::AF_INET, libc::SOCK_STREAM, 0) }; if socket_fd < 0 { println!("[ECALL] create socket failed, ret: {}", socket_fd); return sgx_status_t::SGX_ERROR_UNEXPECTED; } let ret = unsafe { let servaddr = libc::sockaddr_in { sin_family: libc::AF_INET as u16, sin_port: 3456_u16.to_be(), sin_addr: libc::in_addr { s_addr: 0 }, sin_zero: [0; 8], }; libc::ocall::bind( socket_fd, &servaddr as *const _ as *const libc::sockaddr, core::mem::size_of::<libc::sockaddr_in>() as u32, ) }; if ret < 0 { println!("[ECALL] bind failed, ret: {}", ret); unsafe { libc::ocall::close(socket_fd); } return sgx_status_t::SGX_ERROR_UNEXPECTED; } let ret = unsafe { libc::ocall::listen(socket_fd, 10) }; if ret < 0 { println!("[ECALL] listen failed, ret: {}", ret); unsafe { libc::ocall::close(socket_fd); } return sgx_status_t::SGX_ERROR_UNEXPECTED; } socket_fd }; let mut bufpool = Vec::with_capacity(64); let mut buf_alloc = Slab::with_capacity(64); println!("[ECALL] listen 127.0.0.1:3456"); let mut accept = AcceptCount::new(socket_fd, 3); loop { accept.try_push_accept(&ring); ring.trigger_callbacks(); let mut queue = TOKEN_QUEUE.lock().unwrap(); while !queue.is_empty() { let (token, ret) = queue.pop_front().unwrap(); match token { Token::Accept => { println!("[ECALL] accept"); accept.count += 1; let fd = ret; let to_complete_token = Token::Poll { fd }; let mut handle_slab = HANDLE_SLAB.lock().unwrap(); let slab_entry = handle_slab.vacant_entry(); let slab_key = slab_entry.key(); let complete_fn = move |retval: i32| { let mut queue = TOKEN_QUEUE.lock().unwrap(); queue.push_back((to_complete_token, retval)); HANDLE_SLAB.lock().unwrap().remove(slab_key); }; let handle = unsafe { ring.poll(types::Fd(fd), libc::POLLIN as _, complete_fn) }; slab_entry.insert(handle); } Token::Poll { fd } => { let (buf_index, buf) = match bufpool.pop() { Some(buf_index) => (buf_index, &mut buf_alloc[buf_index]), None => { let buf = Box::new(unsafe { std::slice::from_raw_parts_mut( libc::ocall::malloc(2048) as *mut u8, 2048, ) }); let buf_entry = buf_alloc.vacant_entry(); let buf_index = buf_entry.key(); (buf_index, buf_entry.insert(buf)) } }; let to_complete_token = Token::Read { fd, buf_index }; let mut handle_slab = HANDLE_SLAB.lock().unwrap(); let slab_entry = handle_slab.vacant_entry(); let slab_key = slab_entry.key(); let complete_fn = move |retval: i32| { let mut queue = TOKEN_QUEUE.lock().unwrap(); queue.push_back((to_complete_token, retval)); HANDLE_SLAB.lock().unwrap().remove(slab_key); }; let handle = unsafe { ring.read( types::Fd(fd), buf.as_mut_ptr(), buf.len() as _, 0, 0, complete_fn, ) }; slab_entry.insert(handle); } Token::Read { fd, buf_index } => { if ret == 0 { bufpool.push(buf_index); println!("[ECALL] shutdown"); unsafe { libc::ocall::close(fd); } } else { let len = ret as usize; let buf = &buf_alloc[buf_index]; let to_complete_token = Token::Write { fd, buf_index, len, offset: 0, }; let mut handle_slab = HANDLE_SLAB.lock().unwrap(); let slab_entry = handle_slab.vacant_entry(); let slab_key = slab_entry.key(); let complete_fn = move |retval: i32| { let mut queue = TOKEN_QUEUE.lock().unwrap(); queue.push_back((to_complete_token, retval)); HANDLE_SLAB.lock().unwrap().remove(slab_key); }; let handle = unsafe { ring.write(types::Fd(fd), buf.as_ptr(), len as _, 0, 0, complete_fn) }; slab_entry.insert(handle); } } Token::Write { fd, buf_index, offset, len, } => { let write_len = ret as usize; if offset + write_len >= len { bufpool.push(buf_index); let to_complete_token = Token::Poll { fd }; let mut handle_slab = HANDLE_SLAB.lock().unwrap(); let slab_entry = handle_slab.vacant_entry(); let slab_key = slab_entry.key(); let complete_fn = move |retval: i32| { let mut queue = TOKEN_QUEUE.lock().unwrap(); queue.push_back((to_complete_token, retval)); HANDLE_SLAB.lock().unwrap().remove(slab_key); }; let handle = unsafe { ring.poll_add(types::Fd(fd), libc::POLLIN as _, complete_fn) }; slab_entry.insert(handle); } else { let offset = offset + write_len; let len = len - offset; let buf = &buf_alloc[buf_index][offset..]; let to_complete_token = Token::Write { fd, buf_index, offset, len, }; let mut handle_slab = HANDLE_SLAB.lock().unwrap(); let slab_entry = handle_slab.vacant_entry(); let slab_key = slab_entry.key(); let complete_fn = move |retval: i32| { let mut queue = TOKEN_QUEUE.lock().unwrap(); queue.push_back((to_complete_token, retval)); HANDLE_SLAB.lock().unwrap().remove(slab_key); }; let handle = unsafe { ring.write(types::Fd(fd), buf.as_ptr(), len as _, 0, 0, complete_fn) }; slab_entry.insert(handle); }; } } } } }
//! Drawing algorithms and helpers use std::sync::Arc; use crate::component::Component; use crate::data::{FontMetrics, Workspace}; use crate::design_space::ViewPort; use crate::edit_session::EditSession; use crate::guides::{Guide, GuideLine}; use crate::path::Path; use crate::point::PointType; use crate::point_list::RawSegment; use crate::selection::Selection; use crate::theme; use druid::kurbo::{self, Affine, BezPath, Circle, CubicBez, Line, Point, Rect, Vec2}; use druid::piet::{Color, Piet, RenderContext}; use druid::{Env, PaintCtx}; use norad::Glyph; /// A context for drawing that maps between screen space and design space. struct DrawCtx<'a, 'b: 'a> { ctx: &'a mut Piet<'b>, env: &'a Env, space: ViewPort, /// the size of the drawing area visible_rect: Rect, } impl<'a, 'b> std::ops::Deref for DrawCtx<'a, 'b> { type Target = Piet<'b>; fn deref(&self) -> &Self::Target { self.ctx } } impl<'a, 'b> std::ops::DerefMut for DrawCtx<'a, 'b> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.ctx } } impl<'a, 'b: 'a> DrawCtx<'a, 'b> { fn new(ctx: &'a mut Piet<'b>, env: &'a Env, space: ViewPort, visible_rect: Rect) -> Self { DrawCtx { ctx, env, space, visible_rect, } } fn draw_metrics(&mut self, glyph: &Glyph, metrics: &FontMetrics, env: &Env) { let upm = metrics.units_per_em; let x_height = metrics.x_height.unwrap_or_else(|| (upm * 0.5).round()); let cap_height = metrics.cap_height.unwrap_or_else(|| (upm * 0.7).round()); let ascender = metrics.ascender.unwrap_or_else(|| (upm * 0.8).round()); let descender = metrics.descender.unwrap_or_else(|| -(upm * 0.2).round()); let hadvance = glyph .advance .as_ref() .map(|a| a.width as f64) .unwrap_or_else(|| (upm * 0.5).round()); let metrics_color = env.get(theme::METRICS_COLOR); let bounds = Rect::from_points((0., descender), (hadvance, ascender)); let bounds = self.space.rect_to_screen(bounds); self.stroke(bounds, &metrics_color, 1.0); let baseline = Line::new((0.0, 0.0), (hadvance, 0.0)); let baseline = self.space.affine() * baseline; self.stroke(baseline, &metrics_color, 1.0); let x_height_guide = Line::new((0.0, x_height), (hadvance, x_height)); let x_height_guide = self.space.affine() * x_height_guide; self.stroke(x_height_guide, &metrics_color, 1.0); let cap_height_guide = Line::new((0.0, cap_height), (hadvance, cap_height)); let cap_height_guide = self.space.affine() * cap_height_guide; self.stroke(cap_height_guide, &metrics_color, 1.0); } fn draw_grid(&mut self) { const MIN_SCALE_FOR_GRID: f64 = 4.0; if self.space.zoom >= MIN_SCALE_FOR_GRID { // we draw the grid very lightly at low zoom levels. let grid_fade = ((self.space.zoom - MIN_SCALE_FOR_GRID) / 10.) .min(1.0) .max(0.05); let gray_val = 0xFF - (68. * grid_fade) as u8; let brush = Color::rgb8(gray_val, gray_val, gray_val); let visible_pixels = self.visible_rect.width().max(self.visible_rect.height()) / self.space.zoom; let visible_pixels = visible_pixels.ceil() as usize; let view_origin = self.space.inverse_affine() * self.visible_rect.origin(); let Point { x, y } = view_origin.round(); //NOTE: we are drawing in glyph space; y is up. // draw one line past what is visible. let x1 = x - 1.; let y1 = y + 1.; let len = 2.0 + visible_pixels as f64; for i in 0..=visible_pixels { let off = i as f64; let xmin = self.space.to_screen((x1 + off, y1)); let xmax = self.space.to_screen((x1 + off, y1 - len)); //TODO: this might mean that we draw lines at different pixel //intervals, based on how the rounding goes? is it better to floor()? let ymin = self.space.to_screen((x1, y1 - off)).round(); let ymax = self.space.to_screen((x1 + len, y1 - off)).round(); self.stroke(Line::new(xmin, xmax), &brush, 1.0); self.stroke(Line::new(ymin, ymax), &brush, 1.0); } } } fn draw_guides(&mut self, guides: &[Guide], sels: &Selection, env: &Env) { for guide in guides { let line = self.line_for_guide(guide); if sels.contains(&guide.id) { self.stroke(line, &env.get(theme::SELECTED_GUIDE_COLOR), 8.0); } self.stroke(line, &env.get(theme::GUIDE_COLOR), 0.5); } } fn line_for_guide(&self, guide: &Guide) -> Line { let view_origin = self.space.inverse_affine() * self.visible_rect.origin(); let Point { x, y } = view_origin.round(); let vis_size = self.visible_rect.size(); let visible_pixels = ((vis_size.width.max(vis_size.height)) / self.space.zoom).ceil(); match guide.guide { GuideLine::Horiz(p) => { let p1 = self.space.to_screen((x, p.y)); let p2 = self.space.to_screen((x + visible_pixels, p.y)); Line::new(p1, p2) } GuideLine::Vertical(p) => { let p1 = self.space.to_screen((p.x, y)); let p2 = self.space.to_screen((p.x, y - visible_pixels)); Line::new(p1, p2) } GuideLine::Angle { p1, p2 } => { let p1 = p1.to_screen(self.space); let p2 = p2.to_screen(self.space); let vec = (p2 - p1).normalize(); let p1 = p2 - vec * 5000.; // an arbitrary number let p2 = p2 + vec * 5000.; Line::new(p1, p2) } } } fn draw_selected_segments(&mut self, path: &Path, sels: &Selection) { //FIXME: this is less efficient than it could be; we create and //check all segments of all paths, and we could at least just keep track //of whether a path contained *any* selected points, and short-circuit. let selected_seg_color = self.env.get(theme::SELECTED_LINE_SEGMENT_COLOR); for segment in path.segments_for_points(sels) { for segment in segment.kurbo_segments() { let seg = self.space.affine() * segment; //TODO: add width to theme self.stroke(&seg, &selected_seg_color, 3.0); } } } fn draw_path(&mut self, bez: &BezPath) { let path_color = self.env.get(theme::PATH_STROKE_COLOR); self.stroke(bez, &path_color, 1.0); } fn draw_filled(&mut self, session: &EditSession, font: &Workspace) { let bez = self.space.affine() * session.to_bezier(); let fill_color = self.env.get(theme::PATH_FILL_COLOR); self.fill(bez, &fill_color); for comp in session.components.iter() { self.draw_component(comp, font, &fill_color); } } fn draw_control_point_lines(&mut self, path: &Path) { // if there is a trailing handle (the last operation was a click_drag // we need to draw that from the end point, which we track here.) let mut end_point = path.start_point().to_screen(self.space); for seg in path.iter_segments() { match seg.raw_segment() { RawSegment::Line(_, p1) => end_point = p1.to_screen(self.space), RawSegment::Cubic(p0, p1, p2, p3) => { let r = self.space; //FIXME: draw auto handles as dashed lines self.draw_control_handle(p0.to_screen(r), p1.to_screen(r)); self.draw_control_handle(p2.to_screen(r), p3.to_screen(r)); end_point = p3.to_screen(r); } } } if let Some(trailing) = path.trailing() { if path.should_draw_trailing() { self.draw_control_handle(end_point, trailing.to_screen(self.space)); } } } fn draw_control_handle(&mut self, p1: Point, p2: Point) { let handle_color = self.env.get(theme::OFF_CURVE_HANDLE_COLOR); let l = Line::new(p1, p2); self.stroke(l, &handle_color, 1.0); } fn draw_point(&mut self, point: PointStyle, env: &Env) { let PointStyle { style, point, selected, } = point; match style { Style::Open(seg) => self.draw_open_path_terminal(&seg, selected, env), Style::Close(seg) => self.draw_open_path_terminal(&seg, selected, env), Style::OffCurve => self.draw_off_curve_point(point, selected, env), Style::OffCurveAuto => self.draw_auto_point(point, selected, env), Style::Smooth => self.draw_smooth_point(point, selected, env), Style::Corner => self.draw_corner_point(point, selected, env), } } fn draw_open_path_terminal(&mut self, seg: &kurbo::PathSeg, selected: bool, env: &Env) { let cap = cap_line(seg.to_cubic(), 12.); if selected { let inner = cap_line(seg.to_cubic(), 8.); self.stroke(cap, &env.get(theme::SELECTED_POINT_OUTER_COLOR), 4.0); self.stroke(inner, &env.get(theme::SELECTED_POINT_INNER_COLOR), 2.0); } else { self.stroke(cap, &env.get(theme::OFF_CURVE_HANDLE_COLOR), 2.0); } } fn draw_smooth_point(&mut self, p: Point, selected: bool, env: &Env) { let radius = if selected { env.get(theme::SMOOTH_SELECTED_RADIUS) } else { env.get(theme::SMOOTH_RADIUS) }; let circ = Circle::new(p, radius); if selected { self.fill(circ, &env.get(theme::SELECTED_POINT_INNER_COLOR)); self.stroke(circ, &env.get(theme::SELECTED_POINT_OUTER_COLOR), 2.0); } else { self.fill(circ, &env.get(theme::SMOOTH_POINT_INNER_COLOR)); self.stroke(circ, &env.get(theme::SMOOTH_POINT_OUTER_COLOR), 2.0); } } fn draw_corner_point(&mut self, p: Point, selected: bool, env: &Env) { let radius = if selected { env.get(theme::CORNER_SELECTED_RADIUS) } else { env.get(theme::CORNER_RADIUS) }; let rect = Rect::new(p.x - radius, p.y - radius, p.x + radius, p.y + radius); if selected { self.fill(rect, &env.get(theme::SELECTED_POINT_INNER_COLOR)); self.stroke(rect, &env.get(theme::SELECTED_POINT_OUTER_COLOR), 2.0); } else { self.fill(rect, &env.get(theme::CORNER_POINT_INNER_COLOR)); self.stroke(rect, &env.get(theme::CORNER_POINT_OUTER_COLOR), 2.0); } } fn draw_off_curve_point(&mut self, p: Point, selected: bool, env: &Env) { let radius = if selected { env.get(theme::OFF_CURVE_SELECTED_RADIUS) } else { env.get(theme::OFF_CURVE_RADIUS) }; let circ = Circle::new(p, radius); if selected { self.fill(circ, &env.get(theme::SELECTED_POINT_INNER_COLOR)); self.stroke(circ, &env.get(theme::SELECTED_POINT_OUTER_COLOR), 2.0); } else { self.fill(circ, &env.get(theme::OFF_CURVE_POINT_INNER_COLOR)); self.stroke(circ, &env.get(theme::OFF_CURVE_POINT_OUTER_COLOR), 2.0); } } fn draw_auto_point(&mut self, p: Point, selected: bool, env: &Env) { let radius = if selected { env.get(theme::OFF_CURVE_SELECTED_RADIUS) } else { env.get(theme::OFF_CURVE_RADIUS) }; let rect = Rect::new(p.x - radius, p.y - radius, p.x + radius, p.y + radius); let line1 = Line::new(rect.origin(), (rect.x1, rect.y1)); let line2 = Line::new((rect.x1, rect.y0), (rect.x0, rect.y1)); if selected { self.stroke(line1, &env.get(theme::SELECTED_POINT_OUTER_COLOR), 4.0); self.stroke(line2, &env.get(theme::SELECTED_POINT_OUTER_COLOR), 4.0); self.stroke(line1, &env.get(theme::SELECTED_POINT_INNER_COLOR), 2.0); self.stroke(line2, &env.get(theme::SELECTED_POINT_INNER_COLOR), 2.0); } else { self.stroke(line1, &env.get(theme::OFF_CURVE_HANDLE_COLOR), 1.0); self.stroke(line2, &env.get(theme::OFF_CURVE_HANDLE_COLOR), 1.0); } } fn draw_direction_indicator(&mut self, path: &BezPath, env: &Env) { let first_seg = match path.segments().next().as_ref().map(|seg| seg.to_cubic()) { None => return, Some(cubic) => cubic, }; let tangent = tangent_vector(0.05, first_seg).normalize(); let angle = Vec2::new(tangent.y, -tangent.x); let rotate = Affine::rotate(angle.atan2()); let translate = Affine::translate(first_seg.p0.to_vec2() + tangent * 8.0); let mut arrow = make_arrow(); arrow.apply_affine(rotate); arrow.apply_affine(translate); self.fill(arrow, &env.get(theme::DIRECTION_ARROW_COLOR)); } fn draw_component(&mut self, component: &Component, font: &Workspace, color: &Color) { if let Some(mut bez) = font.get_bezier(&component.base) { let bez = Arc::make_mut(&mut bez); bez.apply_affine(component.transform); bez.apply_affine(self.space.affine()); self.fill(&*bez, color); } } } struct PointStyle { point: Point, style: Style, selected: bool, } #[derive(Debug, Clone)] enum Style { Open(kurbo::PathSeg), Close(kurbo::PathSeg), Corner, Smooth, OffCurve, OffCurveAuto, } struct PointIter<'a> { idx: usize, vport: ViewPort, path: &'a Path, bez: &'a BezPath, sels: &'a Selection, } impl<'a> PointIter<'a> { fn new(path: &'a Path, vport: ViewPort, bez: &'a BezPath, sels: &'a Selection) -> Self { PointIter { idx: 0, vport, bez, path, sels, } } fn next_style(&self) -> Style { let len = self.path.points().len(); if len == 1 { return Style::Corner; } let this = self.path.points()[self.idx]; if this.is_on_curve() && !self.path.is_closed() { if self.idx == 0 { return Style::Open(self.bez.segments().next().unwrap()); } else if self.idx == len - 1 { return Style::Close(self.bez.segments().last().unwrap().reverse()); } } match this.typ { PointType::OffCurve { auto: true } if self.path.is_hyper() => Style::OffCurveAuto, PointType::OffCurve { .. } => Style::OffCurve, PointType::OnCurve { smooth: false } => Style::Corner, PointType::OnCurve { smooth: true } => Style::Smooth, } } } impl<'a> std::iter::Iterator for PointIter<'a> { type Item = PointStyle; fn next(&mut self) -> Option<PointStyle> { let point = self.path.points().get(self.idx)?; let style = self.next_style(); let selected = self.sels.contains(&point.id); let point = point.to_screen(self.vport); self.idx += 1; Some(PointStyle { point, style, selected, }) } } #[allow(clippy::too_many_arguments)] pub(crate) fn draw_session( ctx: &mut PaintCtx, env: &Env, space: ViewPort, visible_rect: Rect, metrics: &FontMetrics, session: &EditSession, font: &Workspace, is_preview: bool, ) { let mut draw_ctx = DrawCtx::new(ctx.render_ctx, env, space, visible_rect); if is_preview { draw_ctx.draw_filled(session, font); return; } draw_ctx.draw_grid(); draw_ctx.draw_metrics(&session.glyph, metrics, env); draw_ctx.draw_guides(&session.guides, &session.selection, env); for path in session.paths.iter() { if session.selection.len() > 1 { // for a segment to be selected at least two points must be selected draw_ctx.draw_selected_segments(path, &session.selection); } let bez = space.affine() * path.bezier(); draw_ctx.draw_path(&bez); draw_ctx.draw_control_point_lines(path); draw_ctx.draw_direction_indicator(&bez, env); for point in PointIter::new(path, space, &bez, &session.selection) { draw_ctx.draw_point(point, env) } if let Some(pt) = path.trailing() { if path.should_draw_trailing() { draw_ctx.draw_auto_point(pt.to_screen(space), false, env); } } } for component in session.components.iter() { draw_ctx.draw_component(component, font, &env.get(theme::COMPONENT_FILL_COLOR)); } } /// Return the tangent of the cubic bezier `cb`, at time `t`, as a vector /// relative to the path's start point. fn tangent_vector(t: f64, cb: CubicBez) -> Vec2 { debug_assert!((0.0..=1.0).contains(&t)); let CubicBez { p0, p1, p2, p3 } = cb; let one_minus_t = 1.0 - t; 3.0 * one_minus_t.powi(2) * (p1 - p0) + 6.0 * t * one_minus_t * (p2 - p1) + 3.0 * t.powi(2) * (p3 - p2) } /// Create a line of length `len` perpendicular to the tangent of the cubic /// bezier `cb`, centered on the bezier's start point. fn cap_line(cb: CubicBez, len: f64) -> Line { let tan_vec = tangent_vector(0.01, cb); let end = cb.p0 + tan_vec; perp(cb.p0, end, len) } /// Create a line perpendicular to the line `(p1, p2)`, centered on `p1`. fn perp(p0: Point, p1: Point, len: f64) -> Line { let perp_vec = Vec2::new(p0.y - p1.y, p1.x - p0.x); let norm_perp = perp_vec / perp_vec.hypot(); let p2 = p0 + (len * -0.5) * norm_perp; let p3 = p0 + (len * 0.5) * norm_perp; Line::new(p2, p3) } fn make_arrow() -> BezPath { let mut bez = BezPath::new(); bez.move_to((0., 18.)); bez.line_to((-12., 0.)); bez.line_to((12., 0.)); bez.close_path(); bez }
use crate::stdio_server::provider::ProviderId; use anyhow::{anyhow, Result}; use once_cell::sync::{Lazy, OnceCell}; use paths::AbsPathBuf; use printer::DisplayLines; use rayon::prelude::*; use rpc::RpcClient; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::{json, Value}; use std::collections::HashMap; use std::fmt::Debug; use std::ops::Deref; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use types::ProgressUpdate; static FILENAME_SYNTAX_MAP: Lazy<HashMap<&str, &str>> = Lazy::new(|| { vec![ ("bashrc", "bash"), (".bashrc", "bash"), ("BUCK", "bzl"), ("BUILD", "bzl"), ("BUILD.bazel", "bzl"), ("Tiltfile", "bzl"), ("WORKSPACE", "bz"), ("configure.ac", "config"), ("configure.in", "config"), ("Containerfile", "dockerfile"), ("Dockerfile", "dockerfile"), ("dockerfile", "dockerfile"), ("jsconfig.json", "jsonc"), ("tsconfig.json", "jsonc"), ("mplayer.conf", "mplayerconf"), ("inputrc", "readline"), ("robots.txt", "robots"), ("ssh_config", "sshdconfig"), ("sshd_config", "sshdconfig"), ("tidy.conf", "tidy"), ("tidyrc", "tidy"), ("Pipfile", "toml"), ("vimrc", "vim"), ("_vimrc", "vim"), ("_viminfo", "viminfo"), ] .into_iter() .collect() }); /// Map of file extension to vim syntax mapping. static SYNTAX_MAP: OnceCell<HashMap<String, String>> = OnceCell::new(); pub fn initialize_syntax_map(output: &str) -> HashMap<&str, &str> { let ext_map: HashMap<&str, &str> = output .par_split(|x| x == '\n') .filter(|s| s.contains("setf")) .filter_map(|s| { // *.mkiv setf context let items = s.split_whitespace().collect::<Vec<_>>(); if items.len() != 3 { None } else { // (mkiv, context) items[0].split('.').last().map(|ext| (ext, items[2])) } }) .chain( // Lines as followed can not be parsed correctly, thus the preview highlight of // related file will be broken. Ref #800 // *.c call dist#ft#FTlpc() vec![ ("hpp", "cpp"), ("vimrc", "vim"), ("cc", "cpp"), ("cpp", "cpp"), ("c", "c"), ("h", "c"), ("cmd", "dosbatch"), ("CMakeLists.txt", "cmake"), ("Dockerfile", "dockerfile"), ("directory", "desktop"), ("patch", "diff"), ("dircolors", "dircolors"), ("editorconfig", "dosini"), ("COMMIT_EDITMSG", "gitcommit"), ("MERGE_MSG", "gitcommit"), ("TAG_EDITMSG", "gitcommit"), ("NOTES_EDITMSG", "gitcommit"), ("EDIT_DESCRIPTION", "gitcommit"), ("gitconfig", "gitconfig"), ("worktree", "gitconfig"), ("gitmodules", "gitconfig"), ("htm", "html"), ("html", "html"), ("shtml", "html"), ("stm", "html"), ("toml", "toml"), ] .into_par_iter(), ) .map(|(ext, ft)| (ext, ft)) .collect(); if let Err(e) = SYNTAX_MAP.set( ext_map .par_iter() .map(|(k, v)| (String::from(*k), String::from(*v))) .collect(), ) { tracing::debug!(error = ?e, "Failed to initialized SYNTAX_MAP"); } else { tracing::debug!("SYNTAX_MAP initialized successfully"); } ext_map } /// Returns the value of `&syntax` for given path for the preview buffer highlight. /// /// Try the file name first and then the file extension. pub fn preview_syntax(path: &Path) -> Option<&str> { match path .file_name() .and_then(|x| x.to_str()) .and_then(|filename| FILENAME_SYNTAX_MAP.deref().get(filename)) { None => path .extension() .and_then(|x| x.to_str()) .and_then(|ext| SYNTAX_MAP.get().and_then(|m| m.get(ext).map(AsRef::as_ref))), Some(s) => Some(s), } } #[derive(Debug, Clone)] pub enum PreviewConfig { Number(u64), Map(HashMap<String, u64>), } impl From<Value> for PreviewConfig { fn from(v: Value) -> Self { if v.is_object() { let m: HashMap<String, u64> = serde_json::from_value(v) .unwrap_or_else(|e| panic!("Failed to deserialize preview_size map: {e:?}")); return Self::Map(m); } match v { Value::Number(number) => { Self::Number(number.as_u64().unwrap_or(Self::DEFAULT_PREVIEW_SIZE)) } _ => unreachable!("clap_preview_size has to be either Number or Object"), } } } impl PreviewConfig { const DEFAULT_PREVIEW_SIZE: u64 = 5; pub fn preview_size(&self, provider_id: &str) -> usize { match self { Self::Number(n) => *n as usize, Self::Map(map) => map .get(provider_id) .copied() .unwrap_or_else(|| map.get("*").copied().unwrap_or(Self::DEFAULT_PREVIEW_SIZE)) as usize, } } } pub struct VimProgressor { vim: Vim, stopped: Arc<AtomicBool>, } impl VimProgressor { pub fn new(vim: Vim, stopped: Arc<AtomicBool>) -> Self { Self { vim, stopped } } } impl ProgressUpdate<DisplayLines> for VimProgressor { fn update_brief(&self, total_matched: usize, total_processed: usize) { if self.stopped.load(Ordering::Relaxed) { return; } let _ = self.vim.exec( "clap#state#process_progress", json!([total_matched, total_processed]), ); } fn update_all( &self, display_lines: &DisplayLines, total_matched: usize, total_processed: usize, ) { if self.stopped.load(Ordering::Relaxed) { return; } let _ = self.vim.exec( "clap#state#process_progress_full", json!([display_lines, total_matched, total_processed]), ); } fn on_finished( &self, display_lines: DisplayLines, total_matched: usize, total_processed: usize, ) { if self.stopped.load(Ordering::Relaxed) { return; } let _ = self.vim.exec( "clap#state#process_progress_full", json!([display_lines, total_matched, total_processed]), ); } } // Vim may return 1/0 for true/false. #[inline(always)] fn from_vim_bool(value: Value) -> bool { match value { Value::Bool(b) => b, Value::Number(n) => n.as_u64().map(|n| n == 1).unwrap_or(false), _ => false, } } /// Shareable Vim instance. #[derive(Debug, Clone)] pub struct Vim { rpc_client: Arc<RpcClient>, } impl Vim { /// Constructs a [`Vim`]. pub fn new(rpc_client: Arc<RpcClient>) -> Self { Self { rpc_client } } /// Calls the method with given params in Vim and return the call result. /// /// `method`: Must be a valid argument for `clap#api#call(method, args)`. pub async fn call<R: DeserializeOwned>( &self, method: impl AsRef<str>, params: impl Serialize, ) -> Result<R> { self.rpc_client .request(method, params) .await .map_err(|e| anyhow!("RpcError: {e:?}")) } /// Calls the method with no arguments. pub async fn bare_call<R: DeserializeOwned>(&self, method: impl AsRef<str>) -> Result<R> { self.rpc_client .request(method, json!([])) .await .map_err(|e| anyhow!("RpcError: {e:?}")) } /// Executes the method with given params in Vim, ignoring the call result. /// /// `method`: Same with `{func}` in `:h call()`. pub fn exec(&self, method: impl AsRef<str>, params: impl Serialize) -> Result<()> { self.rpc_client .notify(method, params) .map_err(|e| anyhow!("RpcError: {e:?}")) } /// Executes the method with no arguments. pub fn bare_exec(&self, method: impl AsRef<str>) -> Result<()> { self.rpc_client .notify(method, json!([])) .map_err(|e| anyhow!("RpcError: {e:?}")) } /// Send back the result with specified id. pub fn send_response( &self, id: u64, output_result: Result<impl Serialize, rpc::RpcError>, ) -> Result<()> { self.rpc_client .send_response(id, output_result) .map_err(|e| anyhow!("RpcError: {e:?}")) } ///////////////////////////////////////////////////////////////// // builtin-function-list ///////////////////////////////////////////////////////////////// pub async fn bufname(&self, bufnr: usize) -> Result<String> { self.call("bufname", [bufnr]).await } pub async fn bufnr(&self, buf: impl Serialize) -> Result<usize> { let bufnr: i32 = self.call("bufnr", [buf]).await?; if bufnr < 0 { Err(anyhow!("buffer doesn't exist")) } else { Ok(bufnr as usize) } } pub async fn col(&self, expr: &str) -> Result<usize> { self.call("col", [expr]).await } pub async fn deletebufline( &self, buf: impl Serialize + Debug, first: usize, last: usize, ) -> Result<()> { let ret: u32 = self .call("deletebufline", json!([buf, first, last])) .await?; if ret == 1 { return Err(anyhow!("`deletebufline({buf:?}, {first}, {last})` failure")); } Ok(()) } pub async fn expand(&self, string: impl AsRef<str>) -> Result<String> { self.call("expand", [string.as_ref()]).await } pub async fn eval<R: DeserializeOwned>(&self, s: &str) -> Result<R> { self.call("eval", [s]).await } pub async fn fnamemodify(&self, fname: &str, mods: &str) -> Result<String> { self.call("fnamemodify", [fname, mods]).await } pub async fn getbufoneline(&self, buf: impl Serialize, lnum: usize) -> Result<String> { self.call("getbufoneline", (buf, lnum)).await } pub async fn getbufvar<R: DeserializeOwned>( &self, buf: impl Serialize, varname: &str, ) -> Result<R> { self.call("getbufvar", (buf, varname)).await } pub async fn getbufline( &self, buf: impl Serialize, start: impl Serialize, end: impl Serialize, ) -> Result<Vec<String>> { self.call("getbufline", (buf, start, end)).await } pub async fn getpos(&self, expr: &str) -> Result<[usize; 4]> { self.call("getpos", [expr]).await } pub async fn line(&self, expr: &str) -> Result<usize> { self.call("line", [expr]).await } pub async fn matchdelete(&self, id: i32, win: usize) -> Result<i32> { self.call("matchdelete", (id, win)).await } pub fn setbufvar(&self, bufnr: usize, varname: &str, val: impl Serialize) -> Result<()> { self.exec("setbufvar", (bufnr, varname, val)) } pub async fn winwidth(&self, winid: usize) -> Result<usize> { let width: i32 = self.call("winwidth", [winid]).await?; if width < 0 { Err(anyhow!("window {winid} doesn't exist")) } else { Ok(width as usize) } } pub async fn winheight(&self, winid: usize) -> Result<usize> { let height: i32 = self.call("winheight", [winid]).await?; if height < 0 { Err(anyhow!("window {winid} doesn't exist")) } else { Ok(height as usize) } } ///////////////////////////////////////////////////////////////// // Clap related APIs ///////////////////////////////////////////////////////////////// /// Returns the cursor line in display window, with icon stripped. pub async fn display_getcurline(&self) -> Result<String> { let value: Value = self.bare_call("display_getcurline").await?; match value { Value::Array(arr) => { let icon_added_by_maple = arr[1].as_bool().unwrap_or(false); let curline = match arr.into_iter().next() { Some(Value::String(s)) => s, e => return Err(anyhow!("curline expects a String, but got {e:?}")), }; if icon_added_by_maple { Ok(curline.chars().skip(2).collect()) } else { Ok(curline) } } _ => Err(anyhow!( "Invalid return value of `s:api.display_getcurline()`, [String, Bool] expected" )), } } pub async fn display_getcurlnum(&self) -> Result<usize> { self.eval("g:clap.display.getcurlnum()").await } pub async fn input_get(&self) -> Result<String> { self.eval("g:clap.input.get()").await } pub async fn provider_args(&self) -> Result<Vec<String>> { self.bare_call("provider_args").await } pub async fn working_dir(&self) -> Result<AbsPathBuf> { self.bare_call("clap#rooter#working_dir").await } pub async fn current_buffer_path(&self) -> Result<String> { self.bare_call("current_buffer_path").await } pub async fn curbufline(&self, lnum: usize) -> Result<Option<String>> { self.call("curbufline", [lnum]).await } pub fn set_preview_syntax(&self, syntax: &str) -> Result<()> { self.exec("eval", [format!("g:clap.preview.set_syntax('{syntax}')")]) } ///////////////////////////////////////////////////////////////// // General helpers ///////////////////////////////////////////////////////////////// pub fn echo_info(&self, msg: impl AsRef<str>) -> Result<()> { self.exec("clap#helper#echo_info", [msg.as_ref()]) } pub fn echo_warn(&self, msg: impl AsRef<str>) -> Result<()> { self.exec("clap#helper#echo_warn", [msg.as_ref()]) } pub async fn bufmodified(&self, bufnr: impl Serialize) -> Result<bool> { self.getbufvar::<u32>(bufnr, "&modified") .await .map(|m| m == 1u32) } pub async fn current_winid(&self) -> Result<usize> { self.bare_call("win_getid").await } pub async fn get_var_bool(&self, var: &str) -> Result<bool> { let value: Value = self.call("get_var", [var]).await?; Ok(from_vim_bool(value)) } pub async fn matchdelete_batch(&self, ids: Vec<i32>, win: usize) -> Result<()> { if self.win_is_valid(win).await? { self.exec("matchdelete_batch", (ids, win))?; } Ok(()) } /// Size for fulfilling the preview window. pub async fn preview_size( &self, provider_id: &ProviderId, preview_winid: usize, ) -> Result<usize> { let preview_winheight: usize = self.call("winheight", [preview_winid]).await?; let preview_size: Value = self.call("get_var", ["clap_preview_size"]).await?; let preview_config: PreviewConfig = preview_size.into(); Ok(preview_config .preview_size(provider_id.as_str()) .max(preview_winheight / 2)) } pub fn set_var(&self, var_name: &str, value: impl Serialize) -> Result<()> { self.exec("set_var", (var_name, value)) } pub async fn win_is_valid(&self, winid: usize) -> Result<bool> { let value: Value = self.call("win_is_valid", [winid]).await?; Ok(from_vim_bool(value)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_preview_config_deserialize() { let v: Value = serde_json::json!({"filer": 10, "files": 5}); let _config: PreviewConfig = v.into(); } }
// Copyright 2015 The tiny-http Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub use self::custom_stream::CustomStream; pub use self::equal_reader::EqualReader; pub use self::messages_queue::MessagesQueue; pub use self::refined_tcp_stream::RefinedTcpStream; pub use self::sequential::{SequentialReaderBuilder, SequentialReader}; pub use self::sequential::{SequentialWriterBuilder, SequentialWriter}; pub use self::task_pool::TaskPool; use std::str::FromStr; mod custom_stream; mod equal_reader; mod messages_queue; mod refined_tcp_stream; mod sequential; mod task_pool; /// Parses a the value of a header. /// Suitable for `Accept-*`, `TE`, etc. /// /// For example with `text/plain, image/png; q=1.5` this function would /// return `[ ("text/plain", 1.0), ("image/png", 1.5) ]` pub fn parse_header_value<'a>(input: &'a str) -> Vec<(&'a str, f32)> { input.split(',').filter_map(|elem| { let mut params = elem.split(';'); let t = params.next(); if t.is_none() { return None; } let mut value = 1.0f32; for p in params { if p.trim_left().starts_with("q=") { match FromStr::from_str(&p.trim_left()[2..].trim()) { Ok(val) => { value = val; break }, _ => () } } } Some((t.unwrap().trim(), value)) }).collect() } #[cfg(test)] mod test { #[test] fn test_parse_header() { let result = super::parse_header_value("text/html, text/plain; q=1.5 , image/png ; q=2.0"); assert_eq!(result.len(), 3); assert_eq!(result[0].0, "text/html"); assert_eq!(result[0].1, 1.0); assert_eq!(result[1].0, "text/plain"); assert_eq!(result[1].1, 1.5); assert_eq!(result[2].0, "image/png"); assert_eq!(result[2].1, 2.0); } }
use super::super::AsGtkDialog; use crate::FileDialog; use gtk_sys::GtkFileChooserNative; use std::{ ffi::{CStr, CString}, path::{Path, PathBuf}, ptr, }; #[repr(i32)] pub enum GtkFileChooserAction { Open = 0, Save = 1, SelectFolder = 2, // CreateFolder = 3, } pub struct GtkFileDialog { pub ptr: *mut GtkFileChooserNative, } impl GtkFileDialog { fn new(title: &str, action: GtkFileChooserAction, btn1: &str, btn2: &str) -> Self { let title = CString::new(title).unwrap(); let btn1 = CString::new(btn1).unwrap(); let btn2 = CString::new(btn2).unwrap(); let ptr = unsafe { let dialog = gtk_sys::gtk_file_chooser_native_new( title.as_ptr(), ptr::null_mut(), action as i32, btn2.as_ptr(), btn1.as_ptr(), ); dialog as _ }; Self { ptr } } fn add_filters(&mut self, filters: &[crate::dialog::Filter]) { for f in filters.iter() { if let Ok(name) = CString::new(f.name.as_str()) { unsafe { let filter = gtk_sys::gtk_file_filter_new(); let paterns: Vec<_> = f .extensions .iter() .filter_map(|e| CString::new(format!("*.{}", e)).ok()) .collect(); gtk_sys::gtk_file_filter_set_name(filter, name.as_ptr()); for p in paterns.iter() { gtk_sys::gtk_file_filter_add_pattern(filter, p.as_ptr()); } gtk_sys::gtk_file_chooser_add_filter(self.ptr as _, filter); } } } } fn set_file_name(&self, name: Option<&str>) { if let Some(name) = name { if let Ok(name) = CString::new(name) { unsafe { gtk_sys::gtk_file_chooser_set_filename(self.ptr as _, name.as_ptr()); } } } } fn set_path(&self, path: Option<&Path>) { if let Some(path) = path { if let Some(path) = path.to_str() { if let Ok(path) = CString::new(path) { unsafe { gtk_sys::gtk_file_chooser_set_current_folder(self.ptr as _, path.as_ptr()); } } } } } pub fn get_result(&self) -> Option<PathBuf> { let cstr = unsafe { let chosen_filename = gtk_sys::gtk_file_chooser_get_filename(self.ptr as _); CStr::from_ptr(chosen_filename).to_str() }; if let Ok(cstr) = cstr { Some(PathBuf::from(cstr.to_owned())) } else { None } } pub fn get_results(&self) -> Vec<PathBuf> { #[derive(Debug)] struct FileList(*mut glib_sys::GSList); impl Iterator for FileList { type Item = glib_sys::GSList; fn next(&mut self) -> Option<Self::Item> { let curr_ptr = self.0; if !curr_ptr.is_null() { let curr = unsafe { *curr_ptr }; self.0 = curr.next; Some(curr) } else { None } } } let chosen_filenames = unsafe { gtk_sys::gtk_file_chooser_get_filenames(self.ptr as *mut _) }; let paths: Vec<PathBuf> = FileList(chosen_filenames) .filter_map(|item| { let cstr = unsafe { CStr::from_ptr(item.data as _).to_str() }; if let Ok(cstr) = cstr { Some(PathBuf::from(cstr.to_owned())) } else { None } }) .collect(); paths } pub fn run(&self) -> i32 { unsafe { gtk_sys::gtk_native_dialog_run(self.ptr as *mut _) } } } impl GtkFileDialog { pub fn build_pick_file(opt: &FileDialog) -> Self { let mut dialog = GtkFileDialog::new("Open File", GtkFileChooserAction::Open, "Cancel", "Open"); dialog.add_filters(&opt.filters); dialog.set_path(opt.starting_directory.as_deref()); dialog.set_file_name(opt.file_name.as_deref()); dialog } pub fn build_save_file(opt: &FileDialog) -> Self { let mut dialog = GtkFileDialog::new("Save File", GtkFileChooserAction::Save, "Cancel", "Save"); unsafe { gtk_sys::gtk_file_chooser_set_do_overwrite_confirmation(dialog.ptr as _, 1) }; dialog.add_filters(&opt.filters); dialog.set_path(opt.starting_directory.as_deref()); dialog.set_file_name(opt.file_name.as_deref()); dialog } pub fn build_pick_folder(opt: &FileDialog) -> Self { let dialog = GtkFileDialog::new( "Select Folder", GtkFileChooserAction::SelectFolder, "Cancel", "Select", ); dialog.set_path(opt.starting_directory.as_deref()); dialog.set_file_name(opt.file_name.as_deref()); dialog } pub fn build_pick_files(opt: &FileDialog) -> Self { let mut dialog = GtkFileDialog::new("Open File", GtkFileChooserAction::Open, "Cancel", "Open"); unsafe { gtk_sys::gtk_file_chooser_set_select_multiple(dialog.ptr as _, 1) }; dialog.add_filters(&opt.filters); dialog.set_path(opt.starting_directory.as_deref()); dialog.set_file_name(opt.file_name.as_deref()); dialog } } impl AsGtkDialog for GtkFileDialog { fn gtk_dialog_ptr(&self) -> *mut gtk_sys::GtkDialog { self.ptr as *mut _ } unsafe fn show(&self) { gtk_sys::gtk_native_dialog_show(self.ptr as *mut _); } } impl Drop for GtkFileDialog { fn drop(&mut self) { unsafe { super::super::utils::wait_for_cleanup(); gtk_sys::gtk_native_dialog_destroy(self.ptr as _); super::super::utils::wait_for_cleanup(); } } }
#[cfg(target_arch = "x86_64")] pub use self::x86_64::io::*; mod x86_64 { pub mod io; }
pub use id_types::*; pub use basics_data::*; pub use loot_data::*; pub use suppressable_data::*; pub use damage_data::*; pub use elemental_spells_data::*; pub use spellbook_data::*; pub use plant_spells_data::*; pub use basic_spells_data::*; pub use drawn_data::*; pub use player_data::*; pub use sprite_mappings::*; pub use monster_data::*; pub use wolf_data::*; pub use monster_spawner_data::*; pub use terrain_data::*; pub use grass_biome_data::*; use rand::XorShiftRng; pub use rand::Rng; pub use gvec::*; pub use rand; pub use utils::*; pub use std::collections::HashMap; pub struct Game1{ pub lagged: bool, pub rand_gen: XorShiftRng, pub timer: u64, pub allegiance_counter: u32, pub entity_processing_level: u64, pub movers: GVec<Mover>, pub orbiters: GVec<Orbiter>, pub players: GVec<Player>, pub timers: GVec<Timer>, pub disabled_movers: GVec<DisabledMover>, pub suppressables: GVec<Suppressable>, //DRAWN pub drawn_counter: u32, pub drawn: GVec<Drawn>, pub basic_drawn: GVec<BasicDrawn>, pub health_drawn: GVec<HealthDrawn>, //TERRAIN pub chunks: HashMap<(i64,i64), Chunk>, pub chunk_loaders: GVec<ChunkLoader>, pub basic_chunk_loaders: GVec<BasicChunkLoader>, pub damageable_terrain_watchers:HashMap<(i64,i64),DamageableTerrainWatcher>, pub terrain_damageables: GVec<Damageable>, //DAMAGE pub damageables: GVec<Damageable>, pub damagers: GVec<Damager>, pub projectiles: GVec<Projectile>, pub allegiances: GVec<Allegiance>, //MONSTERS pub monster_spawner: MonsterSpawner, pub zombies: GVec<Zombie>, pub dead_zombies: Vec<usize>, pub prey: GVec<Prey>, pub wolves: GVec<Wolf>, pub dead_wolves: Vec<usize>, pub packs: GVec<Pack>, pub dead_packs: Vec<usize>, //MAGIC pub casters: GVec<Caster>, pub spells: Vec<Box<Spell>>, pub spellbooks: GVec<Spellbook>, //PLANT SPELLS pub spitters: GVec<Spitter>, pub spitter_watchers: GVec<SpitterWatcher> } impl Game1{ pub fn new()->Self{ Game1{ lagged: false, rand_gen: rand::weak_rng(), timer: 0, drawn_counter: 0, allegiance_counter: 0, entity_processing_level: 0, movers: GVec::new(), drawn: GVec::new(), basic_drawn: GVec::new(), health_drawn: GVec::new(), players: GVec::new(), chunks: HashMap::new(), chunk_loaders: GVec::new(), basic_chunk_loaders: GVec::new(), casters: GVec::new(), spells: Vec::new(), spellbooks: GVec::new(), damageables: GVec::new(), damagers: GVec::new(), projectiles: GVec::new(), allegiances: GVec::new(), timers: GVec::new(), disabled_movers: GVec::new(), orbiters: GVec::new(), suppressables: GVec::new(), zombies: GVec::new(), dead_zombies: Vec::new(), prey: GVec::new(), wolves: GVec::new(), dead_wolves: Vec::new(), packs: GVec::new(), dead_packs: Vec::new(), monster_spawner: MonsterSpawner::default(), spitters: GVec::new(), spitter_watchers: GVec::new(), damageable_terrain_watchers: HashMap::new(), terrain_damageables: GVec::new() } } }
use bintree::Tree; use P57::*; pub fn main() { let mut tree = Tree::end(); add_value(&mut tree, 2); println!("add 2: {}", tree); add_value(&mut tree, 3); println!("add 3: {}", tree); add_value(&mut tree, 0); println!("add 0: {}", tree); }
use stream::Stream; use executor; /// A stream combinator which converts an asynchronous stream to a **blocking /// iterator**. /// /// Created by the `Stream::wait` method, this function transforms any stream /// into a standard iterator. This is implemented by blocking the current thread /// while items on the underlying stream aren't ready yet. #[must_use = "iterators do nothing unless advanced"] #[derive(Debug)] pub struct Wait<S> { stream: executor::Spawn<S>, } impl<S> Wait<S> { /// Acquires a reference to the underlying stream that this combinator is /// pulling from. pub fn get_ref(&self) -> &S { self.stream.get_ref() } /// Acquires a mutable reference to the underlying stream that this /// combinator is pulling from. /// /// Note that care must be taken to avoid tampering with the state of the /// stream which may otherwise confuse this combinator. pub fn get_mut(&mut self) -> &mut S { self.stream.get_mut() } /// Consumes this combinator, returning the underlying stream. /// /// Note that this may discard intermediate state of this combinator, so /// care should be taken to avoid losing resources when this is called. pub fn into_inner(self) -> S { self.stream.into_inner() } } pub fn new<S: Stream>(s: S) -> Wait<S> { Wait { stream: executor::spawn(s), } } impl<S: Stream> Iterator for Wait<S> { type Item = Result<S::Item, S::Error>; fn next(&mut self) -> Option<Self::Item> { self.stream.wait_stream() } }