text stringlengths 8 4.13M |
|---|
use crate::data::RideData;
use crate::data::RideWindowedData;
fn agg_u64(buffer: &[RideData], f: impl FnMut(&RideData) -> u64 + Copy) -> (u64, u64, u64, u64) {
let count = buffer.len() as u64;
let sum = buffer.iter().map(f).sum();
let max = buffer.iter().map(f).max().unwrap();
let min = buffer.iter().map(f).min().unwrap();
let avg = sum / count;
(sum, max, min, avg)
}
fn agg_f32(buffer: &[RideData], f: impl FnMut(&RideData) -> f32) -> (f32, f32) {
let count = buffer.len() as f32;
let sum = buffer.iter().map(f).sum();
let avg = sum / count;
(sum, avg)
}
pub fn window_sum(buffer: &[RideData]) -> RideWindowedData {
let count = buffer.len() as u64;
let (sum_fare_amount, max_fare_amount, avg_fare_amount, min_fare_amount) =
agg_u64(buffer, |x| x.fare_amount);
let (sum_trip_distance, avg_trip_distance) = agg_f32(buffer, |x| x.trip_distance);
let (sum_passenger_count, max_passenger_count, avg_passenger_count, min_passenger_count) =
agg_u64(buffer, |x| x.passenger_count);
let (sum_duration, max_duration, avg_duration, min_duration) =
agg_u64(buffer, |x| x.do_time.checked_sub(x.pu_time).unwrap_or(0));
let pu_location_id = buffer[0].pu_location_id;
let pu_time = buffer[0].pu_time;
let pu_location_name = loc_to_name(pu_location_id);
RideWindowedData {
pu_location_id,
pu_time,
pu_location_name,
count,
sum_fare_amount,
max_fare_amount,
avg_fare_amount,
min_fare_amount,
sum_trip_distance,
avg_trip_distance,
sum_passenger_count,
max_passenger_count,
avg_passenger_count,
min_passenger_count,
sum_duration,
max_duration,
avg_duration,
min_duration,
}
}
fn loc_to_name(loc: u64) -> String {
match loc {
1 => "EWR, Newark Airport",
2 => "Queens, Jamaica Bay",
3 => "Bronx, Allerton/Pelham Gardens",
4 => "Manhattan, Alphabet City",
5 => "Staten Island, Arden Heights",
6 => "Staten Island, Arrochar/Fort Wadsworth",
7 => "Queens, Astoria",
8 => "Queens, Astoria Park",
9 => "Queens, Auburndale",
10 => "Queens, Baisley Park",
11 => "Brooklyn, Bath Beach",
12 => "Manhattan, Battery Park",
13 => "Manhattan, Battery Park City",
14 => "Brooklyn, Bay Ridge",
15 => "Queens, Bay Terrace/Fort Totten",
16 => "Queens, Bayside",
17 => "Brooklyn, Bedford",
18 => "Bronx, Bedford Park",
19 => "Queens, Bellerose",
20 => "Bronx, Belmont",
21 => "Brooklyn, Bensonhurst East",
22 => "Brooklyn, Bensonhurst West",
23 => "Staten Island, Bloomfield/Emerson Hill",
24 => "Manhattan, Bloomingdale",
25 => "Brooklyn, Boerum Hill",
26 => "Brooklyn, Borough Park",
27 => "Queens, Breezy Point/Fort Tilden/Riis Beach",
28 => "Queens, Briarwood/Jamaica Hills",
29 => "Brooklyn, Brighton Beach",
30 => "Queens, Broad Channel",
31 => "Bronx, Bronx Park",
32 => "Bronx, Bronxdale",
33 => "Brooklyn, Brooklyn Heights",
34 => "Brooklyn, Brooklyn Navy Yard",
35 => "Brooklyn, Brownsville",
36 => "Brooklyn, Bushwick North",
37 => "Brooklyn, Bushwick South",
38 => "Queens, Cambria Heights",
39 => "Brooklyn, Canarsie",
40 => "Brooklyn, Carroll Gardens",
41 => "Manhattan, Central Harlem",
42 => "Manhattan, Central Harlem North",
43 => "Manhattan, Central Park",
44 => "Staten Island, Charleston/Tottenville",
45 => "Manhattan, Chinatown",
46 => "Bronx, City Island",
47 => "Bronx, Claremont/Bathgate",
48 => "Manhattan, Clinton East",
49 => "Brooklyn, Clinton Hill",
50 => "Manhattan, Clinton West",
51 => "Bronx, Co-Op City",
52 => "Brooklyn, Cobble Hill",
53 => "Queens, College Point",
54 => "Brooklyn, Columbia Street",
55 => "Brooklyn, Coney Island",
56 => "Queens, Corona",
57 => "Queens, Corona",
58 => "Bronx, Country Club",
59 => "Bronx, Crotona Park",
60 => "Bronx, Crotona Park East",
61 => "Brooklyn, Crown Heights North",
62 => "Brooklyn, Crown Heights South",
63 => "Brooklyn, Cypress Hills",
64 => "Queens, Douglaston",
65 => "Brooklyn, Downtown Brooklyn/MetroTech",
66 => "Brooklyn, DUMBO/Vinegar Hill",
67 => "Brooklyn, Dyker Heights",
68 => "Manhattan, East Chelsea",
69 => "Bronx, East Concourse/Concourse Village",
70 => "Queens, East Elmhurst",
71 => "Brooklyn, East Flatbush/Farragut",
72 => "Brooklyn, East Flatbush/Remsen Village",
73 => "Queens, East Flushing",
74 => "Manhattan, East Harlem North",
75 => "Manhattan, East Harlem South",
76 => "Brooklyn, East New York",
77 => "Brooklyn, East New York/Pennsylvania Avenue",
78 => "Bronx, East Tremont",
79 => "Manhattan, East Village",
80 => "Brooklyn, East Williamsburg",
81 => "Bronx, Eastchester",
82 => "Queens, Elmhurst",
83 => "Queens, Elmhurst/Maspeth",
84 => "Staten Island, Eltingville/Annadale/Prince's Bay",
85 => "Brooklyn, Erasmus",
86 => "Queens, Far Rockaway",
87 => "Manhattan, Financial District North",
88 => "Manhattan, Financial District South",
89 => "Brooklyn, Flatbush/Ditmas Park",
90 => "Manhattan, Flatiron",
91 => "Brooklyn, Flatlands",
92 => "Queens, Flushing",
93 => "Queens, Flushing Meadows-Corona Park",
94 => "Bronx, Fordham South",
95 => "Queens, Forest Hills",
96 => "Queens, Forest Park/Highland Park",
97 => "Brooklyn, Fort Greene",
98 => "Queens, Fresh Meadows",
99 => "Staten, Island Freshkills Park",
100 => "Manhattan, Garment District",
101 => "Queens, Glen Oaks",
102 => "Queens, Glendale",
103 => "Manhattan, Governor's Island/Ellis Island/Liberty Island",
104 => "Manhattan, Governor's Island/Ellis Island/Liberty Island",
105 => "Manhattan, Governor's Island/Ellis Island/Liberty Island",
106 => "Brooklyn, Gowanus",
107 => "Manhattan, Gramercy",
108 => "Brooklyn, Gravesend",
109 => "Staten, Island Great Kills",
110 => "Staten, Island Great Kills Park",
111 => "Brooklyn, Green-Wood Cemetery",
112 => "Brooklyn, Greenpoint",
113 => "Manhattan, Greenwich Village North",
114 => "Manhattan, Greenwich Village South",
115 => "Staten Island, Grymes Hill/Clifton",
116 => "Manhattan, Hamilton Heights",
117 => "Queens, Hammels/Arverne",
118 => "Staten Island, Heartland Village/Todt Hill",
119 => "Bronx, Highbridge",
120 => "Manhattan, Highbridge Park",
121 => "Queens, Hillcrest/Pomonok",
122 => "Queens, Hollis",
123 => "Brooklyn, Homecrest",
124 => "Queens, Howard Beach",
125 => "Manhattan, Hudson Sq",
126 => "Bronx, Hunts Point",
127 => "Manhattan, Inwood",
128 => "Manhattan, Inwood Hill Park",
129 => "Queens, Jackson Heights",
130 => "Queens, Jamaica",
131 => "Queens, Jamaica Estates",
132 => "Queens, JFK Airport",
133 => "Brooklyn, Kensington",
134 => "Queens, Kew Gardens",
135 => "Queens, Kew Gardens Hills",
136 => "Bronx, Kingsbridge Heights",
137 => "Manhattan, Kips Bay",
138 => "Queens, LaGuardia Airport",
139 => "Queens, Laurelton",
140 => "Manhattan, Lenox Hill East",
141 => "Manhattan, Lenox Hill West",
142 => "Manhattan, Lincoln Square East",
143 => "Manhattan, Lincoln Square West",
144 => "Manhattan, Little Italy/NoLiTa",
145 => "Queens, Long Island City/Hunters Point",
146 => "Queens, Long Island City/Queens Plaza",
147 => "Bronx, Longwood",
148 => "Manhattan, Lower East Side",
149 => "Brooklyn, Madison",
150 => "Brooklyn, Manhattan Beach",
151 => "Manhattan, Manhattan Valley",
152 => "Manhattan, Manhattanville",
153 => "Manhattan, Marble Hill",
154 => "Brooklyn, Marine Park/Floyd Bennett Field",
155 => "Brooklyn, Marine Park/Mill Basin",
156 => "Staten Island, Mariners Harbor",
157 => "Queens, Maspeth",
158 => "Manhattan, Meatpacking/West Village West",
159 => "Bronx, Melrose South",
160 => "Queens, Middle Village",
161 => "Manhattan, Midtown Center",
162 => "Manhattan, Midtown East",
163 => "Manhattan, Midtown North",
164 => "Manhattan, Midtown South",
165 => "Brooklyn, Midwood",
166 => "Manhattan, Morningside Heights",
167 => "Bronx, Morrisania/Melrose",
168 => "Bronx, Mott Haven/Port Morris",
169 => "Bronx, Mount Hope",
170 => "Manhattan, Murray Hill",
171 => "Queens, Murray Hill-Queens",
172 => "Staten Island, New Dorp/Midland Beach",
173 => "Queens, North Corona",
174 => "Bronx, Norwood",
175 => "Queens, Oakland Gardens",
176 => "Staten, Island Oakwood",
177 => "Brooklyn, Ocean Hill",
178 => "Brooklyn, Ocean Parkway South",
179 => "Queens, Old Astoria",
180 => "Queens, Ozone Park",
181 => "Brooklyn, Park Slope",
182 => "Bronx, Parkchester",
183 => "Bronx, Pelham Bay",
184 => "Bronx, Pelham Bay Park",
185 => "Bronx, Pelham Parkway",
186 => "Manhattan, Penn Station/Madison Sq West",
187 => "Staten, Island Port Richmond",
188 => "Brooklyn, Prospect-Lefferts Gardens",
189 => "Brooklyn, Prospect Heights",
190 => "Brooklyn, Prospect Park",
191 => "Queens, Queens Village",
192 => "Queens, Queensboro Hill",
193 => "Queens, Queensbridge/Ravenswood",
194 => "Manhattan, Randalls Island",
195 => "Brooklyn, Red Hook",
196 => "Queens, Rego Park",
197 => "Queens, Richmond Hill",
198 => "Queens, Ridgewood",
199 => "Bronx, Rikers Island",
200 => "Bronx, Riverdale/North Riverdale/Fieldston",
201 => "Queens, Rockaway Park",
202 => "Manhattan, Roosevelt Island",
203 => "Queens, Rosedale",
204 => "Staten Island, Rossville/Woodrow",
205 => "Queens, Saint Albans",
206 => "Staten Island, Saint George/New Brighton",
207 => "Queens, Saint Michaels Cemetery/Woodside",
208 => "Bronx, Schuylerville/Edgewater Park",
209 => "Manhattan, Seaport",
210 => "Brooklyn, Sheepshead Bay",
211 => "Manhattan, SoHo",
212 => "Bronx, Soundview/Bruckner",
213 => "Bronx, Soundview/Castle Hill",
214 => "Staten Island, South Beach/Dongan Hills",
215 => "Queens, South Jamaica",
216 => "Queens, South Ozone Park",
217 => "Brooklyn, South Williamsburg",
218 => "Queens, Springfield Gardens North",
219 => "Queens, Springfield Gardens South",
220 => "Bronx, Spuyten Duyvil/Kingsbridge",
221 => "Staten, Island Stapleton",
222 => "Brooklyn, Starrett City",
223 => "Queens, Steinway",
224 => "Manhattan, Stuy Town/Peter Cooper Village",
225 => "Brooklyn, Stuyvesant Heights",
226 => "Queens, Sunnyside",
227 => "Brooklyn, Sunset Park East",
228 => "Brooklyn, Sunset Park West",
229 => "Manhattan, Sutton Place/Turtle Bay North",
230 => "Manhattan, Times Sq/Theatre District",
231 => "Manhattan, TriBeCa/Civic Center",
232 => "Manhattan, Two Bridges/Seward Park",
233 => "Manhattan, UN/Turtle Bay South",
234 => "Manhattan, Union Sq",
235 => "Bronx, University Heights/Morris Heights",
236 => "Manhattan, Upper East Side North",
237 => "Manhattan, Upper East Side South",
238 => "Manhattan, Upper West Side North",
239 => "Manhattan, Upper West Side South",
240 => "Bronx Van, Cortlandt Park",
241 => "Bronx Van, Cortlandt Village",
242 => "Bronx Van, Nest/Morris Park",
243 => "Manhattan, Washington Heights North",
244 => "Manhattan, Washington Heights South",
245 => "Staten Island, West Brighton",
246 => "Manhattan, West Chelsea/Hudson Yards",
247 => "Bronx, West Concourse",
248 => "Bronx, West Farms/Bronx River",
249 => "Manhattan, West Village",
250 => "Bronx, Westchester Village/Unionport",
251 => "Staten Island, Westerleigh",
252 => "Queens, Whitestone",
253 => "Queens, Willets Point",
254 => "Bronx, Williamsbridge/Olinville",
255 => "Brooklyn, Williamsburg (North Side)",
256 => "Brooklyn, Williamsburg (South Side)",
257 => "Brooklyn, Windsor Terrace",
258 => "Queens, Woodhaven",
259 => "Bronx, Woodlawn/Wakefield",
260 => "Queens, Woodside",
261 => "Manhattan, World Trade Center",
262 => "Manhattan, Yorkville East",
263 => "Manhattan, Yorkville West",
264 => "Unknown, NV",
265 => "Unknown, NA",
_ => panic!("Unknown location id"),
}
.to_owned()
}
|
use prelude::*;
mod utills;
mod give;
mod info;
mod start;
pub fn register_command(sf: StandardFramework) -> StandardFramework {
sf.group("bp", |mut g| {
chain!(g;
give::register_command(g),
info::register_command(g),
start::register_command(g)
).prefix("bp")
})
}
|
use crate::domain::{BlockHeight, BlockTimestamp, EpochHeight};
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
env,
};
use std::cmp::Ordering;
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, Copy, PartialEq, Default)]
pub struct BlockTimeHeight {
block_height: BlockHeight,
block_timestamp: BlockTimestamp,
epoch_height: EpochHeight,
}
impl PartialOrd for BlockTimeHeight {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.block_height.cmp(&other.block_height))
}
}
impl BlockTimeHeight {
/// [block_height](BlockTimeHeight::block_height), [block_timestamp](BlockTimeHeight::block_timestamp),
/// and [epoch_height](BlockTimeHeight::epoch_height) are initialized from the NEAR runtime
/// environment
///
/// ## Panics
/// if NEAR runtime context is not available
pub fn from_env() -> Self {
Self {
block_height: env::block_index().into(),
block_timestamp: env::block_timestamp().into(),
epoch_height: env::epoch_height().into(),
}
}
pub fn block_height(&self) -> BlockHeight {
self.block_height
}
pub fn block_timestamp(&self) -> BlockTimestamp {
self.block_timestamp
}
pub fn epoch_height(&self) -> EpochHeight {
self.epoch_height
}
/// ## Panics
/// if Near runtime env is not available
pub fn update_from_env(&mut self) {
self.epoch_height = env::epoch_height().into();
self.block_timestamp = env::block_timestamp().into();
self.block_height = env::block_index().into();
}
}
impl From<crate::interface::BlockTimeHeight> for BlockTimeHeight {
fn from(value: crate::interface::BlockTimeHeight) -> Self {
Self {
block_height: value.block_height.0 .0.into(),
block_timestamp: value.block_timestamp.0 .0.into(),
epoch_height: value.epoch_height.0 .0.into(),
}
}
}
|
//! The Unix `fcntl` function is effectively lots of different functions
//! hidden behind a single dynamic dispatch interface. In order to provide
//! a type-safe API, rustix makes them all separate functions so that they
//! can have dedicated static type signatures.
#[cfg(not(any(
target_os = "emscripten",
target_os = "espidf",
target_os = "fuchsia",
target_os = "redox",
target_os = "wasi"
)))]
use crate::fs::FlockOperation;
use crate::{backend, io};
use backend::fd::AsFd;
use backend::fs::types::OFlags;
// These `fcntl` functions live in the `io` module because they're not specific
// to files, directories, or memfd objects. We re-export them here in the `fs`
// module because the other the `fcntl` functions are here.
#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
pub use crate::io::fcntl_dupfd_cloexec;
pub use crate::io::{fcntl_getfd, fcntl_setfd};
/// `fcntl(fd, F_GETFL)`—Returns a file descriptor's access mode and status.
///
/// # References
/// - [POSIX]
/// - [Linux]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html
/// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html
#[inline]
#[doc(alias = "F_GETFL")]
pub fn fcntl_getfl<Fd: AsFd>(fd: Fd) -> io::Result<OFlags> {
backend::fs::syscalls::fcntl_getfl(fd.as_fd())
}
/// `fcntl(fd, F_SETFL, flags)`—Sets a file descriptor's status.
///
/// # References
/// - [POSIX]
/// - [Linux]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html
/// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html
#[inline]
#[doc(alias = "F_SETFL")]
pub fn fcntl_setfl<Fd: AsFd>(fd: Fd, flags: OFlags) -> io::Result<()> {
backend::fs::syscalls::fcntl_setfl(fd.as_fd(), flags)
}
/// `fcntl(fd, F_GET_SEALS)`
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html
#[cfg(any(linux_kernel, target_os = "freebsd", target_os = "fuchsia"))]
#[inline]
#[doc(alias = "F_GET_SEALS")]
pub fn fcntl_get_seals<Fd: AsFd>(fd: Fd) -> io::Result<SealFlags> {
backend::fs::syscalls::fcntl_get_seals(fd.as_fd())
}
#[cfg(any(linux_kernel, target_os = "freebsd", target_os = "fuchsia"))]
pub use backend::fs::types::SealFlags;
/// `fcntl(fd, F_ADD_SEALS)`
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html
#[cfg(any(linux_kernel, target_os = "freebsd", target_os = "fuchsia"))]
#[inline]
#[doc(alias = "F_ADD_SEALS")]
pub fn fcntl_add_seals<Fd: AsFd>(fd: Fd, seals: SealFlags) -> io::Result<()> {
backend::fs::syscalls::fcntl_add_seals(fd.as_fd(), seals)
}
/// `fcntl(fd, F_SETLK)`—Acquire or release an `fcntl`-style lock.
///
/// This function doesn't currently have an offset or len; it currently always
/// sets the `l_len` field to 0, which is a special case that means the entire
/// file should be locked.
///
/// Unlike `flock`-style locks, `fcntl`-style locks are process-associated,
/// meaning that they don't guard against being acquired by two threads in
/// the same process.
///
/// # References
/// - [POSIX]
/// - [Linux]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html
/// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html
#[cfg(not(any(
target_os = "emscripten",
target_os = "espidf",
target_os = "fuchsia",
target_os = "redox",
target_os = "wasi"
)))]
#[inline]
#[doc(alias = "F_SETLK")]
#[doc(alias = "F_SETLKW")]
pub fn fcntl_lock<Fd: AsFd>(fd: Fd, operation: FlockOperation) -> io::Result<()> {
backend::fs::syscalls::fcntl_lock(fd.as_fd(), operation)
}
|
use super::*;
use proptest::prop_oneof;
use proptest::strategy::Strategy;
#[test]
fn without_non_empty_list_or_bitstring_returns_true() {
run!(
|arc_process| {
strategy::term(arc_process.clone())
.prop_filter("Right cannot be a list or bitstring", |right| {
!(right.is_non_empty_list() || right.is_bitstring())
})
},
|right| {
let left = Term::NIL;
prop_assert_eq!(result(left, right), true.into());
Ok(())
},
);
}
#[test]
fn with_non_empty_list_or_bitstring_right_returns_false() {
run!(
|arc_process| {
prop_oneof![
strategy::term::list::non_empty_maybe_improper(arc_process.clone()),
strategy::term::is_bitstring(arc_process)
]
},
|right| {
let left = Term::NIL;
prop_assert_eq!(result(left, right), false.into());
Ok(())
},
);
}
|
use proconio::input;
use std::collections::BTreeSet;
fn main() {
input! {
q: usize,
};
let mut set = BTreeSet::new();
for i in 0..q {
input! {
op: u8,
};
if op == 1 {
input! {
x: u32,
};
set.insert((x, i));
} else if op == 2 {
input! {
x: u32,
c: usize,
};
let remove = set
.range((x, 0)..(x, std::usize::MAX))
.take(c)
.copied()
.collect::<Vec<_>>();
for e in remove {
set.remove(&e);
}
} else {
let (max, _) = set.iter().last().unwrap();
let (min, _) = set.iter().next().unwrap();
println!("{}", max - min);
}
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use serde::Deserialize;
/// item in manifest list file
/// read manifest file by this struct
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct ManifestPtr {
pub manifest_path: String,
pub manifest_length: usize,
pub partition_spec_id: usize,
pub added_snapshot_id: usize,
pub existing_data_files_count: usize,
pub deleted_data_files_count: usize,
pub partitions: Vec<ManiPart>,
pub added_rows_count: usize,
pub existing_rows_count: usize,
pub deleted_rows_count: usize,
}
/// item of manifest spec in `ManifestPtr`
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct ManiPart {
pub contains_null: bool,
pub lower_bound: String,
pub upper_bound: String,
}
/// manifest file
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct Manifest {
pub status: isize,
pub snapshot_id: i64,
pub data_file: DataFile,
}
/// data file
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct DataFile {
pub file_path: String,
pub file_format: String,
pub partition: HashMap<String, u64>,
pub record_count: usize,
pub file_size_in_bytes: usize,
pub block_size_in_bytes: usize,
pub column_sizes: HashMap<u64, u64>,
pub value_counts: HashMap<u64, u64>,
pub null_value_counts: HashMap<u64, u64>,
pub lower_bounds: HashMap<u64, String>,
pub upper_bounds: HashMap<u64, String>,
pub key_metadata: Option<String>,
pub split_offsets: Vec<u64>,
}
|
use super::{CodecError, CodecResult};
use crate::client::schema::{Dictionary, Event, List, Services, Set, Status, Stream, Tuple};
use crate::client::Connection;
use protobuf::{CodedInputStream, Message};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::hash::Hash;
pub trait Decode<'a>
where
Self: 'a + Sized,
{
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self>;
}
impl<'a> Decode<'a> for bool {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_bool()?))
}
}
impl<'a> Decode<'a> for i32 {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_sint32()?))
}
}
impl<'a> Decode<'a> for i64 {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_sint64()?))
}
}
impl<'a> Decode<'a> for u32 {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_uint32()?))
}
}
impl<'a> Decode<'a> for u64 {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_uint64()?))
}
}
impl<'a> Decode<'a> for f32 {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_float()?))
}
}
impl<'a> Decode<'a> for f64 {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_double()?))
}
}
impl<'a> Decode<'a> for String {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_string()?))
}
}
impl<'a> Decode<'a> for Vec<u8> {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
decode_with(bytes, |cis| Ok(cis.read_bytes()?))
}
}
impl<'a, T: Decode<'a>> Decode<'a> for Vec<T> {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut list = List::new();
list.merge_from_bytes(bytes.as_slice())?;
let mut decoded_vec = Vec::with_capacity(list.items.len());
for entry in list.items.iter() {
decoded_vec.push(T::decode(entry, connection)?);
}
Ok(decoded_vec)
}
}
impl<'a, K: Decode<'a> + Ord, V: Decode<'a>> Decode<'a> for BTreeMap<K, V> {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut dict = Dictionary::new();
dict.merge_from_bytes(bytes.as_slice())?;
let mut decoded_map = BTreeMap::new();
for entry in dict.entries.iter() {
decoded_map.insert(
K::decode(&entry.key, connection)?,
V::decode(&entry.value, connection)?,
);
}
Ok(decoded_map)
}
}
impl<'a, K: Decode<'a> + Eq + Hash, V: Decode<'a>> Decode<'a> for HashMap<K, V> {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut dict = Dictionary::new();
dict.merge_from_bytes(bytes.as_slice())?;
let mut decoded_map = HashMap::with_capacity(dict.entries.len());
for entry in dict.entries.iter() {
decoded_map.insert(
K::decode(&entry.key, connection)?,
V::decode(&entry.value, connection)?,
);
}
Ok(decoded_map)
}
}
impl<'a, T: Decode<'a> + Eq + Hash> Decode<'a> for HashSet<T> {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut set = Set::new();
set.merge_from_bytes(bytes.as_slice())?;
let mut decoded_set = HashSet::with_capacity(set.items.len());
for entry in set.items.iter() {
decoded_set.insert(T::decode(entry, connection)?);
}
Ok(decoded_set)
}
}
impl<'a, T: Decode<'a> + Ord> Decode<'a> for BTreeSet<T> {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut set = Set::new();
set.merge_from_bytes(bytes.as_slice())?;
let mut decoded_set = BTreeSet::new();
for entry in set.items.iter() {
decoded_set.insert(T::decode(entry, connection)?);
}
Ok(decoded_set)
}
}
impl<'a> Decode<'a> for () {
fn decode(_bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
Ok(())
}
}
impl<'a, T1: Decode<'a>> Decode<'a> for (T1,) {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut tuple = Tuple::new();
tuple.merge_from_bytes(bytes.as_slice())?;
if tuple.items.len() != 1 {
Err(CodecError::MismatchedTupleLength {
actual: tuple.items.len(),
expected: 1,
})?;
}
Ok((T1::decode(&tuple.get_items()[0], connection)?,))
}
}
impl<'a, T1: Decode<'a>, T2: Decode<'a>> Decode<'a> for (T1, T2) {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut tuple = Tuple::new();
tuple.merge_from_bytes(bytes.as_slice())?;
if tuple.items.len() != 2 {
Err(CodecError::MismatchedTupleLength {
actual: tuple.items.len(),
expected: 2,
})?;
}
Ok((
T1::decode(&tuple.get_items()[0], connection)?,
T2::decode(&tuple.get_items()[1], connection)?,
))
}
}
impl<'a, T1: Decode<'a>, T2: Decode<'a>, T3: Decode<'a>> Decode<'a> for (T1, T2, T3) {
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut tuple = Tuple::new();
tuple.merge_from_bytes(bytes.as_slice())?;
if tuple.items.len() != 3 {
Err(CodecError::MismatchedTupleLength {
actual: tuple.items.len(),
expected: 3,
})?;
}
Ok((
T1::decode(&tuple.get_items()[0], connection)?,
T2::decode(&tuple.get_items()[1], connection)?,
T3::decode(&tuple.get_items()[2], connection)?,
))
}
}
impl<'a, T1: Decode<'a>, T2: Decode<'a>, T3: Decode<'a>, T4: Decode<'a>> Decode<'a>
for (T1, T2, T3, T4)
{
fn decode(bytes: &Vec<u8>, connection: &'a Connection) -> CodecResult<Self> {
let mut tuple = Tuple::new();
tuple.merge_from_bytes(bytes.as_slice())?;
if tuple.items.len() != 4 {
Err(CodecError::MismatchedTupleLength {
actual: tuple.items.len(),
expected: 4,
})?;
}
Ok((
T1::decode(&tuple.get_items()[0], connection)?,
T2::decode(&tuple.get_items()[1], connection)?,
T3::decode(&tuple.get_items()[2], connection)?,
T4::decode(&tuple.get_items()[3], connection)?,
))
}
}
impl<'a> Decode<'a> for Services {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
let mut value = Self::new();
value.merge_from_bytes(bytes.as_slice())?;
Ok(value)
}
}
impl<'a> Decode<'a> for Status {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
let mut value = Self::new();
value.merge_from_bytes(bytes.as_slice())?;
Ok(value)
}
}
impl<'a> Decode<'a> for Stream {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
let mut value = Self::new();
value.merge_from_bytes(bytes.as_slice())?;
Ok(value)
}
}
impl<'a> Decode<'a> for Event {
fn decode(bytes: &Vec<u8>, _connection: &'a Connection) -> CodecResult<Self> {
let mut value = Self::new();
value.merge_from_bytes(bytes.as_slice())?;
Ok(value)
}
}
fn decode_with<T, F>(bytes: &Vec<u8>, decoder: F) -> CodecResult<T>
where
F: FnOnce(&mut CodedInputStream) -> CodecResult<T>,
{
let mut cis = CodedInputStream::from_bytes(bytes);
decoder(&mut cis)
}
|
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#![cfg_attr(feature="cargo-clippy", allow(let_and_return))]
use rabble::Pid;
use haret::vr::{ClientOp, VrState, VrCtx};
use super::arbitrary::{Op, ClientRequest};
/// This is a model of the state of a VR replica set under test. It doesn't represent a particular
/// replica, but rather properties of the system as it transitions through various states and
/// messages.
pub struct Model {
client_req_num: u64,
replicas: Vec<Pid>,
quorum: u64,
crashed: u64,
possible_views: Vec<u64>,
possible_primary_commit_num: Vec<u64>,
possible_backup_commit_num: Vec<u64>,
possible_primary_min_accept: Vec<u64>,
possible_backup_min_accept: Vec<u64>,
// This is the log at every alive replica, since messages are not dropped and there are no
// partitions in the current model
log: Vec<ClientOp>
}
impl Model {
/// Create a new model
pub fn new(mut replicas: Vec<Pid>) -> Model {
replicas.sort();
Model {
client_req_num: 0,
quorum: replicas.len() as u64 / 2 + 1,
replicas: replicas,
crashed: 0,
possible_views: vec![0],
possible_primary_commit_num: vec![0],
possible_backup_commit_num: vec![0],
possible_primary_min_accept: vec![0],
possible_backup_min_accept: vec![0],
log: Vec::new()
}
}
/// Update the model as a result of an operation
pub fn update(&mut self, op: Op) {
match op {
Op::ClientRequest(ClientRequest(mut req)) => {
self.client_req_num += 1;
req.request_num = self.client_req_num;
self.log.push(req.into());
self.possible_backup_commit_num = self.possible_primary_commit_num.clone();
// In our current model we always commit operations
self.possible_primary_commit_num = vec![self.log.len() as u64];
self.possible_backup_min_accept = self.possible_primary_min_accept.clone();
if self.crashed == 0 {
self.possible_primary_min_accept = vec![self.log.len() as u64];
}
}
Op::Commit => {
self.possible_backup_commit_num = self.possible_primary_commit_num.clone();
// A prepare will be rebroadcast and commit if there are uncommitted ops
self.possible_primary_commit_num = vec![self.log.len() as u64];
self.possible_backup_min_accept = self.possible_primary_min_accept.clone();
}
Op::ViewChange => {
self.update_view();
self.possible_backup_commit_num.extend(&self.possible_primary_commit_num);
self.possible_backup_commit_num.sort();
self.possible_backup_commit_num.dedup();
self.possible_backup_min_accept.extend(&self.possible_primary_min_accept);
self.possible_backup_min_accept.sort();
self.possible_backup_min_accept.dedup();
self.possible_primary_min_accept = self.possible_backup_min_accept.clone();
}
Op::CrashBackup => {
if self.replicas.len() as u64 - self.crashed != self.quorum {
self.crashed += 1;
}
}
Op::CrashPrimary => {
if self.replicas.len() as u64 - self.crashed != self.quorum {
self.crashed += 1;
self.update_view();
self.possible_primary_min_accept = self.possible_backup_min_accept.clone();
}
}
Op::Restart => {
// A restarting replica will learn of the primary commit num. Therefore backups may
// diverge.
self.possible_backup_commit_num.extend(&self.possible_primary_commit_num);
self.possible_backup_commit_num.sort();
self.possible_backup_commit_num.dedup();
// A restarting replica will learn of the primary min accept, therefore backups may
// diverge.
self.possible_backup_min_accept.extend(&self.possible_primary_min_accept);
self.possible_backup_min_accept.sort();
self.possible_backup_min_accept.dedup();
if self.crashed == 1 {
// Recovering replicas send PrepareOk to the primary allowing it to learn of the
// latest accepted prepare
self.possible_primary_min_accept = vec![self.log.len() as u64];
}
if self.crashed != 0 {
self.crashed -= 1;
}
}
}
}
/// Compare the model with the actual states of the replicas.
///
/// Note that this method is mutable because some members contain multiple possible values that
/// can be collapsed during checking to known values.
pub fn check(&mut self, states: &[VrState]) -> Result<(), String> {
for state in states {
safe_assert!(self.possible_views.contains(&state.ctx().view))?;
self.possible_views = vec![state.ctx().view];
self.compare_logs(state.ctx())?;
match *state {
VrState::Primary(_) => {
assert_contains!(self.possible_primary_commit_num, &state.ctx().commit_num)?;
// Reset the possible primary value with the known result
self.possible_primary_commit_num = vec![state.ctx().commit_num];
assert_contains!(self.possible_primary_min_accept,
&state.ctx().global_min_accept)?;
},
VrState::Backup(_) => {
assert_contains!(self.possible_backup_commit_num, &state.ctx().commit_num)?;
assert_contains!(self.possible_backup_min_accept,
&state.ctx().global_min_accept)?;
},
_ => fail!()
}
}
Ok(())
}
/// The model log is never garbage collected.
/// In this model there are no message drops or partitions, therefore the log represents the
/// latest state at at all replicas if there was no GC.
/// However, the logs at the replicas are GC'd at different times. The primary log will be GC'd
/// before the backup logs for example.
///
/// Therefore we ensure that the logs match after the GC point.
#[cfg_attr(feature="cargo-clippy", allow(needless_return))]
fn compare_logs(&self, ctx: &VrCtx) -> Result<(), String> {
let begin = ctx.log_start as usize;
let end = ctx.log_start as usize + ctx.log.len();
for i in begin..end {
self.log.get(i).map_or(Ok(()), |entry| {
safe_assert_eq!(*entry, ctx.log[i - ctx.log_start as usize], i)
})?;
}
Ok(())
}
/// With no partitions, at each update there is only going to be one view,
/// because at each call to check, the possible views will be collapsed to a known
/// view.
fn update_view(&mut self) {
assert_eq!(self.possible_views.len(), 1);
let mut view = self.possible_views.pop().unwrap();
view += 1;
self.possible_views.push(view);
for _ in 0..self.crashed {
view += 1;
self.possible_views.push(view);
}
}
}
|
use std::ops::{Add, Div, Mul, Sub};
#[derive(Copy, Clone, Debug, Default)]
pub struct Vec3 {
pub e: [f32; 3],
}
impl Vec3 {}
impl Vec3 {
pub fn new() -> Vec3 {
Vec3 { e: [0.0, 0.0, 0.0] }
}
// translation component accessors
pub fn x(&self) -> f32 {
self.e[0]
}
pub fn y(&self) -> f32 {
self.e[1]
}
pub fn z(&self) -> f32 {
self.e[2]
}
// colour component accessors
pub fn r(&self) -> f32 {
self.e[0]
}
pub fn g(&self) -> f32 {
self.e[1]
}
pub fn b(&self) -> f32 {
self.e[2]
}
pub fn length(&self) -> f32 {
(self.e[0] * self.e[0] + self.e[1] * self.e[1] + self.e[2] * self.e[2]).sqrt()
}
pub fn squared_length(&self) -> f32 {
self.e[0] * self.e[0] + self.e[1] * self.e[1] + self.e[2] * self.e[2]
}
}
impl Add for Vec3 {
type Output = Vec3;
fn add(self, rhs: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] + rhs.e[0],
self.e[1] + rhs.e[1],
self.e[2] + rhs.e[2],
],
}
}
}
impl Sub for Vec3 {
type Output = Vec3;
fn sub(self, rhs: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] - rhs.e[0],
self.e[1] - rhs.e[1],
self.e[2] - rhs.e[2],
],
}
}
}
impl Mul<Vec3> for Vec3 {
type Output = Vec3;
fn mul(self, rhs: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] * rhs.e[0],
self.e[1] * rhs.e[1],
self.e[2] * rhs.e[2],
],
}
}
}
impl Mul<f32> for Vec3 {
type Output = Vec3;
fn mul(self, rhs: f32) -> Vec3 {
Vec3 {
e: [self.e[0] * rhs, self.e[1] * rhs, self.e[2] * rhs],
}
}
}
impl Div<Vec3> for Vec3 {
type Output = Vec3;
fn div(self, rhs: Vec3) -> Vec3 {
Vec3 {
e: [
self.e[0] / rhs.e[0],
self.e[1] / rhs.e[1],
self.e[2] / rhs.e[2],
],
}
}
}
impl Div<f32> for Vec3 {
type Output = Vec3;
fn div(self, rhs: f32) -> Self {
Vec3 {
e: [self.e[0] / rhs, self.e[1] / rhs, self.e[2] / rhs],
}
}
}
pub fn unit_vector(v: Vec3) -> Vec3 {
v / v.length()
}
pub fn dot(v1: &Vec3, v2: &Vec3) -> f32 {
v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1] + v1.e[2] * v2.e[2]
}
pub fn cross(v1: &Vec3, v2: &Vec3) -> Vec3 {
Vec3 {
e: [
v1.e[1] * v2.e[2] - v1.e[2] * v2.e[1],
-(v1.e[0] * v2.e[2] - v1.e[2] * v2.e[0]),
v1.e[0] * v2.e[1] - v1.e[1] * v2.e[0],
],
}
}
|
use actix_http::{Method, Request};
use actix_web::{
dev::{self, Service, ServiceResponse},
test, Error,
};
use lazy_static::lazy_static;
use mockito::{Matcher, mock};
use reqwest::{Client, StatusCode};
use reqwest_middleware::ClientBuilder;
use reqwest_tracing::TracingMiddleware;
use crate::{api::PokemonInfo, new_service, AppConfig, APP_CONFIG};
use std::sync::Once;
static TRACING: Once = Once::new();
fn setup_tracing() {
TRACING.call_once(|| {
tracing_subscriber::fmt()
.with_env_filter("trace")
.with_test_writer()
.init();
});
}
async fn create_test_app(
app_config: &AppConfig,
) -> impl Service<Request, Response = ServiceResponse<dev::AnyBody>, Error = Error> {
setup_tracing();
let client = Client::builder()
.build()
.expect("client build successfully");
let client = ClientBuilder::new(client).with(TracingMiddleware).build();
test::init_service(new_service(client, app_config)).await
}
lazy_static! {
static ref MOCK_CONFIG: AppConfig = {
AppConfig {
pokemon_url: mockito::server_url().into(),
translations_url: mockito::server_url().into(),
}
};
}
#[actix_rt::test]
async fn get_pokemon_ok_mocked() {
let _m = mock("GET", "/api/v2/pokemon-species/mewtwo/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/mewtwo.json")
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/mewtwo")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "mewtwo".into(),
description: "It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.".into(),
is_legendary: true,
habitat: "rare".into(),
})
}
#[actix_rt::test]
async fn get_pokemon_not_found_mocked() {
let _m1 = mock("GET", "/api/v2/pokemon-species/mewthree/")
.with_status(404)
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/mewthree")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn get_pokemon_translated_legendary_mocked() {
let _m1 = mock("GET", "/api/v2/pokemon-species/mewtwo/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/mewtwo.json")
.create();
let _m2 = mock("GET", "/translate/yoda")
.match_query(Matcher::UrlEncoded("text".into(), "It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.".into()))
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/mewtwo_yoda.json")
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/mewtwo")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "mewtwo".into(),
description: "Created by a scientist after years of horrific gene splicing and dna engineering experiments, it was.".into(),
is_legendary: true,
habitat: "rare".into(),
})
}
#[actix_rt::test]
async fn get_pokemon_translated_cave_mocked() {
let _m1 = mock("GET", "/api/v2/pokemon-species/zubat/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/zubat.json")
.create();
let _m2 = mock("GET", "/translate/yoda")
.match_query(Matcher::UrlEncoded("text".into(), "Forms colonies in perpetually dark places. Uses ultrasonic waves to identify and approach targets.".into()))
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/zubat_yoda.json")
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/zubat")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "zubat".into(),
description: "Forms colonies in perpetually dark places.Ultrasonic waves to identify and approach targets, uses.".into(),
is_legendary: false,
habitat: "cave".into(),
})
}
#[actix_rt::test]
async fn get_pokemon_translated_other_mocked() {
let _m1 = mock("GET", "/api/v2/pokemon-species/ditto/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/ditto.json")
.create();
let _m2 = mock("GET", "/translate/shakespeare")
.match_query(Matcher::UrlEncoded("text".into(), "It can freely recombine its own cellular structure to transform into other life-forms.".into()))
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/ditto_shakespeare.json")
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/ditto")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "ditto".into(),
description: "'t can freely recombine its own cellular structure to transform into other life-forms.".into(),
is_legendary: false,
habitat: "urban".into(),
})
}
#[actix_rt::test]
async fn get_pokemon_translated_not_found_mocked() {
let _m1 = mock("GET", "/api/v2/pokemon-species/mewthree/")
.with_status(404)
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/mewthree")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn get_pokemon_translated_bad_translation_mocked() {
let _m1 = mock("GET", "/api/v2/pokemon-species/mewtwo/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body_from_file("replays/mewtwo.json")
.create();
let _m2 = mock("GET", "/translate/yoda")
.match_query(Matcher::UrlEncoded("text".into(), "It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.".into()))
.with_status(500)
.create();
let app = create_test_app(&MOCK_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/mewtwo")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "mewtwo".into(),
description: "It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.".into(),
is_legendary: true,
habitat: "rare".into(),
})
}
#[actix_rt::test]
#[ignore]
async fn get_pokemon_ok() {
let app = create_test_app(&APP_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/mewtwo")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "mewtwo".into(),
description: "It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.".into(),
is_legendary: true,
habitat: "rare".into(),
})
}
#[actix_rt::test]
#[ignore]
async fn get_pokemon_not_found() {
let app = create_test_app(&APP_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/mewthree")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
#[ignore]
async fn get_pokemon_translated_legendary() {
let app = create_test_app(&APP_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/mewtwo")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "mewtwo".into(),
description: "Created by a scientist after years of horrific gene splicing and dna engineering experiments, it was.".into(),
is_legendary: true,
habitat: "rare".into(),
})
}
#[actix_rt::test]
#[ignore]
async fn get_pokemon_translated_cave() {
let app = create_test_app(&APP_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/zubat")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "zubat".into(),
description: "Forms colonies in perpetually dark places.Ultrasonic waves to identify and approach targets, uses.".into(),
is_legendary: false,
habitat: "cave".into(),
})
}
#[actix_rt::test]
#[ignore]
async fn get_pokemon_translated_other() {
let app = create_test_app(&APP_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/ditto")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::OK);
let result: PokemonInfo = test::read_body_json(resp).await;
assert_eq!(result, PokemonInfo {
name: "ditto".into(),
description: "'t can freely recombine its own cellular structure to transform into other life-forms.".into(),
is_legendary: false,
habitat: "urban".into(),
})
}
#[actix_rt::test]
#[ignore]
async fn get_pokemon_translated_not_found() {
let app = create_test_app(&APP_CONFIG).await;
let req = test::TestRequest::with_uri("/pokemon/translated/mewthree")
.method(Method::GET)
.to_request();
let resp: ServiceResponse = app.call(req).await.expect("valid response");
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
|
/*
Some command line options go to cargo test, and some go to the resulting test
binary. To separate these two types of arguments, you list the arguments that go
to cargo test followed by the separator -- and then the ones that go to the test
binary. Running cargo test --help displays the options you can use with cargo
test, and running cargo test -- --help displays the options you can use after
the separator --
If you don’t want to run the tests in parallel or if you want more fine-grained
control over the number of threads used, you can send the --test-threads flag
and the number of threads you want to use to the test binary.
$ cargo test -- --test-threads=1
By default, if a test passes, Rust’s test library captures anything printed to
standard output. If we want to see printed values for passing tests as well, we
can disable the output capture behavior by using the --nocapture flag:
$ cargo test -- --nocapture
We can pass the name of any test function to cargo test to run only that test:
$ cargo test one_hundred
We can specify part of a test name, and any test whose name matches that value
will be run. For example, because two of our tests’ names contain add, we can
run those two by running:
$ cargo test add
Rather than listing as arguments all tests you do want to run, you can instead
annotate the time-consuming tests using the ignore attribute to exclude them, by
putting "#[ignore]" above the test function:
If we want to run only the ignored tests, we can use:
$ cargo test -- --ignored
*/
#[allow(dead_code)]
fn prints_and_returns_10(a: i32) -> i32 {
println!("I got the value {}", a);
10
}
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn this_test_will_pass() {
let value = prints_and_returns_10(4);
assert_eq!(10, value);
}
// #[test]
// fn this_test_will_fail() {
// let value = prints_and_returns_10(8);
// assert_eq!(5, value);
// }
#[test]
fn add_two_and_two() {
assert_eq!(4, add_two(2));
}
#[test]
fn add_three_and_two() {
assert_eq!(5, add_two(3));
}
#[test]
fn one_hundred() {
assert_eq!(102, add_two(100));
}
#[test]
#[ignore]
fn expensive_test() {
// code that takes an hour to run
}
}
|
use ring::test::{compile_time_assert_send, compile_time_assert_sync};
use webpki::DnsNameRef;
#[test]
fn test_dns_name_ref_traits() {
compile_time_assert_send::<DnsNameRef>();
compile_time_assert_sync::<DnsNameRef>();
let a = DnsNameRef::try_from_ascii(b"example.com").unwrap();
// `Copy`
{
let _b = a;
let _c = a;
}
// `Clone`
#[allow(clippy::clone_on_copy)]
let _ = a.clone();
// TODO: verify the clone is the same as `a`.
// TODO: Don't require `alloc` for these.
#[cfg(feature = "alloc")]
{
// `Debug`.
assert_eq!(format!("{:?}", &a), "DnsNameRef(\"example.com\")");
}
}
#[cfg(feature = "alloc")]
#[test]
fn test_dns_name_traits() {
use webpki::DnsName;
fn compile_time_assert_hash<T: core::hash::Hash>() {}
compile_time_assert_hash::<DnsName>();
compile_time_assert_send::<DnsName>();
compile_time_assert_sync::<DnsName>();
let a_ref = DnsNameRef::try_from_ascii(b"example.com").unwrap();
// `From<DnsNameRef>`
let a: DnsName = DnsName::from(a_ref);
// `Clone`, `Debug`, `PartialEq`.
assert_eq!(&a, &a.clone());
// `Debug`.
assert_eq!(format!("{:?}", &a), "DnsName(\"example.com\")");
// PartialEq is case-insensitive
assert_eq!(
a,
DnsName::from(DnsNameRef::try_from_ascii(b"Example.Com").unwrap())
);
// PartialEq isn't completely wrong.
assert_ne!(
a,
DnsName::from(DnsNameRef::try_from_ascii(b"fxample.com").unwrap())
);
assert_ne!(
a,
DnsName::from(DnsNameRef::try_from_ascii(b"example.co").unwrap())
);
}
|
pub mod attribute;
pub mod channel_list;
pub mod cppstd;
pub mod envmap;
pub mod error;
pub mod frame_buffer;
pub mod frames_per_second;
pub mod header;
pub mod input_file;
pub mod input_part;
pub mod keycode;
pub mod multi_view;
pub mod output_file;
pub mod output_part;
pub mod preview_image;
pub mod rational;
pub use rational::Rational;
pub mod refptr;
pub mod standard_attributes;
pub mod tile_description;
pub mod timecode;
pub use timecode::TimeCode;
pub mod version;
pub use version::Version;
pub use openexr_sys::Compression;
pub use openexr_sys::CubeMapFace;
pub use openexr_sys::DataWindowSource;
pub use openexr_sys::Envmap;
pub use openexr_sys::Imf_Chromaticities_t as Chromaticities;
pub use openexr_sys::LevelMode;
pub use openexr_sys::LevelRoundingMode;
pub use openexr_sys::LineOrder;
pub use openexr_sys::PixelType;
|
use std::char;
use std::io::Read;
use crate::counters::{CodelChooser, DirectionPointer};
#[derive(Debug)]
pub enum Command {
Push,
Pop,
Add,
Subtract,
Multiply,
Divide,
Mod,
Not,
Greater,
Pointer,
Switch,
Duplicate,
Roll,
InNumber,
InChar,
OutNumber,
OutChar,
}
impl Command {
pub fn from(diffs: (u8, u8)) -> Option<Command> {
match diffs {
(0, 1) => Some(Command::Add),
(0, 2) => Some(Command::Divide),
(0, 3) => Some(Command::Greater),
(0, 4) => Some(Command::Duplicate),
(0, 5) => Some(Command::InChar),
(1, 0) => Some(Command::Push),
(1, 1) => Some(Command::Subtract),
(1, 2) => Some(Command::Mod),
(1, 3) => Some(Command::Pointer),
(1, 4) => Some(Command::Roll),
(1, 5) => Some(Command::OutNumber),
(2, 0) => Some(Command::Pop),
(2, 1) => Some(Command::Multiply),
(2, 2) => Some(Command::Not),
(2, 3) => Some(Command::Switch),
(2, 4) => Some(Command::InNumber),
(2, 5) => Some(Command::OutChar),
_ => None,
}
}
pub fn execute(
&self,
stack: &mut Vec<i64>,
dp: &mut DirectionPointer,
cc: &mut CodelChooser,
block_size: usize,
verbose_logging: bool,
) {
match self {
Command::Push => {
if verbose_logging {
eprintln!("execute PUSH({})", block_size);
}
stack.push(block_size as i64)
}
Command::Pop => {
if stack.pop().is_some() {
if verbose_logging {
eprintln!("execute POP");
}
} else {
if verbose_logging {
eprintln!("skip executing POP due to empty stack");
}
}
}
Command::Duplicate => {
if let Some(&last) = stack.last() {
if verbose_logging {
eprintln!("execute DUPLICATE");
}
stack.push(last)
} else {
if verbose_logging {
eprintln!("skip executing DUPLICATE due to empty stack");
}
}
}
Command::Add => {
if stack.len() >= 2 {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
if verbose_logging {
eprintln!("execute ADD({}, {})", b, a);
}
stack.push(a + b);
} else {
if verbose_logging {
eprintln!("skip executing ADD due to not enough values on the stack");
}
}
}
Command::Subtract => {
if stack.len() >= 2 {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
if verbose_logging {
eprintln!("execute SUBTRACT({}, {})", b, a);
}
stack.push(b - a);
} else {
if verbose_logging {
eprintln!("skip executing SUBTRACT due to not enough values on the stack");
}
}
}
Command::Multiply => {
if stack.len() >= 2 {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
if verbose_logging {
eprintln!("execute MULTIPLY({}, {})", b, a);
}
stack.push(a * b);
} else {
if verbose_logging {
eprintln!("skip executing MULTIPLY due to not enough values on the stack");
}
}
}
Command::Divide => {
if stack.len() >= 2 {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
if a == 0 {
if verbose_logging {
eprintln!(
"skip executing DIVIDE due to not being able to divide by zero"
);
}
} else {
if verbose_logging {
eprintln!("execute DIVIDE({}, {})", b, a);
}
stack.push(b / a);
}
} else {
if verbose_logging {
eprintln!("skip executing DIVIDE due to not enough values on the stack");
}
}
}
Command::Mod => {
if stack.len() >= 2 {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
if a == 0 {
if verbose_logging {
eprintln!("skip executing MOD due to not being able to modulo by zero");
}
} else {
if verbose_logging {
eprintln!("execute MOD({}, {})", b, a);
}
stack.push(b.rem_euclid(a));
}
} else {
if verbose_logging {
eprintln!("skip executing MOD due to not enough values on the stack");
}
}
}
Command::Not => {
if let Some(a) = stack.pop() {
if verbose_logging {
eprintln!("execute NOT({})", a);
}
if a == 0 {
stack.push(1);
} else {
stack.push(0);
}
} else {
if verbose_logging {
eprintln!("skip executing NOT due to empty stack");
}
}
}
Command::Greater => {
if stack.len() >= 2 {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
if verbose_logging {
eprintln!("execute GREATER({}, {})", b, a);
}
if b > a {
stack.push(1);
} else {
stack.push(0);
}
} else {
if verbose_logging {
eprintln!("skip executing GREATER due to not enough values on the stack");
}
}
}
Command::Pointer => {
if let Some(a) = stack.pop() {
if verbose_logging {
eprintln!("execute POINTER({})", a);
}
match a % 4 {
3 => turn_direction_pointer(dp, 3),
2 => turn_direction_pointer(dp, 2),
1 => turn_direction_pointer(dp, 1),
-1 => turn_direction_pointer(dp, 3),
-2 => turn_direction_pointer(dp, 2),
-3 => turn_direction_pointer(dp, 1),
_ => (),
}
} else {
if verbose_logging {
eprintln!("skip executing POINTER due to empty stack");
}
}
}
Command::Switch => {
if let Some(a) = stack.pop() {
if verbose_logging {
eprintln!("execute SWITCH({})", a);
}
if a % 2 == 1 {
*cc = match cc {
CodelChooser::Left => CodelChooser::Right,
CodelChooser::Right => CodelChooser::Left,
}
}
} else {
if verbose_logging {
eprintln!("skip executing SWITCH due to empty stack");
}
}
}
Command::Roll => {
if stack.len() >= 2 {
let rolls = stack.pop().unwrap();
let depth = stack.pop().unwrap();
if depth <= 0 {
if verbose_logging {
eprintln!("skip executing ROLL must be a positive roll depth");
}
stack.push(depth);
stack.push(rolls);
} else {
if stack.len() < depth as usize {
if verbose_logging {
eprintln!(
"skip executing ROLL due to not enough values on the stack"
);
}
stack.push(depth);
stack.push(rolls);
} else {
if verbose_logging {
eprintln!("execute ROLL({}, {})", depth, rolls);
}
let rolls = rolls % depth;
let mut substack: Vec<_> =
stack.drain(stack.len() - (depth as usize)..).collect();
if rolls > 0 {
substack.rotate_right(rolls as usize);
} else {
substack.rotate_left((rolls * -1) as usize);
}
stack.append(&mut substack);
}
}
} else {
if verbose_logging {
eprintln!("skip executing ROLL due to not enough values on the stack");
}
}
}
Command::OutNumber => {
if let Some(last) = stack.pop() {
if verbose_logging {
eprintln!("execute OUT_NUM({})", last);
}
print!("{}", last);
} else {
if verbose_logging {
eprintln!("skip executing OUT_NUM due to empty stack");
}
}
}
Command::OutChar => {
if let Some(last) = stack.pop() {
if last >= 0 && last <= (u32::max_value() as i64) {
let c = char::from_u32(last as u32);
if let Some(c) = c {
if verbose_logging {
eprintln!("execute OUT_CHAR({} -> {})", last, c);
}
print!("{}", c);
} else {
if verbose_logging {
eprintln!("skip executing OUT_CHAR due invalid char");
}
stack.push(last)
}
} else {
if verbose_logging {
eprintln!("skip executing OUT_CHAR due invalid char");
}
stack.push(last)
}
} else {
if verbose_logging {
eprintln!("skip executing OUT_CHAR due to empty stack");
}
}
}
Command::InNumber => {
let mut buffer = String::new();
if let Ok(_) = std::io::stdin().read_line(&mut buffer) {
if let Ok(num) = buffer.trim().parse::<i64>() {
if verbose_logging {
eprintln!("executed IN_NUM({})", num);
}
stack.push(num);
} else {
if verbose_logging {
eprintln!("skip executing IN_NUM() because input could not be parse as a number");
}
}
} else {
if verbose_logging {
eprintln!("skip executing IN_NUM() because input could read");
}
}
}
Command::InChar => {
let input: Option<u8> = std::io::stdin()
.bytes()
.next()
.and_then(|result| result.ok());
match input {
Some(byte) => {
if verbose_logging {
eprintln!(
"executed IN_CHAR({} -> {})",
char::from_u32(byte as u32).unwrap(),
byte as i64
);
}
stack.push(byte as i64);
}
None => {
if verbose_logging {
eprintln!("skip executing IN_CHAR() because input was empty or could not be read");
}
}
}
}
}
}
}
fn turn_direction_pointer(dp: &mut DirectionPointer, turns: u32) {
if turns == 0 {
return;
}
*dp = match dp {
DirectionPointer::Right => DirectionPointer::Down,
DirectionPointer::Down => DirectionPointer::Left,
DirectionPointer::Left => DirectionPointer::Up,
DirectionPointer::Up => DirectionPointer::Right,
};
turn_direction_pointer(dp, turns - 1)
}
|
use std::mem;
fn analyze_slice(slice: &[i32]) {
println!("first element of slice is {}", slice[0]);
println!("length of slice is {}", slice.len());
}
fn update_slice(slice: &mut [i32]) {
for e in slice {
*e += 3;
}
}
fn main() {
let mut xs: [i32; 7] = [1, 2, 3, 4, 5, 6, 7];
let ys: [i32; 100] = [0; 100];
analyze_slice(&ys);
analyze_slice(&xs[1..4]);
println!("Guncellemeden once {:?}", xs);
update_slice(&mut xs[0..3]);
println!("Guncellemeden sonra {:?}", xs)
}
|
pub trait VectorProperties {
fn length(&self) -> f64;
// TODO: Look at overloading so we have instance and static methods
fn add(vec1: &Self, vec2: &Self) -> Self;
fn sub(vec1: &Self, vec2: &Self) -> Self;
fn mul(vec1: &Self, vec2: &Self) -> Self;
fn lerp(vec1: &Self, vec2: &Self, t: f64) -> Self;
fn dot(vec1: &Self, vec2: &Self) -> f64;
fn angle(vec1: &Self, vec2: &Self) -> f64;
fn dist(vec1: &Self, vec2: &Self) -> f64;
fn getNormalized(v: &Self) -> Self;
// Mutators
fn scale(&mut self, factor: f64);
fn normalize(&mut self);
fn print(&self);
} |
use clap::{crate_description, crate_name, App, Arg};
use console::style;
use solana_archiver_lib::archiver::Archiver;
use solana_clap_utils::{
input_parsers::keypair_of, input_validators::is_keypair_or_ask_keyword,
keypair::SKIP_SEED_PHRASE_VALIDATION_ARG,
};
use solana_core::{
cluster_info::{Node, VALIDATOR_PORT_RANGE},
contact_info::ContactInfo,
};
use solana_sdk::{
commitment_config::CommitmentConfig,
signature::{Keypair, Signer},
};
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
sync::Arc,
};
fn main() {
solana_logger::setup();
let matches = App::new(crate_name!())
.about(crate_description!())
.version(solana_clap_utils::version!())
.arg(
Arg::with_name("identity_keypair")
.short("i")
.long("identity")
.value_name("PATH")
.takes_value(true)
.validator(is_keypair_or_ask_keyword)
.help("File containing an identity (keypair)"),
)
.arg(
Arg::with_name("entrypoint")
.short("n")
.long("entrypoint")
.value_name("HOST:PORT")
.takes_value(true)
.required(true)
.validator(solana_net_utils::is_host_port)
.help("Rendezvous with the cluster at this entry point"),
)
.arg(
Arg::with_name("ledger")
.short("l")
.long("ledger")
.value_name("DIR")
.takes_value(true)
.required(true)
.help("use DIR as persistent ledger location"),
)
.arg(
Arg::with_name("storage_keypair")
.short("s")
.long("storage-keypair")
.value_name("PATH")
.takes_value(true)
.validator(is_keypair_or_ask_keyword)
.help("File containing the storage account keypair"),
)
.arg(
Arg::with_name(SKIP_SEED_PHRASE_VALIDATION_ARG.name)
.long(SKIP_SEED_PHRASE_VALIDATION_ARG.long)
.help(SKIP_SEED_PHRASE_VALIDATION_ARG.help),
)
.get_matches();
let ledger_path = PathBuf::from(matches.value_of("ledger").unwrap());
let identity_keypair = keypair_of(&matches, "identity_keypair").unwrap_or_else(Keypair::new);
let storage_keypair = keypair_of(&matches, "storage_keypair").unwrap_or_else(|| {
clap::Error::with_description(
"The `storage-keypair` argument was not found",
clap::ErrorKind::ArgumentNotFound,
)
.exit();
});
let entrypoint_addr = matches
.value_of("entrypoint")
.map(|entrypoint| {
solana_net_utils::parse_host_port(entrypoint)
.expect("failed to parse entrypoint address")
})
.unwrap();
let gossip_addr = {
let ip = solana_net_utils::get_public_ip_addr(&entrypoint_addr).unwrap();
let mut addr = SocketAddr::new(ip, 0);
addr.set_ip(solana_net_utils::get_public_ip_addr(&entrypoint_addr).unwrap());
addr
};
let node = Node::new_archiver_with_external_ip(
&identity_keypair.pubkey(),
&gossip_addr,
VALIDATOR_PORT_RANGE,
IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
);
println!(
"{} version {} (branch={}, commit={})",
style(crate_name!()).bold(),
solana_clap_utils::version!(),
option_env!("CI_BRANCH").unwrap_or("unknown"),
option_env!("CI_COMMIT").unwrap_or("unknown")
);
solana_metrics::set_host_id(identity_keypair.pubkey().to_string());
println!(
"replicating the data with identity_keypair={:?} gossip_addr={:?}",
identity_keypair.pubkey(),
gossip_addr
);
let entrypoint_info = ContactInfo::new_gossip_entry_point(&entrypoint_addr);
let archiver = Archiver::new(
&ledger_path,
node,
entrypoint_info,
Arc::new(identity_keypair),
Arc::new(storage_keypair),
CommitmentConfig::recent(),
)
.unwrap();
archiver.join();
}
|
#[doc = "Reader of register C10ISR"]
pub type R = crate::R<u32, super::C10ISR>;
#[doc = "Reader of field `TEIF10`"]
pub type TEIF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTCIF10`"]
pub type CTCIF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `BRTIF10`"]
pub type BRTIF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `BTIF10`"]
pub type BTIF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF10`"]
pub type TCIF10_R = crate::R<bool, bool>;
#[doc = "Reader of field `CRQA10`"]
pub type CRQA10_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Channel x transfer error interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn teif10(&self) -> TEIF10_R {
TEIF10_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Channel x Channel Transfer Complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register. CTC is set when the last block was transferred and the channel has been automatically disabled. CTC is also set when the channel is suspended, as a result of writing EN bit to 0."]
#[inline(always)]
pub fn ctcif10(&self) -> CTCIF10_R {
CTCIF10_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Channel x block repeat transfer complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn brtif10(&self) -> BRTIF10_R {
BRTIF10_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Channel x block transfer complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn btif10(&self) -> BTIF10_R {
BTIF10_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - channel x buffer transfer complete"]
#[inline(always)]
pub fn tcif10(&self) -> TCIF10_R {
TCIF10_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 16 - channel x request active flag"]
#[inline(always)]
pub fn crqa10(&self) -> CRQA10_R {
CRQA10_R::new(((self.bits >> 16) & 0x01) != 0)
}
}
|
use std::io::{Read, Result as IOResult};
use crate::lump_data::{LumpData, LumpType};
use crate::PrimitiveRead;
#[derive(Copy, Clone, Debug, Default)]
pub struct Brush {
pub first_side: i32,
pub sides_count: i32,
pub contents: BrushContents
}
bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct BrushContents: u32 {
const EMPTY = 0;
const SOLID = 0x1;
const WINDOW = 0x2;
const AUX = 0x4;
const GRATE = 0x8;
const SLIME = 0x10;
const WATER = 0x20;
const MIST = 0x40;
const OPAQUE = 0x80;
const TEST_FOG_VOLUME = 0x100;
const UNUSED = 0x200;
const UNUSED6 = 0x400;
const TEAM1 = 0x800;
const TEAM2 = 0x1000;
const IGNORE_NO_DRAW_OPAQUE = 0x2000;
const MOVABLE = 0x4000;
const AREA_PORTAL = 0x8000;
const PLAYER_CLIP = 0x10000;
const MONSTER_CLIP = 0x20000;
const CURRENT0 = 0x40000;
const CURRENT90 = 0x80000;
const CURRENT180 = 0x100000;
const CURRENT270 = 0x200000;
const CURRENT_UP = 0x400000;
const CURRENT_DOWN = 0x800000;
const ORIGIN = 0x1000000;
const MONSTER = 0x2000000;
const DEBRIS = 0x4000000;
const DETAIL = 0x8000000;
const TRANSLUCENT = 0x10000000;
const LADDER = 0x20000000;
const HITBOX = 0x40000000;
}
}
impl LumpData for Brush {
fn lump_type() -> LumpType {
LumpType::Brushes
}
fn lump_type_hdr() -> Option<LumpType> {
None
}
fn element_size(_version: i32) -> usize {
12
}
fn read(reader: &mut dyn Read, _version: i32) -> IOResult<Self> {
let first_side = reader.read_i32()?;
let sides_count = reader.read_i32()?;
let contents = reader.read_u32()?;
Ok(Self {
first_side,
sides_count,
contents: BrushContents::from_bits(contents).unwrap()
})
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_expression::FunctionRegistry;
mod arithmetic;
mod arithmetic_modulo;
mod array;
mod boolean;
mod control;
mod datetime;
mod geo;
mod map;
mod math;
mod tuple;
mod variant;
mod vector;
mod comparison;
mod decimal;
mod hash;
mod other;
mod string;
mod string_multi_args;
pub use comparison::check_pattern_type;
pub use comparison::is_like_pattern_escape;
pub use comparison::PatternType;
pub use comparison::ALL_COMP_FUNC_NAMES;
pub fn register(registry: &mut FunctionRegistry) {
variant::register(registry);
arithmetic::register(registry);
array::register(registry);
boolean::register(registry);
control::register(registry);
comparison::register(registry);
datetime::register(registry);
math::register(registry);
map::register(registry);
string::register(registry);
string_multi_args::register(registry);
tuple::register(registry);
geo::register(registry);
hash::register(registry);
other::register(registry);
decimal::register(registry);
vector::register(registry);
}
|
#![no_std]
/*!
# **Humansize**
## Features
Humansize is a humanization library for information size that is:
- Simple & convenient to use
- Customizable
- Supports byte or bit sizes
- `no-std`
- Optionally non-allocating
- Optionally accepts signed values
## How to use it...
Add humansize as a dependency to your project's `cargo.toml`:
```toml
[dependencies]
...
humansize = "2.0.0"
```
### ... to easily format a size:
1. Import the `format_size` function as well as your preferred set of defaults:
- `DECIMAL` (SI)
- `BINARY` (IEC)
- `WINDOWS` (IEC values but SI units)
2. Call `format_size` with an unsigned integer
```rust
use humansize::{format_size, DECIMAL};
let size = 1_000_000u64;
let res: String = format_size(size, DECIMAL);
assert_eq!(&res, "1 MB");
```
### ... to format many sizes:
To improve reusability, you can use `create_format`, which returns a formatter function akin to `format_size` but with the options argument curried so it doesn't need to be specified again:
```rust
use humansize::{make_format, DECIMAL};
let formatter = make_format(DECIMAL);
assert_eq!(formatter(1_000_000u64), "1 MB");
assert_eq!(formatter(1_000_000_000u64), "1 GB");
//...
```
### ... to avoid allocation:
Specify the `no_alloc` feature flag in your project's `cargo.toml`:
```toml
[dependencies]
...
humansize = { version = "2.0.0", features = ["no_alloc"] }
```
This excludes all allocating code from compilation. You may now use the library's internal `SizeFormatter` struct, which implements `core::fmt::display` so that you can `write!` it to a custom buffer of your choice:
```rust
use humansize::{SizeFormatter, DECIMAL};
let formatter = SizeFormatter::new(1_000_000usize, DECIMAL);
assert_eq!(format!("{}", formatter), "1 MB");
```
### ... with the `impl` style API:
For stylistic reasons, you may prefer to use the impl-style API of earlier versions of the crate.
To do so, specify the `impl-style` feature flag in your project's `cargo.toml`:
```toml
[dependencies]
...
humansize = { version = "2.0.0", features = ["impl_style"] }
```
Enabling this feature makes two methods available:
- `format_size` on unsigned integers types
- `format_size_i` on signed integer types.
To use it, bring the FormatSize trait into scope and call its method on an integer type:
```ignore
use humansize::{FormatSize, FormatSizeI DECIMAL};
assert_eq!(1_000_000u64.format_size(DECIMAL), "1 MB");
assert_eq!((-1_000_000).format_size_i(DECIMAL), "-1 MB");
```
### ... to further customize the output:
Humansize exports three default option sets:
* `Decimal`: kilo = 1000, unit format is `XB`.
* `Binary`: kilo = 1024, unit format is `XiB`.
* `WINDOWS` (Windows): kilo = 1024, unit format is `XB`.
The formatting can be further customized by providing providing your own option set. See the documentation of the `FormatSizeOptions` struct to see all the addressable parameters, and [this example](examples/custom_options.rs) for its usage.
### ... to accept negative values:
The solutions presented above only accept unsigned integer types as input (`usize`, `8`, `u16`, `u32` and `u64`). If however accepting negative values is correct for your application, a signed alternative exists for each of them that will accept signed integer types, and format them accordingly if negative:
- `format_size` : `format_size_i`
- `create_format` : `create_format_i`
- `FormatSize` trait : `FormatSizeI` trait
- `SizeFormatter` : `ISizeFormatter`
```rust
use humansize::{format_size_i, make_format_i, ISizeFormatter, DECIMAL};
assert_eq!(&format_size_i(-1_000_000, DECIMAL), "-1 MB");
let signed_formatter = make_format_i(DECIMAL);
assert_eq!(&signed_formatter(-1_000_000), "-1 MB");
// With the `impl-style` feature enabled:
// use humansize::FormatSizeI;
// assert_eq(-1_000_000.format_size(DECIMAL), "-1 MB");
let signed_size_formatter = ISizeFormatter::new(-1_000_000, DECIMAL);
assert_eq!(format!("{}", signed_size_formatter), "-1 MB");
```
*/
#[macro_use]
#[cfg(not(feature = "no_alloc"))]
extern crate alloc;
extern crate libm;
mod options;
pub use options::{BaseUnit, FixedAt, FormatSizeOptions, Kilo, BINARY, DECIMAL, WINDOWS};
mod numeric_traits;
pub use numeric_traits::{Signed, ToF64, Unsigned};
mod scales;
mod utils;
#[cfg(not(feature = "no_alloc"))]
mod allocating;
#[cfg(not(feature = "no_alloc"))]
pub use allocating::*;
#[cfg(feature = "impl_style")]
mod impl_style;
#[cfg(feature = "impl_style")]
pub use impl_style::{FormatSize, FormatSizeI};
mod formatters;
pub use formatters::{SizeFormatter, ISizeFormatter};
|
use core::fmt;
use core::marker::PhantomData;
use {Poll, Future, Stream, Sink, StartSend};
mod atomic_task;
pub use self::atomic_task::AtomicTask;
mod core;
#[cfg(feature = "use_std")]
mod std;
#[cfg(feature = "use_std")]
pub use self::std::*;
#[cfg(not(feature = "use_std"))]
pub use self::core::*;
pub struct BorrowedTask<'a> {
id: usize,
unpark: BorrowedUnpark<'a>,
events: BorrowedEvents<'a>,
// Task-local storage
map: &'a LocalMap,
}
fn fresh_task_id() -> usize {
use core::sync::atomic::{AtomicUsize, Ordering};
#[allow(deprecated)]
use core::sync::atomic::ATOMIC_USIZE_INIT;
// TODO: this assert is a real bummer, need to figure out how to reuse
// old IDs that are no longer in use.
//
// Note, though, that it is intended that these ids go away entirely
// eventually, see the comment on `is_current` below.
#[allow(deprecated)]
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
assert!(id < usize::max_value() / 2,
"too many previous tasks have been allocated");
id
}
fn with<F: FnOnce(&BorrowedTask) -> R, R>(f: F) -> R {
unsafe {
let task = get_ptr().expect("no Task is currently running");
assert!(!task.is_null(), "no Task is currently running");
f(&*(task as *const BorrowedTask))
}
}
/// A handle to a "task", which represents a single lightweight "thread" of
/// execution driving a future to completion.
///
/// In general, futures are composed into large units of work, which are then
/// spawned as tasks onto an *executor*. The executor is responsible for polling
/// the future as notifications arrive, until the future terminates.
///
/// This is obtained by the `task::current` function.
///
/// # FAQ
///
/// ### Why does `Task` not implement `Eq` and `Hash`?
///
/// A valid use case for `Task` to implement these two traits has not been
/// encountered.
///
/// Usually, this question is asked by someone who wants to store a `Task`
/// instance in a `HashSet`. This seems like an obvious way to implement a
/// future aware, multi-handle structure; e.g. a multi-producer channel.
///
/// In this case, the idea is that whenever a `start_send` is called on one of
/// the channel's send handles, if the channel is at capacity, the current task
/// is stored in a set. Then, when capacity is available, a task is removed from
/// the set and notified.
///
/// The problem with this strategy is that multiple `Sender` handles can be used
/// on the same task. In this case, when the second handle is used and the task
/// is stored in a set, there already is an entry. Then, when the first
/// handle is dropped, this entry is cleared, resulting in a dead lock.
///
/// See [here](https://github.com/rust-lang-nursery/futures-rs/issues/670) for
/// more discussion.
///
#[derive(Clone)]
pub struct Task {
id: usize,
unpark: TaskUnpark,
events: UnparkEvents,
}
trait AssertSend: Send {}
impl AssertSend for Task {}
/// Returns a handle to the current task to call `notify` at a later date.
///
/// The returned handle implements the `Send` and `'static` bounds and may also
/// be cheaply cloned. This is useful for squirreling away the handle into a
/// location which is then later signaled that a future can make progress.
///
/// Implementations of the `Future` trait typically use this function if they
/// would otherwise perform a blocking operation. When something isn't ready
/// yet, this `current` function is called to acquire a handle to the current
/// task, and then the future arranges it such that when the blocking operation
/// otherwise finishes (perhaps in the background) it will `notify` the
/// returned handle.
///
/// It's sometimes necessary to pass extra information to the task when
/// unparking it, so that the task knows something about *why* it was woken.
/// See the `FutureQueue` documentation for details on how to do this.
///
/// # Panics
///
/// This function will panic if a task is not currently being executed. That
/// is, this method can be dangerous to call outside of an implementation of
/// `poll`.
pub fn current() -> Task {
with(|borrowed| {
let unpark = borrowed.unpark.to_owned();
let events = borrowed.events.to_owned();
Task {
id: borrowed.id,
unpark: unpark,
events: events,
}
})
}
#[doc(hidden)]
#[deprecated(note = "renamed to `current`")]
pub fn park() -> Task {
current()
}
impl Task {
/// Indicate that the task should attempt to poll its future in a timely
/// fashion.
///
/// It's typically guaranteed that, after calling `notify`, `poll` will
/// be called at least once subsequently (unless the future has terminated).
/// If the task is currently polling its future when `notify` is called, it
/// must poll the future *again* afterwards, ensuring that all relevant
/// events are eventually observed by the future.
pub fn notify(&self) {
self.events.notify();
self.unpark.notify();
}
#[doc(hidden)]
#[deprecated(note = "renamed to `notify`")]
pub fn unpark(&self) {
self.notify()
}
/// Returns `true` when called from within the context of the task.
///
/// In other words, the task is currently running on the thread calling the
/// function. Note that this is currently, and has historically, been
/// implemented by tracking an `id` on every instance of `Spawn` created.
/// When a `Spawn` is being polled it stores in thread-local-storage the id
/// of the instance, and then `task::current` will return a `Task` that also
/// stores this id.
///
/// The intention of this function was to answer questions like "if I
/// `notify` this task, is it equivalent to `task::current().notify()`?"
/// The answer "yes" may be able to avoid some extra work to block the
/// current task, such as sending a task along a channel or updating a
/// stored `Task` somewhere. An answer of "no" typically results in doing
/// the work anyway.
///
/// Unfortunately this function has been somewhat buggy in the past and is
/// not intended to be supported in the future. By simply matching `id` the
/// intended question above isn't accurately taking into account, for
/// example, unpark events (now deprecated, but still a feature). Thus many
/// old users of this API weren't fully accounting for the question it was
/// intended they were asking.
///
/// This API continues to be implemented but will in the future, e.g. in the
/// 0.1.x series of this crate, eventually return `false` unconditionally.
/// It is intended that this function will be removed in the next breaking
/// change of this crate. If you'd like to continue to be able to answer the
/// example question above, it's recommended you use the
/// `will_notify_current` method.
///
/// If you've got questions about this though please let us know! We'd like
/// to learn about other use cases here that we did not consider.
///
/// # Panics
///
/// This function will panic if no current future is being polled.
#[deprecated(note = "intended to be removed, see docs for details")]
pub fn is_current(&self) -> bool {
with(|current| current.id == self.id)
}
/// This function is intended as a performance optimization for structures
/// which store a `Task` internally.
///
/// The purpose of this function is to answer the question "if I `notify`
/// this task is it equivalent to `task::current().notify()`". An answer
/// "yes" may mean that you don't actually need to call `task::current()`
/// and store it, but rather you can simply leave a stored task in place. An
/// answer of "no" typically means that you need to call `task::current()`
/// and store it somewhere.
///
/// As this is purely a performance optimization a valid implementation for
/// this function is to always return `false`. A best effort is done to
/// return `true` where possible, but false negatives may happen. Note that
/// this function will not return a false positive, however.
///
/// # Panics
///
/// This function will panic if no current future is being polled.
#[allow(deprecated)]
pub fn will_notify_current(&self) -> bool {
with(|current| {
self.unpark.will_notify(¤t.unpark) &&
self.events.will_notify(¤t.events)
})
}
}
impl fmt::Debug for Task {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Task")
.finish()
}
}
/// Representation of a spawned future/stream.
///
/// This object is returned by the `spawn` function in this module. This
/// represents a "fused task and future", storing all necessary pieces of a task
/// and owning the top-level future that's being driven as well.
///
/// A `Spawn` can be poll'd for completion or execution of the current thread
/// can be blocked indefinitely until a notification arrives. This can be used
/// with either futures or streams, with different methods being available on
/// `Spawn` depending which is used.
pub struct Spawn<T: ?Sized> {
id: usize,
data: LocalMap,
obj: T,
}
/// Spawns a future or stream, returning it and the new task responsible for
/// running it to completion.
///
/// This function is the termination endpoint for running futures. This method
/// will conceptually allocate a new task to run the given object, which is
/// normally either a `Future` or `Stream`.
///
/// This function is similar to the `thread::spawn` function but does not
/// attempt to run code in the background. The future will not make progress
/// until the methods on `Spawn` are called in turn.
pub fn spawn<T>(obj: T) -> Spawn<T> {
Spawn {
id: fresh_task_id(),
obj: obj,
data: local_map(),
}
}
impl<T: ?Sized> Spawn<T> {
/// Get a shared reference to the object the Spawn is wrapping.
pub fn get_ref(&self) -> &T {
&self.obj
}
/// Get a mutable reference to the object the Spawn is wrapping.
pub fn get_mut(&mut self) -> &mut T {
&mut self.obj
}
/// Consume the Spawn, returning its inner object
pub fn into_inner(self) -> T where T: Sized {
self.obj
}
/// Calls the provided closure, scheduling notifications to be sent to the
/// `notify` argument.
pub fn poll_fn_notify<N, F, R>(&mut self,
notify: &N,
id: usize,
f: F) -> R
where F: FnOnce(&mut T) -> R,
N: Clone + Into<NotifyHandle>,
{
let mk = || notify.clone().into();
self.enter(BorrowedUnpark::new(&mk, id), f)
}
/// Polls the internal future, scheduling notifications to be sent to the
/// `notify` argument.
///
/// This method will poll the internal future, testing if it's completed
/// yet. The `notify` argument is used as a sink for notifications sent to
/// this future. That is, while the future is being polled, any call to
/// `task::current()` will return a handle that contains the `notify`
/// specified.
///
/// If this function returns `NotReady`, then the `notify` should have been
/// scheduled to receive a notification when poll can be called again.
/// Otherwise if `Ready` or `Err` is returned, the `Spawn` task can be
/// safely destroyed.
///
/// Note that `notify` itself is passed as a shared reference, and is itself
/// not required to be a `NotifyHandle`. The `Clone` and `Into` trait bounds
/// will be used to convert this `notify` to a `NotifyHandle` if necessary.
/// This construction can avoid an unnecessary atomic reference count bump
/// in some situations.
///
/// ## Unsafety and `id`
///
/// This function and all other `*_notify` functions on this type will treat
/// the `id` specified very carefully, explicitly calling functions like the
/// `notify` argument's `clone_id` and `drop_id` functions. It should be
/// safe to encode a pointer itself into the `id` specified, such as an
/// `Arc<N>` or a `Box<N>`. The `clone_id` and `drop_id` functions are then
/// intended to be sufficient for the memory management related to that
/// pointer.
pub fn poll_future_notify<N>(&mut self,
notify: &N,
id: usize) -> Poll<T::Item, T::Error>
where N: Clone + Into<NotifyHandle>,
T: Future,
{
self.poll_fn_notify(notify, id, |f| f.poll())
}
/// Like `poll_future_notify`, except polls the underlying stream.
pub fn poll_stream_notify<N>(&mut self,
notify: &N,
id: usize)
-> Poll<Option<T::Item>, T::Error>
where N: Clone + Into<NotifyHandle>,
T: Stream,
{
self.poll_fn_notify(notify, id, |s| s.poll())
}
/// Invokes the underlying `start_send` method with this task in place.
///
/// If the underlying operation returns `NotReady` then the `notify` value
/// passed in will receive a notification when the operation is ready to be
/// attempted again.
pub fn start_send_notify<N>(&mut self,
value: T::SinkItem,
notify: &N,
id: usize)
-> StartSend<T::SinkItem, T::SinkError>
where N: Clone + Into<NotifyHandle>,
T: Sink,
{
self.poll_fn_notify(notify, id, |s| s.start_send(value))
}
/// Invokes the underlying `poll_complete` method with this task in place.
///
/// If the underlying operation returns `NotReady` then the `notify` value
/// passed in will receive a notification when the operation is ready to be
/// attempted again.
pub fn poll_flush_notify<N>(&mut self,
notify: &N,
id: usize)
-> Poll<(), T::SinkError>
where N: Clone + Into<NotifyHandle>,
T: Sink,
{
self.poll_fn_notify(notify, id, |s| s.poll_complete())
}
/// Invokes the underlying `close` method with this task in place.
///
/// If the underlying operation returns `NotReady` then the `notify` value
/// passed in will receive a notification when the operation is ready to be
/// attempted again.
pub fn close_notify<N>(&mut self,
notify: &N,
id: usize)
-> Poll<(), T::SinkError>
where N: Clone + Into<NotifyHandle>,
T: Sink,
{
self.poll_fn_notify(notify, id, |s| s.close())
}
fn enter<F, R>(&mut self, unpark: BorrowedUnpark, f: F) -> R
where F: FnOnce(&mut T) -> R
{
let borrowed = BorrowedTask {
id: self.id,
unpark: unpark,
events: BorrowedEvents::new(),
map: &self.data,
};
let obj = &mut self.obj;
set(&borrowed, || f(obj))
}
}
impl<T: fmt::Debug + ?Sized> fmt::Debug for Spawn<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Spawn")
.field("obj", &&self.obj)
.finish()
}
}
/// A trait which represents a sink of notifications that a future is ready to
/// make progress.
///
/// This trait is provided as an argument to the `Spawn::*_notify` family of
/// functions. It's transitively used as part of the `Task::notify` method to
/// internally deliver notifications of readiness of a future to move forward.
///
/// An instance of `Notify` has one primary method, `notify`, which is given a
/// contextual argument as to what's being notified. This contextual argument is
/// *also* provided to the `Spawn::*_notify` family of functions and can be used
/// to reuse an instance of `Notify` across many futures.
///
/// Instances of `Notify` must be safe to share across threads, and the methods
/// be invoked concurrently. They must also live for the `'static` lifetime,
/// not containing any stack references.
pub trait Notify: Send + Sync {
/// Indicates that an associated future and/or task are ready to make
/// progress.
///
/// Typically this means that the receiver of the notification should
/// arrange for the future to get poll'd in a prompt fashion.
///
/// This method takes an `id` as an argument which was transitively passed
/// in from the original call to `Spawn::*_notify`. This id can be used to
/// disambiguate which precise future became ready for polling.
///
/// # Panics
///
/// Since `unpark` may be invoked from arbitrary contexts, it should
/// endeavor not to panic and to do as little work as possible. However, it
/// is not guaranteed not to panic, and callers should be wary. If a panic
/// occurs, that panic may or may not be propagated to the end-user of the
/// future that you'd otherwise wake up.
fn notify(&self, id: usize);
/// This function is called whenever a new copy of `id` is needed.
///
/// This is called in one of two situations:
///
/// * A `Task` is being created through `task::current` while a future is
/// being polled. In that case the instance of `Notify` passed in to one
/// of the `poll_*` functions is called with the `id` passed into the same
/// `poll_*` function.
/// * A `Task` is itself being cloned. Each `Task` contains its own id and a
/// handle to the `Notify` behind it, and the task's `Notify` is used to
/// clone the internal `id` to assign to the new task.
///
/// The `id` returned here will be stored in the `Task`-to-be and used later
/// to pass to `notify` when the `Task::notify` function is called on that
/// `Task`.
///
/// Note that typically this is just the identity function, passing through
/// the identifier. For more unsafe situations, however, if `id` is itself a
/// pointer of some kind this can be used as a hook to "clone" the pointer,
/// depending on what that means for the specified pointer.
fn clone_id(&self, id: usize) -> usize {
id
}
/// All instances of `Task` store an `id` that they're going to internally
/// notify with, and this function is called when the `Task` is dropped.
///
/// This function provides a hook for schemes which encode pointers in this
/// `id` argument to deallocate resources associated with the pointer. It's
/// guaranteed that after this function is called the `Task` containing this
/// `id` will no longer use the `id`.
fn drop_id(&self, id: usize) {
drop(id);
}
}
/// Sets the `NotifyHandle` of the current task for the duration of the provided
/// closure.
///
/// This function takes a type that can be converted into a notify handle,
/// `notify` and `id`, and a closure `f`. The closure `f` will be executed such
/// that calls to `task::current()` will store a reference to the notify handle
/// provided, not the one previously in the environment.
///
/// Note that calls to `task::current()` in the closure provided *will not* be
/// equivalent to `task::current()` before this method is called. The two tasks
/// returned will notify different handles, and the task handles pulled out
/// during the duration of this closure will not notify the previous task. It's
/// recommended that you call `task::current()` in some capacity before calling
/// this function to ensure that calls to `task::current()` inside of this
/// closure can transitively wake up the outer task.
///
/// # Panics
///
/// This function will panic if it is called outside the context of a future's
/// task. This is only valid to call once you've already entered a future via
/// `Spawn::poll_*` functions.
pub fn with_notify<F, T, R>(notify: &T, id: usize, f: F) -> R
where F: FnOnce() -> R,
T: Clone + Into<NotifyHandle>,
{
with(|task| {
let mk = || notify.clone().into();
let new_task = BorrowedTask {
id: task.id,
unpark: BorrowedUnpark::new(&mk, id),
events: task.events,
map: task.map,
};
set(&new_task, f)
})
}
/// An unsafe trait for implementing custom forms of memory management behind a
/// `Task`.
///
/// The `futures` critically relies on "notification handles" to extract for
/// futures to contain and then later inform that they're ready to make
/// progress. These handles, however, must be cheap to create and cheap
/// to clone to ensure that this operation is efficient throughout the
/// execution of a program.
///
/// Typically this sort of memory management is done in the standard library
/// with the `Arc` type. An `Arc` is relatively cheap to allocate an is
/// quite cheap to clone and pass around. Plus, it's 100% safe!
///
/// When working outside the standard library, however, you don't always have
/// and `Arc` type available to you. This trait, `UnsafeNotify`, is intended
/// to be the "unsafe version" of the `Notify` trait. This trait encodes the
/// memory management operations of a `Task`'s notification handle, allowing
/// custom implementations for the memory management of a notification handle.
///
/// Put another way, the core notification type in this library,
/// `NotifyHandle`, simply internally contains an instance of
/// `*mut UnsafeNotify`. This "unsafe trait object" is then used exclusively
/// to operate with, dynamically dispatching calls to clone, drop, and notify.
/// Critically though as a raw pointer it doesn't require a particular form
/// of memory management, allowing external implementations.
///
/// A default implementation of the `UnsafeNotify` trait is provided for the
/// `Arc` type in the standard library. If the `use_std` feature of this crate
/// is not available however, you'll be required to implement your own
/// instance of this trait to pass it into `NotifyHandle::new`.
///
/// # Unsafety
///
/// This trait is manually encoding the memory management of the underlying
/// handle, and as a result is quite unsafe to implement! Implementors of
/// this trait must guarantee:
///
/// * Calls to `clone_raw` produce uniquely owned handles. It should be safe
/// to drop the current handle and have the returned handle still be valid.
/// * Calls to `drop_raw` work with `self` as a raw pointer, deallocating
/// resources associated with it. This is a pretty unsafe operation as it's
/// invalidating the `self` pointer, so extreme care needs to be taken.
///
/// In general it's recommended to review the trait documentation as well as
/// the implementation for `Arc` in this crate. When in doubt ping the
/// `futures` authors to clarify an unsafety question here.
pub unsafe trait UnsafeNotify: Notify {
/// Creates a new `NotifyHandle` from this instance of `UnsafeNotify`.
///
/// This function will create a new uniquely owned handle that under the
/// hood references the same notification instance. In other words calls
/// to `notify` on the returned handle should be equivalent to calls to
/// `notify` on this handle.
///
/// # Unsafety
///
/// This trait is unsafe to implement, as are all these methods. This
/// method is also unsafe to call as it's asserting the `UnsafeNotify`
/// value is in a consistent state. In general it's recommended to
/// review the trait documentation as well as the implementation for `Arc`
/// in this crate. When in doubt ping the `futures` authors to clarify
/// an unsafety question here.
unsafe fn clone_raw(&self) -> NotifyHandle;
/// Drops this instance of `UnsafeNotify`, deallocating resources
/// associated with it.
///
/// This method is intended to have a signature such as:
///
/// ```ignore
/// fn drop_raw(self: *mut Self);
/// ```
///
/// Unfortunately in Rust today that signature is not object safe.
/// Nevertheless it's recommended to implement this function *as if* that
/// were its signature. As such it is not safe to call on an invalid
/// pointer, nor is the validity of the pointer guaranteed after this
/// function returns.
///
/// # Unsafety
///
/// This trait is unsafe to implement, as are all these methods. This
/// method is also unsafe to call as it's asserting the `UnsafeNotify`
/// value is in a consistent state. In general it's recommended to
/// review the trait documentation as well as the implementation for `Arc`
/// in this crate. When in doubt ping the `futures` authors to clarify
/// an unsafety question here.
unsafe fn drop_raw(&self);
}
/// A `NotifyHandle` is the core value through which notifications are routed
/// in the `futures` crate.
///
/// All instances of `Task` will contain a `NotifyHandle` handle internally.
/// This handle itself contains a trait object pointing to an instance of the
/// `Notify` trait, allowing notifications to get routed through it.
///
/// The `NotifyHandle` type internally does not codify any particular memory
/// management strategy. Internally it contains an instance of `*mut
/// UnsafeNotify`, and more details about that trait can be found on its own
/// documentation. Consequently, though, the one constructor of this type,
/// `NotifyHandle::new`, is `unsafe` to call. It is not recommended to call
/// this constructor directly.
///
/// If you're working with the standard library then it's recommended to
/// work with the `Arc` type. If you have a struct, `T`, which implements the
/// `Notify` trait, then you can construct this with
/// `NotifyHandle::from(t: Arc<T>)`. The coercion to `UnsafeNotify` will
/// happen automatically and safely for you.
///
/// When working externally from the standard library it's recommended to
/// provide a similar safe constructor for your custom type as opposed to
/// recommending an invocation of `NotifyHandle::new` directly.
pub struct NotifyHandle {
inner: *mut UnsafeNotify,
}
unsafe impl Send for NotifyHandle {}
unsafe impl Sync for NotifyHandle {}
impl NotifyHandle {
/// Constructs a new `NotifyHandle` directly.
///
/// Note that most code will not need to call this. Implementers of the
/// `UnsafeNotify` trait will typically provide a wrapper that calls this
/// but you otherwise shouldn't call it directly.
///
/// If you're working with the standard library then it's recommended to
/// use the `NotifyHandle::from` function instead which works with the safe
/// `Arc` type and the safe `Notify` trait.
#[inline]
pub unsafe fn new(inner: *mut UnsafeNotify) -> NotifyHandle {
NotifyHandle { inner: inner }
}
/// Invokes the underlying instance of `Notify` with the provided `id`.
pub fn notify(&self, id: usize) {
unsafe { (*self.inner).notify(id) }
}
fn clone_id(&self, id: usize) -> usize {
unsafe { (*self.inner).clone_id(id) }
}
fn drop_id(&self, id: usize) {
unsafe { (*self.inner).drop_id(id) }
}
}
impl Clone for NotifyHandle {
#[inline]
fn clone(&self) -> Self {
unsafe {
(*self.inner).clone_raw()
}
}
}
impl fmt::Debug for NotifyHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("NotifyHandle")
.finish()
}
}
impl Drop for NotifyHandle {
fn drop(&mut self) {
unsafe {
(*self.inner).drop_raw()
}
}
}
/// Marker for a `T` that is behind &'static.
struct StaticRef<T>(PhantomData<T>);
impl<T: Notify> Notify for StaticRef<T> {
fn notify(&self, id: usize) {
let me = unsafe { &*(self as *const _ as *const T) };
me.notify(id);
}
fn clone_id(&self, id: usize) -> usize {
let me = unsafe { &*(self as *const _ as *const T) };
me.clone_id(id)
}
fn drop_id(&self, id: usize) {
let me = unsafe { &*(self as *const _ as *const T) };
me.drop_id(id);
}
}
unsafe impl<T: Notify + 'static> UnsafeNotify for StaticRef<T> {
unsafe fn clone_raw(&self) -> NotifyHandle {
NotifyHandle::new(self as *const _ as *mut StaticRef<T>)
}
unsafe fn drop_raw(&self) {}
}
impl<T: Notify> From<&'static T> for NotifyHandle {
fn from(src : &'static T) -> NotifyHandle {
unsafe { NotifyHandle::new(src as *const _ as *mut StaticRef<T>) }
}
}
#[cfg(feature = "nightly")]
mod nightly {
use super::NotifyHandle;
use core::marker::Unpin;
impl Unpin for NotifyHandle {}
}
|
use core::{sync::atomic::AtomicBool, usize};
use x86_64::instructions::port::{Port, PortReadOnly, PortWriteOnly};
use crate::svec::SVec;
// Assuming "typical" ports
const IO_BASE_PORT: u16 = 0x1F0;
/// 0x1F0
static mut DATA_REG: Port<u16> = Port::new(IO_BASE_PORT);
/// 0x1F1
static mut ERROR_REG: PortReadOnly<u16> = PortReadOnly::new(IO_BASE_PORT + 1);
/// 0x1F1
static mut FEATURES_REG: PortWriteOnly<u16> = PortWriteOnly::new(IO_BASE_PORT + 1);
/// 0x1F2
static mut SECTOR_COUNT_REG: Port<u8> = Port::new(IO_BASE_PORT + 2); //Actually u16, but low and high needs to be sent separately.
/// 0x1F3
static mut LBA_LOW_REG: Port<u8> = Port::new(IO_BASE_PORT + 3); //same
/// 0x1F4
static mut LBA_MID_REG: Port<u8> = Port::new(IO_BASE_PORT + 4); // with these 2
/// 0x1F5
static mut LBA_HIGH_REG: Port<u8> = Port::new(IO_BASE_PORT + 5);
/// 0x1F6
static mut DRIVE_HEAD_REG: Port<u8> = Port::new(IO_BASE_PORT + 6);
/// 0x1F7
static mut STATUS_REG: PortReadOnly<u8> = PortReadOnly::new(IO_BASE_PORT + 7);
/// 0x1F7
static mut COMMAND_REG: Port<u8> = Port::new(IO_BASE_PORT + 7);
const CONTROL_BASE_PORT: u16 = 0x3F6;
/// 0x3F6
static mut ALT_STATUS_REG: PortReadOnly<u8> = PortReadOnly::new(CONTROL_BASE_PORT);
/// 0x3F6
static mut DEVICE_CONTROL_REG: PortWriteOnly<u8> = PortWriteOnly::new(CONTROL_BASE_PORT + 0);
/// 0x3F7
static mut DRIVE_ADRESS_REG: PortReadOnly<u8> = PortReadOnly::new(CONTROL_BASE_PORT + 1);
/// Is the driver busy?
/// Since only one port is used, the two drives on it will have to go one at a time.
/// TODO: make this per disk
static BUSY: AtomicBool = AtomicBool::new(false);
/// What is the maximum `iter` acheived during `poll()`?
/// Used to compensate for fast/slow CPUs
static mut MAX_ITER: usize = 2000;
/// Contains the information on the drives/disks
static mut DRIVES: SVec<DriveInfo, 2> = SVec::new();
/// Intitialize the primary drive bus, and all drives on it.
/// # Safety
/// All port I/O can threaten safety.
///
/// `printer` should be initialized for panic messages.
pub unsafe fn initialize() {
let status = STATUS_REG.read();
if status == 0xFF {
panic!("Floating bus");
}
DEVICE_CONTROL_REG.write(0);
for drive in 0..DRIVES.capacity() {
DRIVES.push(initialize_drive(drive as u8));
}
}
/// Initializes a particular drive, and returns it's info.
unsafe fn initialize_drive(drive: u8) -> DriveInfo {
let mut disk = DriveInfo {
drive,
status: DriveStatus::Unknown,
sectors: 0,
lba48: false,
identify_result: [0; 256],
};
DRIVE_HEAD_REG.write(0xA0 + (drive << 4));
wait_till_idle();
send_lba_and_sector_count(0, 0, false);
COMMAND_REG.write(0xEC); //IDENTIFY
let status = STATUS_REG.read();
if status == 0 {
disk.status = DriveStatus::Disconnected;
return disk;
}
wait_till_idle();
if LBA_MID_REG.read() != 0 || LBA_HIGH_REG.read() != 0 {
disk.status = DriveStatus::Unknown;
return disk;
}
loop {
let status = STATUS_REG.read();
if status & 8 == 8 {
break;
}
if status & 1 == 1 {
disk.status = DriveStatus::Unknown;
return disk;
}
}
for i in 0..256 {
disk.identify_result[i] = DATA_REG.read();
}
// bit 10
if disk.identify_result[83] & 0x200 != 0x200 {
let mut bytes: [u8; 4] = [0; 4];
let low = disk.identify_result[60].to_le_bytes();
bytes[0] = low[0];
bytes[1] = low[1];
let high = disk.identify_result[61].to_le_bytes();
bytes[2] = high[0];
bytes[3] = high[1];
let lba28 = u32::from_le_bytes(bytes);
if lba28 != 0 {
disk.sectors = lba28 as usize;
}
} else {
let mut bytes: [u8; 8] = [0; 8];
let b100 = disk.identify_result[100].to_le_bytes();
for i in 0..b100.len() {
bytes[i] = b100[i];
}
let b101 = disk.identify_result[101].to_le_bytes();
for i in 0..b101.len() {
bytes[i + 2] = b101[i];
}
let b102 = disk.identify_result[102].to_le_bytes();
for i in 0..b102.len() {
bytes[4 + i] = b102[i];
}
let b103 = disk.identify_result[103].to_le_bytes();
for i in 0..b103.len() {
bytes[6 + i] = b103[i];
}
disk.lba48 = true;
disk.sectors = u64::from_le_bytes(bytes) as usize;
}
disk.status = DriveStatus::Connected;
wait_till_idle();
disk
}
/// Info about the particular drive
#[derive(Clone)]
pub struct DriveInfo {
/// Drive number sent to R/W function
pub drive: u8,
/// The status of the drive (See enum for details)
pub status: DriveStatus,
/// Sectors available on drive
/// Should only be used by partition driver.
pub sectors: usize,
/// Does the drive support lba48?
lba48: bool,
/// The result of original IDENTIFY command
identify_result: [u16; 256],
}
/// The status of the drive at initialization.
#[derive(Clone, PartialEq, Eq)]
pub enum DriveStatus {
/// Drive is connected and ready for action.
Connected,
/// Drive is missing
Disconnected,
/// Drive is read-only (unused)
ReadOnly,
/// Drive status unknown:
/// Not a drive, non ATA/LBA drive, or error getting info off it.
Unknown,
}
enum Errors {
/// Address mark not found.
AMNF = 0b0000_0001,
/// Track zero not found.
TKZNF = 0b0000_0010,
/// Aborted command.
ABRT = 0b0000_0100,
/// Media change request.
MCR = 0b0000_1000,
/// ID not found.
IDNF = 0b0001_0000,
/// Media changed.
MC = 0b0010_0000,
/// Uncorrectable data error.
UNC = 0b0100_0000,
/// Bad Block detected.
BBK = 0b1000_0000,
}
/// Returns info for all drives. Check these before sending requests.
pub unsafe fn get_drives() -> SVec<DriveInfo, 2> /* or bigger*/ {
DRIVES.clone()
}
/// Fills up the provided slice with data from disk, starting with `start_sector`
/// This means the slice needs to have a size that's a multiple of 512.
/// # Safety:
/// The contents/existance of a disk to read from is not checked.
pub unsafe fn read_sectors(drive: u8, start_sector: usize, buffer: &mut [u8]) {
if buffer.len() % 512 != 0 {
panic!("Buffer must be a multiple of 512 bytes");
}
if drive > 1 {
panic!("No support for more than 2 drives")
}
if DRIVES[drive as usize].status != DriveStatus::Connected {
panic!("Attempt to read non-connected drive")
}
while BUSY.load(core::sync::atomic::Ordering::Acquire) {}
BUSY.store(true, core::sync::atomic::Ordering::Release);
let lba = buffer.len() / 512;
let lba48 = DRIVES[drive as usize].lba48;
select_drive(drive, lba);
send_lba_and_sector_count(start_sector, lba, lba48);
wait_till_idle();
if lba48 {
COMMAND_REG.write(0x24); // READ SECTORS EXT
} else {
COMMAND_REG.write(0x20); // READ SECTORS
}
for i in 0..buffer.len() / 512 {
poll();
for j in 0..256 {
let val = DATA_REG.read().to_le_bytes();
buffer[i * 512 + j * 2] = val[0];
buffer[i * 512 + j * 2 + 1] = val[1];
}
for _ in 0..MAX_ITER / 400 {
// 5 times minimum
STATUS_REG.read();
}
}
wait_till_idle();
BUSY.store(false, core::sync::atomic::Ordering::Release);
}
/// Writes the provided slice to the disk, starting at `start_sector`
/// Means slice has to be a multiple of 512 bytes.
/// # Safety:
/// This driver has no idea what is stored where, padding with 0 might for instance overwrite the filesystem.
pub unsafe fn write_sectors(drive: u8, start_sector: usize, buffer: &[u8]) {
if buffer.len() % 512 != 0 {
panic!("Buffer must be a multiple of 512 bytes");
}
if drive > 1 {
panic!("No support for more than 2 drives")
}
if DRIVES[drive as usize].status != DriveStatus::Connected {
panic!("Attempted write to non-connected disk")
}
while BUSY.load(core::sync::atomic::Ordering::Acquire) {}
BUSY.store(true, core::sync::atomic::Ordering::Release);
let lba = buffer.len() / 512;
let lba48 = DRIVES[drive as usize].lba48;
select_drive(drive, lba);
send_lba_and_sector_count(start_sector, lba, lba48);
wait_till_idle();
if lba48 {
COMMAND_REG.write(0x34); // WRITE SECTORS EXT
} else {
COMMAND_REG.write(0x30) // WRITE SECTORS
}
for i in 0..buffer.len() / 512 {
poll();
for j in 0..256 {
let val = u16::from_le_bytes([buffer[i * 512 + j * 2], buffer[i * 512 + j * 2 + 1]]);
DATA_REG.write(val);
for _ in 0..MAX_ITER / 200 {
// 10 times minimum
asm!("jmp no_op", "no_op:", options(nostack, nomem));
}
}
for _ in 0..MAX_ITER / 400 {
// 5 times minimum
STATUS_REG.read();
}
}
wait_till_idle();
//Flush cache
COMMAND_REG.write(0xE7);
wait_till_idle();
BUSY.store(false, core::sync::atomic::Ordering::Release);
}
/// Polls the drive until it's idle.
/// End every call to COMMAND_REG with this (after dealing with the result, if applicable) to ensure the next command will be read.
unsafe fn wait_till_idle() {
loop {
if STATUS_REG.read() & 0x80 == 0 {
break;
}
}
}
/// Polls the status of selected drive, breaking when it's finished.
unsafe fn poll() {
//Time to poll (we be singletasking)
let mut iter = 1;
loop {
let status = STATUS_REG.read();
let bsy = status & 0x80 == 0x80;
let drq = status & 8 == 8;
let err = status & 1 == 1;
let df = status & 0x20 == 0x20;
if err || df {
//TODO: error handling
panic!("Harddisk error")
} else if !bsy && drq {
if MAX_ITER < iter {
MAX_ITER = iter;
}
break;
}
if iter % MAX_ITER == 0 {
software_reset();
}
if iter % (MAX_ITER * 100) == 0 {
panic!("Hardrive polling time-out")
}
iter += 1;
}
}
/// Tells the selected disk which sector to start work on on how many sectors
/// # Example:
/// ```
/// //Select master drive
/// DRIVE_HEAD_REG.write(0x40);
/// //Select work sectors
/// send_lba_and_sector_count(start_sector, sectorcount);
/// //Read sectors
/// COMMAND_REG.write(0x24);
/// ```
unsafe fn send_lba_and_sector_count(start_sector: usize, sector_count: usize, lba48: bool) {
let lba = start_sector.to_le_bytes();
let sectorcount = sector_count.to_le_bytes();
if lba48 {
//high bytes
SECTOR_COUNT_REG.write(sectorcount[1]);
LBA_LOW_REG.write(lba[3]);
LBA_MID_REG.write(lba[4]);
LBA_HIGH_REG.write(lba[5]);
//low bytes
SECTOR_COUNT_REG.write(sectorcount[0]);
LBA_LOW_REG.write(lba[0]);
LBA_MID_REG.write(lba[1]);
LBA_HIGH_REG.write(lba[2]);
} else {
SECTOR_COUNT_REG.write(sector_count as u8);
LBA_LOW_REG.write(lba[0]);
LBA_MID_REG.write(lba[1]);
LBA_HIGH_REG.write(lba[2]);
// lba[3] is sent in select_drive()
}
}
/// Selects drive based on LBA mode
unsafe fn select_drive(drive: u8, lba: usize) {
let lba48 = DRIVES[drive as usize].lba48;
if lba48 {
DRIVE_HEAD_REG.write(0x40 | (drive << 4))
} else {
let lba_high_4 = (lba >> 24) & 0x0F;
DRIVE_HEAD_REG.write(0xE0 | (drive << 4) | (lba_high_4 as u8));
}
}
/// Soft reset of the drive
unsafe fn software_reset() {
DEVICE_CONTROL_REG.write(4);
DEVICE_CONTROL_REG.write(0);
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::vec::Vec;
use super::super::qlib::auth::id::*;
use super::super::task::*;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::syscalls::syscalls::*;
const MAX_NGROUPS: i32 = 65536;
// Getuid implements the Linux syscall getuid.
pub fn SysGetuid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let c = task.Thread().Credentials();
let userns = c.lock().UserNamespace.clone();
let ruid = c.lock().RealKUID.In(&userns).OrOverflow();
return Ok(ruid.0 as i64)
}
// Geteuid implements the Linux syscall geteuid.
pub fn SysGeteuid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let c = task.Thread().Credentials();
let userns = c.lock().UserNamespace.clone();
let euid = c.lock().EffectiveKUID.In(&userns).OrOverflow();
return Ok(euid.0 as i64)
}
// Getresuid implements the Linux syscall getresuid.
pub fn SysGetresuid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let ruidAddr = args.arg0 as u64;
let euidAddr = args.arg1 as u64;
let suidAddr = args.arg2 as u64;
let c = task.Thread().Credentials();
let userns = c.lock().UserNamespace.clone();
let ruid = c.lock().RealKUID.In(&userns).OrOverflow();
let euid = c.lock().EffectiveKUID.In(&userns).OrOverflow();
let suid = c.lock().SavedKUID.In(&userns).OrOverflow();
task.CopyOutObj(&ruid, ruidAddr)?;
task.CopyOutObj(&euid, euidAddr)?;
task.CopyOutObj(&suid, suidAddr)?;
return Ok(0)
}
// Getgid implements the Linux syscall getgid.
pub fn SysGetgid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let c = task.Thread().Credentials();
let userns = c.lock().UserNamespace.clone();
let rgid = c.lock().RealKGID.In(&userns).OrOverflow();
return Ok(rgid.0 as i64)
}
// Getegid implements the Linux syscall getegid.
pub fn SysGetegid(task: &mut Task, _args: &SyscallArguments) -> Result<i64> {
let c = task.Thread().Credentials();
let userns = c.lock().UserNamespace.clone();
let egid = c.lock().EffectiveKGID.In(&userns).OrOverflow();
return Ok(egid.0 as i64)
}
// Getresgid implements the Linux syscall getresgid.
pub fn SysGetresgid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let rgidAddr = args.arg0 as u64;
let egidAddr = args.arg1 as u64;
let sgidAddr = args.arg2 as u64;
let c = task.Thread().Credentials();
let userns = c.lock().UserNamespace.clone();
let rgid = c.lock().RealKGID.In(&userns).OrOverflow();
let egid = c.lock().EffectiveKGID.In(&userns).OrOverflow();
let sgid = c.lock().SavedKGID.In(&userns).OrOverflow();
task.CopyOutObj(&rgid, rgidAddr)?;
task.CopyOutObj(&egid, egidAddr)?;
task.CopyOutObj(&sgid, sgidAddr)?;
return Ok(0)
}
// Setuid implements the Linux syscall setuid.
pub fn SysSetuid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let uid = args.arg0 as u32;
let thread = task.Thread();
thread.SetUID(UID(uid))?;
task.creds = thread.Creds();
return Ok(0);
}
// Setuid implements the Linux syscall Setreuid.
pub fn SysSetreuid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let ruid = args.arg0 as u32;
let euid = args.arg1 as u32;
task.Thread().SetREUID(UID(ruid), UID(euid))?;
task.creds = task.Thread().Creds();
return Ok(0);
}
// Setuid implements the Linux syscall Setresuid.
pub fn SysSetresuid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let ruid = args.arg0 as u32;
let euid = args.arg1 as u32;
let suid = args.arg2 as u32;
task.Thread().SetRESUID(UID(ruid), UID(euid), UID(suid))?;
task.creds = task.Thread().Creds();
return Ok(0);
}
// Setuid implements the Linux syscall Setgid.
pub fn SysSetgid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let gid = args.arg0 as u32;
task.Thread().SetGID(GID(gid))?;
task.creds = task.Thread().Creds();
return Ok(0);
}
// Setuid implements the Linux syscall Setregid.
pub fn SysSetregid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let rgid = args.arg0 as u32;
let egid = args.arg1 as u32;
task.Thread().SetREGID(GID(rgid), GID(egid))?;
task.creds = task.Thread().Creds();
return Ok(0);
}
// Setuid implements the Linux syscall Setresgid.
pub fn SysSetresgid(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let rgid = args.arg0 as u32;
let egid = args.arg1 as u32;
let sgid = args.arg2 as u32;
task.Thread().SetRESGID(GID(rgid), GID(egid), GID(sgid))?;
task.creds = task.Thread().Creds();
return Ok(0);
}
// Getgroups implements the Linux syscall getgroups.
pub fn SysGetgroups(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let size = args.arg0 as i32;
let addr = args.arg1 as u64;
if size < 0 {
return Err(Error::SysError(SysErr::EINVAL));
}
let creds = task.Thread().Credentials();
let kgidslen = creds.lock().ExtraKGIDs.len();
// "If size is zero, list is not modified, but the total number of
// supplementary group IDs for the process is returned." - getgroups(2)
if size == 0 {
return Ok(kgidslen as i64);
}
if size < kgidslen as i32 {
return Err(Error::SysError(SysErr::EINVAL));
}
let mut gids = Vec::new();
let userns = task.Thread().UserNamespace();
for kgid in &creds.lock().ExtraKGIDs {
gids.push(kgid.In(&userns).OrOverflow());
}
task.CopyOutSlice(&gids[..], addr, gids.len())?;
return Ok(kgidslen as i64);
}
// Setgroups implements the Linux syscall setgroups.
pub fn SysSetgroups(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let size = args.arg0 as i32;
let addr = args.arg1 as u64;
if size < 0 || size > MAX_NGROUPS {
return Err(Error::SysError(SysErr::EINVAL));
}
if size == 0 {
let zero: [GID; 0] = [GID(0); 0];
task.Thread().SetExtraGIDs(&zero)?;
return Ok(0)
}
let gids: Vec<GID> = task.CopyInVec(addr, size as usize)?;
task.Thread().SetExtraGIDs(&gids[..])?;
return Ok(0)
} |
pub mod game;
pub mod simulation;
pub mod ui;
pub mod utils;
use ggez::{ContextBuilder, event};
use game::GameState;
use ui::{ui_manager::UIManager, ui_element::UIElement};
use utils::vector2::Vector2F;
const G: f32 = 2.0;
const TIME_STEP: f32 = 0.5;
const WIN_WIDTH: f32 = 1280.0;
const WIN_HEIGHT: f32 = 848.0;
fn main() {
let (ctx, event_loop) = ContextBuilder::new("NBody Simulation", "Gato")
.window_mode(
ggez::conf::WindowMode::default()
.dimensions(WIN_WIDTH, WIN_HEIGHT)
.resizable(false),
)
.window_setup(
ggez::conf::WindowSetup::default()
.title("Gravity Simulator")
.samples(ggez::conf::NumSamples::Sixteen),
)
.build()
.expect("Error");
let game_state = GameState::new(
TIME_STEP,
G,
UIManager::new(vec![
UIElement::new(
"Pause",
"Unpaused",
16.0,
Vector2F::new(0.0, ui::relative_height(0.005))),
UIElement::new(
"Speed",
"Speed: 1.0x",
16.0,
Vector2F::new(0.0, ui::relative_height(0.025)),
),
]),
);
event::run(ctx, event_loop, game_state);
}
|
#[allow(unused)]
fn color(red: f64, green: f64, blue: f64, alpha: f64) -> String {
fn quantize(f: f64) -> i64 {
(f.max(0.0).min(1.0) * 255.0) as i64
}
format!(
"#{:02X}{:02X}{:02X}{:02X}",
quantize(1.0 - alpha),
quantize(red),
quantize(green),
quantize(blue)
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn color_formatting() {
assert_eq!(color(2.0, 3.0, 4.0, 5.0), "#FFFFFFFF");
assert_eq!(color(1.0, 1.0, 1.0, 1.0), "#FFFFFFFF");
assert_eq!(color(0.5, 0.5, 0.5, 0.5), "#7F7F7F7F");
assert_eq!(color(0.0, 0.0, 0.0, 0.0), "#00000000");
assert_eq!(color(0.0, 0.0, 0.0, 0.0), "#00000000");
}
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtNetwork/qnetworkproxy.h
// dst-file: /src/network/qnetworkproxy.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::super::core::qstring::QString; // 771
use super::super::core::qbytearray::QByteArray; // 771
use super::super::core::qvariant::QVariant; // 771
// use super::qnetworkproxy::QNetworkProxyQuery; // 773
use super::super::core::qurl::QUrl; // 771
use super::qnetworkconfiguration::QNetworkConfiguration; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QNetworkProxy_Class_Size() -> c_int;
// proto: static QNetworkProxy QNetworkProxy::applicationProxy();
fn _ZN13QNetworkProxy16applicationProxyEv() -> *mut c_void;
// proto: void QNetworkProxy::~QNetworkProxy();
fn _ZN13QNetworkProxyD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QString QNetworkProxy::hostName();
fn _ZNK13QNetworkProxy8hostNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkProxy::QNetworkProxy();
fn _ZN13QNetworkProxyC2Ev(qthis: u64 /* *mut c_void*/);
// proto: QList<QByteArray> QNetworkProxy::rawHeaderList();
fn _ZNK13QNetworkProxy13rawHeaderListEv(qthis: u64 /* *mut c_void*/);
// proto: static void QNetworkProxy::setApplicationProxy(const QNetworkProxy & proxy);
fn _ZN13QNetworkProxy19setApplicationProxyERKS_(arg0: *mut c_void);
// proto: void QNetworkProxy::setHostName(const QString & hostName);
fn _ZN13QNetworkProxy11setHostNameERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QString QNetworkProxy::user();
fn _ZNK13QNetworkProxy4userEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QNetworkProxy::password();
fn _ZNK13QNetworkProxy8passwordEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QByteArray QNetworkProxy::rawHeader(const QByteArray & headerName);
fn _ZNK13QNetworkProxy9rawHeaderERK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: bool QNetworkProxy::isTransparentProxy();
fn _ZNK13QNetworkProxy18isTransparentProxyEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QNetworkProxy::setPassword(const QString & password);
fn _ZN13QNetworkProxy11setPasswordERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxy::QNetworkProxy(const QNetworkProxy & other);
fn _ZN13QNetworkProxyC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QNetworkProxy::hasRawHeader(const QByteArray & headerName);
fn _ZNK13QNetworkProxy12hasRawHeaderERK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: void QNetworkProxy::swap(QNetworkProxy & other);
fn _ZN13QNetworkProxy4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: quint16 QNetworkProxy::port();
fn _ZNK13QNetworkProxy4portEv(qthis: u64 /* *mut c_void*/) -> c_ushort;
// proto: void QNetworkProxy::setUser(const QString & userName);
fn _ZN13QNetworkProxy7setUserERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxy::setPort(quint16 port);
fn _ZN13QNetworkProxy7setPortEt(qthis: u64 /* *mut c_void*/, arg0: c_ushort);
// proto: void QNetworkProxy::setRawHeader(const QByteArray & headerName, const QByteArray & value);
fn _ZN13QNetworkProxy12setRawHeaderERK10QByteArrayS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: bool QNetworkProxy::isCachingProxy();
fn _ZNK13QNetworkProxy14isCachingProxyEv(qthis: u64 /* *mut c_void*/) -> c_char;
fn QNetworkProxyFactory_Class_Size() -> c_int;
// proto: static void QNetworkProxyFactory::setUseSystemConfiguration(bool enable);
fn _ZN20QNetworkProxyFactory25setUseSystemConfigurationEb(arg0: c_char);
// proto: void QNetworkProxyFactory::QNetworkProxyFactory();
fn _ZN20QNetworkProxyFactoryC2Ev(qthis: u64 /* *mut c_void*/);
// proto: static void QNetworkProxyFactory::setApplicationProxyFactory(QNetworkProxyFactory * factory);
fn _ZN20QNetworkProxyFactory26setApplicationProxyFactoryEPS_(arg0: *mut c_void);
// proto: static QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery & query);
fn _ZN20QNetworkProxyFactory19systemProxyForQueryERK18QNetworkProxyQuery(arg0: *mut c_void);
// proto: QList<QNetworkProxy> QNetworkProxyFactory::queryProxy(const QNetworkProxyQuery & query);
fn _ZN20QNetworkProxyFactory10queryProxyERK18QNetworkProxyQuery(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxyFactory::~QNetworkProxyFactory();
fn _ZN20QNetworkProxyFactoryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: static QList<QNetworkProxy> QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuery & query);
fn _ZN20QNetworkProxyFactory13proxyForQueryERK18QNetworkProxyQuery(arg0: *mut c_void);
fn QNetworkProxyQuery_Class_Size() -> c_int;
// proto: QUrl QNetworkProxyQuery::url();
fn _ZNK18QNetworkProxyQuery3urlEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QNetworkProxyQuery::localPort();
fn _ZNK18QNetworkProxyQuery9localPortEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QNetworkProxyQuery::setNetworkConfiguration(const QNetworkConfiguration & networkConfiguration);
fn _ZN18QNetworkProxyQuery23setNetworkConfigurationERK21QNetworkConfiguration(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxyQuery::setProtocolTag(const QString & protocolTag);
fn _ZN18QNetworkProxyQuery14setProtocolTagERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxyQuery::setUrl(const QUrl & url);
fn _ZN18QNetworkProxyQuery6setUrlERK4QUrl(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QNetworkProxyQuery::peerPort();
fn _ZNK18QNetworkProxyQuery8peerPortEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QNetworkProxyQuery::setLocalPort(int port);
fn _ZN18QNetworkProxyQuery12setLocalPortEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QNetworkProxyQuery::~QNetworkProxyQuery();
fn _ZN18QNetworkProxyQueryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkProxyQuery & other);
fn _ZN18QNetworkProxyQueryC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxyQuery::setPeerHostName(const QString & hostname);
fn _ZN18QNetworkProxyQuery15setPeerHostNameERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxyQuery::swap(QNetworkProxyQuery & other);
fn _ZN18QNetworkProxyQuery4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkProxyQuery::setPeerPort(int port);
fn _ZN18QNetworkProxyQuery11setPeerPortEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: QNetworkConfiguration QNetworkProxyQuery::networkConfiguration();
fn _ZNK18QNetworkProxyQuery20networkConfigurationEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QNetworkProxyQuery::peerHostName();
fn _ZNK18QNetworkProxyQuery12peerHostNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QNetworkProxyQuery::protocolTag();
fn _ZNK18QNetworkProxyQuery11protocolTagEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkProxyQuery::QNetworkProxyQuery();
fn _ZN18QNetworkProxyQueryC2Ev(qthis: u64 /* *mut c_void*/);
} // <= ext block end
// body block begin =>
// class sizeof(QNetworkProxy)=1
#[derive(Default)]
pub struct QNetworkProxy {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QNetworkProxyFactory)=8
#[derive(Default)]
pub struct QNetworkProxyFactory {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QNetworkProxyQuery)=1
#[derive(Default)]
pub struct QNetworkProxyQuery {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QNetworkProxy {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkProxy {
return QNetworkProxy{qclsinst: qthis, ..Default::default()};
}
}
// proto: static QNetworkProxy QNetworkProxy::applicationProxy();
impl /*struct*/ QNetworkProxy {
pub fn applicationProxy_s<RetType, T: QNetworkProxy_applicationProxy_s<RetType>>( overload_args: T) -> RetType {
return overload_args.applicationProxy_s();
// return 1;
}
}
pub trait QNetworkProxy_applicationProxy_s<RetType> {
fn applicationProxy_s(self ) -> RetType;
}
// proto: static QNetworkProxy QNetworkProxy::applicationProxy();
impl<'a> /*trait*/ QNetworkProxy_applicationProxy_s<QNetworkProxy> for () {
fn applicationProxy_s(self ) -> QNetworkProxy {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy16applicationProxyEv()};
let mut ret = unsafe {_ZN13QNetworkProxy16applicationProxyEv()};
let mut ret1 = QNetworkProxy::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkProxy::~QNetworkProxy();
impl /*struct*/ QNetworkProxy {
pub fn free<RetType, T: QNetworkProxy_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QNetworkProxy_free<RetType> {
fn free(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::~QNetworkProxy();
impl<'a> /*trait*/ QNetworkProxy_free<()> for () {
fn free(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxyD2Ev()};
unsafe {_ZN13QNetworkProxyD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QString QNetworkProxy::hostName();
impl /*struct*/ QNetworkProxy {
pub fn hostName<RetType, T: QNetworkProxy_hostName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hostName(self);
// return 1;
}
}
pub trait QNetworkProxy_hostName<RetType> {
fn hostName(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: QString QNetworkProxy::hostName();
impl<'a> /*trait*/ QNetworkProxy_hostName<QString> for () {
fn hostName(self , rsthis: & QNetworkProxy) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy8hostNameEv()};
let mut ret = unsafe {_ZNK13QNetworkProxy8hostNameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkProxy::QNetworkProxy();
impl /*struct*/ QNetworkProxy {
pub fn new<T: QNetworkProxy_new>(value: T) -> QNetworkProxy {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QNetworkProxy_new {
fn new(self) -> QNetworkProxy;
}
// proto: void QNetworkProxy::QNetworkProxy();
impl<'a> /*trait*/ QNetworkProxy_new for () {
fn new(self) -> QNetworkProxy {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxyC2Ev()};
let ctysz: c_int = unsafe{QNetworkProxy_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN13QNetworkProxyC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkProxy{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QList<QByteArray> QNetworkProxy::rawHeaderList();
impl /*struct*/ QNetworkProxy {
pub fn rawHeaderList<RetType, T: QNetworkProxy_rawHeaderList<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rawHeaderList(self);
// return 1;
}
}
pub trait QNetworkProxy_rawHeaderList<RetType> {
fn rawHeaderList(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: QList<QByteArray> QNetworkProxy::rawHeaderList();
impl<'a> /*trait*/ QNetworkProxy_rawHeaderList<()> for () {
fn rawHeaderList(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy13rawHeaderListEv()};
unsafe {_ZNK13QNetworkProxy13rawHeaderListEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: static void QNetworkProxy::setApplicationProxy(const QNetworkProxy & proxy);
impl /*struct*/ QNetworkProxy {
pub fn setApplicationProxy_s<RetType, T: QNetworkProxy_setApplicationProxy_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setApplicationProxy_s();
// return 1;
}
}
pub trait QNetworkProxy_setApplicationProxy_s<RetType> {
fn setApplicationProxy_s(self ) -> RetType;
}
// proto: static void QNetworkProxy::setApplicationProxy(const QNetworkProxy & proxy);
impl<'a> /*trait*/ QNetworkProxy_setApplicationProxy_s<()> for (&'a QNetworkProxy) {
fn setApplicationProxy_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy19setApplicationProxyERKS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxy19setApplicationProxyERKS_(arg0)};
// return 1;
}
}
// proto: void QNetworkProxy::setHostName(const QString & hostName);
impl /*struct*/ QNetworkProxy {
pub fn setHostName<RetType, T: QNetworkProxy_setHostName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setHostName(self);
// return 1;
}
}
pub trait QNetworkProxy_setHostName<RetType> {
fn setHostName(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::setHostName(const QString & hostName);
impl<'a> /*trait*/ QNetworkProxy_setHostName<()> for (&'a QString) {
fn setHostName(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy11setHostNameERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxy11setHostNameERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QString QNetworkProxy::user();
impl /*struct*/ QNetworkProxy {
pub fn user<RetType, T: QNetworkProxy_user<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.user(self);
// return 1;
}
}
pub trait QNetworkProxy_user<RetType> {
fn user(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: QString QNetworkProxy::user();
impl<'a> /*trait*/ QNetworkProxy_user<QString> for () {
fn user(self , rsthis: & QNetworkProxy) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy4userEv()};
let mut ret = unsafe {_ZNK13QNetworkProxy4userEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QNetworkProxy::password();
impl /*struct*/ QNetworkProxy {
pub fn password<RetType, T: QNetworkProxy_password<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.password(self);
// return 1;
}
}
pub trait QNetworkProxy_password<RetType> {
fn password(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: QString QNetworkProxy::password();
impl<'a> /*trait*/ QNetworkProxy_password<QString> for () {
fn password(self , rsthis: & QNetworkProxy) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy8passwordEv()};
let mut ret = unsafe {_ZNK13QNetworkProxy8passwordEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QByteArray QNetworkProxy::rawHeader(const QByteArray & headerName);
impl /*struct*/ QNetworkProxy {
pub fn rawHeader<RetType, T: QNetworkProxy_rawHeader<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rawHeader(self);
// return 1;
}
}
pub trait QNetworkProxy_rawHeader<RetType> {
fn rawHeader(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: QByteArray QNetworkProxy::rawHeader(const QByteArray & headerName);
impl<'a> /*trait*/ QNetworkProxy_rawHeader<QByteArray> for (&'a QByteArray) {
fn rawHeader(self , rsthis: & QNetworkProxy) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy9rawHeaderERK10QByteArray()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK13QNetworkProxy9rawHeaderERK10QByteArray(rsthis.qclsinst, arg0)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QNetworkProxy::isTransparentProxy();
impl /*struct*/ QNetworkProxy {
pub fn isTransparentProxy<RetType, T: QNetworkProxy_isTransparentProxy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isTransparentProxy(self);
// return 1;
}
}
pub trait QNetworkProxy_isTransparentProxy<RetType> {
fn isTransparentProxy(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: bool QNetworkProxy::isTransparentProxy();
impl<'a> /*trait*/ QNetworkProxy_isTransparentProxy<i8> for () {
fn isTransparentProxy(self , rsthis: & QNetworkProxy) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy18isTransparentProxyEv()};
let mut ret = unsafe {_ZNK13QNetworkProxy18isTransparentProxyEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QNetworkProxy::setPassword(const QString & password);
impl /*struct*/ QNetworkProxy {
pub fn setPassword<RetType, T: QNetworkProxy_setPassword<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPassword(self);
// return 1;
}
}
pub trait QNetworkProxy_setPassword<RetType> {
fn setPassword(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::setPassword(const QString & password);
impl<'a> /*trait*/ QNetworkProxy_setPassword<()> for (&'a QString) {
fn setPassword(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy11setPasswordERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxy11setPasswordERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxy::QNetworkProxy(const QNetworkProxy & other);
impl<'a> /*trait*/ QNetworkProxy_new for (&'a QNetworkProxy) {
fn new(self) -> QNetworkProxy {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxyC2ERKS_()};
let ctysz: c_int = unsafe{QNetworkProxy_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxyC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkProxy{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QNetworkProxy::hasRawHeader(const QByteArray & headerName);
impl /*struct*/ QNetworkProxy {
pub fn hasRawHeader<RetType, T: QNetworkProxy_hasRawHeader<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasRawHeader(self);
// return 1;
}
}
pub trait QNetworkProxy_hasRawHeader<RetType> {
fn hasRawHeader(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: bool QNetworkProxy::hasRawHeader(const QByteArray & headerName);
impl<'a> /*trait*/ QNetworkProxy_hasRawHeader<i8> for (&'a QByteArray) {
fn hasRawHeader(self , rsthis: & QNetworkProxy) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy12hasRawHeaderERK10QByteArray()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK13QNetworkProxy12hasRawHeaderERK10QByteArray(rsthis.qclsinst, arg0)};
return ret as i8;
// return 1;
}
}
// proto: void QNetworkProxy::swap(QNetworkProxy & other);
impl /*struct*/ QNetworkProxy {
pub fn swap<RetType, T: QNetworkProxy_swap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.swap(self);
// return 1;
}
}
pub trait QNetworkProxy_swap<RetType> {
fn swap(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::swap(QNetworkProxy & other);
impl<'a> /*trait*/ QNetworkProxy_swap<()> for (&'a QNetworkProxy) {
fn swap(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy4swapERS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxy4swapERS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: quint16 QNetworkProxy::port();
impl /*struct*/ QNetworkProxy {
pub fn port<RetType, T: QNetworkProxy_port<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.port(self);
// return 1;
}
}
pub trait QNetworkProxy_port<RetType> {
fn port(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: quint16 QNetworkProxy::port();
impl<'a> /*trait*/ QNetworkProxy_port<u16> for () {
fn port(self , rsthis: & QNetworkProxy) -> u16 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy4portEv()};
let mut ret = unsafe {_ZNK13QNetworkProxy4portEv(rsthis.qclsinst)};
return ret as u16;
// return 1;
}
}
// proto: void QNetworkProxy::setUser(const QString & userName);
impl /*struct*/ QNetworkProxy {
pub fn setUser<RetType, T: QNetworkProxy_setUser<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setUser(self);
// return 1;
}
}
pub trait QNetworkProxy_setUser<RetType> {
fn setUser(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::setUser(const QString & userName);
impl<'a> /*trait*/ QNetworkProxy_setUser<()> for (&'a QString) {
fn setUser(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy7setUserERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxy7setUserERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxy::setPort(quint16 port);
impl /*struct*/ QNetworkProxy {
pub fn setPort<RetType, T: QNetworkProxy_setPort<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPort(self);
// return 1;
}
}
pub trait QNetworkProxy_setPort<RetType> {
fn setPort(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::setPort(quint16 port);
impl<'a> /*trait*/ QNetworkProxy_setPort<()> for (u16) {
fn setPort(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy7setPortEt()};
let arg0 = self as c_ushort;
unsafe {_ZN13QNetworkProxy7setPortEt(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxy::setRawHeader(const QByteArray & headerName, const QByteArray & value);
impl /*struct*/ QNetworkProxy {
pub fn setRawHeader<RetType, T: QNetworkProxy_setRawHeader<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRawHeader(self);
// return 1;
}
}
pub trait QNetworkProxy_setRawHeader<RetType> {
fn setRawHeader(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: void QNetworkProxy::setRawHeader(const QByteArray & headerName, const QByteArray & value);
impl<'a> /*trait*/ QNetworkProxy_setRawHeader<()> for (&'a QByteArray, &'a QByteArray) {
fn setRawHeader(self , rsthis: & QNetworkProxy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QNetworkProxy12setRawHeaderERK10QByteArrayS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {_ZN13QNetworkProxy12setRawHeaderERK10QByteArrayS2_(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: bool QNetworkProxy::isCachingProxy();
impl /*struct*/ QNetworkProxy {
pub fn isCachingProxy<RetType, T: QNetworkProxy_isCachingProxy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isCachingProxy(self);
// return 1;
}
}
pub trait QNetworkProxy_isCachingProxy<RetType> {
fn isCachingProxy(self , rsthis: & QNetworkProxy) -> RetType;
}
// proto: bool QNetworkProxy::isCachingProxy();
impl<'a> /*trait*/ QNetworkProxy_isCachingProxy<i8> for () {
fn isCachingProxy(self , rsthis: & QNetworkProxy) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QNetworkProxy14isCachingProxyEv()};
let mut ret = unsafe {_ZNK13QNetworkProxy14isCachingProxyEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
impl /*struct*/ QNetworkProxyFactory {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkProxyFactory {
return QNetworkProxyFactory{qclsinst: qthis, ..Default::default()};
}
}
// proto: static void QNetworkProxyFactory::setUseSystemConfiguration(bool enable);
impl /*struct*/ QNetworkProxyFactory {
pub fn setUseSystemConfiguration_s<RetType, T: QNetworkProxyFactory_setUseSystemConfiguration_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setUseSystemConfiguration_s();
// return 1;
}
}
pub trait QNetworkProxyFactory_setUseSystemConfiguration_s<RetType> {
fn setUseSystemConfiguration_s(self ) -> RetType;
}
// proto: static void QNetworkProxyFactory::setUseSystemConfiguration(bool enable);
impl<'a> /*trait*/ QNetworkProxyFactory_setUseSystemConfiguration_s<()> for (i8) {
fn setUseSystemConfiguration_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactory25setUseSystemConfigurationEb()};
let arg0 = self as c_char;
unsafe {_ZN20QNetworkProxyFactory25setUseSystemConfigurationEb(arg0)};
// return 1;
}
}
// proto: void QNetworkProxyFactory::QNetworkProxyFactory();
impl /*struct*/ QNetworkProxyFactory {
pub fn new<T: QNetworkProxyFactory_new>(value: T) -> QNetworkProxyFactory {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QNetworkProxyFactory_new {
fn new(self) -> QNetworkProxyFactory;
}
// proto: void QNetworkProxyFactory::QNetworkProxyFactory();
impl<'a> /*trait*/ QNetworkProxyFactory_new for () {
fn new(self) -> QNetworkProxyFactory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactoryC2Ev()};
let ctysz: c_int = unsafe{QNetworkProxyFactory_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN20QNetworkProxyFactoryC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkProxyFactory{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static void QNetworkProxyFactory::setApplicationProxyFactory(QNetworkProxyFactory * factory);
impl /*struct*/ QNetworkProxyFactory {
pub fn setApplicationProxyFactory_s<RetType, T: QNetworkProxyFactory_setApplicationProxyFactory_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setApplicationProxyFactory_s();
// return 1;
}
}
pub trait QNetworkProxyFactory_setApplicationProxyFactory_s<RetType> {
fn setApplicationProxyFactory_s(self ) -> RetType;
}
// proto: static void QNetworkProxyFactory::setApplicationProxyFactory(QNetworkProxyFactory * factory);
impl<'a> /*trait*/ QNetworkProxyFactory_setApplicationProxyFactory_s<()> for (&'a QNetworkProxyFactory) {
fn setApplicationProxyFactory_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactory26setApplicationProxyFactoryEPS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkProxyFactory26setApplicationProxyFactoryEPS_(arg0)};
// return 1;
}
}
// proto: static QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery & query);
impl /*struct*/ QNetworkProxyFactory {
pub fn systemProxyForQuery_s<RetType, T: QNetworkProxyFactory_systemProxyForQuery_s<RetType>>( overload_args: T) -> RetType {
return overload_args.systemProxyForQuery_s();
// return 1;
}
}
pub trait QNetworkProxyFactory_systemProxyForQuery_s<RetType> {
fn systemProxyForQuery_s(self ) -> RetType;
}
// proto: static QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery & query);
impl<'a> /*trait*/ QNetworkProxyFactory_systemProxyForQuery_s<()> for (&'a QNetworkProxyQuery) {
fn systemProxyForQuery_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactory19systemProxyForQueryERK18QNetworkProxyQuery()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkProxyFactory19systemProxyForQueryERK18QNetworkProxyQuery(arg0)};
// return 1;
}
}
// proto: QList<QNetworkProxy> QNetworkProxyFactory::queryProxy(const QNetworkProxyQuery & query);
impl /*struct*/ QNetworkProxyFactory {
pub fn queryProxy<RetType, T: QNetworkProxyFactory_queryProxy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.queryProxy(self);
// return 1;
}
}
pub trait QNetworkProxyFactory_queryProxy<RetType> {
fn queryProxy(self , rsthis: & QNetworkProxyFactory) -> RetType;
}
// proto: QList<QNetworkProxy> QNetworkProxyFactory::queryProxy(const QNetworkProxyQuery & query);
impl<'a> /*trait*/ QNetworkProxyFactory_queryProxy<()> for (&'a QNetworkProxyQuery) {
fn queryProxy(self , rsthis: & QNetworkProxyFactory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactory10queryProxyERK18QNetworkProxyQuery()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkProxyFactory10queryProxyERK18QNetworkProxyQuery(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxyFactory::~QNetworkProxyFactory();
impl /*struct*/ QNetworkProxyFactory {
pub fn free<RetType, T: QNetworkProxyFactory_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QNetworkProxyFactory_free<RetType> {
fn free(self , rsthis: & QNetworkProxyFactory) -> RetType;
}
// proto: void QNetworkProxyFactory::~QNetworkProxyFactory();
impl<'a> /*trait*/ QNetworkProxyFactory_free<()> for () {
fn free(self , rsthis: & QNetworkProxyFactory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactoryD2Ev()};
unsafe {_ZN20QNetworkProxyFactoryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: static QList<QNetworkProxy> QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuery & query);
impl /*struct*/ QNetworkProxyFactory {
pub fn proxyForQuery_s<RetType, T: QNetworkProxyFactory_proxyForQuery_s<RetType>>( overload_args: T) -> RetType {
return overload_args.proxyForQuery_s();
// return 1;
}
}
pub trait QNetworkProxyFactory_proxyForQuery_s<RetType> {
fn proxyForQuery_s(self ) -> RetType;
}
// proto: static QList<QNetworkProxy> QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuery & query);
impl<'a> /*trait*/ QNetworkProxyFactory_proxyForQuery_s<()> for (&'a QNetworkProxyQuery) {
fn proxyForQuery_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkProxyFactory13proxyForQueryERK18QNetworkProxyQuery()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkProxyFactory13proxyForQueryERK18QNetworkProxyQuery(arg0)};
// return 1;
}
}
impl /*struct*/ QNetworkProxyQuery {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkProxyQuery {
return QNetworkProxyQuery{qclsinst: qthis, ..Default::default()};
}
}
// proto: QUrl QNetworkProxyQuery::url();
impl /*struct*/ QNetworkProxyQuery {
pub fn url<RetType, T: QNetworkProxyQuery_url<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.url(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_url<RetType> {
fn url(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: QUrl QNetworkProxyQuery::url();
impl<'a> /*trait*/ QNetworkProxyQuery_url<QUrl> for () {
fn url(self , rsthis: & QNetworkProxyQuery) -> QUrl {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QNetworkProxyQuery3urlEv()};
let mut ret = unsafe {_ZNK18QNetworkProxyQuery3urlEv(rsthis.qclsinst)};
let mut ret1 = QUrl::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QNetworkProxyQuery::localPort();
impl /*struct*/ QNetworkProxyQuery {
pub fn localPort<RetType, T: QNetworkProxyQuery_localPort<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.localPort(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_localPort<RetType> {
fn localPort(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: int QNetworkProxyQuery::localPort();
impl<'a> /*trait*/ QNetworkProxyQuery_localPort<i32> for () {
fn localPort(self , rsthis: & QNetworkProxyQuery) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QNetworkProxyQuery9localPortEv()};
let mut ret = unsafe {_ZNK18QNetworkProxyQuery9localPortEv(rsthis.qclsinst)};
return ret as i32;
// return 1;
}
}
// proto: void QNetworkProxyQuery::setNetworkConfiguration(const QNetworkConfiguration & networkConfiguration);
impl /*struct*/ QNetworkProxyQuery {
pub fn setNetworkConfiguration<RetType, T: QNetworkProxyQuery_setNetworkConfiguration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setNetworkConfiguration(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_setNetworkConfiguration<RetType> {
fn setNetworkConfiguration(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::setNetworkConfiguration(const QNetworkConfiguration & networkConfiguration);
impl<'a> /*trait*/ QNetworkProxyQuery_setNetworkConfiguration<()> for (&'a QNetworkConfiguration) {
fn setNetworkConfiguration(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery23setNetworkConfigurationERK21QNetworkConfiguration()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN18QNetworkProxyQuery23setNetworkConfigurationERK21QNetworkConfiguration(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxyQuery::setProtocolTag(const QString & protocolTag);
impl /*struct*/ QNetworkProxyQuery {
pub fn setProtocolTag<RetType, T: QNetworkProxyQuery_setProtocolTag<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setProtocolTag(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_setProtocolTag<RetType> {
fn setProtocolTag(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::setProtocolTag(const QString & protocolTag);
impl<'a> /*trait*/ QNetworkProxyQuery_setProtocolTag<()> for (&'a QString) {
fn setProtocolTag(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery14setProtocolTagERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN18QNetworkProxyQuery14setProtocolTagERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxyQuery::setUrl(const QUrl & url);
impl /*struct*/ QNetworkProxyQuery {
pub fn setUrl<RetType, T: QNetworkProxyQuery_setUrl<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setUrl(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_setUrl<RetType> {
fn setUrl(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::setUrl(const QUrl & url);
impl<'a> /*trait*/ QNetworkProxyQuery_setUrl<()> for (&'a QUrl) {
fn setUrl(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery6setUrlERK4QUrl()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN18QNetworkProxyQuery6setUrlERK4QUrl(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QNetworkProxyQuery::peerPort();
impl /*struct*/ QNetworkProxyQuery {
pub fn peerPort<RetType, T: QNetworkProxyQuery_peerPort<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.peerPort(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_peerPort<RetType> {
fn peerPort(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: int QNetworkProxyQuery::peerPort();
impl<'a> /*trait*/ QNetworkProxyQuery_peerPort<i32> for () {
fn peerPort(self , rsthis: & QNetworkProxyQuery) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QNetworkProxyQuery8peerPortEv()};
let mut ret = unsafe {_ZNK18QNetworkProxyQuery8peerPortEv(rsthis.qclsinst)};
return ret as i32;
// return 1;
}
}
// proto: void QNetworkProxyQuery::setLocalPort(int port);
impl /*struct*/ QNetworkProxyQuery {
pub fn setLocalPort<RetType, T: QNetworkProxyQuery_setLocalPort<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLocalPort(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_setLocalPort<RetType> {
fn setLocalPort(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::setLocalPort(int port);
impl<'a> /*trait*/ QNetworkProxyQuery_setLocalPort<()> for (i32) {
fn setLocalPort(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery12setLocalPortEi()};
let arg0 = self as c_int;
unsafe {_ZN18QNetworkProxyQuery12setLocalPortEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxyQuery::~QNetworkProxyQuery();
impl /*struct*/ QNetworkProxyQuery {
pub fn free<RetType, T: QNetworkProxyQuery_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_free<RetType> {
fn free(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::~QNetworkProxyQuery();
impl<'a> /*trait*/ QNetworkProxyQuery_free<()> for () {
fn free(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQueryD2Ev()};
unsafe {_ZN18QNetworkProxyQueryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkProxyQuery & other);
impl /*struct*/ QNetworkProxyQuery {
pub fn new<T: QNetworkProxyQuery_new>(value: T) -> QNetworkProxyQuery {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QNetworkProxyQuery_new {
fn new(self) -> QNetworkProxyQuery;
}
// proto: void QNetworkProxyQuery::QNetworkProxyQuery(const QNetworkProxyQuery & other);
impl<'a> /*trait*/ QNetworkProxyQuery_new for (&'a QNetworkProxyQuery) {
fn new(self) -> QNetworkProxyQuery {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQueryC2ERKS_()};
let ctysz: c_int = unsafe{QNetworkProxyQuery_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN18QNetworkProxyQueryC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkProxyQuery{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QNetworkProxyQuery::setPeerHostName(const QString & hostname);
impl /*struct*/ QNetworkProxyQuery {
pub fn setPeerHostName<RetType, T: QNetworkProxyQuery_setPeerHostName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPeerHostName(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_setPeerHostName<RetType> {
fn setPeerHostName(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::setPeerHostName(const QString & hostname);
impl<'a> /*trait*/ QNetworkProxyQuery_setPeerHostName<()> for (&'a QString) {
fn setPeerHostName(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery15setPeerHostNameERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN18QNetworkProxyQuery15setPeerHostNameERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxyQuery::swap(QNetworkProxyQuery & other);
impl /*struct*/ QNetworkProxyQuery {
pub fn swap<RetType, T: QNetworkProxyQuery_swap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.swap(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_swap<RetType> {
fn swap(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::swap(QNetworkProxyQuery & other);
impl<'a> /*trait*/ QNetworkProxyQuery_swap<()> for (&'a QNetworkProxyQuery) {
fn swap(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery4swapERS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN18QNetworkProxyQuery4swapERS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkProxyQuery::setPeerPort(int port);
impl /*struct*/ QNetworkProxyQuery {
pub fn setPeerPort<RetType, T: QNetworkProxyQuery_setPeerPort<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPeerPort(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_setPeerPort<RetType> {
fn setPeerPort(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: void QNetworkProxyQuery::setPeerPort(int port);
impl<'a> /*trait*/ QNetworkProxyQuery_setPeerPort<()> for (i32) {
fn setPeerPort(self , rsthis: & QNetworkProxyQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQuery11setPeerPortEi()};
let arg0 = self as c_int;
unsafe {_ZN18QNetworkProxyQuery11setPeerPortEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QNetworkConfiguration QNetworkProxyQuery::networkConfiguration();
impl /*struct*/ QNetworkProxyQuery {
pub fn networkConfiguration<RetType, T: QNetworkProxyQuery_networkConfiguration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.networkConfiguration(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_networkConfiguration<RetType> {
fn networkConfiguration(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: QNetworkConfiguration QNetworkProxyQuery::networkConfiguration();
impl<'a> /*trait*/ QNetworkProxyQuery_networkConfiguration<QNetworkConfiguration> for () {
fn networkConfiguration(self , rsthis: & QNetworkProxyQuery) -> QNetworkConfiguration {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QNetworkProxyQuery20networkConfigurationEv()};
let mut ret = unsafe {_ZNK18QNetworkProxyQuery20networkConfigurationEv(rsthis.qclsinst)};
let mut ret1 = QNetworkConfiguration::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QNetworkProxyQuery::peerHostName();
impl /*struct*/ QNetworkProxyQuery {
pub fn peerHostName<RetType, T: QNetworkProxyQuery_peerHostName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.peerHostName(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_peerHostName<RetType> {
fn peerHostName(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: QString QNetworkProxyQuery::peerHostName();
impl<'a> /*trait*/ QNetworkProxyQuery_peerHostName<QString> for () {
fn peerHostName(self , rsthis: & QNetworkProxyQuery) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QNetworkProxyQuery12peerHostNameEv()};
let mut ret = unsafe {_ZNK18QNetworkProxyQuery12peerHostNameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QNetworkProxyQuery::protocolTag();
impl /*struct*/ QNetworkProxyQuery {
pub fn protocolTag<RetType, T: QNetworkProxyQuery_protocolTag<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.protocolTag(self);
// return 1;
}
}
pub trait QNetworkProxyQuery_protocolTag<RetType> {
fn protocolTag(self , rsthis: & QNetworkProxyQuery) -> RetType;
}
// proto: QString QNetworkProxyQuery::protocolTag();
impl<'a> /*trait*/ QNetworkProxyQuery_protocolTag<QString> for () {
fn protocolTag(self , rsthis: & QNetworkProxyQuery) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QNetworkProxyQuery11protocolTagEv()};
let mut ret = unsafe {_ZNK18QNetworkProxyQuery11protocolTagEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkProxyQuery::QNetworkProxyQuery();
impl<'a> /*trait*/ QNetworkProxyQuery_new for () {
fn new(self) -> QNetworkProxyQuery {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QNetworkProxyQueryC2Ev()};
let ctysz: c_int = unsafe{QNetworkProxyQuery_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN18QNetworkProxyQueryC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkProxyQuery{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
use crate::ir::eval::prelude::*;
impl IrEval for ir::IrDecl {
type Output = IrValue;
fn eval(
&self,
interp: &mut IrInterpreter<'_>,
used: Used,
) -> Result<Self::Output, IrEvalOutcome> {
interp.budget.take(self)?;
let value = self.value.eval(interp, used)?;
interp.scopes.decl(&self.name, value, self)?;
Ok(IrValue::Unit)
}
}
|
#[path = "with_function/with_arity_zero.rs"]
pub mod with_arity_zero;
test_stdout!(
without_arity_zero_returns_pid_to_parent_and_child_process_exits_badarity,
"badarity\n"
);
|
pub mod helpers;
|
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;
use serde::de::{self, Deserialize, Deserializer, Visitor};
use serde::ser::{Serialize, Serializer};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
InvalidFormat,
MissingOs,
UnknownArch(UnknownArch),
UnknownOs(UnknownOs),
}
impl Display for ParseError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
ParseError::InvalidFormat => write!(fmt, "invalid target triple"),
ParseError::MissingOs => write!(fmt, "missing OS and vendor"),
ParseError::UnknownArch(ref e) => write!(fmt, "{}", e),
ParseError::UnknownOs(ref e) => write!(fmt, "{}", e),
}
}
}
impl Error for ParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match *self {
ParseError::UnknownArch(ref e) => Some(e),
ParseError::UnknownOs(ref e) => Some(e),
_ => None,
}
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Platform {
pub target_arch: Arch,
pub target_os: Os,
}
impl Display for Platform {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
write!(fmt, "{}-{}", self.target_arch, self.target_os)
}
}
impl FromStr for Platform {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut tokens = s.trim().splitn(2, '-');
let target_arch: Arch = tokens
.next()
.ok_or(ParseError::InvalidFormat)
.and_then(|arch| arch.parse().map_err(ParseError::UnknownArch))?;
let target_os: Os = tokens
.next()
.ok_or(ParseError::MissingOs)
.and_then(|os| os.parse().map_err(ParseError::UnknownOs))?;
if tokens.count() != 0 {
return Err(ParseError::InvalidFormat);
}
Ok(Platform {
target_arch,
target_os,
})
}
}
impl<'de> Deserialize<'de> for Platform {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct PlatformVisitor;
impl<'de> Visitor<'de> for PlatformVisitor {
type Value = Platform;
fn expecting(&self, fmt: &mut Formatter) -> FmtResult {
fmt.write_str("a target triple, e.g. x86_64-unknown-linux")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Platform::from_str(value).map_err(|err| E::custom(err.to_string()))
}
}
deserializer.deserialize_str(PlatformVisitor)
}
}
impl Serialize for Platform {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnknownArch(String);
impl Display for UnknownArch {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
write!(fmt, "unknown CPU architecture `{}`", self.0)
}
}
impl Error for UnknownArch {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Arch {
I686,
X86_64,
}
impl Display for Arch {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
Arch::I686 => write!(fmt, "i686"),
Arch::X86_64 => write!(fmt, "x86_64"),
}
}
}
impl FromStr for Arch {
type Err = UnknownArch;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"i686" => Ok(Arch::I686),
"x86_64" => Ok(Arch::X86_64),
s => Err(UnknownArch(s.to_string())),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnknownOs(String);
impl Display for UnknownOs {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
write!(fmt, "unknown operating system `{}`", self.0)
}
}
impl Error for UnknownOs {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Os {
Darwin,
FreeBsd,
Linux,
NetBsd,
Windows,
}
impl Display for Os {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
Os::Darwin => write!(fmt, "apple-darwin"),
Os::FreeBsd => write!(fmt, "unknown-freebsd"),
Os::Linux => write!(fmt, "unknown-linux"),
Os::NetBsd => write!(fmt, "unknown-netbsd"),
Os::Windows => write!(fmt, "pc-windows"),
}
}
}
impl FromStr for Os {
type Err = UnknownOs;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"apple-darwin" => Ok(Os::Darwin),
"unknown-freebsd" => Ok(Os::FreeBsd),
"unknown-linux" => Ok(Os::Linux),
"unknown-netbsd" => Ok(Os::NetBsd),
"pc-windows" => Ok(Os::Windows),
s => Err(UnknownOs(s.to_string())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Platform>();
}
#[test]
fn parse_common_triples() {
let actual = "x86_64-unknown-linux".parse();
let expected = Ok(Platform {
target_arch: Arch::X86_64,
target_os: Os::Linux,
});
assert_eq!(actual, expected);
let actual = "x86_64-pc-windows".parse();
let expected = Ok(Platform {
target_arch: Arch::X86_64,
target_os: Os::Windows,
});
assert_eq!(actual, expected);
let actual = "x86_64-apple-darwin".parse();
let expected = Ok(Platform {
target_arch: Arch::X86_64,
target_os: Os::Darwin,
});
assert_eq!(actual, expected);
}
#[test]
fn reject_invalid_triples() {
let result = "i686- unknown-freebsd".parse::<Platform>();
assert!(result.is_err());
let result = "i686 -unknown-freebsd".parse::<Platform>();
assert!(result.is_err());
let result = "pc-windows-x86_64".parse::<Platform>();
assert!(result.is_err());
}
#[test]
fn tolerate_leading_trailing_spaces() {
let expected = Ok(Platform {
target_arch: Arch::X86_64,
target_os: Os::Linux,
});
let actual = "x86_64-unknown-linux ".parse();
assert_eq!(actual, expected);
let actual = " x86_64-unknown-linux".parse();
assert_eq!(actual, expected);
let actual = " x86_64-unknown-linux ".parse();
assert_eq!(actual, expected);
}
#[test]
fn parse_roundtrip() {
let original: Platform = "x86_64-unknown-linux"
.parse()
.expect("Failed to parse triple!");
let text_form = original.to_string();
let parsed: Platform = text_form
.parse()
.expect("Failed to parse triple from text!");
assert_eq!(original, parsed);
}
}
|
#[doc = "Reader of register RIS"]
pub type R = crate::R<u32, super::RIS>;
#[doc = "Reader of field `WDTRIS`"]
pub type WDTRIS_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Watchdog Raw Interrupt Status"]
#[inline(always)]
pub fn wdtris(&self) -> WDTRIS_R {
WDTRIS_R::new((self.bits & 0x01) != 0)
}
}
|
use crate::{
core::{
cppstd::CppString,
error::Error,
frame_buffer::FrameBufferRef,
header::{Header, HeaderRef},
preview_image::PreviewRgba,
Compression, LevelMode, LevelRoundingMode, LineOrder,
},
rgba::rgba::{Rgba, RgbaChannels},
};
use imath_traits::{Bound2, Vec2};
use openexr_sys as sys;
use std::ffi::CString;
use std::path::Path;
type Result<T, E = Error> = std::result::Result<T, E>;
/// A simplified interface for writing a tiled RGBA EXR file
/// ```no_run
/// use openexr::prelude::*;
///
/// # use imath_traits::Zero;
/// # let pixels = vec![Rgba::zero(); 64*64];
/// # let width = 64;
/// # let height = 64;
/// let header = Header::from_dimensions(width, height);
/// let mut file = TiledRgbaOutputFile::new(
/// "write_tiled_rgba1.exr",
/// &header,
/// RgbaChannels::WriteRgba,
/// 64,
/// 64,
/// LevelMode::OneLevel,
/// LevelRoundingMode::RoundDown,
/// 1,
/// )
/// .unwrap();
/// file.set_frame_buffer(&pixels, 1, width as usize).unwrap();
/// file.write_tiles(
/// 0,
/// file.num_x_tiles(0).unwrap() - 1,
/// 0,
/// file.num_y_tiles(0).unwrap() - 1,
/// 0,
/// 0,
/// )
/// .unwrap();
/// ```
///
#[repr(transparent)]
pub struct TiledRgbaOutputFile(pub(crate) *mut sys::Imf_TiledRgbaOutputFile_t);
impl TiledRgbaOutputFile {
/// Create a new [`TiledRgbaOutputFile`] with the given header and parameters.
///
/// # Arguments
/// * `filename` - The path to which the resulting file will be written
/// * `header` - Reference to a [`Header`]
/// * `channels` - Which channels the pixel data will contain (overwrites the value in
/// `header`)
/// * `tile_x_size` - The size of the tiles in the x axis (overwrites the value in `header`)
/// * `tile_y_size` - The size of the tiles in the y axis (overwrites the value in `header`)
/// * `mode` - The level mode (overwrites the value in `header`)
/// * `rounding_mode` - The level rounding mode (overwrites the value in `header`)
/// * `num_threads` - The number of threads to use to write the image
///
/// ## Errors
/// * [`Error::Base`] - If an error occurs
///
#[allow(clippy::too_many_arguments)]
pub fn new<P: AsRef<Path>>(
filename: P,
header: &Header,
channels: RgbaChannels,
tile_x_size: i32,
tile_y_size: i32,
mode: LevelMode,
rounding_mode: LevelRoundingMode,
num_threads: i32,
) -> Result<TiledRgbaOutputFile> {
let c_filename = CString::new(
filename
.as_ref()
.to_str()
.expect("Invalid bytes in filename"),
)
.expect("Internal null bytes in filename");
let mut _inner = std::ptr::null_mut();
unsafe {
sys::Imf_TiledRgbaOutputFile_ctor(
&mut _inner,
c_filename.as_ptr(),
header.0.as_ref(),
channels.into(),
tile_x_size,
tile_y_size,
mode.into(),
rounding_mode.into(),
num_threads,
)
.into_result()?;
}
Ok(TiledRgbaOutputFile(_inner))
}
/// Create a new [`TiledRgbaOutputFile`] with the given parameters.
///
/// Display window and data window will both be set to [0, width) and
/// [0, height).
///
/// # Arguments
/// * `filename` - The path to which the resulting file will be written
/// * `width` - The width of the image.
/// * `height` - The height of the image.
/// * `channels` - Which channels the pixel data will contain.
/// * `pixel_aspect_ratio` - The width/height ratio of each pixel
/// * `screen_window_center` - Center of the screen window.
/// * `screen_window_width` - Width of the screen window.
/// * `line_order` - Whether the scanlines are stored top-to-bottom.
/// * `compression` - Which compression scheme to use
/// * `num_threads` - The number of threads to use to write the image
///
/// ## Errors
/// * [`Error::Base`] - If an error occurs
///
#[allow(clippy::too_many_arguments)]
pub fn with_dimensions<P: AsRef<Path>, V>(
filename: P,
width: i32,
height: i32,
channels: RgbaChannels,
tile_x_size: i32,
tile_y_size: i32,
mode: LevelMode,
rounding_mode: LevelRoundingMode,
pixel_aspect_ratio: f32,
screen_window_center: V,
screen_window_width: f32,
line_order: LineOrder,
compression: Compression,
num_threads: i32,
) -> Result<TiledRgbaOutputFile>
where
V: Vec2<f32>,
{
let c_filename = CString::new(
filename
.as_ref()
.to_str()
.expect("Invalid bytes in filename"),
)
.expect("Internal null bytes in filename");
let s = sys::Imath_V2f_t {
x: screen_window_center.as_slice()[0],
y: screen_window_center.as_slice()[1],
};
let mut _inner = std::ptr::null_mut();
unsafe {
sys::Imf_TiledRgbaOutputFile_with_dimensions(
&mut _inner,
c_filename.as_ptr(),
width,
height,
tile_x_size,
tile_y_size,
mode.into(),
rounding_mode.into(),
channels.into(),
pixel_aspect_ratio,
s,
screen_window_width,
line_order.into(),
compression.into(),
num_threads,
)
.into_result()?;
}
Ok(TiledRgbaOutputFile(_inner))
}
/// Define a frame buffer as the pixel data source.
///
/// Pixel (x, y) is at offset x * x_stride + y * y_stride
///
/// ## Errors
/// * [`Error::Base`] - If an error occurs
///
pub fn set_frame_buffer(
&mut self,
data: &[Rgba],
x_stride: usize,
y_stride: usize,
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaOutputFile_setFrameBuffer(
self.0,
data.as_ptr() as *const sys::Imf_Rgba_t,
x_stride as u64,
y_stride as u64,
)
.into_result()?;
}
Ok(())
}
/// Access to the file [`Header`]
///
pub fn header(&self) -> HeaderRef {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_TiledRgbaOutputFile_header(self.0, &mut ptr);
if ptr.is_null() {
panic!("Received null ptr from sys::Imf_TiledRgbaOutputFile_header");
}
HeaderRef::new(ptr)
}
}
/// Get the [`FrameBuffer`](crate::core::frame_buffer::FrameBuffer)
///
pub fn frame_buffer(&self) -> FrameBufferRef {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_TiledRgbaOutputFile_frameBuffer(self.0, &mut ptr);
if ptr.is_null() {
panic!("Received null ptr from sys::Imf_TiledRgbaOutputFile_frameBuffer");
}
FrameBufferRef::new(ptr)
}
}
/// Get the tiles' x dimension
///
pub fn tile_x_size(&self) -> u32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_tileXSize(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaOutputFile_tileXSize");
}
v
}
/// Get the tiles' y dimension
///
pub fn tile_y_size(&self) -> u32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_tileYSize(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaOutputFile_tileYSize");
}
v
}
/// Get the level mode
///
pub fn level_mode(&self) -> LevelMode {
let mut v = sys::Imf_LevelMode(0);
unsafe {
sys::Imf_TiledRgbaOutputFile_levelMode(
self.0,
&mut v,
)
.into_result()
.expect(
"Unexpected exception from Imf_TiledRgbaOutputFile_levelMode",
);
}
v.into()
}
/// Get the level rounding mode
///
pub fn level_rounding_mode(&self) -> LevelRoundingMode {
let mut v = sys::Imf_LevelRoundingMode(0);
unsafe {
sys::Imf_TiledRgbaOutputFile_levelRoundingMode(
self.0,
&mut v,
)
.into_result()
.expect(
"Unexpected exception from Imf_TiledRgbaOutputFile_levelRoundingMode",
);
}
v.into()
}
/// Get the number of levels in the file
///
/// # Returns
/// * `Ok(1)` if [`level_mode()`](TiledRgbaOutputFile::level_mode()) == [`LevelMode::OneLevel`]
/// * `Ok(rfunc (log (max (w, h)) / log (2)) + 1)` if [`level_mode()`](TiledRgbaOutputFile::level_mode()) == [`LevelMode::MipmapLevels`]
/// * `Err(Error::LogicError)` if [`level_mode()`](TiledRgbaOutputFile::level_mode()) == [`LevelMode::RipmapLevels`]
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaOutputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
pub fn num_levels(&self) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_numLevels(self.0, &mut v)
.into_result()?;
}
Ok(v)
}
/// Get the number of levels in the file in the x axis
///
/// # Returns
/// * `1` if [`level_mode()`](TiledRgbaOutputFile::level_mode) == [`LevelMode::OneLevel`]
/// * `rfunc (log (max (w, h)) / log (2)) + 1` if [`level_mode()`](TiledRgbaOutputFile::level_mode) == [`LevelMode::MipmapLevels`]
/// * `rfunc (log (w) / log (2)) + 1` if [`level_mode()`](TiledRgbaOutputFile::level_mode) == [`LevelMode::RipmapLevels`]
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaOutputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
pub fn num_x_levels(&self) -> i32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_numXLevels(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaOutputFile_numXLevels");
}
v
}
/// Get the number of levels in the file in the y axis
///
/// # Returns
/// * `1` if [`level_mode()`](TiledRgbaOutputFile::level_mode) == [`LevelMode::OneLevel`]
/// * `rfunc (log (max (w, h)) / log (2)) + 1` if [`level_mode()`](TiledRgbaOutputFile::level_mode)`TiledRgbaOutputFile::mode()`] == [`LevelMode::MipmapLevels`]
/// * `rfunc (log (h) / log (2)) + 1` if [`level_mode()`](TiledRgbaOutputFile::level_mode) == [`LevelMode::RipmapLevels`]
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaOutputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
pub fn num_y_levels(&self) -> i32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_numYLevels(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaOutputFile_numYLevels");
}
v
}
/// Returns `true` if the file contains a level with level number `(lx, ly)`, `false`
/// otherwise.
///
pub fn is_valid_level(&self, lx: i32, ly: i32) -> bool {
let mut v = false;
unsafe {
sys::Imf_TiledRgbaOutputFile_isValidLevel(self.0, &mut v, lx, ly).into_result().expect("Unexpected exception from Imf_TiledRgbaOutputFile_isValidLevel");
}
v
}
/// Returns the width of the level with level number `(lx, *)`, where `*` is any number.
///
/// # Returns
/// * `max (1, rfunc (w / pow (2, lx)))`
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaOutputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
/// # Errors
/// *[`Error::Base`] - If any error occurs
///
pub fn level_width(&self, lx: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_levelWidth(self.0, &mut v, lx)
.into_result()?;
}
Ok(v)
}
/// Returns the height of the level with level number `(*, ly)`, where `*` is any number.
///
/// # Returns
/// * `max (1, rfunc (h / pow (2, ly)))`
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaOutputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
/// # Errors
/// *[`Error::Base`] - If any error occurs
///
pub fn level_height(&self, ly: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_levelHeight(self.0, &mut v, ly)
.into_result()?;
}
Ok(v)
}
/// Get the number of tiles in the x axis that cover a level with level number `(lx, *)`
/// where `*` is any number
///
/// # Returns
/// *(level_width(lx) + tile_x_size() - 1) / tile_x_size()
///
/// # Errors
/// *[`Error::InvalidArgument`] - If `lx` is not a valid level
///
pub fn num_x_tiles(&self, lx: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_numXTiles(self.0, &mut v, lx)
.into_result()?;
}
Ok(v)
}
/// Get the number of tiles in the y axis that cover a level with level number `(*, ly)`
/// where `*` is any number
///
/// # Returns
/// * (level_height(ly) + tile_y_size() - 1) / tile_y_size()
///
/// # Errors
/// *[`Error::InvalidArgument`] - If `lx` is not a valid level
///
pub fn num_y_tiles(&self, ly: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaOutputFile_numYTiles(self.0, &mut v, ly)
.into_result()?;
}
Ok(v)
}
/// Returns a 2-dimensional region of valid pixel coordinates for a level with level number `(lx, ly)`
///
/// # Errors
/// *[`Error::Base`] - if any error occurs
///
pub fn data_window_for_level<B: Bound2<i32>>(
&self,
lx: i32,
ly: i32,
) -> Result<B> {
let mut dw = [0i32; 4];
unsafe {
sys::Imf_TiledRgbaOutputFile_dataWindowForLevel(
self.0,
dw.as_mut_ptr() as *mut sys::Imath_Box2i_t,
lx,
ly,
)
.into_result()?
}
Ok(B::from_slice(&dw))
}
/// Returns a 2-dimensional region of valid pixel coordinates for a level with tile coordinates `(dx, dy)` and level number `(lx, ly)`
///
/// # Errors
/// * [`Error::InvalidArgument`] - if the passed tile coordinates are invalid
/// * [`Error::Base`] - if any other error occurs
///
pub fn data_window_for_tile<B: Bound2<i32>>(
&self,
dx: i32,
dy: i32,
lx: i32,
ly: i32,
) -> Result<B> {
let mut dw = [0i32; 4];
unsafe {
sys::Imf_TiledRgbaOutputFile_dataWindowForTile(
self.0,
dw.as_mut_ptr() as *mut sys::Imath_Box2i_t,
dx,
dy,
lx,
ly,
)
.into_result()?
}
Ok(B::from_slice(&dw))
}
/// Writes the tile with tile
/// coordinates (dx, dy), and level number (lx, ly) to
/// the file.
///
/// # Errors
/// * [`Error::InvalidArgument`] if dx does not lie in the interval [0, numXTiles(lx) - 1]
/// * [`Error::InvalidArgument`] if dy does not lie in the interval [0, numYTiles(ly) - 1]
///
/// * [`Error::InvalidArgument`] if lx does not lie in the interval [0, numXLevels() - 1]
/// * [`Error::InvalidArgument`] if ly does not lie in the inverval [0, numYLevels() - 1]
/// * [`Error::Base`] if any other error occurs
///
///
/// Pixels that are outside the pixel coordinate range for the tile's
/// level, are never accessed by writeTile().
///
/// Each tile in the file must be written exactly once.
///
/// The file's line order attribute determines the order of the tiles
/// in the file:
///
/// ## [`LineOrder::IncreasingY`]
/// In the file, the tiles for each level are stored
/// in a contiguous block. The levels are ordered
/// like this:
/// ```c
/// (0, 0) (1, 0) ... (nx-1, 0)
/// (0, 1) (1, 1) ... (nx-1, 1)
/// ...
/// (0,ny-1) (1,ny-1) ... (nx-1,ny-1)
/// ```
///
/// where nx = [`num_x_levels()`](TiledRgbaOutputFile::num_x_levels), and ny = [`num_y_levels()`](TiledRgbaOutputFile::num_y_levels).
///
/// In an individual level, `(lx, ly)`, the tiles
/// are stored in the following order:
///
/// ```c
/// (0, 0) (1, 0) ... (tx-1, 0)
/// (0, 1) (1, 1) ... (tx-1, 1)
/// ...
/// (0,ty-1) (1,ty-1) ... (tx-1,ty-1)
/// ```
///
/// where tx = [`num_x_tiles(lx)`](TiledRgbaOutputFile::num_x_tiles),
/// and ty = [`num_y_tiles(ly)`](TiledRgbaOutputFile::num_y_tiles).
///
/// ## [`LineOrder::DecreasingY`]
/// As for [`LineOrder::IncreasingY`], the tiles
/// for each level are stored in a contiguous block. The levels
/// are ordered the same way as for [`LineOrder::IncreasingY`],
/// but within an individual level, the tiles
/// are stored in this order:
///
/// ```c
/// (0,ty-1) (1,ty-1) ... (tx-1,ty-1)
/// ...
/// (0, 1) (1, 1) ... (tx-1, 1)
/// (0, 0) (1, 0) ... (tx-1, 0)
/// ```
///
///
/// ## [`LineOrder::RandomY`]
/// The order of the calls to `write_tile()` determines
/// the order of the tiles in the file.
///
pub fn write_tile(
&mut self,
dx: i32,
dy: i32,
lx: i32,
ly: i32,
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaOutputFile_writeTile(self.0, dx, dy, lx, ly)
.into_result()?;
}
Ok(())
}
/// Writes multiple tiles at once.
///
/// If multi-threading is used multiple tiles are written concurrently.
/// The tile coordinates, dx1, dx2 and dy1, dy2, specify inclusive ranges of tile
/// coordinates. It is valid for dx1 < dx2 or dy1 < dy2; the
/// tiles are always written in the order specified by the line
/// order attribute. Hence, it is not possible to specify an
/// "invalid" or empty tile range.
///
/// Pixels that are outside the pixel coordinate range for the tile's
/// level, are never accessed by writeTile().
///
/// Each tile in the file must be written exactly once.
///
/// The file's line order attribute determines the order of the tiles
/// in the file:
///
/// ## [`LineOrder::IncreasingY`]
/// In the file, the tiles for each level are stored
/// in a contiguous block. The levels are ordered
/// like this:
/// ```c
/// (0, 0) (1, 0) ... (nx-1, 0)
/// (0, 1) (1, 1) ... (nx-1, 1)
/// ...
/// (0,ny-1) (1,ny-1) ... (nx-1,ny-1)
/// ```
///
/// where nx = [`num_x_levels()`](TiledRgbaOutputFile::num_x_levels), and ny = [`num_y_levels()`](TiledRgbaOutputFile::num_y_levels).
///
/// In an individual level, `(lx, ly)`, the tiles
/// are stored in the following order:
///
/// ```c
/// (0, 0) (1, 0) ... (tx-1, 0)
/// (0, 1) (1, 1) ... (tx-1, 1)
/// ...
/// (0,ty-1) (1,ty-1) ... (tx-1,ty-1)
/// ```
///
/// where tx = [`num_x_tiles(lx)`](TiledRgbaOutputFile::num_x_tiles),
/// and ty = [`num_y_tiles(ly)`](TiledRgbaOutputFile::num_y_tiles).
///
/// ## [`LineOrder::DecreasingY`]
/// As for [`LineOrder::IncreasingY`], the tiles
/// for each level are stored in a contiguous block. The levels
/// are ordered the same way as for [`LineOrder::IncreasingY`],
/// but within an individual level, the tiles
/// are stored in this order:
///
/// ```c
/// (0,ty-1) (1,ty-1) ... (tx-1,ty-1)
/// ...
/// (0, 1) (1, 1) ... (tx-1, 1)
/// (0, 0) (1, 0) ... (tx-1, 0)
/// ```
///
///
/// ## [`LineOrder::RandomY`]
/// The order of the calls to `write_tile()` determines
/// the order of the tiles in the file.
///
pub fn write_tiles(
&mut self,
dx1: i32,
dx2: i32,
dy1: i32,
dy2: i32,
lx: i32,
ly: i32,
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaOutputFile_writeTiles(
self.0, dx1, dx2, dy1, dy2, lx, ly,
)
.into_result()?;
}
Ok(())
}
/// Supplies a new set of pixels for the preview image attribute in the file's header
///
/// Note: update_preview_image() is necessary because images are
/// often stored in a file incrementally, a few tiles at a time,
/// while the image is being generated. Since the preview image
/// is an attribute in the file's header, it gets stored in the
/// file as soon as the file is opened, but we may not know what
/// the preview image should look like until we have written the
/// last tile of the main image.
///
/// # Errors
/// * [`Error::LogicError`] - If the image header does not contain a preview image
/// * [`Error::Base`] - If any other error occurs
///
pub fn update_preview_image(
&mut self,
new_pixels: &[PreviewRgba],
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaOutputFile_updatePreviewImage(
self.0,
new_pixels.as_ptr() as *const sys::Imf_PreviewRgba_t,
)
.into_result()?;
}
Ok(())
}
}
impl Drop for TiledRgbaOutputFile {
fn drop(&mut self) {
unsafe {
sys::Imf_TiledRgbaOutputFile_dtor(self.0)
.into_result()
.expect("Unexpected exception in Imf_TiledRgbaOutputFile_dtor");
}
}
}
/// A simplified interface for reading a tiled RGBA EXR file
/// ```no_run
/// # use std::path::PathBuf;
/// # let path = PathBuf::from(
/// # std::env::var("CARGO_MANIFEST_DIR")
/// # .expect("CARGO_MANIFEST_DIR not set"),
/// # )
/// # .join("images")
/// # .join("ferris-tiled.exr");
///
/// use imath_traits::Zero;
/// use openexr::prelude::*;
///
/// let mut file = TiledRgbaInputFile::new(&path, 1).unwrap();
/// let data_window = file.header().data_window::<[i32; 4]>().clone();
/// let width = data_window[2] - data_window[0] + 1;
/// let height = data_window[3] - data_window[1] + 1;
///
/// let mut pixels = vec![Rgba::zero(); (width * height) as usize];
/// file.set_frame_buffer(&mut pixels, 1, width as usize)
/// .unwrap();
/// file.read_tiles(
/// 0,
/// file.num_x_tiles(0).unwrap() - 1,
/// 0,
/// file.num_y_tiles(0).unwrap() - 1,
/// 0,
/// 0,
/// )
/// .unwrap();
/// ```
///
#[repr(transparent)]
pub struct TiledRgbaInputFile(pub(crate) *mut sys::Imf_TiledRgbaInputFile_t);
impl TiledRgbaInputFile {
/// Opens the file at `filename` and reads the header.
///
/// # Errors
/// * [`Error::Base`] - If any error occurs
///
pub fn new<P: AsRef<Path>>(
filename: P,
num_threads: i32,
) -> Result<TiledRgbaInputFile> {
let c_filename = CString::new(
filename
.as_ref()
.to_str()
.expect("Invalid bytes in filename"),
)
.expect("Internal null bytes in filename");
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_TiledRgbaInputFile_ctor(
&mut inner,
c_filename.as_ptr(),
num_threads,
)
.into_result()?;
}
Ok(TiledRgbaInputFile(inner))
}
/// Opens the file at `filename`, reads the header and prepares to read
/// layer `layer_name` from the file.
///
/// # Errors
/// * [`Error::Base`] - If any error occurs
///
pub fn with_layer<P: AsRef<Path>>(
filename: P,
layer_name: &str,
num_threads: i32,
) -> Result<TiledRgbaInputFile> {
let c_filename = CString::new(
filename
.as_ref()
.to_str()
.expect("Invalid bytes in filename"),
)
.expect("Internal null bytes in filename");
let s_layer_name = CppString::new(layer_name);
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_TiledRgbaInputFile_with_layer(
&mut inner,
c_filename.as_ptr(),
s_layer_name.0,
num_threads,
)
.into_result()?;
}
Ok(TiledRgbaInputFile(inner))
}
/// Set a frame buffer as the destination for the decoded pixels
///
/// Pixel (x, y) is at offset x * x_stride + y * y_stride
///
/// ## Errors
/// * [`Error::Base`] - If any error occurs
///
pub fn set_frame_buffer(
&mut self,
pixels: &mut [Rgba],
x_stride: usize,
y_stride: usize,
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaInputFile_setFrameBuffer(
self.0,
pixels.as_mut_ptr() as *mut Rgba as *mut sys::Imf_Rgba_t,
x_stride as u64,
y_stride as u64,
)
.into_result()?;
}
Ok(())
}
/// Switch to a different layer for reading.
///
/// Subsequent calls to `read_tile()` and `read_tiles()` will read channels layer_name.R, layer_name.G, etc.
/// After each call to `set_layer_name()`, `set_frame_buffer()` must be called
/// at least once before the next call to `read_tile()` or `read_tiles()`.
///
pub fn set_layer_name(&mut self, layer_name: &str) {
let s_layer_name = CppString::new(layer_name);
unsafe {
sys::Imf_TiledRgbaInputFile_setLayerName(self.0, s_layer_name.0).into_result().expect("Unexpected exception from Imf_TiledRgbaInputFile_setLayerName");
}
}
/// Access to the file [`Header`]
///
pub fn header(&self) -> HeaderRef {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_TiledRgbaInputFile_header(self.0, &mut ptr);
if ptr.is_null() {
panic!(
"Received null ptr from sys::Imf_TiledRgbaInputFile_header"
);
}
HeaderRef::new(ptr)
}
}
/// Get the [`FrameBuffer`](crate::core::frame_buffer::FrameBuffer)
///
pub fn frame_buffer(&self) -> FrameBufferRef {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_TiledRgbaInputFile_frameBuffer(self.0, &mut ptr);
if ptr.is_null() {
panic!("Received null ptr from sys::Imf_TiledRgbaInputFile_frameBuffer");
}
FrameBufferRef::new(ptr)
}
}
/// Get the tiles' x dimension
///
pub fn tile_x_size(&self) -> u32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_tileXSize(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaInputFile_tileXSize");
}
v
}
/// Get the tiles' y dimension
///
pub fn tile_y_size(&self) -> u32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_tileYSize(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaInputFile_tileYSize");
}
v
}
/// Get the level mode
///
pub fn level_mode(&self) -> LevelMode {
let mut v = sys::Imf_LevelMode(0);
unsafe {
sys::Imf_TiledRgbaInputFile_levelMode(
self.0,
&mut v,
)
.into_result()
.expect(
"Unexpected exception from Imf_TiledRgbaInputFile_levelMode",
);
}
v.into()
}
/// Get the level rounding mode
///
pub fn level_rounding_mode(&self) -> LevelRoundingMode {
let mut v = sys::Imf_LevelRoundingMode(0);
unsafe {
sys::Imf_TiledRgbaInputFile_levelRoundingMode(
self.0,
&mut v,
)
.into_result()
.expect(
"Unexpected exception from Imf_TiledRgbaInputFile_levelRoundingMode",
);
}
v.into()
}
/// Get the number of levels in the file
///
/// # Returns
/// * `Ok(1)` if [`level_mode()`](TiledRgbaInputFile::level_mode()) == [`LevelMode::OneLevel`]
/// * `Ok(rfunc (log (max (w, h)) / log (2)) + 1)` if [`level_mode()`](TiledRgbaInputFile::level_mode()) == [`LevelMode::MipmapLevels`]
/// * `Err(Error::LogicError)` if [`level_mode()`](TiledRgbaInputFile::level_mode()) == [`LevelMode::RipmapLevels`]
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaInputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
pub fn num_levels(&self) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_numLevels(self.0, &mut v)
.into_result()?;
}
Ok(v)
}
/// Get the number of levels in the file in the x axis
///
/// # Returns
/// * `1` if [`level_mode()`](TiledRgbaInputFile::level_mode) == [`LevelMode::OneLevel`]
/// * `rfunc (log (max (w, h)) / log (2)) + 1` if [`level_mode()`](TiledRgbaInputFile::level_mode) == [`LevelMode::MipmapLevels`]
/// * `rfunc (log (w) / log (2)) + 1` if [`level_mode()`](TiledRgbaInputFile::level_mode) == [`LevelMode::RipmapLevels`]
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaInputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
pub fn num_x_levels(&self) -> i32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_numXLevels(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaInputFile_numXLevels");
}
v
}
/// Get the number of levels in the file in the y axis
///
/// # Returns
/// * `1` if [`level_mode()`](TiledRgbaInputFile::level_mode) == [`LevelMode::OneLevel`]
/// * `rfunc (log (max (w, h)) / log (2)) + 1` if [`level_mode()`](TiledRgbaInputFile::level_mode)`TiledRgbaInputFile::mode()`] == [`LevelMode::MipmapLevels`]
/// * `rfunc (log (h) / log (2)) + 1` if [`level_mode()`](TiledRgbaInputFile::level_mode) == [`LevelMode::RipmapLevels`]
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaInputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
pub fn num_y_levels(&self) -> i32 {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_numYLevels(self.0, &mut v).into_result().expect("Unexpected exception from Imf_TiledRgbaInputFile_numYLevels");
}
v
}
/// Returns `true` if the file contains a level with level number `(lx, ly)`, `false`
/// otherwise.
///
pub fn is_valid_level(&self, lx: i32, ly: i32) -> bool {
let mut v = false;
unsafe {
sys::Imf_TiledRgbaInputFile_isValidLevel(self.0, &mut v, lx, ly).into_result().expect("Unexpected exception from Imf_TiledRgbaInputFile_isValidLevel");
}
v
}
/// Returns the width of the level with level number `(lx, *)`, where `*` is any number.
///
/// # Returns
/// * `max (1, rfunc (w / pow (2, lx)))`
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaInputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
/// # Errors
/// *[`Error::Base`] - If any error occurs
///
pub fn level_width(&self, lx: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_levelWidth(self.0, &mut v, lx)
.into_result()?;
}
Ok(v)
}
/// Returns the height of the level with level number `(*, ly)`, where `*` is any number.
///
/// # Returns
/// * `max (1, rfunc (h / pow (2, ly)))`
///
/// where `rfunc` is either `floor()` or `ceil()` depending on whether
/// [`level_rounding_mode()`](TiledRgbaInputFile::level_rounding_mode()) is [`LevelRoundingMode::RoundUp`] or [`LevelRoundingMode::RoundDown`]
///
/// # Errors
/// *[`Error::Base`] - If any error occurs
///
pub fn level_height(&self, ly: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_levelHeight(self.0, &mut v, ly)
.into_result()?;
}
Ok(v)
}
/// Get the number of tiles in the x axis that cover a level with level number `(lx, *)`
/// where `*` is any number
///
/// # Returns
/// *(level_width(lx) + tile_x_size() - 1) / tile_x_size()
///
/// # Errors
/// *[`Error::InvalidArgument`] - If `lx` is not a valid level
///
pub fn num_x_tiles(&self, lx: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_numXTiles(self.0, &mut v, lx)
.into_result()?;
}
Ok(v)
}
/// Get the number of tiles in the y axis that cover a level with level number `(*, ly)`
/// where `*` is any number
///
/// # Returns
/// * (level_height(ly) + tile_y_size() - 1) / tile_y_size()
///
/// # Errors
/// *[`Error::InvalidArgument`] - If `lx` is not a valid level
///
pub fn num_y_tiles(&self, ly: i32) -> Result<i32> {
let mut v = 0;
unsafe {
sys::Imf_TiledRgbaInputFile_numYTiles(self.0, &mut v, ly)
.into_result()?;
}
Ok(v)
}
/// Returns a 2-dimensional region of valid pixel coordinates for a level with level number `(lx, ly)`
///
/// # Errors
/// *[`Error::Base`] - if any error occurs
///
pub fn data_window_for_level<B: Bound2<i32>>(
&self,
lx: i32,
ly: i32,
) -> Result<B> {
let mut dw = [0i32; 4];
unsafe {
sys::Imf_TiledRgbaInputFile_dataWindowForLevel(
self.0,
dw.as_mut_ptr() as *mut sys::Imath_Box2i_t,
lx,
ly,
)
.into_result()?;
}
Ok(B::from_slice(&dw))
}
/// Returns a 2-dimensional region of valid pixel coordinates for a level with tile coordinates `(dx, dy)` and level number `(lx, ly)`
///
/// # Errors
/// * [`Error::InvalidArgument`] - if the passed tile coordinates are invalid
/// * [`Error::Base`] - if any other error occurs
///
pub fn data_window_for_tile<B: Bound2<i32>>(
&self,
dx: i32,
dy: i32,
lx: i32,
ly: i32,
) -> Result<B> {
let mut dw = [0i32; 4];
unsafe {
sys::Imf_TiledRgbaInputFile_dataWindowForTile(
self.0,
dw.as_mut_ptr() as *mut sys::Imath_Box2i_t,
dx,
dy,
lx,
ly,
)
.into_result()?;
}
Ok(B::from_slice(&dw))
}
/// Reads the tile with tile coordinates `(dx, dy)`, and level number `(lx, ly)`,
/// and stores it in the current frame buffer.
///
/// # Errors
/// * [`Error::InvalidArgument`] - if dx does not lie in the interval [0, num_x_tiles(lx)-1]
/// * [`Error::InvalidArgument`] - if dy does not lie in the interval [0, num_y_tiles(ly)-1]
///
/// * [`Error::InvalidArgument`] -if lx does not lie in the interval [0, num_x_levels()-1]
/// * [`Error::InvalidArgument`] -if ly does not lie in the inverval [0, num_y_levels()-1]
/// * [`Error::Base`] - if any other error occurs
///
pub fn read_tile(
&mut self,
dx: i32,
dy: i32,
lx: i32,
ly: i32,
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaInputFile_readTile(self.0, dx, dy, lx, ly)
.into_result()?;
}
Ok(())
}
/// Reads the tile range from with coordinates `(dx1, dy1)`, to `(dx2, dy2)` and level number `(lx, ly)`,
/// and stores it in the current frame buffer.
///
/// # Errors
/// * [`Error::InvalidArgument`] - if dx does not lie in the interval [0, num_x_tiles(lx)-1]
/// * [`Error::InvalidArgument`] - if dy does not lie in the interval [0, num_y_tiles(ly)-1]
///
/// * [`Error::InvalidArgument`] -if lx does not lie in the interval [0, num_x_levels()-1]
/// * [`Error::InvalidArgument`] -if ly does not lie in the inverval [0, num_y_levels()-1]
/// * [`Error::Base`] - if any other error occurs
///
pub fn read_tiles(
&mut self,
dx1: i32,
dx2: i32,
dy1: i32,
dy2: i32,
lx: i32,
ly: i32,
) -> Result<()> {
unsafe {
sys::Imf_TiledRgbaInputFile_readTiles(
self.0, dx1, dx2, dy1, dy2, lx, ly,
)
.into_result()?;
}
Ok(())
}
}
impl Drop for TiledRgbaInputFile {
fn drop(&mut self) {
unsafe {
sys::Imf_TiledRgbaInputFile_dtor(self.0)
.into_result()
.expect("Unexpected exception in Imf_TiledRgbaInputFile_dtor");
}
}
}
#[cfg(test)]
#[test]
fn test_write_tiled_rgba1() -> Result<(), Box<dyn std::error::Error>> {
let (pixels, width, height) = crate::tests::load_ferris();
let header = Header::from_dimensions(width, height);
let mut file = TiledRgbaOutputFile::new(
"write_tiled_rgba1.exr",
&header,
RgbaChannels::WriteRgba,
64,
64,
LevelMode::OneLevel,
LevelRoundingMode::RoundDown,
1,
)?;
file.set_frame_buffer(&pixels, 1, width as usize)?;
file.write_tiles(
0,
file.num_x_tiles(0)? - 1,
0,
file.num_y_tiles(0)? - 1,
0,
0,
)?;
Ok(())
}
#[cfg(test)]
#[test]
fn test_read_tiled_rgba1() -> Result<(), Box<dyn std::error::Error>> {
use crate::prelude::*;
use imath_traits::Zero;
use std::path::PathBuf;
let path = PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR")
.expect("CARGO_MANIFEST_DIR not set"),
)
.join("images")
.join("ferris-tiled.exr");
let mut file = TiledRgbaInputFile::new(&path, 1)?;
let data_window = file.header().data_window::<[i32; 4]>().clone();
let width = data_window[2] - data_window[0] + 1;
let height = data_window[3] - data_window[1] + 1;
let mut pixels = vec![Rgba::zero(); (width * height) as usize];
file.set_frame_buffer(&mut pixels, 1, width as usize)?;
file.read_tiles(
0,
file.num_x_tiles(0)? - 1,
0,
file.num_y_tiles(0)? - 1,
0,
0,
)?;
let mut ofile = RgbaOutputFile::with_dimensions(
"read_tiled_rgba1.exr",
width,
height,
RgbaChannels::WriteRgba,
1.0f32,
[0.0f32, 0.0f32],
1.0f32,
LineOrder::IncreasingY,
Compression::Piz,
1,
)?;
ofile.set_frame_buffer(&pixels, 1, width as usize)?;
ofile.write_pixels(height)?;
Ok(())
}
|
use std::sync::mpsc::Sender;
use std::sync::Arc;
use crate::state::AppState;
use maltebl_chess::{chess_game::ChessGame, piece_logic::Color};
use druid::*;
pub mod action {
use druid::Selector;
pub const MAKE_MOVE: Selector<String> = Selector::new("make_move");
pub const MAKE_MOVE_FROM_NET: Selector<String> = Selector::new("make_move_from_net");
}
pub struct Delegate {
pub game: ChessGame,
pub single_player: Option<Color>,
pub net_sender: Option<Sender<String>>,
}
impl Delegate {
fn attempt_move_from_ui(&mut self, command: &str) -> Result<String, String> {
if let Some(local_player) = self.single_player {
if local_player != self.game.current_player() {
return Err("not your (local player) turn".to_owned());
}
let sender = self
.net_sender
.as_ref()
.ok_or_else(|| "no net_sender".to_owned())?;
sender
.send(command.to_owned())
.map_err(|_| "unable to send".to_owned())?;
}
// TODO: + send move to network + only apply if ok
// for now: just assume everything went smooth
self.game.move_piece(command.to_owned())
}
// if err: send decline, if ok; pass along
fn attempt_move_from_network(&mut self, command: &str) -> Result<String, String> {
let local_player = self
.single_player
.ok_or_else(|| "single_player_white not set".to_owned())?;
if local_player == self.game.current_player() {
return Err("local players turn".to_owned());
}
// TODO: validate move + answer ok/decline + perform if ok
// for now: just assume everything went smooth
let sender = self
.net_sender
.as_ref()
.ok_or_else(|| "no net_sender".to_owned())?;
sender
.send("ok".to_owned())
.map_err(|_| "unable to send".to_owned())?;
self.game.move_piece(command.to_owned())
}
}
impl AppDelegate<AppState> for Delegate {
fn command(
&mut self,
_ctx: &mut DelegateCtx,
_target: Target,
cmd: &Command,
data: &mut AppState,
_env: &Env,
) -> bool {
if let Some(command) = cmd.get(action::MAKE_MOVE) {
data.message = Some(match self.attempt_move_from_ui(command) {
Err(txt) => txt,
Ok(txt) => txt,
});
data.board = Arc::new(self.game.get_board());
return true;
} else if let Some(command) = cmd.get(action::MAKE_MOVE_FROM_NET) {
data.message = Some(match self.attempt_move_from_network(command) {
Err(_txt) => "".to_owned(),
Ok(txt) => txt,
});
data.board = Arc::new(self.game.get_board());
return true;
}
true
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_ast::ast::format_statement;
use common_ast::ast::ExplainKind;
use common_ast::ast::Identifier;
use common_ast::ast::Statement;
use common_ast::parser::parse_sql;
use common_ast::parser::tokenize_sql;
use common_ast::Dialect;
use common_catalog::catalog::CatalogManager;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use common_expression::types::DataType;
use common_meta_app::principal::UserDefinedFunction;
use crate::normalize_identifier;
use crate::planner::udf_validator::UDFValidator;
use crate::plans::AlterUDFPlan;
use crate::plans::CallPlan;
use crate::plans::CreateFileFormatPlan;
use crate::plans::CreateRolePlan;
use crate::plans::CreateUDFPlan;
use crate::plans::DropFileFormatPlan;
use crate::plans::DropRolePlan;
use crate::plans::DropStagePlan;
use crate::plans::DropUDFPlan;
use crate::plans::DropUserPlan;
use crate::plans::Plan;
use crate::plans::RewriteKind;
use crate::plans::ShowFileFormatsPlan;
use crate::plans::ShowGrantsPlan;
use crate::plans::ShowRolesPlan;
use crate::plans::UseDatabasePlan;
use crate::BindContext;
use crate::ColumnBinding;
use crate::MetadataRef;
use crate::NameResolutionContext;
use crate::Visibility;
/// Binder is responsible to transform AST of a query into a canonical logical SExpr.
///
/// During this phase, it will:
/// - Resolve columns and tables with Catalog
/// - Check semantic of query
/// - Validate expressions
/// - Build `Metadata`
pub struct Binder {
pub ctx: Arc<dyn TableContext>,
pub catalogs: Arc<CatalogManager>,
pub name_resolution_ctx: NameResolutionContext,
pub metadata: MetadataRef,
}
impl<'a> Binder {
pub fn new(
ctx: Arc<dyn TableContext>,
catalogs: Arc<CatalogManager>,
name_resolution_ctx: NameResolutionContext,
metadata: MetadataRef,
) -> Self {
Binder {
ctx,
catalogs,
name_resolution_ctx,
metadata,
}
}
pub async fn bind(mut self, stmt: &Statement) -> Result<Plan> {
let mut init_bind_context = BindContext::new();
self.bind_statement(&mut init_bind_context, stmt).await
}
#[async_recursion::async_recursion]
pub(crate) async fn bind_statement(
&mut self,
bind_context: &mut BindContext,
stmt: &Statement,
) -> Result<Plan> {
let plan = match stmt {
Statement::Query(query) => {
let (s_expr, bind_context) = self.bind_query(bind_context, query).await?;
let formatted_ast = if self.ctx.get_settings().get_enable_query_result_cache()? {
Some(format_statement(stmt.clone())?)
} else {
None
};
Plan::Query {
s_expr: Box::new(s_expr),
metadata: self.metadata.clone(),
bind_context: Box::new(bind_context),
rewrite_kind: None,
ignore_result: query.ignore_result,
formatted_ast,
}
}
Statement::Explain { query, kind } => {
match kind {
ExplainKind::Ast(formatted_stmt) => Plan::ExplainAst { formatted_string: formatted_stmt.clone() },
ExplainKind::Syntax(formatted_sql) => Plan::ExplainSyntax { formatted_sql: formatted_sql.clone() },
_ => Plan::Explain { kind: kind.clone(), plan: Box::new(self.bind_statement(bind_context, query).await?) },
}
}
Statement::ExplainAnalyze { query } => {
let plan = self.bind_statement(bind_context, query).await?;
Plan::ExplainAnalyze { plan: Box::new(plan) }
}
Statement::ShowFunctions { limit } => {
self.bind_show_functions(bind_context, limit).await?
}
Statement::ShowTableFunctions { limit } => {
self.bind_show_table_functions(bind_context, limit).await?
}
Statement::Copy(stmt) => self.bind_copy(bind_context, stmt).await?,
Statement::ShowMetrics => {
self.bind_rewrite_to_query(
bind_context,
"SELECT metric, kind, labels, value FROM system.metrics",
RewriteKind::ShowMetrics,
)
.await?
}
Statement::ShowProcessList => {
self.bind_rewrite_to_query(bind_context, "SELECT * FROM system.processes", RewriteKind::ShowProcessList)
.await?
}
Statement::ShowEngines => {
self.bind_rewrite_to_query(bind_context, "SELECT \"Engine\", \"Comment\" FROM system.engines ORDER BY \"Engine\" ASC", RewriteKind::ShowEngines)
.await?
}
Statement::ShowSettings { like } => self.bind_show_settings(bind_context, like).await?,
// Catalogs
Statement::ShowCatalogs(stmt) => self.bind_show_catalogs(bind_context, stmt).await?,
Statement::ShowCreateCatalog(stmt) => self.bind_show_create_catalogs(stmt).await?,
Statement::CreateCatalog(stmt) => self.bind_create_catalog(stmt).await?,
Statement::DropCatalog(stmt) => self.bind_drop_catalog(stmt).await?,
// Databases
Statement::ShowDatabases(stmt) => self.bind_show_databases(bind_context, stmt).await?,
Statement::ShowCreateDatabase(stmt) => self.bind_show_create_database(stmt).await?,
Statement::CreateDatabase(stmt) => self.bind_create_database(stmt).await?,
Statement::DropDatabase(stmt) => self.bind_drop_database(stmt).await?,
Statement::UndropDatabase(stmt) => self.bind_undrop_database(stmt).await?,
Statement::AlterDatabase(stmt) => self.bind_alter_database(stmt).await?,
Statement::UseDatabase { database } => {
Plan::UseDatabase(Box::new(UseDatabasePlan {
database: database.name.clone(),
}))
}
// Columns
Statement::ShowColumns(stmt) => self.bind_show_columns(bind_context, stmt).await?,
// Tables
Statement::ShowTables(stmt) => self.bind_show_tables(bind_context, stmt).await?,
Statement::ShowCreateTable(stmt) => self.bind_show_create_table(stmt).await?,
Statement::DescribeTable(stmt) => self.bind_describe_table(stmt).await?,
Statement::ShowTablesStatus(stmt) => {
self.bind_show_tables_status(bind_context, stmt).await?
}
Statement::CreateTable(stmt) => self.bind_create_table(stmt).await?,
Statement::DropTable(stmt) => self.bind_drop_table(stmt).await?,
Statement::UndropTable(stmt) => self.bind_undrop_table(stmt).await?,
Statement::AlterTable(stmt) => self.bind_alter_table(bind_context, stmt).await?,
Statement::RenameTable(stmt) => self.bind_rename_table(stmt).await?,
Statement::TruncateTable(stmt) => self.bind_truncate_table(stmt).await?,
Statement::OptimizeTable(stmt) => self.bind_optimize_table(bind_context, stmt).await?,
Statement::AnalyzeTable(stmt) => self.bind_analyze_table(stmt).await?,
Statement::ExistsTable(stmt) => self.bind_exists_table(stmt).await?,
// Views
Statement::CreateView(stmt) => self.bind_create_view(stmt).await?,
Statement::AlterView(stmt) => self.bind_alter_view(stmt).await?,
Statement::DropView(stmt) => self.bind_drop_view(stmt).await?,
// Users
Statement::CreateUser(stmt) => self.bind_create_user(stmt).await?,
Statement::DropUser { if_exists, user } => Plan::DropUser(Box::new(DropUserPlan {
if_exists: *if_exists,
user: user.clone(),
})),
Statement::ShowUsers => self.bind_rewrite_to_query(bind_context, "SELECT name, hostname, auth_type, auth_string FROM system.users ORDER BY name", RewriteKind::ShowUsers).await?,
Statement::AlterUser(stmt) => self.bind_alter_user(stmt).await?,
// Roles
Statement::ShowRoles => Plan::ShowRoles(Box::new(ShowRolesPlan {})),
Statement::CreateRole {
if_not_exists,
role_name,
} => Plan::CreateRole(Box::new(CreateRolePlan {
if_not_exists: *if_not_exists,
role_name: role_name.to_string(),
})),
Statement::DropRole {
if_exists,
role_name,
} => Plan::DropRole(Box::new(DropRolePlan {
if_exists: *if_exists,
role_name: role_name.to_string(),
})),
// Stages
Statement::ShowStages => self.bind_rewrite_to_query(bind_context, "SELECT name, stage_type, number_of_files, creator, comment FROM system.stages ORDER BY name", RewriteKind::ShowStages).await?,
Statement::ListStage { location, pattern } => self.bind_rewrite_to_query(bind_context, format!("SELECT * FROM LIST_STAGE(location => '@{location}', pattern => '{pattern}')").as_str(), RewriteKind::ListStage).await?,
Statement::DescribeStage { stage_name } => self.bind_rewrite_to_query(bind_context, format!("SELECT * FROM system.stages WHERE name = '{stage_name}'").as_str(), RewriteKind::DescribeStage).await?,
Statement::CreateStage(stmt) => self.bind_create_stage(stmt).await?,
Statement::DropStage {
stage_name,
if_exists,
} => Plan::DropStage(Box::new(DropStagePlan {
if_exists: *if_exists,
name: stage_name.clone(),
})),
Statement::RemoveStage { location, pattern } => {
self.bind_remove_stage(location, pattern).await?
}
Statement::Insert(stmt) => self.bind_insert(bind_context, stmt).await?,
Statement::Replace(stmt) => self.bind_replace(bind_context, stmt).await?,
Statement::Delete {
table_reference,
selection,
} => {
self.bind_delete(bind_context, table_reference, selection)
.await?
}
Statement::Update(stmt) => self.bind_update(bind_context, stmt).await?,
// Permissions
Statement::Grant(stmt) => self.bind_grant(stmt).await?,
Statement::ShowGrants { principal } => Plan::ShowGrants(Box::new(ShowGrantsPlan {
principal: principal.clone(),
})),
Statement::Revoke(stmt) => self.bind_revoke(stmt).await?,
// File Formats
Statement::CreateFileFormat{ if_not_exists, name, file_format_options} => Plan::CreateFileFormat(Box::new(CreateFileFormatPlan {
if_not_exists: *if_not_exists,
name: name.clone(),
file_format_options: file_format_options.clone()
})),
Statement::DropFileFormat{
if_exists,
name,
} => Plan::DropFileFormat(Box::new(DropFileFormatPlan {
if_exists: *if_exists,
name: name.clone(),
})),
Statement::ShowFileFormats => Plan::ShowFileFormats(Box::new(ShowFileFormatsPlan {})),
// UDFs
Statement::CreateUDF {
if_not_exists,
udf_name,
parameters,
definition,
description,
} => {
let mut validator = UDFValidator {
name: udf_name.to_string(),
parameters: parameters.iter().map(|v| v.to_string()).collect(),
..Default::default()
};
validator.verify_definition_expr(definition)?;
let udf = UserDefinedFunction {
name: validator.name,
parameters: validator.parameters,
definition: definition.to_string(),
description: description.clone().unwrap_or_default(),
};
Plan::CreateUDF(Box::new(CreateUDFPlan {
if_not_exists: *if_not_exists,
udf,
}))
}
Statement::AlterUDF {
udf_name,
parameters,
definition,
description,
} => {
let mut validator = UDFValidator {
name: udf_name.to_string(),
parameters: parameters.iter().map(|v| v.to_string()).collect(),
..Default::default()
};
validator.verify_definition_expr(definition)?;
let udf = UserDefinedFunction {
name: validator.name,
parameters: validator.parameters,
definition: definition.to_string(),
description: description.clone().unwrap_or_default(),
};
Plan::AlterUDF(Box::new(AlterUDFPlan {
udf,
}))
}
Statement::DropUDF {
if_exists,
udf_name,
} => Plan::DropUDF(Box::new(DropUDFPlan {
if_exists: *if_exists,
name: udf_name.to_string(),
})),
Statement::Call(stmt) => Plan::Call(Box::new(CallPlan {
name: stmt.name.clone(),
args: stmt.args.clone(),
})),
Statement::Presign(stmt) => self.bind_presign(bind_context, stmt).await?,
Statement::SetVariable {
is_global,
variable,
value,
} => {
self.bind_set_variable(bind_context, *is_global, variable, value)
.await?
}
Statement::UnSetVariable(stmt) => {
self.bind_unset_variable(bind_context, stmt)
.await?
}
Statement::SetRole {
is_default,
role_name,
} => {
self.bind_set_role(bind_context, *is_default, role_name).await?
}
Statement::KillStmt { kill_target, object_id } => {
self.bind_kill_stmt(bind_context, kill_target, object_id.as_str())
.await?
}
// share statements
Statement::CreateShare(stmt) => {
self.bind_create_share(stmt).await?
}
Statement::DropShare(stmt) => {
self.bind_drop_share(stmt).await?
}
Statement::GrantShareObject(stmt) => {
self.bind_grant_share_object(stmt).await?
}
Statement::RevokeShareObject(stmt) => {
self.bind_revoke_share_object(stmt).await?
}
Statement::AlterShareTenants(stmt) => {
self.bind_alter_share_accounts(stmt).await?
}
Statement::DescShare(stmt) => {
self.bind_desc_share(stmt).await?
}
Statement::ShowShares(stmt) => {
self.bind_show_shares(stmt).await?
}
Statement::ShowObjectGrantPrivileges(stmt) => {
self.bind_show_object_grant_privileges(stmt).await?
}
Statement::ShowGrantsOfShare(stmt) => {
self.bind_show_grants_of_share(stmt).await?
}
};
Ok(plan)
}
pub(crate) async fn bind_rewrite_to_query(
&mut self,
bind_context: &mut BindContext,
query: &str,
rewrite_kind_r: RewriteKind,
) -> Result<Plan> {
let tokens = tokenize_sql(query)?;
let (stmt, _) = parse_sql(&tokens, Dialect::PostgreSQL)?;
let mut plan = self.bind_statement(bind_context, &stmt).await?;
if let Plan::Query { rewrite_kind, .. } = &mut plan {
*rewrite_kind = Some(rewrite_kind_r)
}
Ok(plan)
}
/// Create a new ColumnBinding with assigned index
pub(crate) fn create_column_binding(
&mut self,
database_name: Option<String>,
table_name: Option<String>,
column_name: String,
data_type: DataType,
) -> ColumnBinding {
let index = self
.metadata
.write()
.add_derived_column(column_name.clone(), data_type.clone());
ColumnBinding {
database_name,
table_name,
column_name,
index,
data_type: Box::new(data_type),
visibility: Visibility::Visible,
}
}
/// Normalize [[<catalog>].<database>].<object>
/// object like table, view ...
pub fn normalize_object_identifier_triple(
&self,
catalog: &Option<Identifier>,
database: &Option<Identifier>,
object: &Identifier,
) -> (String, String, String) {
let catalog_name = catalog
.as_ref()
.map(|ident| normalize_identifier(ident, &self.name_resolution_ctx).name)
.unwrap_or_else(|| self.ctx.get_current_catalog());
let database_name = database
.as_ref()
.map(|ident| normalize_identifier(ident, &self.name_resolution_ctx).name)
.unwrap_or_else(|| self.ctx.get_current_database());
let object_name = normalize_identifier(object, &self.name_resolution_ctx).name;
(catalog_name, database_name, object_name)
}
}
|
#[macro_use]
extern crate getset;
#[derive(CopyGetters, Default, Getters, MutGetters, Setters)]
struct RawIdentifiers {
#[get]
r#type: usize,
#[get_copy]
r#move: usize,
#[get_mut]
r#union: usize,
#[set]
r#enum: usize,
#[get = "with_prefix"]
r#const: usize,
#[get_copy = "with_prefix"]
r#if: usize,
// Ensure having no gen mode doesn't break things.
#[allow(dead_code)]
r#loop: usize,
}
#[test]
fn test_get() {
let val = RawIdentifiers::default();
let _ = val.r#type();
}
#[test]
fn test_get_copy() {
let val = RawIdentifiers::default();
let _ = val.r#move();
}
#[test]
fn test_get_mut() {
let mut val = RawIdentifiers::default();
let _ = val.union_mut();
}
#[test]
fn test_set() {
let mut val = RawIdentifiers::default();
val.set_enum(42);
}
#[test]
fn test_get_with_prefix() {
let val = RawIdentifiers::default();
let _ = val.get_const();
}
#[test]
fn test_get_copy_with_prefix() {
let val = RawIdentifiers::default();
let _ = val.get_if();
}
|
use actix_web::{App,fs, http::{header, Method},middleware::{self,cors::Cors}};
use model::db::init;
use share::state::AppState;
use api::{home::{index,path},auth::{signup, signin}};
use api::article::{article,article_list, article_new};
use api::user::{user_info, user_delete, user_update};
pub fn app_state() -> App<AppState> {
let addr = init();
App::with_state(AppState{ db: addr.clone()})
.middleware(middleware::Logger::default())
.prefix("/api")
.configure(|app| {
Cors::for_app(app)
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
.allowed_headers(vec![header::ORIGIN, header::AUTHORIZATION,header::ACCEPT, header::CONTENT_TYPE])
.supports_credentials()
.max_age(3600)
.resource("/signup", |r| { r.method(Method::POST).with(signup); })
.resource("/signin", |r| { r.method(Method::POST).with(signin); })
.resource("/user_info", |r| { r.method(Method::GET).with(user_info); })
.resource("/user_delete", |r| { r.method(Method::GET).with(user_delete); })
.resource("/user_update", |r| { r.method(Method::POST).with(user_update); })
.resource("/article_list", |r| { r.method(Method::GET).with(article_list); })
.resource("/article_new", |r| { r.method(Method::POST).with(article_new); })
.resource("/article/{article_id}", |r| { r.method(Method::GET).with(article);})
.register()
})
}
pub fn app() -> App {
App::new()
.middleware(middleware::Logger::default())
.resource("/", |r| r.f(index))
.resource("/a/{tail:.*}", |r| r.f(path))
.handler("/", fs::StaticFiles::new("public").unwrap())
}
|
use alloc::alloc::{AllocError, Allocator, Layout};
use core::any::TypeId;
use core::convert::AsRef;
use core::fmt::{self, Debug};
use core::hash::{Hash, Hasher};
use core::ops::Range;
use core::ptr::{self, NonNull};
use anyhow::anyhow;
use super::{OpaqueTerm, Term, TupleIndex};
#[repr(C)]
pub struct Tuple([OpaqueTerm]);
impl Tuple {
pub const TYPE_ID: TypeId = TypeId::of::<Tuple>();
/// Creates a new tuple in the given allocator, with room for `capacity` elements
///
/// # Safety
///
/// It is not safe to use the pointer returned from this function without first initializing all
/// of the tuple elements with valid values. This function does not guarantee that the elements are
/// in any particular state, so use of the tuple without the initialization step is undefined behavior.
pub fn new_in<A: Allocator>(capacity: usize, alloc: A) -> Result<NonNull<Tuple>, AllocError> {
let (layout, value_offset) = Layout::new::<usize>()
.extend(Layout::array::<OpaqueTerm>(capacity).unwrap())
.unwrap();
let ptr: *mut u8 = alloc.allocate(layout)?.cast().as_ptr();
unsafe {
// Write the pointer metadata
ptr::write(ptr as *mut usize, capacity);
// Cast the pointer to a fat NonNull
let ptr = ptr::from_raw_parts_mut(ptr.add(value_offset).cast(), capacity);
Ok(NonNull::new_unchecked(ptr))
}
}
/// Creates a new tuple in the given allocator, from a slice of elements.
///
/// This is a safer alternative to `new_in`, and ensures that the resulting pointer is valid for use
/// right away.
pub fn from_slice<A: Allocator>(
slice: &[OpaqueTerm],
alloc: A,
) -> Result<NonNull<Tuple>, AllocError> {
unsafe {
let mut tuple = Self::new_in(slice.len(), alloc)?;
tuple.as_mut().copy_from_slice(slice);
Ok(tuple)
}
}
/// Gets the size of this tuple
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns true if this tuple has no elements
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the element at 0-based index `index` as a `Term`
///
/// If the index is out of bounds, returns `None`
pub fn get(&self, index: usize) -> Option<Term> {
self.0.get(index).copied().map(|term| term.into())
}
/// Returns the element at the given 0-based index as a `Term` without bounds checks
///
/// # Safety
///
/// Calling this function with an out-of-bounds index is undefined behavior
pub unsafe fn get_unchecked(&self, index: usize) -> Term {
let term = *self.0.get_unchecked(index);
term.into()
}
/// Like `get` but with either 0 or 1-based indexing.
#[inline]
pub fn get_element<I: TupleIndex>(&self, index: I) -> anyhow::Result<Term> {
let index: usize = index.into();
self.get(index).ok_or_else(|| {
anyhow!(
"invalid index {}, exceeds max length of {}",
index,
self.len()
)
})
}
/// Sets the element at the given index
#[inline]
pub fn set_element<A: Allocator, I: TupleIndex, V: Into<OpaqueTerm>>(
&self,
index: I,
value: V,
alloc: A,
) -> Result<NonNull<Tuple>, AllocError> {
let index: usize = index.into();
if index >= self.len() {
panic!(
"invalid index {}, exceeds max length of {}",
index,
self.len()
);
}
let mut tuple = Self::new_in(self.len(), alloc)?;
let t = unsafe { tuple.as_mut() };
t.copy_from_slice(self.as_slice());
let element = t.0.get_mut(index).unwrap();
*element = value.into();
Ok(tuple)
}
/// Sets the element at the given index
#[inline]
pub fn set_element_mut<I: TupleIndex, V: Into<OpaqueTerm>>(
&mut self,
index: I,
value: V,
) -> anyhow::Result<()> {
let index: usize = index.into();
if let Some(element) = self.0.get_mut(index) {
*element = value.into();
return Ok(());
}
let len = self.len();
Err(anyhow!(
"invalid index {}, exceeds max length of {}",
index,
len
))
}
/// Copies all of the elements from `slice` into this tuple
///
/// NOTE: The slice and this tuple are asserted to be the same length
pub fn copy_from_slice(&mut self, slice: &[OpaqueTerm]) {
assert_eq!(self.len(), slice.len());
self.0.copy_from_slice(slice)
}
/// Get this tuple as a slice of raw elements
#[inline]
pub fn as_slice(&self) -> &[OpaqueTerm] {
&self.0
}
/// Get this tuple as a mutable slice of raw elements
#[inline]
pub fn as_mut_slice(&mut self) -> &mut [OpaqueTerm] {
&mut self.0
}
/// Get an iterator over the elements of this tuple as `Term`
pub fn iter(&self) -> TupleIter<'_> {
TupleIter::new(self)
}
}
impl AsRef<[OpaqueTerm]> for Tuple {
fn as_ref(&self) -> &[OpaqueTerm] {
self.0.as_ref()
}
}
impl Debug for Tuple {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("{")?;
for (i, element) in self.iter().enumerate() {
if i > 0 {
write!(f, ", {:?}", element)?;
} else {
write!(f, "{:?}", element)?;
}
}
f.write_str("}")
}
}
impl fmt::Display for Tuple {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("{")?;
for (i, element) in self.iter().enumerate() {
if i > 0 {
write!(f, ", {}", element)?;
} else {
write!(f, "{}", element)?;
}
}
f.write_str("}")
}
}
impl PartialOrd for Tuple {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Tuple {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
use core::cmp::Ordering;
let by_len = self.len().cmp(&other.len());
if by_len != Ordering::Equal {
return by_len;
}
for (x, y) in self.iter().zip(other.iter()) {
let result = x.cmp(&y);
match result {
Ordering::Less | Ordering::Greater => return result,
_ => continue,
}
}
Ordering::Equal
}
}
impl Hash for Tuple {
fn hash<H: Hasher>(&self, state: &mut H) {
for item in self.iter() {
item.hash(state);
}
}
}
impl Eq for Tuple {}
impl PartialEq for Tuple {
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
self.iter().zip(other.iter()).all(|(x, y)| x == y)
}
}
pub struct TupleIter<'a> {
tuple: &'a Tuple,
alive: Range<usize>,
}
impl TupleIter<'_> {
pub fn new<'a>(tuple: &'a Tuple) -> TupleIter<'a> {
let alive = match tuple.len() {
0 => 0..0,
n => 0..n,
};
TupleIter { tuple, alive }
}
}
impl<'a> Iterator for TupleIter<'a> {
type Item = Term;
fn next(&mut self) -> Option<Self::Item> {
self.alive
.next()
.map(|idx| unsafe { self.tuple.get_unchecked(idx) })
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
fn count(self) -> usize {
self.len()
}
fn last(mut self) -> Option<Self::Item> {
self.next_back()
}
}
impl<'a> core::iter::DoubleEndedIterator for TupleIter<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
self.alive
.next_back()
.map(|idx| unsafe { self.tuple.get_unchecked(idx) })
}
}
impl<'a> core::iter::ExactSizeIterator for TupleIter<'a> {
fn len(&self) -> usize {
self.alive.end - self.alive.start
}
fn is_empty(&self) -> bool {
self.alive.is_empty()
}
}
impl<'a> core::iter::FusedIterator for TupleIter<'a> {}
unsafe impl<'a> core::iter::TrustedLen for TupleIter<'a> {}
|
use advent::helpers;
use anyhow::{Context, Result};
use itertools::Itertools;
type Adapters = Vec<i64>;
fn parse_jolt_adapters(i: &str) -> Adapters {
helpers::lines_to_longs(i.trim())
}
fn prepare_jolt_adapters(adapters: Adapters) -> Adapters {
// Prepend 0 and append max_jolt + 3.
let final_device = *adapters.iter().max().expect("No max number") + 3;
let mut adapters = std::iter::once(0)
.chain(adapters.into_iter())
.chain(std::iter::once(final_device))
.collect::<Adapters>();
// Sort for pair-wise iteration.
adapters.sort_unstable();
adapters
}
fn compute_jolt_differences(adapters: Adapters) -> (i64, i64) {
let adapters = prepare_jolt_adapters(adapters);
let diff = adapters
.iter()
.tuple_windows()
.fold((0, 0), |mut diff, (a, b)| {
let jolt_diff = b - a;
match jolt_diff {
1 => diff.0 += 1,
3 => diff.1 += 1,
_ => unreachable!(),
};
diff
});
diff
}
fn compute_adapter_arrangement_count(adapters: Adapters) -> i64 {
let adapters = prepare_jolt_adapters(adapters);
let final_device = adapters.iter().max().expect("No max number");
let mut adapter_path_counter = adapters
.iter()
.cloned()
.map(|a| (a, 0))
.collect::<std::collections::HashMap<i64, i64>>();
if let Some(v) = adapter_path_counter.get_mut(&0) {
*v = 1;
}
let counter = adapters
.iter()
.skip(1)
.fold(adapter_path_counter, |mut counter, adapter| {
counter.insert(
*adapter,
(1..=3)
.into_iter()
.map(|delta| {
let input_adapter = adapter - delta;
counter.get(&input_adapter).unwrap_or(&0)
})
.sum::<i64>(),
);
counter
});
counter[final_device]
}
fn solve_p1() -> Result<()> {
let input = helpers::get_data_from_file_res("d10").context("Coudn't read file contents.")?;
let result = compute_jolt_differences(parse_jolt_adapters(&input));
let result = result.0 * result.1;
println!(
"The number of 1-jolt differences multplied by 3-jolt differences is: {}",
result
);
Ok(())
}
fn solve_p2() -> Result<()> {
let input = helpers::get_data_from_file_res("d10").context("Coudn't read file contents.")?;
let result = compute_adapter_arrangement_count(parse_jolt_adapters(&input));
println!(
"The total number of distinct ways the adapters can be arranged in is: {}",
result
);
Ok(())
}
fn main() -> Result<()> {
solve_p1().ok();
solve_p2()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_p1() {
let input = "
16
10
15
5
1
11
7
19
6
12
4
";
let result = compute_jolt_differences(parse_jolt_adapters(input));
assert_eq!(result.0, 7);
assert_eq!(result.1, 5);
let input = "
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
";
let result = compute_jolt_differences(parse_jolt_adapters(input));
assert_eq!(result.0, 22);
assert_eq!(result.1, 10);
}
#[test]
fn test_p2() {
let input = "
16
10
15
5
1
11
7
19
6
12
4
";
let result = compute_adapter_arrangement_count(parse_jolt_adapters(input));
assert_eq!(result, 8);
let input = "
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
";
let result = compute_adapter_arrangement_count(parse_jolt_adapters(input));
assert_eq!(result, 19208);
}
}
|
pub use diesel::prelude::*;
table! {
admins (id) {
id -> Integer,
user_id -> Integer,
}
}
table! {
hashes (sha256) {
sha256 -> Char,
md5 -> Char,
}
}
table! {
player_stats (id) {
id -> Integer,
user_id -> Integer,
date -> Datetime,
playcount -> Integer,
clear -> Integer,
epg -> Integer,
lpg -> Integer,
egr -> Integer,
lgr -> Integer,
egd -> Integer,
lgd -> Integer,
ebd -> Integer,
lbd -> Integer,
epr -> Integer,
lpr -> Integer,
ems -> Integer,
lms -> Integer,
playtime -> Integer,
}
}
table! {
rename_logs (id) {
id -> Integer,
user_id -> Integer,
old_name -> Varchar,
new_name -> Varchar,
date -> Datetime,
}
}
table! {
scores (id) {
id -> Integer,
user_id -> Integer,
sha256 -> Char,
mode -> Integer,
clear -> Integer,
epg -> Integer,
lpg -> Integer,
egr -> Integer,
lgr -> Integer,
egd -> Integer,
lgd -> Integer,
ebd -> Integer,
lbd -> Integer,
epr -> Integer,
lpr -> Integer,
ems -> Integer,
lms -> Integer,
combo -> Integer,
min_bp -> Integer,
play_count -> Integer,
clear_count -> Integer,
date -> Datetime,
}
}
table! {
score_snaps (id) {
id -> Integer,
user_id -> Integer,
sha256 -> Char,
mode -> Integer,
date -> Datetime,
clear -> Integer,
score -> Integer,
combo -> Integer,
min_bp -> Integer,
}
}
table! {
songs (sha256) {
sha256 -> Char,
title -> Varchar,
subtitle -> Varchar,
artist -> Varchar,
sub_artist -> Varchar,
notes -> Integer,
length -> Integer,
features -> Integer,
}
}
table! {
users (id) {
id -> Integer,
google_id -> Varchar,
gmail_address -> Varchar,
name -> Varchar,
registered_date -> Datetime,
}
}
table! {
user_statuses (id) {
id -> Integer,
user_id -> Integer,
visible -> Bool,
score_updated_at -> Datetime,
}
}
joinable!(admins -> users (user_id));
joinable!(player_stats -> users (user_id));
joinable!(score_snaps -> hashes (sha256));
joinable!(score_snaps -> users (user_id));
joinable!(scores -> hashes (sha256));
joinable!(scores -> users (user_id));
joinable!(songs -> hashes (sha256));
joinable!(user_statuses -> users (user_id));
allow_tables_to_appear_in_same_query!(
admins,
hashes,
player_stats,
rename_logs,
scores,
score_snaps,
songs,
users,
user_statuses,
);
|
pub mod decoder;
mod encoder;
use std::{
fs::File,
path::{Path, PathBuf},
thread::spawn,
};
use decoder::read_file;
use encoder::Encoder;
use explorer::Explorer;
mod explorer;
fn main() {
let (explorer, receiver) = Explorer::new();
let (mut encoder, encoder_reciver) = Encoder::new(receiver);
spawn(move || {
explorer.walkdir(Path::new(
&std::env::args().nth(1).unwrap_or("./src".to_string()),
))
});
spawn(move || encoder.run());
let mut res_file = File::create("./compressed.data").unwrap();
for encoded_data in encoder_reciver {
let _ = encoded_data.write(&mut res_file);
}
}
#[test]
fn name_len() {
read_file(PathBuf::from("./compressed.data"));
}
|
/*
* Copyright 2020 Draphar
*
* 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.
*/
/*!
Networking tools for the program.
*/
use std::path::Path;
use bytes::buf::BufExt;
use futures_util::stream::StreamExt;
pub use http::{request::Builder, Method, StatusCode, Uri};
pub use hyper::Body;
use hyper::{client::connect::HttpConnector, Response};
use hyper_tls::HttpsConnector;
use serde::de::DeserializeOwned;
use tokio::{fs::File, io::AsyncWriteExt};
use crate::prelude::*;
/// A client to perform HTTP requests with.
#[derive(Debug)]
pub struct Client(hyper::Client<HttpsConnector<HttpConnector>>);
impl Client {
#[inline]
pub fn new() -> Client {
Client(hyper::Client::builder().build(HttpsConnector::new()))
}
/// Executes a HTTP request.
/// The body can be read using [`to_disk()`] or [`to_json()`].
///
/// Takes a `Result<...>` for convenience.
///
/// [`to_disk()`]: fn.to_disk.html
/// [`to_json()`]: fn.to_json.html
pub async fn request(&self, request: Builder) -> Result<Response<Body>> {
trace!("request({:?})", request);
let request = request
.header("Connection", "Close")
.header("Accept-Encoding", "identity")
.body(Body::empty())?;
let response = self.0.request(request).await?;
Ok(response)
}
}
/// Parses a response as JSON.
pub async fn to_json<T: DeserializeOwned>(response: Response<Body>) -> Result<T> {
trace!("to_json({:?})", response);
let body = hyper::body::aggregate(response).await?;
let value = serde_json::from_reader(body.reader())?;
Ok(value)
}
/// Writes a response to the disk.
pub async fn to_disk(response: Response<Body>, output: &Path) -> Result<()> {
trace!("to_disk({:?}, {:?})", response, output);
let mut file = File::create(output).await?;
let mut body = response.into_body();
while let Some(i) = body.next().await {
let i = i?;
file.write_all(&i).await?;
}
Ok(())
}
/// Downloads a file.
pub async fn download(client: &Client, url: &Uri, output: &Path) -> Result<()> {
trace!("download({:?}, {:?})", url, output);
let response = client
.request(Builder::new().method(Method::GET).uri(url))
.await?;
let status = response.status();
if status.is_success() {
debug!("Received {} from {:?}", status, url);
} else if status.as_u16() == 404 {
return Err(Error::new("File not found"));
} else {
return Err(Error::new(format!("Unexpected response code {}", status)));
};
to_disk(response, output).await?;
Ok(())
}
|
use std::vec::*;
use graphics::*;
use math::*;
use na::{Vector3};
pub trait RendererVertFrag{
fn render_mode (&self) -> usize;
fn shader_name (&self) -> String;
fn set_attrib_ptrs (&mut self);
fn construct (&mut self) -> bool;
fn deconstruct (&mut self) -> bool;
fn draw (&mut self) -> bool;
fn reset (&mut self); //used to clear/reset all data stored in 'self'
}
pub struct RendererVertFragDef{
pub vertex_size: usize,
pub vertex_pool: Vec<f32>,
pub index_pool: Vec<u32>,
pub vertex_count: u32,
pub vbo: usize,
pub vao: usize,
pub ebo: usize,
pub constructed: bool,
pub render_mode: usize,
pub shader_name: String,
pub set_attrib_ptrs: fn(&mut RendererVertFragDef),
}
pub const VERTEX_SIZE_COLOR : usize = 6;
pub const VERTEX_SIZE_COLOR_NORMAL : usize = 9;
pub fn set_attrib_ptrs_color(_:&mut RendererVertFragDef){
gl_vertex_attrib_pointer(0, 3, GL_FLOAT, false, VERTEX_SIZE_COLOR * 4,
0);
gl_enable_vertex_attrib_array(0);
gl_vertex_attrib_pointer(1, 3, GL_FLOAT, false, VERTEX_SIZE_COLOR * 4,
3 * 4);
gl_enable_vertex_attrib_array(1);
}
pub fn set_attrib_ptrs_color_normal(_:&mut RendererVertFragDef){
gl_vertex_attrib_pointer(0, 3, GL_FLOAT, false, VERTEX_SIZE_COLOR_NORMAL * 4,
0);
gl_enable_vertex_attrib_array(0);
gl_vertex_attrib_pointer(1, 3, GL_FLOAT, false, VERTEX_SIZE_COLOR_NORMAL * 4,
3 * 4);
gl_enable_vertex_attrib_array(1);
gl_vertex_attrib_pointer(2, 3, GL_FLOAT, false, VERTEX_SIZE_COLOR_NORMAL * 4,
6 * 4);
gl_enable_vertex_attrib_array(2);
}
impl RendererVertFrag for RendererVertFragDef{
fn render_mode(&self) -> usize {
self.render_mode
}
fn shader_name(&self) -> String {
self.shader_name.clone()
}
fn set_attrib_ptrs(&mut self) {
(self.set_attrib_ptrs)(self)
}
fn construct(&mut self) -> bool {
if self.constructed {return false;};
self.vao = gl_gen_vertex_arrays();
self.vbo = gl_gen_buffers();
self.ebo = gl_gen_buffers();
gl_bind_vertex_array(self.vao);
gl_bind_buffer(GL_ARRAY_BUFFER, self.vbo);
gl_buffer_data(GL_ARRAY_BUFFER,
self.vertex_pool.len(),
self.vertex_pool.as_slice(),
GL_STATIC_DRAW);
gl_bind_buffer(GL_ELEMENT_ARRAY_BUFFER, self.ebo);
gl_buffer_data(GL_ELEMENT_ARRAY_BUFFER, self.index_pool.len(),
self.index_pool.as_slice(),
GL_STATIC_DRAW
);
self.set_attrib_ptrs();
gl_bind_buffer(GL_ARRAY_BUFFER, 0);
gl_bind_vertex_array(0);
self.constructed = true;
true
}
fn deconstruct(&mut self) -> bool {
if !self.constructed {return false;};
gl_delete_vertex_arrays(self.vao);
gl_delete_buffers(self.vbo);
gl_delete_buffers(self.ebo);
self.constructed = false;
true
}
fn draw(&mut self) -> bool {
if !self.constructed {return false;};
gl_bind_vertex_array(self.vao);
gl_draw_elements(self.render_mode, self.index_pool.len(), GL_UNSIGNED_INT, 0);
gl_bind_vertex_array(0);
true
}
fn reset(&mut self) {
self.vertex_pool.clear();
self.index_pool.clear();
self.vertex_count = 0;
}
}
impl RendererVertFragDef{
pub fn make(vs: usize,
set_attrib_ptrs : fn (&mut RendererVertFragDef),
render_mode: usize,
shader_name: String) -> RendererVertFragDef{
RendererVertFragDef{
vertex_size: vs,
vertex_pool: Vec::new(),
index_pool: Vec::new(),
vertex_count: 0,
vbo: 0,
vao: 0,
ebo: 0,
constructed:false,
render_mode,
shader_name,
set_attrib_ptrs
}
}
}
pub fn add_triangle_color(dat: &mut RendererVertFragDef, tr: &Triangle3<f32>, color: Vector3<f32>){
dat.vertex_pool.push(tr.p1[0]);
dat.vertex_pool.push(tr.p1[1]);
dat.vertex_pool.push(tr.p1[2]);
dat.vertex_pool.push(color[0]);
dat.vertex_pool.push(color[1]);
dat.vertex_pool.push(color[2]);
dat.vertex_pool.push(tr.p2[0]);
dat.vertex_pool.push(tr.p2[1]);
dat.vertex_pool.push(tr.p2[2]);
dat.vertex_pool.push(color[0]);
dat.vertex_pool.push(color[1]);
dat.vertex_pool.push(color[2]);
dat.vertex_pool.push(tr.p3[0]);
dat.vertex_pool.push(tr.p3[1]);
dat.vertex_pool.push(tr.p3[2]);
dat.vertex_pool.push(color[0]);
dat.vertex_pool.push(color[1]);
dat.vertex_pool.push(color[2]);
dat.index_pool.push(dat.vertex_count + 0);
dat.index_pool.push(dat.vertex_count + 1);
dat.index_pool.push(dat.vertex_count + 2);
dat.vertex_count += 3;
}
pub fn add_triangle_color_normal(dat: &mut RendererVertFragDef, tr: &Triangle3<f32>, color: &Vector3<f32>, normal : &Vector3<f32>){
dat.vertex_pool.push(tr.p1[0]);
dat.vertex_pool.push(tr.p1[1]);
dat.vertex_pool.push(tr.p1[2]);
dat.vertex_pool.push(color[0]);
dat.vertex_pool.push(color[1]);
dat.vertex_pool.push(color[2]);
dat.vertex_pool.push(normal[0]);
dat.vertex_pool.push(normal[1]);
dat.vertex_pool.push(normal[2]);
dat.vertex_pool.push(tr.p2[0]);
dat.vertex_pool.push(tr.p2[1]);
dat.vertex_pool.push(tr.p2[2]);
dat.vertex_pool.push(color[0]);
dat.vertex_pool.push(color[1]);
dat.vertex_pool.push(color[2]);
dat.vertex_pool.push(normal[0]);
dat.vertex_pool.push(normal[1]);
dat.vertex_pool.push(normal[2]);
dat.vertex_pool.push(tr.p3[0]);
dat.vertex_pool.push(tr.p3[1]);
dat.vertex_pool.push(tr.p3[2]);
dat.vertex_pool.push(color[0]);
dat.vertex_pool.push(color[1]);
dat.vertex_pool.push(color[2]);
dat.vertex_pool.push(normal[0]);
dat.vertex_pool.push(normal[1]);
dat.vertex_pool.push(normal[2]);
dat.index_pool.push(dat.vertex_count + 0);
dat.index_pool.push(dat.vertex_count + 1);
dat.index_pool.push(dat.vertex_count + 2);
dat.vertex_count += 3;
}
fn add_vector_to_pool(dat : &mut RendererVertFragDef, vec : Vector3<f32>){
for i in vec.iter(){dat.vertex_pool.push(i.clone());}
}
pub fn add_line3_color(dat : &mut RendererVertFragDef, line : Line3<f32>, color : Vector3<f32>){
add_vector_to_pool(dat, line.start);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, line.end);
add_vector_to_pool(dat, color);
dat.index_pool.push(0 + dat.vertex_count);
dat.index_pool.push(1 + dat.vertex_count);
dat.vertex_count += 2;
}
pub fn add_square3_bounds_color(dat : &mut RendererVertFragDef, cube : Square3<f32>, color : Vector3<f32>){
add_vector_to_pool(dat, Vector3::new(cube.center.x - cube.extent, cube.center.y - cube.extent, cube.center.z - cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x + cube.extent, cube.center.y - cube.extent, cube.center.z - cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x + cube.extent, cube.center.y + cube.extent, cube.center.z - cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x - cube.extent, cube.center.y + cube.extent, cube.center.z - cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x - cube.extent, cube.center.y - cube.extent, cube.center.z + cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x + cube.extent, cube.center.y - cube.extent, cube.center.z + cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x + cube.extent, cube.center.y + cube.extent, cube.center.z + cube.extent));
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, Vector3::new(cube.center.x - cube.extent, cube.center.y + cube.extent, cube.center.z + cube.extent));
add_vector_to_pool(dat, color);
let indices : [u32;24] = [0,1,1,2,2,3,3,0, 4,5,5,6,6,7,7,4, 0,4, 1,5, 2,6, 3,7];
for i in indices.iter() {dat.index_pool.push(i.clone() + dat.vertex_count);}
dat.vertex_count += 8;
}
//for cubes
fn centers() -> [Vector3<f32>;8]{
[Vector3::new(-0.5, -0.5, -0.5),
Vector3::new(0.5, -0.5, -0.5),
Vector3::new(0.5, -0.5, 0.5),
Vector3::new(-0.5, -0.5, 0.5),
Vector3::new(-0.5, 0.5, -0.5),
Vector3::new(0.5, 0.5, -0.5),
Vector3::new(0.5, 0.5, 0.5),
Vector3::new(-0.5, 0.5, 0.5)]
}
pub fn add_cube_color_normal(dat : &mut RendererVertFragDef, cube : Square3<f32>, color : Vector3<f32>){
let mut corners = [Vector3::zeros();8];
for i in 0..8{
corners[i] = centers()[i] * 2.0 * cube.extent + cube.center;
}
add_triangle_color_normal(dat, &Triangle3{p1 : corners[7], p2 : corners[0], p3 : corners[3]}, &color, &Vector3::new(-1.0, 0.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[0], p2 : corners[7], p3 : corners[4]}, &color, &Vector3::new(-1.0, 0.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[1], p2 : corners[6], p3 : corners[2]}, &color, &Vector3::new(1.0, 0.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[1], p2 : corners[5], p3 : corners[6]}, &color, &Vector3::new(1.0, 0.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[0], p2 : corners[4], p3 : corners[1]}, &color, &Vector3::new(0.0, 0.0, -1.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[1], p2 : corners[4], p3 : corners[5]}, &color, &Vector3::new(0.0, 0.0, -1.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[2], p2 : corners[7], p3 : corners[3]}, &color, &Vector3::new(0.0, 0.0, 1.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[2], p2 : corners[6], p3 : corners[7]}, &color, &Vector3::new(0.0, 0.0, 1.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[0], p2 : corners[2], p3 : corners[3]}, &color, &Vector3::new(0.0, -1.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[2], p2 : corners[0], p3 : corners[1]}, &color, &Vector3::new(0.0, -1.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[6], p2 : corners[4], p3 : corners[7]}, &color, &Vector3::new(0.0, 1.0, 0.0));
add_triangle_color_normal(dat, &Triangle3{p1 : corners[6], p2 : corners[5], p3 : corners[4]}, &color, &Vector3::new(0.0, 1.0, 0.0));
}
pub fn add_sphere_color(dat : &mut RendererVertFragDef, sphere : &Sphere<f32>, n : usize, m : usize, color : Vector3<f32>){
use std;
let pi = std::f32::consts::PI;
let dphi = 2.0 * pi / n as f32;
let dpsi = pi / m as f32;
for i in 0..n{
let phi = i as f32 * dphi;
let phi_next = (i + 1) as f32 * dphi;
for j in 0..m{
let psi = j as f32 * dpsi;
let psi_next = (j + 1) as f32 * dpsi;
let x0 = phi.cos() * psi.sin() * sphere.rad;
let z0 = -phi.sin() * psi.sin() * sphere.rad;
let y0 = -psi.cos() * sphere.rad;
let x1 = phi_next.cos() * psi.sin() * sphere.rad;
let z1 = -phi_next.sin() * psi.sin() * sphere.rad;
let y1 = -psi.cos() * sphere.rad;
let x2 = phi.cos() * psi_next.sin() * sphere.rad;
let z2 = -phi.sin() * psi_next.sin() * sphere.rad;
let y2 = -psi_next.cos() * sphere.rad;
let x3 = phi_next.cos() * psi_next.sin() * sphere.rad;
let z3 = -phi_next.sin() * psi_next.sin() * sphere.rad;
let y3 = -psi_next.cos() * sphere.rad;
let v0 = Vector3::new(x0, y0, z0);
let v1 = Vector3::new(x1, y1, z1);
let v2 = Vector3::new(x2, y2, z2);
let v3 = Vector3::new(x3, y3, z3);
let normal = (v1 - v0).cross(&(v2 - v0)).normalize();
add_vector_to_pool(dat, sphere.center + v0);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, normal);
add_vector_to_pool(dat, sphere.center + v1);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, normal);
add_vector_to_pool(dat, sphere.center + v2);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, normal);
add_vector_to_pool(dat, sphere.center + v3);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, normal);
}
}
for i in 0..n*m{
dat.index_pool.push(dat.vertex_count + 4*i as u32);
dat.index_pool.push(dat.vertex_count + 4*i as u32 + 1);
dat.index_pool.push(dat.vertex_count + 4*i as u32 + 2);
dat.index_pool.push(dat.vertex_count + 4*i as u32 + 1);
dat.index_pool.push(dat.vertex_count + 4*i as u32 + 3);
dat.index_pool.push(dat.vertex_count + 4*i as u32 + 2);
}
dat.vertex_count += n as u32 * m as u32 * 4;
}
pub fn add_grid3_color(dat : &mut RendererVertFragDef, center : Vector3<f32>, tangent : Vector3<f32>, normal : Vector3<f32>, extent : f32, subdiv_num : u32, color : Vector3<f32>){
let right = tangent.cross(&normal) * extent;
let along = tangent * extent;
add_vector_to_pool(dat, center - right - along);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, center + right - along);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, center + right + along);
add_vector_to_pool(dat, color);
add_vector_to_pool(dat, center - right + along);
add_vector_to_pool(dat, color);
let a = extent / subdiv_num as f32;
//TODO inefficient loops(could be done in one)
for i in 1 .. 2 * subdiv_num{
add_vector_to_pool(dat, center - right * (extent - i as f32 * a) - along);
add_vector_to_pool(dat, color);
}
for i in 1 .. 2 * subdiv_num{
add_vector_to_pool(dat, center + right - along * (extent - i as f32 * a) );
add_vector_to_pool(dat, color);
}
for i in 1 .. 2 * subdiv_num{
add_vector_to_pool(dat, center + right * (extent - i as f32 * a) + along);
add_vector_to_pool(dat, color);
}
for i in 1 .. 2 * subdiv_num{
add_vector_to_pool(dat, center - right + along * (extent - i as f32 * a) );
add_vector_to_pool(dat, color);
}
dat.index_pool.push(0 + dat.vertex_count);
dat.index_pool.push(1 + dat.vertex_count);
dat.index_pool.push(1 + dat.vertex_count);
dat.index_pool.push(2 + dat.vertex_count);
dat.index_pool.push(2 + dat.vertex_count);
dat.index_pool.push(3 + dat.vertex_count);
dat.index_pool.push(3 + dat.vertex_count);
dat.index_pool.push(0 + dat.vertex_count);
let off0 : u32 = 4;
let off1 : u32 = subdiv_num * 2 - 1;
for i in 0..off1{
dat.index_pool.push(off0 + off1 + i + dat.vertex_count);
dat.index_pool.push(off0 + 4*off1 - i - 1 + dat.vertex_count);
}
for i in 0..off1{
dat.index_pool.push(off0 + i + dat.vertex_count);
dat.index_pool.push(off0 + 3*off1 - i - 1 + dat.vertex_count);
}
dat.vertex_count += 4 + 4 * (2 * subdiv_num - 1) //TODO ???
}
|
/*
* hurl (https://hurl.dev)
* Copyright (C) 2020 Orange
*
* 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 hurl::parser::error::ParseError;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::{self, Read};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use atty::Stream;
use chrono::{DateTime, Local};
use clap::{AppSettings, ArgMatches};
use hurl::cli;
use hurl::core::common::FormatError;
use hurl::html;
use hurl::http;
use hurl::parser;
use hurl::runner;
use hurl::runner::core::*;
use hurl::runner::log;
use hurl::format;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CLIOptions {
pub verbose: bool,
pub color: bool,
pub fail_fast: bool,
pub insecure: bool,
pub variables: HashMap<String, String>,
pub to_entry: Option<usize>,
pub redirect: http::client::Redirect,
pub http_proxy: Option<String>,
pub https_proxy: Option<String>,
pub all_proxy: Option<String>,
pub noproxy_hosts: Vec<String>,
}
fn execute(filename: &str,
contents: String,
current_dir: &Path,
file_root: Option<String>,
cookies: Vec<http::cookie::Cookie>,
cli_options: CLIOptions,
logger: format::logger::Logger,
) -> HurlResult {
let mut cookiejar = http::cookie::CookieJar::init(cookies);
match parser::parse_hurl_file(contents.as_str()) {
Err(e) => {
let error = hurl::format::error::Error {
source_info: e.source_info(),
description: e.description(),
fixme: e.fixme(),
lines: vec![],
filename: "".to_string(),
warning: false,
color: logger.color,
};
logger.error(&error);
std::process::exit(2);
}
Ok(hurl_file) => {
logger.verbose(format!("Fail fast: {}", cli_options.fail_fast).as_str());
logger.verbose(format!("variables: {:?}", cli_options.variables).as_str());
if let Some(proxy) = cli_options.http_proxy.clone() {
logger.verbose(format!("http_proxy: {}", proxy).as_str());
}
if let Some(proxy) = cli_options.https_proxy.clone() {
logger.verbose(format!("https_proxy: {}", proxy).as_str());
}
if let Some(proxy) = cli_options.all_proxy.clone() {
logger.verbose(format!("all_proxy: {}", proxy).as_str());
}
if !cli_options.noproxy_hosts.is_empty() {
logger.verbose(format!("noproxy: {}", cli_options.noproxy_hosts.join(", ")).as_str());
}
match cli_options.redirect {
http::client::Redirect::None {} => {}
http::client::Redirect::Limited(n) => logger.verbose(format!("follow redirect (max: {})", n).as_str()),
http::client::Redirect::Unlimited {} => logger.verbose("follow redirect"),
};
if let Some(to_entry) = cli_options.to_entry {
if to_entry < hurl_file.entries.len() {
logger.verbose(format!("executing {}/{} entries", to_entry.to_string(), hurl_file.entries.len()).as_str());
} else {
logger.verbose("executing all entries");
}
}
let noproxy_hosts = cli_options.noproxy_hosts.clone();
let redirect = cli_options.redirect.clone();
let client = http::client::Client::init(http::client::ClientOptions {
noproxy_hosts,
insecure: cli_options.insecure,
redirect,
http_proxy: cli_options.http_proxy.clone(),
https_proxy: cli_options.https_proxy.clone(),
all_proxy: cli_options.all_proxy.clone(),
});
let context_dir = match file_root {
None => {
if filename == "-" {
current_dir.to_str().unwrap().to_string()
} else {
let path = Path::new(filename);
let parent = path.parent();
parent.unwrap().to_str().unwrap().to_string()
}
}
Some(filename) => {
filename
}
};
let options = RunnerOptions {
fail_fast: cli_options.fail_fast,
variables: cli_options.variables,
to_entry: cli_options.to_entry,
};
runner::file::run(hurl_file,
client,
filename.to_string(),
&mut cookiejar,
context_dir,
options,
logger,
)
}
}
}
fn output_color(matches: ArgMatches) -> bool {
if matches.is_present("color") {
true
} else if matches.is_present("no_color") {
false
} else {
atty::is(Stream::Stdout)
}
}
fn noproxy_host(matches: ArgMatches) -> Vec<String> {
match matches.value_of("noproxy") {
Some(value) => {
value.split(',').map(|e| e.trim().to_string()).collect()
}
_ => if let Ok(v) = std::env::var("no_proxy") {
v.split(',').map(|e| e.trim().to_string()).collect()
} else {
vec![]
}
}
}
fn to_entry(matches: ArgMatches, logger: format::logger::Logger) -> Option<usize> {
match matches.value_of("to_entry") {
Some(value) => {
match value.parse() {
Ok(v) => Some(v),
Err(_) => {
logger.error_message("Invalid value for option --to-entry - must be a positive integer!".to_string());
std::process::exit(1);
}
}
}
None => None,
}
}
fn json_file(matches: ArgMatches, logger: format::logger::Logger) -> (Vec<HurlResult>, Option<std::path::PathBuf>) {
if let Some(filename) = matches.value_of("json") {
let path = Path::new(filename);
let results = if matches.is_present("append") && std::path::Path::new(&path).exists() {
logger.verbose(format!("Appending session to {}", path.display()).as_str());
let data = fs::read_to_string(path).unwrap();
let v: serde_json::Value = match serde_json::from_str(data.as_str()) {
Ok(v) => v,
Err(_) => {
logger.error_message(format!("The file {} is not a valid json file", path.display()));
std::process::exit(127);
}
};
match log::parse_results(v) {
Err(msg) => {
logger.error_message(format!("Existing Hurl json can not be parsed! - {}", msg));
std::process::exit(127);
}
Ok(results) => results
}
} else {
if matches.is_present("verbose") {
logger.error_message(format!("* Writing session to {}", path.display()));
}
vec![]
};
(results, Some(path.to_path_buf()))
} else {
(vec![], None)
}
}
fn html_report(matches: ArgMatches, logger: format::logger::Logger) -> Option<std::path::PathBuf> {
if let Some(dir) = matches.value_of("html_report") {
let path = Path::new(dir);
if std::path::Path::new(&path).exists() {
if !path.read_dir().map(|mut i| i.next().is_none()).unwrap_or(false) {
logger.error_message(format!("Html dir {} already exists and is not empty", path.display()));
std::process::exit(127)
}
Some(path.to_path_buf())
} else {
match std::fs::create_dir(path) {
Err(_) => {
logger.error_message(format!("Html dir {} can not be created", path.display()));
std::process::exit(127)
}
Ok(_) => Some(path.to_path_buf())
}
}
} else {
None
}
}
fn variables(matches: ArgMatches, logger: format::logger::Logger) -> HashMap<String, String> {
let mut variables = HashMap::new();
if matches.is_present("variable") {
let input: Vec<_> = matches.values_of("variable").unwrap().collect();
for s in input {
match s.find('=') {
None => {
logger.error_message(format!("Missing variable value for {}!", s));
std::process::exit(1);
}
Some(index) => {
let (name, value) = s.split_at(index);
if variables.contains_key(name) {
std::process::exit(1);
}
variables.insert(name.to_string(), value[1..].to_string());
}
};
}
}
variables
}
fn app() -> clap::App<'static, 'static> {
clap::App::new("hurl")
//.author(clap::crate_authors!())
.version(clap::crate_version!())
.about("Run hurl FILE(s) or standard input")
.setting(AppSettings::DeriveDisplayOrder)
.setting(AppSettings::UnifiedHelpMessage)
.arg(
clap::Arg::with_name("INPUT")
.help("Sets the input file to use")
.required(false)
.multiple(true)
)
.arg(clap::Arg::with_name("append")
.long("append")
.help("Append sessions to json output")
)
.arg(
clap::Arg::with_name("color")
.long("color")
.conflicts_with("no-color")
.help("Colorize Output"),
)
.arg(
clap::Arg::with_name("cookies_input_file")
.short("b")
.long("cookie")
.value_name("FILE")
.help("Read cookies from FILE"),
)
.arg(
clap::Arg::with_name("cookies_output_file")
.short("c")
.long("cookie-jar")
.value_name("FILE")
.help("Write cookies to FILE after running the session (only for one session)")
)
.arg(clap::Arg::with_name("fail_at_end")
.long("fail-at-end")
.help("Fail at end")
.takes_value(false)
)
.arg(clap::Arg::with_name("file_root")
.long("file-root")
.value_name("DIR")
.help("set root filesystem to import file in hurl (default is current directory)")
.takes_value(true)
)
.arg(clap::Arg::with_name("html_report")
.long("html")
.value_name("DIR")
.help("Generate html report to dir")
.takes_value(true)
)
.arg(
clap::Arg::with_name("include")
.short("i")
.long("include")
.help("Include the HTTP headers in the output"),
)
.arg(
clap::Arg::with_name("insecure")
.short("k")
.long("insecure")
.help("Allow insecure SSl connections"),
)
.arg(clap::Arg::with_name("json")
.long("json")
.value_name("FILE")
.help("Write full session(s) to json file")
.takes_value(true)
)
.arg(
clap::Arg::with_name("redirect")
.short("L")
.long("location")
.help("Follow redirects"),
)
.arg(
clap::Arg::with_name("max_redirects")
.long("max-redirs")
.value_name("NUM")
.default_value("50")
.allow_hyphen_values(true)
.help("Maximum number of redirects allowed"),
)
.arg(
clap::Arg::with_name("no_color")
.long("no-color")
.conflicts_with("color")
.help("Do not colorize Output"),
)
.arg(clap::Arg::with_name("noproxy")
.long("noproxy")
.value_name("HOST(S)")
.help("List of hosts which do not use proxy")
.takes_value(true)
)
.arg(
clap::Arg::with_name("output")
.short("o")
.long("output")
.value_name("FILE")
.help("Write to FILE instead of stdout"),
)
.arg(
clap::Arg::with_name("proxy")
.short("x")
.long("proxy")
.value_name("[PROTOCOL://]HOST[:PORT]")
.help("Use proxy on given protocol/host/port"),
)
.arg(clap::Arg::with_name("to_entry")
.long("to-entry")
.value_name("ENTRY_NUMBER")
.help("Execute hurl file to ENTRY_NUMBER (starting at 1)")
.takes_value(true)
)
.arg(clap::Arg::with_name("variable")
.long("variable")
.value_name("NAME=VALUE")
.multiple(true)
.number_of_values(1)
.help("Define a variable")
.takes_value(true)
)
.arg(
clap::Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Turn on verbose output"),
)
}
pub fn unwrap_or_exit<T>(result: Result<T, cli::Error>, logger: format::logger::Logger) -> T {
match result {
Ok(v) => v,
Err(e) => {
logger.error_message(e.message);
std::process::exit(127);
}
}
}
fn parse_options(matches: ArgMatches, logger: format::logger::Logger) -> Result<CLIOptions, cli::Error> {
let verbose = matches.is_present("verbose");
let color = output_color(matches.clone());
let fail_fast = !matches.is_present("fail_at_end");
let variables = variables(matches.clone(), logger.clone());
let to_entry = to_entry(matches.clone(), logger);
let redirect = cli::options::redirect(matches.is_present("redirect"), matches.value_of("max_redirects").unwrap_or_default())?;
let http_proxy = cli::options::proxy(matches.value_of("proxy"), env::var("http_proxy").ok())?;
let https_proxy = cli::options::proxy(matches.value_of("proxy"), env::var("https_proxy").ok())?;
let all_proxy = cli::options::proxy(matches.value_of("proxy"), env::var("all_proxy").ok())?;
let noproxy_hosts = noproxy_host(matches.clone());
let insecure = matches.is_present("insecure");
Ok(CLIOptions {
verbose,
color,
fail_fast,
insecure,
variables,
to_entry,
redirect,
http_proxy,
https_proxy,
all_proxy,
noproxy_hosts,
})
}
fn main() -> Result<(), cli::Error> {
let app = app();
let matches = app.clone().get_matches();
let mut filenames = match matches.values_of("INPUT") {
None => vec![],
Some(v) => v.collect()
};
if filenames.is_empty() && atty::is(Stream::Stdin) {
if app.clone().print_help().is_err() {
std::process::exit(1);
} else {}
} else if filenames.is_empty() {
filenames.push("-");
}
let current_dir_buf = std::env::current_dir().unwrap();
let current_dir = current_dir_buf.as_path();
let file_root = match matches.value_of("file_root") {
Some(value) => Some(value.to_string()),
_ => None
};
let logger = format::logger::Logger {
filename: None,
lines: vec![],
verbose: matches.is_present("verbose"),
color: output_color(matches.clone()),
};
let cookies = match matches.value_of("cookies_input_file") {
Some(filename) => unwrap_or_exit(cli::options::cookies(filename), logger.clone()),
None => vec![],
};
let (mut hurl_results, json_file) = json_file(matches.clone(), logger.clone());
let html_report = html_report(matches.clone(), logger.clone());
let cookies_output_file = match matches.value_of("cookies_output_file") {
None => None,
Some(filename) => {
let filename = unwrap_or_exit(cli::options::cookies_output_file(filename.to_string(), filenames.len()), logger.clone());
Some(filename)
}
};
let cli_options = unwrap_or_exit(parse_options(matches.clone(), logger.clone()), logger.clone());
for filename in filenames {
let contents = if filename == "-" {
let mut contents = String::new();
io::stdin()
.read_to_string(&mut contents)
.expect("Something went wrong reading standard input");
contents
} else {
if !Path::new(filename).exists() {
logger.error_message(format!("Input file {} does not exit!", filename));
std::process::exit(1);
}
fs::read_to_string(filename).expect("Something went wrong reading the file")
};
let lines: Vec<String> = regex::Regex::new(r"\n|\r\n")
.unwrap()
.split(&contents)
.map(|l| l.to_string())
.collect();
let logger = format::logger::Logger {
filename: Some(filename.to_string()),
lines: lines.clone(),
verbose: cli_options.verbose,
color: cli_options.color,
};
let hurl_result = execute(
filename,
contents,
current_dir,
file_root.clone(),
cookies.clone(),
cli_options.clone(),
logger.clone(),
);
if hurl_result.errors().is_empty() {
// default
// last entry + response + body
if let Some(entry_result) = hurl_result.entries.last() {
if let Some(response) = entry_result.response.clone() {
if matches.is_present("include") {
logger.info(format!("HTTP/{} {}", response.version.to_string(), response.status.to_string()).as_str());
for header in response.headers.clone() {
logger.info(format!("{}: {}", header.name, header.value).as_str());
}
logger.info("");
}
write_output(response.body, matches.value_of("output"), logger.clone());
} else {
logger.warning_message("no response has been received".to_string());
}
} else {
logger.warning_message(format!("warning: no entry have been executed {}", if filename == "-" { "".to_string() } else { format!("for file {}", filename) }));
};
}
hurl_results.push(hurl_result.clone());
}
if let Some(file_path) = json_file {
let mut file = match std::fs::File::create(&file_path) {
Err(why) => {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
Ok(file) => file,
};
let serialized = serde_json::to_string_pretty(&hurl_results).unwrap();
if let Err(why) = file.write_all(serialized.as_bytes()) {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
}
if let Some(dir_path) = html_report {
logger.verbose(format!("Writing html report to {}", dir_path.display()).as_str());
write_html_report(dir_path, hurl_results.clone(), logger.clone());
}
if let Some(file_path) = cookies_output_file {
logger.verbose(format!("Writing cookies to {}", file_path.display()).as_str());
write_cookies_file(file_path, hurl_results.clone(), logger);
}
std::process::exit(exit_code(hurl_results));
}
fn exit_code(hurl_results: Vec<HurlResult>) -> i32 {
let mut count_errors_runner = 0;
let mut count_errors_assert = 0;
for hurl_result in hurl_results.clone() {
let runner_errors: Vec<runner::core::Error> = hurl_result.clone().errors().iter().filter(|e| !e.assert).cloned().collect();
if hurl_result.clone().errors().is_empty() {} else if runner_errors.is_empty() {
count_errors_assert += 1;
} else {
count_errors_runner += 1;
}
}
if count_errors_runner > 0 {
3
} else if count_errors_assert > 0 {
4
} else {
0
}
}
fn write_output(bytes: Vec<u8>, filename: Option<&str>, logger: format::logger::Logger) {
match filename {
None => {
let stdout = io::stdout();
let mut handle = stdout.lock();
handle.write_all(bytes.as_slice())
.expect("writing bytes to console");
}
Some(filename) => {
let path = Path::new(filename);
let mut file = match std::fs::File::create(&path) {
Err(why) => {
logger.error_message(format!("Issue writing to {}: {:?}", path.display(), why));
std::process::exit(127)
}
Ok(file) => file,
};
file.write_all(bytes.as_slice()).expect("writing bytes to file");
}
}
}
fn write_cookies_file(file_path: PathBuf, hurl_results: Vec<HurlResult>, logger: format::logger::Logger) {
let mut file = match std::fs::File::create(&file_path) {
Err(why) => {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
Ok(file) => file,
};
let mut s = r#"# Netscape HTTP Cookie File
# This file was generated by hurl
"#.to_string();
match hurl_results.first() {
None => {
logger.error_message("Issue fetching results".to_string());
std::process::exit(127)
}
Some(result) => {
for cookie in result.cookies.clone() {
s.push_str(cookie.to_netscape().as_str());
s.push('\n');
}
}
}
if let Err(why) = file.write_all(s.as_bytes()) {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
}
fn write_html_report(dir_path: PathBuf, hurl_results: Vec<HurlResult>, logger: format::logger::Logger) {
//let now: DateTime<Utc> = Utc::now();
let now: DateTime<Local> = Local::now();
let html = create_html_index(now.to_rfc2822(), hurl_results);
let s = html.render();
let file_path = dir_path.join("index.html");
let mut file = match std::fs::File::create(&file_path) {
Err(why) => {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
Ok(file) => file,
};
if let Err(why) = file.write_all(s.as_bytes()) {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
let file_path = dir_path.join("report.css");
let mut file = match std::fs::File::create(&file_path) {
Err(why) => {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
Ok(file) => file,
};
if let Err(why) = file.write_all(include_bytes!("report.css")) {
logger.error_message(format!("Issue writing to {}: {:?}", file_path.display(), why));
std::process::exit(127)
}
}
fn create_html_index(now: String, hurl_results: Vec<HurlResult>) -> html::ast::Html {
let head = html::ast::Head {
title: "Hurl Report".to_string(),
stylesheet: Some("report.css".to_string()),
};
let body = html::ast::Body {
children: vec![
html::ast::Element::NodeElement {
name: "h2".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::TextElement("Hurl Report".to_string())
],
},
html::ast::Element::NodeElement {
name: "div".to_string(),
attributes: vec![
html::ast::Attribute::Class("date".to_string())
],
children: vec![
html::ast::Element::TextElement(now)
],
}, html::ast::Element::NodeElement {
name: "table".to_string(),
attributes: vec![],
children: vec![
create_html_table_header(),
create_html_table_body(hurl_results),
],
}
]
};
html::ast::Html { head, body }
}
fn create_html_table_header() -> html::ast::Element {
html::ast::Element::NodeElement {
name: "thead".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::NodeElement {
name: "tr".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::NodeElement {
name: "td".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::TextElement("filename".to_string())
],
},
html::ast::Element::NodeElement {
name: "td".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::TextElement("duration".to_string())
],
}
],
}
],
}
}
fn create_html_table_body(hurl_results: Vec<HurlResult>) -> html::ast::Element {
let children = hurl_results
.iter()
.map(|result| create_html_result(result.clone()))
.collect();
html::ast::Element::NodeElement {
name: "tbody".to_string(),
attributes: vec![],
children,
}
}
fn create_html_result(result: HurlResult) -> html::ast::Element {
let status = if result.success {
"success".to_string()
} else {
"failure".to_string()
};
html::ast::Element::NodeElement {
name: "tr".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::NodeElement {
name: "td".to_string(),
attributes: vec![
html::ast::Attribute::Class(status)
],
children: vec![
html::ast::Element::TextElement(result.filename.clone())
],
},
html::ast::Element::NodeElement {
name: "td".to_string(),
attributes: vec![],
children: vec![
html::ast::Element::TextElement(format!("{}s", result.time_in_ms as f64 / 1000.0))
],
}
],
}
}
|
pub mod note;
pub mod octave;
pub mod repeat;
pub mod tempo;
pub mod tone;
pub mod volume;
use crate::tokenize::{Token, TokenKind};
use std::fmt;
use tone::Effect;
#[macro_export]
macro_rules! try_or_ok_none {
($option:expr) => {
if let Ok(ok) = $option {
ok
} else {
return Ok(None);
}
};
}
#[derive(Eq, PartialEq, Debug)]
pub enum NoteLength {
DefaultLength,
Dot,
Length(usize),
}
#[derive(PartialEq, Debug)]
pub enum ToneModifier {
Detune(usize, f32),
Envelope(f32, f32, f32, f32),
Tone(usize),
DefinePCMTone(Vec<f32>),
PCMTone(usize),
Gate(f32),
Tune(f32),
Effect(Effect),
Volume(f32),
}
#[derive(PartialEq, Debug)]
pub enum Instruction {
Note(isize, Vec<NoteLength>),
PlayPCM(usize, f32),
Chord(Vec<isize>, Vec<NoteLength>),
Rest(Vec<NoteLength>),
Octave(isize),
Tempo(usize),
Volume(f32),
ToneModifier(ToneModifier),
Repeat(Track, usize),
Length(Vec<NoteLength>),
Synthesize(Vec<Vec<ToneModifier>>),
}
pub type Track = Vec<Instruction>;
pub type ParsedMML = Vec<Track>;
type ParseResult = Result<Option<Instruction>, ParseError>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParseError {
UnexpectedToken(Token),
WrongParamsNumber(usize, usize, usize), // Params at, expected, provided
UnexpectedEOF,
}
impl ParseError {
fn unexpected_char(position: usize, ch: char) -> Self {
Self::UnexpectedToken((position, TokenKind::Character(ch)))
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::UnexpectedToken((token_at, token)) => {
write!(f, "Unexpected token {} at {}", token, token_at)
}
ParseError::WrongParamsNumber(params_at, expected, provided) => write!(
f,
"{} parameter(s) are provided at {}, expected {} parameter(s)",
provided, params_at, expected
),
ParseError::UnexpectedEOF => write!(f, "Unexpected EOF"),
}
}
}
#[derive(Clone)]
pub struct RollbackableTokenStream<'a> {
tokens: &'a [Token],
cursor: usize,
}
impl<'a> Iterator for RollbackableTokenStream<'a> {
type Item = &'a Token;
fn next(&mut self) -> Option<Self::Item> {
let item = self.tokens.get(self.cursor);
self.cursor += 1;
item
}
}
impl<'a> RollbackableTokenStream<'a> {
pub fn rollback(&mut self) {
self.cursor = 0;
}
pub fn accept(&mut self) {
self.tokens = &self.tokens[self.cursor..];
self.cursor = 0;
}
pub fn peek(&self) -> Option<&'a Token> {
self.tokens.get(self.cursor)
}
pub fn empty(&self) -> bool {
self.cursor >= self.tokens.len()
}
pub fn take_number(&mut self) -> Result<(usize, usize), ParseError> {
match self.peek() {
Some(&(token_at, TokenKind::Number(num))) => {
self.next();
Ok((token_at, num))
}
Some(x) => Err(ParseError::UnexpectedToken(x.clone())),
_ => Err(ParseError::UnexpectedEOF),
}
}
pub fn take_character(&mut self) -> Result<(usize, char), ParseError> {
match self.peek() {
Some(&(token_at, TokenKind::Character(ch))) => {
self.next();
Ok((token_at, ch))
}
Some(x) => Err(ParseError::UnexpectedToken(x.clone())),
_ => Err(ParseError::UnexpectedEOF),
}
}
pub fn take_brace_string(&mut self) -> Result<(usize, &'a str), ParseError> {
match self.peek() {
Some((token_at, TokenKind::BraceString(string))) => {
self.next();
Ok((*token_at, string))
}
Some(x) => Err(ParseError::UnexpectedToken(x.clone())),
_ => Err(ParseError::UnexpectedEOF),
}
}
pub fn comma_separated_numbers(&mut self) -> Vec<usize> {
let mut numbers = vec![];
while let Ok((_, number)) = self.take_number() {
numbers.push(number);
if self.expect_character(',').is_err() {
break;
}
}
numbers
}
pub fn comma_separated_n_numbers(&mut self, expected: usize) -> Result<Vec<usize>, ParseError> {
let params_at = self.cursor();
let numbers = self.comma_separated_numbers();
if numbers.len() == expected {
Ok(numbers)
} else {
Err(ParseError::WrongParamsNumber(params_at, expected, numbers.len()))
}
}
pub fn expect_character(&mut self, ch_a: char) -> Result<(), ParseError> {
match self.peek() {
Some(&(_, TokenKind::Character(ch_b))) if ch_a == ch_b => {
self.next();
Ok(())
}
Some(x) => Err(ParseError::UnexpectedToken(x.clone())),
None => Err(ParseError::UnexpectedEOF),
}
}
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn new(tokens: &'a [Token]) -> Self {
RollbackableTokenStream { tokens, cursor: 0 }
}
}
pub type Parser = fn(&mut RollbackableTokenStream) -> ParseResult;
pub fn parse_stream(
stream: &mut RollbackableTokenStream,
inside_bracket: bool,
) -> Result<ParsedMML, ParseError> {
let mut parsed = Vec::new();
let mut track = Vec::new();
'main_loop: while !stream.empty() {
if let Some(&(token_at, TokenKind::Character(';'))) = stream.peek() {
stream.next();
if inside_bracket {
return Err(ParseError::unexpected_char(token_at, ';'));
}
stream.accept();
parsed.push(track);
track = Vec::new();
continue;
}
if let Some(&(token_at, TokenKind::Character(']'))) = stream.peek() {
stream.next();
if inside_bracket {
stream.accept();
return Ok(vec![track]);
} else {
return Err(ParseError::unexpected_char(token_at, ']'));
}
}
let parsers = [
note::note,
note::rest,
note::chord,
note::play_pcm,
note::length,
octave::octave,
tempo::tempo,
tone::synthesize,
tone::tone,
volume::volume,
repeat::repeat,
];
for &parser in &parsers {
stream.rollback();
if let Some(x) = parser(stream)? {
track.push(x);
stream.accept();
continue 'main_loop;
}
}
stream.rollback();
let token = stream.next().unwrap();
return Err(ParseError::UnexpectedToken(token.clone()));
}
if inside_bracket {
return Err(ParseError::UnexpectedEOF);
}
if !track.is_empty() {
parsed.push(track);
}
Ok(parsed)
}
pub fn parse(tokens: &[Token]) -> Result<ParsedMML, ParseError> {
let mut stream = RollbackableTokenStream::new(tokens);
parse_stream(&mut stream, false)
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::collections::btree_map::BTreeMap;
use super::super::qlib::linux_def::*;
use super::super::qlib::common::*;
use super::super::qlib::pagetable::*;
pub fn ZeroPage(pageStart: u64) {
use alloc::slice;
unsafe {
let arr = slice::from_raw_parts_mut(pageStart as *mut u64, 512);
for i in 0..512 {
arr[i] = 0
}
}
}
pub fn CheckZeroPage(pageStart: u64) {
use alloc::slice;
unsafe {
let arr = slice::from_raw_parts_mut(pageStart as *mut u64, 512);
for i in 0..512 {
if arr[i] != 0 {
panic!("alloc non zero page {:x}", pageStart);
}
}
}
}
pub struct PagePool {
//refCount for whole pma
pub refCount: u64,
pub refs: BTreeMap<u64, u32>,
pub allocator: AlignedAllocator,
}
impl PagePool {
pub fn PrintRefs(&self) {
error!("PagePool left is {:#x?}", self.refs);
}
pub fn Ref(&mut self, addr: u64) -> Result<u64> {
assert!(addr & (MemoryDef::PAGE_SIZE-1) == 0);
let refcount = match self.refs.get_mut(&addr) {
None => { // the address is not allocated from PagePool
return Ok(1)
}
Some(v) => {
*v += 1;
*v
}
};
self.refCount += 1;
return Ok(refcount as u64)
}
pub fn Deref(&mut self, addr: u64) -> Result<u64> {
assert!(addr & (MemoryDef::PAGE_SIZE-1) == 0);
let refcount = match self.refs.get_mut(&addr) {
None => { // the address is not allocated from PagePool
return Ok(1)
}
Some(v) => {
assert!(*v >= 1, "deref fail: addresss is {:x}", addr);
*v -= 1;
*v
}
};
self.refCount -= 1;
if refcount == 0 {
self.refs.remove(&addr);
self.Free(addr)?;
}
return Ok(refcount as u64)
}
pub fn GetRef(&self, addr: u64) -> Result<u64> {
let refcount = match self.refs.get(&addr) {
None => { // the address is not allocated from PagePool
return Ok(0)
}
Some(v) => {
*v
}
};
return Ok(refcount as u64)
}
pub fn AllocPage(&mut self, incrRef: bool) -> Result<u64> {
let addr = self.Allocate()?;
if incrRef {
self.refs.insert(addr, 1);
self.refCount += 1;
} else {
self.refs.insert(addr, 0);
}
return Ok(addr)
}
pub fn FreePage(&mut self, addr: u64) -> Result<()> {
return self.Free(addr)
}
//unitSize: how many pages for each unit
pub fn New() -> Self {
return Self {
refs: BTreeMap::new(),
//the PagePool won't be free. fake a always nonzero refcount
refCount: 1,
allocator: AlignedAllocator::New(MemoryDef::PAGE_SIZE as usize, MemoryDef::PAGE_SIZE as usize),
};
}
pub fn Allocate(&mut self) -> Result<u64> {
let addr = self.allocator.Allocate()?;
ZeroPage(addr as u64);
return Ok(addr as u64)
}
pub fn Free(&mut self, addr: u64) -> Result<()> {
return self.allocator.Free(addr);
}
}
|
pub mod post;
pub mod schema;
pub use post::{NewPost, Post};
|
mod utils;
use self::utils::body_generators;
use ggez::{graphics, Context, GameResult};
use rand::Rng;
pub(crate) const GRID_SIZE: (i16, i16) = (10, 20);
pub(crate) const GRID_CELL_SIZE: (i16, i16) = (26, 26);
type ColorTuple = (u8, u8, u8, u8);
/// Trait implementation for turning a Segment into graphics Rectangle object
impl From<&Segment> for graphics::Rect {
fn from(seg: &Segment) -> Self {
graphics::Rect::new_i32(
seg.x as i32 * GRID_CELL_SIZE.0 as i32,
seg.y as i32 * GRID_CELL_SIZE.1 as i32,
GRID_CELL_SIZE.0 as i32,
GRID_CELL_SIZE.1 as i32,
)
}
}
/// Represents motion of a piece
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Motion {
Left,
Right,
RotateLeft,
}
/// Represents piece's shape, 7 classic tetromino shapes are used
#[derive(Debug, Copy, Clone)]
pub(crate) enum Shape {
L,
O,
S,
Z,
I,
T,
J,
}
/// A segment is one out of four blocks making each piece
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct Segment {
pub(crate) x: i16,
pub(crate) y: i16,
pub(crate) color: ColorTuple,
}
/// Default shape is I
impl Default for Shape {
fn default() -> Self {
Shape::I
}
}
impl Segment {
/// Create new segment from position coordinates and add color
pub(crate) fn new(pos: (i16, i16), color: ColorTuple) -> Self {
Self {
x: pos.0,
y: pos.1,
color,
}
}
/// Add an extra segment as a ghost cell
pub(crate) fn add_ghost_layer(&self) -> Self {
Self {
x: self.x,
y: self.y - 1,
color: (1, 1, 0, 255),
}
}
}
impl From<i32> for Shape {
fn from(num: i32) -> Shape {
match num {
0 => Shape::L,
1 => Shape::O,
2 => Shape::S,
3 => Shape::Z,
4 => Shape::I,
5 => Shape::T,
_ => Shape::J,
}
}
}
impl From<&Shape> for ColorTuple {
fn from(shape: &Shape) -> Self {
match *shape {
Shape::L => (255, 128, 0, 255),
Shape::O => (255, 255, 0, 255),
Shape::S => (205, 0, 0, 255),
Shape::Z => (0, 205, 0, 255),
Shape::I => (0, 255, 255, 255),
Shape::T => (51, 0, 104, 255),
Shape::J => (0, 0, 153, 255),
}
}
}
/// Represents a single piece that has a shape and body made out of segments
#[derive(Clone, Debug)]
pub(crate) struct Tetromino {
shape: Shape,
pub(crate) body: Vec<Segment>,
}
impl From<Shape> for Tetromino {
/// Generate body at the starting position from a shape
fn from(shape: Shape) -> Self {
Self {
body: Self::generate_body(&shape),
shape,
}
}
}
impl Tetromino {
/// Create new piece with a random shape
pub(crate) fn new() -> Self {
let shape: Shape = Tetromino::generate_shape().unwrap();
Self::from(shape)
}
/// Translate piece
pub(crate) fn translate(&mut self, x: i16, y: i16) {
for seg in self.body.iter_mut() {
seg.x += x;
seg.y += y;
}
}
/// Move by a single step or rotate the piece
pub(crate) fn move_to(&mut self, dir: Motion, base: &Vec<Segment>) {
match dir {
Motion::Left => {
if self.body.iter().all(|elem| {
elem.x > 0
&& elem.y > -1
&& !base
.iter()
.any(|b_elem| b_elem.x == (elem.x - 1) && b_elem.y == elem.y)
}) {
self.body.iter_mut().for_each(|seg| seg.x -= 1);
}
}
Motion::Right => {
if self.body.iter().all(|elem| {
elem.x < GRID_SIZE.0 - 1
&& elem.y > -1
&& !base
.iter()
.any(|b_elem| b_elem.x == (elem.x + 1) && b_elem.y == elem.y)
}) {
self.body.iter_mut().for_each(|seg| seg.x += 1);
}
}
Motion::RotateLeft => {
self.rotate_left(base);
}
}
}
/// Implements the downward motion
pub(crate) fn update(&mut self) {
for seg in self.body.iter_mut() {
seg.y += 1;
}
}
/// Draw the figure using simple rectangles
pub(crate) fn draw(&self, ctx: &mut Context) -> GameResult<()> {
for seg in self.body.iter() {
let rectangle = graphics::Mesh::new_rectangle(
ctx,
graphics::DrawMode::fill(),
seg.into(),
seg.color.into(),
)?;
graphics::draw(ctx, &rectangle, (ggez::mint::Point2 { x: 0.0, y: 0.0 },))?;
}
Ok(())
}
/// Clone body of a piece
pub(crate) fn clone_body(&self) -> Vec<Segment> {
self.body.clone()
}
fn generate_shape() -> Option<Shape> {
let mut rng = rand::thread_rng();
match rng.gen_range(0, 7) {
0 => Some(Shape::L),
1 => Some(Shape::O),
2 => Some(Shape::S),
3 => Some(Shape::Z),
4 => Some(Shape::I),
5 => Some(Shape::T),
6 => Some(Shape::J),
_ => unreachable!(),
}
}
fn generate_body(shape: &Shape) -> Vec<Segment> {
match *shape {
Shape::L => body_generators::generate_l(),
Shape::O => body_generators::generate_o(),
Shape::S => body_generators::generate_s(),
Shape::Z => body_generators::generate_z(),
Shape::I => body_generators::generate_i(),
Shape::T => body_generators::generate_t(),
Shape::J => body_generators::generate_j(),
}
.into_iter()
.map(|v| Segment::new(v, shape.into()))
.collect()
}
/// Return the central segment around which a piece rotates
fn get_central_segment(&self) -> Option<Segment> {
match self.shape {
Shape::O => None,
_ => Some(self.body[1]),
}
}
/// Implements kick from a wall if a piece segment left the well as a result
/// of rotation
fn kickback(&mut self) {
if self.body.iter().any(|seg| seg.x < 0) {
let kick = self.body.iter().min_by_key(|seg| seg.x).unwrap().x;
self.body
.iter_mut()
.for_each(|seg| *seg = Segment::new((seg.x - kick, seg.y), seg.color));
} else if self.body.iter().any(|seg| seg.x >= GRID_SIZE.0) {
let kick = self.body.iter().max_by_key(|seg| seg.x).unwrap().x;
self.body.iter_mut().for_each(|seg| {
*seg = Segment::new((seg.x - (kick - GRID_SIZE.0 + 1), seg.y), seg.color)
});
}
}
fn rotate_left(&mut self, base: &Vec<Segment>) {
if let Some(central_segment) = self.get_central_segment() {
// get the translation
let (x, y) = (-central_segment.x, -central_segment.y);
// translate, rotate and translate the body back
let new_body: Vec<Segment> = self
.body
.iter()
.map(|seg| Segment::new((-1 * (seg.y + y) - x, seg.x + x - y), seg.color))
.collect();
if !new_body.iter().any(|seg| {
seg.y >= GRID_SIZE.1
|| base
.iter()
.any(|b_elem| b_elem.x == seg.x && b_elem.y == seg.y)
}) {
self.body = new_body;
self.kickback();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
/// Test whether piece is translated appropriately
fn test_translate() {
let mut piece = Tetromino::new();
let orig_piece = piece.clone();
piece.translate(2, -1);
for (seg_translated, seg_orig) in piece.body.iter().zip(orig_piece.body.iter()) {
assert_eq!(seg_translated.x, seg_orig.x + 2);
assert_eq!(seg_translated.y, seg_orig.y - 1);
}
}
#[test]
fn test_kickback() {
let base = Vec::new();
let shape = Shape::I;
let mut piece = Tetromino::from(shape);
let body: Vec<Segment> = vec![(0, -1), (0, 0), (0, 1), (0, 2)]
.into_iter()
.map(|v| Segment::new(v, (0, 0, 0, 0)))
.collect();
piece.body = body;
piece.rotate_left(&base);
}
}
|
extern crate chrono;
use self::chrono::prelude::{DateTime, Utc};
use direction::Direction;
use signal::Signal;
use signal::detector::{DetectSignal, DetectSignalError};
use symbol::SymbolId;
pub struct Always {
symbol_id: SymbolId,
direction: Direction
}
impl Always {
pub fn new(symbol_id: SymbolId, direction: Direction) -> Self {
Always { symbol_id, direction }
}
}
impl DetectSignal for Always {
fn detect_signal(&self, datetime: &DateTime<Utc>) -> Result<Option<Signal>, DetectSignalError> {
let signal = Signal::new(
self.symbol_id.clone(),
self.direction.clone(),
datetime.clone(),
String::from("always detect signal")
);
Ok(Some(signal))
}
} |
use std::iter::Iterator;
use crate::util::CrdtCollection;
#[derive(Clone)]
pub struct SmallVectorImpl<V> {
next_local_id: u32,
local_author: u16,
spans: im::Vector<Span>,
document: V,
}
impl<V: CrdtCollection> SmallVectorImpl<V> {
pub fn new(local_author: u16) -> Self {
Self::with_data(V::new(), local_author)
}
pub fn with_data(data: V, local_author: u16) -> Self {
let mut spans = im::Vector::new();
// Insert a dummy span since we insert always after another element, this is the only
// possible way to insert at the first position.
spans.insert(
0,
Span {
document_index: 0,
length: data.length() as u32 + 1,
start_id: 0,
author: 0,
deleted: false,
},
);
Self {
next_local_id: 0,
local_author,
spans,
document: data,
}
}
pub fn next_local_id(&mut self) -> u32 {
let id = self.next_local_id;
self.next_local_id += 1;
id
}
pub fn author(&self) -> u16 {
self.local_author
}
#[inline(always)]
pub fn position(&self, index: usize) -> LocalId {
let index = index as u32 + 1;
let (span_id, &span) = self.spans.iter()
.enumerate()
.find(|span|!span.1.deleted && span.1.document_index <= index && span.1.document_index + span.1.length > index)
.unwrap();
LocalId {
span_index: span_id,
offset: index - span.document_index,
span
}
}
#[inline(always)]
pub fn stable_position(&self, id: StableId) -> LocalId {
let (span_id, &span) = self.spans.iter()
.enumerate()
.find(|span|span.1.author == id.author && span.1.start_id <= id.id && span.1.start_id + span.1.length > id.id)
.unwrap();
LocalId {
span_index: span_id,
offset: if !span.deleted { id.id - span.start_id } else { 0 },
span
}
}
#[inline(always)]
pub fn insert(&mut self, previous: LocalId, current: StableId, element: V::Element) {
let mut span_id = previous.span_index;
let span = previous.span;
let previous_id = previous.span.start_id + previous.offset;
if span.deleted {
// The span is already deleted: It has no character in the document
self.spans.insert(
span_id + 1,
Span {
document_index: span.document_index,
length: 1,
start_id: current.id,
author: current.author,
deleted: false,
},
);
self.document
.insert(span.document_index as usize - 1, element);
} else {
let document_index = previous_id - span.start_id + span.document_index + 1;
self.document.insert(document_index as usize - 1, element);
if span.start_id + span.length == current.id
&& previous_id + 1 == current.id
&& span.author == current.author
{
// We are behind the last item of this span and are the same author: Extend the span
// This is the case we optimise for, since most of the time typing happens continuously.
self.spans[span_id].length += 1;
} else {
// We are inside the span of another author or jumped back, therefore we need to
// create a new span and split the span if necessary.
let new_length = previous_id - span.start_id + 1;
// Insert the new span after the old span
// span_id
self.spans.insert(
span_id + 1,
Span {
document_index,
length: 1,
start_id: current.id,
author: current.author,
deleted: false,
},
);
if new_length < span.length {
// Split off the rest:
self.spans.insert(
span_id + 2,
Span {
document_index: document_index + 1, // Insert after the current character
length: span.length - new_length, // The remaining length
start_id: span.start_id + new_length, // The id after the last id inside the old span
author: span.author,
deleted: false,
},
);
// Reduce the length
// new length will always be <= span.length therefore this is the only case
// in which we need to change something
self.spans[span_id].length = new_length;
span_id += 1;
}
span_id += 1;
}
}
for span in self.spans.iter_mut().skip(span_id + 1) {
// advance each following span.
span.document_index += 1;
}
}
#[inline(always)]
pub fn delete(&mut self, local_id: LocalId) {
let span_index = local_id.span_index;
let span = local_id.span;
let mut next_span = span_index + 1;
let id = local_id.span.start_id + local_id.offset;
let author = local_id.span.author;
// Otherwise someone else already deleted this id.
if !span.deleted {
self.document
.remove((id - span.start_id + span.document_index) as usize - 1);
let mut new_length = span.length - 1;
let other = if self.spans.len() > span_index + 1 {
let next_span = &mut self.spans[span_index + 1];
if next_span.start_id == id + 1
&& next_span.author == author
&& next_span.deleted
&& span.start_id + span.length == id + 1
&& span.author == author
{
// prepend
next_span.document_index -= 1;
next_span.start_id -= 1;
next_span.length += 1;
false
} else {
true
}
} else {
true
};
if other {
new_length = id - span.start_id;
// The span with the newly deleted item
self.spans.insert(
span_index + 1,
Span {
document_index: span.document_index + new_length,
length: 1,
start_id: id,
author,
deleted: true,
},
);
if new_length < span.length - 1 {
// The additional items of the original span behind the deleted item
self.spans.insert(
span_index + 2,
Span {
document_index: span.document_index + new_length,
length: span.length - new_length - 1,
start_id: id + 1,
author,
deleted: false,
},
);
next_span += 1;
}
next_span += 1;
}
for span in self.spans.iter_mut().skip(next_span) {
span.document_index -= 1;
}
if new_length == 0 {
// The span we are inside of has only one character: remove the span!
self.spans.remove(span_index);
// Merge if possible
let next_span = self.spans[span_index];
// Since we have a dummy item at position 0 span_id will never be 0
let previous = &mut self.spans[span_index - 1];
if previous.start_id + previous.length == next_span.start_id
&& previous.author == next_span.author
{
previous.length += next_span.length;
self.spans.remove(span_index);
}
} else {
let span_ref = &mut self.spans[span_index];
span_ref.length = new_length;
}
}
}
//TODO: decide whether we should move this into crate::cmrdt::SmallVector
// pro: it is the only place where we need it
// contra: we would need to export Span also and this struct would become a leaky abstraction
pub fn merge(&mut self, _other: &Self) {
unimplemented!()
}
/// returns the underlying document. Since this CRDT does not keep a history, document contains
/// the accurate list.
pub fn document(&self) -> &V {
&self.document
}
pub fn dbg_spans(&self) {
println!("Spans: {:#?}", self.spans);
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct LocalId {
span_index: usize,
offset: u32,
span: Span,
}
impl LocalId {
#[inline(always)]
pub fn stable(self) -> StableId {
StableId {
author: self.span.author,
id: self.span.start_id + self.offset,
}
}
pub fn id(self) -> u32 {
self.span.start_id + self.offset
}
#[inline(always)]
pub fn position(self) -> usize {
if !self.span.deleted {
(self.span.document_index + self.offset) as usize + 1
} else {
self.span.document_index as usize + 1
}
}
pub fn author(self) -> u16 {
self.span.author
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct StableId {
author: u16,
id: u32,
}
impl StableId {
pub fn new(author: u16, id: u32) -> Self {
Self {
author,
id,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Span {
pub document_index: u32,
pub length: u32,
pub start_id: u32,
pub author: u16,
pub deleted: bool,
}
|
use crate::buf::{Buf, Channels, ChannelsMut, ExactSizeBuf};
use crate::channel::{Channel, ChannelMut};
use crate::io::ReadBuf;
/// The tail of a buffer.
///
/// See [Buf::tail].
pub struct Tail<B> {
buf: B,
n: usize,
}
impl<B> Tail<B> {
/// Construct a new buffer tail.
pub(crate) fn new(buf: B, n: usize) -> Self {
Self { buf, n }
}
}
/// [Tail] adjusts the implementation of [Buf].
///
/// ```rust
/// use audio::{Buf, ExactSizeBuf};
///
/// let buf = audio::interleaved![[0; 4]; 2];
///
/// assert_eq!((&buf).tail(0).channels(), 2);
/// assert_eq!((&buf).tail(0).frames_hint(), Some(0));
///
/// assert_eq!((&buf).tail(1).channels(), 2);
/// assert_eq!((&buf).tail(1).frames_hint(), Some(1));
///
/// assert_eq!((&buf).tail(5).channels(), 2);
/// assert_eq!((&buf).tail(5).frames_hint(), Some(4));
/// ```
impl<B> Buf for Tail<B>
where
B: Buf,
{
fn frames_hint(&self) -> Option<usize> {
let frames = self.buf.frames_hint()?;
Some(usize::min(frames, self.n))
}
fn channels(&self) -> usize {
self.buf.channels()
}
}
/// [Tail] adjusts the implementation of [ExactSizeBuf].
///
/// ```rust
/// use audio::{Buf, ExactSizeBuf};
///
/// let buf = audio::interleaved![[0; 4]; 2];
///
/// assert_eq!((&buf).tail(0).frames(), 0);
/// assert_eq!((&buf).tail(1).frames(), 1);
/// assert_eq!((&buf).tail(5).frames(), 4);
/// ```
impl<B> ExactSizeBuf for Tail<B>
where
B: ExactSizeBuf,
{
fn frames(&self) -> usize {
usize::min(self.buf.frames(), self.n)
}
}
impl<B, T> Channels<T> for Tail<B>
where
B: Channels<T>,
{
fn channel(&self, channel: usize) -> Channel<'_, T> {
self.buf.channel(channel).tail(self.n)
}
}
impl<B, T> ChannelsMut<T> for Tail<B>
where
B: ChannelsMut<T>,
{
fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T> {
self.buf.channel_mut(channel).tail(self.n)
}
fn copy_channels(&mut self, from: usize, to: usize)
where
T: Copy,
{
self.buf.copy_channels(from, to);
}
}
impl<B> ReadBuf for Tail<B>
where
B: ReadBuf,
{
fn remaining(&self) -> usize {
usize::min(self.buf.remaining(), self.n)
}
fn advance(&mut self, n: usize) {
let n = self
.buf
.remaining()
.saturating_sub(self.n)
.saturating_add(n);
self.buf.advance(n);
}
}
|
use std::collections::HashMap;
fn has_ajacent_equal_characters(string: &String) -> bool {
let digits: Vec<_> = string.chars().map(|n| n.to_digit(10).unwrap()).collect();
// Check never decreases
for i in 1..digits.len() {
if &digits[i] < &digits[i-1] { return false; }
}
// Check for existence of pair
for i in 1..digits.len() {
if &digits[i] == &digits[i-1] { return true; }
}
false
}
fn has_ajacent_equal_characters_2(string: &String) -> bool {
let digits: Vec<_> = string.chars().map(|n| n.to_digit(10).unwrap()).collect();
// Check never decreases
for i in 1..digits.len() {
if &digits[i] < &digits[i-1] { return false; }
}
// Check for existence of pair
let mut value_count = HashMap::new();
for i in digits.iter() {
let current_count = value_count.entry(i).or_insert(0);
*current_count += 1;
}
return value_count.values().into_iter()
.filter(|&&count| count == 2)
.count() > 0;
}
fn puzzle1(start: &u32, end: &u32) -> usize {
//recursive_build(0, 6)
return (start.clone()..end.clone())
.filter(|x| x > start)
.filter(|x| x < end)
.map(|number| -> String { number.to_string() })
.filter(has_ajacent_equal_characters)
.count();
}
fn puzzle2(start: &u32, end: &u32) -> usize {
return (start.clone()..end.clone())
.filter(|x| x > start)
.filter(|x| x < end)
.map(|number| -> String { number.to_string() })
.filter(has_ajacent_equal_characters_2)
.count();
}
#[cfg(test)]
mod tests {
use crate::day4::{puzzle1, puzzle2, has_ajacent_equal_characters_2};
use crate::utils;
struct Puzzle1Test {
start_password: u32,
end_password: u32,
expected_result: usize,
}
#[test]
fn test_puzzle_1() {
let mut tests: Vec<Puzzle1Test> = Vec::new();
tests.push(Puzzle1Test {
start_password: 372304,
end_password: 847060,
expected_result: 475,
});
for test in tests {
let result = puzzle1(&test.start_password, &test.end_password);
assert_eq!(result, test.expected_result);
}
}
struct Puzzle2Test {
start_password: u32,
end_password: u32,
expected_result: usize,
}
#[test]
fn test_puzzle_2() {
let mut tests: Vec<Puzzle2Test> = Vec::new();
tests.push(Puzzle2Test {
start_password: 372304,
end_password: 847060,
expected_result: 297,
});
for test in tests {
let result = puzzle2(&test.start_password, &test.end_password);
assert_eq!(result, test.expected_result);
}
}
#[test]
fn test_has_ajacent_equal_characters_2() {
assert_eq!(has_ajacent_equal_characters_2(&String::from("112233")), true);
assert_eq!(has_ajacent_equal_characters_2(&String::from("123444")), false);
assert_eq!(has_ajacent_equal_characters_2(&String::from("111122")), true);
}
} |
use super::*;
use crate::{TableIndex, TypeReader};
#[derive(Copy, Clone)]
pub struct Param {
pub reader: &'static TypeReader,
pub row: Row,
}
impl Param {
pub fn flags(&self) -> ParamFlags {
ParamFlags(self.reader.u32(self.row, 0))
}
pub fn sequence(&self) -> u32 {
self.reader.u32(self.row, 1)
}
pub fn name(&self) -> &'static str {
self.reader.str(self.row, 2)
}
pub fn attributes(&self) -> impl Iterator<Item = Attribute> + '_ {
self.reader
.equal_range(
self.row.file_index,
TableIndex::CustomAttribute,
0,
HasAttribute::Param(*self).encode(),
)
.map(move |row| Attribute {
reader: self.reader,
row,
})
}
pub fn has_attribute(&self, name: (&str, &str)) -> bool {
self.attributes().any(|attribute| attribute.name() == name)
}
}
impl std::fmt::Debug for Param {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Param")
.field("name", &self.name().to_string())
.field("sequence", &self.sequence())
.finish()
}
}
impl PartialEq for Param {
fn eq(&self, other: &Self) -> bool {
self.row == other.row
}
}
impl Eq for Param {}
impl Ord for Param {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.row.cmp(&other.row)
}
}
impl PartialOrd for Param {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
|
use std::fs;
fn read_file(filename: &str) -> Vec<Vec<u8>> {
let mut file_string = fs::read_to_string(filename).expect("I could not read this file");
let mut matrix = Vec::new();
for line in file_string.lines() {
let mut row: Vec<u8> = Vec::new();
for ch in line.chars() {
row.push(
ch.to_string()
.parse()
.expect("Could not parse string to int"),
);
}
println!("{:?}", row);
matrix.push(row);
}
matrix
}
struct DirectionSolution {
pub top: bool,
pub right: bool,
pub down: bool,
pub left: bool,
}
impl DirectionSolution {
pub fn new() -> Self {
DirectionSolution {
top: false,
right: false,
down: false,
left: false,
}
}
pub fn is_true(&self) -> bool {
if self.top || self.right || self.down || self.left {
return true;
}
return false;
}
}
fn create_solution_matrix(size: usize) -> Vec<Vec<DirectionSolution>> {
let mut sol_mat: Vec<Vec<DirectionSolution>> = Vec::new();
for _ in 0..size {
let mut sol_row: Vec<DirectionSolution> = Vec::new();
for _ in 0..size {
sol_row.push(DirectionSolution::new());
}
sol_mat.push(sol_row);
}
sol_mat
}
fn set_borders(
x: usize,
y: usize,
matrix_len: usize,
sol_mat: &mut Vec<Vec<DirectionSolution>>,
sol_score: &mut i32,
) {
if x == 0 {
sol_mat[y][x].left = true;
*sol_score += 1;
return;
}
if y == 0 {
sol_mat[y][x].top = true;
*sol_score += 1;
return;
}
if x == matrix_len - 1 {
sol_mat[y][x].right = true;
*sol_score += 1;
return;
}
if y == matrix_len - 1 {
sol_mat[y][x].down = true;
*sol_score += 1;
return;
}
}
fn solve_right(
start_x: usize,
y: usize,
matrix: &Vec<Vec<u8>>,
sol_mat: &mut Vec<Vec<DirectionSolution>>,
sol_score: &mut i32,
) -> usize {
let mut new_x = start_x + 1;
while new_x != matrix.len() -1 {
if matrix[y][new_x] >= matrix[y][start_x] {
// A tree to the right is too big for
return new_x - start_x;
}
new_x += 1;
}
if matrix[y][start_x] > matrix[y][new_x] {
println!(
"Could make a path right at {}, y: {}, x: {}",
matrix[y][start_x], y, start_x
);
sol_mat[y][start_x].right = true;
*sol_score += 1;
}
return new_x - start_x;
}
fn solve_down(
x: usize,
start_y: usize,
matrix: &Vec<Vec<u8>>,
sol_mat: &mut Vec<Vec<DirectionSolution>>,
sol_score: &mut i32,
) -> usize {
let mut new_y = start_y + 1;
while new_y != matrix.len() -1 {
if matrix[new_y][x] >= matrix[start_y][x] {
// A tree to the bottom is too big
return new_y - start_y;
}
new_y += 1;
}
if matrix[start_y][x] > matrix[new_y][x] {
println!(
"Could make a path downward at {}, y: {}, x: {}",
matrix[start_y][x], start_y, x
);
sol_mat[start_y][x].down = true;
*sol_score += 1;
}
return new_y - start_y;
}
fn solve_left(
start_x: usize,
y: usize,
matrix: &Vec<Vec<u8>>,
sol_mat: &mut Vec<Vec<DirectionSolution>>,
sol_score: &mut i32,
) -> usize {
let mut new_x = start_x - 1;
while new_x != 0 {
if matrix[y][new_x] >= matrix[y][start_x] {
// A tree to the left is too big
return start_x - new_x;
}
new_x -= 1;
}
if matrix[y][start_x] > matrix[y][new_x] {
println!(
"Could make a path left at {}, y: {}, x: {}",
matrix[y][start_x], y, start_x
);
sol_mat[y][start_x].left = true;
*sol_score += 1;
}
return start_x - new_x;
}
fn solve_top(
x: usize,
start_y: usize,
matrix: &Vec<Vec<u8>>,
sol_mat: &mut Vec<Vec<DirectionSolution>>,
sol_score: &mut i32,
) -> usize {
let mut new_y = start_y - 1;
while new_y != 0 {
if matrix[new_y][x] >= matrix[start_y][x] {
// A tree to the bottom is too big
return start_y - new_y;
}
new_y -= 1;
}
if matrix[start_y][x] > matrix[new_y][x] {
println!(
"Could make a path upward at {}, y: {}, x: {}",
matrix[start_y][x], start_y, x
);
sol_mat[start_y][x].top = true;
*sol_score += 1;
}
return(start_y - new_y);
}
fn solve(matrix: Vec<Vec<u8>>, mut sol_mat: Vec<Vec<DirectionSolution>>) {
let mut sol_score = 0;
let mut highest_score =1;
for y in 0..matrix.len() {
for x in 0..matrix.len() {
if !sol_mat[y][x].is_true() {
let mut tree_score = 1;
if x != matrix.len() -1 {
// solve right
let score_right = solve_right(x, y, &matrix, &mut sol_mat, &mut sol_score);
println!("score_right is {}", score_right);
tree_score = tree_score * score_right;
}
if y != matrix.len() - 1 {
// solve down
let score_down = solve_down(x, y, &matrix, &mut sol_mat, &mut sol_score);
println!("score_down is {}", score_down);
tree_score = tree_score * score_down;
}
if x != 0 {
// solve left
let score_left = solve_left(x, y, &matrix, &mut sol_mat, &mut sol_score);
println!("score left is {}", score_left);
tree_score = tree_score * score_left;
}
if y != 0 {
// solve top
let score_top = solve_top(x, y, &matrix, &mut sol_mat, &mut sol_score);
println!("score top is {}", score_top);
tree_score = tree_score * score_top;
}
if y == 0 || x == 0 || x == matrix.len() - 1 || y == matrix.len() - 1 {
tree_score = 0;
}
println!("tree score was {}", tree_score);
if tree_score > highest_score {
highest_score = tree_score;
}
}
}
println!("solution score is: {}", sol_score);
println!("Highest scenic socre is: {}", highest_score);
}
}
fn main() {
let matrix = read_file("input.txt");
let solution_matrix = create_solution_matrix(matrix.len());
solve(matrix, solution_matrix);
}
|
extern crate ctrlc;
extern crate tuxdroid;
use crate::tuxdroid::tuxdroid::TuxDroid;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn main() -> () {
let fux = tuxdroid::fux::Fux::new().expect("Failed to create Fux");
fux.get_status().unwrap();
let _id = fux.get_id().unwrap();
// Handle Ctrl+C
let running = Arc::new(AtomicUsize::new(0));
let r = running.clone();
ctrlc::set_handler(move || {
let prev = r.fetch_add(1, Ordering::SeqCst);
if prev == 0 {
println!("Exiting...");
} else {
std::process::exit(0);
}
})
.expect("Error setting Ctrl-C handler");
println!("Running...");
// while running.load(Ordering::SeqCst) {
// thread::sleep(Duration::from_millis(10));
// }
// if running.load(Ordering::SeqCst) > 0 {
// break;
// }
//fux.flippers_stop();
fux.wake_up_tux();
thread::sleep(Duration::from_secs(2));
println!("Woke up Tux... that lazy bum!");
fux.eyes_open().unwrap();
println!("eye lights on...");
fux.eyes_on().unwrap();
thread::sleep(Duration::from_secs(3));
let effect = tuxdroid::fux::LedEffect {
effect_type: tuxdroid::fux::LedEffectType::GRADIENT_DELTA,
speed: 1.5,
step: 10,
};
println!("Pulsing left eye...");
fux.led_pulse(tuxdroid::fux::Leds::Left, 100, 220, 6, 1.0, &effect);
thread::sleep(Duration::from_secs(10));
println!("Pulsing right eye...");
fux.led_pulse(tuxdroid::fux::Leds::Right, 100, 220, 2, 1.0, &effect);
thread::sleep(Duration::from_secs(10));
fux.open_mouth();
thread::sleep(Duration::from_secs(2));
fux.eyes_blink();
thread::sleep(Duration::from_secs(20));
fux.close_mouth();
thread::sleep(Duration::from_secs(1));
fux.eyes_close().unwrap();
thread::sleep(Duration::from_secs(1));
fux.eyes_open().unwrap();
thread::sleep(Duration::from_secs(5));
fux.flippers_raise();
thread::sleep(Duration::from_secs(2));
fux.flippers_lower();
thread::sleep(Duration::from_secs(5));
fux.flippers_wave();
thread::sleep(Duration::from_secs(60));
fux.flippers_stop();
let _t = std::thread::spawn(move || {
fux.start();
});
// fux.stop();
// t.join()
//match fux {
// Some(tuxdroid) => tuxdroid.start(),
// None => p
//}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// Test coercions involving DST and/or raw pointers
// pretty-expanded FIXME #23616
struct S;
trait T { fn dummy(&self) { } }
impl T for S {}
pub fn main() {
let x: &T = &S;
// Test we can convert from &-ptr to *-ptr of trait objects
let x: *const T = &S;
// Test we can convert from &-ptr to *-ptr of struct pointer (not DST)
let x: *const S = &S;
// As above, but mut
let x: &mut T = &mut S;
let x: *mut T = &mut S;
let x: *mut S = &mut S;
// Test we can change the mutability from mut to const.
let x: &T = &mut S;
let x: *const T = &mut S;
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct AUDIO_ENDPOINT_SHARED_CREATE_PARAMS {
pub u32Size: u32,
pub u32TSSessionId: u32,
pub targetEndpointConnectorType: EndpointConnectorType,
pub wfxDeviceFormat: super::WAVEFORMATEX,
}
impl AUDIO_ENDPOINT_SHARED_CREATE_PARAMS {}
impl ::core::default::Default for AUDIO_ENDPOINT_SHARED_CREATE_PARAMS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for AUDIO_ENDPOINT_SHARED_CREATE_PARAMS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for AUDIO_ENDPOINT_SHARED_CREATE_PARAMS {}
unsafe impl ::windows::core::Abi for AUDIO_ENDPOINT_SHARED_CREATE_PARAMS {
type Abi = Self;
}
pub const DEVINTERFACE_AUDIOENDPOINTPLUGIN: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f2f7b66_65ac_4fa6_8ae4_123c78b89313);
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const DEVPKEY_AudioEndpointPlugin2_FactoryCLSID: super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x12d83bd7_cf12_46be_8540_812710d3021c), pid: 4u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const DEVPKEY_AudioEndpointPlugin_DataFlow: super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x12d83bd7_cf12_46be_8540_812710d3021c), pid: 2u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const DEVPKEY_AudioEndpointPlugin_FactoryCLSID: super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x12d83bd7_cf12_46be_8540_812710d3021c), pid: 1u32 };
#[cfg(feature = "Win32_UI_Shell_PropertiesSystem")]
pub const DEVPKEY_AudioEndpointPlugin_PnPInterface: super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x12d83bd7_cf12_46be_8540_812710d3021c), pid: 3u32 };
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct EndpointConnectorType(pub i32);
pub const eHostProcessConnector: EndpointConnectorType = EndpointConnectorType(0i32);
pub const eOffloadConnector: EndpointConnectorType = EndpointConnectorType(1i32);
pub const eLoopbackConnector: EndpointConnectorType = EndpointConnectorType(2i32);
pub const eKeywordDetectorConnector: EndpointConnectorType = EndpointConnectorType(3i32);
pub const eConnectorCount: EndpointConnectorType = EndpointConnectorType(4i32);
impl ::core::convert::From<i32> for EndpointConnectorType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for EndpointConnectorType {
type Abi = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointFormatControl(pub ::windows::core::IUnknown);
impl IAudioEndpointFormatControl {
pub unsafe fn ResetToDefault(&self, resetflags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(resetflags)).ok()
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointFormatControl {
type Vtable = IAudioEndpointFormatControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x784cfd40_9f89_456e_a1a6_873b006a664e);
}
impl ::core::convert::From<IAudioEndpointFormatControl> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointFormatControl) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointFormatControl> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointFormatControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointFormatControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointFormatControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointFormatControl_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, resetflags: u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointLastBufferControl(pub ::windows::core::IUnknown);
impl IAudioEndpointLastBufferControl {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn IsLastBufferControlSupported(&self) -> super::super::super::Foundation::BOOL {
::core::mem::transmute((::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)))
}
#[cfg(feature = "Win32_Media_Audio_Apo")]
pub unsafe fn ReleaseOutputDataPointerForLastBuffer(&self, pconnectionproperty: *const super::Apo::APO_CONNECTION_PROPERTY) {
::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pconnectionproperty)))
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointLastBufferControl {
type Vtable = IAudioEndpointLastBufferControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8520dd3_8f9d_4437_9861_62f584c33dd6);
}
impl ::core::convert::From<IAudioEndpointLastBufferControl> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointLastBufferControl) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointLastBufferControl> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointLastBufferControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointLastBufferControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointLastBufferControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointLastBufferControl_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> super::super::super::Foundation::BOOL,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Media_Audio_Apo")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pconnectionproperty: *const super::Apo::APO_CONNECTION_PROPERTY),
#[cfg(not(feature = "Win32_Media_Audio_Apo"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointOffloadStreamMeter(pub ::windows::core::IUnknown);
impl IAudioEndpointOffloadStreamMeter {
pub unsafe fn GetMeterChannelCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetMeteringData(&self, u32channelcount: u32) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(u32channelcount), &mut result__).from_abi::<f32>(result__)
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointOffloadStreamMeter {
type Vtable = IAudioEndpointOffloadStreamMeter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1546dce_9dd1_418b_9ab2_348ced161c86);
}
impl ::core::convert::From<IAudioEndpointOffloadStreamMeter> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointOffloadStreamMeter) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointOffloadStreamMeter> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointOffloadStreamMeter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointOffloadStreamMeter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointOffloadStreamMeter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointOffloadStreamMeter_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, pu32channelcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, u32channelcount: u32, pf32peakvalues: *mut f32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointOffloadStreamMute(pub ::windows::core::IUnknown);
impl IAudioEndpointOffloadStreamMute {
pub unsafe fn SetMute(&self, bmuted: u8) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(bmuted)).ok()
}
pub unsafe fn GetMute(&self) -> ::windows::core::Result<u8> {
let mut result__: <u8 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u8>(result__)
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointOffloadStreamMute {
type Vtable = IAudioEndpointOffloadStreamMute_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdfe21355_5ec2_40e0_8d6b_710ac3c00249);
}
impl ::core::convert::From<IAudioEndpointOffloadStreamMute> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointOffloadStreamMute) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointOffloadStreamMute> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointOffloadStreamMute) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointOffloadStreamMute {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointOffloadStreamMute {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointOffloadStreamMute_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, bmuted: u8) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbmuted: *mut u8) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointOffloadStreamVolume(pub ::windows::core::IUnknown);
impl IAudioEndpointOffloadStreamVolume {
pub unsafe fn GetVolumeChannelCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
#[cfg(feature = "Win32_Media_KernelStreaming")]
pub unsafe fn SetChannelVolumes(&self, u32channelcount: u32, pf32volumes: *const f32, u32curvetype: super::super::KernelStreaming::AUDIO_CURVE_TYPE, pcurveduration: *const i64) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(u32channelcount), ::core::mem::transmute(pf32volumes), ::core::mem::transmute(u32curvetype), ::core::mem::transmute(pcurveduration)).ok()
}
pub unsafe fn GetChannelVolumes(&self, u32channelcount: u32) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(u32channelcount), &mut result__).from_abi::<f32>(result__)
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointOffloadStreamVolume {
type Vtable = IAudioEndpointOffloadStreamVolume_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64f1dd49_71ca_4281_8672_3a9eddd1d0b6);
}
impl ::core::convert::From<IAudioEndpointOffloadStreamVolume> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointOffloadStreamVolume) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointOffloadStreamVolume> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointOffloadStreamVolume) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointOffloadStreamVolume {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointOffloadStreamVolume {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointOffloadStreamVolume_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, pu32channelcount: *mut u32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Media_KernelStreaming")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, u32channelcount: u32, pf32volumes: *const f32, u32curvetype: super::super::KernelStreaming::AUDIO_CURVE_TYPE, pcurveduration: *const i64) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Media_KernelStreaming"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, u32channelcount: u32, pf32volumes: *mut f32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointVolume(pub ::windows::core::IUnknown);
impl IAudioEndpointVolume {
pub unsafe fn RegisterControlChangeNotify<'a, Param0: ::windows::core::IntoParam<'a, IAudioEndpointVolumeCallback>>(&self, pnotify: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pnotify.into_param().abi()).ok()
}
pub unsafe fn UnregisterControlChangeNotify<'a, Param0: ::windows::core::IntoParam<'a, IAudioEndpointVolumeCallback>>(&self, pnotify: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pnotify.into_param().abi()).ok()
}
pub unsafe fn GetChannelCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn SetMasterVolumeLevel(&self, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(fleveldb), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn SetMasterVolumeLevelScalar(&self, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(flevel), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn GetMasterVolumeLevel(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetMasterVolumeLevelScalar(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn SetChannelVolumeLevel(&self, nchannel: u32, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), ::core::mem::transmute(fleveldb), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn SetChannelVolumeLevelScalar(&self, nchannel: u32, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), ::core::mem::transmute(flevel), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn GetChannelVolumeLevel(&self, nchannel: u32) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetChannelVolumeLevelScalar(&self, nchannel: u32) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), &mut result__).from_abi::<f32>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetMute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, bmute: Param0, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bmute.into_param().abi(), ::core::mem::transmute(pguideventcontext)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetMute(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
pub unsafe fn GetVolumeStepInfo(&self, pnstep: *mut u32, pnstepcount: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pnstep), ::core::mem::transmute(pnstepcount)).ok()
}
pub unsafe fn VolumeStepUp(&self, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn VolumeStepDown(&self, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn QueryHardwareSupport(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetVolumeRange(&self, pflvolumemindb: *mut f32, pflvolumemaxdb: *mut f32, pflvolumeincrementdb: *mut f32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(pflvolumemindb), ::core::mem::transmute(pflvolumemaxdb), ::core::mem::transmute(pflvolumeincrementdb)).ok()
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointVolume {
type Vtable = IAudioEndpointVolume_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5cdf2c82_841e_4546_9722_0cf74078229a);
}
impl ::core::convert::From<IAudioEndpointVolume> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointVolume) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointVolume> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointVolume) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointVolume {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointVolume {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointVolume_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, pnotify: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnotify: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnchannelcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfleveldb: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflevel: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, pfleveldb: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, pflevel: *mut f32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bmute: super::super::super::Foundation::BOOL, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbmute: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnstep: *mut u32, pnstepcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwhardwaresupportmask: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflvolumemindb: *mut f32, pflvolumemaxdb: *mut f32, pflvolumeincrementdb: *mut f32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointVolumeCallback(pub ::windows::core::IUnknown);
impl IAudioEndpointVolumeCallback {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn OnNotify(&self, pnotify: *mut super::AUDIO_VOLUME_NOTIFICATION_DATA) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pnotify)).ok()
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointVolumeCallback {
type Vtable = IAudioEndpointVolumeCallback_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x657804fa_d6ad_4496_8a60_352752af4f89);
}
impl ::core::convert::From<IAudioEndpointVolumeCallback> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointVolumeCallback) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointVolumeCallback> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointVolumeCallback) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointVolumeCallback {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointVolumeCallback {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointVolumeCallback_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnotify: *mut super::AUDIO_VOLUME_NOTIFICATION_DATA) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioEndpointVolumeEx(pub ::windows::core::IUnknown);
impl IAudioEndpointVolumeEx {
pub unsafe fn RegisterControlChangeNotify<'a, Param0: ::windows::core::IntoParam<'a, IAudioEndpointVolumeCallback>>(&self, pnotify: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pnotify.into_param().abi()).ok()
}
pub unsafe fn UnregisterControlChangeNotify<'a, Param0: ::windows::core::IntoParam<'a, IAudioEndpointVolumeCallback>>(&self, pnotify: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pnotify.into_param().abi()).ok()
}
pub unsafe fn GetChannelCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn SetMasterVolumeLevel(&self, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(fleveldb), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn SetMasterVolumeLevelScalar(&self, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(flevel), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn GetMasterVolumeLevel(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetMasterVolumeLevelScalar(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn SetChannelVolumeLevel(&self, nchannel: u32, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), ::core::mem::transmute(fleveldb), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn SetChannelVolumeLevelScalar(&self, nchannel: u32, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), ::core::mem::transmute(flevel), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn GetChannelVolumeLevel(&self, nchannel: u32) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetChannelVolumeLevelScalar(&self, nchannel: u32) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(nchannel), &mut result__).from_abi::<f32>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetMute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, bmute: Param0, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bmute.into_param().abi(), ::core::mem::transmute(pguideventcontext)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetMute(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
pub unsafe fn GetVolumeStepInfo(&self, pnstep: *mut u32, pnstepcount: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pnstep), ::core::mem::transmute(pnstepcount)).ok()
}
pub unsafe fn VolumeStepUp(&self, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn VolumeStepDown(&self, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(pguideventcontext)).ok()
}
pub unsafe fn QueryHardwareSupport(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetVolumeRange(&self, pflvolumemindb: *mut f32, pflvolumemaxdb: *mut f32, pflvolumeincrementdb: *mut f32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(pflvolumemindb), ::core::mem::transmute(pflvolumemaxdb), ::core::mem::transmute(pflvolumeincrementdb)).ok()
}
pub unsafe fn GetVolumeRangeChannel(&self, ichannel: u32, pflvolumemindb: *mut f32, pflvolumemaxdb: *mut f32, pflvolumeincrementdb: *mut f32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(ichannel), ::core::mem::transmute(pflvolumemindb), ::core::mem::transmute(pflvolumemaxdb), ::core::mem::transmute(pflvolumeincrementdb)).ok()
}
}
unsafe impl ::windows::core::Interface for IAudioEndpointVolumeEx {
type Vtable = IAudioEndpointVolumeEx_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x66e11784_f695_4f28_a505_a7080081a78f);
}
impl ::core::convert::From<IAudioEndpointVolumeEx> for ::windows::core::IUnknown {
fn from(value: IAudioEndpointVolumeEx) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioEndpointVolumeEx> for ::windows::core::IUnknown {
fn from(value: &IAudioEndpointVolumeEx) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioEndpointVolumeEx {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioEndpointVolumeEx {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IAudioEndpointVolumeEx> for IAudioEndpointVolume {
fn from(value: IAudioEndpointVolumeEx) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IAudioEndpointVolumeEx> for IAudioEndpointVolume {
fn from(value: &IAudioEndpointVolumeEx) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IAudioEndpointVolume> for IAudioEndpointVolumeEx {
fn into_param(self) -> ::windows::core::Param<'a, IAudioEndpointVolume> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IAudioEndpointVolume> for &IAudioEndpointVolumeEx {
fn into_param(self) -> ::windows::core::Param<'a, IAudioEndpointVolume> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEndpointVolumeEx_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, pnotify: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnotify: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnchannelcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfleveldb: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflevel: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, fleveldb: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, flevel: f32, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, pfleveldb: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nchannel: u32, pflevel: *mut f32) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bmute: super::super::super::Foundation::BOOL, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbmute: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnstep: *mut u32, pnstepcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pguideventcontext: *const ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwhardwaresupportmask: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pflvolumemindb: *mut f32, pflvolumemaxdb: *mut f32, pflvolumeincrementdb: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ichannel: u32, pflvolumemindb: *mut f32, pflvolumemaxdb: *mut f32, pflvolumeincrementdb: *mut f32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioLfxControl(pub ::windows::core::IUnknown);
impl IAudioLfxControl {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetLocalEffectsState<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, benabled: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), benabled.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetLocalEffectsState(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
}
unsafe impl ::windows::core::Interface for IAudioLfxControl {
type Vtable = IAudioLfxControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x076a6922_d802_4f83_baf6_409d9ca11bfe);
}
impl ::core::convert::From<IAudioLfxControl> for ::windows::core::IUnknown {
fn from(value: IAudioLfxControl) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioLfxControl> for ::windows::core::IUnknown {
fn from(value: &IAudioLfxControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioLfxControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioLfxControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioLfxControl_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, benabled: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbenabled: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAudioMeterInformation(pub ::windows::core::IUnknown);
impl IAudioMeterInformation {
pub unsafe fn GetPeakValue(&self) -> ::windows::core::Result<f32> {
let mut result__: <f32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<f32>(result__)
}
pub unsafe fn GetMeteringChannelCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetChannelsPeakValues(&self, u32channelcount: u32, afpeakvalues: *mut f32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(u32channelcount), ::core::mem::transmute(afpeakvalues)).ok()
}
pub unsafe fn QueryHardwareSupport(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
}
unsafe impl ::windows::core::Interface for IAudioMeterInformation {
type Vtable = IAudioMeterInformation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc02216f6_8c67_4b5b_9d00_d008e73e0064);
}
impl ::core::convert::From<IAudioMeterInformation> for ::windows::core::IUnknown {
fn from(value: IAudioMeterInformation) -> Self {
value.0
}
}
impl ::core::convert::From<&IAudioMeterInformation> for ::windows::core::IUnknown {
fn from(value: &IAudioMeterInformation) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAudioMeterInformation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAudioMeterInformation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioMeterInformation_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, pfpeak: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pnchannelcount: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, u32channelcount: u32, afpeakvalues: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwhardwaresupportmask: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IHardwareAudioEngineBase(pub ::windows::core::IUnknown);
impl IHardwareAudioEngineBase {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetAvailableOffloadConnectorCount<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, _pwstrdeviceid: Param0, _uconnectorid: u32) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), _pwstrdeviceid.into_param().abi(), ::core::mem::transmute(_uconnectorid), &mut result__).from_abi::<u32>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetEngineFormat<'a, Param0: ::windows::core::IntoParam<'a, super::IMMDevice>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, pdevice: Param0, _brequestdeviceformat: Param1, _ppwfxformat: *mut *mut super::WAVEFORMATEX) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pdevice.into_param().abi(), _brequestdeviceformat.into_param().abi(), ::core::mem::transmute(_ppwfxformat)).ok()
}
pub unsafe fn SetEngineDeviceFormat<'a, Param0: ::windows::core::IntoParam<'a, super::IMMDevice>>(&self, pdevice: Param0, _pwfxformat: *mut super::WAVEFORMATEX) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pdevice.into_param().abi(), ::core::mem::transmute(_pwfxformat)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetGfxState<'a, Param0: ::windows::core::IntoParam<'a, super::IMMDevice>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, pdevice: Param0, _benable: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), pdevice.into_param().abi(), _benable.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetGfxState<'a, Param0: ::windows::core::IntoParam<'a, super::IMMDevice>>(&self, pdevice: Param0) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), pdevice.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
}
unsafe impl ::windows::core::Interface for IHardwareAudioEngineBase {
type Vtable = IHardwareAudioEngineBase_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeddce3e4_f3c1_453a_b461_223563cbd886);
}
impl ::core::convert::From<IHardwareAudioEngineBase> for ::windows::core::IUnknown {
fn from(value: IHardwareAudioEngineBase) -> Self {
value.0
}
}
impl ::core::convert::From<&IHardwareAudioEngineBase> for ::windows::core::IUnknown {
fn from(value: &IHardwareAudioEngineBase) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IHardwareAudioEngineBase {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IHardwareAudioEngineBase {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IHardwareAudioEngineBase_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, _pwstrdeviceid: super::super::super::Foundation::PWSTR, _uconnectorid: u32, _pavailableconnectorinstancecount: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdevice: ::windows::core::RawPtr, _brequestdeviceformat: super::super::super::Foundation::BOOL, _ppwfxformat: *mut *mut super::WAVEFORMATEX) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdevice: ::windows::core::RawPtr, _pwfxformat: *mut super::WAVEFORMATEX) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdevice: ::windows::core::RawPtr, _benable: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdevice: ::windows::core::RawPtr, _pbenable: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
|
use std::ops::BitXor;
#[allow(dead_code)]
fn single_number(nums: Vec<i32>) -> i32 {
nums.into_iter().fold(0, i32::bitxor)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_number() {
assert_eq!(single_number(vec![2, 2, 1]), 1);
assert_eq!(single_number(vec![4, 1, 2, 1, 2]), 4);
}
}
|
mod graph;
mod hashfunc;
use graph::Edges;
use graph::LabelMatrix;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc::channel;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Node {
value: String,
index: (usize, usize),
}
impl Node {
pub fn new(v: String, col: usize, vertex: usize) -> Self {
Node {
value: v,
index: (col, vertex),
}
}
pub fn get_index(&self) -> (usize, usize) {
self.index
}
}
fn main() {
let (n, k) = (5, 5);
let edge = Edges::chung(n);
let gra = Arc::new(LabelMatrix::new(&edge, k, &[1]));
let (tx,rx) = channel();
for col in 1..k {
let tx = tx.clone();
let mut map = HashMap::new();
let edge = edge.clone();
let gra = gra.clone();
thread::spawn(move || {
for vertex in 0..n {
let v2 = &edge.0[vertex];
let value = &gra.0[col - 1][vertex];
let node = Node::new(value.to_string(), col - 1, vertex);
let mut tail = vec![];
for i in v2.iter() {
let value = &gra.0[col][*i];
let node_tail = Node::new(value.to_string(), col, *i);
tail.push(node_tail);
}
map.insert(node, tail);
}
tx.send(map).unwrap();
});
}
for _ in 1..k {
let j = rx.recv().unwrap();
println!("{:?}", j);
}
} |
mod parse;
use std::env;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use serde::Serialize;
use std::fs::File;
use std::io::Write;
use url::Url;
use walkdir::{DirEntry, WalkDir};
#[derive(Debug, Serialize, Eq, PartialEq)]
enum Record {
Login(Login),
CreditCard(CreditCard),
SoftwareLicence(SoftwareLicence),
SecureNote(SecureNote),
}
#[derive(Debug, Serialize, Eq, PartialEq)]
struct Login {
title: String,
website: Option<Url>,
username: Option<String>,
password: Option<String>,
notes: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
struct CreditCard {
title: String,
card_number: String,
expiry_date: Option<String>, // (MM/YYYY)
cardholder_name: Option<String>,
pin: Option<String>,
bank_name: Option<String>,
cvv: Option<String>,
notes: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
struct SoftwareLicence {
title: String,
version: Option<String>,
license_key: Option<String>,
your_name: Option<String>,
your_email: Option<String>,
company: Option<String>,
download_link: Option<Url>,
software_publisher: Option<String>,
publishers_website: Option<Url>,
retail_price: Option<String>,
support_email: Option<String>,
purchase_date: Option<String>,
order_number: Option<String>,
notes: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
struct SecureNote {
title: String,
text: String,
}
struct Writer<W: Write> {
login: csv::Writer<W>,
credit_card: csv::Writer<W>,
software_licence: csv::Writer<W>,
secure_note: csv::Writer<W>,
}
fn main() {
let path = env::args_os().skip(1).next();
if path.is_none() {
usage();
}
let path = PathBuf::from(path.unwrap());
if let Err(err) = main_loop(&path) {
eprintln!("Error: {}", err);
}
}
fn main_loop(path: &Path) -> Result<(), Box<dyn Error>> {
let mut writer = Writer::default();
for record in walk(&path) {
let record = record?;
writer.write(&record)?;
}
Ok(())
}
fn gpg_file_or_dir(entry: &DirEntry) -> bool {
entry.file_type().is_dir() || gpg_file(entry)
}
fn gpg_file(entry: &DirEntry) -> bool {
entry.path().extension().map_or(false, |ext| ext == "gpg")
}
fn docker_credential_helper(entry: &DirEntry) -> bool {
entry
.path()
.components()
.find(|component| component.as_os_str() == "docker-credential-helpers")
.is_some()
}
fn not_hidden(entry: &DirEntry) -> bool {
entry.depth() == 0
|| !entry
.file_name()
.to_str()
.map_or(false, |s| s.starts_with("."))
}
fn entry_filter(entry: &DirEntry) -> bool {
not_hidden(entry) && gpg_file_or_dir(entry) && !docker_credential_helper(entry)
}
fn walk(path: &Path) -> impl Iterator<Item = Result<Record, Box<dyn Error>>> {
let walker = WalkDir::new(path).follow_links(true).into_iter();
walker
.filter_entry(entry_filter)
.into_iter()
.filter_map(|entry| {
let entry = entry.unwrap();
eprintln!("{}", entry.path().display());
if entry.file_type().is_file() {
let path = entry.path();
let res = decrypt(path).map(|contents| {
let raw = parse::raw(path, entry.depth(), &contents);
// println!("{:#?}", raw);
let rec = Record::from(raw);
// println!("{:#?}", rec);
rec
});
Some(res)
} else {
None
}
})
}
fn decrypt(path: &Path) -> Result<String, Box<dyn Error>> {
let output = Command::new("gpg")
.args(&["--decrypt", "--quiet", "--use-agent"])
.arg(path)
.stderr(Stdio::inherit())
.output()?;
if output.status.success() {
let s = String::from_utf8(output.stdout)?;
Ok(s)
} else {
Err(String::from("gpg command did not run successfully").into())
}
}
fn usage() {
eprintln!("Usage: pass2csv path/to/password/store");
std::process::exit(1);
}
impl Login {
fn new(
mut title: String,
mut website: Option<Url>,
username: Option<String>,
password: Option<String>,
notes: Option<String>,
) -> Self {
// If website is empty but title looks like it could work as a url, try that
if website.is_none() && title.contains('.') && !title.contains(' ') {
if let Ok(maybe_website) = format!("https://{}", title).parse() {
website = Some(maybe_website);
}
}
const GENERATED_FOR: &str = "Generated Password for ";
if title.starts_with(GENERATED_FOR) {
title.replace_range(..GENERATED_FOR.len(), "");
}
// Strip the leading domain name from the title if present
let candidate = title.contains(' ') && !title.contains('(');
if let (true, Some(host)) = (candidate, website.as_ref().and_then(|url| url.host_str())) {
let (first, rest) = title.split_once(' ').unwrap();
if host == first {
title = rest.to_string()
}
}
Login {
title,
website,
username,
password,
notes,
}
}
}
impl SoftwareLicence {
fn sanitise(mut self) -> Self {
// Strip the leading domain name from the title if present
let host = self
.download_link
.as_ref()
.or(self.publishers_website.as_ref())
.and_then(|url| url.host_str());
let title = &self.title;
let candidate = title.contains(' ') && !title.contains('(');
if let (true, Some(host)) = (candidate, host) {
let (first, rest) = title.split_once(' ').unwrap();
if host == first {
self.title = rest.to_string()
}
}
self
}
}
impl Default for Writer<File> {
fn default() -> Self {
Writer {
login: csv::Writer::from_path("logins.csv").unwrap(),
credit_card: csv::Writer::from_path("credit_cards.csv").unwrap(),
software_licence: csv::Writer::from_path("software.csv").unwrap(),
secure_note: csv::Writer::from_path("notes.csv").unwrap(),
}
}
}
impl<W: Write> Writer<W> {
fn write(&mut self, record: &Record) -> csv::Result<()> {
match record {
Record::Login(login) => self.login.serialize(login),
Record::CreditCard(card) => self.credit_card.serialize(card),
Record::SoftwareLicence(licence) => self.software_licence.serialize(licence),
Record::SecureNote(note) => self.secure_note.serialize(note),
}
}
}
|
use quote;
use syn::Ident;
use crate::attr::Config;
pub fn open_directory_module(config: &Config, tokens: &mut quote::Tokens) -> String {
// get the leaf directory name
let dirname = config.directory.rsplit('/').next().unwrap();
// create identifier
let dirname = sanitize_ident(dirname);
let dirname_ident = Ident::from(dirname.as_ref());
open_module(dirname_ident, tokens);
dirname
}
pub fn open_file_module(filepath: &str, tokens: &mut quote::Tokens) -> String {
// get file name without extension
let filename = filepath.rsplit('/').next().unwrap().split('.').next().unwrap();
// create identifier
let filename = sanitize_ident(filename);
let filename_ident = Ident::from(filename.as_ref());
open_module(filename_ident, tokens);
filename
}
pub fn open_module<I: Into<Ident>>(module_name: I, tokens: &mut quote::Tokens) {
let module_name = module_name.into();
// append module opening tokens
tokens.append(quote! {
mod #module_name
});
tokens.append("{");
}
pub fn close_brace(tokens: &mut quote::Tokens) {
tokens.append("}")
}
pub fn sanitize_ident(ident: &str) -> String {
// replace empty ident
let ident = if ident.is_empty() {
String::from("unnamed")
} else {
ident.to_string()
};
// prepend alphabetic character if token starts with non-alphabetic character
let ident = if ident.chars().nth(0).map(|c| !c.is_alphabetic()).unwrap_or(true) {
format!("x_{}", ident)
} else {
ident
};
// replace special characters with _
replace_chars(&ident, "!@#$%^&*-+=/<>;\'\"()`~", "_")
}
pub fn replace_chars(s: &str, from: &str, to: &str) -> String {
let mut initial = s.to_owned();
for c in from.chars() {
initial = initial.replace(c, to);
}
initial
}
|
//! Future-aware single-threaded synchronization
//!
//! This module contains similar abstractions to `sync`, for communications
//! between tasks on the same thread only.
pub mod mpsc;
pub mod oneshot;
|
mod parser;
fn main() {
println!("Hello, world!");
use std::f64::consts::*;
println!("acos(2)={}",(PI/3.0).cos());
}
|
pub use VkAttachmentStoreOp::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkAttachmentStoreOp {
VK_ATTACHMENT_STORE_OP_STORE = 0,
VK_ATTACHMENT_STORE_OP_DONT_CARE = 1,
}
|
use derivative::Derivative;
use js_sys as js;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::UnwrapThrowExt;
use web_sys as web;
pub type Send<Message> = Rc<dyn Fn(Message)>;
pub trait Subscription {
type Message;
fn subscribe(self, send: Send<Self::Message>) -> Unsubscribe;
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Unsubscribe(#[derivative(Debug = "ignore")] Option<Box<dyn FnMut()>>);
impl Unsubscribe {
pub fn new(f: impl FnMut() + 'static) -> Self {
Unsubscribe(Some(Box::new(f)))
}
}
impl Drop for Unsubscribe {
fn drop(&mut self) {
if let Some(mut f) = self.0.take() {
f()
}
}
}
#[derive(Debug)]
pub struct OnWindow {
name: String,
}
impl OnWindow {
pub fn new<N: Into<String>>(name: N) -> Self {
OnWindow { name: name.into() }
}
}
impl Subscription for OnWindow {
type Message = web::Event;
fn subscribe(self, send: Send<Self::Message>) -> Unsubscribe {
let window = web::window().unwrap_throw();
let closure = Closure::wrap(Box::new(move |event: web::Event| {
send(event);
}) as Box<dyn FnMut(web::Event)>);
(window.as_ref() as &web::EventTarget)
.add_event_listener_with_callback(&self.name, closure.as_ref().unchecked_ref())
.unwrap_throw();
Unsubscribe::new(move || {
(window.as_ref() as &web::EventTarget)
.remove_event_listener_with_callback(&self.name, closure.as_ref().unchecked_ref())
.unwrap_throw();
})
}
}
#[derive(Debug)]
pub struct Interval {
ms: i32,
}
impl Interval {
pub fn new(ms: i32) -> Self {
Interval { ms }
}
}
impl Subscription for Interval {
type Message = ();
fn subscribe(self, send: Send<Self::Message>) -> Unsubscribe {
let window = web::window().unwrap_throw();
let closure = Closure::wrap(Box::new(move || {
send(());
}) as Box<dyn FnMut()>);
let id = window
.set_interval_with_callback_and_timeout_and_arguments(
closure.as_ref().unchecked_ref(),
self.ms,
&js::Array::new(),
)
.unwrap_throw();
Unsubscribe::new(move || {
// We need to move `closure` here so that it isn't dropped too early.
let _ = closure;
window.clear_interval_with_handle(id);
})
}
}
#[derive(Debug)]
pub struct AnimationFrame {}
impl AnimationFrame {
pub fn new() -> Self {
AnimationFrame {}
}
}
impl Subscription for AnimationFrame {
type Message = f64;
fn subscribe(self, send: Send<Self::Message>) -> Unsubscribe {
let closure = Rc::new(RefCell::new(None));
let closure2 = closure.clone();
let done = Rc::new(Cell::new(false));
let done2 = done.clone();
*closure2.borrow_mut() = Some(Closure::wrap(Box::new(move |f64| {
send(f64);
if !done.get() {
request_animation_frame(closure.borrow().as_ref().unwrap_throw());
}
}) as Box<dyn FnMut(f64)>));
request_animation_frame(closure2.borrow().as_ref().unwrap_throw());
return Unsubscribe::new(move || {
done2.set(true);
});
fn request_animation_frame(f: &Closure<dyn FnMut(f64)>) {
web::window()
.unwrap_throw()
.request_animation_frame(f.as_ref().unchecked_ref())
.unwrap_throw();
}
}
}
|
use crate::entities::Item;
use crate::game_event::GameEventType;
use crate::room::Room;
use crate::EventQueue;
use crate::{Action, ActionHandled, State};
// Second room room, locked per default, lever needs to be pulled.
#[derive(Debug)]
pub struct SlushLobbyRoom {
pub visited: bool,
}
impl SlushLobbyRoom {
pub fn new() -> SlushLobbyRoom {
SlushLobbyRoom { visited: false }
}
}
impl Room for SlushLobbyRoom {
fn handle_action(
&mut self,
state: &mut State,
event_queue: &mut EventQueue,
action: &Action,
) -> ActionHandled {
match action {
Action::UseCrowbar => {
if state.player.has_item(Item::Crowbar) {
event_queue.schedule_action(Action::OpenCorridor);
ActionHandled::Handled
} else {
event_queue.schedule_action(Action::Message(
String::from("You don't have a crowbar."),
GameEventType::Failure,
));
ActionHandled::Handled
}
}
Action::UseKeycard => {
if state.player.has_item(Item::Crowbar) {
event_queue.schedule_action(Action::OpenCryoControl);
ActionHandled::Handled
} else {
event_queue.schedule_action(Action::Message(
String::from("You don't have a keycard."),
GameEventType::Failure,
));
ActionHandled::Handled
}
}
_ => ActionHandled::NotHandled,
}
}
fn is_opened(&self) -> bool {
true
}
fn open(&mut self) {}
fn visit(&mut self) {
self.visited = true;
}
fn is_visited(&self) -> bool {
self.visited
}
}
|
#![allow(dead_code, non_camel_case_types)]
use crate::base::logic::bit::{I, O};
use core::panic;
use std::{
fmt::{self, Formatter},
ops::Index,
write,
};
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum bit {
O,
I,
}
impl fmt::Display for bit {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let str = match self {
O => "0".to_string(),
I => "1".to_string(),
};
write!(f, "{}", str)
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Word([bit; 16]);
impl From<&str> for Word {
// TODO from(number)
fn from(str: &str) -> Self {
let char_bits: Vec<char> = str.chars().collect();
if char_bits.len() != 16 {
panic!(&format!("couldn't parse {:?}", str));
}
let mut bits = [O; 16];
for i in 0..16 {
bits[i] = match char_bits[i].to_digit(10) {
Some(0) => O,
Some(1) => I,
_ => panic!(&format!("unknown number {}", char_bits[i])),
}
}
Word::new(bits)
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let str = self
.0
.iter()
.map(|bit| -> String {
match bit {
O => "0".to_string(),
I => "1".to_string(),
}
})
.collect::<Vec<String>>()
.join("");
write!(f, "{}", str)
}
}
impl Word {
pub fn new(bits: [bit; 16]) -> Self {
Self(bits)
}
}
impl Index<usize> for Word {
type Output = bit;
fn index(&self, index: usize) -> &Self::Output {
if index > 15 {
panic!(&format!("index {} is out of range.", index));
}
&self.0[index]
}
}
pub fn nand(a: bit, b: bit) -> bit {
match a {
O => match b {
O => I,
I => I,
},
I => match b {
O => I,
I => O,
},
}
}
pub fn not(a: bit) -> bit {
nand(a, I)
}
pub fn and(a: bit, b: bit) -> bit {
not(nand(a, b))
}
pub fn or(a: bit, b: bit) -> bit {
nand(not(a), not(b))
}
pub fn xor(a: bit, b: bit) -> bit {
and(or(a, b), nand(a, b))
}
pub fn mux(a: bit, b: bit, sel: bit) -> bit {
xor(and(a, not(sel)), and(b, sel))
}
pub fn dmux(input: bit, sel: bit) -> [bit; 2] {
[and(input, not(sel)), and(input, sel)]
}
pub fn not16(bits: Word) -> Word {
Word([
not(bits[0]),
not(bits[1]),
not(bits[2]),
not(bits[3]),
not(bits[4]),
not(bits[5]),
not(bits[6]),
not(bits[7]),
not(bits[8]),
not(bits[9]),
not(bits[10]),
not(bits[11]),
not(bits[12]),
not(bits[13]),
not(bits[14]),
not(bits[15]),
])
}
pub fn and16(a: Word, b: Word) -> Word {
Word([
and(a[0], b[0]),
and(a[1], b[1]),
and(a[2], b[2]),
and(a[3], b[3]),
and(a[4], b[4]),
and(a[5], b[5]),
and(a[6], b[6]),
and(a[7], b[7]),
and(a[8], b[8]),
and(a[9], b[9]),
and(a[10], b[10]),
and(a[11], b[11]),
and(a[12], b[12]),
and(a[13], b[13]),
and(a[14], b[14]),
and(a[15], b[15]),
])
}
pub fn or16(a: Word, b: Word) -> Word {
Word([
or(a[0], b[0]),
or(a[1], b[1]),
or(a[2], b[2]),
or(a[3], b[3]),
or(a[4], b[4]),
or(a[5], b[5]),
or(a[6], b[6]),
or(a[7], b[7]),
or(a[8], b[8]),
or(a[9], b[9]),
or(a[10], b[10]),
or(a[11], b[11]),
or(a[12], b[12]),
or(a[13], b[13]),
or(a[14], b[14]),
or(a[15], b[15]),
])
}
pub fn mux16(a: Word, b: Word, sel: bit) -> Word {
Word([
mux(a[0], b[0], sel),
mux(a[1], b[1], sel),
mux(a[2], b[2], sel),
mux(a[3], b[3], sel),
mux(a[4], b[4], sel),
mux(a[5], b[5], sel),
mux(a[6], b[6], sel),
mux(a[7], b[7], sel),
mux(a[8], b[8], sel),
mux(a[9], b[9], sel),
mux(a[10], b[10], sel),
mux(a[11], b[11], sel),
mux(a[12], b[12], sel),
mux(a[13], b[13], sel),
mux(a[14], b[14], sel),
mux(a[15], b[15], sel),
])
}
pub fn or8way(a: [bit; 8]) -> bit {
or(
or(or(a[0], a[7]), or(a[1], a[6])),
or(or(a[2], a[5]), or(a[3], a[4])),
)
}
pub fn mux2(a: bit, b: bit, c: bit, d: bit, sel: [bit; 2]) -> bit {
mux(mux(a, b, sel[1]), mux(c, d, sel[1]), sel[0])
}
pub fn mux3(a: bit, b: bit, c: bit, d: bit, e: bit, f: bit, g: bit, h: bit, sel: [bit; 3]) -> bit {
mux2(
mux(a, b, sel[2]),
mux(c, d, sel[2]),
mux(e, f, sel[2]),
mux(g, h, sel[2]),
[sel[0], sel[1]],
)
}
pub fn mux4way16(a: Word, b: Word, c: Word, d: Word, sel: [bit; 2]) -> Word {
Word::new([
mux2(a[0], b[0], c[0], d[0], sel),
mux2(a[1], b[1], c[1], d[1], sel),
mux2(a[2], b[2], c[2], d[2], sel),
mux2(a[3], b[3], c[3], d[3], sel),
mux2(a[4], b[4], c[4], d[4], sel),
mux2(a[5], b[5], c[5], d[5], sel),
mux2(a[6], b[6], c[6], d[6], sel),
mux2(a[7], b[7], c[7], d[7], sel),
mux2(a[8], b[8], c[8], d[8], sel),
mux2(a[9], b[9], c[9], d[9], sel),
mux2(a[10], b[10], c[10], d[10], sel),
mux2(a[11], b[11], c[11], d[11], sel),
mux2(a[12], b[12], c[12], d[12], sel),
mux2(a[13], b[13], c[13], d[13], sel),
mux2(a[14], b[14], c[14], d[14], sel),
mux2(a[15], b[15], c[15], d[15], sel),
])
}
pub fn mux8way16(
a: Word,
b: Word,
c: Word,
d: Word,
e: Word,
f: Word,
g: Word,
h: Word,
sel: [bit; 3],
) -> Word {
Word::new([
mux3(a[0], b[0], c[0], d[0], e[0], f[0], g[0], h[0], sel),
mux3(a[1], b[1], c[1], d[1], e[1], f[1], g[1], h[1], sel),
mux3(a[2], b[2], c[2], d[2], e[2], f[2], g[2], h[2], sel),
mux3(a[3], b[3], c[3], d[3], e[3], f[3], g[3], h[3], sel),
mux3(a[4], b[4], c[4], d[4], e[4], f[4], g[4], h[4], sel),
mux3(a[5], b[5], c[5], d[5], e[5], f[5], g[5], h[5], sel),
mux3(a[6], b[6], c[6], d[6], e[6], f[6], g[6], h[6], sel),
mux3(a[7], b[7], c[7], d[7], e[7], f[7], g[7], h[7], sel),
mux3(a[8], b[8], c[8], d[8], e[8], f[8], g[8], h[8], sel),
mux3(a[9], b[9], c[9], d[9], e[9], f[9], g[9], h[9], sel),
mux3(a[10], b[10], c[10], d[10], e[10], f[10], g[10], h[10], sel),
mux3(a[11], b[11], c[11], d[11], e[11], f[11], g[11], h[11], sel),
mux3(a[12], b[12], c[12], d[12], e[12], f[12], g[12], h[12], sel),
mux3(a[13], b[13], c[13], d[13], e[13], f[13], g[13], h[13], sel),
mux3(a[14], b[14], c[14], d[14], e[14], f[14], g[14], h[14], sel),
mux3(a[15], b[15], c[15], d[15], e[15], f[15], g[15], h[15], sel),
])
}
pub fn dmux4way(input: bit, sel: [bit; 2]) -> [bit; 4] {
[
and(and(not(xor(sel[0], O)), not(xor(sel[1], O))), input),
and(and(not(xor(sel[0], O)), not(xor(sel[1], I))), input),
and(and(not(xor(sel[0], I)), not(xor(sel[1], O))), input),
and(and(not(xor(sel[0], I)), not(xor(sel[1], I))), input),
]
}
pub fn dmux8way(input: bit, sel: [bit; 3]) -> [bit; 8] {
let nxor = |a: bit, b: bit| -> bit { not(xor(a, b)) };
[
and(
and(and(nxor(sel[0], O), nxor(sel[1], O)), nxor(sel[2], O)),
input,
),
and(
and(and(nxor(sel[0], O), nxor(sel[1], O)), nxor(sel[2], I)),
input,
),
and(
and(and(nxor(sel[0], O), nxor(sel[1], I)), nxor(sel[2], O)),
input,
),
and(
and(and(nxor(sel[0], O), nxor(sel[1], I)), nxor(sel[2], I)),
input,
),
and(
and(and(nxor(sel[0], I), nxor(sel[1], O)), nxor(sel[2], O)),
input,
),
and(
and(and(nxor(sel[0], I), nxor(sel[1], O)), nxor(sel[2], I)),
input,
),
and(
and(and(nxor(sel[0], I), nxor(sel[1], I)), nxor(sel[2], O)),
input,
),
and(
and(and(nxor(sel[0], I), nxor(sel[1], I)), nxor(sel[2], I)),
input,
),
]
}
#[cfg(test)]
mod tests {
use super::{
and, and16, dmux, dmux4way, dmux8way, mux, mux16, nand, not, not16, or, or16, xor, Word,
};
use super::{
bit::{I, O},
or8way,
};
use crate::base::logic::mux2;
use crate::base::logic::mux3;
use crate::base::logic::mux4way16;
use crate::base::logic::mux8way16;
#[test]
fn for_nand() {
assert_eq!(nand(O, O), I);
assert_eq!(nand(I, O), I);
assert_eq!(nand(O, I), I);
assert_eq!(nand(I, I), O);
}
#[test]
fn for_not() {
assert_eq!(not(O), I);
assert_eq!(not(I), O);
}
#[test]
fn for_and() {
assert_eq!(and(O, O), O);
assert_eq!(and(I, O), O);
assert_eq!(and(O, I), O);
assert_eq!(and(I, I), I);
}
#[test]
fn for_or() {
assert_eq!(or(O, O), O);
assert_eq!(or(I, O), I);
assert_eq!(or(O, I), I);
assert_eq!(or(I, I), I);
}
#[test]
fn for_xor() {
assert_eq!(xor(O, O), O);
assert_eq!(xor(I, O), I);
assert_eq!(xor(O, I), I);
assert_eq!(xor(I, I), O);
}
#[test]
fn for_mux() {
assert_eq!(mux(O, O, O), O);
assert_eq!(mux(O, I, O), O);
assert_eq!(mux(I, O, O), I);
assert_eq!(mux(I, I, O), I);
assert_eq!(mux(O, O, I), O);
assert_eq!(mux(O, I, I), I);
assert_eq!(mux(I, O, I), O);
assert_eq!(mux(I, I, I), I);
}
#[test]
fn for_dmux() {
assert_eq!(dmux(O, O), [O, O]);
assert_eq!(dmux(O, I), [O, O]);
assert_eq!(dmux(I, O), [I, O]);
assert_eq!(dmux(I, I), [O, I]);
}
#[test]
fn for_not16() {
assert_eq!(not16(Word([O; 16])), Word([I; 16]));
assert_eq!(not16(Word([I; 16])), Word([O; 16]));
assert_eq!(
not16(Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])),
Word([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I])
);
assert_eq!(
not16(Word([I, I, I, O, I, O, I, O, I, O, I, O, I, I, I, O])),
Word([O, O, O, I, O, I, O, I, O, I, O, I, O, O, O, I])
);
}
#[test]
fn for_and16() {
assert_eq!(and16(Word([O; 16]), Word([O; 16])), Word([O; 16]));
assert_eq!(and16(Word([I; 16]), Word([O; 16])), Word([O; 16]));
assert_eq!(and16(Word([O; 16]), Word([I; 16])), Word([O; 16]));
assert_eq!(and16(Word([I; 16]), Word([I; 16])), Word([I; 16]));
assert_eq!(
and16(
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O]),
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])
),
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])
);
assert_eq!(
and16(
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O]),
Word([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I])
),
Word([O; 16])
);
}
#[test]
fn for_or16() {
assert_eq!(or16(Word([O; 16]), Word([O; 16])), Word([O; 16]));
assert_eq!(or16(Word([I; 16]), Word([O; 16])), Word([I; 16]));
assert_eq!(or16(Word([O; 16]), Word([I; 16])), Word([I; 16]));
assert_eq!(or16(Word([I; 16]), Word([I; 16])), Word([I; 16]));
assert_eq!(
or16(
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O]),
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])
),
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])
);
assert_eq!(
or16(
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O]),
Word([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I])
),
Word([I; 16])
);
}
#[test]
fn for_mux16() {
assert_eq!(mux16(Word([O; 16]), Word([O; 16]), O), Word([O; 16]));
assert_eq!(mux16(Word([O; 16]), Word([I; 16]), O), Word([O; 16]));
assert_eq!(mux16(Word([I; 16]), Word([O; 16]), O), Word([I; 16]));
assert_eq!(mux16(Word([I; 16]), Word([I; 16]), O), Word([I; 16]));
assert_eq!(mux16(Word([O; 16]), Word([O; 16]), I), Word([O; 16]));
assert_eq!(mux16(Word([I; 16]), Word([O; 16]), I), Word([O; 16]));
assert_eq!(mux16(Word([O; 16]), Word([I; 16]), I), Word([I; 16]));
assert_eq!(mux16(Word([I; 16]), Word([I; 16]), I), Word([I; 16]));
assert_eq!(
mux16(
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O]),
Word([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I]),
O
),
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])
);
assert_eq!(
mux16(
Word([I, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O]),
Word([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I]),
I
),
Word([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I])
);
}
#[test]
fn for_or8way() {
assert_eq!(or8way([O; 8]), O);
assert_eq!(or8way([I; 8]), I);
assert_eq!(or8way([O, O, O, O, O, O, O, I]), I);
assert_eq!(or8way([O, O, O, O, O, O, I, I]), I);
assert_eq!(or8way([O, O, I, O, O, O, I, I]), I);
assert_eq!(or8way([O, O, O, I, O, O, O, O]), I);
}
#[test]
fn for_mux2() {
assert_eq!(mux2(I, O, O, O, [O, O]), I);
assert_eq!(mux2(O, I, O, O, [O, I]), I);
assert_eq!(mux2(O, O, I, O, [I, O]), I);
assert_eq!(mux2(O, O, O, I, [I, I]), I);
}
#[test]
fn for_mux3() {
assert_eq!(mux3(I, O, O, O, O, O, O, O, [O, O, O]), I);
assert_eq!(mux3(O, I, O, O, O, O, O, O, [O, O, I]), I);
assert_eq!(mux3(O, O, I, O, O, O, O, O, [O, I, O]), I);
assert_eq!(mux3(O, O, O, I, O, O, O, O, [O, I, I]), I);
assert_eq!(mux3(O, O, O, O, I, O, O, O, [I, O, O]), I);
assert_eq!(mux3(O, O, O, O, O, I, O, O, [I, O, I]), I);
assert_eq!(mux3(O, O, O, O, O, O, I, O, [I, I, O]), I);
assert_eq!(mux3(O, O, O, O, O, O, O, I, [I, I, I]), I);
}
#[test]
fn for_mux4way16() {
let zero = Word::new([O; 16]);
let one = Word::new([I; 16]);
assert_eq!(mux4way16(one, zero, zero, zero, [O, O]), one);
assert_eq!(mux4way16(zero, one, zero, zero, [O, I]), one);
assert_eq!(mux4way16(zero, zero, one, zero, [I, O]), one);
assert_eq!(mux4way16(zero, zero, zero, one, [I, I]), one);
}
#[test]
fn for_mux8way16() {
let zero = Word::new([O; 16]);
let one = Word::new([I; 16]);
assert_eq!(
mux8way16(one, zero, zero, zero, zero, zero, zero, zero, [O, O, O]),
one
);
assert_eq!(
mux8way16(zero, one, zero, zero, zero, zero, zero, zero, [O, O, I]),
one
);
assert_eq!(
mux8way16(zero, zero, one, zero, zero, zero, zero, zero, [O, I, O]),
one
);
assert_eq!(
mux8way16(zero, zero, zero, one, zero, zero, zero, zero, [O, I, I]),
one
);
assert_eq!(
mux8way16(zero, zero, zero, zero, one, zero, zero, zero, [I, O, O]),
one
);
assert_eq!(
mux8way16(zero, zero, zero, zero, zero, one, zero, zero, [I, O, I]),
one
);
assert_eq!(
mux8way16(zero, zero, zero, zero, zero, zero, one, zero, [I, I, O]),
one
);
assert_eq!(
mux8way16(zero, zero, zero, zero, zero, zero, zero, one, [I, I, I]),
one
);
}
#[test]
fn for_dmux4way() {
assert_eq!(dmux4way(I, [O, O]), [I, O, O, O]);
assert_eq!(dmux4way(I, [O, I]), [O, I, O, O]);
assert_eq!(dmux4way(I, [I, O]), [O, O, I, O]);
assert_eq!(dmux4way(I, [I, I]), [O, O, O, I]);
}
#[test]
fn for_dmux8way() {
assert_eq!(dmux8way(I, [O, O, O]), [I, O, O, O, O, O, O, O]);
assert_eq!(dmux8way(I, [O, O, I]), [O, I, O, O, O, O, O, O]);
assert_eq!(dmux8way(I, [O, I, O]), [O, O, I, O, O, O, O, O]);
assert_eq!(dmux8way(I, [O, I, I]), [O, O, O, I, O, O, O, O]);
assert_eq!(dmux8way(I, [I, O, O]), [O, O, O, O, I, O, O, O]);
assert_eq!(dmux8way(I, [I, O, I]), [O, O, O, O, O, I, O, O]);
assert_eq!(dmux8way(I, [I, I, O]), [O, O, O, O, O, O, I, O]);
assert_eq!(dmux8way(I, [I, I, I]), [O, O, O, O, O, O, O, I]);
}
#[test]
fn for_word_from() {
assert_eq!(Word::from("0000000000000000"), Word::new([O; 16]));
assert_eq!(Word::from("1111111111111111"), Word::new([I; 16]));
assert_eq!(
Word::from("0101010101010101"),
Word::new([O, I, O, I, O, I, O, I, O, I, O, I, O, I, O, I])
);
assert_eq!(
Word::from("0010101010101010"),
Word::new([O, O, I, O, I, O, I, O, I, O, I, O, I, O, I, O])
);
}
#[test]
#[should_panic]
fn for_word_from2() {
Word::from("11");
}
#[test]
#[should_panic]
fn for_word_from3() {
Word::from("000000000000000a");
}
}
|
mod title;
mod level;
use core::mem::ManuallyDrop;
use crate::framebuffer::Framebuffer;
use crate::controller::Buttons;
pub struct GameState {
pub buttons: Buttons,
pub id: GameStateId,
pub data: GameStateData
}
pub enum GameStateId {
Init,
Title,
Level
}
pub union GameStateData {
init: (),
title: ManuallyDrop<title::TitleState>,
level: ManuallyDrop<level::LevelState>
}
impl GameState {
pub const fn new() -> Self {
Self {
buttons: Buttons::new(),
id: GameStateId::Init,
data: GameStateData { init: () }
}
}
pub fn as_level(&mut self) -> &mut level::LevelState {
unsafe { &mut self.data.level }
}
pub fn as_title(&mut self) -> &mut title::TitleState {
unsafe { &mut self.data.title }
}
pub fn run(&mut self, fb: &mut Framebuffer, b: u32) {
self.buttons.update(b);
let b = self.buttons;
match self.id {
GameStateId::Init => {
crate::data::init();
self.id = GameStateId::Title;
self.as_title().init_flag = true;
}
GameStateId::Title => {
self.as_title().run(fb,b);
},
GameStateId::Level => {
self.as_level().run(fb,b);
},
}
}
}
|
#[cfg(test)]
mod tests {
use cdl::{Data_new, Data_free};
#[test]
fn test_struct() {
let s = unsafe { Box::from_raw(Data_new()) };
Data_free(Box::into_raw(s));
}
} |
use ash::{
self,
version::{DeviceV1_0, FunctionPointers},
vk,
};
use device::{CommandBuffer, CommandQueue, Device};
use fence;
impl From<fence::FenceCreateFlags> for vk::FenceCreateFlags {
fn from(flags: fence::FenceCreateFlags) -> Self {
Self::from_flags(flags.bits()).expect("Unsupported flags")
}
}
impl<V> Device for ash::Device<V>
where
V: FunctionPointers,
ash::Device<V>: DeviceV1_0,
{
type Semaphore = vk::Semaphore;
type Fence = vk::Fence;
type Submit = vk::CommandBuffer;
type CommandPool = (vk::DeviceFnV1_0, vk::CommandBuffer);
type CommandBuffer = (vk::DeviceFnV1_0, vk::CommandBuffer);
type CommandQueue = vk::Queue;
unsafe fn create_fence(&self, info: fence::FenceCreateInfo) -> Self::Fence {
use std::ptr::null;
DeviceV1_0::create_fence(self, &vk::FenceCreateInfo {
s_type: vk::StructureType::FenceCreateInfo,
p_next: null(),
flags: info.flags.into(),
}, None).unwrap()
}
}
impl CommandBuffer for (vk::DeviceFnV1_0, vk::CommandBuffer) {
type Submit = vk::CommandBuffer;
unsafe fn submit(&self) -> Self::Submit {
self.1
}
}
impl CommandQueue for vk::Queue {
type Semaphore = vk::Semaphore;
type Fence = vk::Fence;
type Submit = vk::CommandBuffer;
}
|
// Copyright (c) 2013, 2014 Michael Woerister
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! This library contains some implementations of persistent data structures. Persistent
//! data structures, also called purely functional data structures, are always immutable from the
//! view of the user and can safely and easily be shared in a concurrent setting. For more
//! information see [Wikipedia](https://en.wikipedia.org/wiki/Persistent_data_structure) for
//! example.
#![feature(unsafe_destructor)]
#![feature(default_type_params)]
#![feature(macro_rules)]
#[cfg(test)]
extern crate test;
extern crate sync;
pub use hamt::GenericHamtMapIterator;
pub use hamt::HamtMap;
pub use hamt::CloningHamtMap;
mod hamt;
mod item_store;
#[cfg(test)]
mod testing;
#[cfg(test)]
mod rbtree;
/// A trait to represent persistent maps. Objects implementing this trait are supposed to be
/// cheaply copyable. Typically they can be seen as a kind of smart pointer with similar performance
/// characteristics.
pub trait PersistentMap<K, V>: Map<K, V> + Clone {
/// Inserts a key-value pair into the map. An existing value for a
/// key is replaced by the new value. The first tuple element of the return value is the new
/// map instance representing the map after the insertion. The second tuple element is true if
/// the size of the map was changed by the operation and false otherwise.
fn insert(self, key: K, value: V) -> (Self, bool);
/// Removes a key-value pair from the map. The first tuple element of the return value is the new
/// map instance representing the map after the insertion. The second tuple element is true if
/// the size of the map was changed by the operation and false otherwise.
fn remove(self, key: &K) -> (Self, bool);
/// Inserts a key-value pair into the map. Same as `insert()` but with a return type that's
/// better suited to chaining multiple calls together.
fn plus(self, key: K, val: V) -> Self {
self.insert(key, val).val0()
}
/// Removes a key-value pair from the map. Same as `remove()` but with a return type that's
/// better suited to chaining multiple call together
fn minus(self, key: &K) -> Self {
self.remove(key).val0()
}
}
/// A trait to represent persistent sets. Objects implementing this trait are supposed to be
/// cheaply copyable. Typically they can be seen as a kind of smart pointer with similar performance
/// characteristics.
pub trait PersistentSet<K>: Set<K> + Clone {
/// Inserts a value into the set. The first tuple element of the return value is the new
/// map instance representing the set after the insertion. The second tuple element is true if
/// the size of the map was changed by the operation and false otherwise.
fn insert(self, value: K) -> (Self, bool);
/// Removes a value from the set. The first tuple element of the return value is the new
/// map instance representing the map after the insertion. The second tuple element is true if
/// the size of the map was changed by the operation and false otherwise.
fn remove(self, key: &K) -> (Self, bool);
/// Inserts a value into the set. Same as `insert()` but with a return type that's
/// better suited to chaining multiple calls together.
fn plus(self, key: K) -> Self {
self.insert(key).val0()
}
/// Removes a value from the set. Same as `remove()` but with a return type that's
/// better suited to chaining multiple call together
fn minus(self, key: &K) -> Self {
self.remove(key).val0()
}
}
|
use std::io;
// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)
/**********Converts between Fahrenheit and Celsius*********/
fn main() -> () {
println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
let mut convert_type = String::new();
io::stdin()
.read_line(&mut convert_type)
.expect("Failed to conversion type.");
let t = String::from(convert_type);
println!("You want to convert to: {}", t);
println!("What temperature would you like to convert?");
let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read temperature.");
let temp: i32 = match temp.trim().parse() {
Ok(temp) => temp,
Err(_e) => -1,
};
match t.as_str() {
"C\n" => println!("{}", ftoc(temp)),
"F\n" => println!("{}", ctof(temp)),
_ => println!("t = {:?}", t),
}
}
// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
(c * (9 / 5)) + 32
}
//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
(f - 32) * (5 / 9)
}
|
use task::Task;
use worker;
use crossbeam_deque::Injector;
use futures::task::AtomicTask;
use futures::{Async, Future, Poll};
use std::sync::{Arc, Mutex};
/// Future that resolves when the thread pool is shutdown.
///
/// A `ThreadPool` is shutdown once all the worker have drained their queues and
/// shutdown their threads.
///
/// `Shutdown` is returned by [`shutdown`], [`shutdown_on_idle`], and
/// [`shutdown_now`].
///
/// [`shutdown`]: struct.ThreadPool.html#method.shutdown
/// [`shutdown_on_idle`]: struct.ThreadPool.html#method.shutdown_on_idle
/// [`shutdown_now`]: struct.ThreadPool.html#method.shutdown_now
#[derive(Debug)]
pub struct Shutdown {
inner: Arc<Mutex<Inner>>,
}
/// Shared state between `Shutdown` and `ShutdownTrigger`.
///
/// This is used for notifying the `Shutdown` future when `ShutdownTrigger` gets dropped.
#[derive(Debug)]
struct Inner {
/// The task to notify when the threadpool completes the shutdown process.
task: AtomicTask,
/// `true` if the threadpool has been shut down.
completed: bool,
}
impl Shutdown {
pub(crate) fn new(trigger: &ShutdownTrigger) -> Shutdown {
Shutdown {
inner: trigger.inner.clone(),
}
}
}
impl Future for Shutdown {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
let inner = self.inner.lock().unwrap();
if !inner.completed {
inner.task.register();
Ok(Async::NotReady)
} else {
Ok(().into())
}
}
}
/// When dropped, cleans up threadpool's resources and completes the shutdown process.
#[derive(Debug)]
pub(crate) struct ShutdownTrigger {
inner: Arc<Mutex<Inner>>,
workers: Arc<[worker::Entry]>,
queue: Arc<Injector<Arc<Task>>>,
}
unsafe impl Send for ShutdownTrigger {}
unsafe impl Sync for ShutdownTrigger {}
impl ShutdownTrigger {
pub(crate) fn new(
workers: Arc<[worker::Entry]>,
queue: Arc<Injector<Arc<Task>>>,
) -> ShutdownTrigger {
ShutdownTrigger {
inner: Arc::new(Mutex::new(Inner {
task: AtomicTask::new(),
completed: false,
})),
workers,
queue,
}
}
}
impl Drop for ShutdownTrigger {
fn drop(&mut self) {
// Drain the global task queue.
while !self.queue.steal().is_empty() {}
// Drop the remaining incomplete tasks and parkers assosicated with workers.
for worker in self.workers.iter() {
worker.shutdown();
}
// Notify the task interested in shutdown.
let mut inner = self.inner.lock().unwrap();
inner.completed = true;
inner.task.notify();
}
}
|
#![recursion_limit = "128"]
use inflector::Inflector;
use quote::quote;
use syn::export::{Span, TokenStream2};
use syn::spanned::Spanned;
use syn::{Error, FnArg, Ident, ItemTrait, LitByteStr, LitStr, Pat, TraitItem};
pub fn process_trait(t: &ItemTrait, mod_name: Option<String>) -> syn::Result<TokenStream2> {
let mod_name = mod_name.unwrap_or_else(|| t.ident.to_string().to_snake_case());
let mod_name = Ident::new(&mod_name, Span::call_site());
let mut res = TokenStream2::new();
for item in &t.items {
match item {
TraitItem::Type(_) => {
return Err(Error::new(
item.span(),
"Traits for external contracts do not support associated trait types yet.",
))
}
TraitItem::Method(method) => {
if method.default.is_some() {
return Err(Error::new(
method.span(),
"Traits that are used to describe external contract should not include\
default implementations because this is not a valid use case of traits\
to describe external contracts.",
));
}
let sig = &method.sig;
if sig.unsafety.is_some() {
return Err(Error::new(
method.span(),
"Methods of external contracts are not allowed to be unsafe.",
));
}
if sig.asyncness.is_some() {
return Err(Error::new(
method.span(),
"Methods of external contracts are not allowed to be async.",
));
}
if sig.abi.is_some() {
return Err(Error::new(
method.span(),
"Methods of external contracts are not allowed to have binary interface.",
));
}
if !sig.generics.params.is_empty() {
return Err(Error::new(
method.span(),
"Methods of external contracts are not allowed to have generics.",
));
}
if sig.variadic.is_some() {
return Err(Error::new(
method.span(),
"Methods of external contracts are not allowed to have variadic arguments.",
));
}
let method_name = &sig.ident;
let inputs = &sig.inputs;
let method_name_byte_str =
LitByteStr::new(sig.ident.to_string().as_bytes(), Span::call_site());
let mut arg_to_json = TokenStream2::new();
let mut method_args = TokenStream2::new();
let num_args = inputs.len();
for (i, arg) in inputs.iter().enumerate() {
match arg {
FnArg::Receiver(_) => {}
FnArg::Typed(arg) => {
let arg_name = if let Pat::Ident(arg_name) = arg.pat.as_ref() {
&arg_name.ident
} else {
return Err(Error::new(
arg.span(),
"Unsupported argument name pattern.",
));
};
let arg_name_quoted =
LitStr::new(&arg_name.to_string(), Span::call_site());
arg_to_json.extend(quote! {
#arg_name_quoted: #arg_name
});
method_args.extend(quote! {
#arg ,
});
if i < num_args - 1 {
arg_to_json.extend(quote! {,});
}
}
}
}
if arg_to_json.is_empty() {
arg_to_json = quote! {vec![]};
} else {
arg_to_json = quote! {json!({ #arg_to_json }).to_string().as_bytes().to_vec()};
}
res.extend( quote! {
pub fn #method_name<T: ToString>(#method_args __account_id: &T, __balance: Balance, __gas: Gas) -> Promise {
Promise::new(__account_id.to_string())
.function_call(
#method_name_byte_str.to_vec(),
#arg_to_json,
__balance,
__gas,
)
}
});
}
_ => (),
}
}
Ok(quote! {
pub mod #mod_name {
use super::*;
use near_bindgen::{Gas, Balance, AccountId, Promise};
use std::string::ToString;
#res
}
})
}
// Rustfmt removes comas.
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use syn::ItemTrait;
use quote::quote;
use crate::process_trait;
#[test]
fn standard() {
let t: ItemTrait = syn::parse2(
quote!{
pub trait ExternalCrossContract {
fn merge_sort(&self, arr: Vec<u8>) -> Vec<u8>;
fn merge(&self) -> Vec<u8>;
}
}
).unwrap();
let actual = process_trait(&t, None).unwrap();
let expected = quote! {
pub mod external_cross_contract {
use super::*;
use near_bindgen::{Gas, Balance, AccountId, Promise};
use std::string::ToString;
pub fn merge_sort<T: ToString>(arr: Vec<u8>, __account_id: &T, __balance: Balance, __gas: Gas) -> Promise {
Promise::new(__account_id.to_string())
.function_call(
b"merge_sort".to_vec(),
json!({ "arr": arr }).to_string().as_bytes().to_vec(),
__balance,
__gas,
)
}
pub fn merge<T: ToString>(__account_id: &T, __balance: Balance, __gas: Gas) -> Promise {
Promise::new(__account_id.to_string())
.function_call(
b"merge".to_vec(),
vec![],
__balance,
__gas,
)
}
}
};
assert_eq!(actual.to_string(), expected.to_string());
}
}
|
#![allow(clippy::all)]
use std::collections::{HashMap, HashSet};
type Cave<'a> = &'a str;
type CaveMap<'a> = HashMap<Cave<'a>, Vec<Cave<'a>>>;
type SmallCaveSet<'a> = HashSet<Cave<'a>>;
pub fn part1(input: String) {
let (mut cave_map, mut small_caves) = parse_input(&input);
let mut all_paths = 0;
let mut root_path = vec![];
follow(
&mut all_paths,
&mut small_caves,
&mut cave_map,
&mut root_path,
"start",
true,
);
println!("Number of paths: {}", all_paths);
}
pub fn part2(input: String) {
let (mut cave_map, mut small_caves) = parse_input(&input);
let mut all_paths = 0;
let mut root_path = vec![];
follow(
&mut all_paths,
&mut small_caves,
&mut cave_map,
&mut root_path,
"start",
false,
);
println!("Number of paths: {}", all_paths);
}
fn parse_input(input: &str) -> (CaveMap, SmallCaveSet) {
let mut cave_map = CaveMap::new();
let mut small_caves = SmallCaveSet::new();
input.trim().split("\n").for_each(|l| {
let mut parts = l.trim().split("-");
let left = parts.next().unwrap();
if left.chars().next().unwrap().is_lowercase() {
small_caves.insert(left);
}
let right = parts.next().unwrap();
if right.chars().next().unwrap().is_lowercase() {
small_caves.insert(right);
}
if left != "end" && right != "start" {
insert_edge(&mut cave_map, left, right);
}
if right != "end" && left != "start" {
insert_edge(&mut cave_map, right, left);
}
});
(cave_map, small_caves)
}
fn insert_edge<'a>(cave_map: &mut CaveMap<'a>, from: Cave<'a>, to: Cave<'a>) {
if let Some(neighbors) = cave_map.get_mut(from) {
neighbors.push(to);
} else {
cave_map.insert(from, vec![to]);
}
}
fn follow<'a>(
all_paths: &mut usize,
small_caves: &mut HashSet<Cave<'a>>,
map: &CaveMap<'a>,
path: &mut Vec<Cave<'a>>,
to: Cave<'a>,
double_visit_used: bool,
) {
let mut next_double_visit_used = double_visit_used;
path.push(to);
if to == "end" {
*all_paths += 1;
return;
}
if to.chars().next().unwrap().is_lowercase() {
if !small_caves.remove(to) {
if double_visit_used {
return;
}
next_double_visit_used = true;
}
}
let original_length = path.len();
for c in map.get(to).unwrap() {
follow(all_paths, small_caves, map, path, c, next_double_visit_used);
path.truncate(original_length);
}
if to.clone().to_lowercase() == to && next_double_visit_used == double_visit_used {
small_caves.insert(to);
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn simple_mocked_cave_map() {
let mut cave_map = CaveMap::new();
cave_map.insert("start", vec!["A", "b"]);
cave_map.insert("A", vec!["c", "end", "b"]);
cave_map.insert("c", vec!["A"]);
cave_map.insert("b", vec!["A", "d", "end"]);
cave_map.insert("d", vec![]);
cave_map.insert("end", vec![]);
let mut small_caves = SmallCaveSet::new();
small_caves.insert("c");
small_caves.insert("b");
small_caves.insert("d");
let mut all_paths = 0;
let mut root_path = vec![];
follow(
&mut all_paths,
&mut small_caves,
&mut cave_map,
&mut root_path,
"start",
false,
);
assert_eq!(10, all_paths);
}
}
|
use proconio::input;
fn main() {
input! {
n: usize,
h: u32,
x: u32,
p: [u32; n],
};
for i in 0..n {
if h + p[i] >= x {
println!("{}", i + 1);
return;
}
}
unreachable!();
}
|
use std::{
io,
net::{ToSocketAddrs, TcpListener, TcpStream, SocketAddr},
thread,
sync::{mpsc, Arc, Mutex},
};
pub fn listen<A, F, H>(addr: A, factory: F) -> io::Result<()>
where
A: ToSocketAddrs,
F: FnMut() -> H,
F: Send + Sync + 'static,
H: Handler
{
Builder::new().bind(addr)?.build(factory).run()
}
#[derive(Debug)]
pub struct LajiDiscard<F>
where F: Factory
{
tcp: Vec<TcpListener>,
factory: F
}
impl<F> LajiDiscard<F>
where
F: 'static + Factory + Send + Sync
{
pub fn run(self) -> io::Result<()> {
let (err_tx, err_rx) = mpsc::channel();
let factory = Arc::new(Mutex::new(self.factory));
for listener in self.tcp {
let err_tx = err_tx.clone();
let listener = listener.try_clone()?;
let factory = Arc::clone(&factory);
thread::spawn(move || {
for stream in listener.incoming() {
process_one_stream(factory.clone(), stream)
.unwrap_or_else(|e| err_tx.send(e).unwrap())
}
});
}
while let Ok(err) = err_rx.recv() {
return Err(err);
}
Ok(())
}
}
fn process_one_stream<F>(factory: Arc<Mutex<F>>, stream: io::Result<TcpStream>) -> io::Result<()>
where F: Factory
{
let mut handler = factory.lock().unwrap().connection_made();
let stream = stream?;
handler.on_open(Handshake::read_stream(&stream)?);
drop(stream);
handler.on_close();
Ok(())
}
#[derive(Debug)]
pub struct Builder {
tcp: Vec<TcpListener>,
}
impl Builder {
pub fn new() -> Self {
Self { tcp: Vec::new() }
}
pub fn bind<A>(mut self, addr: A) -> io::Result<Builder>
where A: ToSocketAddrs
{
let new_listener = TcpListener::bind(addr)?;
self.tcp.push(new_listener);
Ok(self)
}
pub fn build<F>(self, factory: F) -> LajiDiscard<F>
where F: Factory
{
LajiDiscard {
tcp: self.tcp,
factory,
}
}
}
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub struct Handshake {
peer_addr: SocketAddr,
local_addr: SocketAddr,
}
impl Handshake {
#[inline]
fn read_stream(ts: &TcpStream) -> io::Result<Self> {
Ok(Self {
peer_addr: ts.peer_addr()?,
local_addr: ts.local_addr()?,
})
}
#[inline]
pub fn peer_addr(&self) -> &SocketAddr {
&self.peer_addr
}
#[inline]
pub fn local_addr(&self) -> &SocketAddr {
&self.local_addr
}
}
pub trait Handler {
fn on_open(&mut self, _shake: Handshake) {}
fn on_close(&mut self) {}
}
impl<F> Handler for F
where F: FnMut(Handshake) {
fn on_open(&mut self, shake: Handshake) {
self(shake)
}
fn on_close(&mut self) {}
}
pub trait Factory {
type Handler: Handler;
fn connection_made(&mut self) -> Self::Handler;
}
impl<F, H> Factory for F
where H: Handler, F: FnMut() -> H {
type Handler = H;
fn connection_made(&mut self) -> H {
self()
}
}
#[cfg(test)]
mod tests {
mod laji_discard {
pub use super::super::*;
}
use std::thread;
use std::net::TcpStream;
#[test]
fn listen() {
laji_discard::listen("0.0.0.0:9", move || {
|shake: super::Handshake| {
println!("Remote {} connected to {}", shake.peer_addr(), shake.local_addr());
}
}).unwrap();
}
#[test]
fn test_listen() {
thread::spawn(move || {
laji_discard::listen("0.0.0.0:9", move || {
|shake: super::Handshake| {
println!("Remote {} connected to {}", shake.peer_addr(), shake.local_addr());
}
}).unwrap();
});
TcpStream::connect("127.0.0.1:9").unwrap();
}
#[test]
fn test_batch() -> std::io::Result<()> {
use super::*;
struct MyFactory;
impl Factory for MyFactory {
type Handler = MyHandler;
fn connection_made(&mut self) -> MyHandler {
MyHandler(None)
}
}
struct MyHandler(Option<Handshake>);
impl Handler for MyHandler {
fn on_open(&mut self, shake: Handshake) {
println!("Remote {} connected to {}", shake.peer_addr(), shake.local_addr());
self.0 = Some(shake);
}
fn on_close(&mut self) {
let shake = self.0.unwrap();
println!("Closed remote {} at {}!", shake.peer_addr(), shake.local_addr());
}
}
thread::spawn(move || {
Builder::new()
.bind("0.0.0.0:9").unwrap()
.bind("0.0.0.0:9999").unwrap()
.build(MyFactory)
.run().unwrap();
});
TcpStream::connect("127.0.0.1:9").unwrap();
TcpStream::connect("127.0.0.1:9").unwrap();
TcpStream::connect("127.0.0.1:9999").unwrap();
Ok(())
}
}
|
#![allow(non_snake_case)]
use std::fmt;
use std::mem;
use std::slice;
use num;
use approx;
use channel::{PosFreeChannel, FreeChannelScalar, AngularChannel, AngularChannelScalar,
ChannelFormatCast, ChannelCast, ColorChannel};
use angle::{Deg, Angle, FromAngle, IntoAngle, Turns, Rad};
use angle;
use color::{Color, PolarColor, FromTuple, Lerp, Bounded, Flatten};
use convert::{GetHue, GetChroma, FromColor};
use luv::Luv;
pub struct LchuvTag;
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Lchuv<T, A = Deg<T>> {
pub L: PosFreeChannel<T>,
pub chroma: PosFreeChannel<T>,
pub hue: AngularChannel<A>,
}
impl<T, A> Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
pub fn from_channels(L: T, chroma: T, hue: A) -> Self {
Lchuv {
L: PosFreeChannel::new(L),
chroma: PosFreeChannel::new(chroma),
hue: AngularChannel::new(hue),
}
}
impl_color_color_cast_angular!(Lchuv {L, chroma, hue},
chan_traits={FreeChannelScalar});
pub fn L(&self) -> T {
self.L.0.clone()
}
pub fn chroma(&self) -> T {
self.chroma.0.clone()
}
pub fn hue(&self) -> A {
self.hue.0.clone()
}
pub fn L_mut(&mut self) -> &mut T {
&mut self.L.0
}
pub fn chroma_mut(&mut self) -> &mut T {
&mut self.chroma.0
}
pub fn hue_mut(&mut self) -> &mut A {
&mut self.hue.0
}
pub fn set_L(&mut self, val: T) {
self.L.0 = val;
}
pub fn set_chroma(&mut self, val: T) {
self.chroma.0 = val;
}
pub fn set_hue(&mut self, val: A) {
self.hue.0 = val;
}
}
impl<T, A> Color for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
type Tag = LchuvTag;
type ChannelsTuple = (T, T, A);
fn num_channels() -> u32 {
3
}
fn to_tuple(self) -> Self::ChannelsTuple {
(self.L.0, self.chroma.0, self.hue.0)
}
}
impl<T, A> PolarColor for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
type Angular = A;
type Cartesian = T;
}
impl<T, A> FromTuple for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
fn from_tuple(values: Self::ChannelsTuple) -> Self {
Lchuv::from_channels(values.0, values.1, values.2)
}
}
impl<T, A> Lerp for Lchuv<T, A>
where T: FreeChannelScalar + Lerp,
A: AngularChannelScalar + Lerp
{
type Position = A::Position;
impl_color_lerp_angular!(Lchuv<T> {hue, L, chroma});
}
impl<T, A> Bounded for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
impl_color_bounded!(Lchuv {L, chroma, hue});
}
impl<T, A> Flatten for Lchuv<T, A>
where T: FreeChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T> + FromAngle<Turns<T>>
{
type ScalarFormat = T;
impl_color_as_slice!(T);
fn from_slice(vals: &[T]) -> Self {
Lchuv::from_channels(vals[0].clone(),
vals[1].clone(),
A::from_angle(angle::Turns(vals[2].clone())))
}
}
impl<T, A> approx::ApproxEq for Lchuv<T, A>
where T: FreeChannelScalar + approx::ApproxEq<Epsilon = A::Epsilon>,
A: AngularChannelScalar + approx::ApproxEq,
A::Epsilon: Clone + num::Float
{
impl_approx_eq!({L, chroma, hue});
}
impl<T, A> Default for Lchuv<T, A>
where T: FreeChannelScalar + num::Zero,
A: AngularChannelScalar + num::Zero
{
impl_color_default!(Lchuv {hue: AngularChannel,
L: PosFreeChannel, chroma: PosFreeChannel});
}
impl<T, A> fmt::Display for Lchuv<T, A>
where T: FreeChannelScalar + fmt::Display,
A: AngularChannelScalar + fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Lch(uv)({}, {}, {})", self.L, self.chroma, self.hue)
}
}
impl<T, A> GetChroma for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
type ChromaType = T;
fn get_chroma(&self) -> T {
return self.chroma();
}
}
impl<T, A> GetHue for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar
{
impl_color_get_hue_angular!(Lchuv);
}
impl<T, A> FromColor<Luv<T>> for Lchuv<T, A>
where T: FreeChannelScalar,
A: AngularChannelScalar + FromAngle<Rad<T>> + Angle
{
fn from_color(from: &Luv<T>) -> Self {
let L = from.L();
let c = (from.u() * from.u() + from.v() * from.v()).sqrt();
let h = A::from_angle(Rad::atan2(from.v(), from.u()));
Lchuv::from_channels(L, c, <A as Angle>::normalize(h))
}
}
impl<T, A> FromColor<Lchuv<T, A>> for Luv<T>
where T: FreeChannelScalar,
A: AngularChannelScalar + Angle<Scalar = T>
{
fn from_color(from: &Lchuv<T, A>) -> Self {
let L = from.L();
let u = from.chroma() * from.hue().cos();
let v = from.chroma() * from.hue().sin();
Luv::from_channels(L, u, v)
}
}
#[cfg(test)]
mod test {
use super::*;
use luv::Luv;
use angle::*;
use convert::*;
use color::*;
#[test]
fn test_construct() {
let c1 = Lchuv::from_channels(60.0, 30.0, Turns(0.33));
assert_relative_eq!(c1.L(), 60.0);
assert_relative_eq!(c1.chroma(), 30.0);
assert_relative_eq!(c1.hue(), Turns(0.33));
assert_eq!(c1.to_tuple(), (60.0, 30.0, Turns(0.33)));
assert_relative_eq!(Lchuv::from_tuple(c1.to_tuple()), c1);
}
#[test]
fn test_lerp() {
let c1 = Lchuv::from_channels(50.0, 70.0, Deg(120.0));
let c2 = Lchuv::from_channels(00.0, 80.0, Deg(0.0));
assert_relative_eq!(c1.lerp(&c2, 0.0), c1);
assert_relative_eq!(c1.lerp(&c2, 1.0), c2);
assert_relative_eq!(c2.lerp(&c1, 1.0), c1);
assert_relative_eq!(c1.lerp(&c2, 0.5), Lchuv::from_channels(25.0, 75.0, Deg(60.0)));
assert_relative_eq!(c1.lerp(&c2, 0.75), Lchuv::from_channels(12.5, 77.5, Deg(30.0)));
let c3 = Lchuv::from_channels(20.0, 60.0, Deg(150.0));
let c4 = Lchuv::from_channels(50.0, 100.0, Deg(350.0));
assert_relative_eq!(c3.lerp(&c4, 0.0), c3);
assert_relative_eq!(c3.lerp(&c4, 1.0), c4);
assert_relative_eq!(c3.lerp(&c4, 0.5), Lchuv::from_channels(35.0, 80.0, Deg(70.0)));
assert_relative_eq!(c3.lerp(&c4, 0.25), Lchuv::from_channels(27.5, 70.0, Deg(110.0)));
}
#[test]
fn test_normalize() {
let c1 = Lchuv::from_channels(111.1, 222.2, Deg(333.3));
assert!(c1.is_normalized());
assert_relative_eq!(c1.normalize(), c1);
let c2 = Lchuv::from_channels(-50.5, -100.0, Deg(50.0));
assert!(!c2.is_normalized());
assert_relative_eq!(c2.normalize(), Lchuv::from_channels(0.0, 0.0, Deg(50.0)));
let c3 = Lchuv::from_channels(20.0, 60.0, Turns(-1.25));
assert!(!c3.is_normalized());
assert_relative_eq!(c3.normalize(), Lchuv::from_channels(20.0, 60.0, Turns(0.75)));
let c4 = Lchuv::from_channels(60.0, -10.0, Deg(500.0));
assert!(!c4.is_normalized());
assert_relative_eq!(c4.normalize(), Lchuv::from_channels(60.0, 0.0, Deg(140.0)));
}
#[test]
fn test_flatten() {
let c1 = Lchuv::from_channels(55.0, 23.0, Turns(0.5));
assert_eq!(c1.as_slice(), &[55.0, 23.0, 0.5]);
assert_relative_eq!(Lchuv::from_slice(c1.as_slice()), c1);
}
#[test]
fn test_get_chroma() {
let c1 = Lchuv::from_channels(50.0, 25.0, Deg(65.5));
assert_relative_eq!(c1.chroma(), 25.0);
}
#[test]
fn test_get_hue() {
let c1 = Lchuv::from_channels(22.0, 98.0, Deg(120.0));
assert_relative_eq!(c1.get_hue(), Deg(120.0));
assert_relative_eq!(c1.get_hue(), Turns(1.0/3.0));
}
#[test]
fn test_from_luv() {
let c1 = Luv::from_channels(60.0, 30.0, -30.0);
let t1 = Lchuv::from_color(&c1);
assert_relative_eq!(t1, Lchuv::from_channels(60.0, 42.4264, Deg(315.0)), epsilon=1e-4);
assert_relative_eq!(Luv::from_color(&t1), c1, epsilon=1e-4);
let c2 = Luv::from_channels(75.0, 0.0, 100.0);
let t2 = Lchuv::from_color(&c2);
assert_relative_eq!(t2, Lchuv::from_channels(75.0, 100.0, Deg(90.0)), epsilon=1e-4);
assert_relative_eq!(Luv::from_color(&t2), c2, epsilon=1e-4);
let c3 = Luv::from_channels(50.0, -45.0, -30.0);
let t3 = Lchuv::from_color(&c3);
assert_relative_eq!(t3, Lchuv::from_channels(50.0, 54.0833, Deg(213.6901)), epsilon=1e-4);
assert_relative_eq!(Luv::from_color(&t3), c3, epsilon=1e-4);
let c4 = Luv::from_channels(0.0, 0.0, 0.0);
let t4 = Lchuv::from_color(&c4);
assert_relative_eq!(t4, Lchuv::from_channels(0.0, 0.0, Rad(0.0)), epsilon=1e-4);
assert_relative_eq!(Luv::from_color(&t4), c4, epsilon=1e-4);
let c5 = Luv::from_channels(72.0, -100.0, -100.0);
let t5 = Lchuv::from_color(&c5);
assert_relative_eq!(t5, Lchuv::from_channels(72.0, 141.4214, Deg(225.0)), epsilon=1e-4);
assert_relative_eq!(Luv::from_color(&t5), c5, epsilon=1e-4);
let c6 = Luv::from_channels(88.0, 0.0, 0.0);
let t6 = Lchuv::from_color(&c6);
assert_relative_eq!(t6, Lchuv::from_channels(88.0, 0.0, Deg(0.0)), epsilon=1e-6);
assert_relative_eq!(Luv::from_color(&t6), c6, epsilon=1e-4);
}
#[test]
fn test_to_luv() {
let c1 = Lchuv::from_channels(50.0, 70.0, Turns(0.5));
let t1 = Luv::from_color(&c1);
assert_relative_eq!(t1, Luv::from_channels(50.0, -70.0, 0.0), epsilon=1e-4);
assert_relative_eq!(Lchuv::from_color(&t1), c1, epsilon=1e-4);
let c2 = Lchuv::from_channels(66.0, 75.0, Deg(35.35335335));
let t2 = Luv::from_color(&c2);
assert_relative_eq!(t2, Luv::from_channels(66.0, 61.1699, 43.3963), epsilon=1e-4);
assert_relative_eq!(Lchuv::from_color(&t2), c2, epsilon=1e-4);
let c3 = Lchuv::from_channels(100.0, 100.0, Deg(155.0));
let t3 = Luv::from_color(&c3);
assert_relative_eq!(t3, Luv::from_channels(100.0, -90.6308, 42.2618), epsilon=1e-4);
assert_relative_eq!(Lchuv::from_color(&t3), c3, epsilon=1e-4);
let c4 = Lchuv::from_channels(23.0, 70.0, Deg(222.0));
let t4 = Luv::from_color(&c4);
assert_relative_eq!(t4, Luv::from_channels(23.0, -52.0201, -46.8391), epsilon=1e-4);
assert_relative_eq!(Lchuv::from_color(&t4), c4, epsilon=1e-4);
}
#[test]
fn test_color_cast() {
let c1 = Lchuv::from_channels(88.0, 31.0, Deg(180.0));
assert_relative_eq!(c1.color_cast(), c1);
assert_relative_eq!(c1.color_cast::<f32, Turns<f32>>(),
Lchuv::from_channels(88.0f32, 31.0f32, Turns(0.5f32)));
assert_relative_eq!(c1.color_cast::<f32, Rad<f32>>().color_cast(), c1);
}
}
|
//! A fantastically advanced mathematical librarie
/// Double a value
pub fn add_two(n: i64) -> i64 {
n + 2
}
#[test]
fn smoketest() {
assert_eq!(add_two(2), 4);
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
/// `*/2` infix operator
#[native_implemented::function(erlang:*/2)]
pub fn result(process: &Process, multiplier: Term, multiplicand: Term) -> exception::Result<Term> {
number_infix_operator!(multiplier, multiplicand, process, checked_mul, *)
}
|
use super::Span;
use std::num::ParseFloatError;
use unit::Unit;
#[derive(Debug, Clone)]
pub struct Expression {
pub span: Span,
pub expression: ExpressionEnum,
}
impl PartialEq for Expression {
fn eq(&self, other: &Expression) -> bool {
self.expression == other.expression
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExpressionEnum {
Constant(f32),
Unit(Unit),
Add,
Minus,
Multiply,
Divide,
Block(Vec<Expression>),
}
struct Reader {
str: Vec<char>,
index: usize,
}
impl<'a> From<&'a str> for Reader {
fn from(s: &str) -> Reader {
Reader {
str: s.chars().collect(),
index: 0,
}
}
}
impl Reader {
pub fn take(&mut self) -> Option<char> {
let result = self.peek();
self.index += 1;
result
}
pub fn peek(&mut self) -> Option<char> {
self.str.get(self.index).cloned()
}
pub fn is_at_eof(&self) -> bool {
self.index >= self.str.len()
}
}
const OPERATORS: &[(char, ExpressionEnum)] = &[
('*', ExpressionEnum::Multiply),
('/', ExpressionEnum::Divide),
('-', ExpressionEnum::Minus),
('+', ExpressionEnum::Add),
];
impl Expression {
pub fn parse(input: impl AsRef<str>) -> Result<Expression, ParseError> {
let mut reader: Reader = input.as_ref().into();
let mut result = Vec::new();
while let Some(e) = Expression::parse_impl(&mut reader)? {
result.push(e);
}
if result.is_empty() {
Err(ParseError::UnexpectedEnd)
} else if !reader.is_at_eof() {
Err(ParseError::TrailingTokens {
span: Span {
from: reader.index,
to: reader.str.len(),
},
})
} else if result.len() == 1 {
let first = result.into_iter().next().unwrap();
Ok(first)
} else {
Ok(Expression {
span: Span {
from: 0,
to: reader.index,
},
expression: ExpressionEnum::Block(result),
})
}
}
fn parse_block(reader: &mut Reader) -> Result<Option<Expression>, ParseError> {
let start_index = reader.index;
let start = reader.take().unwrap();
let end_token = if start == '(' {
')'
} else if start == '[' {
']'
} else {
'}'
};
let mut inner = Vec::new();
while let Some(child) = Expression::parse_impl(reader)? {
inner.push(child);
}
if reader.take() != Some(end_token) {
return Err(ParseError::MissingEndBracket {
start_bracket: start,
span: Span {
from: start_index,
to: reader.index,
},
});
}
Ok(Some(Expression {
span: Span {
from: start_index,
to: reader.index,
},
expression: ExpressionEnum::Block(inner),
}))
}
fn parse_impl(reader: &mut Reader) -> Result<Option<Expression>, ParseError> {
let mut c = match reader.peek() {
Some(c) => c,
None => return Ok(None),
};
while c.is_whitespace() {
reader.take();
c = match reader.peek() {
Some(c) => c,
None => return Ok(None),
};
}
let operator = OPERATORS.iter().find(|o| o.0 == c);
if let Some(operator) = operator {
reader.take();
return Ok(Some(Expression {
span: Span {
from: reader.index - 1,
to: reader.index,
},
expression: operator.1.clone(),
}));
} else if c == '(' || c == '[' || c == '{' {
Expression::parse_block(reader)
} else if c == ')' || c == ']' || c == '}' {
Ok(None)
} else if c.is_numeric() || c == '-' {
let mut str = c.to_string();
let start_index = reader.index;
reader.take();
while let Some(c) = reader.peek() {
if c.is_numeric() || c == '.' {
str.push(c);
reader.take();
} else if c == '_' {
continue;
} else {
break;
}
}
match str.parse() {
Err(e) => Err(ParseError::ParseFloatError {
span: Span {
from: start_index,
to: reader.index,
},
error: e,
}),
Ok(v) => Ok(Some(Expression {
span: Span {
from: start_index,
to: reader.index,
},
expression: ExpressionEnum::Constant(v),
})),
}
} else {
Err(ParseError::InvalidToken {
token: c,
span: Span {
from: reader.index,
to: reader.index + 1,
},
})
}
}
}
#[derive(Debug)]
pub enum ParseError {
UnexpectedEnd,
TrailingTokens { span: Span },
InvalidToken { span: Span, token: char },
MissingEndBracket { start_bracket: char, span: Span },
ParseFloatError { span: Span, error: ParseFloatError },
}
impl ParseError {
pub fn get_span(&self) -> Option<Span> {
match *self {
ParseError::TrailingTokens { span, .. }
| ParseError::InvalidToken { span, .. }
| ParseError::MissingEndBracket { span, .. }
| ParseError::ParseFloatError { span, .. } => Some(span),
ParseError::UnexpectedEnd => None,
}
}
}
|
use actix_web::Json;
use actix_web::State;
use actix_web::{http::StatusCode, HttpResponse};
use auth::user::User;
use bigneon_db::models::*;
use bigneon_db::utils::errors::Optional;
use db::Connection;
use errors::BigNeonError;
use helpers::application;
use itertools::Itertools;
use payments::PaymentProcessor;
use server::AppState;
use std::collections::HashMap;
use utils::ServiceLocator;
use uuid::Uuid;
#[derive(Deserialize, Serialize)]
pub struct CartResponse {
pub cart_id: Uuid,
}
#[derive(Deserialize)]
pub struct AddToCartRequestItem {
pub ticket_type_id: Uuid,
pub quantity: u32,
}
#[derive(Deserialize)]
pub struct AddToCartRequest {
pub items: Vec<AddToCartRequestItem>,
}
pub fn add(
(connection, json, user): (Connection, Json<AddToCartRequest>, User),
) -> Result<HttpResponse, BigNeonError> {
let connection = connection.get();
if json.items.is_empty() {
return application::unprocessable("Could not update cart as no items provided");
}
// Find the current cart of the user, if it exists.
let mut cart = Order::find_or_create_cart(&user.user, connection)?;
// Force only one thread to update the order at a time.
cart.lock_version(connection)?;
// Add the item (first combining ticket type id to avoid multiple add calls for the same id)
for (ticket_type_id, request_items) in &json
.items
.iter()
.group_by(|request_item| request_item.ticket_type_id)
{
let quantity = request_items.fold(0, |sum, request_item| sum + request_item.quantity);
cart.add_tickets(ticket_type_id, quantity, connection)?;
}
cart.update_event_fees(connection)?;
Ok(HttpResponse::Created().json(&CartResponse { cart_id: cart.id }))
}
#[derive(Deserialize)]
pub struct RemoveCartRequest {
pub ticket_pricing_id: Uuid,
pub quantity: Option<u32>,
}
pub fn remove(
(connection, json, user): (Connection, Json<RemoveCartRequest>, User),
) -> Result<HttpResponse, BigNeonError> {
let connection = connection.get();
// Find the current cart of the user, if it exists.
let mut current_cart = Order::find_cart_for_user(user.id(), connection)?;
match current_cart.as_mut() {
Some(cart) => {
cart.lock_version(connection)?;
cart.remove_tickets(json.ticket_pricing_id, json.quantity, connection)?;
if cart.has_items(connection)? {
Ok(HttpResponse::Ok().json(&CartResponse { cart_id: cart.id }))
} else {
cart.destroy(connection)?;
Ok(HttpResponse::Ok().json(json!({})))
}
}
None => application::unprocessable("No cart exists for user"),
}
}
pub fn show((connection, user): (Connection, User)) -> Result<HttpResponse, BigNeonError> {
let connection = connection.get();
let order = Order::find_cart_for_user(user.id(), connection)?;
if order.is_none() {
return Ok(HttpResponse::Ok().json(json!({})));
}
let order = order.unwrap();
Ok(HttpResponse::Ok().json(order.for_display(connection)?))
}
#[derive(Deserialize)]
pub struct CheckoutCartRequest {
pub amount: i64,
pub method: PaymentRequest,
}
#[derive(Deserialize)]
#[serde(tag = "type")]
pub enum PaymentRequest {
External {
reference: String,
},
Card {
token: String,
provider: String,
save_payment_method: bool,
set_default: bool,
},
PaymentMethod {
provider: Option<String>,
},
}
pub fn checkout(
(connection, json, user, state): (Connection, Json<CheckoutCartRequest>, User, State<AppState>),
) -> Result<HttpResponse, BigNeonError> {
let req = json.into_inner();
info!("CART: Checking out");
let mut order = match Order::find_cart_for_user(user.id(), connection.get())? {
Some(o) => o,
None => return application::unprocessable("No cart exists for user"),
};
order.lock_version(connection.get())?;
let order_items = order.items(connection.get())?;
//Assemble token ids and ticket instance ids for each asset in the order
let mut tokens_per_asset: HashMap<Uuid, Vec<u64>> = HashMap::new();
let mut wallet_id_per_asset: HashMap<Uuid, Uuid> = HashMap::new();
for oi in &order_items {
let tickets = TicketInstance::find_for_order_item(oi.id, connection.get())?;
for ticket in &tickets {
tokens_per_asset
.entry(ticket.asset_id)
.or_insert_with(|| Vec::new())
.push(ticket.token_id as u64);
wallet_id_per_asset
.entry(ticket.asset_id)
.or_insert(ticket.wallet_id);
}
}
info!("CART: Verifying asset");
//Just confirming that the asset is setup correctly before proceeding to payment.
for asset_id in tokens_per_asset.keys() {
let asset = Asset::find(*asset_id, connection.get())?;
if asset.blockchain_asset_id.is_none() {
return application::internal_server_error(
"Could not complete this checkout because the asset has not been assigned on the blockchain",
);
}
}
let payment_response = match &req.method {
PaymentRequest::External { reference } => {
info!("CART: Received external payment");
checkout_external(&connection, &mut order, reference, &req, &user)?
}
PaymentRequest::PaymentMethod { provider } => {
info!("CART: Received provider payment");
let provider = match provider {
Some(provider) => provider.clone(),
None => match user
.user
.default_payment_method(connection.get())
.optional()?
{
Some(payment_method) => payment_method.name,
None => {
return application::unprocessable(
"Could not complete this cart because user has no default payment method",
);
}
},
};
checkout_payment_processor(
&connection,
&mut order,
None,
&req,
&user,
&state.config.primary_currency,
&provider,
true,
false,
false,
&state.service_locator,
)?
}
PaymentRequest::Card {
token,
provider,
save_payment_method,
set_default,
} => checkout_payment_processor(
&connection,
&mut order,
Some(&token),
&req,
&user,
&state.config.primary_currency,
provider,
false,
*save_payment_method,
*set_default,
&state.service_locator,
)?,
};
if payment_response.status() == StatusCode::OK {
let new_owner_wallet = Wallet::find_default_for_user(user.id(), connection.get())?;
for (asset_id, token_ids) in &tokens_per_asset {
let asset = Asset::find(*asset_id, connection.get())?;
match asset.blockchain_asset_id {
Some(a) => {
let wallet_id=wallet_id_per_asset.get(asset_id).unwrap().clone();
let org_wallet = Wallet::find(wallet_id, connection.get())?;
state.config.tari_client.transfer_tokens(&org_wallet.secret_key, &org_wallet.public_key,
&a,
token_ids.clone(),
new_owner_wallet.public_key.clone(),
)?
},
None => return application::internal_server_error(
"Could not complete this checkout because the asset has not been assigned on the blockchain",
),
}
}
}
Ok(payment_response)
}
// TODO: This should actually probably move to an `orders` controller, since the
// user will not be calling this.
fn checkout_external(
conn: &Connection,
order: &mut Order,
reference: &str,
checkout_request: &CheckoutCartRequest,
user: &User,
) -> Result<HttpResponse, BigNeonError> {
let connection = conn.get();
if !user.has_scope(Scopes::OrderMakeExternalPayment, None, connection)? {
return application::unauthorized();
}
if order.status() != OrderStatus::Draft {
return application::unprocessable(
"Could not complete this cart because it is not in the correct status",
);
}
let payment = order.add_external_payment(
reference.to_string(),
user.id(),
checkout_request.amount,
connection,
)?;
Ok(HttpResponse::Ok().json(json!({"payment_id": payment.id})))
}
fn checkout_payment_processor(
conn: &Connection,
order: &mut Order,
token: Option<&str>,
req: &CheckoutCartRequest,
auth_user: &User,
currency: &str,
provider_name: &str,
use_stored_payment: bool,
save_payment_method: bool,
set_default: bool,
service_locator: &ServiceLocator,
) -> Result<HttpResponse, BigNeonError> {
info!("CART: Executing provider payment");
let connection = conn.get();
if order.user_id != auth_user.id() {
return application::forbidden("This cart does not belong to you");
} else if order.status() != OrderStatus::Draft {
return application::unprocessable(
"Could not complete this cart because it is not in the correct status",
);
}
let client = service_locator.create_payment_processor(provider_name);
let token = if use_stored_payment {
info!("CART: Using stored payment");
match auth_user
.user
.payment_method(provider_name.to_string(), connection)
.optional()?
{
Some(payment_method) => payment_method.provider,
None => {
return application::unprocessable(
"Could not complete this cart because stored provider does not exist",
)
}
}
} else {
info!("CART: Not using stored payment");
if token.is_none() {
return application::unprocessable(
"Could not complete this cart because no token provided",
);
}
let token = token.unwrap();
if save_payment_method {
info!("CART: User has requested to save the payment method");
match auth_user
.user
.payment_method(provider_name.to_string(), connection)
.optional()?
{
Some(payment_method) => {
let client_response = client.update_repeat_token(
&payment_method.provider,
token,
"Big Neon something",
)?;
let payment_method_parameters = PaymentMethodEditableAttributes {
provider_data: Some(client_response.to_json()?),
};
payment_method.update(&payment_method_parameters, connection)?;
payment_method.provider
}
None => {
let repeat_token =
client.create_token_for_repeat_charges(token, "Big Neon something")?;
let _payment_method = PaymentMethod::create(
auth_user.id(),
provider_name.to_string(),
set_default,
repeat_token.token.clone(),
repeat_token.to_json()?,
).commit(connection)?;
repeat_token.token
}
}
} else {
token.to_string()
}
};
info!("CART: Auth'ing to payment provider");
let auth_result = client.auth(
&token,
req.amount,
currency,
"Tickets from Bigneon",
vec![("order_id".to_string(), order.id.to_string())],
)?;
info!("CART: Saving payment to order");
let payment = match order.add_credit_card_payment(
auth_user.id(),
req.amount,
provider_name.to_string(),
auth_result.id.clone(),
PaymentStatus::Authorized,
auth_result.to_json()?,
connection,
) {
Ok(p) => p,
Err(e) => {
client.refund(&auth_result.id)?;
return Err(e.into());
}
};
conn.commit_transaction()?;
conn.begin_transaction()?;
info!("CART: Completing auth with payment provider");
let charge_result = client.complete_authed_charge(&auth_result.id)?;
info!("CART: Completing payment on order");
match payment.mark_complete(charge_result.to_json()?, connection) {
Ok(_) => Ok(HttpResponse::Ok().json(json!({"payment_id": payment.id}))),
Err(e) => {
client.refund(&auth_result.id)?;
Err(e.into())
}
}
}
|
use cql_bindgen::CassLogMessage;
#[repr(C)]
pub enum CassLogLevel {
DISABLED = 0,
CRITICAL = 1,
ERROR = 2,
WARN = 3,
INFO = 4,
DEBUG = 5,
TRACE = 6,
LAST_ENTRY = 7,
}
pub type CassLogCallback =
::std::option::Option<extern "C" fn (
message: *const CassLogMessage,
data: *mut ::libc::c_void
)>;
|
// spell-checker:ignore compresslevel
pub(crate) use _bz2::make_module;
#[pymodule]
mod _bz2 {
use crate::common::lock::PyMutex;
use crate::vm::{
builtins::{PyBytesRef, PyTypeRef},
function::{ArgBytesLike, OptionalArg},
object::{PyPayload, PyResult},
types::Constructor,
VirtualMachine,
};
use bzip2::{write::BzEncoder, Decompress, Status};
use std::{fmt, io::Write};
// const BUFSIZ: i32 = 8192;
struct DecompressorState {
decoder: Decompress,
eof: bool,
needs_input: bool,
// input_buffer: Vec<u8>,
// output_buffer: Vec<u8>,
}
#[pyattr]
#[pyclass(name = "BZ2Decompressor")]
#[derive(PyPayload)]
struct BZ2Decompressor {
state: PyMutex<DecompressorState>,
}
impl fmt::Debug for BZ2Decompressor {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "_bz2.BZ2Decompressor")
}
}
impl Constructor for BZ2Decompressor {
type Args = ();
fn py_new(cls: PyTypeRef, _: Self::Args, vm: &VirtualMachine) -> PyResult {
Self {
state: PyMutex::new(DecompressorState {
decoder: Decompress::new(false),
eof: false,
needs_input: true,
// input_buffer: Vec::new(),
// output_buffer: Vec::new(),
}),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
}
}
#[pyclass(with(Constructor))]
impl BZ2Decompressor {
#[pymethod]
fn decompress(
&self,
data: ArgBytesLike,
// TODO: PyIntRef
max_length: OptionalArg<i32>,
vm: &VirtualMachine,
) -> PyResult<PyBytesRef> {
let max_length = max_length.unwrap_or(-1);
if max_length >= 0 {
return Err(vm.new_not_implemented_error(
"the max_value argument is not implemented yet".to_owned(),
));
}
// let max_length = if max_length < 0 || max_length >= BUFSIZ {
// BUFSIZ
// } else {
// max_length
// };
let mut state = self.state.lock();
let DecompressorState {
decoder,
eof,
..
// needs_input,
// input_buffer,
// output_buffer,
} = &mut *state;
if *eof {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.eof_error.to_owned(),
"End of stream already reached".to_owned(),
));
}
// data.with_ref(|data| input_buffer.extend(data));
// If max_length is negative:
// read the input X bytes at a time, compress it and append it to output.
// Once you're out of input, setting needs_input to true and return the
// output as bytes.
//
// TODO:
// If max_length is non-negative:
// Read the input X bytes at a time, compress it and append it to
// the output. If output reaches `max_length` in size, return
// it (up to max_length), and store the rest of the output
// for later.
// TODO: arbitrary choice, not the right way to do it.
let mut buf = Vec::with_capacity(data.len() * 32);
let before = decoder.total_in();
let res = data.with_ref(|data| decoder.decompress_vec(data, &mut buf));
let _written = (decoder.total_in() - before) as usize;
let res = match res {
Ok(x) => x,
// TODO: error message
_ => return Err(vm.new_os_error("Invalid data stream".to_owned())),
};
if res == Status::StreamEnd {
*eof = true;
}
Ok(vm.ctx.new_bytes(buf.to_vec()))
}
#[pygetset]
fn eof(&self) -> bool {
let state = self.state.lock();
state.eof
}
#[pygetset]
fn unused_data(&self, vm: &VirtualMachine) -> PyBytesRef {
// Data found after the end of the compressed stream.
// If this attribute is accessed before the end of the stream
// has been reached, its value will be b''.
vm.ctx.new_bytes(b"".to_vec())
// alternatively, be more honest:
// Err(vm.new_not_implemented_error(
// "unused_data isn't implemented yet".to_owned(),
// ))
//
// TODO
// let state = self.state.lock();
// if state.eof {
// vm.ctx.new_bytes(state.input_buffer.to_vec())
// else {
// vm.ctx.new_bytes(b"".to_vec())
// }
}
#[pygetset]
fn needs_input(&self) -> bool {
// False if the decompress() method can provide more
// decompressed data before requiring new uncompressed input.
let state = self.state.lock();
state.needs_input
}
// TODO: mro()?
}
struct CompressorState {
flushed: bool,
encoder: Option<BzEncoder<Vec<u8>>>,
}
#[pyattr]
#[pyclass(name = "BZ2Compressor")]
#[derive(PyPayload)]
struct BZ2Compressor {
state: PyMutex<CompressorState>,
}
impl fmt::Debug for BZ2Compressor {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "_bz2.BZ2Compressor")
}
}
impl Constructor for BZ2Compressor {
type Args = (OptionalArg<i32>,);
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
let (compresslevel,) = args;
// TODO: seriously?
// compresslevel.unwrap_or(bzip2::Compression::best().level().try_into().unwrap());
let compresslevel = compresslevel.unwrap_or(9);
let level = match compresslevel {
valid_level @ 1..=9 => bzip2::Compression::new(valid_level as u32),
_ => {
return Err(
vm.new_value_error("compresslevel must be between 1 and 9".to_owned())
)
}
};
Self {
state: PyMutex::new(CompressorState {
flushed: false,
encoder: Some(BzEncoder::new(Vec::new(), level)),
}),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
}
}
// TODO: return partial results from compress() instead of returning everything in flush()
#[pyclass(with(Constructor))]
impl BZ2Compressor {
#[pymethod]
fn compress(&self, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
let mut state = self.state.lock();
if state.flushed {
return Err(vm.new_value_error("Compressor has been flushed".to_owned()));
}
// let CompressorState { flushed, encoder } = &mut *state;
let CompressorState { encoder, .. } = &mut *state;
// TODO: handle Err
data.with_ref(|input_bytes| encoder.as_mut().unwrap().write_all(input_bytes).unwrap());
Ok(vm.ctx.new_bytes(Vec::new()))
}
#[pymethod]
fn flush(&self, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
let mut state = self.state.lock();
if state.flushed {
return Err(vm.new_value_error("Repeated call to flush()".to_owned()));
}
// let CompressorState { flushed, encoder } = &mut *state;
let CompressorState { encoder, .. } = &mut *state;
// TODO: handle Err
let out = encoder.take().unwrap().finish().unwrap();
state.flushed = true;
Ok(vm.ctx.new_bytes(out.to_vec()))
}
}
}
|
//==============================================================================
// Notes
//==============================================================================
// mcu::mod.rs
//==============================================================================
// Crates and Mods
//==============================================================================
pub mod adc;
pub mod gpio;
pub mod i2c;
pub mod input;
pub mod rtc;
pub mod spi;
pub mod spim;
pub mod timer;
use cortex_m;
use nrf52832_pac;
use crate::app::info;
//==============================================================================
// Enums, Structs, and Types
//==============================================================================
#[allow(dead_code)]
pub enum McuState {
AdcBusy,
SpiBusy,
TimerBusy,
Idle
}
//==============================================================================
// Variables
//==============================================================================
//==============================================================================
// Public Functions
//==============================================================================
pub fn init(wake_interval: rtc::WakeInterval) {
let peripherals = nrf52832_pac::Peripherals::take().unwrap();
// let cortex = cortex_m::Peripherals::take().unwrap();
peripherals.CLOCK.tasks_hfclkstart.write(|w| unsafe { w.bits(1) });
while peripherals.CLOCK.events_hfclkstarted.read().bits() == 0 {};
adc::init(peripherals.SAADC);
gpio::init(peripherals.P0);
input::init(peripherals.GPIOTE);
i2c::init(peripherals.TWI1);
rtc::init(peripherals.RTC0, &peripherals.CLOCK, wake_interval);
spi::init(peripherals.SPI0);
spim::init(peripherals.SPIM0);
timer::init(peripherals.TIMER0);
}
pub fn get_busy() -> McuState {
if adc::get_busy() {
return McuState::AdcBusy;
}
if timer::get_busy() {
return McuState::TimerBusy;
}
McuState::Idle
}
pub fn restart() {
cortex_m::peripheral::SCB::sys_reset();
}
//==============================================================================
// Private Functions
//==============================================================================
//==============================================================================
// Task Handler
//==============================================================================
pub fn task_handler(_d: &info::DeviceInfo) {
input::task_handler();
} |
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SICR {
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Proxy"]
pub struct _I2C_SICR_DATAICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_DATAICW<'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"Proxy"]
pub struct _I2C_SICR_STARTICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_STARTICW<'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"Proxy"]
pub struct _I2C_SICR_STOPICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_STOPICW<'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"Proxy"]
pub struct _I2C_SICR_DMARXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_DMARXICW<'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"Proxy"]
pub struct _I2C_SICR_DMATXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_DMATXICW<'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"Proxy"]
pub struct _I2C_SICR_TXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_TXICW<'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"Proxy"]
pub struct _I2C_SICR_RXICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_RXICW<'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"Proxy"]
pub struct _I2C_SICR_TXFEICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_TXFEICW<'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"Proxy"]
pub struct _I2C_SICR_RXFFICW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_SICR_RXFFICW<'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
}
}
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 - Data Interrupt Clear"]
#[inline(always)]
pub fn i2c_sicr_dataic(&mut self) -> _I2C_SICR_DATAICW {
_I2C_SICR_DATAICW { w: self }
}
#[doc = "Bit 1 - Start Condition Interrupt Clear"]
#[inline(always)]
pub fn i2c_sicr_startic(&mut self) -> _I2C_SICR_STARTICW {
_I2C_SICR_STARTICW { w: self }
}
#[doc = "Bit 2 - Stop Condition Interrupt Clear"]
#[inline(always)]
pub fn i2c_sicr_stopic(&mut self) -> _I2C_SICR_STOPICW {
_I2C_SICR_STOPICW { w: self }
}
#[doc = "Bit 3 - Receive DMA Interrupt Clear"]
#[inline(always)]
pub fn i2c_sicr_dmarxic(&mut self) -> _I2C_SICR_DMARXICW {
_I2C_SICR_DMARXICW { w: self }
}
#[doc = "Bit 4 - Transmit DMA Interrupt Clear"]
#[inline(always)]
pub fn i2c_sicr_dmatxic(&mut self) -> _I2C_SICR_DMATXICW {
_I2C_SICR_DMATXICW { w: self }
}
#[doc = "Bit 5 - Transmit Request Interrupt Mask"]
#[inline(always)]
pub fn i2c_sicr_txic(&mut self) -> _I2C_SICR_TXICW {
_I2C_SICR_TXICW { w: self }
}
#[doc = "Bit 6 - Receive Request Interrupt Mask"]
#[inline(always)]
pub fn i2c_sicr_rxic(&mut self) -> _I2C_SICR_RXICW {
_I2C_SICR_RXICW { w: self }
}
#[doc = "Bit 7 - Transmit FIFO Empty Interrupt Mask"]
#[inline(always)]
pub fn i2c_sicr_txfeic(&mut self) -> _I2C_SICR_TXFEICW {
_I2C_SICR_TXFEICW { w: self }
}
#[doc = "Bit 8 - Receive FIFO Full Interrupt Mask"]
#[inline(always)]
pub fn i2c_sicr_rxffic(&mut self) -> _I2C_SICR_RXFFICW {
_I2C_SICR_RXFFICW { w: self }
}
}
|
use byteorder::ReadBytesExt;
use core::mem;
use num_derive::FromPrimitive;
use std::io::{Cursor, Write};
use wayk_proto::{
container::Vec16,
error::*,
message::connection_sequence::InputActionCode,
serialization::{Decode, Encode},
};
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum InputMessageType {
Mouse = 0x01,
Scroll = 0x02,
Keyboard = 0x03,
Unicode = 0x04,
Toggle = 0x05,
Action = 0x06,
}
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum EventMouseFlags {
None = 0x0,
ButtonLeft = 0x01,
ButtonRight = 0x02,
ButtonMiddle = 0x04,
ButtonX1 = 0x10,
ButtonX2 = 0x20,
}
#[derive(Encode, Decode, Clone, Debug)]
pub struct NowInputEventMouse {
subtype: InputMessageType,
pub flags: EventMouseFlags,
pub x: i16,
pub y: i16,
}
impl NowInputEventMouse {
pub fn new_with_flags_and_position(flags: EventMouseFlags, x: i16, y: i16) -> Self {
Self {
subtype: InputMessageType::Mouse,
flags,
x,
y,
}
}
}
#[derive(Encode, Decode, Clone, Debug)]
pub struct NowInputEventScroll {
subtype: InputMessageType,
flags: u8,
pub x: i16,
pub y: i16,
}
impl NowInputEventScroll {
pub fn new_with_position(x: i16, y: i16) -> Self {
Self {
subtype: InputMessageType::Scroll,
flags: 0x0,
x,
y,
}
}
}
#[derive(Encode, Decode, Clone, Debug)]
pub struct NowInputEventKeyboard {
subtype: InputMessageType,
pub flags: u8,
pub code: u16,
}
impl NowInputEventKeyboard {
pub fn new_with_flags_and_code(flags: u8, code: u16) -> Self {
Self {
subtype: InputMessageType::Keyboard,
flags,
code,
}
}
}
#[derive(Clone, Debug)]
pub struct NowInputEventUnicode {
subtype: InputMessageType,
pub code: Vec<u8>,
}
impl<'a> Encode for NowInputEventUnicode {
fn encoded_len(&self) -> usize {
mem::size_of::<u8>() + mem::size_of::<u8>() + self.code.len()
}
fn encode_into<W: Write>(&self, writer: &mut W) -> Result<()> {
self.subtype.encode_into(writer)?;
let flags = (self.code.len() as u8 - 1) << 6;
flags.encode_into(writer)?;
writer.write_all(&self.code)?;
Ok(())
}
}
impl<'dec: 'a, 'a> Decode<'dec> for NowInputEventUnicode {
fn decode_from(cursor: &mut Cursor<&'dec [u8]>) -> Result<Self> {
let _subtype = cursor.read_u8()?;
let flags = cursor.read_u8()?;
let start_inclusive = cursor.position() as usize;
let code_size = (flags >> 6) + 1;
let end_exclusive = start_inclusive + code_size as usize;
const SUBTYPE_FLAGS_BYTES: usize = 2;
let bytes_left = (cursor.get_ref().len() - start_inclusive + SUBTYPE_FLAGS_BYTES) as usize;
let code = if bytes_left == end_exclusive {
cursor.get_ref()[start_inclusive..end_exclusive].to_vec()
} else {
return ProtoError::new(ProtoErrorKind::Decoding(
"NowInputEventUnicode: bytes_left != end_exclusive",
));
};
Ok(NowInputEventUnicode {
subtype: InputMessageType::Unicode,
code,
})
}
}
impl NowInputEventUnicode {
pub fn new(code: Vec<u8>) -> Self {
Self {
subtype: InputMessageType::Unicode,
code,
}
}
}
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u16)]
pub enum ToggleEventKeys {
ScrollLock = 0x0001,
NumLock = 0x0002,
CapsLock = 0x0004,
KanaLock = 0x0008,
}
#[derive(Encode, Decode, Clone, Debug)]
pub struct NowInputEventToggle {
subtype: InputMessageType,
flags: u8,
pub code: u16,
}
impl NowInputEventToggle {
pub fn new_with_code(code: u16) -> Self {
Self {
subtype: InputMessageType::Toggle,
flags: 0x0,
code,
}
}
}
#[derive(Encode, Decode, Clone, Debug)]
pub struct NowInputEventAction {
subtype: InputMessageType,
flags: u8,
pub code: InputActionCode,
}
impl NowInputEventAction {
pub fn new_with_code(code: InputActionCode) -> Self {
Self {
subtype: InputMessageType::Action,
flags: 0x0,
code,
}
}
}
#[derive(Debug, Clone, Encode, Decode)]
#[meta_enum = "InputMessageType"]
pub enum InputEvent {
Mouse(NowInputEventMouse),
Scroll(NowInputEventScroll),
Keyboard(NowInputEventKeyboard),
Unicode(NowInputEventUnicode),
Toggle(NowInputEventToggle),
Action(NowInputEventAction),
}
#[derive(Encode, Decode, Clone, Debug)]
pub struct NowInputMsg {
input_event: Vec16<InputEvent>,
}
impl NowInputMsg {
pub fn new_with_events(input_event: Vec<InputEvent>) -> Self {
Self {
input_event: Vec16(input_event),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{message::VirtChannelsCtx, packet::NowPacket};
const TOGGLE_EVENT_FULL_PACKET: [u8; 10] = [0x06, 0x00, 0x43, 0x80, 0x01, 0x00, 0x05, 0x00, 0x02, 0x00];
const MOUSE_SCROLL_EVENT_FULL_PACKET: [u8; 12] =
[0x08, 0x00, 0x43, 0x80, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x78, 0x00];
const KEYBOARD_EVENT_FULL_PACKET: [u8; 10] = [0x06, 0x00, 0x43, 0x80, 0x01, 0x00, 0x03, 0x01, 0x08, 0x00];
const MOUSE_POSITION_EVENT_FULL_PACKET: [u8; 18] = [
0x0e, 0x00, 0x43, 0x80, 0x02, 0x00, 0x01, 0x00, 0xe4, 0x05, 0x77, 0x02, 0x01, 0x00, 0xe0, 0x05, 0x70, 0x02,
];
const UNICODE_EVENT_FULL_PACKET: [u8; 12] =
[0x08, 0x00, 0x43, 0x80, 0x01, 0x00, 0x04, 0xC0, 0xe4, 0x05, 0x77, 0x02];
#[test]
fn input_event_mouse_encode() {
let mouse_events = vec![
InputEvent::Mouse(NowInputEventMouse::new_with_flags_and_position(
EventMouseFlags::None,
1508,
631,
)),
InputEvent::Mouse(NowInputEventMouse::new_with_flags_and_position(
EventMouseFlags::None,
1504,
624,
)),
];
let packet = NowPacket::from_message(NowInputMsg::new_with_events(mouse_events));
assert_eq!(packet.encode().unwrap(), MOUSE_POSITION_EVENT_FULL_PACKET.to_vec());
}
#[test]
fn input_event_mouse_decode_full_packet() {
let mut buffer = Vec::new();
let mut reader = Cursor::new(&MOUSE_POSITION_EVENT_FULL_PACKET[..]);
match NowPacket::read_from(&mut reader, &mut buffer, &VirtChannelsCtx::new()) {
Ok(_) => {}
Err(e) => {
e.print_trace();
panic!("couldn't decode input mouse event packet");
}
}
}
#[test]
fn input_event_toggle_encode() {
let toggle_event = vec![InputEvent::Toggle(NowInputEventToggle::new_with_code(
ToggleEventKeys::NumLock as u16,
))];
let packet = NowPacket::from_message(NowInputMsg::new_with_events(toggle_event));
assert_eq!(packet.encode().unwrap(), TOGGLE_EVENT_FULL_PACKET.to_vec());
}
#[test]
fn input_event_toggle_decode() {
let toggle_event = InputEvent::decode(&TOGGLE_EVENT_FULL_PACKET[6..]).unwrap();
if let InputEvent::Toggle(toggle_event) = toggle_event {
assert_eq!(toggle_event.subtype, InputMessageType::Toggle);
assert_eq!(toggle_event.code, 2);
} else {
panic!("couldn't decode toggle message")
}
}
#[test]
fn input_event_keyboard_encode() {
let kb_events = vec![InputEvent::Keyboard(NowInputEventKeyboard::new_with_flags_and_code(
1, 8,
))];
let packet = NowPacket::from_message(NowInputMsg::new_with_events(kb_events));
assert_eq!(packet.encode().unwrap(), KEYBOARD_EVENT_FULL_PACKET.to_vec());
}
#[test]
fn input_event_keyboard_decode() {
let kb_event = InputEvent::decode(&KEYBOARD_EVENT_FULL_PACKET[6..]).unwrap();
if let InputEvent::Keyboard(kb_event) = kb_event {
assert_eq!(kb_event.subtype, InputMessageType::Keyboard);
assert_eq!(kb_event.code, 8);
} else {
panic!("couldn't decode keyboard message")
}
}
#[test]
fn input_event_scroll_encode() {
let scroll_events = vec![InputEvent::Scroll(NowInputEventScroll::new_with_position(0, 120))];
let packet = NowPacket::from_message(NowInputMsg::new_with_events(scroll_events));
assert_eq!(packet.encode().unwrap(), MOUSE_SCROLL_EVENT_FULL_PACKET.to_vec());
}
#[test]
fn input_event_scroll_decode() {
let scroll_event = InputEvent::decode(&MOUSE_SCROLL_EVENT_FULL_PACKET[6..]).unwrap();
if let InputEvent::Scroll(scroll_event) = scroll_event {
assert_eq!(scroll_event.subtype, InputMessageType::Scroll);
assert_eq!(scroll_event.x, 0);
assert_eq!(scroll_event.y, 120);
} else {
panic!("couldn't decode scroll message")
}
}
#[test]
fn input_event_unicode_encode() {
let unicode_events = vec![InputEvent::Unicode(NowInputEventUnicode::new(vec![
0xe4, 0x05, 0x77, 0x02,
]))];
let packet = NowPacket::from_message(NowInputMsg::new_with_events(unicode_events));
assert_eq!(packet.encode().unwrap(), UNICODE_EVENT_FULL_PACKET.to_vec());
}
#[test]
fn input_event_unicode_decode() {
let unicode_event = InputEvent::decode(&UNICODE_EVENT_FULL_PACKET[6..]).unwrap();
if let InputEvent::Unicode(unicode_event) = unicode_event {
assert_eq!(unicode_event.subtype, InputMessageType::Unicode);
assert_eq!(unicode_event.code, vec![0xe4, 0x05, 0x77, 0x02]);
} else {
panic!("didnt decode unicode message")
}
}
}
|
use crate::{Config, RequireIdentityForPorts, SkipByPort};
pub use futures::prelude::*;
use linkerd_app_core::{
config,
dns::Suffix,
drain, exp_backoff, metrics,
proxy::{
http::{h1, h2},
tap,
},
transport::{BindTcp, Keepalive, ListenAddr},
NameMatch, ProxyRuntime,
};
pub use linkerd_app_test as support;
use std::{net::SocketAddr, time::Duration};
const LOCALHOST: [u8; 4] = [127, 0, 0, 1];
pub fn default_config(orig_dst: SocketAddr) -> Config {
let cluster_local = "svc.cluster.local."
.parse::<Suffix>()
.expect("`svc.cluster.local.` suffix is definitely valid");
Config {
allow_discovery: NameMatch::new(Some(cluster_local)),
proxy: config::ProxyConfig {
server: config::ServerConfig {
bind: BindTcp::new(
ListenAddr(SocketAddr::new(LOCALHOST.into(), 0)),
Keepalive(None),
)
.with_orig_dst_addr(orig_dst.into()),
h2_settings: h2::Settings::default(),
},
connect: config::ConnectConfig {
keepalive: Keepalive(None),
timeout: Duration::from_secs(1),
backoff: exp_backoff::ExponentialBackoff::new(
Duration::from_millis(100),
Duration::from_millis(500),
0.1,
)
.unwrap(),
h1_settings: h1::PoolSettings {
max_idle: 1,
idle_timeout: Duration::from_secs(1),
},
h2_settings: h2::Settings::default(),
},
buffer_capacity: 10_000,
cache_max_idle_age: Duration::from_secs(20),
dispatch_timeout: Duration::from_secs(1),
max_in_flight_requests: 10_000,
detect_protocol_timeout: Duration::from_secs(10),
},
require_identity_for_inbound_ports: RequireIdentityForPorts::from(None),
disable_protocol_detection_for_ports: SkipByPort::from(indexmap::IndexSet::default()),
profile_idle_timeout: Duration::from_millis(500),
}
}
pub fn runtime() -> (ProxyRuntime, drain::Signal) {
let (metrics, _) = metrics::Metrics::new(std::time::Duration::from_secs(10));
let (drain_tx, drain) = drain::channel();
let (tap, _) = tap::new();
let runtime = ProxyRuntime {
identity: None,
metrics: metrics.outbound,
tap,
span_sink: None,
drain,
};
(runtime, drain_tx)
}
|
use super::double::{double_escape_sequence, interpolated_character_sequence};
use crate::ast::Literal;
use crate::lexer::*;
use crate::parsers::comment::line_content;
use crate::parsers::program::{line_terminator, source_character, whitespace};
use crate::parsers::token::identifier::identifier_character;
// TODO: ensure nested interpolated heredocs work
// TODO: ensure sequenced heredocs work
/// *heredoc_start_line* *heredoc_body* *heredoc_end_line*
pub(crate) fn here_document(i: Input) -> NodeResult {
wrap_heredoc(_here_document)(i)
}
// When dealing with heredocs, the parser has to make a jump in the input.
// First, the heredoc is parsed, and parsing continues using the rest of the heredoc's start line.
// Only then does parsing resume after the heredoc's ending identifier.
fn _here_document(i: Input) -> NodeResult {
let (i, mut line) = heredoc_start_line(i)?;
let (remaining, token) = terminated(heredoc_body, heredoc_end_line)(i)?;
line.remaining_input = Some(Box::new(remaining));
Ok((line, token))
}
/// *heredoc_signifier* *rest_of_line*
fn heredoc_start_line(i: Input) -> LexResult {
preceded(heredoc_signifier, rest_of_line)(i)
}
/// `<<` *heredoc_quote_type_specifier*
fn heredoc_signifier(i: Input) -> LexResult {
preceded(tag("<<"), heredoc_quote_type_specifier)(i)
}
/// *line_content*? *line_terminator*
fn rest_of_line(i: Input) -> LexResult {
terminated(recognize(opt(line_content)), line_terminator)(i)
}
/// *comment_line** **but not** *heredoc_end_line*
fn heredoc_body(i: Input) -> NodeResult {
let heredoc_contents = match i.metadata.heredoc.as_deref().unwrap().quote_type.unwrap() {
HeredocQuoteType::SingleQuoted => single_quoted_character,
_ => double_quoted_character,
};
let indentation = i.metadata.heredoc.as_deref().unwrap().indentation;
let (i, contents) = map(
many0(preceded(peek(not(heredoc_end_line)), heredoc_contents)),
|vec| {
let val = Interpolatable::from(vec.into_iter().collect::<Vec<Segment>>());
match indentation {
Some(HeredocIndentation::FullyIndented) => val.to_unindented(),
_ => val,
}
},
)(i)?;
let token = match i.metadata.heredoc.as_deref().unwrap().quote_type {
Some(HeredocQuoteType::CommandQuoted) => match contents {
Interpolatable::String(v) => Node::Literal(Literal::Command(v)),
Interpolatable::Interpolated(v) => Node::Interpolated(Interpolated::Command(v)),
},
_ => match contents {
Interpolatable::String(v) => Node::Literal(Literal::String(v)),
Interpolatable::Interpolated(v) => Node::Interpolated(Interpolated::String(v)),
},
};
Ok((i, token))
}
fn single_quoted_character(i: Input) -> SegmentResult {
map(source_character, |c| Segment::Char(c))(i)
}
fn double_quoted_character(i: Input) -> SegmentResult {
alt((
map(none_of("#\\"), |c| Segment::Char(c)),
map(double_escape_sequence, |s| Segment::String(s)),
map(interpolated_character_sequence, |e| Segment::expr(e)),
map(char('#'), |c| Segment::Char(c)),
))(i)
}
/// ( `-` | `~` )? *heredoc_quote_type*
fn heredoc_quote_type_specifier(i: Input) -> LexResult {
preceded(
set_indentiation(opt(alt((char('-'), char('~'))))),
heredoc_quote_type,
)(i)
}
/// *non_quoted_delimiter* | *single_quoted_delimiter* | *double_quoted_delimiter* | *command_quoted_delimiter*
fn heredoc_quote_type(i: Input) -> LexResult {
let (mut i, res) = alt((
set_quote_type(non_quoted_delimiter, HeredocQuoteType::Unquoted),
set_quote_type(single_quoted_delimiter, HeredocQuoteType::SingleQuoted),
set_quote_type(double_quoted_delimiter, HeredocQuoteType::DoubleQuoted),
set_quote_type(command_quoted_delimiter, HeredocQuoteType::CommandQuoted),
))(i)?;
i.metadata.heredoc.as_deref_mut().unwrap().identifier = Some(*res);
Ok((i, res))
}
/// *non_quoted_delimiter_identifier*
pub(crate) fn non_quoted_delimiter(i: Input) -> LexResult {
non_quoted_delimiter_identifier(i)
}
/// *identifier_character*+
pub(crate) fn non_quoted_delimiter_identifier(i: Input) -> LexResult {
recognize(many1(identifier_character))(i)
}
/// `'` *single_quoted_delimiter_identifier* `'`
pub(crate) fn single_quoted_delimiter(i: Input) -> LexResult {
delimited(char('\''), single_quoted_delimiter_identifier, char('\''))(i)
}
/// ( ( *source_character* *source_character*? ) **but not** ( `'` | *line_terminator* ) )*
pub(crate) fn single_quoted_delimiter_identifier(i: Input) -> LexResult {
preceded(
peek(not(whitespace)),
recognize(many1(preceded(
peek(not(alt((tag("'"), line_terminator)))),
source_character,
))),
)(i)
}
/// `"` *double_quoted_delimiter_identifier* `"`
pub(crate) fn double_quoted_delimiter(i: Input) -> LexResult {
delimited(char('"'), double_quoted_delimiter_identifier, char('"'))(i)
}
/// ( ( *source_character* *source_character*? ) **but not** ( `"` | *line_terminator* ) )*
pub(crate) fn double_quoted_delimiter_identifier(i: Input) -> LexResult {
preceded(
peek(not(whitespace)),
recognize(many1(preceded(
peek(not(alt((tag("\""), line_terminator)))),
source_character,
))),
)(i)
}
/// ``` *command_quoted_delimiter_identifier* ```
pub(crate) fn command_quoted_delimiter(i: Input) -> LexResult {
delimited(char('`'), command_quoted_delimiter_identifier, char('`'))(i)
}
/// ( ( *source_character* *source_character*? ) **but not** ( ``` | *line_terminator* ) )*
pub(crate) fn command_quoted_delimiter_identifier(i: Input) -> LexResult {
preceded(
peek(not(whitespace)),
recognize(many1(preceded(
peek(not(alt((tag("`"), line_terminator)))),
source_character,
))),
)(i)
}
/// *indented_heredoc_end_line* | *non_indented_heredoc_end_line*
fn heredoc_end_line(i: Input) -> LexResult {
match i.metadata.heredoc.as_ref().unwrap().indentation {
Some(HeredocIndentation::Unindented) => non_indented_heredoc_end_line(i.clone()),
_ => indented_heredoc_end_line(i.clone()),
}
}
/// [ beginning of a line ] *whitespace** *heredoc_quote_type_identifier* *line_terminator*
fn indented_heredoc_end_line(i: Input) -> LexResult {
if !i.beginning_of_line() {
return Err(nom::Err::Error((i, crate::ErrorKind::Space)));
}
delimited(
many0(whitespace),
heredoc_quote_type_identifier,
alt((line_terminator, at_eof)),
)(i)
}
// Success if the end of the input has been reached
fn at_eof(i: Input) -> LexResult {
recognize(not(peek(anychar)))(i)
}
/// [ beginning of a line ] *heredoc_quote_type_identifier* *line_terminator*
fn non_indented_heredoc_end_line(i: Input) -> LexResult {
if !i.beginning_of_line() {
return Err(nom::Err::Error((i, crate::ErrorKind::Space)));
}
terminated(
heredoc_quote_type_identifier,
alt((line_terminator, at_eof)),
)(i)
}
/// *non_quoted_delimiter_identifier* | *single_quoted_delimiter_identifier* | *double_quoted_delimiter_identifier* | *command_quoted_delimiter_identifier*
fn heredoc_quote_type_identifier(i: Input) -> LexResult {
if let Some(identifier) = i.metadata.heredoc.as_ref().unwrap().identifier {
tag(identifier)(i.clone())
} else {
Err(nom::Err::Error((i.clone(), crate::ErrorKind::Char)))
}
}
/// Sets the type of heredoc indentation used
fn set_indentiation<'a, E, F>(
mut func: F,
) -> impl FnMut(Input<'a>) -> nom::IResult<Input<'a>, Option<char>, E>
where
F: nom::Parser<Input<'a>, Option<char>, E>,
{
move |i: Input<'a>| {
let res = func.parse(i);
match res {
Ok((mut i, char)) => {
i.metadata.heredoc.as_deref_mut().unwrap().indentation = match char {
Some('-') => Some(HeredocIndentation::Indented),
Some('~') => Some(HeredocIndentation::FullyIndented),
_ => Some(HeredocIndentation::Unindented),
};
Ok((i, char))
}
error @ _ => error,
}
}
}
/// Sets the type of heredoc quoting used
fn set_quote_type<'a, O1, E, F>(
mut func: F,
quote_type: HeredocQuoteType,
) -> impl FnMut(Input<'a>) -> nom::IResult<Input<'a>, O1, E>
where
F: nom::Parser<Input<'a>, O1, E>,
{
move |i: Input<'a>| {
let res = func.parse(i);
match res {
Ok((mut i, o1)) => {
i.metadata.heredoc.as_deref_mut().unwrap().quote_type = Some(quote_type);
Ok((i, o1))
}
error @ _ => error,
}
}
}
/// Manages the state of the input's heredoc parsing
fn wrap_heredoc<'a, O1, E, F>(
mut func: F,
) -> impl FnMut(Input<'a>) -> nom::IResult<Input<'a>, O1, E>
where
F: nom::Parser<Input<'a>, O1, E>,
{
move |mut i: Input<'a>| {
let original = i.metadata.heredoc;
i.metadata.heredoc = Some(Box::new(HeredocMetadata::default()));
let res = func.parse(i);
match res {
Ok((mut i, o1)) => {
// The following is a hack to intentionally expose the heredoc parser's state
// for verification purposes within this module's unit tests
#[cfg(test)]
{
if original.is_none() || !original.as_deref().unwrap().should_leak {
i.metadata.heredoc = original;
}
}
#[cfg(not(test))]
{
i.metadata.heredoc = original;
}
Ok((i, o1))
}
error @ _ => error,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! assert_signifier {
($input:expr, $ident:expr, $indent:expr, $quote:expr) => {
// Bootstrap the input with a flag that will cause the heredoc parser's state to leak
let mut i: Input = $input.into();
i.metadata.heredoc = Some(Box::new(HeredocMetadata::default()));
i.metadata.heredoc.as_deref_mut().unwrap().should_leak = true;
let (i, _result) = parser!(i).unwrap();
// Verifies the state of the heredoc parser
let heredoc = i.metadata.heredoc.as_ref().unwrap();
assert_eq!(heredoc.identifier, Some($ident));
assert_eq!(heredoc.indentation, Some($indent));
assert_eq!(heredoc.quote_type, Some($quote));
};
}
#[test]
fn test_here_document() {
fn s(v: &str) -> Node {
Node::Literal(Literal::String(v.to_owned()))
}
fn i(v: Vec<Node>) -> Node {
Node::Interpolated(Interpolated::String(v))
}
fn cs(v: &str) -> Node {
Node::Literal(Literal::Command(v.to_owned()))
}
fn ci(v: Vec<Node>) -> Node {
Node::Interpolated(Interpolated::Command(v))
}
use_parser!(here_document);
// Synax errors
assert_err!("<<foo\nbar\nfood\n");
assert_partial!("<<foo\nbar\nfoo\nextra");
// Unindented heredocs
assert_ok!("<<h\nh", s(""));
assert_partial!("<<foo + rest * of * line\nbar\nfoo\n", s("bar\n"));
assert_ok!("<<foo\n meh\n bar\n\nfoo", s(" meh\n bar\n\n"));
assert_ok!("<<-`foo`\nbar\n foot\nfoo", cs("bar\n foot\n"));
assert_err!("<<foo\nbar\n foo\n");
// Indented marker heredocs
assert_ok!("<<-foo\n bar\nfoo\n", s(" bar\n"));
assert_ok!("<<-foo\n bar\n foo", s(" bar\n"));
// Interpolated heredocs
assert_ok!(
"<<-foo\nbar#{2.4}\nfoo",
i(vec![
Node::Segment(Segment::String("bar".to_owned())),
Node::Block(vec![Node::float(2.4)]),
Node::Segment(Segment::String("\n".to_owned()))
])
);
assert_ok!(
"<<-`foo`\nbar#{2.4}\nfoo",
ci(vec![
Node::Segment(Segment::String("bar".to_owned())),
Node::Block(vec![Node::float(2.4)]),
Node::Segment(Segment::String("\n".to_owned()))
])
);
// Literal heredocs
assert_ok!("<<-'foo'\nbar#{2.4}\nfoo", s("bar#{2.4}\n"));
assert_ok!("<<-foo\nbar\\#{2.4}\nfoo", s("bar#{2.4}\n"));
// Squiggly heredocs
assert_partial!("<<~foo rest_of_line\n foo", s(""));
assert_ok!("<<~foo\n#bar\nbaz\nfoo", s("#bar\nbaz\n"));
assert_ok!(
"<<~foo\n#{2} bar\nfoo",
i(vec![
Node::Block(vec![Node::int(2)]),
Node::Segment(Segment::String(" bar\n".to_owned()))
])
);
// Squiggly heredocs with indented content
assert_ok!("<<~foo\n bar\n baz\nfoo", s(" bar\nbaz\n"));
assert_ok!(
"<<~foo\n bar#{\n2\n} stuff\n\t\n \n 3\nfoo",
i(vec![
Node::Segment(Segment::String(" bar".to_owned())),
Node::Block(vec![Node::int(2)]),
Node::Segment(Segment::String(" stuff\n\n \n3\n".to_owned()))
])
);
}
#[test]
fn test_heredoc_signifier() {
// This unit test uses a wrapped testing harness that intentionally leaks the
// heredoc parser's top-level state
fn wrapped_heredoc_signifier(i: Input) -> LexResult {
wrap_heredoc(heredoc_signifier)(i)
}
use_parser!(wrapped_heredoc_signifier);
assert_err!("<<");
assert_err!("<<FOO,");
assert_err!("<<FOO ");
assert_err!("<<'FOO");
assert_err!("<<'FOO\nBAR'");
assert_err!("<<\"bar\"\"");
assert_err!("<<`baz");
assert_err!("<<''");
assert_err!("<<-' foo'");
assert_err!("<<`baz");
assert_signifier!(
"<<foo",
"foo",
HeredocIndentation::Unindented,
HeredocQuoteType::Unquoted
);
assert_signifier!(
"<<-BAR",
"BAR",
HeredocIndentation::Indented,
HeredocQuoteType::Unquoted
);
assert_signifier!(
"<<~'BA Z'",
"BA Z",
HeredocIndentation::FullyIndented,
HeredocQuoteType::SingleQuoted
);
assert_signifier!(
"<<\"bar\"",
"bar",
HeredocIndentation::Unindented,
HeredocQuoteType::DoubleQuoted
);
assert_signifier!(
"<<-`FOO, `",
"FOO, ",
HeredocIndentation::Indented,
HeredocQuoteType::CommandQuoted
);
assert_signifier!(
"<<'foo :bar'",
"foo :bar",
HeredocIndentation::Unindented,
HeredocQuoteType::SingleQuoted
);
}
#[test]
fn test_heredoc_start_line() {
fn wrapped_heredoc_start_line(i: Input) -> StringResult {
map(wrap_heredoc(heredoc_start_line), |s| s.into())(i)
}
use_parser!(wrapped_heredoc_start_line);
assert_err!("<<-Foo");
assert_err!("<<-Foo\nbar\n");
assert_ok!("<<-Foo\n", "");
assert_ok!("<<-'FOO BAR' BAZ\n", " BAZ");
assert_ok!("<<foo, 2; 3 * blah\n", ", 2; 3 * blah");
assert_signifier!(
"<<~'foo' bar\n",
"foo",
HeredocIndentation::FullyIndented,
HeredocQuoteType::SingleQuoted
);
}
}
|
use std::fs::File;
use std::io::{BufRead, BufReader};
#[derive(Debug)]
struct Claim {
id: i32,
top: i32,
left: i32,
height: i32,
width: i32,
}
impl Claim {
fn parse(line: String) -> Claim {
let (offset, id) = find_value(&line, "#", Some(" "), 0);
let (offset, top) = find_value(&line, "@ ", Some(","), offset);
let (offset, left) = find_value(&line, ",", Some(":"), offset);
let (offset, height) = find_value(&line, ": ", Some("x"), offset);
let (_, width) = find_value(&line, "x", None, offset);
println!("{:?}", top);
return Claim {
id,
top,
left,
height,
width,
};
}
}
fn main() {
let file = File::open("input").expect("Cannot read input");
for line in BufReader::new(file).lines() {
let line = line.expect("Unable to read line");
println!("{:?}", Claim::parse(line));
}
}
fn find(line: &String, from: usize, pat: &str) -> usize {
return line[from..].find(pat).unwrap();
}
fn parse_value(line: &String, from: usize, to: Option<usize>) -> i32 {
return match to {
Some(to) => line[from..to].parse::<i32>().expect("Unable to parse value"),
None => line[from..].parse::<i32>().expect("Unable to parse value"),
};
}
fn find_value(line: &String, start: &str, end: Option<&str>, offset: usize) -> (usize, i32) {
let from = find(&line, offset, start) + offset + start.len();
return match end {
Some(end) => {
let to = find(&line, from, end) + from;
return (to, parse_value(&line, from, Some(to)));
}
None => (line.len(), parse_value(&line, from, None)),
};
}
|
use num::ToPrimitive;
use num::Zero;
use num::{BigUint, Integer};
use projecteuler::factorial;
fn main() {
dbg!(solve(100));
dbg!(solve(10));
}
fn solve(n: usize) -> usize {
let mut sum = 0;
let mut prod: BigUint = factorial::factorial(n);
dbg!(&prod);
while prod > BigUint::zero() {
let (new_prod, rem) = prod.div_rem(&BigUint::from(10usize));
sum += rem.to_usize().unwrap();
prod = new_prod;
}
sum
}
|
use rayon::prelude::*;
use std::io::prelude::*;
fn main() {
let start = std::time::Instant::now();
let mut output = std::path::PathBuf::from(reader::workspace_dir());
output.push("src/Windows");
let _ = std::fs::remove_dir_all(&output);
output.pop();
let reader = reader::TypeReader::get_mut();
include_all(&mut reader.types);
let root = reader.types.get_namespace("Windows").unwrap();
let mut trees = Vec::new();
collect_trees(&output, root.namespace, root, &mut trees);
trees.par_iter().for_each(|tree| gen_tree(&output, root.namespace, tree));
output.pop();
output.push("Cargo.toml");
write_toml(&output, root);
println!("Elapsed: {} ms", start.elapsed().as_millis());
}
fn write_toml(output: &std::path::Path, tree: &reader::TypeTree) {
let mut file = std::fs::File::create(&output).unwrap();
file.write_all(
r#"
[package]
name = "windows"
version = "0.28.0"
authors = ["Microsoft"]
edition = "2018"
license = "MIT OR Apache-2.0"
description = "Rust for Windows"
repository = "https://github.com/microsoft/windows-rs"
documentation = "https://microsoft.github.io/windows-docs-rs/"
readme = ".github/readme.md"
exclude = [".github", ".windows", "docs", "tests"]
[workspace]
members = [
"crates/deps/*",
"crates/targets/*",
"crates/tools/*",
"crates/tests/legacy/*",
"crates/tests/metadata/*",
"crates/tests/winrt/*",
"crates/tests/win32/*",
"crates/tests/core",
"crates/tests/sys",
]
exclude = ["crates/tests/component"]
[package.metadata.docs.rs]
default-target = "x86_64-pc-windows-msvc"
targets = []
[target.i686-pc-windows-msvc.dependencies]
windows_i686_msvc = { path = "crates/targets/i686_msvc", version = "0.28.0" }
[target.x86_64-pc-windows-msvc.dependencies]
windows_x86_64_msvc = { path = "crates/targets/x86_64_msvc", version = "0.28.0" }
[target.aarch64-pc-windows-msvc.dependencies]
windows_aarch64_msvc = { path = "crates/targets/aarch64_msvc", version = "0.28.0" }
[target.i686-pc-windows-gnu.dependencies]
windows_i686_gnu = { path = "crates/targets/i686_gnu", version = "0.28.0" }
[target.x86_64-pc-windows-gnu.dependencies]
windows_x86_64_gnu = { path = "crates/targets/x86_64_gnu", version = "0.28.0" }
[dependencies]
windows_macros = { path = "crates/deps/macros", version = "0.28.0", optional = true }
windows_reader = { path = "crates/deps/reader", version = "0.28.0", optional = true }
windows_gen = { path = "crates/deps/gen", version = "0.28.0", optional = true }
[features]
default = []
std = []
alloc = []
deprecated = []
build = ["windows_gen", "windows_macros", "windows_reader"]
"#
.as_bytes(),
)
.unwrap();
write_features(&mut file, tree.namespace, tree);
}
fn write_features(file: &mut std::fs::File, root: &'static str, tree: &reader::TypeTree) {
for tree in tree.namespaces.values() {
write_feature(file, root, tree);
write_features(file, root, tree);
}
}
fn write_feature(file: &mut std::fs::File, root: &'static str, tree: &reader::TypeTree) {
if !tree.include {
return;
}
let feature = tree.namespace[root.len() + 1..].replace('.', "_");
if let Some(pos) = feature.rfind('_') {
let dependency = &feature[..pos];
file.write_all(format!("{} = [\"{}\"]\n", feature, dependency).as_bytes()).unwrap();
} else {
file.write_all(format!("{} = []\n", feature).as_bytes()).unwrap();
}
}
fn include_all(tree: &mut reader::TypeTree) {
tree.include = true;
tree.types.values_mut().for_each(|entry| entry.include = reader::TypeInclude::Full);
tree.namespaces.values_mut().for_each(include_all);
tree.exclude_namespace("Windows.Win32.Interop");
}
fn collect_trees<'a>(output: &std::path::Path, root: &'static str, tree: &'a reader::TypeTree, trees: &mut Vec<&'a reader::TypeTree>) {
trees.push(tree);
tree.namespaces.values().for_each(|tree| collect_trees(output, root, tree, trees));
let mut path = std::path::PathBuf::from(output);
path.push(tree.namespace.replace('.', "/"));
std::fs::create_dir_all(&path).unwrap();
}
fn gen_tree(output: &std::path::Path, root: &'static str, tree: &reader::TypeTree) {
if !tree.include {
return;
}
println!("{}", tree.namespace);
let mut path = std::path::PathBuf::from(output);
path.push(tree.namespace.replace('.', "/"));
path.push("mod.rs");
let tokens = gen::gen_source_file(root, tree, false);
let mut child = std::process::Command::new("rustfmt").stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).spawn().expect("Failed to spawn `rustfmt`");
let mut stdin = child.stdin.take().expect("Failed to open stdin");
stdin.write_all(tokens.into_string().as_bytes()).unwrap();
drop(stdin);
let output = child.wait_with_output().unwrap();
assert!(output.status.success());
std::fs::write(&path, String::from_utf8(output.stdout).expect("Failed to parse UTF-8")).unwrap();
}
|
extern crate libc;
use self::libc::{c_int, c_uint, uint16_t, uint8_t};
pub mod gpio;
pub mod spio;
#[link(name = "bcm2835")]
extern "C" {
fn bcm2835_init() -> c_int; // returns 1 if successful 0 if not
fn bcm2835_delay(delay_time: c_uint);
fn bcm2835_gpio_write(pin: uint8_t, value: uint8_t);
fn bcm2835_gpio_lev(pin: uint8_t) -> uint8_t;
fn bcm2835_gpio_fsel(pin: uint8_t, mode: uint8_t);
fn bcm2835_spi_begin() -> c_int; // returns 1 if successful 0 if not call spi_end later
fn bcm2835_spi_end();
fn bcm2835_spi_transfer(value: uint8_t) -> uint8_t; //currently no need for the return value
fn bcm2835_spi_setBitOrder(order: uint8_t);
fn bcm2835_spi_setDataMode(mode: uint8_t);
fn bcm2835_spi_setClockDivider(divider: uint16_t);
fn bcm2835_spi_chipSelect(cs: uint8_t);
fn bcm2835_spi_setChipSelectPolarity(cs: uint8_t, active: uint8_t);
}
#[derive(PartialEq)]
pub enum PinLevel {
HIGH,
LOW,
}
impl PinLevel {
fn as_uint8_t(&self) -> uint8_t {
match *self {
PinLevel::HIGH => 1,
PinLevel::LOW => 0,
}
}
}
pub fn init() {
let x: c_int = unsafe { bcm2835_init() };
if x != 1 {
panic!("Init bcm2835 failed with code {}", x);
}
}
pub fn delay(delay_ms: u32) {
unsafe { bcm2835_delay(delay_ms as c_uint) };
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub struct CoreUserActivityManager {}
impl CoreUserActivityManager {
pub fn CreateUserActivitySessionInBackground<'a, Param0: ::windows::core::IntoParam<'a, super::UserActivity>>(activity: Param0) -> ::windows::core::Result<super::UserActivitySession> {
Self::ICoreUserActivityManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), activity.into_param().abi(), &mut result__).from_abi::<super::UserActivitySession>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn DeleteUserActivitySessionsInTimeRangeAsync<'a, Param0: ::windows::core::IntoParam<'a, super::UserActivityChannel>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::DateTime>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::DateTime>>(channel: Param0, starttime: Param1, endtime: Param2) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
Self::ICoreUserActivityManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), channel.into_param().abi(), starttime.into_param().abi(), endtime.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
})
}
pub fn ICoreUserActivityManagerStatics<R, F: FnOnce(&ICoreUserActivityManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CoreUserActivityManager, ICoreUserActivityManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for CoreUserActivityManager {
const NAME: &'static str = "Windows.ApplicationModel.UserActivities.Core.CoreUserActivityManager";
}
#[repr(transparent)]
#[doc(hidden)]
pub struct ICoreUserActivityManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICoreUserActivityManagerStatics {
type Vtable = ICoreUserActivityManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca3adb02_a4be_4d4d_bfa8_6795f4264efb);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICoreUserActivityManagerStatics_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, activity: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, channel: ::windows::core::RawPtr, starttime: super::super::super::Foundation::DateTime, endtime: super::super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
|
#![deny(
unused_import_braces,
unused_imports,
unused_comparisons,
unused_must_use,
unused_variables,
non_shorthand_field_patterns,
unreachable_code
)]
use bigint::{Address, H256, M256, U256};
use block::{Account, Transaction};
use evm::errors::{PreExecutionError, RequireError};
use evm::{
AccountChange, AccountCommitment, AccountState, HeaderParams, Memory, Patch, TransactionVM, ValidTransaction, VM,
};
use sha3::{Digest, Keccak256};
use std::cmp::min;
use std::collections::HashMap;
use std::ops::Deref;
use std::rc::Rc;
use trie::{Database, DatabaseGuard, DatabaseOwned, FixedSecureTrie, MemoryDatabase};
pub struct LiteralAccount {
pub nonce: U256,
pub balance: U256,
pub storage: HashMap<U256, M256>,
pub code: Vec<u8>,
}
#[derive(Copy, Clone, Debug)]
pub struct Stateful<'a, D: 'a> {
database: &'a D,
root: H256,
}
impl<'a, D> Stateful<'a, D> {
pub fn new(database: &'a D, root: H256) -> Self {
Self { database, root }
}
pub fn empty(database: &'a D) -> Self {
Self::new(database, MemoryDatabase::new().create_empty().root())
}
}
impl<'b, D: DatabaseOwned> Stateful<'b, D> {
fn is_empty_hash(hash: H256) -> bool {
hash == H256::from(Keccak256::digest(&[]).as_slice())
}
pub fn database(&self) -> &'b D {
self.database
}
pub fn code(&self, hash: H256) -> Option<Vec<u8>> {
let code_hashes = self.database.create_guard();
if Self::is_empty_hash(hash) {
Some(Vec::new())
} else {
code_hashes.get(hash)
}
}
pub fn step<V: VM>(&self, vm: &mut V, block_number: U256, most_recent_block_hashes: &[H256]) {
assert!(U256::from(most_recent_block_hashes.len()) >= min(block_number, U256::from(256)));
let state = self.database.create_fixed_secure_trie(self.root);
let code_hashes = self.database.create_guard();
loop {
match vm.step() {
Ok(()) => break,
Err(RequireError::Account(address)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
code_hashes.get(account.code_hash).unwrap()
};
vm.commit_account(AccountCommitment::Full {
nonce: account.nonce,
address,
balance: account.balance,
code: Rc::new(code),
})
.unwrap();
}
None => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::AccountCode(address)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
code_hashes.get(account.code_hash).unwrap()
};
vm.commit_account(AccountCommitment::Code {
address,
code: Rc::new(code),
})
.unwrap();
}
None => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::AccountStorage(address, index)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let storage = self.database.create_fixed_secure_trie(account.storage_root);
let value = storage.get(&H256::from(index)).unwrap_or_else(M256::zero);
vm.commit_account(AccountCommitment::Storage { address, index, value })
.unwrap();
}
None => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::Blockhash(number)) => {
let index = (block_number - number).as_usize();
vm.commit_blockhash(number, most_recent_block_hashes[index]).unwrap();
}
}
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn require_to_commit(&self, require: RequireError, root: Option<H256>) -> AccountCommitment {
let state = self.database.create_fixed_secure_trie(root.unwrap_or(self.root));
match require {
RequireError::Account(address) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
self.code(account.code_hash).unwrap()
};
AccountCommitment::Full {
nonce: account.nonce,
address,
balance: account.balance,
code: Rc::new(code),
}
}
None => AccountCommitment::Nonexist(address),
}
}
RequireError::AccountCode(address) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
self.code(account.code_hash).unwrap()
};
AccountCommitment::Code {
address,
code: Rc::new(code),
}
}
None => AccountCommitment::Nonexist(address),
}
}
RequireError::AccountStorage(address, index) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let storage = self.database.create_fixed_secure_trie(account.storage_root);
let value = storage.get(&H256::from(index)).unwrap_or_else(M256::zero);
AccountCommitment::Storage { address, index, value }
}
None => AccountCommitment::Nonexist(address),
}
}
RequireError::Blockhash(_) => panic!(),
}
}
pub fn call<'a, M: Memory, P: Patch>(
&self,
patch: &'a P,
transaction: ValidTransaction,
block: &HeaderParams,
most_recent_block_hashes: &[H256],
) -> TransactionVM<'a, M, P> {
assert!(U256::from(most_recent_block_hashes.len()) >= min(block.number, U256::from(256)));
let mut vm = TransactionVM::new(patch, transaction, block.clone());
let state = self.database.create_fixed_secure_trie(self.root);
let code_hashes = self.database.create_guard();
loop {
match vm.fire() {
Ok(()) => break,
Err(RequireError::Account(address)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
code_hashes.get(account.code_hash).unwrap()
};
vm.commit_account(AccountCommitment::Full {
nonce: account.nonce,
address,
balance: account.balance,
code: Rc::new(code),
})
.unwrap();
}
None => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::AccountCode(address)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
code_hashes.get(account.code_hash).unwrap()
};
vm.commit_account(AccountCommitment::Code {
address,
code: Rc::new(code),
})
.unwrap();
}
None => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::AccountStorage(address, index)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let storage = self.database.create_fixed_secure_trie(account.storage_root);
let value = storage.get(&H256::from(index)).unwrap_or_else(M256::zero);
vm.commit_account(AccountCommitment::Storage { address, index, value })
.unwrap();
}
None => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::Blockhash(number)) => {
let index = (block.number - number).as_usize();
vm.commit_blockhash(number, most_recent_block_hashes[index]).unwrap();
}
}
}
vm
}
pub fn sets(&mut self, accounts: &[(Address, LiteralAccount)]) {
let mut state = self.database.create_fixed_secure_trie(self.root);
let mut code_hashes = self.database.create_guard();
for &(address, ref account) in accounts {
let mut storage_trie = self.database.create_fixed_secure_empty();
for (key, value) in &account.storage {
if *value == M256::zero() {
storage_trie.remove(&H256::from(*key));
} else {
storage_trie.insert(H256::from(*key), *value);
}
}
let code_hash = H256::from(Keccak256::digest(&account.code).as_slice());
code_hashes.set(code_hash, account.code.clone());
let account = Account {
nonce: account.nonce,
balance: account.balance,
storage_root: storage_trie.root(),
code_hash,
};
state.insert(address, account);
}
self.root = state.root();
}
pub fn transit(&mut self, accounts: &[AccountChange]) {
let mut state = self.database.create_fixed_secure_trie(self.root);
let mut code_hashes = self.database.create_guard();
for account in accounts {
match account.clone() {
AccountChange::Full {
nonce,
address,
balance,
changing_storage,
code,
} => {
let changing_storage: HashMap<U256, M256> = changing_storage.into();
let mut account: Account = state.get(&address).unwrap();
let mut storage_trie = self.database.create_fixed_secure_trie(account.storage_root);
for (key, value) in changing_storage {
if value == M256::zero() {
storage_trie.remove(&H256::from(key));
} else {
storage_trie.insert(H256::from(key), value);
}
}
account.balance = balance;
account.nonce = nonce;
account.storage_root = storage_trie.root();
assert!(account.code_hash == H256::from(Keccak256::digest(&code).as_slice()));
state.insert(address, account);
}
AccountChange::IncreaseBalance(address, value) => match state.get(&address) {
Some(mut account) => {
account.balance = account.balance + value;
state.insert(address, account);
}
None => {
let account = Account {
nonce: U256::zero(),
balance: value,
storage_root: self.database.create_empty().root(),
code_hash: H256::from(Keccak256::digest(&[]).as_slice()),
};
state.insert(address, account);
}
},
AccountChange::Create {
nonce,
address,
balance,
storage,
code,
} => {
let storage: HashMap<U256, M256> = storage.into();
let mut storage_trie = self.database.create_fixed_secure_empty();
for (key, value) in storage {
if value == M256::zero() {
storage_trie.remove(&H256::from(key));
} else {
storage_trie.insert(H256::from(key), value);
}
}
let code_hash = H256::from(Keccak256::digest(&code).as_slice());
code_hashes.set(code_hash, code.deref().clone());
let account = Account {
nonce,
balance,
storage_root: storage_trie.root(),
code_hash,
};
state.insert(address, account);
}
AccountChange::Nonexist(address) => {
state.remove(&address);
}
}
}
self.root = state.root();
}
pub fn execute<'a, M: Memory, P: Patch>(
&mut self,
patch: &'a P,
transaction: ValidTransaction,
block: &HeaderParams,
most_recent_block_hashes: &[H256],
) -> TransactionVM<'a, M, P> {
let vm = self.call::<_, P>(patch, transaction, &block, most_recent_block_hashes);
let mut accounts = Vec::new();
for account in vm.accounts() {
accounts.push(account.clone());
}
self.transit(&accounts);
vm
}
pub fn to_valid<P: Patch>(
&self,
patch: &P,
transaction: &Transaction,
) -> Result<ValidTransaction, PreExecutionError> {
let state = self.database.create_fixed_secure_trie(self.root);
let code_hashes = self.database.create_guard();
let account_patch = patch.account_patch().clone();
let mut account_state = AccountState::new(account_patch);
loop {
match ValidTransaction::from_transaction(patch, transaction, &account_state) {
Ok(val) => return val,
Err(RequireError::Account(address)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
code_hashes.get(account.code_hash).unwrap()
};
account_state
.commit(AccountCommitment::Full {
nonce: account.nonce,
address,
balance: account.balance,
code: Rc::new(code),
})
.unwrap();
}
None => {
account_state.commit(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::AccountCode(address)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let code = if Self::is_empty_hash(account.code_hash) {
Vec::new()
} else {
code_hashes.get(account.code_hash).unwrap()
};
account_state
.commit(AccountCommitment::Code {
address,
code: Rc::new(code),
})
.unwrap();
}
None => {
account_state.commit(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::AccountStorage(address, index)) => {
let account: Option<Account> = state.get(&address);
match account {
Some(account) => {
let storage = self.database.create_fixed_secure_trie(account.storage_root);
let value = storage.get(&H256::from(index)).unwrap_or_else(M256::zero);
account_state
.commit(AccountCommitment::Storage { address, index, value })
.unwrap();
}
None => {
account_state.commit(AccountCommitment::Nonexist(address)).unwrap();
}
}
}
Err(RequireError::Blockhash(_)) => panic!(),
}
}
}
pub fn root(&self) -> H256 {
self.root
}
pub fn state_of<'a>(&'a self, root: H256) -> FixedSecureTrie<<D as Database<'a>>::Guard, Address, Account> {
self.database.create_fixed_secure_trie::<Address, Account>(root)
}
pub fn state<'a>(&'a self) -> FixedSecureTrie<<D as Database<'a>>::Guard, Address, Account> {
self.state_of(self.root())
}
pub fn storage_state_of<'a>(&'a self, root: H256) -> FixedSecureTrie<<D as Database<'a>>::Guard, H256, M256> {
self.database.create_fixed_secure_trie::<H256, M256>(root)
}
pub fn storage_state<'a>(
&'a self,
address: Address,
) -> Option<FixedSecureTrie<<D as Database<'a>>::Guard, H256, M256>> {
// Specify the full type as a workaround for https://github.com/rust-lang/rust/issues/55756
let state: FixedSecureTrie<<D as Database<'a>>::Guard, Address, Account> = self.state();
let account = state.get(&address);
match account {
Some(account) => Some(self.storage_state_of(account.storage_root)),
None => None,
}
}
}
pub type MemoryStateful<'a> = Stateful<'a, MemoryDatabase>;
|
use amethyst::{GameData, SimpleState, SimpleTrans, StateData, StateEvent, Trans};
use amethyst::core::ecs::{Entity, WorldExt};
use amethyst::input::{is_close_requested, is_key_down, is_mouse_button_down, VirtualKeyCode};
use amethyst::renderer::rendy::wsi::winit::MouseButton;
use amethyst::ui::UiCreator;
use crate::audio::audio::initialise_audio;
use crate::state::Pause;
use crate::taunt::Taunt;
use crate::timer::TimerText;
use crate::persistence::Settings;
#[derive(Debug)]
pub struct StartScreen {
settings: Settings,
ui_handle: Option<Entity>,
}
impl StartScreen {
pub fn new(settings: Settings) -> Self {
StartScreen { settings, ui_handle: None }
}
}
impl SimpleState for StartScreen {
fn on_start(&mut self, data: StateData<'_, GameData>) {
let world = data.world;
world.insert(Taunt::default());
world.insert(TimerText::default());
world.insert(Pause::default());
world.insert(self.settings);
initialise_audio(world, &self.settings);
self.ui_handle =
Some(world.exec(|mut creator: UiCreator<'_>| creator.create("ui/start.ron", ())));
}
fn on_stop(&mut self, data: StateData<GameData>) {
if let Some(root_entity) = self.ui_handle {
data.world
.delete_entity(root_entity)
.expect("Failed to remove WelcomeScreen");
}
self.ui_handle = None;
}
fn handle_event(&mut self, _: StateData<'_, GameData>, event: StateEvent) -> SimpleTrans {
match &event {
StateEvent::Window(event) => {
if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) {
log::info!("[Trans::Quit] Quitting Application!");
Trans::Quit
} else if is_mouse_button_down(&event, MouseButton::Left) {
log::info!("[Trans::Switch] Switching to MainMenu!");
Trans::Switch(Box::new(crate::state::main_menu::MainMenu::default()))
} else {
Trans::None
}
}
_ => Trans::None,
}
}
}
|
//! WASM ABI supported by the contracts module.
use oasis_contract_sdk_types::{message::Reply, ExecutionOk};
use oasis_runtime_sdk::{
context::Context,
types::{address::Address, token},
};
use super::{types, Error, Parameters};
pub mod gas;
pub mod oasis;
/// Trait for any WASM ABI to implement.
pub trait ABI<C: Context> {
/// Validate that the given WASM module conforms to the ABI.
fn validate(&self, module: &mut walrus::Module) -> Result<(), Error>;
/// Link required functions into the WASM module instance.
fn link(
&self,
instance: &mut wasm3::Instance<'_, '_, ExecutionContext<'_, C>>,
) -> Result<(), Error>;
/// Set the gas limit for any following executions.
///
/// The specified gas limit should be in regular SDK gas units, not in WASM gas units. The ABI
/// should perform any necessary conversions if required.
fn set_gas_limit(
&self,
instance: &mut wasm3::Instance<'_, '_, ExecutionContext<'_, C>>,
gas_limit: u64,
) -> Result<(), Error>;
/// Instantiate a contract.
fn instantiate<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult;
/// Call a contract.
fn call<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult;
/// Invoke the contract's reply handler.
fn handle_reply<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
reply: Reply,
) -> ExecutionResult;
/// Invoke the contract's pre-upgrade handler.
fn pre_upgrade<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult;
/// Invoke the contract's post-upgrade handler.
fn post_upgrade<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult;
/// Query a contract.
fn query<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
) -> ExecutionResult;
}
/// Execution context.
pub struct ExecutionContext<'ctx, C: Context> {
/// Transaction context.
pub tx_context: &'ctx mut C,
/// Contracts module parameters.
pub params: &'ctx Parameters,
/// Contract instance information.
pub instance_info: &'ctx types::Instance,
/// Gas limit for this contract execution.
pub gas_limit: u64,
/// Address of the caller.
pub caller_address: Address,
}
/// Result of an execution that contains additional metadata like gas used.
#[must_use]
pub struct ExecutionResult {
/// Actual execution result.
pub inner: Result<ExecutionOk, Error>,
/// Amount of gas used by the execution.
pub gas_used: u64,
}
|
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use bevy::prelude::*;
use rand::prelude::*;
use crate::populations::HerdSize;
#[readonly::make]
#[derive(Debug, Clone, Copy)]
pub struct DiseaseParameters {
/// Infection rate
infection_rate: f64,
/// Recovery rate
recovery_rate: f64,
}
impl DiseaseParameters {
pub fn new(infection_rate: f64, recovery_rate: f64) -> Self {
Self {
infection_rate,
recovery_rate,
}
}
}
// #[readonly::make]
#[derive(
Debug,
Clone,
Copy,
derive_more::Into,
derive_more::From,
derive_more::Add,
derive_more::AddAssign,
derive_more::Display,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Susceptible(pub usize);
// #[readonly::make]
#[derive(
Debug,
Clone,
Copy,
derive_more::Into,
derive_more::From,
derive_more::Add,
derive_more::AddAssign,
derive_more::Display,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Infected(pub usize);
impl Infected {
pub fn new(total_infected: usize) -> Self {
Self(total_infected)
}
// pub fn add(&mut self) {
// self.0 += 1;
// }
}
// #[readonly::make]
#[derive(Debug, derive_more::Display, derive_more::Into, derive_more::From)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Recovered(pub usize);
// pub struct Dead(pub usize);
/// This is only used to instantiate the entities that are susceptible
/// to this disease.
#[readonly::make]
#[derive(Debug, Bundle)]
pub struct DiseaseCompartments {
susceptible: Susceptible,
infected: Infected,
recovered: Recovered,
}
impl DiseaseCompartments {
pub fn new(herd_size: usize) -> Self {
Self {
susceptible: herd_size.into(),
infected: 0.into(),
recovered: 0.into(),
}
}
}
// TODO: Add a [DiseaseParameter] that is part of the [ScenarioConfiguration]
/// Update disease dynamics
pub fn update_disease_compartments(
// scenario_configuration: Res<ScenarioConfiguration>,
mut query: Query<(
&HerdSize,
&mut Susceptible,
&mut Infected,
&mut Recovered,
&DiseaseParameters,
)>,
mut rng: ResMut<StdRng>,
) {
for (herd_size, mut susceptible, mut infected, mut recovered, disease_parameters) in
query.iter_mut()
{
// dbg!("any");
let DiseaseParameters {
infection_rate,
recovery_rate,
..
} = *disease_parameters;
// maybe no-one ever recovers..
// and maybe no-one ever get infected, so we need to do something about this..
let delta_infected = infection_rate * (susceptible.0 * infected.0) as f64;
let delta_infected = delta_infected / herd_size.0 as f64;
// let delta_infected = delta_infected.round() as usize;
let delta_infected = if rng.gen_bool(delta_infected.fract()) {
delta_infected.ceil()
} else {
delta_infected.floor()
} as usize;
// newly infected may only be atmost the number of susceptible animals
debug_assert!(
delta_infected <= susceptible.0,
"cannot infect more animals than there are present."
);
let delta_recovered = recovery_rate * infected.0 as f64;
// let delta_recovered = delta_recovered.round() as usize;
let delta_recovered = if rng.gen_bool(delta_recovered.fract()) {
delta_recovered.ceil()
} else {
delta_recovered.floor()
} as usize;
// number of recovered may at most be the number of infected
debug_assert!(
delta_recovered <= infected.0,
"cannot recover more animals than infected"
);
susceptible.0 = susceptible.0.saturating_sub(delta_infected);
infected.0 = if delta_infected < delta_recovered {
infected.0.saturating_sub(delta_recovered - delta_infected)
} else {
infected.0.saturating_add(delta_infected - delta_recovered)
};
recovered.0 = recovered.0.saturating_add(delta_recovered);
}
}
/// Place one infected individual into the mix.
pub fn seed_infection_random(
mut rng: ResMut<StdRng>,
mut query: Query<(&mut Susceptible, &mut Infected)>,
) {
let mut empty_query = true;
// currently this infects everyone
// for between-herd infection, we should just infect one farm.
// Choose that one at random.. Why not?
query
.iter_mut()
.choose(&mut *rng)
.map(|(mut susceptible, mut infected)| {
// .for_each_mut(|(mut susceptible, mut infected)| {
// susceptible.0 -= 1;
susceptible.0 = susceptible
.0
.checked_sub(1)
.expect("no susceptible individuals to infect");
// (susceptible.0 < 0).then(|| panic!("no susceptible individuals to infect"));
infected.0 = infected.0.saturating_add(1);
empty_query = false;
})
.expect("couldn't find a farm to seed the infection.");
if empty_query {
panic!("failed to seed infection, as no viable infection point was found");
}
}
/// Place one infected individual into the mix.
pub fn seed_infected_everywhere(mut query: Query<(&mut Susceptible, &mut Infected)>) {
let mut empty_query = true;
// currently this infects everyone
// for between-herd infection, we should just infect one farm.
// Choose that one at random.. Why not?
query.for_each_mut(|(mut susceptible, mut infected)| {
// susceptible.0 -= 1;
susceptible.0 = susceptible
.0
.checked_sub(1)
.expect("no susceptible individuals to infect");
// (susceptible.0 < 0).then(|| panic!("no susceptible individuals to infect"));
infected.0 = infected.0.saturating_add(1);
empty_query = false;
});
if empty_query {
panic!("failed to seed infection, as no viable infection point was found");
}
}
|
use winapi::um::winuser::{WS_VISIBLE, WS_DISABLED, WS_BORDER, WS_CHILD, WS_CLIPCHILDREN, WS_EX_CONTROLPARENT};
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::NwgError;
use super::{ControlBase, ControlHandle};
const NOT_BOUND: &'static str = "Frame is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Frame handle is not HWND!";
bitflags! {
/**
The frame flags
* NONE: No flags. Equivalent to a invisible frame without borders.
* VISIBLE: The frame is immediatly visible after creation
* DISABLED: The frame chidlren cannot be interacted with by the user.
* BORDER: The frame has a thin black border
*/
pub struct FrameFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
const BORDER = WS_BORDER;
}
}
/**
A frame is a rectangle containing children controls. Frame is implemented as a custom control.
Requires the `frame` feature.
**Builder parameters:**
* `parent`: **Required.** The frame parent container.
* `size`: The frame size.
* `position`: The frame position.
* `enabled`: If the frame children can be used by the user.
* `flags`: A combination of the FrameFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
**Control events:**
* `MousePress(_)`: Generic mouse press events on the button
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
*/
#[derive(Default, PartialEq, Eq)]
pub struct Frame {
pub handle: ControlHandle
}
impl Frame {
pub fn builder() -> FrameBuilder {
FrameBuilder {
size: (100, 25),
position: (0, 0),
enabled: true,
flags: None,
ex_flags: 0,
parent: None,
}
}
/// Returns true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Sets the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Returns true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Returns true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Returns the size of the button in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Sets the size of the button in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Returns the position of the button in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Sets the position of the button in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"NWG_FRAME"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
WS_VISIBLE | WS_BORDER
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
WS_CHILD | WS_CLIPCHILDREN
}
}
impl Drop for Frame {
fn drop(&mut self) {
self.handle.destroy();
}
}
pub struct FrameBuilder {
size: (i32, i32),
position: (i32, i32),
enabled: bool,
flags: Option<FrameFlags>,
ex_flags: u32,
parent: Option<ControlHandle>
}
impl FrameBuilder {
pub fn flags(mut self, flags: FrameFlags) -> FrameBuilder {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> FrameBuilder {
self.ex_flags = flags;
self
}
pub fn size(mut self, size: (i32, i32)) -> FrameBuilder {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> FrameBuilder {
self.position = pos;
self
}
pub fn enabled(mut self, e: bool) -> FrameBuilder {
self.enabled = e;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> FrameBuilder {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Frame) -> Result<(), NwgError> {
let flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Frame"))
}?;
*out = Default::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(WS_EX_CONTROLPARENT | self.ex_flags)
.size(self.size)
.position(self.position)
.parent(Some(parent))
.build()?;
out.set_enabled(self.enabled);
Ok(())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.