text stringlengths 8 4.13M |
|---|
// Hopefully a working hangman Rust CLI
use rand::Rng;
use text_io::read;
use colorful::{Color, Colorful};
// Function to replace "underscored" word with correctly guessed letters
fn add_letters(end_word: &String, mut cur_word: String, letter: &String) -> String {
let char_letter = letter.chars().next().expect("Should be just one char whats happening?");
for (index, character) in end_word.char_indices() {
if character == char_letter { cur_word.replace_range(index*2..(index*2)+1, letter.as_ref()) }
}
return cur_word
}
// Main function
fn main() {
// Words with categories to choose from
let words = [ ("orange", "Food"), ("boat", "Transportation"), ("thelegr", "Viewer of el Chance"), ("mountain dew", "Drink"), ("vase", "household item"), ("cemetery", "place"), ("lawyer", "occupation"), ("secretary", "occupation"), ("berry", "food"), ("engine", "piece of machinery"), ("vessel", "transportation") ];
// Clear the screen
print!("\x1B[2J\x1B[1;1H");
// Randomly choose word/hint tuple from words list
let (word, hint) = words[rand::thread_rng().gen_range(0..words.len())];
// Create String from word
let word = String::from(word);
// Create mut var that is underscores of same length of the word
let mut cur_guess = std::iter::repeat("_ ").take(word.len()).collect::<String>();
// Variable in same format as cur_guess for checking if finished.
let word_space: String = word.chars().map(|c| format!("{} ", c)).collect();
// Instantiate guessed word variable for if word is guess correctly
let mut guessed_word = false;
// Keep count of incorrect guesses
let mut incorrect_guesses = 0;
// Keep track of already guessed letters
let mut already_guessed = Vec::new();
// Error variable
let mut error = String::new();
// Message variable for saying whether or not the guess was correct
let mut message = String::new();
// While loop for the game
while guessed_word == false && incorrect_guesses < 6 {
// Clear the screen for each loop
print!("\x1B[2J\x1B[1;1H");
let ascii_art = r#"
('-. .-. ('-. .-') _ _ .-') ('-. .-') _
( OO ) / ( OO ).-. ( OO ) ) ( '.( OO )_ ( OO ).-. ( OO ) )
,--. ,--. / . --. /,--./ ,--,' ,----. ,--. ,--.) / . --. /,--./ ,--,'
| | | | | \-. \ | \ | |\ ' .-./-') | `.' | | \-. \ | \ | |\
| .| |.-'-' | || \| | )| |_( O- )| |.-'-' | || \| | )
| | \| |_.' || . |/ | | .--, \| |'.'| | \| |_.' || . |/
| .-. | | .-. || |\ | (| | '. (_/| | | | | .-. || |\ |
| | | | | | | || | \ | | '--' | | | | | | | | || | \ |
`--' `--' `--' `--'`--' `--' `------' `--' `--' `--' `--'`--' `--'"#.trim_matches('\n');
println!("{}", ascii_art.gradient(Color::Green).bold());
// Print main message each loop
println!("\
Welcome to Hangman, brought to you by Rust.\
\n\
\n\
Word: {cur_guess}\
\n\
Hint: {hint}\
\n\
Guessed Letters: {already_guessed:?}\
\n", cur_guess=cur_guess, hint=hint, already_guessed = already_guessed);
// Print error message if exists
if error.is_empty() == false { println!("{}\n", error.clone().gradient(Color::Red).bold()); error.clear(); };
// Print message for correct/incorrect
if message.is_empty() == false { println!("{}\n", message); message.clear() };
println!("Please enter one letter:\n");
// Get the input and save it to the line variable
let mut guess: String = read!("{}\n");
// Format guess to lowercase
guess = guess.to_lowercase();
// Check if input is valid
if guess.len() > 1 {
error = String::from("Too many characters");
continue;
}
// Check if letter already guessed
if already_guessed.contains(&guess) {
error = String::from("Letter already guessed");
continue;
}
// Check if the letter was a correct letter
if word.contains(&guess) {
message = String::from("That is a correct letter");
cur_guess = add_letters(&word, cur_guess, &guess);
already_guessed.push(guess);
} else {
message = String::from("That letter isn't in the word");
incorrect_guesses += 1;
already_guessed.push(guess);
}
// Check to see if we have guessed the word
if cur_guess == word_space { guessed_word = true };
}
// Winning message
if guessed_word == true { println!("You have won! The correct word was {}", word.gradient(Color::Green).bold()) };
// Losing Message
if incorrect_guesses == 6 { println!("The stickman has been hung/hanged/hunged?") };
}
|
use crate::window_context::WindowContext;
use ecs::{ResourceRegistry, RunSystemPhase, Service, ECS};
use glutin::event::{ElementState, Event, MouseButton, VirtualKeyCode, WindowEvent};
fn emit_events(resources: &mut ResourceRegistry, value: &RunSystemPhase) {
let window_context = resources.get_mut::<WindowContext>().unwrap();
match value {
RunSystemPhase::Event(event) => match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::Focused(is_focused) => {
if !is_focused {
window_context.set_cursor_grab(false);
}
}
WindowEvent::MouseInput {
state: ElementState::Pressed,
button: MouseButton::Left,
..
} => {
window_context.set_cursor_grab(true);
}
WindowEvent::KeyboardInput {
input,
is_synthetic: false,
..
} => {
if let Some(key) = input.virtual_keycode {
if key == VirtualKeyCode::Escape {
window_context.set_cursor_grab(false);
}
}
}
_ => (),
},
_ => (),
},
_ => (),
}
}
pub fn load(ecs: &mut ECS) {
ecs.add_before_service(Service::at_event(emit_events));
}
|
use async_trait::async_trait;
use baipiao_bot_rust::{
Bot, Dispatcher, IssueCreatedEvent, IssueReopenedEvent, PullRequestCreatedEvent, Repository,
RunningInfo,
};
use chrono::SecondsFormat;
use log::info;
use octocrab::{models, params, Octocrab, OctocrabBuilder};
use rand::rngs::OsRng;
use rand::Rng;
use regex::Regex;
use simpler_git::{
git2,
git2::{Cred, Signature},
GitHubRepository,
};
use std::path::Path;
use std::{env, fs, fs::File, io::Write, time::Duration};
use tokio::time;
fn collect_changed_files(diff: &str) -> Vec<&str> {
let re = Regex::new(r"(\s*)diff --git a/(.+)").unwrap();
re.find_iter(diff)
.map(|m| {
m.as_str()
.splitn(3, ' ')
.last()
.unwrap()
.trim()
.trim_start_matches("diff --git ")
})
.collect()
}
struct StaticWikiBot {
github_client: Octocrab,
}
impl StaticWikiBot {
fn new(token: String) -> Self {
Self {
github_client: OctocrabBuilder::new()
.personal_token(token)
.build()
.unwrap(),
}
}
fn save_file_and_push(
&self,
repo_info: &Repository,
branch_name: &str,
language: &str,
answer: &str,
filename: &str,
content: &str,
) -> Result<(), git2::Error> {
info!("try to add file {}/{}/{}", language, answer, content);
let github_repo = GitHubRepository {
owner: repo_info.owner.clone(),
name: repo_info.name.clone(),
};
let mut repo = github_repo.clone(
format!("./{}", &repo_info.name),
Some(|| {
Cred::userpass_plaintext("baipiao-bot", &env::var("BAIPIAO_BOT_TOKEN").unwrap())
}),
)?;
if branch_name != "main" {
repo.pull(
branch_name,
Some(|| {
Cred::userpass_plaintext("baipiao-bot", &env::var("BAIPIAO_BOT_TOKEN").unwrap())
}),
)?;
}
fs::create_dir_all(format!(
"./{}/data/{}/{}/",
repo_info.name, language, answer
))
.unwrap();
let filename = if Path::new(&format!(
"./{}/data/{}/{}/{}",
repo_info.name, language, answer, filename
))
.exists()
{
let digest = md5::compute(content);
format!("{}-{:?}.md", filename.trim_end_matches(".md"), digest)
} else {
filename.to_string()
};
let mut file = File::create(format!(
"./{}/data/{}/{}/{}",
repo_info.name, language, answer, filename
))
.unwrap();
file.write_all(content.as_bytes()).unwrap();
drop(file);
let tree_id = repo.add_all()?;
let signature = Signature::now("baipiao-bot", "moss_the_bot@163.com")?;
repo.commit(
tree_id,
"contribute: merge contribution from issue",
signature,
)?;
repo.push(
|| Cred::userpass_plaintext("baipiao-bot", &env::var("BAIPIAO_BOT_TOKEN").unwrap()),
branch_name,
)
}
async fn merge_pr(&self, repo: &Repository, pr_id: usize) {
let pr = self
.github_client
.pulls(&repo.owner, &repo.name)
.get(pr_id as _)
.await
.unwrap();
self.github_client
.pulls(&repo.owner, &repo.name)
.merge(pr_id as _)
.title(&pr.title)
.message(&pr.title)
.method(params::pulls::MergeMethod::Squash)
.send()
.await
.unwrap();
}
async fn comment(&self, repo: &Repository, issue_id: usize, content: &str) {
self.github_client
.issues(&repo.owner, &repo.name)
.create_comment(issue_id as u64, content)
.await
.unwrap();
info!("commented on {}/{}#{}", repo.owner, repo.name, issue_id);
}
async fn close_issue(&self, repo: &Repository, issue_id: usize) {
self.github_client
.issues(&repo.owner, &repo.name)
.update(issue_id as _)
.state(models::IssueState::Closed)
.send()
.await
.unwrap();
}
fn update_file_contents(content: &str, author: &str) -> String {
let mut splitted = content.split("---");
let nothing = splitted.next();
assert_eq!(nothing, Some(""));
let mut meta = splitted.next().unwrap().to_string();
let now = chrono::Utc::now();
meta += &format!(
"author: {}\nlast_update: {}\n",
author,
now.to_rfc3339_opts(SecondsFormat::Secs, true)
);
let content = splitted.next().unwrap();
assert_eq!(splitted.next(), None);
format!("---\n{}---\n{}", meta, content)
}
async fn handle_contribute_issue(
&self,
repo: &Repository,
id: usize,
title: &str,
body: &str,
author: &str,
locker_id: usize,
) {
info!("Contribute issue created with title {}", title);
let title = title.strip_prefix("[Contribute] ").unwrap();
let content_start = body.find("---").unwrap();
let mut meta = body[..content_start].split('\n').map(|it| it.trim());
let language = meta
.clone()
.find(|it| it.starts_with("language:"))
.map(|it| it.trim_start_matches("language:").trim())
.unwrap();
let answer = meta
.find(|it| it.starts_with("answer:"))
.map(|it| it.trim_start_matches("answer:").trim())
.unwrap();
let content = &body[content_start..];
self.acquire_lock_with_issue(&repo, locker_id).await;
let content = Self::update_file_contents(content, author);
self.save_file_and_push(
&repo,
"main",
language,
answer,
&format!(
"{}.md",
title
.replace(".", "-")
.replace("&", "%26")
.replace("/", "%2F")
),
&content,
)
.unwrap();
info!("File saved and pushed {}", title);
self.comment(&repo, id, "Merged. Thank you for contribution!")
.await;
self.close_issue(&repo, id).await;
// we won't unlock here, build site action will do the unlock job
}
async fn acquire_lock_with_issue(&self, repo: &Repository, locker_id: usize) {
loop {
let current_holder = self.current_lock_holder(repo).await;
match current_holder {
None => {
info!("Seems no body is holding the lock, try to acquire it...");
self.github_client
.issues(&repo.owner, &repo.name)
.update(1)
.body(&format!("{}", locker_id))
.send()
.await
.map_err(|_| info!("Error raised by GitHub, retry ..."));
}
Some(x) if x == locker_id => {
info!("Seems I got the lock successfully, waiting for any possible concurrent running locker...");
time::sleep(Duration::from_secs(10)).await;
let current_holder_after_wait = self.current_lock_holder(&repo).await;
match current_holder_after_wait {
Some(x) if x == locker_id => {
info!("I still have the lock! Acquire success!");
break;
}
_ => info!("I lost the lock TAT, I'll retry ..."),
}
}
Some(current_holder) => {
info!("Blocked by {}, wait and retry ...", current_holder);
time::sleep(Duration::from_secs(10)).await;
time::sleep(Duration::from_millis(OsRng.gen_range(0..10000))).await;
}
}
}
}
async fn current_lock_holder(&self, repo: &Repository) -> Option<usize> {
self.github_client
.issues(&repo.owner, &repo.name)
.get(1)
.await
.unwrap()
.body
.and_then(|holder| usize::from_str_radix(&holder, 10).ok())
}
async fn handle_contribute_pr(&self, repo: &Repository, id: usize, locker_id: usize) {
info!("Contribute pr created with id {}", id);
let diff = self
.github_client
.pulls(&repo.owner, &repo.name)
.get_patch(id as _)
.await
.unwrap();
info!("diff: {}", diff);
let changed_files = collect_changed_files(&diff);
println!("changed files: {:?}", changed_files);
let all_files_valid = collect_changed_files(&diff)
.iter()
.all(|it| it.starts_with("a/data") && it.ends_with(".md"));
if all_files_valid {
self.acquire_lock_with_issue(&repo, locker_id).await;
self.merge_pr(&repo, id).await;
} else {
self.comment(
repo,
id,
"Sorry I cannot make sure your PR is safe to merge.\n@longfangsong PTAL.",
)
.await;
}
}
}
#[async_trait]
impl Bot for StaticWikiBot {
async fn on_issue_created(
&self,
repo: Repository,
running_info: RunningInfo,
event: IssueCreatedEvent,
) {
if event.title.starts_with("[Contribute]") {
self.handle_contribute_issue(
&repo,
event.id,
&event.title,
&event.body,
&event.user,
running_info.run_id,
)
.await;
}
}
async fn on_issue_reopened(
&self,
repo: Repository,
running_info: RunningInfo,
event: IssueReopenedEvent,
) {
if event.title.starts_with("[Contribute]") {
self.handle_contribute_issue(
&repo,
event.id,
&event.title,
&event.body,
&event.user,
running_info.run_id,
)
.await;
}
}
async fn on_pull_request_created(
&self,
repo: Repository,
running_info: RunningInfo,
event: PullRequestCreatedEvent,
) {
self.handle_contribute_pr(&repo, event.id, running_info.run_id)
.await;
}
}
#[tokio::main]
async fn main() {
env_logger::init();
let token = env::var("BAIPIAO_BOT_TOKEN").unwrap();
let bot = StaticWikiBot::new(token);
let dispatcher = Dispatcher::new(bot);
let content = env::var("JSON").unwrap();
let input: serde_json::Value = serde_json::from_str(&content).unwrap();
dispatcher.dispatch_event(input).await;
}
|
use virtual_filesystem::virtual_filesystem::command::pwd;
use virtual_filesystem::virtual_filesystem::shell::{CommandError, Buffer, Shell};
use virtual_filesystem::virtual_filesystem_core::logger::LoggerRepository;
struct MockLoggerRepository {}
impl LoggerRepository for MockLoggerRepository {
fn print(&self, message: &str) {
println!("{}", message);
}
}
fn main() {
println!("start interactive shell. Enjoy! :/");
println!("to stop, press Ctrl + c or type exit");
println!("if you need help, type :?");
let mut shell = Shell::init();
loop {
println!("[{}] $> ", pwd(&shell.current));
let mut buffer = Buffer::new();
std::io::stdin().read_line(&mut buffer).unwrap();
let buffer = buffer.trim();
if buffer == "exit" { break }
else if buffer == ":?" {
println!("to stop, press Ctrl + c or type exit");
println!("command list");
println!(" ls");
println!(" pwd");
println!(" cd [directory]");
println!(" find [path]");
println!(" mkdir [directory]");
println!(" touch [file]");
println!(" read [file]");
println!(" write [file] [string]");
println!(" exit");
continue
}
match shell.run(buffer) {
Ok(None) => {},
Ok(Some(response)) => { println!("{}", response) },
Err(CommandError::UnknownError) => { println!("unknown error.") },
Err(CommandError::NotFound) => { println!("not found.") },
Err(CommandError::IllegalArgument) => { println!("illegal argument.") },
Err(CommandError::NotFile) => { println!("not file.") },
Err(CommandError::CommandNotFound(command)) => { println!("{} command not found.", command) },
}
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qmovie.h
// dst-file: /src/gui/qmovie.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qobject::*; // 771
use std::ops::Deref;
use super::super::core::qsize::*; // 771
use super::super::core::qiodevice::*; // 771
use super::qimage::*; // 773
use super::super::core::qstring::*; // 771
use super::super::core::qbytearray::*; // 771
use super::super::core::qobjectdefs::*; // 771
// use super::qlist::*; // 775
use super::super::core::qrect::*; // 771
use super::qcolor::*; // 773
use super::qpixmap::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QMovie_Class_Size() -> c_int;
// proto: void QMovie::QMovie(QObject * parent);
fn C_ZN6QMovieC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: int QMovie::speed();
fn C_ZNK6QMovie5speedEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMovie::jumpToNextFrame();
fn C_ZN6QMovie15jumpToNextFrameEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QMovie::frameCount();
fn C_ZNK6QMovie10frameCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QMovie::setScaledSize(const QSize & size);
fn C_ZN6QMovie13setScaledSizeERK5QSize(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QMovie::setDevice(QIODevice * device);
fn C_ZN6QMovie9setDeviceEP9QIODevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QImage QMovie::currentImage();
fn C_ZNK6QMovie12currentImageEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QMovie::jumpToFrame(int frameNumber);
fn C_ZN6QMovie11jumpToFrameEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_char;
// proto: void QMovie::QMovie(const QString & fileName, const QByteArray & format, QObject * parent);
fn C_ZN6QMovieC2ERK7QStringRK10QByteArrayP7QObject(arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> u64;
// proto: const QMetaObject * QMovie::metaObject();
fn C_ZNK6QMovie10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QMovie::~QMovie();
fn C_ZN6QMovieD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QMovie::start();
fn C_ZN6QMovie5startEv(qthis: u64 /* *mut c_void*/);
// proto: int QMovie::loopCount();
fn C_ZNK6QMovie9loopCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QMovie::QMovie(QIODevice * device, const QByteArray & format, QObject * parent);
fn C_ZN6QMovieC2EP9QIODeviceRK10QByteArrayP7QObject(arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> u64;
// proto: void QMovie::setFormat(const QByteArray & format);
fn C_ZN6QMovie9setFormatERK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QList<QByteArray> QMovie::supportedFormats();
fn C_ZN6QMovie16supportedFormatsEv() -> *mut c_void;
// proto: QRect QMovie::frameRect();
fn C_ZNK6QMovie9frameRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QMovie::setPaused(bool paused);
fn C_ZN6QMovie9setPausedEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QSize QMovie::scaledSize();
fn C_ZN6QMovie10scaledSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QIODevice * QMovie::device();
fn C_ZNK6QMovie6deviceEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QMovie::setBackgroundColor(const QColor & color);
fn C_ZN6QMovie18setBackgroundColorERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QMovie::isValid();
fn C_ZNK6QMovie7isValidEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QMovie::setSpeed(int percentSpeed);
fn C_ZN6QMovie8setSpeedEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QMovie::stop();
fn C_ZN6QMovie4stopEv(qthis: u64 /* *mut c_void*/);
// proto: int QMovie::currentFrameNumber();
fn C_ZNK6QMovie18currentFrameNumberEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMovie::nextFrameDelay();
fn C_ZNK6QMovie14nextFrameDelayEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QPixmap QMovie::currentPixmap();
fn C_ZNK6QMovie13currentPixmapEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QByteArray QMovie::format();
fn C_ZNK6QMovie6formatEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QMovie::fileName();
fn C_ZNK6QMovie8fileNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QColor QMovie::backgroundColor();
fn C_ZNK6QMovie15backgroundColorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QMovie::setFileName(const QString & fileName);
fn C_ZN6QMovie11setFileNameERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
fn QMovie_SlotProxy_connect__ZN6QMovie7resizedERK5QSize(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QMovie_SlotProxy_connect__ZN6QMovie12frameChangedEi(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QMovie_SlotProxy_connect__ZN6QMovie8finishedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QMovie_SlotProxy_connect__ZN6QMovie7startedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QMovie_SlotProxy_connect__ZN6QMovie7updatedERK5QRect(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QMovie)=1
#[derive(Default)]
pub struct QMovie {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
pub _updated: QMovie_updated_signal,
pub _stateChanged: QMovie_stateChanged_signal,
pub _started: QMovie_started_signal,
pub _resized: QMovie_resized_signal,
pub _finished: QMovie_finished_signal,
pub _error: QMovie_error_signal,
pub _frameChanged: QMovie_frameChanged_signal,
}
impl /*struct*/ QMovie {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMovie {
return QMovie{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QMovie {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QMovie {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QMovie::QMovie(QObject * parent);
impl /*struct*/ QMovie {
pub fn new<T: QMovie_new>(value: T) -> QMovie {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMovie_new {
fn new(self) -> QMovie;
}
// proto: void QMovie::QMovie(QObject * parent);
impl<'a> /*trait*/ QMovie_new for (Option<&'a QObject>) {
fn new(self) -> QMovie {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovieC2EP7QObject()};
let ctysz: c_int = unsafe{QMovie_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN6QMovieC2EP7QObject(arg0)};
let rsthis = QMovie{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QMovie::speed();
impl /*struct*/ QMovie {
pub fn speed<RetType, T: QMovie_speed<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.speed(self);
// return 1;
}
}
pub trait QMovie_speed<RetType> {
fn speed(self , rsthis: & QMovie) -> RetType;
}
// proto: int QMovie::speed();
impl<'a> /*trait*/ QMovie_speed<i32> for () {
fn speed(self , rsthis: & QMovie) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie5speedEv()};
let mut ret = unsafe {C_ZNK6QMovie5speedEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMovie::jumpToNextFrame();
impl /*struct*/ QMovie {
pub fn jumpToNextFrame<RetType, T: QMovie_jumpToNextFrame<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.jumpToNextFrame(self);
// return 1;
}
}
pub trait QMovie_jumpToNextFrame<RetType> {
fn jumpToNextFrame(self , rsthis: & QMovie) -> RetType;
}
// proto: bool QMovie::jumpToNextFrame();
impl<'a> /*trait*/ QMovie_jumpToNextFrame<i8> for () {
fn jumpToNextFrame(self , rsthis: & QMovie) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie15jumpToNextFrameEv()};
let mut ret = unsafe {C_ZN6QMovie15jumpToNextFrameEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMovie::frameCount();
impl /*struct*/ QMovie {
pub fn frameCount<RetType, T: QMovie_frameCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.frameCount(self);
// return 1;
}
}
pub trait QMovie_frameCount<RetType> {
fn frameCount(self , rsthis: & QMovie) -> RetType;
}
// proto: int QMovie::frameCount();
impl<'a> /*trait*/ QMovie_frameCount<i32> for () {
fn frameCount(self , rsthis: & QMovie) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie10frameCountEv()};
let mut ret = unsafe {C_ZNK6QMovie10frameCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QMovie::setScaledSize(const QSize & size);
impl /*struct*/ QMovie {
pub fn setScaledSize<RetType, T: QMovie_setScaledSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setScaledSize(self);
// return 1;
}
}
pub trait QMovie_setScaledSize<RetType> {
fn setScaledSize(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setScaledSize(const QSize & size);
impl<'a> /*trait*/ QMovie_setScaledSize<()> for (&'a QSize) {
fn setScaledSize(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie13setScaledSizeERK5QSize()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QMovie13setScaledSizeERK5QSize(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QMovie::setDevice(QIODevice * device);
impl /*struct*/ QMovie {
pub fn setDevice<RetType, T: QMovie_setDevice<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setDevice(self);
// return 1;
}
}
pub trait QMovie_setDevice<RetType> {
fn setDevice(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setDevice(QIODevice * device);
impl<'a> /*trait*/ QMovie_setDevice<()> for (&'a QIODevice) {
fn setDevice(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie9setDeviceEP9QIODevice()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QMovie9setDeviceEP9QIODevice(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QImage QMovie::currentImage();
impl /*struct*/ QMovie {
pub fn currentImage<RetType, T: QMovie_currentImage<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentImage(self);
// return 1;
}
}
pub trait QMovie_currentImage<RetType> {
fn currentImage(self , rsthis: & QMovie) -> RetType;
}
// proto: QImage QMovie::currentImage();
impl<'a> /*trait*/ QMovie_currentImage<QImage> for () {
fn currentImage(self , rsthis: & QMovie) -> QImage {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie12currentImageEv()};
let mut ret = unsafe {C_ZNK6QMovie12currentImageEv(rsthis.qclsinst)};
let mut ret1 = QImage::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QMovie::jumpToFrame(int frameNumber);
impl /*struct*/ QMovie {
pub fn jumpToFrame<RetType, T: QMovie_jumpToFrame<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.jumpToFrame(self);
// return 1;
}
}
pub trait QMovie_jumpToFrame<RetType> {
fn jumpToFrame(self , rsthis: & QMovie) -> RetType;
}
// proto: bool QMovie::jumpToFrame(int frameNumber);
impl<'a> /*trait*/ QMovie_jumpToFrame<i8> for (i32) {
fn jumpToFrame(self , rsthis: & QMovie) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie11jumpToFrameEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN6QMovie11jumpToFrameEi(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QMovie::QMovie(const QString & fileName, const QByteArray & format, QObject * parent);
impl<'a> /*trait*/ QMovie_new for (&'a QString, Option<&'a QByteArray>, Option<&'a QObject>) {
fn new(self) -> QMovie {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovieC2ERK7QStringRK10QByteArrayP7QObject()};
let ctysz: c_int = unsafe{QMovie_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QByteArray::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let arg2 = (if self.2.is_none() {0} else {self.2.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN6QMovieC2ERK7QStringRK10QByteArrayP7QObject(arg0, arg1, arg2)};
let rsthis = QMovie{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QMovie::metaObject();
impl /*struct*/ QMovie {
pub fn metaObject<RetType, T: QMovie_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QMovie_metaObject<RetType> {
fn metaObject(self , rsthis: & QMovie) -> RetType;
}
// proto: const QMetaObject * QMovie::metaObject();
impl<'a> /*trait*/ QMovie_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QMovie) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie10metaObjectEv()};
let mut ret = unsafe {C_ZNK6QMovie10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QMovie::~QMovie();
impl /*struct*/ QMovie {
pub fn free<RetType, T: QMovie_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QMovie_free<RetType> {
fn free(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::~QMovie();
impl<'a> /*trait*/ QMovie_free<()> for () {
fn free(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovieD2Ev()};
unsafe {C_ZN6QMovieD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QMovie::start();
impl /*struct*/ QMovie {
pub fn start<RetType, T: QMovie_start<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.start(self);
// return 1;
}
}
pub trait QMovie_start<RetType> {
fn start(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::start();
impl<'a> /*trait*/ QMovie_start<()> for () {
fn start(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie5startEv()};
unsafe {C_ZN6QMovie5startEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QMovie::loopCount();
impl /*struct*/ QMovie {
pub fn loopCount<RetType, T: QMovie_loopCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.loopCount(self);
// return 1;
}
}
pub trait QMovie_loopCount<RetType> {
fn loopCount(self , rsthis: & QMovie) -> RetType;
}
// proto: int QMovie::loopCount();
impl<'a> /*trait*/ QMovie_loopCount<i32> for () {
fn loopCount(self , rsthis: & QMovie) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie9loopCountEv()};
let mut ret = unsafe {C_ZNK6QMovie9loopCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QMovie::QMovie(QIODevice * device, const QByteArray & format, QObject * parent);
impl<'a> /*trait*/ QMovie_new for (&'a QIODevice, Option<&'a QByteArray>, Option<&'a QObject>) {
fn new(self) -> QMovie {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovieC2EP9QIODeviceRK10QByteArrayP7QObject()};
let ctysz: c_int = unsafe{QMovie_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QByteArray::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let arg2 = (if self.2.is_none() {0} else {self.2.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN6QMovieC2EP9QIODeviceRK10QByteArrayP7QObject(arg0, arg1, arg2)};
let rsthis = QMovie{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QMovie::setFormat(const QByteArray & format);
impl /*struct*/ QMovie {
pub fn setFormat<RetType, T: QMovie_setFormat<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFormat(self);
// return 1;
}
}
pub trait QMovie_setFormat<RetType> {
fn setFormat(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setFormat(const QByteArray & format);
impl<'a> /*trait*/ QMovie_setFormat<()> for (&'a QByteArray) {
fn setFormat(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie9setFormatERK10QByteArray()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QMovie9setFormatERK10QByteArray(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static QList<QByteArray> QMovie::supportedFormats();
impl /*struct*/ QMovie {
pub fn supportedFormats_s<RetType, T: QMovie_supportedFormats_s<RetType>>( overload_args: T) -> RetType {
return overload_args.supportedFormats_s();
// return 1;
}
}
pub trait QMovie_supportedFormats_s<RetType> {
fn supportedFormats_s(self ) -> RetType;
}
// proto: static QList<QByteArray> QMovie::supportedFormats();
impl<'a> /*trait*/ QMovie_supportedFormats_s<u64> for () {
fn supportedFormats_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie16supportedFormatsEv()};
let mut ret = unsafe {C_ZN6QMovie16supportedFormatsEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: QRect QMovie::frameRect();
impl /*struct*/ QMovie {
pub fn frameRect<RetType, T: QMovie_frameRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.frameRect(self);
// return 1;
}
}
pub trait QMovie_frameRect<RetType> {
fn frameRect(self , rsthis: & QMovie) -> RetType;
}
// proto: QRect QMovie::frameRect();
impl<'a> /*trait*/ QMovie_frameRect<QRect> for () {
fn frameRect(self , rsthis: & QMovie) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie9frameRectEv()};
let mut ret = unsafe {C_ZNK6QMovie9frameRectEv(rsthis.qclsinst)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QMovie::setPaused(bool paused);
impl /*struct*/ QMovie {
pub fn setPaused<RetType, T: QMovie_setPaused<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPaused(self);
// return 1;
}
}
pub trait QMovie_setPaused<RetType> {
fn setPaused(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setPaused(bool paused);
impl<'a> /*trait*/ QMovie_setPaused<()> for (i8) {
fn setPaused(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie9setPausedEb()};
let arg0 = self as c_char;
unsafe {C_ZN6QMovie9setPausedEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSize QMovie::scaledSize();
impl /*struct*/ QMovie {
pub fn scaledSize<RetType, T: QMovie_scaledSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scaledSize(self);
// return 1;
}
}
pub trait QMovie_scaledSize<RetType> {
fn scaledSize(self , rsthis: & QMovie) -> RetType;
}
// proto: QSize QMovie::scaledSize();
impl<'a> /*trait*/ QMovie_scaledSize<QSize> for () {
fn scaledSize(self , rsthis: & QMovie) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie10scaledSizeEv()};
let mut ret = unsafe {C_ZN6QMovie10scaledSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QIODevice * QMovie::device();
impl /*struct*/ QMovie {
pub fn device<RetType, T: QMovie_device<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.device(self);
// return 1;
}
}
pub trait QMovie_device<RetType> {
fn device(self , rsthis: & QMovie) -> RetType;
}
// proto: QIODevice * QMovie::device();
impl<'a> /*trait*/ QMovie_device<QIODevice> for () {
fn device(self , rsthis: & QMovie) -> QIODevice {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie6deviceEv()};
let mut ret = unsafe {C_ZNK6QMovie6deviceEv(rsthis.qclsinst)};
let mut ret1 = QIODevice::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QMovie::setBackgroundColor(const QColor & color);
impl /*struct*/ QMovie {
pub fn setBackgroundColor<RetType, T: QMovie_setBackgroundColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBackgroundColor(self);
// return 1;
}
}
pub trait QMovie_setBackgroundColor<RetType> {
fn setBackgroundColor(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setBackgroundColor(const QColor & color);
impl<'a> /*trait*/ QMovie_setBackgroundColor<()> for (&'a QColor) {
fn setBackgroundColor(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie18setBackgroundColorERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QMovie18setBackgroundColorERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QMovie::isValid();
impl /*struct*/ QMovie {
pub fn isValid<RetType, T: QMovie_isValid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isValid(self);
// return 1;
}
}
pub trait QMovie_isValid<RetType> {
fn isValid(self , rsthis: & QMovie) -> RetType;
}
// proto: bool QMovie::isValid();
impl<'a> /*trait*/ QMovie_isValid<i8> for () {
fn isValid(self , rsthis: & QMovie) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie7isValidEv()};
let mut ret = unsafe {C_ZNK6QMovie7isValidEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QMovie::setSpeed(int percentSpeed);
impl /*struct*/ QMovie {
pub fn setSpeed<RetType, T: QMovie_setSpeed<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSpeed(self);
// return 1;
}
}
pub trait QMovie_setSpeed<RetType> {
fn setSpeed(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setSpeed(int percentSpeed);
impl<'a> /*trait*/ QMovie_setSpeed<()> for (i32) {
fn setSpeed(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie8setSpeedEi()};
let arg0 = self as c_int;
unsafe {C_ZN6QMovie8setSpeedEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QMovie::stop();
impl /*struct*/ QMovie {
pub fn stop<RetType, T: QMovie_stop<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.stop(self);
// return 1;
}
}
pub trait QMovie_stop<RetType> {
fn stop(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::stop();
impl<'a> /*trait*/ QMovie_stop<()> for () {
fn stop(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie4stopEv()};
unsafe {C_ZN6QMovie4stopEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QMovie::currentFrameNumber();
impl /*struct*/ QMovie {
pub fn currentFrameNumber<RetType, T: QMovie_currentFrameNumber<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentFrameNumber(self);
// return 1;
}
}
pub trait QMovie_currentFrameNumber<RetType> {
fn currentFrameNumber(self , rsthis: & QMovie) -> RetType;
}
// proto: int QMovie::currentFrameNumber();
impl<'a> /*trait*/ QMovie_currentFrameNumber<i32> for () {
fn currentFrameNumber(self , rsthis: & QMovie) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie18currentFrameNumberEv()};
let mut ret = unsafe {C_ZNK6QMovie18currentFrameNumberEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMovie::nextFrameDelay();
impl /*struct*/ QMovie {
pub fn nextFrameDelay<RetType, T: QMovie_nextFrameDelay<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.nextFrameDelay(self);
// return 1;
}
}
pub trait QMovie_nextFrameDelay<RetType> {
fn nextFrameDelay(self , rsthis: & QMovie) -> RetType;
}
// proto: int QMovie::nextFrameDelay();
impl<'a> /*trait*/ QMovie_nextFrameDelay<i32> for () {
fn nextFrameDelay(self , rsthis: & QMovie) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie14nextFrameDelayEv()};
let mut ret = unsafe {C_ZNK6QMovie14nextFrameDelayEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QPixmap QMovie::currentPixmap();
impl /*struct*/ QMovie {
pub fn currentPixmap<RetType, T: QMovie_currentPixmap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentPixmap(self);
// return 1;
}
}
pub trait QMovie_currentPixmap<RetType> {
fn currentPixmap(self , rsthis: & QMovie) -> RetType;
}
// proto: QPixmap QMovie::currentPixmap();
impl<'a> /*trait*/ QMovie_currentPixmap<QPixmap> for () {
fn currentPixmap(self , rsthis: & QMovie) -> QPixmap {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie13currentPixmapEv()};
let mut ret = unsafe {C_ZNK6QMovie13currentPixmapEv(rsthis.qclsinst)};
let mut ret1 = QPixmap::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QByteArray QMovie::format();
impl /*struct*/ QMovie {
pub fn format<RetType, T: QMovie_format<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.format(self);
// return 1;
}
}
pub trait QMovie_format<RetType> {
fn format(self , rsthis: & QMovie) -> RetType;
}
// proto: QByteArray QMovie::format();
impl<'a> /*trait*/ QMovie_format<QByteArray> for () {
fn format(self , rsthis: & QMovie) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie6formatEv()};
let mut ret = unsafe {C_ZNK6QMovie6formatEv(rsthis.qclsinst)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QMovie::fileName();
impl /*struct*/ QMovie {
pub fn fileName<RetType, T: QMovie_fileName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.fileName(self);
// return 1;
}
}
pub trait QMovie_fileName<RetType> {
fn fileName(self , rsthis: & QMovie) -> RetType;
}
// proto: QString QMovie::fileName();
impl<'a> /*trait*/ QMovie_fileName<QString> for () {
fn fileName(self , rsthis: & QMovie) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie8fileNameEv()};
let mut ret = unsafe {C_ZNK6QMovie8fileNameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QColor QMovie::backgroundColor();
impl /*struct*/ QMovie {
pub fn backgroundColor<RetType, T: QMovie_backgroundColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.backgroundColor(self);
// return 1;
}
}
pub trait QMovie_backgroundColor<RetType> {
fn backgroundColor(self , rsthis: & QMovie) -> RetType;
}
// proto: QColor QMovie::backgroundColor();
impl<'a> /*trait*/ QMovie_backgroundColor<QColor> for () {
fn backgroundColor(self , rsthis: & QMovie) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QMovie15backgroundColorEv()};
let mut ret = unsafe {C_ZNK6QMovie15backgroundColorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QMovie::setFileName(const QString & fileName);
impl /*struct*/ QMovie {
pub fn setFileName<RetType, T: QMovie_setFileName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFileName(self);
// return 1;
}
}
pub trait QMovie_setFileName<RetType> {
fn setFileName(self , rsthis: & QMovie) -> RetType;
}
// proto: void QMovie::setFileName(const QString & fileName);
impl<'a> /*trait*/ QMovie_setFileName<()> for (&'a QString) {
fn setFileName(self , rsthis: & QMovie) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QMovie11setFileNameERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QMovie11setFileNameERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
#[derive(Default)] // for QMovie_updated
pub struct QMovie_updated_signal{poi:u64}
impl /* struct */ QMovie {
pub fn updated(&self) -> QMovie_updated_signal {
return QMovie_updated_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_updated_signal {
pub fn connect<T: QMovie_updated_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_updated_signal_connect {
fn connect(self, sigthis: QMovie_updated_signal);
}
#[derive(Default)] // for QMovie_stateChanged
pub struct QMovie_stateChanged_signal{poi:u64}
impl /* struct */ QMovie {
pub fn stateChanged(&self) -> QMovie_stateChanged_signal {
return QMovie_stateChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_stateChanged_signal {
pub fn connect<T: QMovie_stateChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_stateChanged_signal_connect {
fn connect(self, sigthis: QMovie_stateChanged_signal);
}
#[derive(Default)] // for QMovie_started
pub struct QMovie_started_signal{poi:u64}
impl /* struct */ QMovie {
pub fn started(&self) -> QMovie_started_signal {
return QMovie_started_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_started_signal {
pub fn connect<T: QMovie_started_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_started_signal_connect {
fn connect(self, sigthis: QMovie_started_signal);
}
#[derive(Default)] // for QMovie_resized
pub struct QMovie_resized_signal{poi:u64}
impl /* struct */ QMovie {
pub fn resized(&self) -> QMovie_resized_signal {
return QMovie_resized_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_resized_signal {
pub fn connect<T: QMovie_resized_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_resized_signal_connect {
fn connect(self, sigthis: QMovie_resized_signal);
}
#[derive(Default)] // for QMovie_finished
pub struct QMovie_finished_signal{poi:u64}
impl /* struct */ QMovie {
pub fn finished(&self) -> QMovie_finished_signal {
return QMovie_finished_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_finished_signal {
pub fn connect<T: QMovie_finished_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_finished_signal_connect {
fn connect(self, sigthis: QMovie_finished_signal);
}
#[derive(Default)] // for QMovie_error
pub struct QMovie_error_signal{poi:u64}
impl /* struct */ QMovie {
pub fn error(&self) -> QMovie_error_signal {
return QMovie_error_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_error_signal {
pub fn connect<T: QMovie_error_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_error_signal_connect {
fn connect(self, sigthis: QMovie_error_signal);
}
#[derive(Default)] // for QMovie_frameChanged
pub struct QMovie_frameChanged_signal{poi:u64}
impl /* struct */ QMovie {
pub fn frameChanged(&self) -> QMovie_frameChanged_signal {
return QMovie_frameChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QMovie_frameChanged_signal {
pub fn connect<T: QMovie_frameChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QMovie_frameChanged_signal_connect {
fn connect(self, sigthis: QMovie_frameChanged_signal);
}
// resized(const class QSize &)
extern fn QMovie_resized_signal_connect_cb_0(rsfptr:fn(QSize), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QSize::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QMovie_resized_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QSize)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QSize::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QMovie_resized_signal_connect for fn(QSize) {
fn connect(self, sigthis: QMovie_resized_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_resized_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie7resizedERK5QSize(arg0, arg1, arg2)};
}
}
impl /* trait */ QMovie_resized_signal_connect for Box<Fn(QSize)> {
fn connect(self, sigthis: QMovie_resized_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_resized_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie7resizedERK5QSize(arg0, arg1, arg2)};
}
}
// frameChanged(int)
extern fn QMovie_frameChanged_signal_connect_cb_1(rsfptr:fn(i32), arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
rsfptr(rsarg0);
}
extern fn QMovie_frameChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(i32)>, arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QMovie_frameChanged_signal_connect for fn(i32) {
fn connect(self, sigthis: QMovie_frameChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_frameChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie12frameChangedEi(arg0, arg1, arg2)};
}
}
impl /* trait */ QMovie_frameChanged_signal_connect for Box<Fn(i32)> {
fn connect(self, sigthis: QMovie_frameChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_frameChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie12frameChangedEi(arg0, arg1, arg2)};
}
}
// finished()
extern fn QMovie_finished_signal_connect_cb_2(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QMovie_finished_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QMovie_finished_signal_connect for fn() {
fn connect(self, sigthis: QMovie_finished_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_finished_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie8finishedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QMovie_finished_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QMovie_finished_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_finished_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie8finishedEv(arg0, arg1, arg2)};
}
}
// started()
extern fn QMovie_started_signal_connect_cb_3(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QMovie_started_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QMovie_started_signal_connect for fn() {
fn connect(self, sigthis: QMovie_started_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_started_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie7startedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QMovie_started_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QMovie_started_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_started_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie7startedEv(arg0, arg1, arg2)};
}
}
// updated(const class QRect &)
extern fn QMovie_updated_signal_connect_cb_4(rsfptr:fn(QRect), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QRect::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QMovie_updated_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(QRect)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QRect::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QMovie_updated_signal_connect for fn(QRect) {
fn connect(self, sigthis: QMovie_updated_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_updated_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie7updatedERK5QRect(arg0, arg1, arg2)};
}
}
impl /* trait */ QMovie_updated_signal_connect for Box<Fn(QRect)> {
fn connect(self, sigthis: QMovie_updated_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QMovie_updated_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QMovie_SlotProxy_connect__ZN6QMovie7updatedERK5QRect(arg0, arg1, arg2)};
}
}
// <= body block end
|
fn main() {
match get_floored_nth_of_geometric_progression(84.0, 87.0, 3.0) {
Ok(result) => println!("{}", result),
Err(err) => println!("{}", err),
};
}
const MIN: f32 = -100.0;
const MAX: f32 = 100.0;
const N_MIN: f32 = 1.0;
const N_MAX: f32 = 5.0;
fn get_floored_nth_of_geometric_progression(a: f32, b: f32, n: f32) -> Result<i32, String> {
if a < MIN || a > MAX || b < MIN || b > MAX || n < N_MIN || n > N_MAX {
Err(String::from("invalid arguments"))
} else {
Ok((a * (b / a).powf(n - 1.0)) as i32)
}
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
macro_rules! write_loop_or_await_or_error
{
($io_error: ident, $yielder: expr, $complete_error_kind_wrapping_io_error: ident) =>
{
{
use ::std::io::ErrorKind::*;
match $io_error.kind()
{
Interrupted => continue,
WouldBlock => await_further_input_or_output_to_become_available!($yielder),
_ => return Err(CompleteError::$complete_error_kind_wrapping_io_error($io_error))
}
}
}
}
|
//! DMA
//!
//! Some of this implementation was scraped from:
//! https://github.com/stm32-rs/stm32f7xx-hal
// TODO
// - move chan_num field a typenum type state
// - finish the impl to allow peripheral/mem transfers, currently focused on
// mem-to-mem only
// - add src/dst cached support once caches are enabled
// - consider using https://crates.io/crates/embedded-dma
use crate::ccu::Ccu;
use crate::pac::{
ccu::{BusClockGating0, BusSoftReset0},
dma::channel::ChannelEnable,
dma::{AutoGating, Security, Status, DMA},
};
use as_slice::AsSlice;
use core::{
mem,
ops::Deref,
ops::DerefMut,
pin::Pin,
sync::atomic::{self, Ordering},
};
use cortex_a::asm;
pub mod descriptor;
pub use descriptor::Descriptor;
use descriptor::{AddressMode, BurstLength, Config, DataWidth, DrqPort, Param};
pub trait DmaExt {
type Parts;
fn split(self, ccu: &mut Ccu) -> Self::Parts;
}
pub struct Dma {
pub ch0: Channel,
// TODO ch1..=ch7
}
pub struct Channel {
dma: DMA,
chan_num: ChannelNumber,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
enum ChannelNumber {
Ch0,
// Ch1..=Ch7
}
impl DmaExt for DMA {
type Parts = Dma;
fn split(self, ccu: &mut Ccu) -> Self::Parts {
ccu.bsr0.rstr().modify(BusSoftReset0::Dma::Clear);
ccu.bsr0.rstr().modify(BusSoftReset0::Dma::Set);
ccu.bcg0.enr().modify(BusClockGating0::Dma::Set);
let mut dma = unsafe { DMA::from_paddr() };
dma.auto_gating.modify(AutoGating::MasterClock::Enable);
dma.auto_gating.modify(AutoGating::Channel::Enable);
dma.auto_gating.modify(AutoGating::Common::Enable);
Dma {
ch0: Channel {
dma,
chan_num: ChannelNumber::Ch0,
},
}
}
}
#[derive(Debug)]
pub struct TransferResources<SrcBuf, DstBuf> {
// TODO - desc could be a slice, to-be-chained/linked
pub desc: Pin<&'static mut Descriptor>,
pub src_buffer: Pin<SrcBuf>,
pub dst_buffer: Pin<DstBuf>,
}
impl<SrcBuf, DstBuf> TransferResources<SrcBuf, DstBuf>
where
SrcBuf: 'static,
DstBuf: 'static,
{
pub fn mem_to_mem<SrcWord, DstWord>(
mut desc: Pin<&'static mut Descriptor>,
src_buffer: Pin<SrcBuf>,
dst_buffer: Pin<DstBuf>,
) -> Self
where
SrcBuf: Deref,
SrcBuf::Target: Buffer<SrcWord>,
DstBuf: DerefMut,
DstBuf::Target: Buffer<DstWord>,
SrcWord: SupportedWordSize,
DstWord: SupportedWordSize,
{
// TODO
// - check descriptor for half-word alignment
// - check descriptor address
assert!(src_buffer.size() <= u32::max_value() as usize);
assert!(dst_buffer.size() <= u32::max_value() as usize);
assert!(src_buffer.size() == dst_buffer.size());
// AddrHigh bit0
assert!(desc.as_ptr() as usize & 0x01 == 0);
let transfer_size_bytes = src_buffer.size() as u32;
let mut config = Config(0);
config.set_src_drq_port(DrqPort::SdRam);
config.set_dst_drq_port(DrqPort::SdRam);
config.set_src_address_mode(AddressMode::Linear);
config.set_dst_address_mode(AddressMode::Linear);
// TODO - config or trait provided
config.set_src_burst_length(BurstLength::Bytes4);
config.set_dst_burst_length(BurstLength::Bytes4);
config.set_src_data_width(SrcWord::data_width());
config.set_dst_data_width(DstWord::data_width());
let mut param = Param(0);
param.set_wait(Param::NORMAL_WAIT);
desc.config = config;
desc.src_addr = src_buffer.as_ptr() as u32;
desc.dst_addr = dst_buffer.as_ptr() as u32;
desc.length = transfer_size_bytes;
desc.param = param;
desc.next_addr = Descriptor::LAST_ADDR;
TransferResources {
desc,
src_buffer,
dst_buffer,
}
}
}
#[derive(Debug)]
pub struct Transfer<SrcBuf, DstBuf, State> {
res: TransferResources<SrcBuf, DstBuf>,
_state: State,
}
impl<SrcBuf, DstBuf> Transfer<SrcBuf, DstBuf, Ready>
where
SrcBuf: 'static,
DstBuf: 'static,
{
pub fn new<SrcWord, DstWord>(
res: TransferResources<SrcBuf, DstBuf>,
channel: &mut Channel,
) -> Self
where
SrcBuf: Deref,
SrcBuf::Target: Buffer<SrcWord>,
DstBuf: DerefMut,
DstBuf::Target: Buffer<DstWord>,
SrcWord: SupportedWordSize,
DstWord: SupportedWordSize,
{
channel.set_nonsecure();
channel.set_desc_addr(&res.desc);
Transfer { res, _state: Ready }
}
pub fn start(self, channel: &mut Channel) -> Transfer<SrcBuf, DstBuf, Started> {
atomic::fence(Ordering::SeqCst);
channel.enable();
Transfer {
res: self.res,
_state: Started,
}
}
}
impl<SrcBuf, DstBuf> Transfer<SrcBuf, DstBuf, Started> {
pub fn is_active(&self, channel: &mut Channel) -> bool {
channel.is_active()
}
pub fn wait(self, channel: &mut Channel) -> TransferResources<SrcBuf, DstBuf> {
// Wait for transfer to finish
while self.is_active(channel) {
asm::nop();
}
atomic::fence(Ordering::SeqCst);
self.res
}
}
impl ChannelNumber {
fn into_index(self) -> usize {
match self {
ChannelNumber::Ch0 => 0,
}
}
}
impl Channel {
fn is_active(&self) -> bool {
match self.chan_num {
ChannelNumber::Ch0 => self.dma.status.is_set(Status::Ch0Busy::Read),
}
}
fn enable(&mut self) {
let chan = self.chan_num.into_index();
self.dma.channels[chan]
.enable
.modify(ChannelEnable::Enable::Set);
}
fn set_desc_addr(&mut self, desc: &Descriptor) {
let addr = desc.as_ptr() as u32;
let chan = self.chan_num.into_index();
self.dma.channels[chan].desc_addr.write(addr);
}
fn set_nonsecure(&mut self) {
match self.chan_num {
ChannelNumber::Ch0 => self.dma.security.modify(Security::Ch0::NonSecure),
}
}
}
/// Indicates that a DMA transfer is ready to be started
pub struct Ready;
/// Indicates that a DMA transfer has been started
pub struct Started;
/// Implemented for types that can be used as a buffer for DMA transfers
pub trait Buffer<Word> {
fn as_ptr(&self) -> *const Word;
fn len(&self) -> usize;
fn size(&self) -> usize;
}
impl<T, Word> Buffer<Word> for T
where
T: ?Sized + AsSlice<Element = Word>,
{
fn as_ptr(&self) -> *const Word {
self.as_slice().as_ptr()
}
fn len(&self) -> usize {
self.as_slice().len()
}
fn size(&self) -> usize {
mem::size_of::<Word>() * self.len()
}
}
pub trait SupportedWordSize: private::Sealed + Unpin + 'static {
fn data_width() -> DataWidth;
}
impl private::Sealed for u8 {}
impl SupportedWordSize for u8 {
fn data_width() -> DataWidth {
DataWidth::Bits8
}
}
impl private::Sealed for u16 {}
impl SupportedWordSize for u16 {
fn data_width() -> DataWidth {
DataWidth::Bits16
}
}
impl private::Sealed for u32 {}
impl SupportedWordSize for u32 {
fn data_width() -> DataWidth {
DataWidth::Bits32
}
}
impl private::Sealed for u64 {}
impl SupportedWordSize for u64 {
fn data_width() -> DataWidth {
DataWidth::Bits64
}
}
mod private {
pub trait Sealed {}
}
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::GString;
use glib_sys;
use libc;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use webkit2_webextension_sys;
use DOMElement;
use DOMEventTarget;
use DOMHTMLElement;
use DOMNode;
use DOMObject;
glib_wrapper! {
pub struct DOMHTMLAppletElement(Object<webkit2_webextension_sys::WebKitDOMHTMLAppletElement, webkit2_webextension_sys::WebKitDOMHTMLAppletElementClass, DOMHTMLAppletElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_html_applet_element_get_type(),
}
}
pub const NONE_DOMHTML_APPLET_ELEMENT: Option<&DOMHTMLAppletElement> = None;
pub trait DOMHTMLAppletElementExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_align(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_alt(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_archive(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_code(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_code_base(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_height(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_hspace(&self) -> libc::c_long;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_name(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_object(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_vspace(&self) -> libc::c_long;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_width(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_align(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_alt(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_archive(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_code(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_code_base(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_height(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_hspace(&self, value: libc::c_long);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_name(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_object(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_vspace(&self, value: libc::c_long);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_width(&self, value: &str);
fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_alt_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_archive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_code_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_code_base_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_hspace_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_object_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_vspace_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLAppletElement>> DOMHTMLAppletElementExt for O {
fn get_align(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_align(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_alt(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_alt(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_archive(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_archive(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_code(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_code(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_code_base(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_code_base(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_height(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_height(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_hspace(&self) -> libc::c_long {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_get_hspace(
self.as_ref().to_glib_none().0,
)
}
}
fn get_name(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_name(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_object(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_object(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_vspace(&self) -> libc::c_long {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_get_vspace(
self.as_ref().to_glib_none().0,
)
}
}
fn get_width(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_applet_element_get_width(
self.as_ref().to_glib_none().0,
),
)
}
}
fn set_align(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_align(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_alt(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_alt(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_archive(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_archive(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_code(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_code(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_code_base(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_code_base(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_height(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_height(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_hspace(&self, value: libc::c_long) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_hspace(
self.as_ref().to_glib_none().0,
value,
);
}
}
fn set_name(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_name(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_object(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_object(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_vspace(&self, value: libc::c_long) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_vspace(
self.as_ref().to_glib_none().0,
value,
);
}
}
fn set_width(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_applet_element_set_width(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::align\0".as_ptr() as *const _,
Some(transmute(notify_align_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_alt_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_alt_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::alt\0".as_ptr() as *const _,
Some(transmute(notify_alt_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_archive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_archive_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::archive\0".as_ptr() as *const _,
Some(transmute(notify_archive_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_code_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_code_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::code\0".as_ptr() as *const _,
Some(transmute(notify_code_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_code_base_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_code_base_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::code-base\0".as_ptr() as *const _,
Some(transmute(notify_code_base_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_height_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::height\0".as_ptr() as *const _,
Some(transmute(notify_height_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_hspace_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_hspace_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::hspace\0".as_ptr() as *const _,
Some(transmute(notify_hspace_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_name_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::name\0".as_ptr() as *const _,
Some(transmute(notify_name_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_object_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_object_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::object\0".as_ptr() as *const _,
Some(transmute(notify_object_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_vspace_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_vspace_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::vspace\0".as_ptr() as *const _,
Some(transmute(notify_vspace_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_width_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLAppletElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLAppletElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLAppletElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::width\0".as_ptr() as *const _,
Some(transmute(notify_width_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMHTMLAppletElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMHTMLAppletElement")
}
}
|
use std::convert::TryInto;
use proptest::prop_assert;
use crate::erlang::round_1::result;
#[test]
fn without_number_errors_badarg() {
crate::test::without_number_errors_badarg(file!(), result);
}
#[test]
fn with_integer_returns_integer() {
crate::test::with_integer_returns_integer(file!(), result);
}
#[test]
fn with_float_rounds_to_nearest_integer() {
crate::test::number_to_integer_with_float(file!(), result, |_, number_f64, result_term| {
let result_f64: f64 = result_term.try_into().unwrap();
prop_assert!((result_f64 - number_f64).abs() <= 0.5);
Ok(())
});
}
|
use models;
use schema;
use diesel::prelude::*;
use diesel::MysqlConnection;
pub fn get_user_acl(user_id: i32, wcf_db: &MysqlConnection) -> QueryResult<Vec<models::WcfAclOption>> {
let mut acl_option_ids = schema::wcf1_user_to_group::table
.inner_join(schema::wcf1_acl_option_to_group::table.on(
schema::wcf1_acl_option_to_group::group_id.eq(
schema::wcf1_user_to_group::group_id
)
))
.select(schema::wcf1_acl_option_to_group::option_id)
.filter(schema::wcf1_user_to_group::user_id.eq(user_id))
.filter(schema::wcf1_acl_option_to_group::option_value.eq(true))
.group_by(schema::wcf1_acl_option_to_group::option_id)
.load::<i32>(wcf_db)
.expect("failed to load user group acl options");
let mut user_acl_option_ids = schema::wcf1_acl_option_to_user::table
.select(schema::wcf1_acl_option_to_user::option_id)
.filter(schema::wcf1_acl_option_to_user::user_id.eq(user_id))
.filter(schema::wcf1_acl_option_to_user::option_value.eq(true))
.load::<i32>(wcf_db)
.expect("failed to load user acl option ids");
acl_option_ids.append(&mut user_acl_option_ids);
acl_option_ids.sort_unstable();
acl_option_ids.dedup();
schema::wcf1_acl_option::table
.filter(schema::wcf1_acl_option::id.eq_any(acl_option_ids))
.load::<models::WcfAclOption>(wcf_db)
} |
use sqlx::PgPool;
use crate::application::dtos::answer_question_dto::AnswerQuestionData;
use crate::infrastructure::models::AnswerCorretionModel;
use crate::infrastructure::repositories::{
answer_repository, student_answers_repository, student_exams_repository,
};
pub async fn insert(pool: &PgPool, answer: &AnswerQuestionData) {
student_answers_repository::insert(&pool, &answer)
.await
.unwrap();
let answer_corretion: AnswerCorretionModel =
answer_repository::find_correction_by_id(&pool, answer.id_answer)
.await
.unwrap();
if answer_corretion.is_correct {
student_exams_repository::increment_score(&pool, answer.id_student_exam)
.await
.unwrap();
}
}
|
use super::{Error, Result};
use difference;
use handlebars::{Context, Handlebars, Helper, RenderContext, RenderError};
use std::collections::BTreeMap;
use flate2::read::GzDecoder;
use hyper::Client;
use hyper::header::UserAgent;
use std::env;
use std::fs::{self, File, create_dir_all, read_dir, rename, OpenOptions};
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
use std::io::{self, Read, Write};
use tar::Archive;
use tempdir::TempDir;
use walkdir::WalkDir;
use super::defaults;
/// file to clone template to
// const TMP_PREFIX: &'static str = "porteurbars";
/// subdirectory containing template source
const TEMPLATE_DIR: &'static str = "template";
/// name of file containing key/value pairs representing template defaults
const DEFAULTS: &'static str = "default.env";
pub fn templates_dir() -> Result<PathBuf> {
let path = try!(env::home_dir().ok_or(Error::Homeless))
.join(".porteurbars")
.join("templates");
Ok(path)
}
/// A template holds a path to template source and a
/// file describing the default values associated with
/// names used in the template
pub struct Template {
/// path to template source
pub path: PathBuf,
}
impl Template {
/// validates a template located at `path`
pub fn validate(path: &Path) -> Result<bool> {
if !path.exists() {
return Ok(false);
}
if !path.join(TEMPLATE_DIR).exists() {
return Ok(false);
}
let tmpdir = try!(TempDir::new("pb-test"));
let template = try!(Template::get(path));
let def = try!(defaults::parse(path.join(DEFAULTS)));
for (k, _) in def {
env::set_var(k, "test_value")
}
let _ = try!(template.apply(tmpdir.path()));
Ok(true)
}
/// initializes current working directory with porteurbar defaults
pub fn init(force: bool) -> Result<()> {
if Path::new(TEMPLATE_DIR).exists() && !force {
return Ok(());
}
try!(fs::create_dir(TEMPLATE_DIR));
try!(fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(DEFAULTS));
Ok(())
}
/// downloads a template from repo (user/repo)
/// todo: handle host (ghe), branch, credentials (private repo)
pub fn download(repo: &str, tag: Option<&str>) -> Result<bool> {
let template_dir = try!(templates_dir()).join(tag.unwrap_or(&repo.replace("/", "-")[..]));
if template_dir.exists() {
return Ok(true);
}
let download = try!(TempDir::new("porteurbars-dl"));
let host = "api.github.com";
let branch = "master";
let res = try!(Client::new()
.get(&format!("https://{}/repos/{}/tarball/{}", host, repo, branch)[..])
.header(UserAgent("porteurbars/0.1.0".to_owned()))
.send());
try!(Archive::new(try!(GzDecoder::new(res))).unpack(download.path()));
let sandbox = try!(try!(read_dir(download.path())).next().unwrap()).path();
let valid = try!(Template::validate(&sandbox));
if valid {
try!(fs::create_dir_all(&template_dir));
try!(rename(sandbox, template_dir));
}
Ok(valid)
}
pub fn list() -> Result<Vec<String>> {
let mut names = vec![];
let template_dir = try!(templates_dir());
for entry in try!(fs::read_dir(template_dir)) {
let e = try!(entry);
if let Some(name) = e.file_name().to_str() {
names.push(name.to_owned());
}
}
Ok(names)
}
pub fn delete(tag: &str) -> Result<bool> {
let template_dir = try!(templates_dir()).join(tag);
if !template_dir.exists() {
return Ok(false);
}
try!(fs::remove_dir_all(template_dir));
Ok(true)
}
/// Resolve template
pub fn get<P>(path: P) -> Result<Template>
where P: AsRef<Path>
{
match find(&path, DEFAULTS) {
Ok(Some(_)) => Ok(Template { path: path.as_ref().join(TEMPLATE_DIR) }),
_ => Err(Error::DefaultsNotFound),
}
}
/// resolve context
fn context(&self) -> Result<BTreeMap<String, String>> {
let defaults_file = self.path.join(DEFAULTS);
let map = try!(defaults::parse(defaults_file));
let resolved = try!(interact(&map));
Ok(resolved)
}
/// Apply template
pub fn apply(&self, target: &Path) -> Result<()> {
let ctx = try!(self.context());
let data = Context::wraps(&ctx);
// apply handlebars processing
let apply = |path: &Path, hbs: &mut Handlebars| -> Result<()> {
// /tmp/download_dir/templates
let scratchpath = &format!("{}{}", self.path.to_str().unwrap(), MAIN_SEPARATOR)[..];
// path relatived based on scratch dir
let localpath = path.to_str()
.unwrap()
.trim_left_matches(scratchpath);
// eval path as template
let evalpath = try!(hbs.template_render(&localpath, &ctx));
// rewritten path, based on target dir and eval path
let targetpath = target.join(evalpath);
if path.is_dir() {
try!(fs::create_dir_all(targetpath))
} else {
let mut file = try!(File::open(path));
let mut s = String::new();
try!(file.read_to_string(&mut s));
if targetpath.exists() {
// open file for reading and writing
let mut file = try!(OpenOptions::new()
.append(false)
.write(true)
.read(true)
.open(&targetpath));
// get the current content
let mut current_content = String::new();
try!(file.read_to_string(&mut current_content));
// get the target content
let template_eval = try!(hbs.template_render(&s, &ctx));
// if there's a diff prompt for change
if template_eval != current_content {
let keep = try!(prompt_diff(current_content.as_ref(),
template_eval.as_ref()));
if !keep {
// force truncation of current content
let mut file = try!(File::create(targetpath));
try!(file.write_all(template_eval.as_bytes()));
}
}
} else {
let mut file = try!(File::create(targetpath));
try!(hbs.template_renderw(&s, &data, &mut file));
}
}
Ok(())
};
try!(create_dir_all(target));
let mut hbs = bars();
for entry in WalkDir::new(&self.path).into_iter().skip(1).filter_map(|e| e.ok()) {
println!("{:?}", entry.path().display());
try!(apply(entry.path(), &mut hbs))
}
Ok(())
}
}
pub fn bars() -> Handlebars {
let mut hbs = Handlebars::new();
fn transform<F>(bars: &mut Handlebars, name: &str, f: F)
where F: 'static + Fn(&str) -> String + Sync + Send
{
bars.register_helper(name,
Box::new(move |c: &Context,
h: &Helper,
_: &Handlebars,
rc: &mut RenderContext|
-> ::std::result::Result<(), RenderError> {
let param = h.params().get(0).unwrap();
let value = c.navigate(rc.get_path(), param);
try!(rc.writer.write(f(value.as_string().unwrap()).as_bytes()));
Ok(())
}));
}
transform(&mut hbs, "upper", str::to_uppercase);
transform(&mut hbs, "lower", str::to_lowercase);
hbs
}
fn prompt_diff(current: &str, new: &str) -> io::Result<bool> {
let mut answer = String::new();
println!("local changes exists in file <file>");
difference::print_diff(current, new, "\n");
print!("local changes exists. do you want to keep them? [y]: ");
try!(io::stdout().flush());
try!(io::stdin().read_line(&mut answer));
let trimmed = answer.trim();
if trimmed.is_empty() || trimmed != "n" {
Ok(true)
} else {
Ok(false)
}
}
/// prompt for a value defaulting to a given string when an answer is not available
fn prompt(name: &str, default: &str) -> io::Result<String> {
let mut answer = String::new();
print!("{} [{}]: ", name, default);
try!(io::stdout().flush());
try!(io::stdin().read_line(&mut answer));
let trimmed = answer.trim();
if trimmed.trim().is_empty() {
Ok(default.to_owned())
} else {
Ok(trimmed.to_owned())
}
}
/// given a set of defaults, attempt to interact with a user
/// to resolve the parameters that can not be inferred from env
fn interact(defaults: &BTreeMap<String, String>) -> Result<BTreeMap<String, String>> {
let mut resolved = BTreeMap::new();
for (k, v) in defaults {
let answer = match env::var(k) {
Ok(v) => v,
_ => try!(prompt(k, v)),
};
resolved.insert(k.clone(), answer);
}
Ok(resolved)
}
fn find<P>(target_dir: P, target_name: &str) -> io::Result<Option<PathBuf>>
where P: AsRef<Path>
{
for entry in try!(fs::read_dir(target_dir)) {
let e = try!(entry);
if let Some(name) = e.file_name().to_str() {
if name == target_name {
return Ok(Some(e.path()));
}
}
}
Ok(None)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use regex::Regex;
use super::*;
#[test]
fn test_bars_upper() {
let mut map = BTreeMap::new();
map.insert("name".to_owned(), "porteurbars".to_owned());
assert_eq!("Hello, PORTEURBARS",
bars().template_render("Hello, {{upper name}}", &map).unwrap());
}
#[test]
fn test_bars_lower() {
let mut map = BTreeMap::new();
map.insert("name".to_owned(), "PORTEURBARS".to_owned());
assert_eq!("Hello, porteurbars",
bars().template_render("Hello, {{lower name}}", &map).unwrap());
}
}
|
//! Process InfluxQL time range expressions
//!
use crate::expression::walk::{walk_expression, Expression};
use crate::expression::{
lit, Binary, BinaryOperator, ConditionalBinary, ConditionalExpression, Expr, VarRef,
};
use crate::functions::is_now_function;
use crate::literal::{nanos_to_timestamp, Duration, Literal};
use crate::timestamp::{parse_timestamp, Timestamp};
use std::ops::ControlFlow;
/// Result type for operations that return an [`Expr`] and could result in an [`ExprError`].
pub type ExprResult = Result<Expr, ExprError>;
/// Traverse `expr` and separate time range expressions from other predicates.
///
/// # NOTE
///
/// Combining relational operators like `time > now() - 5s` and equality
/// operators like `time = <timestamp>` with a disjunction (`OR`)
/// will evaluate to `false`, like InfluxQL.
///
/// # Background
///
/// The InfluxQL query engine always promotes the time range expression to filter
/// all results. It is misleading that time ranges are written in the `WHERE` clause,
/// as the `WHERE` predicate is not evaluated in its entirety for each row. Rather,
/// InfluxQL extracts the time range to form a time bound for the entire query and
/// removes any time range expressions from the filter predicate. The time range
/// is determined using the `>` and `≥` operators to form the lower bound and
/// the `<` and `≤` operators to form the upper bound. When multiple instances of
/// the lower or upper bound operators are found, the time bounds will form the
/// intersection. For example
///
/// ```sql
/// WHERE time >= 1000 AND time >= 2000 AND time < 10000 and time < 9000
/// ```
///
/// is equivalent to
///
/// ```sql
/// WHERE time >= 2000 AND time < 9000
/// ```
///
/// Further, InfluxQL only allows a single `time = <value>` binary expression. Multiple
/// occurrences result in an empty result set.
///
/// ## Examples
///
/// Lets illustrate how InfluxQL applies predicates with a typical example, using the
/// `metrics.lp` data in the IOx repository:
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WHERE
/// time > '2020-06-11T16:53:30Z' AND time < '2020-06-11T16:55:00Z' AND cpu = 'cpu0'
/// ```
///
/// InfluxQL first filters rows based on the time range:
///
/// ```sql
/// '2020-06-11T16:53:30Z' < time < '2020-06-11T16:55:00Z'
/// ```
///
/// and then applies the predicate to the individual rows:
///
/// ```sql
/// cpu = 'cpu0'
/// ```
///
/// Producing the following result:
///
/// ```text
/// name: cpu
/// time cpu usage_idle
/// ---- --- ----------
/// 2020-06-11T16:53:40Z cpu0 90.29029029029029
/// 2020-06-11T16:53:50Z cpu0 89.8
/// 2020-06-11T16:54:00Z cpu0 90.09009009009009
/// 2020-06-11T16:54:10Z cpu0 88.82235528942115
/// ```
///
/// The following example is a little more complicated, but shows again how InfluxQL
/// separates the time ranges from the predicate:
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WHERE
/// time > '2020-06-11T16:53:30Z' AND time < '2020-06-11T16:55:00Z' AND cpu = 'cpu0' OR cpu = 'cpu1'
/// ```
///
/// InfluxQL first filters rows based on the time range:
///
/// ```sql
/// '2020-06-11T16:53:30Z' < time < '2020-06-11T16:55:00Z'
/// ```
///
/// and then applies the predicate to the individual rows:
///
/// ```sql
/// cpu = 'cpu0' OR cpu = 'cpu1'
/// ```
///
/// This is certainly quite different to SQL, which would evaluate the predicate as:
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WHERE
/// (time > '2020-06-11T16:53:30Z' AND time < '2020-06-11T16:55:00Z' AND cpu = 'cpu0') OR cpu = 'cpu1'
/// ```
///
/// ## Time ranges are not normal
///
/// Here we demonstrate how the operators combining time ranges do not matter. Using the
/// original query:
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WHERE
/// time > '2020-06-11T16:53:30Z' AND time < '2020-06-11T16:55:00Z' AND cpu = 'cpu0'
/// ```
///
/// we replace all `AND` operators with `OR`:
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WHERE
/// time > '2020-06-11T16:53:30Z' OR time < '2020-06-11T16:55:00Z' OR cpu = 'cpu0'
/// ```
///
/// This should return all rows, but yet it returns the same result 🤯:
///
/// ```text
/// name: cpu
/// time cpu usage_idle
/// ---- --- ----------
/// 2020-06-11T16:53:40Z cpu0 90.29029029029029
/// 2020-06-11T16:53:50Z cpu0 89.8
/// 2020-06-11T16:54:00Z cpu0 90.09009009009009
/// 2020-06-11T16:54:10Z cpu0 88.82235528942115
/// ```
///
/// It becomes clearer, if we again review at how InfluxQL OG evaluates the `WHERE`
/// predicate, InfluxQL first filters rows based on the time range, which uses the
/// rules previously defined by finding `>` and `≥` to determine the lower bound
/// and `<` and `≤`:
///
/// ```sql
/// '2020-06-11T16:53:30Z' < time < '2020-06-11T16:55:00Z'
/// ```
///
/// and then applies the predicate to the individual rows:
///
/// ```sql
/// cpu = 'cpu0'
/// ```
///
/// ## How to think of time ranges intuitively
///
/// Imagine a slight variation of InfluxQL has a separate _time bounds clause_.
/// It could have two forms, first as a `BETWEEN`
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WITH TIME BETWEEN '2020-06-11T16:53:30Z' AND '2020-06-11T16:55:00Z'
/// WHERE
/// cpu = 'cpu0'
/// ```
///
/// or as an `IN` to select multiple points:
///
/// ```sql
/// SELECT cpu, usage_idle FROM cpu
/// WITH TIME IN ('2004-04-09T12:00:00Z', '2004-04-09T12:00:10Z', ...)
/// WHERE
/// cpu = 'cpu0'
/// ```
pub fn split_cond(
ctx: &ReduceContext,
cond: &ConditionalExpression,
) -> Result<(Option<ConditionalExpression>, TimeRange), ExprError> {
if !has_time_range(cond) {
return Ok((Some(cond.clone()), TimeRange::default()));
}
let mut time_range = TimeRange::default();
let mut stack: Vec<Option<ConditionalExpression>> = vec![];
let res = walk_expression(cond, &mut |expr| {
if let Expression::Conditional(cond) = expr {
use crate::expression::ConditionalOperator::*;
use ConditionalExpression as CE;
match cond {
CE::Binary(ConditionalBinary {
lhs,
op: op @ (Eq | NotEq | Gt | Lt | GtEq | LtEq),
rhs,
}) if is_time_field(lhs) || is_time_field(rhs) => {
if matches!(op, NotEq) {
// Stop recursing, as != is an invalid operator for time expressions
return ControlFlow::Break(error::map::expr(
"invalid time comparison operator: !=",
));
}
stack.push(None);
/// Op is the limited set of operators expected from here on,
/// to avoid repeated wildcard match arms with unreachable!().
enum Op {
Eq,
Gt,
GtEq,
Lt,
LtEq,
}
// Map the DataFusion Operator to Op
let op = match op {
Eq => Op::Eq,
Gt => Op::Gt,
GtEq => Op::GtEq,
Lt => Op::Lt,
LtEq => Op::LtEq,
_ => unreachable!("expected: Eq | Gt | GtEq | Lt | LtEq"),
};
let (expr, op) = if is_time_field(lhs) {
(rhs, op)
} else {
(
lhs,
match op {
Op::Eq => Op::Eq,
// swap the relational operators when the conditional is `expression OP "time"`
Op::Gt => Op::Lt,
Op::GtEq => Op::LtEq,
Op::Lt => Op::Gt,
Op::LtEq => Op::GtEq,
},
)
};
let Some(expr) = expr.expr() else {
return ControlFlow::Break(error::map::internal("expected Expr"))
};
// simplify binary expressions to a constant, including resolve `now()`
let expr = match reduce_time_expr(ctx, expr) {
Ok(e) => e,
Err(err) => return ControlFlow::Break(err),
};
let ts = match expr {
Expr::Literal(Literal::Timestamp(ts)) => ts.timestamp_nanos(),
expr => {
return ControlFlow::Break(error::map::internal(format!(
"expected Timestamp, got: {}",
expr
)))
}
};
// See InfluxQL OG for details.
//
// https://github.com/influxdata/influxql/blob/802555d6b3a35cd464a6d8afa2a6511002cf3c2c/ast.go#L5836-L5846
let mut other = TimeRange::default();
match op {
Op::Eq => {
other.lower = Some(ts);
other.upper = Some(ts);
}
Op::Gt => {
other.lower = Some(ts + 1);
}
Op::GtEq => {
other.lower = Some(ts);
}
Op::Lt => {
other.upper = Some(ts - 1);
}
Op::LtEq => {
other.upper = Some(ts);
}
}
time_range.intersect(other);
}
node @ CE::Binary(ConditionalBinary {
op: Eq | NotEq | Gt | GtEq | Lt | LtEq | EqRegex | NotEqRegex,
..
}) => {
stack.push(Some(node.clone()));
}
CE::Binary(ConditionalBinary {
op: op @ (And | Or),
..
}) => {
let Some(right) = stack
.pop() else {
return ControlFlow::Break(error::map::internal("invalid expr stack"))
};
let Some(left) = stack
.pop() else {
return ControlFlow::Break(error::map::internal("invalid expr stack"))
};
stack.push(match (left, right) {
(Some(left), Some(right)) => Some(CE::Binary(ConditionalBinary {
lhs: Box::new(left),
op: *op,
rhs: Box::new(right),
})),
(None, Some(node)) | (Some(node), None) => Some(node),
(None, None) => None,
});
}
_ => {}
}
}
ControlFlow::Continue(())
});
if let ControlFlow::Break(err) = res {
return Err(err);
}
let cond = stack
.pop()
.ok_or_else(|| error::map::internal("expected an element on stack"))?;
Ok((cond, time_range))
}
/// Search `cond` for expressions involving the `time` column.
pub fn has_time_range(cond: &ConditionalExpression) -> bool {
walk_expression(cond, &mut |e| {
if let Expression::Conditional(cond) = e {
if is_time_field(cond) {
return ControlFlow::Break(());
}
}
ControlFlow::Continue(())
})
.is_break()
}
/// Represents the time range as [lower, upper].
///
/// A value of [`None`] is unbounded.
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq)]
pub struct TimeRange {
/// The lower bound of the time range.
pub lower: Option<i64>,
/// The upper bound of the time range.
pub upper: Option<i64>,
}
impl TimeRange {
/// Create a new time range with the specified lower and upper bounds.
pub fn new(lower: Option<i64>, upper: Option<i64>) -> Self {
Self { lower, upper }
}
/// Returns `true` if the `lower` and `upper` bounds are `None`.
pub fn is_unbounded(self) -> bool {
self.lower.is_none() && self.upper.is_none()
}
/// Update the receiver so it is the intersection with `other`.
fn intersect(&mut self, other: Self) {
*self = self.intersected(other)
}
/// Return a time range that is the intersection of the receiver and `other`.
pub fn intersected(self, other: Self) -> Self {
let lower = other.lower.map_or(self.lower, |other| match self.lower {
None => Some(other),
Some(existing) if other > existing => Some(other),
_ => self.lower,
});
let upper = other.upper.map_or(self.upper, |other| match self.upper {
None => Some(other),
Some(existing) if other < existing => Some(other),
_ => self.upper,
});
Self { lower, upper }
}
}
/// Simplifies an InfluxQL duration `expr` to a nanosecond interval represented as an `i64`.
pub fn duration_expr_to_nanoseconds(ctx: &ReduceContext, expr: &Expr) -> Result<i64, ExprError> {
match reduce_time_expr(ctx, expr)? {
Expr::Literal(Literal::Timestamp(v)) => Ok(v.timestamp_nanos()),
_ => error::expr("invalid duration expression"),
}
}
/// Represents an error that occurred whilst simplifying an InfluxQL expression.
#[derive(Debug)]
pub enum ExprError {
/// An error in the expression that can be resolved by the client.
Expression(String),
/// An internal error that signals a bug.
Internal(String),
}
/// Helper functions for creating errors.
mod error {
use super::ExprError;
pub(crate) fn expr<T>(s: impl Into<String>) -> Result<T, ExprError> {
Err(map::expr(s))
}
pub(crate) fn internal<T>(s: impl Into<String>) -> Result<T, ExprError> {
Err(map::internal(s))
}
pub(crate) mod map {
use super::*;
pub(crate) fn expr(s: impl Into<String>) -> ExprError {
ExprError::Expression(s.into())
}
pub(crate) fn internal(s: impl Into<String>) -> ExprError {
ExprError::Internal(s.into())
}
}
}
/// Context used when simplifying InfluxQL time range expressions.
#[derive(Default, Debug, Clone, Copy)]
pub struct ReduceContext {
/// The value for the `now()` function.
pub now: Option<Timestamp>,
/// The timezone to evaluate literal timestamp strings.
pub tz: Option<chrono_tz::Tz>,
}
/// Simplify the time range expression and return a literal [timestamp](Timestamp).
fn reduce_time_expr(ctx: &ReduceContext, expr: &Expr) -> ExprResult {
match reduce_expr(ctx, expr)? {
expr @ Expr::Literal(Literal::Timestamp(_)) => Ok(expr),
Expr::Literal(Literal::String(ref s)) => {
parse_timestamp_expr(s, ctx.tz).map_err(map_expr_err(expr))
}
Expr::Literal(Literal::Duration(v)) => Ok(lit(nanos_to_timestamp(*v))),
Expr::Literal(Literal::Float(v)) => Ok(lit(nanos_to_timestamp(v as i64))),
Expr::Literal(Literal::Integer(v)) => Ok(lit(nanos_to_timestamp(v))),
_ => error::expr("invalid time range expression"),
}
}
fn reduce_expr(ctx: &ReduceContext, expr: &Expr) -> ExprResult {
match expr {
Expr::Binary(ref v) => reduce_binary_expr(ctx, v).map_err(map_expr_err(expr)),
Expr::Call (call) if is_now_function(call.name.as_str()) => ctx.now.map(lit).ok_or_else(|| error::map::internal("unable to resolve now")),
Expr::Call (call) => {
error::expr(
format!("invalid function call '{}'", call.name),
)
}
Expr::Nested(expr) => reduce_expr(ctx, expr),
Expr::Literal(val) => match val {
Literal::Integer(_) |
Literal::Float(_) |
Literal::String(_) |
Literal::Timestamp(_) |
Literal::Duration(_) => Ok(Expr::Literal(val.clone())),
_ => error::expr(format!(
"found literal '{val}', expected duration, float, integer, or timestamp string"
)),
},
Expr::VarRef { .. } | Expr::BindParameter(_) | Expr::Wildcard(_) | Expr::Distinct(_) => error::expr(format!(
"found symbol '{expr}', expected now() or a literal duration, float, integer and timestamp string"
)),
}
}
fn reduce_binary_expr(ctx: &ReduceContext, expr: &Binary) -> ExprResult {
let lhs = reduce_expr(ctx, &expr.lhs)?;
let op = expr.op;
let rhs = reduce_expr(ctx, &expr.rhs)?;
match lhs {
Expr::Literal(Literal::Duration(v)) => reduce_binary_lhs_duration(ctx, v, op, rhs),
Expr::Literal(Literal::Integer(v)) => reduce_binary_lhs_integer(ctx, v, op, rhs),
Expr::Literal(Literal::Float(v)) => reduce_binary_lhs_float(v, op, rhs),
Expr::Literal(Literal::Timestamp(v)) => reduce_binary_lhs_timestamp(ctx, v, op, rhs),
Expr::Literal(Literal::String(v)) => reduce_binary_lhs_string(ctx, v, op, rhs),
_ => Ok(Expr::Binary(Binary {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
})),
}
}
/// Reduce `duration OP expr`.
///
/// ```text
/// duration = duration ( ADD | SUB ) ( duration | NOW() )
/// duration = duration ( MUL | DIV ) ( float | integer )
/// timestamp = duration ADD string
/// timestamp = duration ADD timestamp
/// ```
fn reduce_binary_lhs_duration(
ctx: &ReduceContext,
lhs: Duration,
op: BinaryOperator,
rhs: Expr,
) -> ExprResult {
match rhs {
Expr::Literal(ref val) => match val {
// durations may be added and subtracted from other durations
Literal::Duration(Duration(v)) => match op {
BinaryOperator::Add => Ok(lit(Duration(
lhs.checked_add(*v)
.ok_or_else(|| error::map::expr("overflow"))?,
))),
BinaryOperator::Sub => Ok(lit(Duration(
lhs.checked_sub(*v)
.ok_or_else(|| error::map::expr("overflow"))?,
))),
_ => error::expr(format!("found operator '{op}', expected +, -")),
},
// durations may only be scaled by float literals
Literal::Float(v) => {
reduce_binary_lhs_duration(ctx, lhs, op, Expr::Literal(Literal::Integer(*v as i64)))
}
Literal::Integer(v) => match op {
BinaryOperator::Mul => Ok(lit(Duration(*lhs * *v))),
BinaryOperator::Div => Ok(lit(Duration(*lhs / *v))),
_ => error::expr(format!("found operator '{op}', expected *, /")),
},
// A timestamp may be added to a duration
Literal::Timestamp(v) if matches!(op, BinaryOperator::Add) => {
Ok(lit(*v + chrono::Duration::nanoseconds(*lhs)))
}
Literal::String(v) => {
reduce_binary_lhs_duration(ctx, lhs, op, parse_timestamp_expr(v, ctx.tz)?)
}
// This should not occur, as acceptable literals are validated in `reduce_expr`.
_ => error::internal(format!(
"unexpected literal '{rhs}' for duration expression"
)),
},
_ => error::expr("invalid duration expression"),
}
}
/// Reduce `integer OP expr`.
///
/// ```text
/// integer = integer ( ADD | SUB | MUL | DIV | MOD | BitwiseAND | BitwiseOR | BitwiseXOR ) integer
/// float = integer as float OP float
/// timestamp = integer as timestamp OP duration
/// ```
fn reduce_binary_lhs_integer(
ctx: &ReduceContext,
lhs: i64,
op: BinaryOperator,
rhs: Expr,
) -> ExprResult {
match rhs {
Expr::Literal(Literal::Float(_)) => reduce_binary_lhs_float(lhs as f64, op, rhs),
Expr::Literal(Literal::Integer(v)) => Ok(lit(op.reduce(lhs, v))),
Expr::Literal(Literal::Duration(_)) => {
reduce_binary_lhs_timestamp(ctx, nanos_to_timestamp(lhs), op, rhs)
}
Expr::Literal(Literal::String(v)) => {
reduce_binary_lhs_duration(ctx, Duration(lhs), op, parse_timestamp_expr(&v, ctx.tz)?)
}
_ => error::expr("invalid integer expression"),
}
}
/// Reduce `float OP expr`.
///
/// ```text
/// float = float ( ADD | SUB | MUL | DIV | MOD ) ( float | integer)
/// ```
fn reduce_binary_lhs_float(lhs: f64, op: BinaryOperator, rhs: Expr) -> ExprResult {
Ok(lit(match rhs {
Expr::Literal(Literal::Float(v)) => op
.try_reduce(lhs, v)
.ok_or_else(|| error::map::expr("invalid operator for float expression"))?,
Expr::Literal(Literal::Integer(v)) => op
.try_reduce(lhs, v)
.ok_or_else(|| error::map::expr("invalid operator for float expression"))?,
_ => return error::expr("invalid float expression"),
}))
}
/// Reduce `timestamp OP expr`.
///
/// The right-hand `expr` must be of a type that can be
/// coalesced to a duration, which includes a `duration`, `integer` or a
/// `string`. A `string` is parsed as a timestamp an interpreted as
/// the number of nanoseconds from the Unix epoch.
///
/// ```text
/// timestamp = timestamp ( ADD | SUB ) ( duration | integer | string | timestamp )
/// ```
fn reduce_binary_lhs_timestamp(
ctx: &ReduceContext,
lhs: Timestamp,
op: BinaryOperator,
rhs: Expr,
) -> ExprResult {
match rhs {
Expr::Literal(Literal::Duration(d)) => match op {
BinaryOperator::Add => Ok(lit(lhs + chrono::Duration::nanoseconds(*d))),
BinaryOperator::Sub => Ok(lit(lhs - chrono::Duration::nanoseconds(*d))),
_ => error::expr(format!(
"invalid operator '{op}' for timestamp and duration: expected +, -"
)),
},
Expr::Literal(Literal::Integer(_))
// NOTE: This is a slight deviation from InfluxQL, for which the only valid binary
// operator for two timestamps is subtraction. By converting the timestamp to a
// duration and calling this function recursively, we permit the addition operator.
| Expr::Literal(Literal::Timestamp(_))
| Expr::Literal(Literal::String(_)) => {
reduce_binary_lhs_timestamp(ctx, lhs, op, expr_to_duration(ctx, rhs)?)
}
_ => error::expr(format!(
"invalid expression '{rhs}': expected duration, integer or timestamp string"
)),
}
}
fn expr_to_duration(ctx: &ReduceContext, expr: Expr) -> ExprResult {
Ok(lit(match expr {
Expr::Literal(Literal::Duration(v)) => v,
Expr::Literal(Literal::Integer(v)) => Duration(v),
Expr::Literal(Literal::Timestamp(v)) => Duration(v.timestamp_nanos()),
Expr::Literal(Literal::String(v)) => {
Duration(parse_timestamp_nanos(&v, ctx.tz)?.timestamp_nanos())
}
_ => return error::expr(format!("unable to cast {expr} to duration")),
}))
}
/// Reduce `string OP expr`.
///
/// If `expr` is a string, concatenates the two values and returns a new string.
/// If `expr` is a duration, integer or timestamp, the left-hand
/// string is parsed as a timestamp and the expression evaluated as
/// `timestamp OP expr`
fn reduce_binary_lhs_string(
ctx: &ReduceContext,
lhs: String,
op: BinaryOperator,
rhs: Expr,
) -> ExprResult {
match rhs {
Expr::Literal(Literal::String(ref s)) => match op {
// concatenate the two strings
BinaryOperator::Add => Ok(lit(lhs + s)),
_ => reduce_binary_lhs_timestamp(ctx, parse_timestamp_nanos(&lhs, ctx.tz)?, op, rhs),
},
Expr::Literal(Literal::Duration(_))
| Expr::Literal(Literal::Timestamp(_))
| Expr::Literal(Literal::Integer(_)) => {
reduce_binary_lhs_timestamp(ctx, parse_timestamp_nanos(&lhs, ctx.tz)?, op, rhs)
}
_ => error::expr(format!(
"found '{rhs}', expected duration, integer or timestamp string"
)),
}
}
/// Returns true if the conditional expression is a single node that
/// refers to the `time` column.
///
/// In a conditional expression, this comparison is case-insensitive per the [Go implementation][go]
///
/// [go]: https://github.com/influxdata/influxql/blob/1ba470371ec093d57a726b143fe6ccbacf1b452b/ast.go#L5751-L5753
fn is_time_field(cond: &ConditionalExpression) -> bool {
if let ConditionalExpression::Expr(expr) = cond {
if let Expr::VarRef(VarRef { ref name, .. }) = **expr {
name.eq_ignore_ascii_case("time")
} else {
false
}
} else {
false
}
}
fn parse_timestamp_nanos(s: &str, tz: Option<chrono_tz::Tz>) -> Result<Timestamp, ExprError> {
parse_timestamp(s, tz)
.ok_or_else(|| error::map::expr(format!("'{s}' is not a valid timestamp")))
}
/// Parse s as a timestamp in the specified timezone and return the timestamp
/// as a literal timestamp expression.
fn parse_timestamp_expr(s: &str, tz: Option<chrono_tz::Tz>) -> ExprResult {
Ok(Expr::Literal(Literal::Timestamp(parse_timestamp_nanos(
s, tz,
)?)))
}
fn map_expr_err(expr: &Expr) -> impl Fn(ExprError) -> ExprError + '_ {
move |err| {
error::map::expr(format!(
"invalid expression \"{expr}\": {}",
match err {
ExprError::Expression(str) | ExprError::Internal(str) => str,
}
))
}
}
#[cfg(test)]
mod test {
use crate::expression::ConditionalExpression;
use crate::time_range::{
duration_expr_to_nanoseconds, reduce_time_expr, split_cond, ExprError, ExprResult,
ReduceContext, TimeRange,
};
use crate::timestamp::Timestamp;
use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Offset, Utc};
use test_helpers::assert_error;
/// Return a `ReduceContext` with a value of
/// now set to `2023-01-01T00:00:00Z` / `1672531200000000000`
/// and not timezone.
fn reduce_context() -> ReduceContext {
ReduceContext {
now: Some(Timestamp::from_utc(
NaiveDateTime::new(
NaiveDate::from_ymd_opt(2023, 1, 1).unwrap(),
NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
),
Utc.fix(),
)),
tz: None,
}
}
#[test]
fn test_split_cond() {
fn split_exprs(s: &str) -> Result<(Option<ConditionalExpression>, TimeRange), ExprError> {
let ctx = reduce_context();
let cond: ConditionalExpression = s.parse().unwrap();
split_cond(&ctx, &cond)
}
macro_rules! range {
(lower=$LOWER:literal) => {
TimeRange {
lower: Some($LOWER),
upper: None,
}
};
(lower=$LOWER:literal, upper ex=$UPPER:literal) => {
TimeRange {
lower: Some($LOWER),
upper: Some($UPPER - 1),
}
};
(lower=$LOWER:literal, upper=$UPPER:literal) => {
TimeRange {
lower: Some($LOWER),
upper: Some($UPPER),
}
};
(lower ex=$LOWER:literal, upper=$UPPER:literal) => {
TimeRange {
lower: Some($LOWER + 1),
upper: Some($UPPER),
}
};
(lower ex=$LOWER:literal) => {
TimeRange {
lower: Some($LOWER + 1),
upper: None,
}
};
(upper=$UPPER:literal) => {
TimeRange {
lower: None,
upper: Some($UPPER),
}
};
(upper ex=$UPPER:literal) => {
TimeRange {
lower: None,
upper: Some($UPPER - 1),
}
};
(eq=$TS:literal) => {
TimeRange {
lower: Some($TS),
upper: Some($TS),
}
};
}
let (cond, tr) = split_exprs("time >= now() - 1s").unwrap();
assert!(cond.is_none());
assert_eq!(tr, range!(lower = 1672531199000000000));
// reduces the lower bound to a single expression
let (cond, tr) = split_exprs("time >= now() - 1s AND time >= now() - 500ms").unwrap();
assert!(cond.is_none());
assert_eq!(tr, range!(lower = 1672531199500000000));
let (cond, tr) = split_exprs("time <= now() - 1s").unwrap();
assert!(cond.is_none());
assert_eq!(tr, range!(upper = 1672531199000000000));
// reduces the upper bound to a single expression
let (cond, tr) = split_exprs("time <= now() + 1s AND time <= now() + 500ms").unwrap();
assert!(cond.is_none());
assert_eq!(tr, range!(upper = 1672531200500000000));
let (cond, tr) = split_exprs("time >= now() - 1s AND time < now()").unwrap();
assert!(cond.is_none());
assert_eq!(
tr,
range!(lower=1672531199000000000, upper ex=1672531200000000000)
);
let (cond, tr) = split_exprs("time >= now() - 1s AND cpu = 'cpu0'").unwrap();
assert_eq!(cond.unwrap().to_string(), "cpu = 'cpu0'");
assert_eq!(tr, range!(lower = 1672531199000000000));
let (cond, tr) = split_exprs("time = 0").unwrap();
assert!(cond.is_none());
assert_eq!(tr, range!(eq = 0));
let (cond, tr) = split_exprs(
"instance = 'instance-01' OR instance = 'instance-02' AND time >= now() - 1s",
)
.unwrap();
assert_eq!(
cond.unwrap().to_string(),
"instance = 'instance-01' OR instance = 'instance-02'"
);
assert_eq!(tr, range!(lower = 1672531199000000000));
let (cond, tr) =
split_exprs("time >= now() - 1s AND time < now() AND cpu = 'cpu0' OR cpu = 'cpu1'")
.unwrap();
assert_eq!(cond.unwrap().to_string(), "cpu = 'cpu0' OR cpu = 'cpu1'");
assert_eq!(
tr,
range!(lower=1672531199000000000, upper ex=1672531200000000000)
);
// time >= now - 60s AND time < now() OR cpu = 'cpu0' OR cpu = 'cpu1'
//
// Split the time range, despite using the disjunction (OR) operator
let (cond, tr) =
split_exprs("time >= now() - 1s AND time < now() OR cpu = 'cpu0' OR cpu = 'cpu1'")
.unwrap();
assert_eq!(cond.unwrap().to_string(), "cpu = 'cpu0' OR cpu = 'cpu1'");
assert_eq!(
tr,
range!(lower=1672531199000000000, upper ex=1672531200000000000)
);
let (cond, tr) = split_exprs("time = 0 OR time = 10 AND cpu = 'cpu0'").unwrap();
assert_eq!(cond.unwrap().to_string(), "cpu = 'cpu0'");
// Models InfluxQL behaviour, which will result in no results being returned because
// upper < lower
assert_eq!(tr, range!(lower = 10, upper = 0));
// no time
let (cond, tr) = split_exprs("f64 >= 19.5 OR f64 =~ /foo/").unwrap();
assert_eq!(cond.unwrap().to_string(), "f64 >= 19.5 OR f64 =~ /foo/");
assert!(tr.is_unbounded());
let (cond, tr) = split_exprs("time > now() OR time = 1000").unwrap();
assert!(cond.is_none());
assert_eq!(tr, range!(lower ex = 1672531200000000000, upper = 1000));
// fallible
assert_error!(split_exprs("time > '2004-04-09T'"), ExprError::Expression(ref s) if s == "invalid expression \"'2004-04-09T'\": '2004-04-09T' is not a valid timestamp");
}
#[test]
fn test_rewrite_time_expression_no_timezone() {
fn process_expr(s: &str) -> ExprResult {
let cond: ConditionalExpression =
s.parse().expect("unexpected error parsing expression");
let ctx = ReduceContext {
now: Some(Timestamp::from_utc(
NaiveDateTime::new(
NaiveDate::from_ymd_opt(2004, 4, 9).unwrap(),
NaiveTime::from_hms_opt(12, 13, 14).unwrap(),
),
Utc.fix(),
)),
tz: None,
};
reduce_time_expr(&ctx, cond.expr().unwrap())
}
macro_rules! assert_expr {
($S: expr, $EXPECTED: expr) => {
let expr = process_expr($S).unwrap();
assert_eq!(expr.to_string(), $EXPECTED);
};
}
//
// Valid literals
//
// Duration
assert_expr!("1d", "1970-01-02T00:00:00+00:00");
// Single integer interpreted as a Unix nanosecond epoch
assert_expr!("1157082310000000000", "2006-09-01T03:45:10+00:00");
// Single float interpreted as a Unix nanosecond epoch
assert_expr!("1157082310000000000.0", "2006-09-01T03:45:10+00:00");
// Single string interpreted as a timestamp
assert_expr!(
"'2004-04-09 02:33:45.123456789'",
"2004-04-09T02:33:45.123456789+00:00"
);
// now
assert_expr!("now()", "2004-04-09T12:13:14+00:00");
//
// Expressions
//
// now() OP expr
assert_expr!("now() - 5m", "2004-04-09T12:08:14+00:00");
assert_expr!("(now() - 5m)", "2004-04-09T12:08:14+00:00");
assert_expr!("now() - 5m - 60m", "2004-04-09T11:08:14+00:00");
assert_expr!("now() - 500", "2004-04-09T12:13:13.999999500+00:00");
assert_expr!("now() - (5m + 60m)", "2004-04-09T11:08:14+00:00");
// expr OP now()
assert_expr!("5m + now()", "2004-04-09T12:18:14+00:00");
// duration OP expr
assert_expr!("1w3d + 1d", "1970-01-12T00:00:00+00:00");
assert_expr!("1w3d - 1d", "1970-01-10T00:00:00+00:00");
// string OP expr
assert_expr!("'2004-04-09' - '2004-04-08'", "1970-01-02T00:00:00+00:00");
assert_expr!("'2004-04-09' + '02:33:45'", "2004-04-09T02:33:45+00:00");
// integer OP expr
assert_expr!("1157082310000000000 - 1s", "2006-09-01T03:45:09+00:00");
// nested evaluation order
assert_expr!("now() - (6m - (1m * 5))", r#"2004-04-09T12:12:14+00:00"#);
// Fallible
use super::ExprError::Expression;
assert_error!(process_expr("foo + 1"), Expression(ref s) if s == "invalid expression \"foo + 1\": found symbol 'foo', expected now() or a literal duration, float, integer and timestamp string");
assert_error!(process_expr("5m - now()"), Expression(ref s) if s == "invalid expression \"5m - now()\": unexpected literal '2004-04-09T12:13:14+00:00' for duration expression");
assert_error!(process_expr("'2004-04-09' + false"), Expression(ref s) if s == "invalid expression \"'2004-04-09' + false\": found literal 'false', expected duration, float, integer, or timestamp string");
assert_error!(process_expr("1s * 1s"), Expression(ref s) if s == "invalid expression \"1000ms * 1000ms\": found operator '*', expected +, -");
assert_error!(process_expr("1s + 0.5"), Expression(ref s) if s == "invalid expression \"1000ms + 0.5\": found operator '+', expected *, /");
assert_error!(process_expr("'2004-04-09T'"), Expression(ref s) if s == "invalid expression \"'2004-04-09T'\": '2004-04-09T' is not a valid timestamp");
assert_error!(process_expr("now() * 1"), Expression(ref s) if s == "invalid expression \"now() * 1\": invalid operator '*' for timestamp and duration: expected +, -");
assert_error!(process_expr("'2' + now()"), Expression(ref s) if s == "invalid expression \"'2' + now()\": '2' is not a valid timestamp");
assert_error!(process_expr("'2' + '3'"), Expression(ref s) if s == "invalid expression \"'2' + '3'\": '23' is not a valid timestamp");
assert_error!(process_expr("'2' + '3' + 10s"), Expression(ref s) if s == "invalid expression \"'2' + '3' + 10s\": '23' is not a valid timestamp");
}
#[test]
fn test_rewrite_time_expression_with_timezone() {
fn process_expr(s: &str) -> ExprResult {
let cond: ConditionalExpression =
s.parse().expect("unexpected error parsing expression");
let ctx = ReduceContext {
now: None,
tz: Some(chrono_tz::Australia::Hobart),
};
reduce_time_expr(&ctx, cond.expr().unwrap())
}
macro_rules! assert_expr {
($S: expr, $EXPECTED: expr) => {
let expr = process_expr($S).unwrap();
assert_eq!(expr.to_string(), $EXPECTED);
};
}
assert_expr!(
"'2004-04-09 10:05:00.123456789'",
"2004-04-09T10:05:00.123456789+10:00"
);
assert_expr!("'2004-04-09'", "2004-04-09T00:00:00+10:00");
assert_expr!(
"'2004-04-09T10:05:00.123456789Z'",
"2004-04-09T20:05:00.123456789+10:00"
);
}
#[test]
fn test_expr_to_duration() {
fn parse(s: &str) -> Result<i64, ExprError> {
let ctx = reduce_context();
let expr = s
.parse::<ConditionalExpression>()
.unwrap()
.expr()
.unwrap()
.clone();
duration_expr_to_nanoseconds(&ctx, &expr)
}
let cases = vec![
("10s", 10_000_000_000_i64),
("10s + 1d", 86_410_000_000_000),
("5d10ms", 432_000_010_000_000),
("-2d10ms", -172800010000000),
("-2d10ns", -172800000000010),
("now()", 1672531200000000000),
("'2023-01-01T00:00:00Z'", 1672531200000000000),
];
for (interval_str, exp) in cases {
let got = parse(interval_str).unwrap();
assert_eq!(got, exp, "Actual: {got:?}");
}
}
#[test]
fn test_time_range_is_unbounded() {
let a = TimeRange::new(Some(1000), Some(5000));
assert!(!a.is_unbounded());
let a = TimeRange::new(None, Some(5000));
assert!(!a.is_unbounded());
let a = TimeRange::new(Some(1000), None);
assert!(!a.is_unbounded());
let a = TimeRange::new(None, None);
assert!(a.is_unbounded());
}
#[test]
fn test_time_range_intersect() {
let a = TimeRange::new(Some(1000), Some(5000));
let b = TimeRange::new(Some(2000), Some(6000));
assert_eq!(a.intersected(b), TimeRange::new(Some(2000), Some(5000)));
assert_eq!(b.intersected(a), TimeRange::new(Some(2000), Some(5000)));
let a = TimeRange::new(Some(1000), None);
let b = TimeRange::new(Some(2000), Some(6000));
assert_eq!(a.intersected(b), TimeRange::new(Some(2000), Some(6000)));
let a = TimeRange::new(None, None);
let b = TimeRange::new(Some(2000), Some(6000));
assert_eq!(a.intersected(b), TimeRange::new(Some(2000), Some(6000)));
}
}
|
// //! Adaptor Signatures
// use crate::{PublicKey, SecretKey, Signature};
// use bacteria::Transcript;
// use mohan::dalek::{
// constants::{RISTRETTO_BASEPOINT_POINT, RISTRETTO_BASEPOINT_TABLE},
// ristretto::{CompressedRistretto, RistrettoPoint},
// scalar::Scalar,
// traits::{IsIdentity, VartimeMultiscalarMul},
// };
/// Lets say t is a payment secret (preimage)
/// and tG = T. G is the group generator.
/// Alice and Bob will participate
// /// https://joinmarket.me/blog/blog/flipping-the-scriptless-script-on-schnorr/
// ///
// /// Alice (P = xG), constructs for Bob:
// /// Calculate T = tG, R = rG
// /// Calculate s = r + t + H(P || R+T || m) * x
// /// Publish (to Bob, others): (s', R, T) with s' = s - t
// /// (so s' should be "adaptor signature"; this notation is retained for the rest of the document).
// /// so you simply share an elliptic curve point (in this case it will be T), and the secret will
// /// be its corresponding private key.
// pub fn adaptor(
// transcript: &mut Transcript,
// secret_key: &SecretKey,
// excess: &SecretKey,
// ) -> (Signature, PublicKey) {
// // The message `m` has already been fed into the transcript
// let public_key = PublicKey::from_secret(secret_key);
// // The message `m` has already been fed into the transcript
// let t_public_key = PublicKey::from_secret(excess);
// //randomize transcript and commit private key
// let mut rng = transcript
// .build_rng()
// .rekey_with_witness_bytes(b"secret_key", &secret_key.to_bytes())
// .finalize(&mut mohan::mohan_rand());
// // Generate ephemeral keypair (r, R). r is a random nonce.
// let mut r: Scalar = Scalar::random(&mut rng);
// // R = generator * r, commiment to nonce
// let _r = (&r * &RISTRETTO_BASEPOINT_TABLE);
// let r_plus_t = _r + t_public_key.as_point();
// //Acts as the hash commitment for message, nonce commitment & pubkey
// let c = {
// // Domain seperation
// transcript.proto_name(b"organism_schnorr_adaptor");
// //commit corresponding public key
// transcript.commit_point(b"public_key", public_key.as_compressed());
// //commit to our nonce
// transcript.commit_point(b"R+T", &r_plus_t.compress());
// //sample challenge
// transcript.challenge_scalar(b"c")
// };
// //compute the signature, s = r + t + cx
// let s = &r + excess.as_scalar() + &(&c * secret_key.as_scalar());
// // s' = s - t (s' is the adaptor signature)
// let s_prime = s - excess.as_scalar();
// //zero out secret r
// mohan::zeroize_hack(&mut r);
// (
// Signature {
// R: _r.compress(),
// s: s_prime,
// },
// t_public_key,
// )
// }
// /// Can verify the adaptor sig s' for T,m:
// /// s' * G ?= R + H(P || R+T || m) * P
// /// This is not a valid sig: hashed nonce point is R+T not R;
// /// Cannot retrieve a valid sig : to recover s'+t requires ECDLP solving.
// /// After validation of adaptor sig we know: t <=> receipt of valid sig s = s' + t
// pub fn verify_adaptor(
// transcript: &mut Transcript,
// public_key: &PublicKey,
// big_t: &PublicKey,
// signature: &Signature,
// ) -> bool {
// //set the domain
// transcript.proto_name(b"organism_schnorr_adaptor");
// // Make c = H(X, R+T, m)
// // The message `m` has already been fed into the transcript
// transcript.commit_point(b"public_key", public_key.as_compressed());
// transcript.commit_point(b"R+T", &signature.R);
// let c: Scalar = transcript.challenge_scalar(b"c");
// let A: &RistrettoPoint = public_key.as_point();
// let R: RistrettoPoint =
// RistrettoPoint::vartime_double_scalar_mul_basepoint(&c, &(-A), &signature.s);
// // Validate the final linear combination:
// // `s' * G = R + c * X`
// // ->
// // `0 == (-s' * G) + (1 * R) + (c * X)`
// //If g^s' == RX^c then we have valid adaptor signature.
// R.compress() == signature.R
// }
// /// Knowing the final signature and the original partial signatures can compute `t`. The excess.
// pub fn extract_adaptor(
// partial_sig: &Signature,
// final_sig: &Signature
// ) -> Scalar {
// //s' = s - t, t = s - s'
// let s = final_sig.s + partial_sig.s;
// /// R' = R - T
// let r_prime = final_sig.R.decompress();
// // //zero out secret r
// // mohan::zeroize_hack(&mut excess);
// }
|
//! General Purpose I/O
use core::ops::Deref;
use e310x::gpio0;
/// Enumeration of possible pin configurations.
pub enum PinConfig {
Input,
InputPullup,
Output,
OutputDrive,
IoFn0,
IoFn1,
}
/// Enumeration of pin interrupts.
pub enum PinInterrupt {
Rise,
Fall,
High,
Low,
}
macro_rules! pin {
($Pin:ident, $pinx:ident) => (
pub struct $Pin;
impl $Pin {
pub fn init<T>(gpio: &T, config: PinConfig)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
match config {
PinConfig::Input => {
gpio.iof_en.modify(|_, w| w.$pinx().bit(false));
gpio.pullup.modify(|_, w| w.$pinx().bit(false));
gpio.input_en.modify(|_, w| w.$pinx().bit(true));
},
PinConfig::InputPullup => {
gpio.iof_en.modify(|_, w| w.$pinx().bit(false));
gpio.pullup.modify(|_, w| w.$pinx().bit(true));
gpio.input_en.modify(|_, w| w.$pinx().bit(true));
},
PinConfig::Output => {
gpio.iof_en.modify(|_, w| w.$pinx().bit(false));
gpio.drive.modify(|_, w| w.$pinx().bit(false));
gpio.output_en.modify(|_, w| w.$pinx().bit(true));
},
PinConfig::OutputDrive => {
gpio.iof_en.modify(|_, w| w.$pinx().bit(false));
gpio.drive.modify(|_, w| w.$pinx().bit(true));
gpio.output_en.modify(|_, w| w.$pinx().bit(true));
},
PinConfig::IoFn0 => {
gpio.iof_sel.modify(|_, w| w.$pinx().bit(false));
gpio.iof_en.modify(|_, w| w.$pinx().bit(true));
},
PinConfig::IoFn1 => {
gpio.iof_sel.modify(|_, w| w.$pinx().bit(true));
gpio.iof_en.modify(|_, w| w.$pinx().bit(true));
},
}
}
pub fn read<T>(gpio: &T) -> bool
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.value.read().$pinx().bit()
}
pub fn write<T>(gpio: &T, value: bool)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
match value {
true => $Pin::high(gpio),
false => $Pin::low(gpio),
}
}
pub fn high<T>(gpio: &T)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.port.modify(|_, w| w.$pinx().bit(true));
}
pub fn low<T>(gpio: &T)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.port.modify(|_, w| w.$pinx().bit(false));
}
pub fn toggle<T>(gpio: &T)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.port.modify(|r, w| w.$pinx().bit(!r.$pinx().bit()));
}
pub fn enable_interrupt<T>(gpio: &T, intr: PinInterrupt)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
match intr {
PinInterrupt::Rise =>
gpio.rise_ie.modify(|_, w| w.$pinx().bit(true)),
PinInterrupt::Fall =>
gpio.fall_ie.modify(|_, w| w.$pinx().bit(true)),
PinInterrupt::High =>
gpio.high_ie.modify(|_, w| w.$pinx().bit(true)),
PinInterrupt::Low =>
gpio.low_ie.modify(|_, w| w.$pinx().bit(true)),
};
}
pub fn disable_interrupt<T>(gpio: &T, intr: PinInterrupt)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
match intr {
PinInterrupt::Rise =>
gpio.rise_ie.modify(|_, w| w.$pinx().bit(false)),
PinInterrupt::Fall =>
gpio.fall_ie.modify(|_, w| w.$pinx().bit(false)),
PinInterrupt::High =>
gpio.high_ie.modify(|_, w| w.$pinx().bit(false)),
PinInterrupt::Low =>
gpio.low_ie.modify(|_, w| w.$pinx().bit(false)),
};
}
pub fn clear_pending<T>(gpio: &T, intr: PinInterrupt)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
match intr {
PinInterrupt::Rise =>
gpio.rise_ip.write(|w| w.$pinx().bit(true)),
PinInterrupt::Fall =>
gpio.fall_ip.write(|w| w.$pinx().bit(true)),
PinInterrupt::High =>
gpio.high_ip.write(|w| w.$pinx().bit(true)),
PinInterrupt::Low =>
gpio.low_ip.write(|w| w.$pinx().bit(true)),
}
}
pub fn is_interrupt_pending<T>(gpio: &T, intr: PinInterrupt) -> bool
where
T: Deref<Target = gpio0::RegisterBlock>,
{
match intr {
PinInterrupt::Rise =>
gpio.rise_ip.read().$pinx().bit(),
PinInterrupt::Fall =>
gpio.fall_ip.read().$pinx().bit(),
PinInterrupt::High =>
gpio.high_ip.read().$pinx().bit(),
PinInterrupt::Low =>
gpio.low_ip.read().$pinx().bit(),
}
}
pub fn is_inverted<T>(gpio: &T) -> bool
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.out_xor.read().$pinx().bit()
}
pub fn set_invert<T>(gpio: &T, value: bool)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.out_xor.modify(|_, w| w.$pinx().bit(value));
}
pub fn invert<T>(gpio: &T)
where
T: Deref<Target = gpio0::RegisterBlock>,
{
gpio.out_xor.modify(|r, w| w.$pinx().bit(!r.$pinx().bit()));
}
}
)
}
pin!(Pin0, pin0);
pin!(Pin1, pin1);
pin!(Pin2, pin2);
pin!(Pin3, pin3);
pin!(Pin4, pin4);
pin!(Pin5, pin5);
pin!(Pin6, pin6);
pin!(Pin7, pin7);
pin!(Pin8, pin8);
pin!(Pin9, pin9);
pin!(Pin10, pin10);
pin!(Pin11, pin11);
pin!(Pin12, pin12);
pin!(Pin13, pin13);
pin!(Pin14, pin14);
pin!(Pin15, pin15);
pin!(Pin16, pin16);
pin!(Pin17, pin17);
pin!(Pin18, pin18);
pin!(Pin19, pin19);
pin!(Pin20, pin20);
pin!(Pin21, pin21);
pin!(Pin22, pin22);
pin!(Pin23, pin23);
pin!(Pin24, pin24);
pin!(Pin25, pin25);
pin!(Pin26, pin26);
pin!(Pin27, pin27);
pin!(Pin28, pin28);
pin!(Pin29, pin29);
pin!(Pin30, pin30);
pin!(Pin31, pin31);
|
pub mod optional;
|
extern crate miniz_oxide;
use std::io::Read;
use miniz_oxide::inflate::decompress_to_vec;
use miniz_oxide::deflate::compress_to_vec;
fn get_test_file_data(name: &str) -> Vec<u8> {
use std::fs::File;
let mut input = Vec::new();
let mut f = File::open(name).unwrap();
f.read_to_end(&mut input).unwrap();
input
}
fn get_test_data() -> Vec<u8> {
use std::env;
let path = env::var("TEST_FILE").unwrap_or_else(|_| "miniz/miniz.c".to_string());
get_test_file_data(&path)
}
#[test]
fn roundtrip() {
let level = 9;
let data = get_test_data();
let enc = compress_to_vec(&data.as_slice()[..], level);
println!(
"Input len: {}, compressed len: {}, level: {}",
data.len(),
enc.len(),
level
);
let dec = decompress_to_vec(enc.as_slice()).unwrap();
assert!(data == dec);
}
#[test]
fn roundtrip_level_1() {
let level = 1;
let data = get_test_data();
let enc = compress_to_vec(&data.as_slice()[..], level);
println!(
"Input len: {}, compressed len: {}, level: {}",
data.len(),
enc.len(),
level
);
let dec = decompress_to_vec(enc.as_slice()).unwrap();
assert!(data == dec);
}
|
use serde::{Deserialize, Serialize};
use saoleile_derive::{Event, NetworkEvent};
use crate::layer::{Layer, NetworkLayer};
use crate::util::Id;
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum LayerPosition {
Top,
Bottom,
}
#[derive(Debug, Event)]
pub struct AddLayerEvent {
pub push: LayerPosition,
pub pin: Option<LayerPosition>,
pub layer: Box<dyn Layer>,
}
#[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)]
pub struct AddNetworkLayerEvent {
pub push: LayerPosition,
pub pin: Option<LayerPosition>,
pub layer: Box<dyn NetworkLayer>,
}
#[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)]
pub struct RemoveLayerEvent {
pub id: Id,
} |
mod cache;
pub mod destination;
mod observe;
pub mod pb;
mod remote_stream;
mod serve_http;
pub use self::observe::Observe;
pub use self::serve_http::serve_http;
|
#[derive(Clone)]
pub struct SpriteFormat {
pub name: String,
pub extra_offset_x2: (i32, i32),
pub radial_offset_x2: (f32, f32),
pub final_offset: (f32, f32),
pub direction_count: i32,
pub used_directions: Option<Vec<i32>>,
pub animation_length: i32,
pub empty_pad: i32,
pub source_range_index: (i32, i32),
pub draw_as_shadow: bool,
pub draw_as_glow: bool,
pub scalable: bool,
pub run_mode: String,
pub frame_sequence: Option<Vec<i32>>,
pub split_anim: bool,
}
pub struct SpriteGroup {
pub source: String,
pub category: String,
pub base_offset_x2: (i32, i32),
pub sprites: Vec<SpriteFormat>,
}
pub fn getConfig() -> Vec<SpriteGroup> {
let DEFAULT_SPRITE_FORMAT = SpriteFormat {
name: String::new(),
extra_offset_x2: (0, 0),
radial_offset_x2: (0.0, 0.0),
final_offset: (0.0, 0.0),
direction_count: 0,
used_directions: None,
animation_length: 0,
empty_pad: 0,
source_range_index: (0, 0),
draw_as_shadow: false,
draw_as_glow: false,
scalable: false,
run_mode: String::from("forward"),
frame_sequence: None,
split_anim: false
};
vec![
SpriteGroup {
source: String::from("anim/main_112.anim"),
category: String::from("carrier"),
base_offset_x2: (-3, 0),
sprites: vec![
SpriteFormat {
name: String::from("run"),
direction_count: 32,
animation_length: 1,
source_range_index: (0, 17),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_113.anim"),
category: String::from("carrier"),
base_offset_x2: (-3, 0),
sprites: vec![
SpriteFormat {
name: String::from("run-shadow"),
direction_count: 32,
animation_length: 1,
source_range_index: (0, 17),
draw_as_shadow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_114.anim"),
category: String::from("carrier"),
base_offset_x2: (-3, 0),
sprites: vec![
SpriteFormat {
name: String::from("exhaust"),
direction_count: 32,
animation_length: 1,
source_range_index: (0, 17),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_116.anim"),
category: String::from("interceptor"),
base_offset_x2: (-4, 0),
sprites: vec![
SpriteFormat {
name: String::from("run"),
direction_count: 32,
animation_length: 1,
source_range_index: (0, 17),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("attack"),
direction_count: 32,
animation_length: 1,
source_range_index: (17, 34),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_122.anim"),
category: String::from("dragoon"),
base_offset_x2: (-4, 0),
sprites: vec![
SpriteFormat {
name: String::from("idle"),
direction_count: 1,
animation_length: 8,
source_range_index: (0, 136),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("run"),
direction_count: 4,
animation_length: 8,
source_range_index: (136, 272),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("attack"),
direction_count: 1,
animation_length: 8,
source_range_index: (272, 408),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("die"),
direction_count: 1,
animation_length: 7,
source_range_index: (408, 415),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_123.anim"),
category: String::from("dragoon"),
base_offset_x2: (-8, 0),
sprites: vec![
SpriteFormat {
name: String::from("idle-shadow"),
direction_count: 1,
animation_length: 8,
source_range_index: (0, 136),
draw_as_shadow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("run-shadow"),
direction_count: 4,
animation_length: 8,
source_range_index: (136, 272),
draw_as_shadow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("attack-shadow"),
direction_count: 1,
animation_length: 8,
source_range_index: (272, 408),
draw_as_shadow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_124.anim"),
category: String::from("dragoon"),
base_offset_x2: (-8, 0),
sprites: vec![
SpriteFormat {
name: String::from("corpse"),
direction_count: 1,
animation_length: 5,
source_range_index: (0, 5),
empty_pad: 1,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_134.anim"),
category: String::from("archon"),
base_offset_x2: (-36, -20),
sprites: vec![
SpriteFormat {
name: String::from("flame"),
direction_count: 1,
animation_length: 10,
source_range_index: (0, 10),
draw_as_glow: true,
frame_sequence: Option::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_135.anim"),
category: String::from("archon"),
base_offset_x2: (-14, -20),
sprites: vec![
SpriteFormat {
name: String::from("attack"),
direction_count: 32,
animation_length: 10,
source_range_index: (0, 170),
radial_offset_x2: (30.0, -20.0),
frame_sequence: Option::from(vec![2, 3, 4, 5, 6, 7, 7, 7, 8, 9, 10, 3, 3, 2, 2, 1, 1]),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("run"),
direction_count: 32,
animation_length: 4,
source_range_index: (170, 238),
radial_offset_x2: (30.0, -20.0),
run_mode: String::from("forward-then-backward"),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_136.anim"),
category: String::from("archon"),
base_offset_x2: (-36, -20),
sprites: vec![
SpriteFormat {
name: String::from("orbs"),
direction_count: 1,
animation_length: 15,
source_range_index: (0, 15),
draw_as_glow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_151.anim"),
category: String::from("zealot"),
base_offset_x2: (14, 0),
sprites: vec![
SpriteFormat {
name: String::from("attack"),
direction_count: 32,
animation_length: 5,
source_range_index: (0, 85),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("run"),
direction_count: 32,
animation_length: 8,
source_range_index: (85, 221),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("die"),
direction_count: 1,
animation_length: 7,
source_range_index: (221, 228),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_152.anim"),
category: String::from("zealot"),
base_offset_x2: (14, 0),
sprites: vec![
SpriteFormat {
name: String::from("attack-shadow"),
direction_count: 32,
animation_length: 5,
source_range_index: (0, 85),
draw_as_shadow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("run-shadow"),
direction_count: 32,
animation_length: 8,
source_range_index: (85, 221),
draw_as_shadow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_424.anim"),
category: String::from("effects"),
base_offset_x2: (0, 69),
sprites: vec![
SpriteFormat {
name: String::from("shield"),
direction_count: 8,
animation_length: 4,
source_range_index: (0, 68),
draw_as_glow: true,
scalable: true,
split_anim: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_427.anim"),
category: String::from("effects"),
base_offset_x2: (0, 0),
sprites: vec![
SpriteFormat {
name: String::from("explosion-medium"),
direction_count: 1,
animation_length: 14,
source_range_index: (0, 14),
draw_as_glow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_523.anim"),
category: String::from("projectiles"),
base_offset_x2: (0, 0),
sprites: vec![
SpriteFormat {
name: String::from("phase-disruptor"),
direction_count: 1,
animation_length: 5,
source_range_index: (0, 5),
draw_as_glow: true,
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_547.anim"),
category: String::from("archon"),
base_offset_x2: (-16, 44),
sprites: vec![
SpriteFormat {
name: String::from("psionic-shockwave"),
direction_count: 1,
animation_length: 6,
source_range_index: (0, 6),
extra_offset_x2: (-600, 0),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
SpriteGroup {
source: String::from("anim/main_549.anim"),
category: String::from("archon"),
base_offset_x2: (-18, 42),
sprites: vec![
SpriteFormat {
name: String::from("lightning-long"),
direction_count: 1,
animation_length: 2,
source_range_index: (0, 34),
used_directions: Option::from(vec![8]),
frame_sequence: Option::from(vec![1, 2, 1, 2, 1, 2]),
..DEFAULT_SPRITE_FORMAT.clone()
},
SpriteFormat {
name: String::from("lightning-short"),
direction_count: 1,
animation_length: 2,
source_range_index: (34, 68),
used_directions: Option::from(vec![8]),
frame_sequence: Option::from(vec![1, 2, 1, 2, 1, 2]),
..DEFAULT_SPRITE_FORMAT.clone()
},
],
},
]
}
|
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{get_parent_expr, is_lang_ctor, match_def_path, paths};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::LangItem::ResultErr;
use rustc_hir::{Expr, ExprKind, LangItem, MatchSource, QPath};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::{self, Ty};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{hygiene, sym};
declare_clippy_lint! {
/// ### What it does
/// Checks for usages of `Err(x)?`.
///
/// ### Why is this bad?
/// The `?` operator is designed to allow calls that
/// can fail to be easily chained. For example, `foo()?.bar()` or
/// `foo(bar()?)`. Because `Err(x)?` can't be used that way (it will
/// always return), it is more clear to write `return Err(x)`.
///
/// ### Example
/// ```rust
/// fn foo(fail: bool) -> Result<i32, String> {
/// if fail {
/// Err("failed")?;
/// }
/// Ok(0)
/// }
/// ```
/// Could be written:
///
/// ```rust
/// fn foo(fail: bool) -> Result<i32, String> {
/// if fail {
/// return Err("failed".into());
/// }
/// Ok(0)
/// }
/// ```
#[clippy::version = "1.38.0"]
pub TRY_ERR,
style,
"return errors explicitly rather than hiding them behind a `?`"
}
declare_lint_pass!(TryErr => [TRY_ERR]);
impl<'tcx> LateLintPass<'tcx> for TryErr {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
// Looks for a structure like this:
// match ::std::ops::Try::into_result(Err(5)) {
// ::std::result::Result::Err(err) =>
// #[allow(unreachable_code)]
// return ::std::ops::Try::from_error(::std::convert::From::from(err)),
// ::std::result::Result::Ok(val) =>
// #[allow(unreachable_code)]
// val,
// };
if_chain! {
if !in_external_macro(cx.tcx.sess, expr.span);
if let ExprKind::Match(match_arg, _, MatchSource::TryDesugar) = expr.kind;
if let ExprKind::Call(match_fun, try_args) = match_arg.kind;
if let ExprKind::Path(ref match_fun_path) = match_fun.kind;
if matches!(match_fun_path, QPath::LangItem(LangItem::TryTraitBranch, _));
if let Some(try_arg) = try_args.get(0);
if let ExprKind::Call(err_fun, err_args) = try_arg.kind;
if let Some(err_arg) = err_args.get(0);
if let ExprKind::Path(ref err_fun_path) = err_fun.kind;
if is_lang_ctor(cx, err_fun_path, ResultErr);
if let Some(return_ty) = find_return_type(cx, &expr.kind);
then {
let prefix;
let suffix;
let err_ty;
if let Some(ty) = result_error_type(cx, return_ty) {
prefix = "Err(";
suffix = ")";
err_ty = ty;
} else if let Some(ty) = poll_result_error_type(cx, return_ty) {
prefix = "Poll::Ready(Err(";
suffix = "))";
err_ty = ty;
} else if let Some(ty) = poll_option_result_error_type(cx, return_ty) {
prefix = "Poll::Ready(Some(Err(";
suffix = ")))";
err_ty = ty;
} else {
return;
};
let expr_err_ty = cx.typeck_results().expr_ty(err_arg);
let span = hygiene::walk_chain(err_arg.span, try_arg.span.ctxt());
let mut applicability = Applicability::MachineApplicable;
let origin_snippet = snippet_with_applicability(cx, span, "_", &mut applicability);
let ret_prefix = if get_parent_expr(cx, expr).map_or(false, |e| matches!(e.kind, ExprKind::Ret(_))) {
"" // already returns
} else {
"return "
};
let suggestion = if err_ty == expr_err_ty {
format!("{}{}{}{}", ret_prefix, prefix, origin_snippet, suffix)
} else {
format!("{}{}{}.into(){}", ret_prefix, prefix, origin_snippet, suffix)
};
span_lint_and_sugg(
cx,
TRY_ERR,
expr.span,
"returning an `Err(_)` with the `?` operator",
"try this",
suggestion,
applicability,
);
}
}
}
}
/// Finds function return type by examining return expressions in match arms.
fn find_return_type<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx ExprKind<'_>) -> Option<Ty<'tcx>> {
if let ExprKind::Match(_, arms, MatchSource::TryDesugar) = expr {
for arm in arms.iter() {
if let ExprKind::Ret(Some(ret)) = arm.body.kind {
return Some(cx.typeck_results().expr_ty(ret));
}
}
}
None
}
/// Extracts the error type from Result<T, E>.
fn result_error_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
if_chain! {
if let ty::Adt(_, subst) = ty.kind();
if is_type_diagnostic_item(cx, ty, sym::Result);
then {
Some(subst.type_at(1))
} else {
None
}
}
}
/// Extracts the error type from Poll<Result<T, E>>.
fn poll_result_error_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
if_chain! {
if let ty::Adt(def, subst) = ty.kind();
if match_def_path(cx, def.did, &paths::POLL);
let ready_ty = subst.type_at(0);
if let ty::Adt(ready_def, ready_subst) = ready_ty.kind();
if cx.tcx.is_diagnostic_item(sym::Result, ready_def.did);
then {
Some(ready_subst.type_at(1))
} else {
None
}
}
}
/// Extracts the error type from Poll<Option<Result<T, E>>>.
fn poll_option_result_error_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
if_chain! {
if let ty::Adt(def, subst) = ty.kind();
if match_def_path(cx, def.did, &paths::POLL);
let ready_ty = subst.type_at(0);
if let ty::Adt(ready_def, ready_subst) = ready_ty.kind();
if cx.tcx.is_diagnostic_item(sym::Option, ready_def.did);
let some_ty = ready_subst.type_at(0);
if let ty::Adt(some_def, some_subst) = some_ty.kind();
if cx.tcx.is_diagnostic_item(sym::Result, some_def.did);
then {
Some(some_subst.type_at(1))
} else {
None
}
}
}
|
// 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.
#![feature(box_syntax)]
fn match_on_local() {
let mut foo: Option<Box<_>> = Some(box 5);
match foo {
None => {},
Some(x) => {
foo = Some(x);
}
}
println!("'{}'", foo.unwrap());
}
fn match_on_arg(mut foo: Option<Box<i32>>) {
match foo {
None => {}
Some(x) => {
foo = Some(x);
}
}
println!("'{}'", foo.unwrap());
}
fn match_on_binding() {
match Some(Box::new(7)) {
mut foo => {
match foo {
None => {},
Some(x) => {
foo = Some(x);
}
}
println!("'{}'", foo.unwrap());
}
}
}
fn match_on_upvar() {
let mut foo: Option<Box<_>> = Some(box 8);
let f = move|| {
match foo {
None => {},
Some(x) => {
foo = Some(x);
}
}
println!("'{}'", foo.unwrap());
};
f();
}
fn main() {
match_on_local();
match_on_arg(Some(box 6));
match_on_binding();
match_on_upvar();
}
|
//super::log;
use super::model::{
ColumnType, CsvError, CsvErrors, StatementSelections, StatementType, StatementSelection, ColumnSource
};
use super::{DATETIME_FORMATS, DATE_FORMATS};
use chrono::{NaiveDate, NaiveDateTime};
use wasm_bindgen::prelude::*;
use csv::StringRecord;
#[wasm_bindgen]
pub fn check_correction(value: &str, column_type: &str) -> JsValue {
let error = match column_type {
"Int" => check_int_errors(value),
"Float" => check_float_errors(value),
"Date" => check_date_errors(value),
"DateTime" => check_date_errors(value),
"VarChar" => check_varchar_errors(value),
_ => false,
};
return JsValue::from_bool(!error);
}
#[wasm_bindgen]
pub fn process_file(data: &str, statements: JsValue) -> JsValue {
let statements: StatementSelections = match statements.into_serde() {
Ok(s) => s,
Err(_e) => {
return JsValue::from_str("Couldn't deserialize the statements, did the model change?");
}
};
let errors = match process_file_impl(data, statements) {
Ok(e) => e,
Err(e) => return JsValue::from_str(&e),
};
let csv_error = CsvErrors { value: errors };
return JsValue::from_serde(&csv_error).unwrap();
}
fn process_file_impl(data: &str, statements: StatementSelections) -> Result<Vec<CsvError>, String> {
let mut errors: Vec<CsvError> = Vec::new();
let mut reader = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(data.as_bytes());
for (index, row) in reader.records().enumerate() {
let record = row
.map_err(|e|
format!("The .csv file could not be parsed. Internal Error: {}", e ))?;
if record.iter().all(|r| r.trim().is_empty()) {
continue;
}
for statement in &statements.value {
process_record_for_statment(&record, index, &statement, &mut errors);
if statement.r#type == StatementType::Update {
for condition in &statement.where_selections {
let column_id = condition.value.unwrap();
let column_type = condition.r#type.clone().unwrap();
let value = &record[column_id];
if check_for_error(&column_type, value) {
add_error(&mut errors, value, statement.id, column_id, index, &column_type);
}
}
}
}
}
Ok(errors)
}
fn process_record_for_statment(record: &StringRecord, index: usize, statement: &StatementSelection, mut errors: &mut Vec<CsvError>){
if let Some(selections) = &statement.column_selections {
for column in &selections.value {
match column.source {
ColumnSource::FreeText => {
// Don't add errors for freetext it always is what the user typed in.
},
ColumnSource::CSV => {
let id = column.column.unwrap();
let value = &record[id];
if check_for_error(&column.r#type, value) {
add_error(&mut errors, value, statement.id, id, index, &column.r#type);
}
}
}
}
}
}
fn add_error(errors: &mut Vec<CsvError>,
value: &str,
statement_id: usize,
column_id: usize,
index: usize,
column_type: &ColumnType)
{
if let Some(e) = errors
.iter_mut()
.find(|i| &(**i).error_text == value && &(**i).column_id == &column_id) {
e.rows.push(index);
}
else {
let error = CsvError {
statement_id,
column_id,
r#type: column_type.clone(),
error_text: value.to_string(),
rows: vec![index],
};
errors.push(error);
}
}
fn check_for_error(column_type: &ColumnType, value: &str) -> bool {
match column_type {
ColumnType::Int => check_int_errors(value.trim()),
ColumnType::Float => check_float_errors(value.trim()),
ColumnType::Date => check_date_errors(value.trim()),
ColumnType::DateTime => check_date_errors(value.trim()),
ColumnType::VarChar => check_varchar_errors(value.trim()),
ColumnType::PreFormatted => true,
}
}
fn check_int_errors(value: &str) -> bool {
let value = value.trim();
if is_null(value) {
return false;
}
!value.parse::<i32>().is_ok()
}
fn check_float_errors(value: &str) -> bool {
let value = value.trim();
if is_null(value) {
return false;
}
!value.parse::<f32>().is_ok()
}
fn check_date_errors(value: &str) -> bool {
let value = value.trim();
if is_null(value) {
return false;
}
for format in &DATETIME_FORMATS {
let parsed = NaiveDateTime::parse_from_str(value.trim(), format);
if parsed.is_ok() {
return false;
}
}
for format in &DATE_FORMATS {
let parsed = NaiveDate::parse_from_str(value.trim(), format);
if parsed.is_ok() {
return false;
}
}
return true;
}
fn check_varchar_errors(value: &str) -> bool {
let value = value.trim();
if is_null(value) {
return false;
}
false
}
fn is_null(value: &str) -> bool {
let value = value.trim();
value.to_lowercase() == "null"
}
#[cfg(test)]
pub mod tests {
use super::super::model::{ColumnSelections, CsvError, CsvErrors};
use super::process_file;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn process_file_finds_errors() {
let (csv_data, column_selections) = setup();
let value = process_file(&csv_data, column_selections);
let errors: CsvErrors = value.into_serde().unwrap();
assert_eq!(2, errors.value.len());
}
fn setup() -> (String, JsValue) {
let csv_data = r#"FirstName,Enabled,StartDate
Dan,1,01/01/2017
Carlos,0,2017-01-01
Gerald,h,Not a date
Jordan,2,01/02/2016
"#;
let column_selections = r#"
{
"value": [
{
"column": 0,
"statement_id": 0,
"name": "FirstName",
"type": "VarChar",
"use_source": true
},
{
"column": 1,
"statement_id": 0,
"name": "Enabled",
"type": "Int",
"use_source": true
},
{
"column": 2,
"statement_id": 0,
"name": "StartDate",
"type": "Date",
"use_source": true
}
],
"done": false
}
"#;
let column_selections: ColumnSelections = serde_json::from_str(column_selections).unwrap();
let column_selections: JsValue = JsValue::from_serde(&column_selections).unwrap();
(csv_data.to_string(), column_selections)
}
}
|
use std::fmt::{Result, Display, Formatter};
use piece::*;
use kind::*;
use mask::Mask;
use mask::masks::*;
use color::Color;
use side::*;
use sided_mask::*;
#[derive(Eq, Copy, Clone, Debug, Default, PartialEq)]
pub struct BitBoard([Mask; PIECES_COUNT]);
impl BitBoard {
pub fn new() -> Self {
BitBoard([EMPTY; PIECES_COUNT])
}
fn index(&self, piece: Piece) -> Mask {
self.0[piece.bits() as usize]
}
pub fn pawns<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.index(S::PAWN))
}
pub fn pawns_of(&self, color: Color) -> Mask {
self.index(PAWN.of(color))
}
pub fn knights<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.index(S::KNIGHT))
}
pub fn knights_of(&self, color: Color) -> Mask {
self.index(KNIGHT.of(color))
}
pub fn bishops<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.index(S::BISHOP))
}
pub fn bishops_of(&self, color: Color) -> Mask {
self.index(BISHOP.of(color))
}
pub fn rooks<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.index(S::ROOK))
}
pub fn rooks_of(&self, color: Color) -> Mask {
self.index(ROOK.of(color))
}
pub fn queens<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.index(S::QUEEN))
}
pub fn queens_of(&self, color: Color) -> Mask {
self.index(QUEEN.of(color))
}
pub fn kings<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.index(S::KING))
}
pub fn kings_of(&self, color: Color) -> Mask {
self.index(KING.of(color))
}
pub fn set_piece(&mut self, square: Mask, piece: Piece) {
let idx = piece.bits() as usize;
self.0[idx] |= square;
}
pub fn get_piece(&self, square: Mask) -> Piece {
for probe in ALL_PIECES {
if self.index(probe).intersects(square) {
return probe;
}
}
VOID
}
pub fn squares(&self) -> SquareIter {
SquareIter {
board: self,
current: MaskIter::new(),
}
}
pub fn parse(input: &str) -> Self {
fen::parse_bit_board(input.as_bytes()).unwrap().1
}
pub fn occupation_of(&self, color: Color) -> Mask {
if color == Color::White {
self.occupation_gen::<White>().mask()
} else {
self.occupation_gen::<Black>().mask()
}
}
pub fn occupation_gen<S: Side>(&self) -> S::Mask {
S::Mask::wrap(self.0[S::RANGE].iter().fold(EMPTY, |acc, &x| acc | x))
}
pub fn occupation(&self) -> Mask {
self.0.iter().fold(EMPTY, |acc, &x| acc | x)
}
pub fn castling_move_masks<S: Side>(&self) -> Mask {
EMPTY
}
pub fn swap_colors(&self) -> Self {
let x = self.0;
BitBoard([x[6].flip_vertically(),
x[7].flip_vertically(),
x[8].flip_vertically(),
x[9].flip_vertically(),
x[10].flip_vertically(),
x[11].flip_vertically(),
x[0].flip_vertically(),
x[1].flip_vertically(),
x[2].flip_vertically(),
x[3].flip_vertically(),
x[4].flip_vertically(),
x[5].flip_vertically()])
}
}
pub mod fen;
pub mod attacks;
impl Display for BitBoard {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.print_fen())
}
}
#[derive(Copy, Clone, Debug)]
pub struct SquareIter<'a> {
board: &'a BitBoard,
current: MaskIter,
}
impl<'a> Iterator for SquareIter<'a> {
type Item = Piece;
fn next(&mut self) -> Option<Self::Item> {
self.current.next().map(|square| self.board.get_piece(square))
}
}
#[cfg(test)]
mod test {
use super::*;
use std::iter::*;
use rand::*;
use mask::Mask;
#[test]
fn get_piece() {
let mut b = BitBoard::new();
b.set_piece(E2, BLACK_ROOK);
b.set_piece(E3, BLACK_ROOK);
assert_eq!(b.get_piece(E2), BLACK_ROOK);
assert_eq!(b.get_piece(E3), BLACK_ROOK);
}
#[test]
fn bit_board_squares() {
use std::iter::*;
let mut b = BitBoard::new();
b.set_piece(A8, BLACK_ROOK);
let all = b.squares().collect::<Vec<_>>();
assert_eq!(all.len(), 64);
assert_eq!(all[0], BLACK_ROOK);
assert_eq!(all[63], VOID);
}
#[test]
fn occupation() {
assert_eq!(sample_with_one_of_each_kind().occupation().dump(),
"|@@@@@@^^|...|^^^^^^^^|...|^^^^^^^^|...|^^^^^^^^|...|^^^^^^^^|...|^^^^^^^^|..\
.|^^^^^^^^|...|@@@@@@^^|...");
}
#[test]
fn black_occupation() {
assert_eq!(sample_with_one_of_each_kind().occupation_gen::<Black>().0.dump(),
"|@@@@@@^^|...|^^^^^^^^|...|^^^^^^^^|...|^^^^^^^^|...|^^^^^^^^|...|^^^^^^^^|..\
.|^^^^^^^^|...|^^^^^^^^|...");
}
#[test]
fn white_occupation() {
assert_eq!(sample_with_one_of_each_kind()
.occupation_gen::<White>().0.dump(),
"|^^^^^^^^|..\
.|^^^^^^^^|..\
.|^^^^^^^^|..\
.|^^^^^^^^|..\
.|^^^^^^^^|..\
.|^^^^^^^^|..\
.|^^^^^^^^|..\
.|@@@@@@^^|...");
}
fn sample_with_one_of_each_kind() -> BitBoard {
let mut b = BitBoard::new();
b.set_piece(A8, BLACK_ROOK);
b.set_piece(B8, BLACK_BISHOP);
b.set_piece(C8, BLACK_KING);
b.set_piece(D8, BLACK_QUEEN);
b.set_piece(E8, BLACK_PAWN);
b.set_piece(F8, BLACK_KNIGHT);
b.set_piece(A1, WHITE_ROOK);
b.set_piece(B1, WHITE_BISHOP);
b.set_piece(C1, WHITE_KING);
b.set_piece(D1, WHITE_QUEEN);
b.set_piece(E1, WHITE_PAWN);
b.set_piece(F1, WHITE_KNIGHT);
b
}
// #[test]
// fn white_attacks() {
// let mut gen = weak_rng();
// for _ in 0..2000 {
// let bb = generate_random_board(&mut gen);
// let b88 = Board88::from(&bb);
// if bb.white_attacks() != b88.white_attacks() {
// panic!("\r\nbit-board: {:?}\r\nx88 board: {:?}\r\nfen: {}\r\n",
// bb.white_attacks(),
// b88.white_attacks(),
// format!("{}", bb))
// }
// }
// }
// #[test]
// fn black_attacks_are_white_attacks_reverse() {
// let mut gen = weak_rng();
// for _ in 0..2000 {
// let bb = generate_random_board(&mut gen);
// let inverse = bb.swap_colors();
// let cmp = inverse.black_attacks().flip_vertically();
// if bb.white_attacks() != cmp {
// panic!("\r\nbit-board: {:?}\r\nx88 board: {:?}\r\nbb: {}\r\ninverse: {}\r\n",
// bb.white_attacks(),
// cmp,
// bb,
// inverse)
// }
// }
// }
#[test]
fn test_generate_random_board() {
let mut gen = XorShiftRng::from_seed([1, 2, 3, 4]);
assert_eq!(format!("{}", generate_random_board(&mut gen)),
"Nrqp4/3P4/8/8/3P4/3p4/8/8");
assert_eq!(format!("{}", generate_random_board(&mut gen)),
"6p1/pb2P3/2p4N/2p2p2/3P1Pqp/r2n4/K7/5n2");
}
#[test]
fn test_generate_random_board_count() {
let mut gen = XorShiftRng::from_seed([1, 2, 3, 4]);
assert_eq!((0..10000)
.into_iter()
.map(|_| generate_random_board(&mut gen).occupation().count())
.sum::<u32>(),
159635);
}
#[test]
fn test_generate_random_board_unique_masks() {
let mut gen = XorShiftRng::from_seed([1, 2, 3, 4]);
for _ in 0..10000 {
let board = generate_random_board(&mut gen);
let fen = format!("{}", board);
assert_eq!(BitBoard::parse(fen.as_str()), board);
}
}
fn generate_random_board(rng: &mut XorShiftRng) -> BitBoard {
let mut result = BitBoard::new();
for one in Mask::new(rng.next_u64()).single_bits() {
match rng.next_u32() % 38 {
0...3 => result.set_piece(one, WHITE_PAWN),
4 => result.set_piece(one, WHITE_KNIGHT),
5 => result.set_piece(one, WHITE_BISHOP),
6 => result.set_piece(one, WHITE_ROOK),
7 => result.set_piece(one, WHITE_QUEEN),
8 => result.set_piece(one, WHITE_KING),
9...13 => result.set_piece(one, BLACK_PAWN),
14 => result.set_piece(one, BLACK_KNIGHT),
15 => result.set_piece(one, BLACK_BISHOP),
16 => result.set_piece(one, BLACK_ROOK),
17 => result.set_piece(one, BLACK_QUEEN),
18 => result.set_piece(one, BLACK_KING),
_ => {}
}
}
result
}
}
|
use super::VarResult;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::str_replace;
use crate::helper::{
move_element, pine_ref_to_bool, pine_ref_to_f64, pine_ref_to_f64_series, pine_ref_to_i64,
require_param,
};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::runtime::InputSrc;
use crate::types::{
downcast_pf_ref, int2float, Arithmetic, Callable, CallableFactory, Evaluate, EvaluateVal,
Float, Int, ParamCollectCall, PineRef, RefData, RuntimeErr, Series, SeriesCall, NA,
};
use std::mem;
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq)]
struct EmaVal;
impl<'a> SeriesCall<'a> for EmaVal {
fn step(
&mut self,
_ctx: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
let source = mem::replace(&mut param[0], None);
let source = require_param("x", pine_ref_to_f64_series(source))?;
// x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6
let val = (source
.index_value(3)
.unwrap()
.add(source.index_value(0).unwrap()))
.div(Some(6f64))
.add(
source
.index_value(2)
.unwrap()
.add(source.index_value(1).unwrap())
.mul(Some(2f64).div(Some(6f64))),
);
Ok(PineRef::new(Series::from(val)))
}
fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> {
Box::new(self.clone())
}
}
pub fn declare_var<'a>() -> VarResult<'a> {
let value = PineRef::new(CallableFactory::new(|| {
Callable::new(
None,
Some(Box::new(ParamCollectCall::new_with_caller(Box::new(
EmaVal,
)))),
)
}));
let func_type = FunctionTypes(vec![FunctionType::new((
vec![("source", SyntaxType::float_series())],
SyntaxType::float_series(),
))]);
let syntax_type = SyntaxType::Function(Rc::new(func_type));
VarResult::new(value, syntax_type, "swma")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::syntax_type::SyntaxType;
use crate::runtime::VarOperate;
use crate::runtime::{AnySeries, NoneCallback};
use crate::types::Series;
use crate::{LibInfo, PineParser, PineRunner};
// use crate::libs::{floor, exp, };
#[test]
fn alma_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::float_series())],
);
let src = "m1 = swma(close)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![(
"close",
AnySeries::from_float_vec(vec![
Some(6f64),
Some(12f64),
Some(12f64),
Some(6f64),
]),
)],
None,
)
.unwrap();
assert_eq!(
runner.get_context().move_var(VarIndex::new(0, 0)),
Some(PineRef::new(Series::from_vec(vec![
None,
None,
None,
Some(10f64)
])))
);
}
}
|
#[doc = "Reader of register TXBTO"]
pub type R = crate::R<u32, super::TXBTO>;
#[doc = "Reader of field `TO`"]
pub type TO_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - TO"]
#[inline(always)]
pub fn to(&self) -> TO_R {
TO_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
//! Day 22
use std::collections::{HashSet, VecDeque};
trait Solution {
fn part_1(&self) -> u64;
fn part_2(&self) -> u64;
}
impl Solution for str {
fn part_1(&self) -> u64 {
let (player_1, player_2) = parsers::input(self).expect("Failed to parse the input");
let mut game = Combat::new(player_1, player_2);
game.play_out();
game.winner_score()
}
fn part_2(&self) -> u64 {
let (player_1, player_2) = parsers::input(self).expect("Failed to parse the input");
let mut game = RecursiveCombat::new(player_1, player_2);
game.play_out();
game.winner_score()
}
}
type Card = u64;
struct Combat {
player_1: Deck,
player_2: Deck,
}
struct RecursiveCombat {
player_1: Deck,
player_2: Deck,
history_1: HashSet<Deck>,
history_2: HashSet<Deck>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Deck(pub VecDeque<Card>);
trait Game {
fn play_round(&mut self);
fn has_winner(&self) -> bool;
fn winner_score(&self) -> Card;
}
trait GameExt: Game {
fn play_out(&mut self) {
while !self.has_winner() {
self.play_round()
}
}
}
impl<T: Game> GameExt for T {}
impl Combat {
pub fn new(
player_1: impl IntoIterator<Item = Card>,
player_2: impl IntoIterator<Item = Card>,
) -> Self {
Self {
player_1: Deck(player_1.into_iter().collect()),
player_2: Deck(player_2.into_iter().collect()),
}
}
}
impl Game for Combat {
fn play_round(&mut self) {
let card_1 = self.player_1.0.pop_front().unwrap();
let card_2 = self.player_2.0.pop_front().unwrap();
if card_1 > card_2 {
self.player_1.0.push_back(card_1);
self.player_1.0.push_back(card_2);
} else {
self.player_2.0.push_back(card_2);
self.player_2.0.push_back(card_1);
}
}
fn has_winner(&self) -> bool {
self.player_1.0.is_empty() || self.player_2.0.is_empty()
}
fn winner_score(&self) -> Card {
if self.player_1.0.is_empty() {
self.player_2.score()
} else {
self.player_1.score()
}
}
}
impl RecursiveCombat {
pub fn new(
player_1: impl IntoIterator<Item = Card>,
player_2: impl IntoIterator<Item = Card>,
) -> Self {
Self {
player_1: Deck(player_1.into_iter().collect()),
player_2: Deck(player_2.into_iter().collect()),
history_1: HashSet::new(),
history_2: HashSet::new(),
}
}
fn player_1_wins(&self) -> bool {
self.has_already_been_played() || self.player_2.0.is_empty()
}
fn has_already_been_played(&self) -> bool {
self.history_1.contains(&self.player_1) || self.history_2.contains(&self.player_2)
}
}
impl Game for RecursiveCombat {
fn play_round(&mut self) {
self.history_1.insert(self.player_1.clone());
self.history_2.insert(self.player_2.clone());
let card_1 = self.player_1.0.pop_front().unwrap();
let card_2 = self.player_2.0.pop_front().unwrap();
let player_1_wins = if card_1 as usize <= self.player_1.0.len()
&& card_2 as usize <= self.player_2.0.len()
{
let mut sub_game = RecursiveCombat::new(
self.player_1.0.iter().copied().take(card_1 as usize),
self.player_2.0.iter().copied().take(card_2 as usize),
);
sub_game.play_out();
sub_game.player_1_wins()
} else {
card_1 > card_2
};
if player_1_wins {
self.player_1.0.push_back(card_1);
self.player_1.0.push_back(card_2);
} else {
self.player_2.0.push_back(card_2);
self.player_2.0.push_back(card_1);
}
}
fn has_winner(&self) -> bool {
self.has_already_been_played() || self.player_1.0.is_empty() || self.player_2.0.is_empty()
}
fn winner_score(&self) -> Card {
if self.player_1.0.is_empty() {
self.player_2.score()
} else {
self.player_1.score()
}
}
}
impl Deck {
pub fn score(&self) -> Card {
self.0
.iter()
.rev()
.enumerate()
.map(|(ix, card)| (ix as Card + 1) * card)
.sum()
}
}
mod parsers {
use nom::{
bytes::streaming::tag,
character::complete::line_ending,
error::Error,
multi::separated_list1,
sequence::{separated_pair, terminated},
IResult,
};
use crate::parsers::{double_line_ending, finished_parser, integer};
use super::Card;
pub fn input(s: &str) -> Result<(Vec<Card>, Vec<Card>), Error<&str>> {
finished_parser(separated_pair(deck("1"), double_line_ending, deck("2")))(s)
}
fn deck(player: impl Into<String>) -> impl FnMut(&str) -> IResult<&str, Vec<Card>> {
let player = player.into();
move |s| {
let (s, _) = tag("Player ")(s)?;
let (s, _) = tag(player.as_str())(s)?;
let (s, _) = terminated(tag(":"), line_ending)(s)?;
separated_list1(line_ending, integer)(s)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example_1() {
assert_eq!(
"\
Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10"
.part_1(),
306
)
}
#[test]
fn part_1() {
assert_eq!(include_str!("inputs/day_22").part_1(), 31_809);
}
#[test]
fn example_2() {
let (player_1, player_2) = parsers::input(
"\
Player 1:
43
19
Player 2:
2
29
14",
)
.unwrap();
let mut game = RecursiveCombat::new(player_1, player_2);
for _ in 0..7 {
game.play_round();
}
assert!(game.has_already_been_played());
}
#[test]
fn example_3() {
assert_eq!(
"\
Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10"
.part_2(),
291
)
}
#[test]
fn part_2() {
assert_eq!(include_str!("inputs/day_22").part_2(), 32_835);
}
}
|
use crate::bindings::*;
use std::marker::PhantomData;
use std::slice;
use std::str::{self, Utf8Error};
use std::borrow::Cow;
pub struct NgxStr<'a>(ngx_str_t, PhantomData<&'a [u8]>);
impl<'a> NgxStr<'a> {
pub fn new(str: &str) -> NgxStr {
NgxStr(ngx_str_t { len: str.len(), data: str.as_ptr() as *mut u_char }, PhantomData)
}
pub unsafe fn from_ngx_str(str: ngx_str_t) -> NgxStr<'a> {
NgxStr(str, PhantomData)
}
pub fn as_bytes(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.0.data, self.0.len) }
}
pub fn to_str(&self) -> Result<&str, Utf8Error> {
str::from_utf8(self.as_bytes())
}
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(self.as_bytes())
}
pub fn is_empty(&self) -> bool {
self.0.len == 0
}
}
impl AsRef<[u8]> for NgxStr<'_> {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl Default for NgxStr<'_> {
fn default() -> Self {
NgxStr(ngx_str_t { len: 0, data: b"".as_ptr() as *mut u_char }, PhantomData)
}
}
|
use {
crate::registry::base::{Command, Notifier, State},
crate::switchboard::base::{DeviceInfo, SettingResponse},
fuchsia_async as fasync,
fuchsia_syslog::fx_log_info,
futures::StreamExt,
parking_lot::RwLock,
std::fs,
};
const BUILD_TAG_FILE_PATH: &str = "/config/build-info/version";
pub fn spawn_device_controller() -> futures::channel::mpsc::UnboundedSender<Command> {
let (device_handler_tx, mut device_handler_rx) = futures::channel::mpsc::unbounded::<Command>();
let notifier_lock = RwLock::<Option<Notifier>>::new(None);
fasync::spawn(async move {
while let Some(command) = device_handler_rx.next().await {
match command {
Command::ChangeState(state) => match state {
State::Listen(notifier) => {
let mut n = notifier_lock.write();
*n = Some(notifier);
}
State::EndListen => {
let mut n = notifier_lock.write();
*n = None;
}
},
Command::HandleRequest(_request, responder) => {
// TODO (go/fxb/36506): Send error back to client through responder.
// Right now will panic in hanging_get_handler if Err is sent back.
let contents = fs::read_to_string(BUILD_TAG_FILE_PATH)
.expect("Could not read build tag file");
let device_info = DeviceInfo {
build_tag: contents.trim().to_string(),
};
fx_log_info!("{:?}", device_info);
responder
.send(Ok(Some(SettingResponse::Device(device_info))))
.ok();
}
}
}
});
device_handler_tx
}
|
use symbol::SymbolId;
use std::rc::Rc;
pub type Unique = u32;
#[derive(Debug, PartialEq, Clone)]
pub enum Ty {
Int,
String,
Nil,
Bool,
Record {
unique: Unique,
fields: Vec<(SymbolId, Rc<Ty>)>,
},
Array {
typ: Rc<Ty>,
unique: Unique,
},
Unit,
Name(SymbolId, Option<Rc<Ty>>),
}
#[derive(Debug, PartialEq, Clone)]
pub enum EnvEntry {
VarEntry(Rc<Ty>),
FunEntry {
formals: Vec<Rc<Ty>>,
result: Rc<Ty>,
}
}
use std::collections::BTreeMap;
pub struct Table<'a, T: 'a> {
parent: Option<&'a Table<'a, T>>,
map: BTreeMap<SymbolId, Rc<T>>,
}
impl<'a, T: 'a> Table<'a, T> {
pub fn new(parent: Option<&'a Table<'a, T>>) -> Table<'a, T> {
Table {
map: BTreeMap::new(),
parent: parent
}
}
pub fn enter(&mut self, s: SymbolId, v: Rc<T>) {
self.map.insert(s, v);
}
pub fn look(&self, s: SymbolId) -> Option<&Rc<T>> {
let v = self.map.get(&s);
match (v, self.parent.as_ref()) {
(Some(_), _) => v,
(None, Some(parent)) => parent.look(s),
(None, None) => None,
}
}
pub fn contains(&self, s: SymbolId) -> bool {
match (self.map.contains_key(&s), self.parent.as_ref()) {
(true, _) => true,
(false, None) => false,
(false, Some(parent)) => parent.contains(s)
}
}
}
#[test]
fn test_table() {
let ty = Rc::new(Ty::Int);
let ty2 = Rc::new(Ty::String);
let mut table: Table<Ty> = Table::new(None);
table.enter(0, ty);
assert_eq!(table.contains(0), true);
assert_eq!(table.contains(1), false);
let res = table.look(0);
assert!(res.is_some());
assert_eq!(&**res.unwrap(), &Ty::Int);
let mut t2: Table<Ty> = Table::new(Some(&table));
t2.enter(1, ty2);
assert_eq!(t2.contains(0), true);
assert_eq!(t2.contains(1), true);
assert_eq!(t2.contains(2), false);
assert_eq!(&**t2.look(0).unwrap(), &Ty::Int);
assert_eq!(&**t2.look(1).unwrap(), &Ty::String);
let ty3 = Rc::new(Ty::Array {
typ: t2.look(0).unwrap().clone(),
unique: 2
});
t2.enter(2, ty3);
}
pub type TypeEnv<'a> = Table<'a, Ty>;
pub type ValueEnv<'a> = Table<'a, EnvEntry>;
#[test]
fn test_table_refs() {
// let mut tenv = TypeEnv::new(None);
//
// let ty = Box::new(Ty::Int);
// tenv.enter(0, ty);
// let ty = tenv.look(0).unwrap();
//
// let ty2 = Box::new(Ty::Array {
// unique: 0,
// typ: ty,
// });
//
// tenv.enter(1, ty2);
}
|
use fixedbitset::FixedBitSet;
use parser::Cell;
use puzzle::Line;
use puzzle::LineHint;
use puzzle::LineMut;
use puzzle::LinePass;
#[derive(Debug, Eq)]
pub struct FilledRun {
start: usize,
end: usize,
numbers: FixedBitSet,
}
impl LineHint for FilledRun {
fn check(&self, line: &Line) -> bool {
line.range_contains_unfilled(self.start..self.end)
}
fn apply(&self, line: &mut LineMut) {
line.fill_range(self.start..self.end)
}
}
impl PartialEq for FilledRun {
fn eq(&self, other: &Self) -> bool {
self.start == other.start
&& self.end == other.end
&& self.numbers.intersection(&other.numbers).count()
== self.numbers.count_ones(0..self.numbers.len())
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct CrossedRun {
start: usize,
end: usize,
}
impl LineHint for CrossedRun {
fn check(&self, line: &Line) -> bool {
line.range_contains_uncrossed(self.start..self.end)
}
fn apply(&self, line: &mut LineMut) {
line.cross_range(self.start..self.end)
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum DiscreteRangeHint {
CrossedRun(CrossedRun),
FilledRun(FilledRun),
}
impl LineHint for DiscreteRangeHint {
fn check(&self, line: &Line) -> bool {
match self {
DiscreteRangeHint::CrossedRun(inner) => inner.check(line),
DiscreteRangeHint::FilledRun(inner) => inner.check(line),
}
}
fn apply(&self, line: &mut LineMut) {
match self {
DiscreteRangeHint::CrossedRun(inner) => inner.apply(line),
DiscreteRangeHint::FilledRun(inner) => inner.apply(line),
}
}
}
#[derive(Clone, Copy)]
enum State {
Empty(usize),
Filled(usize, usize),
End,
}
impl State {
fn start() -> State {
State::Empty(0)
}
fn cell(self, cell: Cell) -> Self {
match (self, cell) {
(State::Empty(_), Cell::Crossed) => State::Empty(0),
(State::Empty(n), Cell::Undecided) => State::Empty(n + 1),
(State::Empty(n), Cell::Filled) => State::Filled(1, n + 1),
(State::Filled(m, n), Cell::Undecided) => State::Filled(m + 1, n + 1),
(State::Filled(m, n), Cell::Filled) => State::Filled(m + 1, n + 1),
(State::Filled(_, _), Cell::Crossed) => State::End,
(State::End, _) => State::End,
(_, Cell::Impossible) => State::End,
}
}
}
struct Iter<'a> {
line: &'a Line,
number: usize,
focus: usize,
state: State,
}
impl<'a> Iter<'a> {
fn new(line: &'a Line, number: usize, start: usize) -> Self {
Iter {
line,
number,
focus: start,
state: State::start(),
}
}
}
impl<'a> Iterator for Iter<'a> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
for focus in self.focus..self.line.len() {
self.state = match self.state.cell(self.line.get(focus)) {
State::Filled(m, _) if m > self.number => State::End,
state => state,
};
let emit = match self.state {
State::Filled(_, n) if n >= self.number => true,
State::Empty(n) if n >= self.number => true,
_ => false,
};
if emit && (focus + 1 >= self.line.len() || !self.line.is_filled(focus + 1)) {
self.focus = focus + 1;
return Some(self.focus - self.number);
}
}
self.focus = self.line.len();
None
}
}
struct Possibilities {
filled: FixedBitSet,
crossed: FixedBitSet,
cell_numbers: FixedBitSet,
}
impl Possibilities {
fn new(line_len: usize, clue_len: usize) -> Self {
let cell_numbers = FixedBitSet::with_capacity(line_len * clue_len);
let mut filled = FixedBitSet::with_capacity(line_len);
let mut crossed = FixedBitSet::with_capacity(line_len);
filled.set_range(0..line_len, true);
crossed.set_range(0..line_len, true);
Possibilities {
filled,
crossed,
cell_numbers,
}
}
fn positions(&mut self, positions: &[usize], clue: &[usize]) {
//println!(" OK {} {:?}", start, &positions);
let mut old_end = 0;
for ((number_index, number), start) in clue.iter().enumerate().zip(positions) {
//println!(" filled {}..{}", old_end, start);
for j in old_end..*start {
self.filled.set(j, false);
}
//println!(" crossed {}..{}", *start, *start + number);
for j in *start..*start + number {
self.crossed.set(j, false);
self.cell_numbers.put(j * clue.len() + number_index);
}
old_end = *start + number;
}
//println!(" filled {}..{}", old_end, line.len());
for j in old_end..self.filled.len() {
self.filled.set(j, false);
}
}
fn solve(
&mut self,
line: &Line,
clue: &[usize],
depth: usize,
start: usize,
positions: &mut Vec<usize>,
) {
if let Some(number) = clue.get(depth) {
for start in Iter::new(line, *number, start) {
positions.push(start);
self.solve(line, clue, depth + 1, start + number + 1, positions);
positions.pop();
}
} else if !line.range_contains_filled(start..line.len()) {
self.positions(positions, clue);
}
}
fn hints(&self, line: &Line, clue: &[usize]) -> Vec<Box<DiscreteRangeHint>> {
/*
println!("filled {:?}", self.filled.ones().collect::<Vec<_>>());
println!("crossed {:?}", self.crossed.ones().collect::<Vec<_>>());
println!(
"cell_numbers {:?}",
self.cell_numbers.ones().collect::<Vec<_>>()
);
*/
let mut hints: Vec<Box<DiscreteRangeHint>> = vec![];
let mut i = 0;
while i < self.filled.len() {
while i < self.filled.len() && !self.filled.contains(i) && !self.crossed.contains(i) {
i += 1;
}
if i >= self.crossed.len() {
break;
}
let start = i;
if self.filled.contains(i) {
while i < line.len() && self.filled.contains(i) {
i += 1;
}
let mut numbers = FixedBitSet::with_capacity(clue.len());
for j in 0..clue.len() {
if self.cell_numbers.contains(start * clue.len() + j) {
numbers.put(j);
}
}
let filled_run = FilledRun {
start,
end: i,
numbers,
};
if filled_run.check(line) {
hints.push(Box::new(DiscreteRangeHint::FilledRun(filled_run)));
}
} else {
while i < line.len() && self.crossed.contains(i) {
i += 1;
}
let crossed_run = CrossedRun { start, end: i };
if crossed_run.check(line) {
hints.push(Box::new(DiscreteRangeHint::CrossedRun(crossed_run)));
}
}
}
//for h in &hints { println!("{:?}", h); }
hints
}
}
#[derive(Debug)]
pub struct DiscreteRangePass;
impl LinePass for DiscreteRangePass {
type Hint = DiscreteRangeHint;
fn run(&self, clue: &[usize], line: &Line) -> Vec<Box<Self::Hint>> {
let mut possibilities = Possibilities::new(line.len(), clue.len());
possibilities.solve(line, clue, 0, 0, &mut vec![]);
possibilities.hints(line, clue)
}
}
#[cfg(test)]
mod tests {
use super::*;
use puzzle::line_grid;
use puzzle::Grid;
use std::iter::FromIterator;
#[test]
fn run1() {
let mut grid = Grid::new(4, 1);
let mut line = grid.horz_mut(0);
line.fill(0);
line.fill(2);
let hints = DiscreteRangePass.run(&[1, 1], &line);
assert_eq!(
hints,
vec![
Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 1,
end: 2,
})),
Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 3,
end: 4,
})),
]
);
}
#[test]
fn run2() {
let mut grid = Grid::new(4, 1);
let mut line = grid.horz_mut(0);
line.fill(2);
let hints = DiscreteRangePass.run(&[2], &line);
assert_eq!(
hints,
vec![Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 0,
end: 1,
}))]
);
}
#[test]
fn run3() {
let mut grid = Grid::new(6, 1);
let mut line = grid.horz_mut(0);
line.fill(0);
line.cross(2);
line.fill(4);
line.cross(5);
let hints = DiscreteRangePass.run(&[1, 2], &line);
assert_eq!(
hints,
vec![
Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 1,
end: 3,
})),
Box::new(DiscreteRangeHint::FilledRun(FilledRun {
start: 3,
end: 5,
numbers: FixedBitSet::from_iter(vec![1]),
})),
]
);
}
#[test]
fn run4() {
let mut grid = Grid::new(4, 1);
let mut line = grid.horz_mut(0);
line.cross(1);
line.fill(2);
line.cross(3);
let hints = DiscreteRangePass.run(&[1], &line);
assert_eq!(
hints,
vec![Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 0,
end: 2,
}))]
);
}
#[test]
fn run5() {
let mut grid = Grid::new(4, 1);
let mut line = grid.horz_mut(0);
line.cross(0);
line.fill(1);
line.cross(2);
let hints = DiscreteRangePass.run(&[1], &line);
assert_eq!(
hints,
vec![Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 2,
end: 4,
}))]
);
}
#[test]
fn run6() {
let mut grid = Grid::new(7, 1);
let mut line = grid.horz_mut(0);
line.fill(1);
line.cross(2);
let hints = DiscreteRangePass.run(&[2, 1], &line);
assert_eq!(
hints,
vec![Box::new(DiscreteRangeHint::FilledRun(FilledRun {
start: 0,
end: 2,
numbers: FixedBitSet::from_iter(vec![0]),
}))]
);
}
#[test]
fn run7() {
let mut grid = Grid::new(7, 1);
let mut line = grid.horz_mut(0);
line.cross(2);
line.fill(3);
line.cross(4);
line.fill_range(5..7);
let hints = DiscreteRangePass.run(&[1, 2], &line);
assert_eq!(
hints,
vec![Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 0,
end: 3,
}))]
);
}
#[test]
fn run8() {
let mut grid = line_grid("xxxx#x###x#####xxx..#...x.....");
let hints = DiscreteRangePass.run(&[1, 3, 5, 1, 2, 2], &grid.horz_mut(0));
assert_eq!(
hints,
vec![Box::new(DiscreteRangeHint::CrossedRun(CrossedRun {
start: 19,
end: 20,
}))]
);
}
}
|
extern crate dotenv;
extern crate json;
extern crate reqwest;
#[macro_use]
extern crate cached;
mod swr3_api;
mod youtube_api;
use dotenv::dotenv;
use std::process::{exit, Command};
use std::thread::sleep;
use std::time::Duration;
/// Maximum time to poll until we eventually give up because we don't get a (new) song.
/// Most likely some kind of refusal/server out of business.
const MAX_WAIT_COUNT: u8 = 20;
fn main() {
// load .env file, containing the YouTube API key
dotenv().ok();
// Keeps a record of the latest song that was enqueued/is playing
let mut playing_song: Option<swr3_api::Swr3Song> = None;
// Remembers how many times SWR3 reported that they still would play the same song.
// This doesn't grow linear over time.
let mut same_song_counter: u8 = 0;
// Holds how long we're waiting in relation to how many times we already
// have been reported back that SWR3 would play the same song.
let mut sleep_duration = get_wait_duration(same_song_counter);
// TODO: Refactor errors to be fatal (in certain circumstances)
loop {
if let Some(song_data) = swr3_api::get_current_played_song() {
// TODO: Can we get rid of this clone here?
if playing_song != Some(song_data.clone()) {
println!("Searching for a remix of {} …", &song_data);
// TODO: Can we get rid of the clone here?
if let Some(video_url) =
youtube_api::get_video_search_result_url(get_yt_search_query(song_data.clone()))
{
enqueue_vlc_playlist(
download_video(video_url).expect("Cannot download video!"),
);
// remember the new song and reset counters
playing_song = Some(song_data);
same_song_counter = 0;
sleep_duration = get_wait_duration(same_song_counter);
}
} else {
same_song_counter += 1;
if same_song_counter > MAX_WAIT_COUNT {
eprintln!(
"Still no new song after waiting {} times, aborting!",
MAX_WAIT_COUNT
);
break;
}
sleep_duration = get_wait_duration(same_song_counter);
println!(
"[{}] Still playing the same song, skipping this iteration. Polling again in {:?} …",
same_song_counter, sleep_duration
);
}
}
sleep(sleep_duration);
}
// We only get here when an fatal error occured, so exit with non-zero error code.
exit(1);
}
/// Returns the duration the program should wait between two tries with the same data.
/// Gets more aggressive the higher the given `try_count` is.
fn get_wait_duration(try_count: u8) -> Duration {
Duration::from_secs(match try_count {
0..=1 => 60,
2..=4 => 30,
_ => 20,
})
}
fn download_video(url: String) -> Option<String> {
println!("Downloading {} …", url);
let ytdl_args = [
"-x",
"--no-playlist",
"--ignore-config",
"--print-json",
"-o",
"downloads/%(id)s.%(acodec)s", // save the file in e.g. `Q4orjhvnkIk.opus`,
// where `Q4orjhvnkIk` is the video id and `opus` is the audio codec of it
&url,
];
let mut youtube_dl = Command::new(if cfg!(windows) {
"cmd.exe"
} else {
"youtube-dl"
});
if cfg!(windows) {
youtube_dl.args(&["/C", "youtube-dl.exe"]);
}
let youtube_dl = youtube_dl
.args(&ytdl_args)
.output()
.expect("Cannot get output of finished child process!");
let buffer =
String::from_utf8(youtube_dl.stdout).expect("Invalid encoding in youtube_dl output!");
let json = json::parse(&buffer).expect("youtube_dl returned no valid json!");
println!(
r#"Downloaded the song "{}", queuing up for playing …"#,
json["title"]
);
Some(format!("downloads/{}.{}", json["id"], json["acodec"]))
}
/// Returns the search query for a given `song`. The returned
/// string should be - when fed into the YouTube search - leading to
/// the best possible remix for a given song.
fn get_yt_search_query(song: swr3_api::Swr3Song) -> String {
format!(
r#"{} "{}" remix"#, // make sure the song title is in the search results
song.artist
.replace(';', "") // removing the semicolon SWR3 is using for separation of the artists increases the quality of the search results
.replace("'", "'"), // TODO: Decode html entities properly, rust support in terms with serde is pretty limited here
song.title
)
}
fn enqueue_vlc_playlist(uri: String) {
println!("Enqueuing {} in vlc!", &uri);
let mut command = Command::new(if cfg!(windows) { "cmd.exe" } else { "vlc" });
if cfg!(windows) {
command.args(&["/C", "vlc.exe"]);
}
command
.args(&["--started-from-file", "--playlist-enqueue"])
.arg(uri);
command.spawn().unwrap();
}
|
//! Expression
use serde::{Deserialize, Serialize};
/// Expression AST
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Expression {
/// Type of AST node
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub r#type: Option<String>,
/// Elements of the dictionary
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub elements: Vec<crate::models::ast::DictItem>,
/// Function parameters
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub params: Vec<crate::models::ast::Property>,
/// Node
#[serde(skip_serializing_if = "Option::is_none")]
pub body: Option<crate::models::ast::Node>,
/// Operator
#[serde(skip_serializing_if = "Option::is_none")]
pub operator: Option<String>,
/// Left leaf
#[serde(skip_serializing_if = "Option::is_none")]
pub left: Option<Box<crate::models::ast::Expression>>,
/// Right leaf
#[serde(skip_serializing_if = "Option::is_none")]
pub right: Option<Box<crate::models::ast::Expression>>,
/// Parent Expression
#[serde(skip_serializing_if = "Option::is_none")]
pub callee: Option<Box<crate::models::ast::Expression>>,
/// Function arguments
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub arguments: Vec<crate::models::ast::Expression>,
/// Test Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub test: Option<Box<crate::models::ast::Expression>>,
/// Alternate Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub alternate: Option<Box<crate::models::ast::Expression>>,
/// Consequent Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub consequent: Option<Box<crate::models::ast::Expression>>,
/// Object Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub object: Option<Box<crate::models::ast::Expression>>,
/// PropertyKey Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub property: Option<Box<crate::models::ast::PropertyKey>>,
/// Array Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub array: Option<Box<crate::models::ast::Expression>>,
/// Index Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub index: Option<Box<crate::models::ast::Expression>>,
/// Properties
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub properties: Vec<crate::models::ast::Property>,
/// Expression
#[serde(skip_serializing_if = "Option::is_none")]
pub expression: Option<Box<crate::models::ast::Expression>>,
/// Argument
#[serde(skip_serializing_if = "Option::is_none")]
pub argument: Option<Box<crate::models::ast::Expression>>,
/// Call Expr
#[serde(skip_serializing_if = "Option::is_none")]
pub call: Option<crate::models::ast::CallExpression>,
/// Expression Value
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
/// Duration values
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<crate::models::ast::Duration>,
/// Expression Name
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl Expression {
/// Return instance of expression
pub fn new() -> Self {
Self::default()
}
}
|
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
#[derive(PartialEq)]
enum SwitchType
{
TurnOn,
TurnOff,
Toggle,
}
const TOGGLE_STR: &'static str = "toggle";
const TURN_ON_STR: &'static str = "turn on";
const TURN_OFF_STR: &'static str = "turn off";
fn parse(in_string:&str, out_type: &mut SwitchType, start_x: &mut u32, start_y: &mut u32, end_x: &mut u32, end_y: &mut u32)
{
let mut start_str_length = 0;
if in_string.starts_with(TOGGLE_STR)
{
*out_type = SwitchType::Toggle;
start_str_length = TOGGLE_STR.len() + 1;
}
else if in_string.starts_with(TURN_ON_STR)
{
*out_type = SwitchType::TurnOn;
start_str_length = TURN_ON_STR.len() + 1;
}
else if in_string.starts_with(TURN_OFF_STR)
{
*out_type = SwitchType::TurnOff;
start_str_length = TURN_OFF_STR.len() + 1;
}
let start_end_str = &in_string[start_str_length..];
let tokens:Vec<&str> = start_end_str.split_whitespace().collect();
let start_pair:Vec<&str> = tokens[0].split(',').collect();
let end_pair:Vec<&str> = tokens[2].split(',').collect();
*start_x = start_pair[0].trim().parse().ok().expect("Start X");
*start_y = start_pair[1].trim().parse().ok().expect("Start Y");
*end_x = end_pair[0].trim().parse().ok().expect("End X");
*end_y = end_pair[1].trim().parse().ok().expect("End Y");
}
#[cfg(test)]
fn test_parse(in_string:&str, expected_type:&SwitchType, start_x:u32, start_y:u32, end_x:u32, end_y:u32) -> bool
{
let mut out_type = SwitchType::Toggle;
let mut out_start_x: u32 = 0;
let mut out_start_y: u32 = 0;
let mut out_end_x: u32 = 0;
let mut out_end_y: u32 = 0;
parse(&in_string, &mut out_type, &mut out_start_x, &mut out_start_y, &mut out_end_x, &mut out_end_y);
let correct = out_type == *expected_type && start_x == out_start_x && out_start_y == start_y && out_end_x == end_x && out_end_y == end_y;
println!("{}: correct: {}", in_string, correct);
correct
}
#[test]
fn run_string_parse_tests()
{
assert_eq!(test_parse("turn on 489,959 through 759,964", &SwitchType::TurnOn, 489, 959, 759, 964), true);
assert_eq!(test_parse("turn off 820,516 through 871,914", &SwitchType::TurnOff, 820, 516, 871, 914), true);
assert_eq!(test_parse("toggle 756,965 through 812,992", &SwitchType::Toggle, 756, 965, 812, 992), true);
}
fn main()
{
let mut lights = [[false; 1000]; 1000];
let mut light_map: Vec< Vec<u32> > = Vec::new();;
let mut start_x: u32 = 0;
let mut end_x: u32 = 0;
let mut start_y: u32 = 0;
let mut end_y: u32 = 0;
let mut out_type:SwitchType = SwitchType::Toggle;
for i in 0..1000
{
let mut vec: Vec<u32> = Vec::new();
for j in 0.. 1000
{
vec.push(0);
}
light_map.push(vec);
}
let f = File::open("day6input.txt").unwrap();
let reader = BufReader::new(f);
// Iterate over lines
for line in reader.lines()
{
let unwrapped_line = line.unwrap();
parse(&unwrapped_line, &mut out_type, &mut start_x, &mut start_y, &mut end_x, &mut end_y);
for i in start_y .. end_y + 1
{
for j in start_x .. end_x + 1
{
let r = i as usize;
let c = j as usize;
let value = lights[r][c];
let brightness = light_map[r][c];
if out_type == SwitchType::TurnOn
{
lights[r][c] = true;
light_map[r][c] += 1;
}
else if out_type == SwitchType::TurnOff
{
lights[r][c] = false;
if brightness > 0
{
light_map[r][c] -= 1;
}
}
else if out_type == SwitchType::Toggle
{
lights[r][c] = !value;
light_map[r][c] += 2;
}
}
}
}
let mut light_count = 0;
let mut total_brightness = 0;
for i in 0 .. 1000
{
for j in 0 .. 1000
{
if lights[i][j]
{
light_count += 1;
}
total_brightness += light_map[i][j];
}
}
println!("Part 1 - Light Count: {}", light_count);
println!("Part 2 - Total Brightness: {}", total_brightness);
}
|
fn main() {
let mut v = Vec::new();
v.push(1);
push(&mut v);
read(&v);
}
fn push(v: &mut Vec<i32>) {
v.push(2);
v.push(3);
}
fn read(v: &Vec<i32>) {
for x in v {
println!("{}", x);
}
} |
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
pub type VkPhysicalDeviceMemoryProperties2 = VkPhysicalDeviceMemoryProperties2KHR;
#[repr(C)]
#[derive(Debug)]
pub struct VkPhysicalDeviceMemoryProperties2KHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub memoryProperties: VkPhysicalDeviceMemoryProperties,
}
impl VkPhysicalDeviceMemoryProperties2KHR {
pub fn new(memory_properties: VkPhysicalDeviceMemoryProperties) -> Self {
VkPhysicalDeviceMemoryProperties2KHR {
sType: VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR,
pNext: ptr::null(),
memoryProperties: memory_properties,
}
}
}
impl Default for VkPhysicalDeviceMemoryProperties2KHR {
fn default() -> Self {
Self::new(VkPhysicalDeviceMemoryProperties::default())
}
}
impl PNext<VkPhysicalDeviceMemoryBudgetPropertiesEXT> for VkPhysicalDeviceMemoryProperties2KHR {
fn chain(&mut self, p_next: &VkPhysicalDeviceMemoryBudgetPropertiesEXT) {
self.pNext = p_next as *const VkPhysicalDeviceMemoryBudgetPropertiesEXT as *const c_void;
}
}
|
use super::VarResult;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::{
move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_f64, pine_ref_to_i64,
pine_ref_to_string,
};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::types::{Callable, Float, Int, PineFrom, PineRef, RuntimeErr, Series, SeriesCall, NA};
use std::cmp;
use std::mem::transmute;
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq)]
struct MinMaxCallVal {
int_func: *mut (),
float_func: *mut (),
}
impl MinMaxCallVal {
pub fn new(int_func: *mut (), float_func: *mut ()) -> MinMaxCallVal {
MinMaxCallVal {
int_func,
float_func,
}
}
}
impl<'a> SeriesCall<'a> for MinMaxCallVal {
fn step(
&mut self,
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
move_tuplet!((x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) = param);
let input_vals = vec![x1, x2, x3, x4, x5, x6, x7, x8, x9, x10];
let int_func =
unsafe { transmute::<_, fn(Vec<Option<PineRef<'a>>>) -> Int>(self.int_func) };
let float_func =
unsafe { transmute::<_, fn(Vec<Option<PineRef<'a>>>) -> Float>(self.float_func) };
match func_type.get_type(0).unwrap() {
SyntaxType::Simple(SimpleSyntaxType::Int) => {
let res = int_func(input_vals);
Ok(PineRef::new_box(res))
}
SyntaxType::Series(SimpleSyntaxType::Int) => {
let res = int_func(input_vals);
Ok(PineRef::new_rc(Series::from(res)))
}
SyntaxType::Simple(SimpleSyntaxType::Float) => {
let res = float_func(input_vals);
Ok(PineRef::new_box(res))
}
SyntaxType::Series(SimpleSyntaxType::Float) => {
let res = float_func(input_vals);
Ok(PineRef::new_rc(Series::from(res)))
}
_ => unreachable!(),
}
}
fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> {
Box::new(self.clone())
}
}
pub fn declare_minmax_var<'a>(
name: &'static str,
int_func: fn(Vec<Option<PineRef<'a>>>) -> Int,
float_func: fn(Vec<Option<PineRef<'a>>>) -> Float,
) -> VarResult<'a> {
let value = PineRef::new(Callable::new(
None,
Some(Box::new(MinMaxCallVal::new(
int_func as *mut (),
float_func as *mut (),
))),
));
let func_type = FunctionTypes(vec![
FunctionType::new((
vec![
("x1", SyntaxType::int()),
("x2", SyntaxType::int()),
("x3", SyntaxType::int()),
("x4", SyntaxType::int()),
("x5", SyntaxType::int()),
("x6", SyntaxType::int()),
("x7", SyntaxType::int()),
("x8", SyntaxType::int()),
("x9", SyntaxType::int()),
("x10", SyntaxType::int()),
],
SyntaxType::int(),
)),
FunctionType::new((
vec![
("x1", SyntaxType::float()),
("x2", SyntaxType::float()),
("x3", SyntaxType::float()),
("x4", SyntaxType::float()),
("x5", SyntaxType::float()),
("x6", SyntaxType::float()),
("x7", SyntaxType::float()),
("x8", SyntaxType::float()),
("x9", SyntaxType::float()),
("x10", SyntaxType::float()),
],
SyntaxType::float(),
)),
FunctionType::new((
vec![
("x1", SyntaxType::int_series()),
("x2", SyntaxType::int_series()),
("x3", SyntaxType::int_series()),
("x4", SyntaxType::int_series()),
("x5", SyntaxType::int_series()),
("x6", SyntaxType::int_series()),
("x7", SyntaxType::int_series()),
("x8", SyntaxType::int_series()),
("x9", SyntaxType::int_series()),
("x10", SyntaxType::int_series()),
],
SyntaxType::int_series(),
)),
FunctionType::new((
vec![
("x1", SyntaxType::float_series()),
("x2", SyntaxType::float_series()),
("x3", SyntaxType::float_series()),
("x4", SyntaxType::float_series()),
("x5", SyntaxType::float_series()),
("x6", SyntaxType::float_series()),
("x7", SyntaxType::float_series()),
("x8", SyntaxType::float_series()),
("x9", SyntaxType::float_series()),
("x10", SyntaxType::float_series()),
],
SyntaxType::float_series(),
)),
]);
let syntax_type = SyntaxType::Function(Rc::new(func_type));
VarResult::new(value, syntax_type, name)
}
fn int_max<'a>(vals: Vec<Option<PineRef<'a>>>) -> Int {
vals.into_iter().filter_map(|v| pine_ref_to_i64(v)).max()
}
fn float_max<'a>(vals: Vec<Option<PineRef<'a>>>) -> Float {
vals.into_iter()
.filter_map(|v| pine_ref_to_f64(v))
.max_by(|x1, x2| x1.partial_cmp(x2).unwrap_or(cmp::Ordering::Equal))
}
pub fn declare_max_var<'a>() -> VarResult<'a> {
declare_minmax_var("max", int_max, float_max)
}
fn int_min<'a>(vals: Vec<Option<PineRef<'a>>>) -> Int {
vals.into_iter().filter_map(|v| pine_ref_to_i64(v)).min()
}
fn float_min<'a>(vals: Vec<Option<PineRef<'a>>>) -> Float {
vals.into_iter()
.filter_map(|v| pine_ref_to_f64(v))
.min_by(|x1, x2| x1.partial_cmp(x2).unwrap_or(cmp::Ordering::Equal))
}
pub fn declare_min_var<'a>() -> VarResult<'a> {
declare_minmax_var("min", int_min, float_min)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::SimpleSyntaxType;
use crate::runtime::{AnySeries, NoneCallback, VarOperate};
use crate::{LibInfo, PineParser, PineRunner};
#[test]
fn na_test() {
let lib_info = LibInfo::new(
vec![declare_max_var(), declare_min_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "
m1 = max(1, 2, 3, 4, 5)
m2 = max(close, close + 1, close + 2)
m3 = min(1, 2, 3, 4, 5)
m4 = min(close, close + 1, close + 2)
";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![("close", AnySeries::from_float_vec(vec![Some(2f64)]))],
None,
)
.unwrap();
assert_eq!(
runner.get_context().move_var(VarIndex::new(0, 0)),
Some(PineRef::new_box(Some(5i64)))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(1, 0)),
Some(PineRef::new_rc(Series::from_vec(vec![Some(4f64)])))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(2, 0)),
Some(PineRef::new_box(Some(1i64)))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(3, 0)),
Some(PineRef::new_rc(Series::from_vec(vec![Some(2f64)])))
);
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::models::Intent,
maplit::{hashmap, hashset},
serde_derive::{Deserialize, Serialize},
std::{
collections::{HashMap, HashSet},
time::{SystemTime, UNIX_EPOCH},
},
};
type EntityReference = String;
type EntityType = String;
type ModuleId = String;
type OutputName = String;
#[cfg(test)]
type StoryId = String;
#[cfg(test)]
pub struct SessionGraph {
stories: HashMap<StoryId, StoryGraph>,
}
#[cfg(test)]
impl SessionGraph {
/// Creates a new empty session graph.
pub fn new() -> Self {
SessionGraph { stories: hashmap!() }
}
/// Creates a new story entry in the graph.
pub fn new_story(&mut self, story_id: impl Into<String>) {
self.stories.insert(story_id.into(), StoryGraph::new());
}
/// Returns the story graph for the given |story_id|.
pub fn get_story_graph(&self, story_id: &str) -> Option<&StoryGraph> {
self.stories.get(story_id)
}
/// Returns the mutable story graph for the given |story_id|.
pub fn get_story_graph_mut(&mut self, story_id: &str) -> Option<&mut StoryGraph> {
self.stories.get_mut(story_id)
}
}
#[derive(Clone, Deserialize, Serialize)]
pub struct StoryGraph {
modules: HashMap<ModuleId, ModuleData>,
}
impl StoryGraph {
/// Creates a new empty story graph.
pub fn new() -> Self {
StoryGraph { modules: hashmap!() }
}
/// Adds a module with the given initial intent to the graph.
pub fn add_module(&mut self, module_id: impl Into<String>, intent: Intent) {
let module_id_str = module_id.into();
self.modules.insert(module_id_str.clone(), ModuleData::new(intent));
}
/// Returns the module data associated to the given |module_id|.
pub fn get_module_data(&self, module_id: &str) -> Option<&ModuleData> {
self.modules.get(module_id)
}
/// Returns the mutable module data associated to the given |module_id|.
pub fn get_module_data_mut(&mut self, module_id: &str) -> Option<&mut ModuleData> {
self.modules.get_mut(module_id)
}
/// Returns an iterator of all modules in it.
pub fn get_all_modules(&self) -> impl Iterator<Item = (&ModuleId, &ModuleData)> {
self.modules.iter()
}
/// Retures the number of modules in this story.
#[cfg(test)]
pub fn get_module_count(&self) -> usize {
self.modules.len()
}
}
/// Holds both module_id and corresponding module_data.
pub struct Module {
pub module_id: String,
pub module_data: ModuleData,
}
impl Module {
pub fn new(module_id: impl Into<String>, module_data: ModuleData) -> Self {
Module { module_id: module_id.into(), module_data }
}
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ModuleData {
pub outputs: HashMap<OutputName, ModuleOutput>,
children: HashSet<ModuleId>,
pub last_intent: Intent,
created_timestamp: u128,
last_modified_timestamp: u128,
}
impl ModuleData {
/// Creates a new empty module data with the given |intent| as the intial one.
pub fn new(intent: Intent) -> Self {
let timestamp =
SystemTime::now().duration_since(UNIX_EPOCH).expect("time went backwards").as_nanos();
ModuleData {
children: hashset!(),
outputs: hashmap!(),
last_intent: intent,
created_timestamp: timestamp,
last_modified_timestamp: timestamp,
}
}
/// Updates an output with the given reference. If no reference is given, the
/// output is removed.
pub fn update_output(&mut self, output_name: &str, new_reference: Option<String>) {
match new_reference {
Some(reference) => {
let output = self
.outputs
.entry(output_name.to_string())
.or_insert(ModuleOutput::new(reference.clone()));
output.update_reference(reference);
}
None => {
self.outputs.remove(output_name);
}
}
self.update_timestamp();
}
/// Add new consumer for an output.
pub fn add_output_consumer(
&mut self,
output_name: impl Into<String>,
reference: impl Into<String>,
module_id: impl Into<String>,
entity_type: impl Into<String>,
) {
let output =
self.outputs.entry(output_name.into()).or_insert(ModuleOutput::new(reference.into()));
output.add_consumer(module_id, entity_type);
self.update_timestamp();
}
/// Updates the last intent issued to the module with |new_intent|.
pub fn update_intent(&mut self, new_intent: Intent) {
self.last_intent = new_intent;
self.update_timestamp();
}
/// Links two mods through intents. This means this module issued an intent to
/// the module with id |child_module_id|.
pub fn add_child(&mut self, child_module_id: impl Into<String>) {
self.children.insert(child_module_id.into());
self.update_timestamp();
}
#[cfg(test)]
/// Unlinks two mods through linked through intent issuing.
pub fn remove_child(&mut self, child_module_id: &str) {
self.children.remove(child_module_id);
self.update_timestamp();
}
fn update_timestamp(&mut self) {
self.last_modified_timestamp =
SystemTime::now().duration_since(UNIX_EPOCH).expect("time went backwards").as_nanos();
}
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ModuleOutput {
pub entity_reference: EntityReference,
pub consumers: HashSet<(ModuleId, EntityType)>,
}
impl ModuleOutput {
fn new(entity_reference: impl Into<String>) -> Self {
ModuleOutput { entity_reference: entity_reference.into(), consumers: hashset!() }
}
/// Links the mod outputing this output to the given mod with id |module_id|.
pub fn add_consumer(&mut self, module_id: impl Into<String>, entity_type: impl Into<String>) {
self.consumers.insert((module_id.into(), entity_type.into()));
}
/// Unlinks the mod outputing this output and the mod with id |module_id|.
#[cfg(test)]
pub fn remove_consumer(&mut self, module_id: &str) {
self.consumers.retain(|(m, _)| m != module_id);
}
fn update_reference(&mut self, new_reference: impl Into<String>) {
self.entity_reference = new_reference.into();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn session_graph() {
let mut session_graph = SessionGraph::new();
assert!(session_graph.stories.is_empty());
assert!(session_graph.get_story_graph("story_x").is_none());
assert!(session_graph.get_story_graph_mut("story_x").is_none());
assert_eq!(session_graph.stories.len(), 0);
session_graph.new_story("story_x");
assert!(session_graph.get_story_graph("story_x").is_some());
assert!(session_graph.get_story_graph_mut("story_x").is_some());
assert_eq!(session_graph.stories.len(), 1);
}
#[test]
fn story_graph() {
let mut story_graph = StoryGraph::new();
assert!(story_graph.modules.is_empty());
let intent = Intent::new().with_action("SOME_ACTION");
story_graph.add_module("mod-id", intent.clone());
assert_eq!(story_graph.get_module_count(), 1);
assert!(story_graph.modules.contains_key("mod-id"));
assert!(story_graph.get_module_data_mut("mod-id").is_some());
let module_data = story_graph.get_module_data("mod-id").unwrap();
assert_eq!(module_data.last_intent, intent);
}
#[test]
fn module_data() {
let intent = Intent::new().with_action("SOME_ACTION");
let mut module_data = ModuleData::new(intent.clone());
assert_eq!(module_data.last_intent, intent);
assert_eq!(module_data.created_timestamp, module_data.last_modified_timestamp);
assert!(module_data.children.is_empty());
assert!(module_data.outputs.is_empty());
let created_timestamp = module_data.created_timestamp;
let mut timestamps = vec![module_data.last_modified_timestamp];
// Verify intents
let new_intent = Intent::new().with_action("SOME_OTHER_ACTION");
module_data.update_intent(new_intent.clone());
assert_eq!(module_data.last_intent, new_intent);
timestamps.push(module_data.last_modified_timestamp);
// Verify children
module_data.add_child("other-mod");
assert!(module_data.children.contains("other-mod"));
timestamps.push(module_data.last_modified_timestamp);
module_data.remove_child("other-mod");
assert!(module_data.children.is_empty());
timestamps.push(module_data.last_modified_timestamp);
// Verify outputs
module_data.update_output("some-output", Some("some-ref".to_string()));
let output = module_data.outputs.get("some-output").unwrap();
assert_eq!(output.entity_reference, "some-ref");
assert!(output.consumers.is_empty());
timestamps.push(module_data.last_modified_timestamp);
module_data.add_output_consumer("some-output", "some-ref", "some_consumer_id", "some_type");
let new_output = module_data.outputs.get("some-output").unwrap();
assert!(!new_output.consumers.is_empty());
timestamps.push(module_data.last_modified_timestamp);
module_data.update_output("some-output", None);
assert!(module_data.outputs.is_empty());
timestamps.push(module_data.last_modified_timestamp);
// Verify all timestamp changes are incremental and created timestamp wasn't updated.
for i in 1..timestamps.len() {
assert!(timestamps[i] > timestamps[i - 1]);
}
assert_eq!(module_data.created_timestamp, created_timestamp);
}
#[test]
fn module_output() {
let mut module_output = ModuleOutput::new("some-ref");
assert!(module_output.consumers.is_empty());
assert_eq!(module_output.entity_reference, "some-ref");
module_output.add_consumer("some-consumer", "some-type");
module_output.add_consumer("other-consumer", "some-type");
assert_eq!(
module_output.consumers,
hashset!(
("some-consumer".to_string(), "some-type".to_string()),
("other-consumer".to_string(), "some-type".to_string())
)
);
module_output.remove_consumer("some-consumer");
assert_eq!(
module_output.consumers,
hashset!(("other-consumer".to_string(), "some-type".to_string()))
);
}
}
|
//! Utilities for use while developing dynamic libraries.
use std::{
io,
path::{Path, PathBuf},
};
use crate::library::RootModule;
/// Returns the path in the target directory
/// to the last version of an implementation crate's dynamic library.
///
/// The path can be in either the "debug" or "release" subdirectories.
pub fn compute_library_path<M: RootModule>(target_path: &Path) -> io::Result<PathBuf> {
let debug_dir = target_path.join("debug/");
let release_dir = target_path.join("release/");
let debug_path = M::get_library_path(&debug_dir);
let release_path = M::get_library_path(&release_dir);
Ok(match (debug_path.exists(), release_path.exists()) {
(false, false) => debug_dir,
(true, false) => debug_dir,
(false, true) => release_dir,
(true, true) => {
if debug_path.metadata()?.modified()? < release_path.metadata()?.modified()? {
release_dir
} else {
debug_dir
}
}
})
}
|
// todo:
// https://mathematica.stackexchange.com/questions/80291/efficient-way-to-sum-all-the-primes-below-n-million-in-mathematica
// S(v,p)=S(v,p-1)-p\times(S(\left\lfloor\frac{v}{p}\right\rfloor,p-1)-S(p-1,p-1))
use crate::{
error::Error::{Undefined, Unimplemented},
Result,
};
use itertools::Itertools;
use num::{integer::Roots, BigInt, Signed, ToPrimitive};
use std::{collections::BTreeMap, str::FromStr};
#[rustfmt::skip]
pub fn prime_sum_u64(n: u64) -> u64 {
let r = n.sqrt() as u64;
assert!(r * r <= n && (r + 1).pow(2) > n);
let mut v = (1..=r).map(|i| n / i).collect_vec();
v.extend((0..*v.last().unwrap()).rev());
let mut s: BTreeMap<u64, u64> = v.iter().copied().map(|i| (i, ((i + 1) * i / 2).wrapping_sub(1))).collect();
for p in 2..=r {
if s[&p] > s[&(p - 1)] {
// p is prime
let (sp, p2) = (s[&(p - 1)], p * p);
for &ve in &v {
if ve < p2 { break; }
*s.get_mut(&ve).unwrap() -= p * (s[&(ve / p)] - sp);
}
}
}
return s[&n];
}
// https://oeis.org/A046731
// ```wl
// data=Import["https://oeis.org/A046731/b046731.txt","Table"]
// T="table.insert(BigInt::from_str(\"``\").unwrap(),BigInt::from_str(\"``\").unwrap());\n"
// StringJoin[TemplateApply[T,{10^#1,#2}]&@@@data]//CopyToClipboard
// ```
#[rustfmt::skip]
fn prime_sum_table() -> BTreeMap<BigInt, BigInt> {
let mut table = BTreeMap::new();
table.insert(BigInt::from_str("1").unwrap(), BigInt::from_str("0").unwrap());
table.insert(BigInt::from_str("10").unwrap(), BigInt::from_str("17").unwrap());
table.insert(BigInt::from_str("100").unwrap(), BigInt::from_str("1060").unwrap());
table.insert(BigInt::from_str("1000").unwrap(), BigInt::from_str("76127").unwrap());
table.insert(BigInt::from_str("10000").unwrap(), BigInt::from_str("5736396").unwrap());
table.insert(BigInt::from_str("100000").unwrap(), BigInt::from_str("454396537").unwrap());
table.insert(BigInt::from_str("1000000").unwrap(), BigInt::from_str("37550402023").unwrap());
table.insert(BigInt::from_str("10000000").unwrap(), BigInt::from_str("3203324994356").unwrap());
table.insert(BigInt::from_str("100000000").unwrap(), BigInt::from_str("279209790387276").unwrap());
table.insert(BigInt::from_str("1000000000").unwrap(), BigInt::from_str("24739512092254535").unwrap());
table.insert(BigInt::from_str("10000000000").unwrap(), BigInt::from_str("2220822432581729238").unwrap());
// u128
table.insert(BigInt::from_str("100000000000").unwrap(), BigInt::from_str("201467077743744681014").unwrap());
table.insert(BigInt::from_str("1000000000000").unwrap(), BigInt::from_str("18435588552550705911377").unwrap());
table.insert(BigInt::from_str("10000000000000").unwrap(), BigInt::from_str("1699246443377779418889494").unwrap());
table.insert(BigInt::from_str("100000000000000").unwrap(), BigInt::from_str("157589260710736940541561021").unwrap());
table.insert(BigInt::from_str("1000000000000000").unwrap(), BigInt::from_str("14692398516908006398225702366").unwrap());
table.insert(BigInt::from_str("10000000000000000").unwrap(), BigInt::from_str("1376110854313351899159632866552").unwrap());
table.insert(BigInt::from_str("100000000000000000").unwrap(), BigInt::from_str("129408626276669278966252031311350").unwrap());
table.insert(BigInt::from_str("1000000000000000000").unwrap(), BigInt::from_str("12212914292949226570880576733896687").unwrap());
table.insert(BigInt::from_str("10000000000000000000").unwrap(), BigInt::from_str("1156251260549368082781614413945980126").unwrap());
table.insert(BigInt::from_str("100000000000000000000").unwrap(), BigInt::from_str("109778913483063648128485839045703833541").unwrap());
table.insert(BigInt::from_str("1000000000000000000000").unwrap(), BigInt::from_str("10449550362130704786220283253063405651965").unwrap());
table.insert(BigInt::from_str("10000000000000000000000").unwrap(), BigInt::from_str("996973504763259668279213971353794878368213").unwrap());
table.insert(BigInt::from_str("100000000000000000000000").unwrap(), BigInt::from_str("95320530117168404458544684912403185555509650").unwrap());
table.insert(BigInt::from_str("1000000000000000000000000").unwrap(), BigInt::from_str("9131187511156941634384410084928380134453142199").unwrap());
table.insert(BigInt::from_str("10000000000000000000000000").unwrap(), BigInt::from_str("876268031750623105684911815303505535704119354853").unwrap());
return table;
}
pub fn prime_sum_i(n: &BigInt) -> Result<BigInt> {
if let Some(s) = prime_sum_table().get(&n) {
return Ok(s.clone());
};
if n.is_negative() {
return Err(Undefined(String::from("wrong def")));
}
return match n.to_u64() {
None => Err(Unimplemented),
Some(s) => Ok(BigInt::from(prime_sum_u64(s))),
};
}
#[test]
fn test_prime_sum() {
assert_eq!(format!("{}", prime_sum_u64(1)), "0");
assert_eq!(format!("{}", prime_sum_u64(2)), "2");
assert_eq!(format!("{}", prime_sum_u64(3)), "5");
assert_eq!(format!("{}", prime_sum_u64(4)), "5");
assert_eq!(format!("{}", prime_sum_u64(5)), "10");
assert_eq!(format!("{}", prime_sum_u64(6)), "10");
assert_eq!(format!("{}", prime_sum_u64(7)), "17");
assert_eq!(format!("{}", prime_sum_u64(8)), "17");
assert_eq!(format!("{}", prime_sum_u64(9)), "17");
assert_eq!(format!("{}", prime_sum_u64(10)), "17");
assert_eq!(format!("{}", prime_sum_u64(11)), "28");
assert_eq!(format!("{}", prime_sum_u64(100)), "1060");
assert_eq!(format!("{}", prime_sum_u64(1000)), "76127");
assert_eq!(format!("{}", prime_sum_u64(10000)), "5736396");
}
|
mod line;
mod machine;
mod parse;
mod smtp;
mod fuse;
mod peer;
mod mail;
pub use self::mail::*;
pub use self::peer::*;
pub use self::fuse::*;
pub use self::line::*;
pub use self::parse::*;
pub use self::smtp::*;
pub use self::machine::*;
#[cfg(test)]
mod tests {
//use env_logger;
use bytes::{Bytes, BytesMut};
use model::command::SmtpCommand::*;
use model::controll::{ClientControll, ServerControll::*};
use protocol::SmtpCodec;
use tokio_codec::Encoder;
#[test]
fn decode_takes_first_line() {
let mut sut = SmtpCodec::new();
let mut buf = b(b"helo there\r\nquit\r\n").into();
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Command(Unknown("helo there\r\n".into())));
assert_eq!(buf.len(), 6); // only quit\r\n is left
}
#[test]
fn decode_checks_sanity() {
let mut sut = SmtpCodec::new();
let mut buf = b(b"he\r\n").into();
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Invalid(b(b"he\r\n")));
assert_eq!(buf.len(), 0);
}
#[test]
fn decode_recovers_from_errors() {
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::from(b(b"!@#\r\nquit\r\n"));
let _ = sut.decode_either(&mut buf).unwrap().unwrap();
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Command(Unknown("quit\r\n".into())));
assert_eq!(buf.len(), 0);
}
#[test]
fn decode_takes_second_line() {
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::from(b(b"helo there\r\nquit\r\n"));
sut.decode_either(&mut buf).expect("ok");
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Command(Unknown("quit\r\n".into())));
assert_eq!(buf.len(), 0);
}
#[test]
fn decode_handles_empty_data_buffer() {
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::from(b(b"data\r\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Command(Unknown("data\r\n".into())));
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
assert_eq!(buf.len(), 0);
}
#[test]
fn decode_finds_data_dot() {
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::new();
sut.encode(ClientControll::AcceptData, &mut buf).unwrap();
buf.extend(b(b"daaataaa\r\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, DataChunk(b(b"daaataaa")));
buf.extend(b(b".\r\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, FinalDot(b(b"\r\n.\r\n")));
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
assert_eq!(buf.len(), 0);
}
#[test]
fn decode_finds_data_dot_after_empty_data() {
//env_logger::init();
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::new();
sut.encode(ClientControll::AcceptData, &mut buf).unwrap();
buf.extend(b(b".\r\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, FinalDot(b(b".\r\n")));
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
assert_eq!(buf.len(), 0);
}
#[test]
fn decode_handles_dangling_data() {
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::from(b(b"helo "));
let result = sut.decode_either(&mut buf).unwrap();
assert!(result.is_none());
buf.extend(b(b"there\r\nxx"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Command(Unknown("helo there\r\n".into())));
assert_eq!(buf.len(), 2);
}
#[test]
fn decode_handles_data_command() {
//env_logger::init();
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::from(b(b"data\r\nxxxx\r\n.\r\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, Command(Unknown("data\r\n".into())));
sut.encode(ClientControll::AcceptData, &mut buf).unwrap();
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, DataChunk(b(b"xxxx")));
assert_eq!(buf.len(), 5); // the dot is still in there
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, FinalDot(b(b"\r\n.\r\n")));
assert_eq!(buf.len(), 0); // the dot is gone
}
#[test]
fn decode_handles_trickle() {
//env_logger::init();
let mut sut = SmtpCodec::new();
let mut buf = BytesMut::new();
sut.encode(ClientControll::AcceptData, &mut buf).unwrap();
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
buf.extend(b(b"\r"));
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
buf.extend(b(b"\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, DataChunk(b(b"\r\n")));
buf.extend(b(b"."));
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
buf.extend(b(b"\r"));
let result = sut.decode_either(&mut buf).unwrap();
assert_eq!(result, None);
buf.extend(b(b"\n"));
let result = sut.decode_either(&mut buf).unwrap().unwrap();
assert_eq!(result, FinalDot(b(b".\r\n")));
}
fn b(bytes: &[u8]) -> Bytes {
Bytes::from(&bytes[..])
}
}
|
use native_windows_gui as nwg;
use native_windows_derive as nwd;
use nwd::{NwgUi, NwgPartial};
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct ConfigDlg {
#[nwg_control(size: (500, 400), position: (300, 300), title: "DynLayout")]
#[nwg_events(OnInit: [ConfigDlg::init], OnResize: [ConfigDlg::size], OnWindowClose: [ConfigDlg::exit])]
window: nwg::Window,
#[nwg_layout(parent: window)]
layout: nwg::DynLayout,
#[nwg_control(position: (10, 30), size: (220, 330), collection: vec!["People"])]
list: nwg::ListBox<&'static str>,
#[nwg_control(text: "Cancel", position: (10, 350), size: (100, 25))]
cancel_btn: nwg::Button,
#[nwg_control(text: "Ok", position: (120, 350), size: (100, 25))]
ok_btn: nwg::Button,
#[nwg_control(text: "Config", position: (380, 350), size: (100, 25))]
config_btn: nwg::Button,
#[nwg_control(position: (240, 30), size: (240, 300))]
frame: nwg::Frame,
#[nwg_partial(parent: frame)]
#[nwg_events((save_btn, OnButtonClick): [ConfigDlg::save])]
controls: Controls,
}
impl ConfigDlg {
fn init(&self) {
self.frame.set_visible(true);
self.layout.add_child((0, 0), (50, 100), &self.list);
self.layout.add_child((0, 100), (0, 0), &self.ok_btn);
self.layout.add_child((0, 100), (0, 0), &self.cancel_btn);
self.layout.add_child((100, 100), (0, 0), &self.config_btn);
self.layout.add_child((50, 0), (50, 100), &self.frame);
self.controls.init(&self.frame);
self.layout.fit();
}
fn size(&self) {
self.layout.fit();
}
fn save(&self) {
nwg::simple_message("Saved!", "Data saved!");
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
#[derive(Default, NwgPartial)]
pub struct Controls {
#[nwg_layout]
layout: nwg::DynLayout,
#[nwg_control(text: "Name:", h_align: HTextAlign::Right, position: (10, 10), size: (100, 20))]
label1: nwg::Label,
#[nwg_control(text: "Age:", h_align: HTextAlign::Right, position: (10, 40), size: (100, 20))]
label2: nwg::Label,
#[nwg_control(text: "Job:", h_align: HTextAlign::Right, position: (10, 70), size: (100, 20))]
label3: nwg::Label,
#[nwg_control(text: "John Doe", position: (120, 10), size: (100, 20))]
#[nwg_events(OnChar: [print_char(EVT_DATA)])]
name_input: nwg::TextInput,
#[nwg_control(text: "75", flags: "NUMBER|VISIBLE", position: (120, 40), size: (100, 20))]
age_input: nwg::TextInput,
#[nwg_control(text: "Programmer", position: (120, 70), size: (100, 25))]
job_input: nwg::TextInput,
#[nwg_control(text: "Save", position: (10, 250), size: (100, 25))]
save_btn: nwg::Button,
}
impl Controls {
fn init(&self, frame: &nwg::Frame) {
self.layout.parent(frame);
self.layout.add_child((0, 0), (0, 0), &self.label1);
self.layout.add_child((0, 0), (0, 0), &self.label2);
self.layout.add_child((0, 0), (0, 0), &self.label3);
self.layout.add_child((0, 0), (100, 0), &self.name_input);
self.layout.add_child((0, 0), (100, 0), &self.age_input);
self.layout.add_child((0, 0), (100, 0), &self.job_input);
self.layout.add_child((0, 100), (0, 0), &self.save_btn);
}
}
fn print_char(data: &nwg::EventData) {
println!("{:?}", data.on_char());
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
//nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let mut font = nwg::Font::default();
nwg::Font::builder()
.family("MS Shell Dlg")
.size(15)
.build(&mut font)
.expect("Failed to build font");
nwg::Font::set_global_default(Some(font));
let _ui = ConfigDlg::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
|
extern crate enum_map;
pub type Coordinate = i8;
#[derive(Clone)]
pub struct Map<T> {
pub height: Coordinate,
pub width: Coordinate,
pub map: Vec<T>,
}
impl<T> Map<T> {
pub fn get(&self, x: Coordinate, y: Coordinate) -> Option<&T> {
if x < 0 || x >= self.width || y < 0 || y >= self.height {
return None;
}
self.map.get(((y as usize) * (self.width as usize) + (x as usize)) as usize)
}
pub fn get_mut(&mut self, x: Coordinate, y: Coordinate) -> Option<&mut T> {
if x < 0 || x >= self.width || y < 0 || y >= self.height {
return None;
}
self.map.get_mut((y * self.width + x) as usize)
}
}
#[derive(Clone, Copy, enum_map::Enum, PartialEq, Eq)]
pub enum CaseState {
Empty,
Box,
Wall,
}
#[derive(Clone, Copy, enum_map::Enum)]
pub enum Direction {
Up,
Down,
Left,
Right,
}
#[derive(Clone)]
pub struct State {
pub map: Map<CaseState>,
pub spots: Vec<(Coordinate, Coordinate)>,
pub mario_x: Coordinate,
pub mario_y: Coordinate,
pub mario_orientation: Direction,
}
impl State {
pub fn is_solved(&self) -> bool {
self.spots.iter().all(|(x,y)| self.map.get(*x,*y)==Some(&CaseState::Box))
}
pub fn move_mario(&mut self, direction: Direction) {
let (dx, dy) = match direction {
Direction::Down => (0, 1),
Direction::Up => (0, -1),
Direction::Left => (-1, 0),
Direction::Right => (1, 0),
};
if let Some(case) = self.map.get(self.mario_x + dx, self.mario_y + dy) {
match case {
CaseState::Wall => {}
CaseState::Empty => {
self.mario_x += dx;
self.mario_y += dy;
self.mario_orientation = direction;
}
CaseState::Box => {
if let Some(case2) = self.map.get(self.mario_x + 2 * dx, self.mario_y + 2 * dy)
{
match case2 {
CaseState::Wall | CaseState::Box => {}
CaseState::Empty => {
*self
.map
.get_mut(self.mario_x + dx, self.mario_y + dy)
.unwrap() = CaseState::Empty;
*self
.map
.get_mut(self.mario_x + 2 * dx, self.mario_y + 2 * dy)
.unwrap() = CaseState::Box;
self.mario_x += dx;
self.mario_y += dy;
self.mario_orientation = direction;
}
}
}
}
}
}
}
}
|
#[doc = "Reader of register DAC_SR"]
pub type R = crate::R<u32, super::DAC_SR>;
#[doc = "Writer for register DAC_SR"]
pub type W = crate::W<u32, super::DAC_SR>;
#[doc = "Register DAC_SR `reset()`'s with value 0"]
impl crate::ResetValue for super::DAC_SR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DAC1RDY`"]
pub type DAC1RDY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DAC1RDY`"]
pub struct DAC1RDY_W<'a> {
w: &'a mut W,
}
impl<'a> DAC1RDY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `DORSTAT1`"]
pub type DORSTAT1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DORSTAT1`"]
pub struct DORSTAT1_W<'a> {
w: &'a mut W,
}
impl<'a> DORSTAT1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `DMAUDR1`"]
pub type DMAUDR1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAUDR1`"]
pub struct DMAUDR1_W<'a> {
w: &'a mut W,
}
impl<'a> DMAUDR1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `CAL_FLAG1`"]
pub type CAL_FLAG1_R = crate::R<bool, bool>;
#[doc = "Reader of field `BWST1`"]
pub type BWST1_R = crate::R<bool, bool>;
#[doc = "Reader of field `DAC2RDY`"]
pub type DAC2RDY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DAC2RDY`"]
pub struct DAC2RDY_W<'a> {
w: &'a mut W,
}
impl<'a> DAC2RDY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `DORSTAT2`"]
pub type DORSTAT2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DORSTAT2`"]
pub struct DORSTAT2_W<'a> {
w: &'a mut W,
}
impl<'a> DORSTAT2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `DMAUDR2`"]
pub type DMAUDR2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAUDR2`"]
pub struct DMAUDR2_W<'a> {
w: &'a mut W,
}
impl<'a> DMAUDR2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `CAL_FLAG2`"]
pub type CAL_FLAG2_R = crate::R<bool, bool>;
#[doc = "Reader of field `BWST2`"]
pub type BWST2_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 11 - DAC channel1 ready status bit"]
#[inline(always)]
pub fn dac1rdy(&self) -> DAC1RDY_R {
DAC1RDY_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - DAC channel1 output register status bit"]
#[inline(always)]
pub fn dorstat1(&self) -> DORSTAT1_R {
DORSTAT1_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - DAC channel1 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
#[inline(always)]
pub fn dmaudr1(&self) -> DMAUDR1_R {
DMAUDR1_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - DAC Channel 1 calibration offset status This bit is set and cleared by hardware"]
#[inline(always)]
pub fn cal_flag1(&self) -> CAL_FLAG1_R {
CAL_FLAG1_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - DAC Channel 1 busy writing sample time flag This bit is systematically set just after Sample & Hold mode enable and is set each time the software writes the register DAC_SHSR1, It is cleared by hardware when the write operation of DAC_SHSR1 is complete. (It takes about 3LSI periods of synchronization)."]
#[inline(always)]
pub fn bwst1(&self) -> BWST1_R {
BWST1_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 27 - DAC channel 2 ready status bit"]
#[inline(always)]
pub fn dac2rdy(&self) -> DAC2RDY_R {
DAC2RDY_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - DAC channel 2 output register status bit"]
#[inline(always)]
pub fn dorstat2(&self) -> DORSTAT2_R {
DORSTAT2_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - DAC channel2 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
#[inline(always)]
pub fn dmaudr2(&self) -> DMAUDR2_R {
DMAUDR2_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - DAC Channel 2 calibration offset status This bit is set and cleared by hardware"]
#[inline(always)]
pub fn cal_flag2(&self) -> CAL_FLAG2_R {
CAL_FLAG2_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - DAC Channel 2 busy writing sample time flag This bit is systematically set just after Sample & Hold mode enable and is set each time the software writes the register DAC_SHSR2, It is cleared by hardware when the write operation of DAC_SHSR2 is complete. (It takes about 3 LSI periods of synchronization)."]
#[inline(always)]
pub fn bwst2(&self) -> BWST2_R {
BWST2_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 11 - DAC channel1 ready status bit"]
#[inline(always)]
pub fn dac1rdy(&mut self) -> DAC1RDY_W {
DAC1RDY_W { w: self }
}
#[doc = "Bit 12 - DAC channel1 output register status bit"]
#[inline(always)]
pub fn dorstat1(&mut self) -> DORSTAT1_W {
DORSTAT1_W { w: self }
}
#[doc = "Bit 13 - DAC channel1 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
#[inline(always)]
pub fn dmaudr1(&mut self) -> DMAUDR1_W {
DMAUDR1_W { w: self }
}
#[doc = "Bit 27 - DAC channel 2 ready status bit"]
#[inline(always)]
pub fn dac2rdy(&mut self) -> DAC2RDY_W {
DAC2RDY_W { w: self }
}
#[doc = "Bit 28 - DAC channel 2 output register status bit"]
#[inline(always)]
pub fn dorstat2(&mut self) -> DORSTAT2_W {
DORSTAT2_W { w: self }
}
#[doc = "Bit 29 - DAC channel2 DMA underrun flag This bit is set by hardware and cleared by software (by writing it to 1)."]
#[inline(always)]
pub fn dmaudr2(&mut self) -> DMAUDR2_W {
DMAUDR2_W { w: self }
}
}
|
use std::{env, error::Error, fs};
use mmap::{MapOption, MemoryMap};
use region::{protect, Protection};
fn main() -> Result<(), Box<dyn Error>> {
let input_path = env::args().nth(1).expect("Usage: elk FILE");
let input = fs::read(&input_path)?;
println!("Analyzing {:?}...", input_path);
let file = match delf::File::parse_or_print_error(&input[..]) {
Some(f) => f,
None => std::process::exit(1),
};
println!("{:#?}", file);
println!("Disassembling {:?}...", input_path);
let code_ph = file
.program_headers
.iter()
.find(|ph| ph.mem_range().contains(&file.entry_point))
.expect("segment with entry point not found");
ndisasm(&code_ph.data[..], file.entry_point)?;
println!("Mapping {:?} in memory...", input_path);
let mut mappings = Vec::new();
for ph in file
.program_headers
.iter()
.filter(|ph| ph.r#type == delf::SegmentType::Load)
{
println!("Mapping segment @ {:?} with {:?}", ph.mem_range(), ph.flags);
let mem_range = ph.mem_range();
let len: usize = (mem_range.end - mem_range.start).into();
let addr: *mut u8 = mem_range.start.0 as _;
let map = MemoryMap::new(len, &[MapOption::MapWritable, MapOption::MapAddr(addr)])?;
println!("Copying segment data");
{
let dst = unsafe { std::slice::from_raw_parts_mut(addr, ph.data.len()) };
dst.copy_from_slice(&ph.data[..]);
}
let mut protection = Protection::NONE;
for flag in ph.flags.iter() {
protection |= match flag {
delf::SegmentFlag::Read => Protection::READ,
delf::SegmentFlag::Execute => Protection::EXECUTE,
delf::SegmentFlag::Write => Protection::WRITE,
}
}
unsafe {
protect(addr, len, protection)?;
}
mappings.push(map)
}
println!("Executing {:?} in memory...", input_path);
unsafe {
jmp(file.entry_point.0 as _);
}
Ok(())
}
fn ndisasm(code: &[u8], origin: delf::Addr) -> Result<(), Box<dyn Error>> {
use std::{
io::Write,
process::{Command, Stdio},
};
let mut child = Command::new("ndisasm")
.arg("-b")
.arg("64")
.arg("-o")
.arg(format!("{}", origin.0))
.arg("-")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
child.stdin.as_mut().unwrap().write_all(code)?;
let output = child.wait_with_output()?;
println!("{}", String::from_utf8_lossy(&output.stdout));
Ok(())
}
unsafe fn jmp(addr: *const u8) {
let fn_ptr: fn() = std::mem::transmute(addr);
fn_ptr();
}
|
mod queries;
mod query_groups;
pub use self::query_groups::{Parser, ParserStorage};
pub(crate) mod prelude {
pub use super::query_groups::{Parser, ParserStorage};
pub use crate::diagnostics::*;
pub use crate::interner::*;
pub use crate::output::CompilerOutput;
}
|
use atoms::{Location, TokenType};
use std::fmt;
use traits::HasLocation;
///
/// A token is the smallest element of a program that has meaning.
/// Tokens are then put together to create the various nodes of the
/// syntax tree.
///
/// The token is tied to the lifetime of the
/// file buffer from which the token was taken.
///
#[derive(Clone, Debug)]
pub struct Token {
///
/// The starting position of this token.
///
pub start_pos: Location,
///
/// The string data wrapped by this token.
///
pub string: String,
///
/// The type of this token.
///
pub ttype: TokenType,
}
impl Token {
///
/// Create a new token with the specified data.
///
pub fn new(start_pos: Location, string: String, ttype: TokenType) -> Token {
Token {
start_pos,
string,
ttype,
}
}
}
impl HasLocation for Token {
fn start(&self) -> Location {
self.start_pos.clone()
}
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"\"{}\" ({:?} @ {})",
self.string,
self.ttype,
self.start_pos
)
}
}
|
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! Packed variant of secret sharing, allowing to share efficiently several values together.
use numtheory::{mod_pow, fft2_inverse, fft3};
use rand;
/// Packed variant of the secret sharing.
///
/// In Shamir scheme, one single value (one number) is set as the 0-th
/// coefficient of a polynomial, and the evaluation of this polynomial
/// at different point is shared to different sharees. Once enough shares
/// (degree+1) are put together, the polynomial can be uniquely determined
/// and evaluated in 0 to reconstruct the secret.
///
/// The idea behing the packed scheme is to "fix" more values of the
/// polynomial to represent more secret values. We could for instance pick
/// evaluation at 0, -1, -2 to encode three values, find a polynomial of
/// high-enough degree going through these points, then evaluate it on 1, 2...
/// to generate enough shares.
///
/// But operations on polynomial are expensive (quadratic) in the general case.
/// By careful picking of evaluation points and using Fast Fourier Transform,
/// most of our operation can be kept under `O(n.log(n))`.
///
/// * secrets are positioned on 2^n roots of unity
/// * shares are read on 3^n roots of unity
///
/// Except from the evaluation in `1`, a point that we do not use, these two
/// sets are distinct, so no share exposes coincidentaly any secret.
///
/// So there exist constraints between the various parameters:
///
/// * `prime` must be big enough to handle the shared values
/// * `secret_count + threshold + 1` (aka reconstruct_limit) must be a power of 2
/// * `share_count + 1` must be a power of 3
/// * `omega_secrets` must be a `reconstruct_limit()`-th root of unity
/// * `omega_shares` must be a `(share_count+1)`-th root of unity
#[derive(Debug,Copy,Clone,PartialEq)]
pub struct PackedSecretSharing {
// abstract properties
/// security threshold
pub threshold: usize,
/// number of shares to generate
pub share_count: usize,
/// number of secrets in each share
pub secret_count: usize,
// implementation configuration
/// prime field to use
pub prime: i64,
/// `reconstruct_limit`-th principal root of unity in Z_p
pub omega_secrets: i64,
/// `secret_count+1`-th principal root of unity in Z_p
pub omega_shares: i64,
}
/// Example of tiny PSS settings, for sharing 3 secrets 8 ways, with
/// a security threshold of 4.
pub static PSS_4_8_3: PackedSecretSharing = PackedSecretSharing {
threshold: 4,
share_count: 8,
secret_count: 3,
prime: 433,
omega_secrets: 354,
omega_shares: 150,
};
/// Example of small PSS settings, for sharing 3 secrets 26 ways, with
/// a security threshold of 4.
pub static PSS_4_26_3: PackedSecretSharing = PackedSecretSharing {
threshold: 4,
share_count: 26,
secret_count: 3,
prime: 433,
omega_secrets: 354,
omega_shares: 17,
};
/// Example of PSS settings, for sharing 100 secrets 728 ways, with
/// a security threshold of 156.
pub static PSS_155_728_100: PackedSecretSharing = PackedSecretSharing {
threshold: 155,
share_count: 728,
secret_count: 100,
prime: 746497,
omega_secrets: 95660,
omega_shares: 610121,
};
/// Example of PSS settings, for sharing 100 secrets 19682 ways, with
/// a security threshold of 156.
pub static PSS_155_19682_100: PackedSecretSharing = PackedSecretSharing {
threshold: 155,
share_count: 19682,
secret_count: 100,
prime: 5038849,
omega_secrets: 4318906,
omega_shares: 1814687,
};
impl PackedSecretSharing {
/// minimum number of shares required to reconstruct secret
///
/// (secret_count + threshold + 1)
pub fn reconstruct_limit(&self) -> usize {
self.secret_count + self.threshold + 1
}
/// Computes shares for the vector of secrets.
///
/// It is assumed that `secret` is equal in len to `secret_count` (the
/// code will assert otherwise). It is safe to pad with anything, including
/// zeros.
pub fn share(&self, secrets: &[i64]) -> Vec<i64> {
assert_eq!(secrets.len(), self.secret_count);
// sample polynomial
let mut poly = self.sample_polynomial(secrets);
// .. and extend it
poly.extend(vec![0; self.share_count + 1 - self.reconstruct_limit()]);
// evaluate polynomial to generate shares
let mut shares = self.evaluate_polynomial(poly);
// .. but remove first element since it should not be used as a share (it's always 1)
shares.remove(0);
// return
assert_eq!(shares.len(), self.share_count);
shares
}
fn sample_polynomial(&self, secrets: &[i64]) -> Vec<i64> {
// sample randomness
// - for cryptographic use we should use OsRng as dictated here
// https://doc.rust-lang.org/rand/rand/index.html#cryptographic-security
use rand::distributions::Sample;
let mut range = rand::distributions::range::Range::new(0, self.prime - 1);
let mut rng = rand::OsRng::new().unwrap();
let randomness: Vec<i64> =
(0..self.threshold).map(|_| range.sample(&mut rng) as i64).collect();
// recover polynomial
let coefficients = self.recover_polynomial(secrets, randomness);
coefficients
}
fn recover_polynomial(&self, secrets: &[i64], randomness: Vec<i64>) -> Vec<i64> {
// fix the value corresponding to point 1
let mut values: Vec<i64> = vec![0];
// let the subsequent values correspond to the secrets
values.extend(secrets);
// fill in with random values
values.extend(randomness);
// run backward FFT to recover polynomial in coefficient representation
assert_eq!(values.len(), self.reconstruct_limit());
let coefficients = fft2_inverse(&values, self.omega_secrets, self.prime);
coefficients
}
fn evaluate_polynomial(&self, coefficients: Vec<i64>) -> Vec<i64> {
assert_eq!(coefficients.len(), self.share_count + 1);
let points = fft3(&coefficients, self.omega_shares, self.prime);
points
}
/// Reconstruct the secret vector from enough shares.
///
/// `indices` and `shares` must be of the same size, and strictly more than
/// `threshold` (it will assert if otherwise).
///
/// `indices` is the rank of the known shares from the `share` method
/// output, while `values` are the actual values of these shares.
///
/// The result is of length `secret_count`.
pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> Vec<i64> {
assert!(shares.len() == indices.len());
assert!(shares.len() >= self.reconstruct_limit());
let shares_points: Vec<i64> =
indices.iter().map(|&x| mod_pow(self.omega_shares, x as u32 + 1, self.prime)).collect();
// interpolate using Newton's method
use numtheory::{newton_interpolation_general, newton_evaluate};
// TODO optimise by using Newton-equally-space variant
let poly = newton_interpolation_general(&shares_points, &shares, self.prime);
// evaluate at omega_secrets points to recover secrets
// TODO optimise to avoid re-computation of power
let secrets = (1..self.reconstruct_limit())
.map(|e| mod_pow(self.omega_secrets, e as u32, self.prime))
.map(|point| newton_evaluate(&poly, point, self.prime))
.take(self.secret_count)
.collect();
secrets
}
}
#[cfg(test)]
mod tests {
use super::*;
use numtheory::*;
#[test]
fn test_recover_polynomial() {
let ref pss = PSS_4_8_3;
let secrets = vec![1, 2, 3];
let randomness = vec![8, 8, 8, 8]; // use fixed randomness
let poly = pss.recover_polynomial(&secrets, randomness);
assert_eq!(positivise(&poly, pss.prime), positivise(&[113, -382, -172, 267, -325, 432, 388, -321], pss.prime));
}
#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_evaluate_polynomial() {
let ref pss = PSS_4_26_3;
let poly = vec![113, 51, 261, 267, 108, 432, 388, 112, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let points = positivise(&pss.evaluate_polynomial(poly), pss.prime);
assert_eq!(points, vec![ 0, 77, 230, 91, 286, 179, 337, 83, 212, 88,
406, 58, 425, 345, 350, 336, 430, 404, 51, 60, 305,
395, 84, 156, 160, 112, 422]);
}
#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn test_share() {
let ref pss = PSS_4_26_3;
// do sharing
let secrets = vec![5, 6, 7];
let mut shares = pss.share(&secrets);
// manually recover secrets
use numtheory::{fft3_inverse, mod_evaluate_polynomial};
shares.insert(0, 0);
let poly = fft3_inverse(&shares, PSS_4_26_3.omega_shares, PSS_4_26_3.prime);
let recovered_secrets: Vec<i64> = (1..secrets.len() + 1)
.map(|i| {
mod_evaluate_polynomial(&poly,
mod_pow(PSS_4_26_3.omega_secrets,
i as u32,
PSS_4_26_3.prime),
PSS_4_26_3.prime)
})
.collect();
use numtheory::positivise;
assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);
}
#[test]
fn test_large_share() {
let ref pss = PSS_155_19682_100;
let secrets = vec![5 ; pss.secret_count];
let shares = pss.share(&secrets);
assert_eq!(shares.len(), pss.share_count);
}
#[test]
fn test_share_reconstruct() {
let ref pss = PSS_4_26_3;
let secrets = vec![5, 6, 7];
let shares = pss.share(&secrets);
use numtheory::positivise;
// reconstruction must work for all shares
let indices: Vec<usize> = (0..shares.len()).collect();
let recovered_secrets = pss.reconstruct(&indices, &shares);
assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);
// .. and for only sufficient shares
let indices: Vec<usize> = (0..pss.reconstruct_limit()).collect();
let recovered_secrets = pss.reconstruct(&indices, &shares[0..pss.reconstruct_limit()]);
assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);
}
#[test]
fn test_share_additive_homomorphism() {
let ref pss = PSS_4_26_3;
let secrets_1 = vec![1, 2, 3];
let secrets_2 = vec![4, 5, 6];
let shares_1 = pss.share(&secrets_1);
let shares_2 = pss.share(&secrets_2);
// add shares pointwise
let shares_sum: Vec<i64> =
shares_1.iter().zip(shares_2).map(|(a, b)| (a + b) % pss.prime).collect();
// reconstruct sum, using same reconstruction limit
let reconstruct_limit = pss.reconstruct_limit();
let indices: Vec<usize> = (0..reconstruct_limit).collect();
let shares = &shares_sum[0..reconstruct_limit];
let recovered_secrets = pss.reconstruct(&indices, shares);
use numtheory::positivise;
assert_eq!(positivise(&recovered_secrets, pss.prime), vec![5, 7, 9]);
}
#[test]
fn test_share_multiplicative_homomorphism() {
let ref pss = PSS_4_26_3;
let secrets_1 = vec![1, 2, 3];
let secrets_2 = vec![4, 5, 6];
let shares_1 = pss.share(&secrets_1);
let shares_2 = pss.share(&secrets_2);
// multiply shares pointwise
let shares_product: Vec<i64> =
shares_1.iter().zip(shares_2).map(|(a, b)| (a * b) % pss.prime).collect();
// reconstruct product, using double reconstruction limit (minus one)
let reconstruct_limit = pss.reconstruct_limit() * 2 - 1;
let indices: Vec<usize> = (0..reconstruct_limit).collect();
let shares = &shares_product[0..reconstruct_limit];
let recovered_secrets = pss.reconstruct(&indices, shares);
use numtheory::positivise;
assert_eq!(positivise(&recovered_secrets, pss.prime), vec![4, 10, 18]);
}
}
#[cfg(feature = "paramgen")]
pub mod paramgen {
extern crate primal;
#[cfg_attr(rustfmt, rustfmt_skip)]
fn check_prime_form(min_p: usize, n: usize, m: usize, p: usize) -> bool {
if p < min_p { return false; }
let q = p - 1;
if q % n != 0 { return false; }
if q % m != 0 { return false; }
let q = q / (n * m);
if q % n == 0 { return false; }
if q % m == 0 { return false; }
return true;
}
#[test]
fn test_check_prime_form() {
assert_eq!(primal::Primes::all().find(|p| check_prime_form(198, 8, 9, *p)).unwrap(),
433);
}
fn factor(p: usize) -> Vec<usize> {
let mut factors = vec![];
let bound = (p as f64).sqrt().ceil() as usize;
for f in 2..bound + 1 {
if p % f == 0 {
factors.push(f);
factors.push(p / f);
}
}
factors
}
#[test]
fn test_factor() {
assert_eq!(factor(40), [2, 20, 4, 10, 5, 8]);
assert_eq!(factor(41), []);
}
fn find_field(min_p: usize, n: usize, m: usize) -> Option<(i64, i64)> {
// find prime of right form
let p = primal::Primes::all().find(|p| check_prime_form(min_p, n, m, *p)).unwrap();
// find (any) generator
let factors = factor(p - 1);
for g in 2..p {
// test generator against all factors of p-1
let is_generator = factors.iter().all(|f| {
use numtheory::mod_pow;
let e = (p - 1) / f;
mod_pow(g as i64, e as u32, p as i64) != 1 // TODO check for negative value
});
// return
if is_generator {
return Some((p as i64, g as i64));
}
}
// didn't find any
None
}
#[test]
fn test_find_field() {
assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(2)).unwrap(),
(433, 5));
assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(3)).unwrap(),
(433, 5));
assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(6)).unwrap(),
(746497, 5));
assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(9)).unwrap(),
(5038849, 29));
// assert_eq!(find_field(198, 2usize.pow(11), 3usize.pow(8)).unwrap(), (120932353, 5));
// assert_eq!(find_field(198, 2usize.pow(13), 3usize.pow(9)).unwrap(), (483729409, 23));
}
fn find_roots(n: usize, m: usize, p: i64, g: i64) -> (i64, i64) {
use numtheory::mod_pow;
let omega_secrets = mod_pow(g, ((p - 1) / n as i64) as u32, p);
let omega_shares = mod_pow(g, ((p - 1) / m as i64) as u32, p);
(omega_secrets, omega_shares)
}
#[test]
fn test_find_roots() {
assert_eq!(find_roots(2usize.pow(3), 3usize.pow(2), 433, 5), (354, 150));
assert_eq!(find_roots(2usize.pow(3), 3usize.pow(3), 433, 5), (354, 17));
}
pub fn generate_parameters(min_size: usize, n: usize, m: usize) -> (i64, i64, i64) {
let (prime, g) = find_field(min_size, n, m).unwrap(); // TODO settle option business once and for all (don't remember it as needed)
let (omega_secrets, omega_shares) = find_roots(n, m, prime, g);
(prime, omega_secrets, omega_shares)
}
#[test]
fn test_generate_parameters() {
assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(2)),
(433, 354, 150));
assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(3)),
(433, 354, 17));
}
use super::PackedSecretSharing;
impl PackedSecretSharing {
pub fn new_with_min_size(threshold: usize,
secret_count: usize,
share_count: usize,
min_size: usize)
-> PackedSecretSharing {
let n = threshold + secret_count + 1;
let m = share_count + 1;
let two_power = (n as f64).log(2f64).floor() as u32;
assert!(2usize.pow(two_power) == n);
let three_power = (m as f64).log(3f64).floor() as u32;
assert!(3usize.pow(three_power) == m);
assert!(min_size >= share_count + secret_count + 1);
let (prime, omega_secrets, omega_shares) = generate_parameters(min_size, n, m);
PackedSecretSharing {
threshold: threshold,
share_count: share_count,
secret_count: secret_count,
prime: prime,
omega_secrets: omega_secrets,
omega_shares: omega_shares,
}
}
pub fn new(threshold: usize,
secret_count: usize,
share_count: usize)
-> PackedSecretSharing {
let min_size = share_count + secret_count + threshold + 1;
Self::new_with_min_size(threshold, secret_count, share_count, min_size)
}
}
#[test]
fn test_new() {
assert_eq!(PackedSecretSharing::new(155, 100, 728),
super::PSS_155_728_100);
assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 8, 200),
super::PSS_4_8_3);
assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 26, 200),
super::PSS_4_26_3);
}
}
|
use std::collections::HashSet;
use std::env;
use std::error::Error;
use std::fs;
// This function is also defined in lib.rs
pub fn composition(k: usize, text: &[u8]) -> HashSet<String> {
text.windows(k)
.map(|kmer| String::from_utf8_lossy(kmer).into_owned())
.collect()
}
fn main() -> Result<(), Box<dyn Error>> {
let input: String = env::args()
.nth(1)
.unwrap_or("data/rosalind_ba3a.txt".into());
let data = fs::read_to_string(input)?;
let mut lines = data.lines();
let k = lines.next().unwrap().parse()?;
let text: String = lines.next().unwrap().into();
for kmer in composition(k, text.as_str().as_bytes()) {
println!("{}", kmer);
}
Ok(())
}
|
#[doc = "Reader of register OTG_HS_GLPMCFG"]
pub type R = crate::R<u32, super::OTG_HS_GLPMCFG>;
#[doc = "Writer for register OTG_HS_GLPMCFG"]
pub type W = crate::W<u32, super::OTG_HS_GLPMCFG>;
#[doc = "Register OTG_HS_GLPMCFG `reset()`'s with value 0"]
impl crate::ResetValue for super::OTG_HS_GLPMCFG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LPMEN`"]
pub type LPMEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPMEN`"]
pub struct LPMEN_W<'a> {
w: &'a mut W,
}
impl<'a> LPMEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `LPMACK`"]
pub type LPMACK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPMACK`"]
pub struct LPMACK_W<'a> {
w: &'a mut W,
}
impl<'a> LPMACK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `BESL`"]
pub type BESL_R = crate::R<u8, u8>;
#[doc = "Reader of field `REMWAKE`"]
pub type REMWAKE_R = crate::R<bool, bool>;
#[doc = "Reader of field `L1SSEN`"]
pub type L1SSEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `L1SSEN`"]
pub struct L1SSEN_W<'a> {
w: &'a mut W,
}
impl<'a> L1SSEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `BESLTHRS`"]
pub type BESLTHRS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `BESLTHRS`"]
pub struct BESLTHRS_W<'a> {
w: &'a mut W,
}
impl<'a> BESLTHRS_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `L1DSEN`"]
pub type L1DSEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `L1DSEN`"]
pub struct L1DSEN_W<'a> {
w: &'a mut W,
}
impl<'a> L1DSEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `LPMRST`"]
pub type LPMRST_R = crate::R<u8, u8>;
#[doc = "Reader of field `SLPSTS`"]
pub type SLPSTS_R = crate::R<bool, bool>;
#[doc = "Reader of field `L1RSMOK`"]
pub type L1RSMOK_R = crate::R<bool, bool>;
#[doc = "Reader of field `LPMCHIDX`"]
pub type LPMCHIDX_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `LPMCHIDX`"]
pub struct LPMCHIDX_W<'a> {
w: &'a mut W,
}
impl<'a> LPMCHIDX_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 17)) | (((value as u32) & 0x0f) << 17);
self.w
}
}
#[doc = "Reader of field `LPMRCNT`"]
pub type LPMRCNT_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `LPMRCNT`"]
pub struct LPMRCNT_W<'a> {
w: &'a mut W,
}
impl<'a> LPMRCNT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 21)) | (((value as u32) & 0x07) << 21);
self.w
}
}
#[doc = "Reader of field `SNDLPM`"]
pub type SNDLPM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SNDLPM`"]
pub struct SNDLPM_W<'a> {
w: &'a mut W,
}
impl<'a> SNDLPM_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `LPMRCNTSTS`"]
pub type LPMRCNTSTS_R = crate::R<u8, u8>;
#[doc = "Reader of field `ENBESL`"]
pub type ENBESL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ENBESL`"]
pub struct ENBESL_W<'a> {
w: &'a mut W,
}
impl<'a> ENBESL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
impl R {
#[doc = "Bit 0 - LPM support enable"]
#[inline(always)]
pub fn lpmen(&self) -> LPMEN_R {
LPMEN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LPM token acknowledge enable"]
#[inline(always)]
pub fn lpmack(&self) -> LPMACK_R {
LPMACK_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bits 2:5 - Best effort service latency"]
#[inline(always)]
pub fn besl(&self) -> BESL_R {
BESL_R::new(((self.bits >> 2) & 0x0f) as u8)
}
#[doc = "Bit 6 - bRemoteWake value"]
#[inline(always)]
pub fn remwake(&self) -> REMWAKE_R {
REMWAKE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - L1 Shallow Sleep enable"]
#[inline(always)]
pub fn l1ssen(&self) -> L1SSEN_R {
L1SSEN_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bits 8:11 - BESL threshold"]
#[inline(always)]
pub fn beslthrs(&self) -> BESLTHRS_R {
BESLTHRS_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bit 12 - L1 deep sleep enable"]
#[inline(always)]
pub fn l1dsen(&self) -> L1DSEN_R {
L1DSEN_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bits 13:14 - LPM response"]
#[inline(always)]
pub fn lpmrst(&self) -> LPMRST_R {
LPMRST_R::new(((self.bits >> 13) & 0x03) as u8)
}
#[doc = "Bit 15 - Port sleep status"]
#[inline(always)]
pub fn slpsts(&self) -> SLPSTS_R {
SLPSTS_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - Sleep State Resume OK"]
#[inline(always)]
pub fn l1rsmok(&self) -> L1RSMOK_R {
L1RSMOK_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bits 17:20 - LPM Channel Index"]
#[inline(always)]
pub fn lpmchidx(&self) -> LPMCHIDX_R {
LPMCHIDX_R::new(((self.bits >> 17) & 0x0f) as u8)
}
#[doc = "Bits 21:23 - LPM retry count"]
#[inline(always)]
pub fn lpmrcnt(&self) -> LPMRCNT_R {
LPMRCNT_R::new(((self.bits >> 21) & 0x07) as u8)
}
#[doc = "Bit 24 - Send LPM transaction"]
#[inline(always)]
pub fn sndlpm(&self) -> SNDLPM_R {
SNDLPM_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bits 25:27 - LPM retry count status"]
#[inline(always)]
pub fn lpmrcntsts(&self) -> LPMRCNTSTS_R {
LPMRCNTSTS_R::new(((self.bits >> 25) & 0x07) as u8)
}
#[doc = "Bit 28 - Enable best effort service latency"]
#[inline(always)]
pub fn enbesl(&self) -> ENBESL_R {
ENBESL_R::new(((self.bits >> 28) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LPM support enable"]
#[inline(always)]
pub fn lpmen(&mut self) -> LPMEN_W {
LPMEN_W { w: self }
}
#[doc = "Bit 1 - LPM token acknowledge enable"]
#[inline(always)]
pub fn lpmack(&mut self) -> LPMACK_W {
LPMACK_W { w: self }
}
#[doc = "Bit 7 - L1 Shallow Sleep enable"]
#[inline(always)]
pub fn l1ssen(&mut self) -> L1SSEN_W {
L1SSEN_W { w: self }
}
#[doc = "Bits 8:11 - BESL threshold"]
#[inline(always)]
pub fn beslthrs(&mut self) -> BESLTHRS_W {
BESLTHRS_W { w: self }
}
#[doc = "Bit 12 - L1 deep sleep enable"]
#[inline(always)]
pub fn l1dsen(&mut self) -> L1DSEN_W {
L1DSEN_W { w: self }
}
#[doc = "Bits 17:20 - LPM Channel Index"]
#[inline(always)]
pub fn lpmchidx(&mut self) -> LPMCHIDX_W {
LPMCHIDX_W { w: self }
}
#[doc = "Bits 21:23 - LPM retry count"]
#[inline(always)]
pub fn lpmrcnt(&mut self) -> LPMRCNT_W {
LPMRCNT_W { w: self }
}
#[doc = "Bit 24 - Send LPM transaction"]
#[inline(always)]
pub fn sndlpm(&mut self) -> SNDLPM_W {
SNDLPM_W { w: self }
}
#[doc = "Bit 28 - Enable best effort service latency"]
#[inline(always)]
pub fn enbesl(&mut self) -> ENBESL_W {
ENBESL_W { w: self }
}
}
|
use std::sync::Arc;
pub trait HEq<T> {
fn are_eq(&self, left: &T, right: &T) -> bool;
fn calc_hash(&self, value: &T) -> u64;
}
pub type ArcDynHEq<T> = Arc<dyn HEq<T>>;
|
use std::io::IsTerminal;
use crate::app::Args;
use anyhow::{anyhow, Result};
use clap::Parser;
/// Starts a RPC service using stdio.
#[derive(Parser, Debug, Clone)]
pub struct Rpc;
impl Rpc {
pub async fn run(&self, args: Args) -> Result<()> {
let (config, config_err) =
maple_core::config::load_config_on_startup(args.config_file.clone());
let maybe_log = if let Some(log_path) = args.log {
Some(log_path)
} else if let Ok(log_path) =
std::env::var("VIM_CLAP_LOG_PATH").map(std::path::PathBuf::from)
{
Some(log_path)
} else {
config.log.log_file.as_ref().map(std::path::PathBuf::from)
};
if let Some(log_path) = maybe_log {
if let Ok(metadata) = std::fs::metadata(&log_path) {
if log_path.is_file() && metadata.len() > 8 * 1024 * 1024 {
std::fs::remove_file(&log_path)?;
}
}
let file_name = log_path
.file_name()
.ok_or_else(|| anyhow!("no file name in {log_path:?}"))?;
let directory = log_path
.parent()
.ok_or_else(|| anyhow!("{log_path:?} has no parent"))?;
let file_appender = tracing_appender::rolling::never(directory, file_name);
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let max_level = config
.log
.max_level
.parse()
.unwrap_or(tracing::Level::DEBUG);
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_max_level(max_level)
.with_line_number(true)
.with_writer(non_blocking)
.with_ansi(std::io::stdout().is_terminal())
.finish();
tracing::subscriber::set_global_default(subscriber)?;
maple_core::stdio_server::start(config_err).await;
} else {
maple_core::stdio_server::start(config_err).await;
}
Ok(())
}
}
|
pub mod level;
pub mod object;
pub mod world;
pub mod context;
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/tempdir/0.3.7")]
#![cfg_attr(test, deny(warnings))]
//! Temporary directories of files.
//!
//! The [`TempDir`] type creates a directory on the file system that
//! is deleted once it goes out of scope. At construction, the
//! `TempDir` creates a new directory with a randomly generated name
//! and a prefix of your choosing.
//!
//! [`TempDir`]: struct.TempDir.html
//! [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
//!
//! # Examples
//!
//! ```
//! extern crate tempdir;
//!
//! use std::fs::File;
//! use std::io::{self, Write};
//! use tempdir::TempDir;
//!
//! fn main() {
//! if let Err(_) = run() {
//! ::std::process::exit(1);
//! }
//! }
//!
//! fn run() -> Result<(), io::Error> {
//! // Create a directory inside of `std::env::temp_dir()`, named with
//! // the prefix "example".
//! let tmp_dir = TempDir::new("example")?;
//! let file_path = tmp_dir.path().join("my-temporary-note.txt");
//! let mut tmp_file = File::create(file_path)?;
//! writeln!(tmp_file, "Brian was here. Briefly.")?;
//!
//! // By closing the `TempDir` explicitly, we can check that it has
//! // been deleted successfully. If we don't close it explicitly,
//! // the directory will still be deleted when `tmp_dir` goes out
//! // of scope, but we won't know whether deleting the directory
//! // succeeded.
//! drop(tmp_file);
//! tmp_dir.close()?;
//! Ok(())
//! }
//! ```
extern crate rand;
extern crate remove_dir_all;
use std::env;
use std::io::{self, Error, ErrorKind};
use std::fmt;
use std::fs;
use std::path::{self, PathBuf, Path};
use rand::{thread_rng, Rng};
use remove_dir_all::remove_dir_all;
/// A directory in the filesystem that is automatically deleted when
/// it goes out of scope.
///
/// The [`TempDir`] type creates a directory on the file system that
/// is deleted once it goes out of scope. At construction, the
/// `TempDir` creates a new directory with a randomly generated name,
/// and with a prefix of your choosing.
///
/// The default constructor, [`TempDir::new`], creates directories in
/// the location returned by [`std::env::temp_dir()`], but `TempDir`
/// can be configured to manage a temporary directory in any location
/// by constructing with [`TempDir::new_in`].
///
/// After creating a `TempDir`, work with the file system by doing
/// standard [`std::fs`] file system operations on its [`Path`],
/// which can be retrieved with [`TempDir::path`]. Once the `TempDir`
/// value is dropped, the directory at the path will be deleted, along
/// with any files and directories it contains. It is your responsibility
/// to ensure that no further file system operations are attempted
/// inside the temporary directory once it has been deleted.
///
/// Various platform-specific conditions may cause `TempDir` to fail
/// to delete the underlying directory. It's important to ensure that
/// handles (like [`File`] and [`ReadDir`]) to files inside the
/// directory are dropped before the `TempDir` goes out of scope. The
/// `TempDir` destructor will silently ignore any errors in deleting
/// the directory; to instead handle errors call [`TempDir::close`].
///
/// Note that if the program exits before the `TempDir` destructor is
/// run, such as via [`std::process::exit`], by segfaulting, or by
/// receiving a signal like `SIGINT`, then the temporary directory
/// will not be deleted.
///
/// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html
/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
/// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html
/// [`TempDir::close`]: struct.TempDir.html#method.close
/// [`TempDir::new`]: struct.TempDir.html#method.new
/// [`TempDir::new_in`]: struct.TempDir.html#method.new_in
/// [`TempDir::path`]: struct.TempDir.html#method.path
/// [`TempDir`]: struct.TempDir.html
/// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
/// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html
/// [`std::process::exit`]: http://doc.rust-lang.org/std/process/fn.exit.html
pub struct TempDir {
path: Option<PathBuf>,
}
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out of patience.
const NUM_RETRIES: u32 = 1 << 31;
// How many characters should we include in a random file name? It needs to
// be enough to dissuade an attacker from trying to preemptively create names
// of that length, but not so huge that we unnecessarily drain the random number
// generator of entropy.
const NUM_RAND_CHARS: usize = 12;
impl TempDir {
/// Attempts to make a temporary directory inside of `env::temp_dir()` whose
/// name will have the prefix, `prefix`. The directory and
/// everything inside it will be automatically deleted once the
/// returned `TempDir` is destroyed.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempdir::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of `std::env::temp_dir()`, named with
/// // the prefix, "example".
/// let tmp_dir = TempDir::new("example")?;
/// let file_path = tmp_dir.path().join("my-temporary-note.txt");
/// let mut tmp_file = File::create(file_path)?;
/// writeln!(tmp_file, "Brian was here. Briefly.")?;
///
/// // `tmp_dir` goes out of scope, the directory as well as
/// // `tmp_file` will be deleted here.
/// # Ok(())
/// # }
/// ```
pub fn new(prefix: &str) -> io::Result<TempDir> {
TempDir::new_in(&env::temp_dir(), prefix)
}
/// Attempts to make a temporary directory inside of `tmpdir`
/// whose name will have the prefix `prefix`. The directory and
/// everything inside it will be automatically deleted once the
/// returned `TempDir` is destroyed.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::{self, File};
/// use std::io::Write;
/// use tempdir::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of the current directory, named with
/// // the prefix, "example".
/// let tmp_dir = TempDir::new_in(".", "example")?;
/// let file_path = tmp_dir.path().join("my-temporary-note.txt");
/// let mut tmp_file = File::create(file_path)?;
/// writeln!(tmp_file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> {
let storage;
let mut tmpdir = tmpdir.as_ref();
if !tmpdir.is_absolute() {
let cur_dir = env::current_dir()?;
storage = cur_dir.join(tmpdir);
tmpdir = &storage;
// return TempDir::new_in(&cur_dir.join(tmpdir), prefix);
}
let mut rng = thread_rng();
for _ in 0..NUM_RETRIES {
let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect();
let leaf = if !prefix.is_empty() {
format!("{}.{}", prefix, suffix)
} else {
// If we're given an empty string for a prefix, then creating a
// directory starting with "." would lead to it being
// semi-invisible on some systems.
suffix
};
let path = tmpdir.join(&leaf);
match fs::create_dir(&path) {
Ok(_) => return Ok(TempDir { path: Some(path) }),
Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
}
Err(Error::new(ErrorKind::AlreadyExists,
"too many temporary directories already exist"))
}
/// Accesses the [`Path`] to the temporary directory.
///
/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
///
/// # Examples
///
/// ```
/// use tempdir::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_path;
///
/// {
/// let tmp_dir = TempDir::new("example")?;
/// tmp_path = tmp_dir.path().to_owned();
///
/// // Check that the temp directory actually exists.
/// assert!(tmp_path.exists());
///
/// // End of `tmp_dir` scope, directory will be deleted
/// }
///
/// // Temp directory should be deleted by now
/// assert_eq!(tmp_path.exists(), false);
/// # Ok(())
/// # }
/// ```
pub fn path(&self) -> &path::Path {
self.path.as_ref().unwrap()
}
/// Unwraps the [`Path`] contained in the `TempDir` and
/// returns it. This destroys the `TempDir` without deleting the
/// directory represented by the returned `Path`.
///
/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
///
/// # Examples
///
/// ```
/// use std::fs;
/// use tempdir::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = TempDir::new("example")?;
///
/// // Convert `tmp_dir` into a `Path`, destroying the `TempDir`
/// // without deleting the directory.
/// let tmp_path = tmp_dir.into_path();
///
/// // Delete the temporary directory ourselves.
/// fs::remove_dir_all(tmp_path)?;
/// # Ok(())
/// # }
/// ```
pub fn into_path(mut self) -> PathBuf {
self.path.take().unwrap()
}
/// Closes and removes the temporary directory, returing a `Result`.
///
/// Although `TempDir` removes the directory on drop, in the destructor
/// any errors are ignored. To detect errors cleaning up the temporary
/// directory, call `close` instead.
///
/// # Errors
///
/// This function may return a variety of [`std::io::Error`]s that result from deleting
/// the files and directories contained with the temporary directory,
/// as well as from deleting the temporary directory itself. These errors
/// may be platform specific.
///
/// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempdir::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of `std::env::temp_dir()`, named with
/// // the prefix, "example".
/// let tmp_dir = TempDir::new("example")?;
/// let file_path = tmp_dir.path().join("my-temporary-note.txt");
/// let mut tmp_file = File::create(file_path)?;
/// writeln!(tmp_file, "Brian was here. Briefly.")?;
///
/// // By closing the `TempDir` explicitly we can check that it has
/// // been deleted successfully. If we don't close it explicitly,
/// // the directory will still be deleted when `tmp_dir` goes out
/// // of scope, but we won't know whether deleting the directory
/// // succeeded.
/// drop(tmp_file);
/// tmp_dir.close()?;
/// # Ok(())
/// # }
/// ```
pub fn close(mut self) -> io::Result<()> {
let result = remove_dir_all(self.path());
// Prevent the Drop impl from removing the dir a second time.
self.path = None;
result
}
}
impl AsRef<Path> for TempDir {
fn as_ref(&self) -> &Path {
self.path()
}
}
impl fmt::Debug for TempDir {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TempDir")
.field("path", &self.path())
.finish()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
// Path is `None` if `close()` or `into_path()` has been called.
if let Some(ref p) = self.path {
let _ = remove_dir_all(p);
}
}
}
// the tests for this module need to change the path using change_dir,
// and this doesn't play nicely with other tests so these unit tests are located
// in src/test/run-pass/tempfile.rs
|
//! Parse Postgres service configuration files
//!
//! [Postgres service files](https://www.postgresql.org/docs/current/libpq-pgservice.html)
//! are configuration files that contain connection parameters
//!
//! # Example
//!
//! ```rust
//! # fn _norun() {
//! postgres_service::load_connect_params("mydb")
//! .expect("reading postgres service")
//! .user("username") // optionally override the username
//! .connect(postgres::NoTls)
//! .expect("connecting to postgres");
//! # }
//! ```
use ini::Properties;
fn build_from_section(section: &Properties) -> tokio_postgres::config::Config {
let mut username: Option<String> = None;
let mut password: Option<String> = None;
let mut builder = tokio_postgres::config::Config::new();
let mut options = String::new();
for (k, v) in section.iter() {
match k {
"host" => {
builder.host(v);
}
"hostaddr" => {
builder.host(v);
}
"port" => {
builder.port(v.parse().unwrap());
}
"dbname" => {
builder.dbname(v);
}
"user" => username = Some(v.to_owned()),
"password" => password = Some(v.to_owned()),
_ => options += &format!("{}={} ", k, v),
}
}
if !options.is_empty() {
builder.options(&options);
}
if let Some(username) = username {
builder.user(&username);
}
if let Some(password) = password {
builder.password(&password);
}
builder
}
/// Load connection parameters for the named Postgresql service
pub fn load_connect_params(service_name: &str) -> Option<postgres::config::Config> {
tokio::load_connect_params(service_name).map(Into::into)
}
/// For use with tokio-postgres
pub mod tokio {
use crate::build_from_section;
use ini::Ini;
/// Load connection parameters for the named Postgresql service
pub fn load_connect_params(service_name: &str) -> Option<tokio_postgres::config::Config> {
if let Ok(home) = std::env::var("HOME") {
if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf") {
if let Some(section) = ini.section(Some(service_name.clone())) {
return Some(build_from_section(section));
}
}
}
let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into());
if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") {
if let Some(section) = ini.section(Some(service_name)) {
return Some(build_from_section(section));
}
}
None
}
}
|
// compile-flags: --emit=link
// no-prefer-dynamic
#![crate_type = "proc-macro"]
#![feature(repr128, proc_macro_hygiene, proc_macro_quote)]
#![allow(clippy::useless_conversion)]
extern crate proc_macro;
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::parse_macro_input;
use syn::{parse_quote, ItemTrait, TraitItem};
#[proc_macro_attribute]
pub fn fake_async_trait(_args: TokenStream, input: TokenStream) -> TokenStream {
let mut item = parse_macro_input!(input as ItemTrait);
for inner in &mut item.items {
if let TraitItem::Method(method) = inner {
let sig = &method.sig;
let block = &mut method.default;
if let Some(block) = block {
let brace = block.brace_token;
let my_block = quote_spanned!( brace.span => {
// Should not trigger `empty_line_after_outer_attr`
#[crate_type = "lib"]
#sig #block
Vec::new()
});
*block = parse_quote!(#my_block);
}
}
}
TokenStream::from(quote!(#item))
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
pub(crate) struct JoinHandles<'terminate, T: 'terminate + Terminate>
{
join_handles: Vec<JoinHandle<()>>,
terminate: &'terminate T,
}
impl<'terminate, T: 'terminate + Terminate> Drop for JoinHandles<'terminate, T>
{
#[inline(always)]
fn drop(&mut self)
{
for join_handle in self.join_handles.drain(..)
{
if let Err(panic_information) = join_handle.join()
{
self.terminate.begin_termination_due_to_irrecoverable_error(&panic_information)
}
}
}
}
impl<'terminate, T: 'terminate + Terminate> JoinHandles<'terminate, T>
{
#[inline(always)]
pub(crate) fn new(logical_cores: &LogicalCores, terminate: &'terminate T) -> Self
{
Self
{
join_handles: Vec::with_capacity(logical_cores.len()),
terminate,
}
}
#[inline(always)]
pub(crate) fn push(&mut self, join_handle: JoinHandle<()>)
{
self.join_handles.push(join_handle)
}
}
|
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
fn main() {
run();
}
fn run() {
let start = std::time::Instant::now();
// code goes here
let mut limit: u64 = 600_851_475_143;
let mut res = 2;
while res * res <= limit {
while limit % res == 0 {
limit /= res;
}
res += 1;
}
if limit > res {
res = limit;
}
let span = start.elapsed().as_nanos();
println!("{} {}", res, span);
}
|
//! Conversions between Rust and standard **SQL** types.
//!
//! # Types
//!
//! | Rust type | SQL type(s) |
//! |---------------------------------------|------------------------------------------------------|
//! | `bool` | BOOLEAN |
//! | `i16` | SMALLINT |
//! | `i32` | INT |
//! | `i64` | BIGINT |
//! | `f32` | FLOAT |
//! | `f64` | DOUBLE |
//! | `&str`, [`String`] | VARCHAR, CHAR, TEXT |
//!
//! # Nullable
//!
//! In addition, `Option<T>` is supported where `T` implements `Type`. An `Option<T>` represents
//! a potentially `NULL` value from SQL.
//!
// Type
impl_any_type!(bool);
impl_any_type!(i16);
impl_any_type!(i32);
impl_any_type!(i64);
impl_any_type!(f32);
impl_any_type!(f64);
impl_any_type!(str);
impl_any_type!(String);
// Encode
impl_any_encode!(bool);
impl_any_encode!(i16);
impl_any_encode!(i32);
impl_any_encode!(i64);
impl_any_encode!(f32);
impl_any_encode!(f64);
impl_any_encode!(&'q str);
impl_any_encode!(String);
// Decode
impl_any_decode!(bool);
impl_any_decode!(i16);
impl_any_decode!(i32);
impl_any_decode!(i64);
impl_any_decode!(f32);
impl_any_decode!(f64);
impl_any_decode!(&'r str);
impl_any_decode!(String);
// Conversions for Blob SQL types
// Type
#[cfg(all(
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_type!([u8]);
#[cfg(all(
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_type!(Vec<u8>);
// Encode
#[cfg(all(
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_encode!(&'q [u8]);
#[cfg(all(
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_encode!(Vec<u8>);
// Decode
#[cfg(all(
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_decode!(&'r [u8]);
#[cfg(all(
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_decode!(Vec<u8>);
// Conversions for Time SQL types
// Type
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_type!(chrono::NaiveDate);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_type!(chrono::NaiveTime);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_type!(chrono::NaiveDateTime);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_type!(chrono::DateTime<chrono::offset::Utc>);
#[cfg(all(
feature = "chrono",
any(feature = "sqlite", feature = "postgres", feature = "mysql"),
not(feature = "mssql")
))]
impl_any_type!(chrono::DateTime<chrono::offset::Local>);
// Encode
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_encode!(chrono::NaiveDate);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_encode!(chrono::NaiveTime);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_encode!(chrono::NaiveDateTime);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_encode!(chrono::DateTime<chrono::offset::Utc>);
#[cfg(all(
feature = "chrono",
any(feature = "sqlite", feature = "postgres", feature = "mysql"),
not(feature = "mssql")
))]
impl_any_encode!(chrono::DateTime<chrono::offset::Local>);
// Decode
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_decode!(chrono::NaiveDate);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_decode!(chrono::NaiveTime);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_decode!(chrono::NaiveDateTime);
#[cfg(all(
feature = "chrono",
any(feature = "mysql", feature = "sqlite", feature = "postgres"),
not(feature = "mssql")
))]
impl_any_decode!(chrono::DateTime<chrono::offset::Utc>);
#[cfg(all(
feature = "chrono",
any(feature = "sqlite", feature = "postgres", feature = "mysql"),
not(feature = "mssql")
))]
impl_any_decode!(chrono::DateTime<chrono::offset::Local>);
|
use toml_edit::Document;
fn main() {
let args = libtest_mimic::Arguments::from_args();
let tests = toml_test_data::invalid()
.map(|case| {
libtest_mimic::Trial::test(case.name.display().to_string(), || {
let expect_path =
std::path::Path::new("tests/fixtures").join(case.name.with_extension("stderr"));
let err = match run_case(case.fixture) {
Ok(()) => "".to_owned(),
Err(err) => err,
};
snapbox::assert_eq_path(expect_path, err);
Ok(())
})
})
.collect();
libtest_mimic::run(&args, tests).exit()
}
fn run_case(input: &[u8]) -> Result<(), String> {
let raw = std::str::from_utf8(input).map_err(|e| e.to_string())?;
let _ = raw.parse::<Document>().map_err(|e| e.to_string())?;
Ok(())
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::borrow::BorrowMut;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::ColumnBuilder;
use common_expression::DataBlock;
use common_functions::aggregates::StateAddr;
use common_hashtable::HashtableEntryMutRefLike;
use common_hashtable::HashtableEntryRefLike;
use common_hashtable::HashtableLike;
use common_pipeline_core::processors::port::InputPort;
use common_pipeline_core::processors::port::OutputPort;
use common_pipeline_core::processors::processor::ProcessorPtr;
use common_pipeline_transforms::processors::transforms::BlockMetaTransform;
use common_pipeline_transforms::processors::transforms::BlockMetaTransformer;
use crate::pipelines::processors::transforms::aggregator::aggregate_cell::AggregateHashTableDropper;
use crate::pipelines::processors::transforms::aggregator::aggregate_meta::AggregateMeta;
use crate::pipelines::processors::transforms::aggregator::estimated_key_size;
use crate::pipelines::processors::transforms::group_by::GroupColumnsBuilder;
use crate::pipelines::processors::transforms::group_by::HashMethodBounds;
use crate::pipelines::processors::transforms::group_by::KeysColumnIter;
use crate::pipelines::processors::transforms::HashTableCell;
use crate::pipelines::processors::AggregatorParams;
pub struct TransformFinalAggregate<Method: HashMethodBounds> {
method: Method,
params: Arc<AggregatorParams>,
}
impl<Method: HashMethodBounds> TransformFinalAggregate<Method> {
pub fn try_create(
input: Arc<InputPort>,
output: Arc<OutputPort>,
method: Method,
params: Arc<AggregatorParams>,
) -> Result<ProcessorPtr> {
Ok(ProcessorPtr::create(BlockMetaTransformer::create(
input,
output,
TransformFinalAggregate::<Method> { method, params },
)))
}
}
impl<Method> BlockMetaTransform<AggregateMeta<Method, usize>> for TransformFinalAggregate<Method>
where Method: HashMethodBounds
{
const NAME: &'static str = "TransformFinalAggregate";
fn transform(&mut self, meta: AggregateMeta<Method, usize>) -> Result<DataBlock> {
if let AggregateMeta::Partitioned { bucket, data } = meta {
let mut reach_limit = false;
let hashtable = self.method.create_hash_table::<usize>()?;
let _dropper = AggregateHashTableDropper::create(self.params.clone());
let mut hash_cell = HashTableCell::<Method, usize>::create(hashtable, _dropper);
let temp_place = self.params.alloc_layout(&mut hash_cell.arena);
hash_cell.temp_values.push(temp_place.addr());
for bucket_data in data {
match bucket_data {
AggregateMeta::Spilled(_) => unreachable!(),
AggregateMeta::Spilling(_) => unreachable!(),
AggregateMeta::Partitioned { .. } => unreachable!(),
AggregateMeta::Serialized(payload) => {
debug_assert!(bucket == payload.bucket);
let aggregate_function_len = self.params.aggregate_functions.len();
let column = payload.get_group_by_column();
let keys_iter = self.method.keys_iter_from_column(column)?;
// first state places of current block
let places = {
let keys_iter = keys_iter.iter();
let (len, _) = keys_iter.size_hint();
let mut places = Vec::with_capacity(len);
let mut current_len = hash_cell.hashtable.len();
unsafe {
for (row, key) in keys_iter.enumerate() {
if reach_limit {
let entry = hash_cell.hashtable.entry(key);
if let Some(entry) = entry {
let place = Into::<StateAddr>::into(*entry.get());
places.push((row, place));
}
continue;
}
match hash_cell.hashtable.insert_and_entry(key) {
Ok(mut entry) => {
let place =
self.params.alloc_layout(&mut hash_cell.arena);
places.push((row, place));
*entry.get_mut() = place.addr();
if let Some(limit) = self.params.limit {
current_len += 1;
if current_len >= limit {
reach_limit = true;
}
}
}
Err(entry) => {
let place = Into::<StateAddr>::into(*entry.get());
places.push((row, place));
}
}
}
}
places
};
let states_columns = (0..aggregate_function_len)
.map(|i| payload.data_block.get_by_offset(i))
.collect::<Vec<_>>();
let mut states_binary_columns = Vec::with_capacity(states_columns.len());
for agg in states_columns.iter().take(aggregate_function_len) {
let aggr_column =
agg.value.as_column().unwrap().as_string().ok_or_else(|| {
ErrorCode::IllegalDataType(format!(
"Aggregation column should be StringType, but got {:?}",
agg.value
))
})?;
states_binary_columns.push(aggr_column);
}
let aggregate_functions = &self.params.aggregate_functions;
let offsets_aggregate_states = &self.params.offsets_aggregate_states;
for (row, place) in places.iter() {
for (idx, aggregate_function) in aggregate_functions.iter().enumerate()
{
let final_place = place.next(offsets_aggregate_states[idx]);
let state_place = temp_place.next(offsets_aggregate_states[idx]);
let mut data =
unsafe { states_binary_columns[idx].index_unchecked(*row) };
aggregate_function.deserialize(state_place, &mut data)?;
aggregate_function.merge(final_place, state_place)?;
}
}
}
AggregateMeta::HashTable(payload) => unsafe {
debug_assert!(bucket == payload.bucket);
let aggregate_functions = &self.params.aggregate_functions;
let offsets_aggregate_states = &self.params.offsets_aggregate_states;
for entry in payload.cell.hashtable.iter() {
let place = match hash_cell.hashtable.insert(entry.key()) {
Err(place) => StateAddr::new(*place),
Ok(entry) => {
let place = self.params.alloc_layout(&mut hash_cell.arena);
entry.write(place.addr());
place
}
};
let old_place = StateAddr::new(*entry.get());
for (idx, aggregate_function) in aggregate_functions.iter().enumerate()
{
let final_place = place.next(offsets_aggregate_states[idx]);
let state_place = old_place.next(offsets_aggregate_states[idx]);
aggregate_function.merge(final_place, state_place)?;
}
}
},
}
}
let keys_len = hash_cell.hashtable.len();
let value_size = estimated_key_size(&hash_cell.hashtable);
let mut group_columns_builder =
self.method
.group_columns_builder(keys_len, value_size, &self.params);
let aggregate_functions = &self.params.aggregate_functions;
let offsets_aggregate_states = &self.params.offsets_aggregate_states;
let mut aggregates_column_builder = {
let mut values = vec![];
for aggregate_function in aggregate_functions {
let data_type = aggregate_function.return_type()?;
let builder = ColumnBuilder::with_capacity(&data_type, keys_len);
values.push(builder)
}
values
};
let mut places = Vec::with_capacity(keys_len);
for group_entity in hash_cell.hashtable.iter() {
places.push(StateAddr::new(*group_entity.get()));
group_columns_builder.append_value(group_entity.key());
}
for (idx, aggregate_function) in aggregate_functions.iter().enumerate() {
let builder = aggregates_column_builder[idx].borrow_mut();
if idx > 0 {
for place in places.iter_mut() {
*place = place.next(
offsets_aggregate_states[idx] - offsets_aggregate_states[idx - 1],
);
}
}
aggregate_function.batch_merge_result(&places, builder)?;
}
// Build final state block.
let mut columns = aggregates_column_builder
.into_iter()
.map(|builder| builder.build())
.collect::<Vec<_>>();
let group_columns = group_columns_builder.finish()?;
columns.extend_from_slice(&group_columns);
return Ok(DataBlock::new_from_columns(columns));
}
Err(ErrorCode::Internal(
"TransformFinalAggregate only recv AggregateMeta::Partitioned",
))
}
}
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z borrowck=compare
pub fn main(){
let maybe = Some(vec![true, true]);
loop {
if let Some(thing) = maybe {
}
//~^^ ERROR use of partially moved value: `maybe` (Ast) [E0382]
//~| ERROR use of moved value: `(maybe as std::prelude::v1::Some).0` (Ast) [E0382]
//~| ERROR use of moved value: `maybe` (Mir) [E0382]
//~| ERROR use of moved value: `maybe` (Mir) [E0382]
//~| ERROR use of moved value (Mir) [E0382]
//~| ERROR borrow of moved value: `maybe` (Mir) [E0382]
}
}
|
// 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::any::Any;
use std::sync::Arc;
use common_catalog::catalog::StorageDescription;
use common_catalog::plan::DataSourcePlan;
use common_catalog::plan::PartStatistics;
use common_catalog::plan::Partitions;
use common_catalog::plan::PartitionsShuffleKind;
use common_catalog::plan::Projection;
use common_catalog::plan::PushDownInfo;
use common_catalog::table::Table;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use common_expression::BlockEntry;
use common_expression::Column;
use common_expression::DataBlock;
use common_expression::TableSchemaRef;
use common_expression::Value;
use common_meta_app::schema::TableInfo;
use common_pipeline_core::processors::port::OutputPort;
use common_pipeline_core::processors::processor::ProcessorPtr;
use common_pipeline_core::Pipeline;
use common_pipeline_core::SourcePipeBuilder;
use common_pipeline_sources::SyncSource;
use common_pipeline_sources::SyncSourcer;
use crate::RandomPartInfo;
pub struct RandomTable {
table_info: TableInfo,
}
impl RandomTable {
pub fn try_create(table_info: TableInfo) -> Result<Box<dyn Table>> {
Ok(Box::new(Self { table_info }))
}
pub fn description() -> StorageDescription {
StorageDescription {
engine_name: "RANDOM".to_string(),
comment: "RANDOM Storage Engine".to_string(),
..Default::default()
}
}
pub fn generate_random_parts(workers: usize, total: usize) -> Partitions {
let part_size = total / workers;
let mut part_remain = total % workers;
let mut partitions = Vec::with_capacity(workers);
if part_size == 0 {
partitions.push(RandomPartInfo::create(total));
} else {
for _ in 0..workers {
let rows = if part_remain > 0 {
part_remain -= 1;
part_size + 1
} else {
part_size
};
partitions.push(RandomPartInfo::create(rows));
}
}
Partitions::create_nolazy(PartitionsShuffleKind::Seq, partitions)
}
}
#[async_trait::async_trait]
impl Table for RandomTable {
fn as_any(&self) -> &dyn Any {
self
}
fn get_table_info(&self) -> &TableInfo {
&self.table_info
}
async fn read_partitions(
&self,
ctx: Arc<dyn TableContext>,
push_downs: Option<PushDownInfo>,
) -> Result<(PartStatistics, Partitions)> {
let settings = ctx.get_settings();
let block_size = settings.get_max_block_size()? as usize;
// If extras.push_downs is None or extras.push_down.limit is None,
// set limit to `max_block_size`.
let (schema, total_rows) = match push_downs {
Some(push_downs) => {
let mut schema = self.schema();
if let Some(projection) = push_downs.projection {
// do projection on schema
schema = match projection {
Projection::Columns(indices) => Arc::new(schema.project(&indices)),
Projection::InnerColumns(path_indices) => {
Arc::new(schema.inner_project(&path_indices))
}
};
}
let limit = match push_downs.limit {
Some(limit) => limit,
None => block_size,
};
(schema, limit)
}
None => (self.schema(), block_size),
};
// generate one row to estimate the bytes size.
let columns = schema
.fields()
.iter()
.map(|f| {
let data_type = f.data_type().into();
BlockEntry {
value: Value::Column(Column::random(&data_type, 1)),
data_type,
}
})
.collect::<Vec<_>>();
let block = DataBlock::new(columns, 1);
let one_row_bytes = block.memory_size();
let read_bytes = total_rows * one_row_bytes;
let parts_num = (total_rows / block_size) + 1;
let statistics = PartStatistics::new_exact(total_rows, read_bytes, parts_num, parts_num);
let mut worker_num = settings.get_max_threads()? as usize;
if worker_num > parts_num {
worker_num = parts_num;
}
let parts = Self::generate_random_parts(worker_num, total_rows);
Ok((statistics, parts))
}
fn benefit_column_prune(&self) -> bool {
true
}
fn read_data(
&self,
ctx: Arc<dyn TableContext>,
plan: &DataSourcePlan,
pipeline: &mut Pipeline,
) -> Result<()> {
let mut output_schema = self.table_info.schema();
let push_downs = plan.push_downs.clone();
if let Some(extras) = push_downs {
if let Some(projection) = extras.projection {
// do projection on schema
output_schema = match projection {
Projection::Columns(indices) => Arc::new(output_schema.project(&indices)),
Projection::InnerColumns(path_indices) => {
Arc::new(output_schema.inner_project(&path_indices))
}
};
}
}
let mut builder = SourcePipeBuilder::create();
for index in 0..plan.parts.len() {
let output = OutputPort::create();
let parts = RandomPartInfo::from_part(&plan.parts.partitions[index])?;
builder.add_source(
output.clone(),
RandomSource::create(ctx.clone(), output, output_schema.clone(), parts.rows)?,
);
}
pipeline.add_pipe(builder.finalize());
Ok(())
}
}
struct RandomSource {
schema: TableSchemaRef,
/// how many rows are needed to generate
rows: usize,
}
impl RandomSource {
pub fn create(
ctx: Arc<dyn TableContext>,
output: Arc<OutputPort>,
schema: TableSchemaRef,
rows: usize,
) -> Result<ProcessorPtr> {
SyncSourcer::create(ctx, output, RandomSource { schema, rows })
}
}
impl SyncSource for RandomSource {
const NAME: &'static str = "RandomTable";
fn generate(&mut self) -> Result<Option<DataBlock>> {
if self.rows == 0 {
// No more row is needed to generate.
return Ok(None);
}
let columns = self
.schema
.fields()
.iter()
.map(|f| {
let data_type = f.data_type().into();
BlockEntry {
value: Value::Column(Column::random(&data_type, self.rows)),
data_type,
}
})
.collect();
// The partition guarantees the number of rows is less than or equal to `max_block_size`.
// And we generate all the `self.rows` at once.
let num_rows = self.rows;
self.rows = 0;
Ok(Some(DataBlock::new(columns, num_rows)))
}
}
|
pub trait Messenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: 'a + Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where
T: Messenger,
{
pub fn new(messenger: &T, max: usize) -> LimitTracker<T> {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 0.75 && percentage_of_max < 0.9 {
self.messenger
.send("Warning: You've used up 75% of your quota!");
} else if percentage_of_max >= 0.9 && percentage_of_max < 1.0 {
self.messenger
.send("Urgent warning: Your've used up over 90% of your quota!");
} else if percentage_of_max >= 1.0 {
self.messenger.send("Error: Your are over your quota!");
}
}
}
#[cfg(test)]
mod tests {
use crate::{LimitTracker, Messenger};
use std::cell::RefCell;
struct MockMessenger {
// RefCell<T> 在运行时记录借用
// 当创建不可变和可变引用时,我们分别使用 & 和 &mut 语法,
// 对于 RefCell<T> 来说则是 borrow 和 borrow_mut 方法,这属于 RefCell<T> 安全API的一部分
// RefCell 记录当前有多少个活动的 Ref<T> 和 RefMut<T> 智能指针,
// 每次调用 borrow 则 RefCell<T> 将 Ref<T> 的引用计数加一,当 Ref<T> 离开作用域时减一
// RefCell<T> 在任何时刻只允许 一个可变的借用 或者是 多个不可变的借用(即读/写的scope要隔离)
// 如果违反上述规则,RefCell<T> 的实现会在运行时 panic!
send_messages: RefCell<Vec<String>>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
send_messages: RefCell::new(vec![]),
}
}
}
impl Messenger for MockMessenger {
fn send(&self, msg: &str) {
// borrow_mut 方法返回 RefMut 类型的智能指针
// Ref 和 RefMut 都实现了 Deref trait 所以可以当做常规引用对待
self.send_messages.borrow_mut().push(String::from(msg));
//let mut one_borrow = self.send_messages.borrow_mut();
//let mut two_borrow = self.send_messages.borrow_mut();
//one_borrow.push(String::from(msg));
//two_borrow.push(String::from(msg));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
let mock_messenger = MockMessenger::new();
let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);
limit_tracker.set_value(80);
// borrow 方法返回 Ref 类型的智能指针
assert_eq!(mock_messenger.send_messages.borrow().len(), 1);
}
}
|
//! The quicksilver tutorials, generated through Rustdoc
//!
//! While this isn't a traditional way of hosting a tutorial, Rustdoc ensures that all the code in
//! the tutorials is checked when CI runs, keeping it nice and up-to-date.
//!
//! Before you jump into the tutorials below, make sure your development environment is ready. If
//! you're just targeting desktop, all you need is the latest stable Rust. If you're targeting the
//! web, make sure you install cargo-web first (cargo install -f cargo-web).
pub mod _01_basic;
pub mod _02_drawing;
pub mod _03_input;
pub mod _04_lifecycle;
pub mod _05_images;
pub mod _06_asset_combinators;
pub mod _07_font;
pub mod _08_sound;
pub mod _09_animations_and_atlases;
pub mod _10_views;
pub mod _11_mesh;
|
pub use self::game::Game;
pub use self::context::{ UpdateContext as UContext, DrawingContext as DContext };
pub mod game;
pub mod operation;
mod context;
mod object;
mod player;
mod camera;
mod world;
mod input_state;
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAnnotationProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAnnotationProvider {
type Vtable = IAnnotationProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x95ba1417_4437_451b_9461_050a49b59d06);
}
impl IAnnotationProvider {
pub fn AnnotationTypeId(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn AnnotationTypeName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Author(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DateTime(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Target(&self) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IAnnotationProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{95ba1417-4437-451b-9461-050a49b59d06}");
}
impl ::core::convert::From<IAnnotationProvider> for ::windows::core::IUnknown {
fn from(value: IAnnotationProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IAnnotationProvider> for ::windows::core::IUnknown {
fn from(value: &IAnnotationProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAnnotationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAnnotationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IAnnotationProvider> for ::windows::core::IInspectable {
fn from(value: IAnnotationProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IAnnotationProvider> for ::windows::core::IInspectable {
fn from(value: &IAnnotationProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IAnnotationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IAnnotationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAnnotationProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ICustomNavigationProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICustomNavigationProvider {
type Vtable = ICustomNavigationProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2bd8a6d0_2fa3_4717_b28c_4917ce54928d);
}
impl ICustomNavigationProvider {
#[cfg(feature = "UI_Xaml_Automation_Peers")]
pub fn NavigateCustom(&self, direction: super::Peers::AutomationNavigationDirection) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), direction, &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ICustomNavigationProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{2bd8a6d0-2fa3-4717-b28c-4917ce54928d}");
}
impl ::core::convert::From<ICustomNavigationProvider> for ::windows::core::IUnknown {
fn from(value: ICustomNavigationProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ICustomNavigationProvider> for ::windows::core::IUnknown {
fn from(value: &ICustomNavigationProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICustomNavigationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ICustomNavigationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ICustomNavigationProvider> for ::windows::core::IInspectable {
fn from(value: ICustomNavigationProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ICustomNavigationProvider> for ::windows::core::IInspectable {
fn from(value: &ICustomNavigationProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ICustomNavigationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ICustomNavigationProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ICustomNavigationProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, direction: super::Peers::AutomationNavigationDirection, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDockProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDockProvider {
type Vtable = IDockProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x48c243f8_78b1_44a0_ac5f_750757bcde3c);
}
impl IDockProvider {
pub fn DockPosition(&self) -> ::windows::core::Result<super::DockPosition> {
let this = self;
unsafe {
let mut result__: super::DockPosition = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DockPosition>(result__)
}
}
pub fn SetDockPosition(&self, dockposition: super::DockPosition) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), dockposition).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IDockProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{48c243f8-78b1-44a0-ac5f-750757bcde3c}");
}
impl ::core::convert::From<IDockProvider> for ::windows::core::IUnknown {
fn from(value: IDockProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IDockProvider> for ::windows::core::IUnknown {
fn from(value: &IDockProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDockProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDockProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IDockProvider> for ::windows::core::IInspectable {
fn from(value: IDockProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IDockProvider> for ::windows::core::IInspectable {
fn from(value: &IDockProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IDockProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IDockProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDockProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::DockPosition) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dockposition: super::DockPosition) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDragProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDragProvider {
type Vtable = IDragProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2e7786a9_7ffc_4f57_b965_1ef1f373f546);
}
impl IDragProvider {
pub fn IsGrabbed(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn DropEffect(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DropEffects(&self) -> ::windows::core::Result<::windows::core::Array<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<::windows::core::HSTRING>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetGrabbedItems(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IDragProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{2e7786a9-7ffc-4f57-b965-1ef1f373f546}");
}
impl ::core::convert::From<IDragProvider> for ::windows::core::IUnknown {
fn from(value: IDragProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IDragProvider> for ::windows::core::IUnknown {
fn from(value: &IDragProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDragProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDragProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IDragProvider> for ::windows::core::IInspectable {
fn from(value: IDragProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IDragProvider> for ::windows::core::IInspectable {
fn from(value: &IDragProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IDragProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IDragProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDragProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDropTargetProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDropTargetProvider {
type Vtable = IDropTargetProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a245bdd_b458_4fe0_98c8_aac89df56d61);
}
impl IDropTargetProvider {
pub fn DropEffect(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DropEffects(&self) -> ::windows::core::Result<::windows::core::Array<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<::windows::core::HSTRING>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IDropTargetProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{7a245bdd-b458-4fe0-98c8-aac89df56d61}");
}
impl ::core::convert::From<IDropTargetProvider> for ::windows::core::IUnknown {
fn from(value: IDropTargetProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IDropTargetProvider> for ::windows::core::IUnknown {
fn from(value: &IDropTargetProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDropTargetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDropTargetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IDropTargetProvider> for ::windows::core::IInspectable {
fn from(value: IDropTargetProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IDropTargetProvider> for ::windows::core::IInspectable {
fn from(value: &IDropTargetProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IDropTargetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IDropTargetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDropTargetProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IExpandCollapseProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IExpandCollapseProvider {
type Vtable = IExpandCollapseProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49ac8399_d626_4543_94b9_a6d9a9593af6);
}
impl IExpandCollapseProvider {
pub fn ExpandCollapseState(&self) -> ::windows::core::Result<super::ExpandCollapseState> {
let this = self;
unsafe {
let mut result__: super::ExpandCollapseState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::ExpandCollapseState>(result__)
}
}
pub fn Collapse(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Expand(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IExpandCollapseProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{49ac8399-d626-4543-94b9-a6d9a9593af6}");
}
impl ::core::convert::From<IExpandCollapseProvider> for ::windows::core::IUnknown {
fn from(value: IExpandCollapseProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IExpandCollapseProvider> for ::windows::core::IUnknown {
fn from(value: &IExpandCollapseProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IExpandCollapseProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IExpandCollapseProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IExpandCollapseProvider> for ::windows::core::IInspectable {
fn from(value: IExpandCollapseProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IExpandCollapseProvider> for ::windows::core::IInspectable {
fn from(value: &IExpandCollapseProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IExpandCollapseProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IExpandCollapseProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IExpandCollapseProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::ExpandCollapseState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IGridItemProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGridItemProvider {
type Vtable = IGridItemProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfff3683c_7407_45bb_a936_df3ed6d3837d);
}
impl IGridItemProvider {
pub fn Column(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn ColumnSpan(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn ContainingGrid(&self) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
pub fn Row(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn RowSpan(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IGridItemProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{fff3683c-7407-45bb-a936-df3ed6d3837d}");
}
impl ::core::convert::From<IGridItemProvider> for ::windows::core::IUnknown {
fn from(value: IGridItemProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IGridItemProvider> for ::windows::core::IUnknown {
fn from(value: &IGridItemProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IGridItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IGridItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IGridItemProvider> for ::windows::core::IInspectable {
fn from(value: IGridItemProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IGridItemProvider> for ::windows::core::IInspectable {
fn from(value: &IGridItemProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IGridItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IGridItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IGridItemProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IGridProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGridProvider {
type Vtable = IGridProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8b62b7a0_932c_4490_9a13_02fdb39a8f5b);
}
impl IGridProvider {
pub fn ColumnCount(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn RowCount(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn GetItem(&self, row: i32, column: i32) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), row, column, &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IGridProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{8b62b7a0-932c-4490-9a13-02fdb39a8f5b}");
}
impl ::core::convert::From<IGridProvider> for ::windows::core::IUnknown {
fn from(value: IGridProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IGridProvider> for ::windows::core::IUnknown {
fn from(value: &IGridProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IGridProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IGridProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IGridProvider> for ::windows::core::IInspectable {
fn from(value: IGridProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IGridProvider> for ::windows::core::IInspectable {
fn from(value: &IGridProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IGridProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IGridProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IGridProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, row: i32, column: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IIRawElementProviderSimple(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IIRawElementProviderSimple {
type Vtable = IIRawElementProviderSimple_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xec752224_9b77_4720_bb21_4ac89fdb1afd);
}
#[repr(C)]
#[doc(hidden)]
pub struct IIRawElementProviderSimple_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,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IInvokeProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IInvokeProvider {
type Vtable = IInvokeProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf7d1a187_b13c_4540_b09e_6778e2dc9ba5);
}
impl IInvokeProvider {
pub fn Invoke(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IInvokeProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{f7d1a187-b13c-4540-b09e-6778e2dc9ba5}");
}
impl ::core::convert::From<IInvokeProvider> for ::windows::core::IUnknown {
fn from(value: IInvokeProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IInvokeProvider> for ::windows::core::IUnknown {
fn from(value: &IInvokeProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IInvokeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IInvokeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IInvokeProvider> for ::windows::core::IInspectable {
fn from(value: IInvokeProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IInvokeProvider> for ::windows::core::IInspectable {
fn from(value: &IInvokeProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IInvokeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IInvokeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IInvokeProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IItemContainerProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IItemContainerProvider {
type Vtable = IItemContainerProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef5cd845_e1d4_40f4_bad5_c7fad44a703e);
}
impl IItemContainerProvider {
pub fn FindItemByProperty<'a, Param0: ::windows::core::IntoParam<'a, IRawElementProviderSimple>, Param1: ::windows::core::IntoParam<'a, super::AutomationProperty>, Param2: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, startafter: Param0, automationproperty: Param1, value: Param2) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), startafter.into_param().abi(), automationproperty.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IItemContainerProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ef5cd845-e1d4-40f4-bad5-c7fad44a703e}");
}
impl ::core::convert::From<IItemContainerProvider> for ::windows::core::IUnknown {
fn from(value: IItemContainerProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IItemContainerProvider> for ::windows::core::IUnknown {
fn from(value: &IItemContainerProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IItemContainerProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IItemContainerProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IItemContainerProvider> for ::windows::core::IInspectable {
fn from(value: IItemContainerProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IItemContainerProvider> for ::windows::core::IInspectable {
fn from(value: &IItemContainerProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IItemContainerProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IItemContainerProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IItemContainerProvider_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, startafter: ::windows::core::RawPtr, automationproperty: ::windows::core::RawPtr, value: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMultipleViewProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMultipleViewProvider {
type Vtable = IMultipleViewProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd014e196_0e50_4843_a5d2_c22897c8845a);
}
impl IMultipleViewProvider {
pub fn CurrentView(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn GetSupportedViews(&self) -> ::windows::core::Result<::windows::core::Array<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<i32> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<i32>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetViewName(&self, viewid: i32) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), viewid, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetCurrentView(&self, viewid: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), viewid).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IMultipleViewProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d014e196-0e50-4843-a5d2-c22897c8845a}");
}
impl ::core::convert::From<IMultipleViewProvider> for ::windows::core::IUnknown {
fn from(value: IMultipleViewProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IMultipleViewProvider> for ::windows::core::IUnknown {
fn from(value: &IMultipleViewProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMultipleViewProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMultipleViewProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IMultipleViewProvider> for ::windows::core::IInspectable {
fn from(value: IMultipleViewProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IMultipleViewProvider> for ::windows::core::IInspectable {
fn from(value: &IMultipleViewProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMultipleViewProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IMultipleViewProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMultipleViewProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, viewid: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, viewid: i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IObjectModelProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IObjectModelProvider {
type Vtable = IObjectModelProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc3ca36b9_0793_4ed0_bbf4_9ff4e0f98f80);
}
impl IObjectModelProvider {
pub fn GetUnderlyingObjectModel(&self) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IObjectModelProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{c3ca36b9-0793-4ed0-bbf4-9ff4e0f98f80}");
}
impl ::core::convert::From<IObjectModelProvider> for ::windows::core::IUnknown {
fn from(value: IObjectModelProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IObjectModelProvider> for ::windows::core::IUnknown {
fn from(value: &IObjectModelProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IObjectModelProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IObjectModelProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IObjectModelProvider> for ::windows::core::IInspectable {
fn from(value: IObjectModelProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IObjectModelProvider> for ::windows::core::IInspectable {
fn from(value: &IObjectModelProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IObjectModelProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IObjectModelProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IObjectModelProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IRangeValueProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IRangeValueProvider {
type Vtable = IRangeValueProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x838a34a8_7d5f_4079_af03_c3d015e93413);
}
impl IRangeValueProvider {
pub fn IsReadOnly(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn LargeChange(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn Maximum(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn Minimum(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn SmallChange(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn Value(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn SetValue(&self, value: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IRangeValueProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{838a34a8-7d5f-4079-af03-c3d015e93413}");
}
impl ::core::convert::From<IRangeValueProvider> for ::windows::core::IUnknown {
fn from(value: IRangeValueProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IRangeValueProvider> for ::windows::core::IUnknown {
fn from(value: &IRangeValueProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRangeValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRangeValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IRangeValueProvider> for ::windows::core::IInspectable {
fn from(value: IRangeValueProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IRangeValueProvider> for ::windows::core::IInspectable {
fn from(value: &IRangeValueProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IRangeValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IRangeValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IRangeValueProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IRawElementProviderSimple(pub ::windows::core::IInspectable);
impl IRawElementProviderSimple {}
unsafe impl ::windows::core::RuntimeType for IRawElementProviderSimple {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.Provider.IRawElementProviderSimple;{ec752224-9b77-4720-bb21-4ac89fdb1afd})");
}
unsafe impl ::windows::core::Interface for IRawElementProviderSimple {
type Vtable = IIRawElementProviderSimple_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xec752224_9b77_4720_bb21_4ac89fdb1afd);
}
impl ::windows::core::RuntimeName for IRawElementProviderSimple {
const NAME: &'static str = "Windows.UI.Xaml.Automation.Provider.IRawElementProviderSimple";
}
impl ::core::convert::From<IRawElementProviderSimple> for ::windows::core::IUnknown {
fn from(value: IRawElementProviderSimple) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IRawElementProviderSimple> for ::windows::core::IUnknown {
fn from(value: &IRawElementProviderSimple) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRawElementProviderSimple {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRawElementProviderSimple {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IRawElementProviderSimple> for ::windows::core::IInspectable {
fn from(value: IRawElementProviderSimple) -> Self {
value.0
}
}
impl ::core::convert::From<&IRawElementProviderSimple> for ::windows::core::IInspectable {
fn from(value: &IRawElementProviderSimple) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IRawElementProviderSimple {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IRawElementProviderSimple {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IRawElementProviderSimple> for super::super::DependencyObject {
fn from(value: IRawElementProviderSimple) -> Self {
::core::convert::Into::<super::super::DependencyObject>::into(&value)
}
}
impl ::core::convert::From<&IRawElementProviderSimple> for super::super::DependencyObject {
fn from(value: &IRawElementProviderSimple) -> Self {
::windows::core::Interface::cast(value).unwrap()
}
}
impl<'a> ::windows::core::IntoParam<'a, super::super::DependencyObject> for IRawElementProviderSimple {
fn into_param(self) -> ::windows::core::Param<'a, super::super::DependencyObject> {
::windows::core::Param::Owned(::core::convert::Into::<super::super::DependencyObject>::into(self))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::super::DependencyObject> for &IRawElementProviderSimple {
fn into_param(self) -> ::windows::core::Param<'a, super::super::DependencyObject> {
::windows::core::Param::Owned(::core::convert::Into::<super::super::DependencyObject>::into(::core::clone::Clone::clone(self)))
}
}
unsafe impl ::core::marker::Send for IRawElementProviderSimple {}
unsafe impl ::core::marker::Sync for IRawElementProviderSimple {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IScrollItemProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IScrollItemProvider {
type Vtable = IScrollItemProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a3ec090_5d2c_4e42_9ee6_9d58db100b55);
}
impl IScrollItemProvider {
pub fn ScrollIntoView(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IScrollItemProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{9a3ec090-5d2c-4e42-9ee6-9d58db100b55}");
}
impl ::core::convert::From<IScrollItemProvider> for ::windows::core::IUnknown {
fn from(value: IScrollItemProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IScrollItemProvider> for ::windows::core::IUnknown {
fn from(value: &IScrollItemProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IScrollItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IScrollItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IScrollItemProvider> for ::windows::core::IInspectable {
fn from(value: IScrollItemProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IScrollItemProvider> for ::windows::core::IInspectable {
fn from(value: &IScrollItemProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IScrollItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IScrollItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IScrollItemProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IScrollProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IScrollProvider {
type Vtable = IScrollProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x374bf581_7716_4bbc_82eb_d997006ea999);
}
impl IScrollProvider {
pub fn HorizontallyScrollable(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn HorizontalScrollPercent(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn HorizontalViewSize(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn VerticallyScrollable(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn VerticalScrollPercent(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn VerticalViewSize(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn Scroll(&self, horizontalamount: super::ScrollAmount, verticalamount: super::ScrollAmount) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), horizontalamount, verticalamount).ok() }
}
pub fn SetScrollPercent(&self, horizontalpercent: f64, verticalpercent: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), horizontalpercent, verticalpercent).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IScrollProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{374bf581-7716-4bbc-82eb-d997006ea999}");
}
impl ::core::convert::From<IScrollProvider> for ::windows::core::IUnknown {
fn from(value: IScrollProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IScrollProvider> for ::windows::core::IUnknown {
fn from(value: &IScrollProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IScrollProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IScrollProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IScrollProvider> for ::windows::core::IInspectable {
fn from(value: IScrollProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IScrollProvider> for ::windows::core::IInspectable {
fn from(value: &IScrollProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IScrollProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IScrollProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IScrollProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, horizontalamount: super::ScrollAmount, verticalamount: super::ScrollAmount) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, horizontalpercent: f64, verticalpercent: f64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISelectionItemProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISelectionItemProvider {
type Vtable = ISelectionItemProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6a4977c1_830d_42d2_bf62_042ebddecc19);
}
impl ISelectionItemProvider {
pub fn IsSelected(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SelectionContainer(&self) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
pub fn AddToSelection(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() }
}
pub fn RemoveFromSelection(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Select(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for ISelectionItemProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{6a4977c1-830d-42d2-bf62-042ebddecc19}");
}
impl ::core::convert::From<ISelectionItemProvider> for ::windows::core::IUnknown {
fn from(value: ISelectionItemProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISelectionItemProvider> for ::windows::core::IUnknown {
fn from(value: &ISelectionItemProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISelectionItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISelectionItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISelectionItemProvider> for ::windows::core::IInspectable {
fn from(value: ISelectionItemProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ISelectionItemProvider> for ::windows::core::IInspectable {
fn from(value: &ISelectionItemProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISelectionItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ISelectionItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISelectionItemProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISelectionProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISelectionProvider {
type Vtable = ISelectionProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f018fca_b944_4395_8de1_88f674af51d3);
}
impl ISelectionProvider {
pub fn CanSelectMultiple(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsSelectionRequired(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetSelection(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ISelectionProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1f018fca-b944-4395-8de1-88f674af51d3}");
}
impl ::core::convert::From<ISelectionProvider> for ::windows::core::IUnknown {
fn from(value: ISelectionProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISelectionProvider> for ::windows::core::IUnknown {
fn from(value: &ISelectionProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISelectionProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISelectionProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISelectionProvider> for ::windows::core::IInspectable {
fn from(value: ISelectionProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ISelectionProvider> for ::windows::core::IInspectable {
fn from(value: &ISelectionProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISelectionProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ISelectionProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISelectionProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISpreadsheetItemProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpreadsheetItemProvider {
type Vtable = ISpreadsheetItemProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xebde8f92_6015_4826_b719_47521a81c67e);
}
impl ISpreadsheetItemProvider {
pub fn Formula(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn GetAnnotationObjects(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetAnnotationTypes(&self) -> ::windows::core::Result<::windows::core::Array<super::AnnotationType>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<super::AnnotationType> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<super::AnnotationType>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ISpreadsheetItemProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ebde8f92-6015-4826-b719-47521a81c67e}");
}
impl ::core::convert::From<ISpreadsheetItemProvider> for ::windows::core::IUnknown {
fn from(value: ISpreadsheetItemProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISpreadsheetItemProvider> for ::windows::core::IUnknown {
fn from(value: &ISpreadsheetItemProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISpreadsheetItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISpreadsheetItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISpreadsheetItemProvider> for ::windows::core::IInspectable {
fn from(value: ISpreadsheetItemProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ISpreadsheetItemProvider> for ::windows::core::IInspectable {
fn from(value: &ISpreadsheetItemProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISpreadsheetItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ISpreadsheetItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpreadsheetItemProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut super::AnnotationType) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISpreadsheetProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpreadsheetProvider {
type Vtable = ISpreadsheetProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x15359093_bd99_4cfd_9f07_3b14b315e23d);
}
impl ISpreadsheetProvider {
pub fn GetItemByName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ISpreadsheetProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{15359093-bd99-4cfd-9f07-3b14b315e23d}");
}
impl ::core::convert::From<ISpreadsheetProvider> for ::windows::core::IUnknown {
fn from(value: ISpreadsheetProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISpreadsheetProvider> for ::windows::core::IUnknown {
fn from(value: &ISpreadsheetProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISpreadsheetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISpreadsheetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISpreadsheetProvider> for ::windows::core::IInspectable {
fn from(value: ISpreadsheetProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ISpreadsheetProvider> for ::windows::core::IInspectable {
fn from(value: &ISpreadsheetProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISpreadsheetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ISpreadsheetProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpreadsheetProvider_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, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IStylesProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IStylesProvider {
type Vtable = IStylesProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1a5b7a17_7c01_4bec_9cd4_2dfa7dc246cd);
}
impl IStylesProvider {
pub fn ExtendedProperties(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FillColor(&self) -> ::windows::core::Result<super::super::super::Color> {
let this = self;
unsafe {
let mut result__: super::super::super::Color = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Color>(result__)
}
}
pub fn FillPatternColor(&self) -> ::windows::core::Result<super::super::super::Color> {
let this = self;
unsafe {
let mut result__: super::super::super::Color = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Color>(result__)
}
}
pub fn FillPatternStyle(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Shape(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn StyleId(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn StyleName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IStylesProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1a5b7a17-7c01-4bec-9cd4-2dfa7dc246cd}");
}
impl ::core::convert::From<IStylesProvider> for ::windows::core::IUnknown {
fn from(value: IStylesProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IStylesProvider> for ::windows::core::IUnknown {
fn from(value: &IStylesProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IStylesProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IStylesProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IStylesProvider> for ::windows::core::IInspectable {
fn from(value: IStylesProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IStylesProvider> for ::windows::core::IInspectable {
fn from(value: &IStylesProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IStylesProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IStylesProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IStylesProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Color) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Color) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISynchronizedInputProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISynchronizedInputProvider {
type Vtable = ISynchronizedInputProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3d60cecb_da54_4aa3_b915_e3244427d4ac);
}
impl ISynchronizedInputProvider {
pub fn Cancel(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
pub fn StartListening(&self, inputtype: super::SynchronizedInputType) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), inputtype).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for ISynchronizedInputProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{3d60cecb-da54-4aa3-b915-e3244427d4ac}");
}
impl ::core::convert::From<ISynchronizedInputProvider> for ::windows::core::IUnknown {
fn from(value: ISynchronizedInputProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISynchronizedInputProvider> for ::windows::core::IUnknown {
fn from(value: &ISynchronizedInputProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISynchronizedInputProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISynchronizedInputProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISynchronizedInputProvider> for ::windows::core::IInspectable {
fn from(value: ISynchronizedInputProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ISynchronizedInputProvider> for ::windows::core::IInspectable {
fn from(value: &ISynchronizedInputProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISynchronizedInputProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ISynchronizedInputProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISynchronizedInputProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputtype: super::SynchronizedInputType) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITableItemProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITableItemProvider {
type Vtable = ITableItemProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3b2c49cd_1de2_4ee2_a3e1_fb553559d15d);
}
impl ITableItemProvider {
pub fn GetColumnHeaderItems(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetRowHeaderItems(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITableItemProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{3b2c49cd-1de2-4ee2-a3e1-fb553559d15d}");
}
impl ::core::convert::From<ITableItemProvider> for ::windows::core::IUnknown {
fn from(value: ITableItemProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITableItemProvider> for ::windows::core::IUnknown {
fn from(value: &ITableItemProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITableItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITableItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITableItemProvider> for ::windows::core::IInspectable {
fn from(value: ITableItemProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITableItemProvider> for ::windows::core::IInspectable {
fn from(value: &ITableItemProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITableItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITableItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITableItemProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITableProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITableProvider {
type Vtable = ITableProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a8ed399_6824_4595_bab3_464bc9a04417);
}
impl ITableProvider {
pub fn RowOrColumnMajor(&self) -> ::windows::core::Result<super::RowOrColumnMajor> {
let this = self;
unsafe {
let mut result__: super::RowOrColumnMajor = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::RowOrColumnMajor>(result__)
}
}
pub fn GetColumnHeaders(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetRowHeaders(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITableProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{7a8ed399-6824-4595-bab3-464bc9a04417}");
}
impl ::core::convert::From<ITableProvider> for ::windows::core::IUnknown {
fn from(value: ITableProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITableProvider> for ::windows::core::IUnknown {
fn from(value: &ITableProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITableProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITableProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITableProvider> for ::windows::core::IInspectable {
fn from(value: ITableProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITableProvider> for ::windows::core::IInspectable {
fn from(value: &ITableProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITableProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITableProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITableProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::RowOrColumnMajor) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITextChildProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITextChildProvider {
type Vtable = ITextChildProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1133c336_a89b_4130_9be6_55e33334f557);
}
impl ITextChildProvider {
pub fn TextContainer(&self) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
pub fn TextRange(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITextChildProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1133c336-a89b-4130-9be6-55e33334f557}");
}
impl ::core::convert::From<ITextChildProvider> for ::windows::core::IUnknown {
fn from(value: ITextChildProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITextChildProvider> for ::windows::core::IUnknown {
fn from(value: &ITextChildProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITextChildProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITextChildProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITextChildProvider> for ::windows::core::IInspectable {
fn from(value: ITextChildProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITextChildProvider> for ::windows::core::IInspectable {
fn from(value: &ITextChildProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITextChildProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITextChildProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITextChildProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITextEditProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITextEditProvider {
type Vtable = ITextEditProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xea3605b4_3a05_400e_b5f9_4e91b40f6176);
}
impl ITextEditProvider {
pub fn GetActiveComposition(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn GetConversionTarget(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn DocumentRange(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn SupportedTextSelection(&self) -> ::windows::core::Result<super::SupportedTextSelection> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: super::SupportedTextSelection = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::SupportedTextSelection>(result__)
}
}
pub fn GetSelection(&self) -> ::windows::core::Result<::windows::core::Array<ITextRangeProvider>> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::Array<ITextRangeProvider> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<ITextRangeProvider>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetVisibleRanges(&self) -> ::windows::core::Result<::windows::core::Array<ITextRangeProvider>> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::Array<ITextRangeProvider> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), ::windows::core::Array::<ITextRangeProvider>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn RangeFromChild<'a, Param0: ::windows::core::IntoParam<'a, IRawElementProviderSimple>>(&self, childelement: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), childelement.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RangeFromPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Point>>(&self, screenlocation: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), screenlocation.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITextEditProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ea3605b4-3a05-400e-b5f9-4e91b40f6176}");
}
impl ::core::convert::From<ITextEditProvider> for ::windows::core::IUnknown {
fn from(value: ITextEditProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITextEditProvider> for ::windows::core::IUnknown {
fn from(value: &ITextEditProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITextEditProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITextEditProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITextEditProvider> for ::windows::core::IInspectable {
fn from(value: ITextEditProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITextEditProvider> for ::windows::core::IInspectable {
fn from(value: &ITextEditProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITextEditProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITextEditProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<ITextEditProvider> for ITextProvider {
type Error = ::windows::core::Error;
fn try_from(value: ITextEditProvider) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ITextEditProvider> for ITextProvider {
type Error = ::windows::core::Error;
fn try_from(value: &ITextEditProvider) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITextProvider> for ITextEditProvider {
fn into_param(self) -> ::windows::core::Param<'a, ITextProvider> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITextProvider> for &ITextEditProvider {
fn into_param(self) -> ::windows::core::Param<'a, ITextProvider> {
::core::convert::TryInto::<ITextProvider>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITextEditProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITextProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITextProvider {
type Vtable = ITextProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdb5bbc9f_4807_4f2a_8678_1b13f3c60e22);
}
impl ITextProvider {
pub fn DocumentRange(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn SupportedTextSelection(&self) -> ::windows::core::Result<super::SupportedTextSelection> {
let this = self;
unsafe {
let mut result__: super::SupportedTextSelection = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::SupportedTextSelection>(result__)
}
}
pub fn GetSelection(&self) -> ::windows::core::Result<::windows::core::Array<ITextRangeProvider>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<ITextRangeProvider> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<ITextRangeProvider>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetVisibleRanges(&self) -> ::windows::core::Result<::windows::core::Array<ITextRangeProvider>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<ITextRangeProvider> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), ::windows::core::Array::<ITextRangeProvider>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn RangeFromChild<'a, Param0: ::windows::core::IntoParam<'a, IRawElementProviderSimple>>(&self, childelement: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), childelement.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RangeFromPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Point>>(&self, screenlocation: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), screenlocation.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITextProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{db5bbc9f-4807-4f2a-8678-1b13f3c60e22}");
}
impl ::core::convert::From<ITextProvider> for ::windows::core::IUnknown {
fn from(value: ITextProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITextProvider> for ::windows::core::IUnknown {
fn from(value: &ITextProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITextProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITextProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITextProvider> for ::windows::core::IInspectable {
fn from(value: ITextProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITextProvider> for ::windows::core::IInspectable {
fn from(value: &ITextProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITextProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITextProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITextProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::SupportedTextSelection) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, childelement: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, screenlocation: super::super::super::super::Foundation::Point, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITextProvider2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITextProvider2 {
type Vtable = ITextProvider2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdf1d48bc_0487_4e7f_9d5e_f09e77e41246);
}
impl ITextProvider2 {
pub fn RangeFromAnnotation<'a, Param0: ::windows::core::IntoParam<'a, IRawElementProviderSimple>>(&self, annotationelement: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), annotationelement.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn GetCaretRange(&self, isactive: &mut bool) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), isactive, &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn DocumentRange(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn SupportedTextSelection(&self) -> ::windows::core::Result<super::SupportedTextSelection> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: super::SupportedTextSelection = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::SupportedTextSelection>(result__)
}
}
pub fn GetSelection(&self) -> ::windows::core::Result<::windows::core::Array<ITextRangeProvider>> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::Array<ITextRangeProvider> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<ITextRangeProvider>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn GetVisibleRanges(&self) -> ::windows::core::Result<::windows::core::Array<ITextRangeProvider>> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::Array<ITextRangeProvider> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), ::windows::core::Array::<ITextRangeProvider>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn RangeFromChild<'a, Param0: ::windows::core::IntoParam<'a, IRawElementProviderSimple>>(&self, childelement: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), childelement.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RangeFromPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Point>>(&self, screenlocation: Param0) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), screenlocation.into_param().abi(), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITextProvider2 {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{df1d48bc-0487-4e7f-9d5e-f09e77e41246}");
}
impl ::core::convert::From<ITextProvider2> for ::windows::core::IUnknown {
fn from(value: ITextProvider2) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITextProvider2> for ::windows::core::IUnknown {
fn from(value: &ITextProvider2) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITextProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITextProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITextProvider2> for ::windows::core::IInspectable {
fn from(value: ITextProvider2) -> Self {
value.0
}
}
impl ::core::convert::From<&ITextProvider2> for ::windows::core::IInspectable {
fn from(value: &ITextProvider2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITextProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITextProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<ITextProvider2> for ITextProvider {
type Error = ::windows::core::Error;
fn try_from(value: ITextProvider2) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ITextProvider2> for ITextProvider {
type Error = ::windows::core::Error;
fn try_from(value: &ITextProvider2) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITextProvider> for ITextProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ITextProvider> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITextProvider> for &ITextProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ITextProvider> {
::core::convert::TryInto::<ITextProvider>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITextProvider2_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, annotationelement: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, isactive: *mut bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITextRangeProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITextRangeProvider {
type Vtable = ITextRangeProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0274688d_06e9_4f66_9446_28a5be98fbd0);
}
impl ITextRangeProvider {
pub fn Clone(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn Compare<'a, Param0: ::windows::core::IntoParam<'a, ITextRangeProvider>>(&self, textrangeprovider: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), textrangeprovider.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn CompareEndpoints<'a, Param1: ::windows::core::IntoParam<'a, ITextRangeProvider>>(&self, endpoint: super::Text::TextPatternRangeEndpoint, textrangeprovider: Param1, targetendpoint: super::Text::TextPatternRangeEndpoint) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), endpoint, textrangeprovider.into_param().abi(), targetendpoint, &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn ExpandToEnclosingUnit(&self, unit: super::Text::TextUnit) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), unit).ok() }
}
pub fn FindAttribute<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, attributeid: i32, value: Param1, backward: bool) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), attributeid, value.into_param().abi(), backward, &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn FindText<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0, backward: bool, ignorecase: bool) -> ::windows::core::Result<ITextRangeProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), text.into_param().abi(), backward, ignorecase, &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn GetAttributeValue(&self, attributeid: i32) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), attributeid, &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
pub fn GetBoundingRectangles(&self, returnvalue: &mut ::windows::core::Array<f64>) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), returnvalue.set_abi_len(), returnvalue as *mut _ as _).ok() }
}
pub fn GetEnclosingElement(&self) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
pub fn GetText(&self, maxlength: i32) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), maxlength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn Move(&self, unit: super::Text::TextUnit, count: i32) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), unit, count, &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn MoveEndpointByUnit(&self, endpoint: super::Text::TextPatternRangeEndpoint, unit: super::Text::TextUnit, count: i32) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), endpoint, unit, count, &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn MoveEndpointByRange<'a, Param1: ::windows::core::IntoParam<'a, ITextRangeProvider>>(&self, endpoint: super::Text::TextPatternRangeEndpoint, textrangeprovider: Param1, targetendpoint: super::Text::TextPatternRangeEndpoint) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), endpoint, textrangeprovider.into_param().abi(), targetendpoint).ok() }
}
pub fn Select(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this)).ok() }
}
pub fn AddToSelection(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this)).ok() }
}
pub fn RemoveFromSelection(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ScrollIntoView(&self, aligntotop: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), aligntotop).ok() }
}
pub fn GetChildren(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITextRangeProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{0274688d-06e9-4f66-9446-28a5be98fbd0}");
}
impl ::core::convert::From<ITextRangeProvider> for ::windows::core::IUnknown {
fn from(value: ITextRangeProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITextRangeProvider> for ::windows::core::IUnknown {
fn from(value: &ITextRangeProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITextRangeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITextRangeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITextRangeProvider> for ::windows::core::IInspectable {
fn from(value: ITextRangeProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITextRangeProvider> for ::windows::core::IInspectable {
fn from(value: &ITextRangeProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITextRangeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITextRangeProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITextRangeProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, textrangeprovider: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "UI_Xaml_Automation_Text")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endpoint: super::Text::TextPatternRangeEndpoint, textrangeprovider: ::windows::core::RawPtr, targetendpoint: super::Text::TextPatternRangeEndpoint, result__: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "UI_Xaml_Automation_Text"))] usize,
#[cfg(feature = "UI_Xaml_Automation_Text")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, unit: super::Text::TextUnit) -> ::windows::core::HRESULT,
#[cfg(not(feature = "UI_Xaml_Automation_Text"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, attributeid: i32, value: ::windows::core::RawPtr, backward: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, text: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, backward: bool, ignorecase: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, attributeid: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, returnValue_array_size: *mut u32, returnvalue: *mut *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, maxlength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "UI_Xaml_Automation_Text")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, unit: super::Text::TextUnit, count: i32, result__: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "UI_Xaml_Automation_Text"))] usize,
#[cfg(feature = "UI_Xaml_Automation_Text")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endpoint: super::Text::TextPatternRangeEndpoint, unit: super::Text::TextUnit, count: i32, result__: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "UI_Xaml_Automation_Text"))] usize,
#[cfg(feature = "UI_Xaml_Automation_Text")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endpoint: super::Text::TextPatternRangeEndpoint, textrangeprovider: ::windows::core::RawPtr, targetendpoint: super::Text::TextPatternRangeEndpoint) -> ::windows::core::HRESULT,
#[cfg(not(feature = "UI_Xaml_Automation_Text"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, aligntotop: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITextRangeProvider2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITextRangeProvider2 {
type Vtable = ITextRangeProvider2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd3be3dfb_9f54_4642_a7a5_5c18d5ee2a3f);
}
impl ITextRangeProvider2 {
pub fn ShowContextMenu(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Clone(&self) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn Compare<'a, Param0: ::windows::core::IntoParam<'a, ITextRangeProvider>>(&self, textrangeprovider: Param0) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), textrangeprovider.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn CompareEndpoints<'a, Param1: ::windows::core::IntoParam<'a, ITextRangeProvider>>(&self, endpoint: super::Text::TextPatternRangeEndpoint, textrangeprovider: Param1, targetendpoint: super::Text::TextPatternRangeEndpoint) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), endpoint, textrangeprovider.into_param().abi(), targetendpoint, &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn ExpandToEnclosingUnit(&self, unit: super::Text::TextUnit) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), unit).ok() }
}
pub fn FindAttribute<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, attributeid: i32, value: Param1, backward: bool) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), attributeid, value.into_param().abi(), backward, &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn FindText<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0, backward: bool, ignorecase: bool) -> ::windows::core::Result<ITextRangeProvider> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), text.into_param().abi(), backward, ignorecase, &mut result__).from_abi::<ITextRangeProvider>(result__)
}
}
pub fn GetAttributeValue(&self, attributeid: i32) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), attributeid, &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
pub fn GetBoundingRectangles(&self, returnvalue: &mut ::windows::core::Array<f64>) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), returnvalue.set_abi_len(), returnvalue as *mut _ as _).ok() }
}
pub fn GetEnclosingElement(&self) -> ::windows::core::Result<IRawElementProviderSimple> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<IRawElementProviderSimple>(result__)
}
}
pub fn GetText(&self, maxlength: i32) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), maxlength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn Move(&self, unit: super::Text::TextUnit, count: i32) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), unit, count, &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn MoveEndpointByUnit(&self, endpoint: super::Text::TextPatternRangeEndpoint, unit: super::Text::TextUnit, count: i32) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), endpoint, unit, count, &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "UI_Xaml_Automation_Text")]
pub fn MoveEndpointByRange<'a, Param1: ::windows::core::IntoParam<'a, ITextRangeProvider>>(&self, endpoint: super::Text::TextPatternRangeEndpoint, textrangeprovider: Param1, targetendpoint: super::Text::TextPatternRangeEndpoint) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), endpoint, textrangeprovider.into_param().abi(), targetendpoint).ok() }
}
pub fn Select(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this)).ok() }
}
pub fn AddToSelection(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this)).ok() }
}
pub fn RemoveFromSelection(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ScrollIntoView(&self, aligntotop: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), aligntotop).ok() }
}
pub fn GetChildren(&self) -> ::windows::core::Result<::windows::core::Array<IRawElementProviderSimple>> {
let this = &::windows::core::Interface::cast::<ITextRangeProvider>(self)?;
unsafe {
let mut result__: ::windows::core::Array<IRawElementProviderSimple> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), ::windows::core::Array::<IRawElementProviderSimple>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ITextRangeProvider2 {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d3be3dfb-9f54-4642-a7a5-5c18d5ee2a3f}");
}
impl ::core::convert::From<ITextRangeProvider2> for ::windows::core::IUnknown {
fn from(value: ITextRangeProvider2) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITextRangeProvider2> for ::windows::core::IUnknown {
fn from(value: &ITextRangeProvider2) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITextRangeProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITextRangeProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITextRangeProvider2> for ::windows::core::IInspectable {
fn from(value: ITextRangeProvider2) -> Self {
value.0
}
}
impl ::core::convert::From<&ITextRangeProvider2> for ::windows::core::IInspectable {
fn from(value: &ITextRangeProvider2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITextRangeProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITextRangeProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<ITextRangeProvider2> for ITextRangeProvider {
type Error = ::windows::core::Error;
fn try_from(value: ITextRangeProvider2) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ITextRangeProvider2> for ITextRangeProvider {
type Error = ::windows::core::Error;
fn try_from(value: &ITextRangeProvider2) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITextRangeProvider> for ITextRangeProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ITextRangeProvider> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITextRangeProvider> for &ITextRangeProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ITextRangeProvider> {
::core::convert::TryInto::<ITextRangeProvider>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITextRangeProvider2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IToggleProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IToggleProvider {
type Vtable = IToggleProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x93b88290_656f_44f7_aeaf_78b8f944d062);
}
impl IToggleProvider {
pub fn ToggleState(&self) -> ::windows::core::Result<super::ToggleState> {
let this = self;
unsafe {
let mut result__: super::ToggleState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::ToggleState>(result__)
}
}
pub fn Toggle(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IToggleProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{93b88290-656f-44f7-aeaf-78b8f944d062}");
}
impl ::core::convert::From<IToggleProvider> for ::windows::core::IUnknown {
fn from(value: IToggleProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IToggleProvider> for ::windows::core::IUnknown {
fn from(value: &IToggleProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IToggleProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IToggleProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IToggleProvider> for ::windows::core::IInspectable {
fn from(value: IToggleProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IToggleProvider> for ::windows::core::IInspectable {
fn from(value: &IToggleProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IToggleProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IToggleProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IToggleProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::ToggleState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITransformProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITransformProvider {
type Vtable = ITransformProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79670fdd_f6a9_4a65_af17_861db799a2da);
}
impl ITransformProvider {
pub fn CanMove(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn CanResize(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn CanRotate(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Move(&self, x: f64, y: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), x, y).ok() }
}
pub fn Resize(&self, width: f64, height: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), width, height).ok() }
}
pub fn Rotate(&self, degrees: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), degrees).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for ITransformProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{79670fdd-f6a9-4a65-af17-861db799a2da}");
}
impl ::core::convert::From<ITransformProvider> for ::windows::core::IUnknown {
fn from(value: ITransformProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITransformProvider> for ::windows::core::IUnknown {
fn from(value: &ITransformProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITransformProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITransformProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITransformProvider> for ::windows::core::IInspectable {
fn from(value: ITransformProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ITransformProvider> for ::windows::core::IInspectable {
fn from(value: &ITransformProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITransformProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITransformProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITransformProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, x: f64, y: f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, width: f64, height: f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, degrees: f64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ITransformProvider2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITransformProvider2 {
type Vtable = ITransformProvider2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa8b11756_a39f_4e97_8c7d_c1ea8dd633c5);
}
impl ITransformProvider2 {
pub fn CanZoom(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn ZoomLevel(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn MaxZoom(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn MinZoom(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn Zoom(&self, zoom: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), zoom).ok() }
}
pub fn ZoomByUnit(&self, zoomunit: super::ZoomUnit) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), zoomunit).ok() }
}
pub fn CanMove(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ITransformProvider>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn CanResize(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ITransformProvider>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn CanRotate(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ITransformProvider>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Move(&self, x: f64, y: f64) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITransformProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), x, y).ok() }
}
pub fn Resize(&self, width: f64, height: f64) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITransformProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), width, height).ok() }
}
pub fn Rotate(&self, degrees: f64) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITransformProvider>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), degrees).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for ITransformProvider2 {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{a8b11756-a39f-4e97-8c7d-c1ea8dd633c5}");
}
impl ::core::convert::From<ITransformProvider2> for ::windows::core::IUnknown {
fn from(value: ITransformProvider2) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ITransformProvider2> for ::windows::core::IUnknown {
fn from(value: &ITransformProvider2) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITransformProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ITransformProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ITransformProvider2> for ::windows::core::IInspectable {
fn from(value: ITransformProvider2) -> Self {
value.0
}
}
impl ::core::convert::From<&ITransformProvider2> for ::windows::core::IInspectable {
fn from(value: &ITransformProvider2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ITransformProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ITransformProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<ITransformProvider2> for ITransformProvider {
type Error = ::windows::core::Error;
fn try_from(value: ITransformProvider2) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ITransformProvider2> for ITransformProvider {
type Error = ::windows::core::Error;
fn try_from(value: &ITransformProvider2) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITransformProvider> for ITransformProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ITransformProvider> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ITransformProvider> for &ITransformProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ITransformProvider> {
::core::convert::TryInto::<ITransformProvider>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITransformProvider2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, zoom: f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, zoomunit: super::ZoomUnit) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IValueProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IValueProvider {
type Vtable = IValueProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2086b7a7_ac0e_47d1_ab9b_2a64292afdf8);
}
impl IValueProvider {
pub fn IsReadOnly(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Value(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetValue<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IValueProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{2086b7a7-ac0e-47d1-ab9b-2a64292afdf8}");
}
impl ::core::convert::From<IValueProvider> for ::windows::core::IUnknown {
fn from(value: IValueProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IValueProvider> for ::windows::core::IUnknown {
fn from(value: &IValueProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IValueProvider> for ::windows::core::IInspectable {
fn from(value: IValueProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IValueProvider> for ::windows::core::IInspectable {
fn from(value: &IValueProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IValueProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IValueProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IVirtualizedItemProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVirtualizedItemProvider {
type Vtable = IVirtualizedItemProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x17d4a04b_d658_48e0_a574_5a516c58dfa7);
}
impl IVirtualizedItemProvider {
pub fn Realize(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IVirtualizedItemProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{17d4a04b-d658-48e0-a574-5a516c58dfa7}");
}
impl ::core::convert::From<IVirtualizedItemProvider> for ::windows::core::IUnknown {
fn from(value: IVirtualizedItemProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IVirtualizedItemProvider> for ::windows::core::IUnknown {
fn from(value: &IVirtualizedItemProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVirtualizedItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVirtualizedItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IVirtualizedItemProvider> for ::windows::core::IInspectable {
fn from(value: IVirtualizedItemProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IVirtualizedItemProvider> for ::windows::core::IInspectable {
fn from(value: &IVirtualizedItemProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IVirtualizedItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IVirtualizedItemProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IVirtualizedItemProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IWindowProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IWindowProvider {
type Vtable = IWindowProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1baa8b3d_38cf_415a_85d3_20e43a0ec1b1);
}
impl IWindowProvider {
pub fn IsModal(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsTopmost(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Maximizable(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Minimizable(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn InteractionState(&self) -> ::windows::core::Result<super::WindowInteractionState> {
let this = self;
unsafe {
let mut result__: super::WindowInteractionState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::WindowInteractionState>(result__)
}
}
pub fn VisualState(&self) -> ::windows::core::Result<super::WindowVisualState> {
let this = self;
unsafe {
let mut result__: super::WindowVisualState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::WindowVisualState>(result__)
}
}
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn SetVisualState(&self, state: super::WindowVisualState) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), state).ok() }
}
pub fn WaitForInputIdle(&self, milliseconds: i32) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), milliseconds, &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IWindowProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1baa8b3d-38cf-415a-85d3-20e43a0ec1b1}");
}
impl ::core::convert::From<IWindowProvider> for ::windows::core::IUnknown {
fn from(value: IWindowProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IWindowProvider> for ::windows::core::IUnknown {
fn from(value: &IWindowProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWindowProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWindowProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IWindowProvider> for ::windows::core::IInspectable {
fn from(value: IWindowProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IWindowProvider> for ::windows::core::IInspectable {
fn from(value: &IWindowProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IWindowProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IWindowProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IWindowProvider_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::WindowInteractionState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::WindowVisualState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, state: super::WindowVisualState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, milliseconds: i32, result__: *mut bool) -> ::windows::core::HRESULT,
);
|
#[macro_use]
extern crate rental;
pub struct Foo {
i: i32,
}
pub struct Bar<'a> {
foo: &'a mut Foo,
}
pub struct Baz<'a: 'b, 'b> {
bar: &'b mut Bar<'a>
}
pub struct Qux<'a: 'b, 'b: 'c, 'c> {
baz: &'c mut Baz<'a, 'b>
}
pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> {
qux: &'d mut Qux<'a, 'b, 'c>
}
impl Foo {
pub fn borrow_mut<'a>(&'a mut self) -> Bar<'a> { Bar { foo: self } }
pub fn try_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) }
pub fn fail_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Err(()) }
}
impl<'a> Bar<'a> {
pub fn borrow_mut<'b>(&'b mut self) -> Baz<'a, 'b> { Baz { bar: self } }
pub fn try_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Ok(Baz { bar: self }) }
pub fn fail_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Err(()) }
}
impl<'a: 'b, 'b> Baz<'a, 'b> {
pub fn borrow_mut<'c>(&'c mut self) -> Qux<'a, 'b, 'c> { Qux { baz: self } }
pub fn try_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> { Ok(Qux { baz: self }) }
pub fn fail_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> { Err(()) }
}
impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> {
pub fn borrow_mut<'d>(&'d mut self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self } }
pub fn try_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Ok(Xyzzy { qux: self }) }
pub fn fail_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Err(()) }
}
rental! {
mod rentals {
use super::*;
#[rental_mut]
pub struct ComplexRent {
foo: Box<Foo>,
bar: Box<Bar<'foo>>,
baz: Box<Baz<'foo, 'bar>>,
qux: Box<Qux<'foo, 'bar, 'baz>>,
xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>,
}
}
}
#[test]
fn new() {
let foo = Foo { i: 5 };
let _ = rentals::ComplexRent::new(
Box::new(foo),
|foo| Box::new(foo.borrow_mut()),
|bar| Box::new(bar.borrow_mut()),
|baz| Box::new(baz.borrow_mut()),
|qux| qux.borrow_mut()
);
let foo = Foo { i: 5 };
let cm = rentals::ComplexRent::try_new(
Box::new(foo),
|foo| foo.try_borrow_mut().map(|bar| Box::new(bar)),
|bar| bar.try_borrow_mut().map(|baz| Box::new(baz)),
|baz| baz.try_borrow_mut().map(|qux| Box::new(qux)),
|qux| qux.try_borrow_mut()
);
assert!(cm.is_ok());
let foo = Foo { i: 5 };
let cm = rentals::ComplexRent::try_new(
Box::new(foo),
|foo| foo.try_borrow_mut().map(|bar| Box::new(bar)),
|bar| bar.try_borrow_mut().map(|baz| Box::new(baz)),
|baz| baz.try_borrow_mut().map(|qux| Box::new(qux)),
|qux| qux.fail_borrow_mut()
);
assert!(cm.is_err());
}
#[test]
fn read() {
let foo = Foo { i: 5 };
let cm = rentals::ComplexRent::new(
Box::new(foo),
|foo| Box::new(foo.borrow_mut()),
|bar| Box::new(bar.borrow_mut()),
|baz| Box::new(baz.borrow_mut()),
|qux| qux.borrow_mut()
);
let i = cm.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i);
assert_eq!(i, 5);
let iref = cm.ref_rent(|xyzzy| &xyzzy.qux.baz.bar.foo.i);
assert_eq!(*iref, 5);
}
#[test]
fn write() {
let foo = Foo { i: 5 };
let mut cm = rentals::ComplexRent::new(
Box::new(foo),
|foo| Box::new(foo.borrow_mut()),
|bar| Box::new(bar.borrow_mut()),
|baz| Box::new(baz.borrow_mut()),
|qux| qux.borrow_mut()
);
{
let iref: &mut i32 = cm.ref_rent_mut(|xyzzy| &mut xyzzy.qux.baz.bar.foo.i);
*iref = 12;
}
let i = cm.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i);
assert_eq!(i, 12);
}
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from ../gir-files
// DO NOT EDIT
use crate::SessionFeature;
use glib::object::IsA;
use glib::translate::*;
use std::fmt;
glib::wrapper! {
#[doc(alias = "SoupContentSniffer")]
pub struct ContentSniffer(Object<ffi::SoupContentSniffer, ffi::SoupContentSnifferClass>) @implements SessionFeature;
match fn {
type_ => || ffi::soup_content_sniffer_get_type(),
}
}
impl ContentSniffer {
#[doc(alias = "soup_content_sniffer_new")]
pub fn new() -> ContentSniffer {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::soup_content_sniffer_new())
}
}
}
#[cfg(any(feature = "v2_28", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_28")))]
impl Default for ContentSniffer {
fn default() -> Self {
Self::new()
}
}
pub const NONE_CONTENT_SNIFFER: Option<&ContentSniffer> = None;
pub trait ContentSnifferExt: 'static {
#[doc(alias = "soup_content_sniffer_get_buffer_size")]
#[doc(alias = "get_buffer_size")]
fn buffer_size(&self) -> usize;
//#[doc(alias = "soup_content_sniffer_sniff")]
//fn sniff<P: IsA<Message>>(&self, msg: &P, buffer: &mut Buffer, params: /*Unknown conversion*//*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 }) -> Option<glib::GString>;
}
impl<O: IsA<ContentSniffer>> ContentSnifferExt for O {
fn buffer_size(&self) -> usize {
unsafe {
ffi::soup_content_sniffer_get_buffer_size(self.as_ref().to_glib_none().0)
}
}
//fn sniff<P: IsA<Message>>(&self, msg: &P, buffer: &mut Buffer, params: /*Unknown conversion*//*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 }) -> Option<glib::GString> {
// unsafe { TODO: call ffi:soup_content_sniffer_sniff() }
//}
}
impl fmt::Display for ContentSniffer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("ContentSniffer")
}
}
|
//! Hyper service that adds a context to an incoming request and passes it on
//! to a wrapped service.
use crate::ContextualPayload;
use hyper::{Body, Request};
use std::marker::PhantomData;
use std::task::{Context, Poll};
/// Middleware wrapper service that drops the context from the incoming request
/// and passes the plain `hyper::Request` to the wrapped service.
///
/// This service can be used to to include services that take a plain `hyper::Request`
/// in a `CompositeService` wrapped in an `AddContextService`.
///
/// Example Usage
/// =============
///
/// In the following example `SwaggerService` implements `hyper::service::MakeService`
/// with `Request = (hyper::Request, SomeContext)`, and `PlainService` implements it
/// with `Request = hyper::Request`
///
/// ```ignore
/// let swagger_service_one = SwaggerService::new();
/// let swagger_service_two = SwaggerService::new();
/// let plain_service = PlainService::new();
///
/// let mut composite_new_service = CompositeMakeService::new();
/// composite_new_service.push(("/base/path/1", swagger_service_one));
/// composite_new_service.push(("/base/path/2", swagger_service_two));
/// composite_new_service.push(("/base/path/3", DropContextMakeService::new(plain_service)));
/// ```
#[derive(Debug)]
pub struct DropContextMakeService<C> {
phantom: PhantomData<C>,
}
impl<C> DropContextMakeService<C> {
/// Create a new DropContextMakeService struct wrapping a value
pub fn new() -> Self {
DropContextMakeService {
phantom: PhantomData,
}
}
}
impl<T, C> hyper::service::Service<T> for DropContextMakeService<C> {
type Response = DropContextService<T, C>;
type Error = std::io::Error;
type Future = futures::future::Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>> {
Ok(()).into()
}
fn call(&mut self, inner: T) -> Self::Future {
futures::future::ok(DropContextService::new(inner))
}
}
/// Swagger Middleware that wraps a `hyper::service::Service`, and drops any contextual information
/// on the request. Services will normally want to use `DropContextMakeService`, which will create
/// a `DropContextService` to handle each connection.
#[derive(Debug)]
pub struct DropContextService<T, C> {
inner: T,
marker: PhantomData<C>,
}
impl<T, C> DropContextService<T, C> {
/// Create a new AddContextService struct wrapping a value
pub fn new(inner: T) -> Self {
DropContextService {
inner,
marker: PhantomData,
}
}
}
impl<T, C> hyper::service::Service<ContextualPayload<C>> for DropContextService<T, C>
where
C: Send + Sync + 'static,
T: hyper::service::Service<Request<Body>>,
{
type Response = T::Response;
type Error = T::Error;
type Future = T::Future;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Ok(()).into()
}
fn call(&mut self, req: ContextualPayload<C>) -> Self::Future {
self.inner.call(req.inner)
}
} |
use super::bus::*;
pub struct Cpu {
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
h: u8,
l: u8,
pc: u16,
sp: u16,
zerof: u8,
add_subf: u8,
half_carryf: u8,
carryf: u8,
wait: i32,
interrupts_enabled: bool,
halted: bool,
}
const ZERO: u8 = 7;
const ADDSUB: u8 = 6;
const HALFCARRY: u8 = 5;
const CARRY: u8 = 4;
impl Cpu {
pub fn new() -> Self {
Cpu {
a: 0,
b: 0,
c: 0,
d: 0,
e: 0,
h: 0,
l: 0,
pc: 0x100,
sp: 0xfffe,
zerof: 0,
add_subf: 0,
half_carryf: 0,
carryf: 0,
wait: 0,
interrupts_enabled: false,
halted: false,
}
}
pub fn reset(&mut self) {
self.a = 0;
self.b = 0;
self.c = 0;
self.d = 0;
self.e = 0;
self.h = 0;
self.l = 0;
self.pc = 0x100;
self.sp = 0xfffe;
self.zerof = 0;
self.add_subf = 0;
self.half_carryf = 0;
self.carryf = 0;
self.interrupts_enabled = false;
}
fn flags(&self) -> u8 {
self.zerof << ZERO
| self.add_subf << ADDSUB
| self.half_carryf << HALFCARRY
| self.carryf << CARRY
}
fn set_flags(&mut self, f: u8) {
self.zerof = f >> ZERO & 1;
self.add_subf = f >> ADDSUB & 1;
self.half_carryf = f >> HALFCARRY & 1;
self.carryf = f >> CARRY & 1;
}
fn call(&mut self, bus: &mut Bus, addr: u16) {
bus.write16(self.sp - 2, self.pc + 1);
self.sp -= 2;
self.pc = u16::wrapping_sub(addr, 1);
self.wait = 16;
}
fn ret(&mut self, bus: &mut Bus) {
let l = bus.read(self.sp);
let h = bus.read(self.sp + 1);
self.sp += 2;
self.pc = (h as u16) << 8 | l as u16;
self.pc = u16::wrapping_sub(self.pc, 1);
self.wait = 16;
}
#[allow(clippy::collapsible_else_if)]
#[allow(unused_parens)]
pub fn tick(&mut self, bus: &mut Bus) {
self.wait -= 1;
if self.wait > 0 {
return;
}
if self.halted{
if bus.requested_interrupts != 0 {
self.pc += 1;
self.halted = false;
} else {
return;
}
}
if self.interrupts_enabled && (bus.enabled_interrupts & bus.requested_interrupts != 0) {
let active_interrupts = bus.enabled_interrupts & bus.requested_interrupts;
self.sp -= 2;
self.interrupts_enabled = false;
bus.write16(self.sp, self.pc);
self.wait = 20;
//println!("Interrupt {:x} at pc={:#x}", active_interrupts, self.pc);
if active_interrupts & VBLANK != 0 {
self.pc = 0x40;
bus.requested_interrupts &= !VBLANK;
} else if active_interrupts & LCD_STAT != 0 {
self.pc = 0x48;
bus.requested_interrupts &= !LCD_STAT;
} else if active_interrupts & TIMER != 0 {
self.pc = 0x50;
bus.requested_interrupts &= !TIMER;
} else if active_interrupts & SERIAL != 0 {
self.pc = 0x58;
bus.requested_interrupts &= !SERIAL;
} else if active_interrupts & JOYPAD != 0 {
self.pc = 0x60;
bus.requested_interrupts &= !JOYPAD;
}
return;
}
macro_rules! disasm {
($($arg:tt)+) => (
#[cfg(feature = "disasm")]
{
print!("0x{:<8x}: ", self.pc);
println!($($arg)+);
}
)
}
macro_rules! disasm_pc {
($pc: expr, $($arg:tt)+) => (
#[cfg(feature = "disasm")]
{
print!("0x{:<8x}: ", $pc);
println!($($arg)+);
}
)
}
macro_rules! inc {
($arg:ident) => {{
let before = self.$arg;
self.$arg = u8::wrapping_add(self.$arg, 1);
self.zerof = if self.$arg == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((before & 0xf) + 1) & 0x10 != 0 {
1
} else {
0
};
self.wait = 4;
disasm!("Inc {}", stringify!($arg));
}};
}
macro_rules! dec {
($arg:ident) => {{
let before = self.$arg;
self.$arg = u8::wrapping_sub(self.$arg, 1);
self.zerof = if self.$arg == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if (before & 0xf) == 0 { 1 } else { 0 };
self.wait = 4;
disasm!("Dec {}", stringify!($arg));
}};
}
macro_rules! addA {
($arg:ident) => {{
let (new_a, carry) = u8::overflowing_add(self.$arg, self.a);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((self.a & 0xf) + (self.$arg & 0xf)) & 0x10 != 0 {
1
} else {
0
};
self.carryf = if carry { 1 } else { 0 };
self.a = new_a;
self.wait = 4;
disasm!("Add a, {}={:#x}", stringify!($arg), self.$arg);
}};
}
macro_rules! addHL {
($arg:ident) => {{
let hl = (self.h as u16) << 8 | self.l as u16;
let (res, carry) = u16::overflowing_add(hl, $arg);
self.add_subf = 0;
self.carryf = carry as u8;
self.half_carryf = if ((hl & 0xfff) + ($arg & 0xfff)) & 0x1000 != 0 {
1
} else {
0
};
self.h = (res >> 8) as u8;
self.l = res as u8;
self.wait = 8;
disasm!(
"Add HL:{:#x}, {}:{:#x} => {:#x}",
hl,
stringify!($arg),
$arg,
res
);
}};
}
macro_rules! push16 {
($arg:ident) => {
self.sp -= 2;
bus.write16(self.sp, $arg);
self.wait = 16;
disasm!("PUSH {}", stringify!($arg))
};
}
macro_rules! pop16 {
($h:ident, $l:ident) => {
*$l = bus.read(self.sp);
self.sp += 1;
*$h = bus.read(self.sp);
self.sp += 1;
self.wait = 12;
disasm!(
"POP {}{}:0x{:02x}{:02x}",
stringify!($h),
stringify!($l),
$h,
$l
);
};
}
macro_rules! subA {
($arg:ident) => {{
let before = self.$arg;
let (new_a, carry) = u8::overflowing_sub(self.a, self.$arg);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if self.a & 0xf >= before & 0xf { 0 } else { 1 };
self.carryf = if carry { 1 } else { 0 };
self.a = new_a;
self.wait = 4;
disasm!("Sub a, {}", stringify!($arg));
}};
}
macro_rules! adcA {
($arg:ident) => {{
let (new_a, carry) = u8::overflowing_add(self.$arg, self.a);
let (new_a2, carry2) = u8::overflowing_add(new_a, self.carryf);
self.zerof = if new_a2 == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((self.a & 0xf) + (self.$arg & 0xf) + self.carryf) & 0x10 != 0
{
1
} else {
0
};
self.carryf = if carry || carry2 { 1 } else { 0 };
self.a = new_a2;
self.wait = 4;
disasm!("Adc a, {}", stringify!($arg));
}};
}
macro_rules! sbcA {
($arg:ident) => {{
let (new_a, carry) = u8::overflowing_sub(self.a, self.$arg);
let (new_a2, carry2) = u8::overflowing_sub(new_a, self.carryf);
self.zerof = if new_a2 == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if self.a & 0xf < (self.$arg & 0xf) + self.carryf {
1
} else {
0
};
self.carryf = if carry || carry2 { 1 } else { 0 };
self.a = new_a2;
self.wait = 4;
disasm!("SBC a, {}", stringify!($arg));
}};
}
macro_rules! andA {
($arg:expr) => {{
self.a &= $arg;
self.zerof = if self.a != 0 { 0 } else { 1 };
self.add_subf = 0;
self.half_carryf = 1;
self.carryf = 0;
self.wait = 4;
disasm!("And A, {}:{:#x}", stringify!($arg), $arg);
}};
}
#[allow(unused_parens)]
macro_rules! orA {
($arg:expr) => {{
self.a |= $arg;
self.zerof = if self.a == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = 0;
self.carryf = 0;
self.wait = 4;
disasm!("Or A, {}:{:#x}", stringify!($arg), $arg);
}};
}
macro_rules! xorA {
($arg:expr) => {{
self.a ^= $arg;
self.zerof = if self.a == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = 0;
self.carryf = 0;
self.wait = 4;
disasm!("Xor A, {}", stringify!($arg));
}};
}
macro_rules! cmpA {
($arg:expr) => {{
let (new_a, carry) = u8::overflowing_sub(self.a, $arg);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if $arg & 0xf > (self.a & 0xf) { 1 } else { 0 };
self.carryf = carry as u8;
self.wait = 4;
disasm!("Cmp A:{:#x}, {}:{:#x}", self.a, stringify!($arg), $arg);
}};
}
fn jump(this: &mut Cpu, bus: &mut Bus) -> u16 {
let addr = bus.read16(this.pc + 1);
this.pc = addr;
this.wait = 16;
this.pc = u16::wrapping_sub(this.pc, 1);
addr
}
fn jrel(this: &mut Cpu, bus: &mut Bus) -> u8 {
let addr = bus.read(this.pc + 1);
this.pc = u16::wrapping_add(this.pc, addr as i8 as u16);
this.wait = 12;
this.pc = u16::wrapping_add(this.pc, 1);
addr
}
let op = bus.read(self.pc);
match op {
0x0 => {
self.wait = 4;
disasm!("NOP");
}
0x1 => {
self.c = bus.read(self.pc + 1);
self.b = bus.read(self.pc + 2);
disasm!("LD BC, 0x{:x}{:x}", self.b, self.c);
self.wait = 12;
self.pc += 2;
}
0x11 => {
self.e = bus.read(self.pc + 1);
self.d = bus.read(self.pc + 2);
disasm!("LD DE, 0x{:x}{:x}", self.d, self.e);
self.wait = 12;
self.pc += 2;
}
0x21 => {
self.l = bus.read(self.pc + 1);
self.h = bus.read(self.pc + 2);
disasm!("LD HL, 0x{:x}{:x}", self.h, self.l);
self.wait = 12;
self.pc += 2;
}
0x31 => {
self.sp = bus.read(self.pc + 1) as u16 | (bus.read(self.pc + 2) as u16) << 8;
disasm!("LD SP, 0x{:x}", self.sp);
self.wait = 12;
self.pc += 2;
}
0x40 => {
//self.b = self.b;
self.wait = 4;
disasm!("LD B, B");
}
0x50 => {
self.d = self.b;
self.wait = 4;
disasm!("LD D, B");
}
0x60 => {
self.h = self.b;
self.wait = 4;
disasm!("LD H, B");
}
0x41 => {
self.b = self.c;
self.wait = 4;
disasm!("LD B, C");
}
0x51 => {
self.d = self.c;
self.wait = 4;
disasm!("LD D, C");
}
0x61 => {
self.h = self.c;
self.wait = 4;
disasm!("LD H, C");
}
0x42 => {
self.b = self.d;
self.wait = 4;
disasm!("LD B, D");
}
0x52 => {
//self.d = self.d;
self.wait = 4;
disasm!("LD D, D");
}
0x62 => {
self.h = self.d;
self.wait = 4;
disasm!("LD H, D");
}
0x43 => {
self.b = self.e;
self.wait = 4;
disasm!("LD B, E");
}
0x53 => {
self.d = self.e;
self.wait = 4;
disasm!("LD D, E");
}
0x63 => {
self.h = self.e;
self.wait = 4;
disasm!("LD H, E");
}
0x44 => {
self.b = self.h;
self.wait = 4;
disasm!("LD B, H");
}
0x54 => {
self.d = self.h;
self.wait = 4;
disasm!("LD D, H");
}
0x64 => {
//self.h = self.h;
self.wait = 4;
disasm!("LD H, H");
}
0x45 => {
self.b = self.l;
self.wait = 4;
disasm!("LD B, L");
}
0x55 => {
self.d = self.l;
self.wait = 4;
disasm!("LD D, L");
}
0x65 => {
self.h = self.l;
self.wait = 4;
disasm!("LD H, L");
}
0x46 => {
self.b = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD B, (HL)");
}
0x56 => {
self.d = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD D, (HL):{:#x}", self.d);
}
0x66 => {
self.h = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD H, (HL)");
}
0x47 => {
self.b = self.a;
self.wait = 4;
disasm!("LD B, A");
}
0x57 => {
self.d = self.a;
self.wait = 4;
disasm!("LD D, A");
}
0x67 => {
self.h = self.a;
self.wait = 4;
disasm!("LD H, A");
}
0x48 => {
self.c = self.b;
self.wait = 4;
disasm!("LD C, B");
}
0x58 => {
self.e = self.b;
self.wait = 4;
disasm!("LD E, B");
}
0x68 => {
self.l = self.b;
self.wait = 4;
disasm!("LD L, B");
}
0x78 => {
self.a = self.b;
self.wait = 4;
disasm!("LD A, B");
}
0x49 => {
//self.c = self.c;
self.wait = 4;
disasm!("LD C, C");
}
0x59 => {
self.e = self.c;
self.wait = 4;
disasm!("LD E, C");
}
0x69 => {
self.l = self.c;
self.wait = 4;
disasm!("LD L, C");
}
0x79 => {
self.a = self.c;
self.wait = 4;
disasm!("LD A, C");
}
0x4a => {
self.c = self.d;
self.wait = 4;
disasm!("LD C, D");
}
0x5a => {
self.e = self.d;
self.wait = 4;
disasm!("LD E, D");
}
0x6a => {
self.l = self.d;
self.wait = 4;
disasm!("LD L, D");
}
0x7a => {
self.a = self.d;
self.wait = 4;
disasm!("LD A, D");
}
0x4b => {
self.c = self.e;
self.wait = 4;
disasm!("LD C, E");
}
0x5b => {
//self.e = self.e;
self.wait = 4;
disasm!("LD E, E");
}
0x6b => {
self.l = self.e;
self.wait = 4;
disasm!("LD L, E");
}
0x7b => {
self.a = self.e;
self.wait = 4;
disasm!("LD A, E");
}
0x4c => {
self.c = self.h;
self.wait = 4;
disasm!("LD C, H");
}
0x5c => {
self.e = self.h;
self.wait = 4;
disasm!("LD E, H");
}
0x6c => {
self.l = self.h;
self.wait = 4;
disasm!("LD L, H");
}
0x7c => {
self.a = self.h;
self.wait = 4;
disasm!("LD A, H");
}
0x4d => {
self.c = self.l;
self.wait = 4;
disasm!("LD C, L");
}
0x5d => {
self.e = self.l;
self.wait = 4;
disasm!("LD E, L");
}
0x6d => {
//self.l = self.l;
self.wait = 4;
disasm!("LD L, L");
}
0x7d => {
self.a = self.l;
self.wait = 4;
disasm!("LD A, L");
}
0x4e => {
self.c = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD C, (HL)");
}
0x5e => {
self.e = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD E, (HL):{:#x}", self.e);
}
0x6e => {
self.l = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD L, (HL)");
}
0x7e => {
self.a = bus.read((self.h as u16) << 8 | self.l as u16);
self.wait = 8;
disasm!("LD A, (HL)");
}
0x4f => {
self.c = self.a;
self.wait = 4;
disasm!("LD C, A");
}
0x5f => {
self.e = self.a;
self.wait = 4;
disasm!("LD E, A");
}
0x6f => {
self.l = self.a;
self.wait = 4;
disasm!("LD L, A");
}
0x7f => {
//self.a = self.a;
self.wait = 4;
disasm!("LD A, A");
}
0x70 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.b);
self.wait = 8;
disasm!("LD (HL), B");
}
0x71 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.c);
self.wait = 8;
disasm!("LD (HL), C");
}
0x72 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.d);
self.wait = 8;
disasm!("LD (HL), D");
}
0x73 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.e);
self.wait = 8;
disasm!("LD (HL), E");
}
0x74 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.h);
self.wait = 8;
disasm!("LD (HL), H");
}
0x75 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.l);
self.wait = 8;
disasm!("LD (HL), L");
}
0x77 => {
bus.write((self.h as u16) << 8 | self.l as u16, self.a);
self.wait = 8;
disasm!("LD (HL), A");
}
0x02 => {
bus.write((self.b as u16) << 8 | self.c as u16, self.a);
self.wait = 8;
disasm!("LD (BC), A");
}
0x12 => {
bus.write((self.d as u16) << 8 | self.e as u16, self.a);
self.wait = 8;
disasm!("LD (DE), A");
}
0x22 => {
let mut hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.a);
hl = u16::wrapping_add(hl, 1);
self.h = (hl >> 8) as u8;
self.l = (hl & 0xff) as u8;
self.wait = 8;
disasm!("LD (HL+), A");
}
0x32 => {
let mut hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.a);
hl = u16::wrapping_sub(hl, 1);
self.h = (hl >> 8) as u8;
self.l = (hl & 0xff) as u8;
self.wait = 8;
disasm!("LD (HL-), A");
}
0x06 => {
self.b = bus.read(self.pc + 1);
disasm!("LD B, d8:{:#x}", self.b);
self.wait = 8;
self.pc += 1;
}
0x16 => {
self.d = bus.read(self.pc + 1);
disasm!("LD D, d8");
self.wait = 8;
self.pc += 1;
}
0x26 => {
self.h = bus.read(self.pc + 1);
disasm!("LD H, d8");
self.wait = 8;
self.pc += 1;
}
0x36 => {
let arg = bus.read(self.pc + 1);
bus.write((self.h as u16) << 8 | self.l as u16, arg);
disasm!("LD (HL), d8");
self.wait = 12;
self.pc += 1;
}
0x0a => {
self.a = bus.read((self.b as u16) << 8 | self.c as u16);
self.wait = 8;
disasm!("LD A, (BC)");
}
0x1a => {
self.a = bus.read((self.d as u16) << 8 | self.e as u16);
self.wait = 8;
disasm!("LD A, (DE)");
}
0x2a => {
let mut hl = (self.h as u16) << 8 | self.l as u16;
self.a = bus.read(hl);
hl = u16::wrapping_add(hl, 1);
self.h = (hl >> 8) as u8;
self.l = (hl & 0xff) as u8;
self.wait = 8;
disasm!("LD A, (HL+)");
}
0x3a => {
let mut hl = (self.h as u16) << 8 | self.l as u16;
self.a = bus.read(hl);
hl = u16::wrapping_sub(hl, 1);
self.h = (hl >> 8) as u8;
self.l = (hl & 0xff) as u8;
self.wait = 8;
disasm!("LD A, (HL-)");
}
0x0e => {
self.c = bus.read(self.pc + 1);
disasm!("LD C, d8");
self.wait = 8;
self.pc += 1;
}
0x1e => {
self.e = bus.read(self.pc + 1);
disasm!("LD E, d8");
self.wait = 8;
self.pc += 1;
}
0x2e => {
self.l = bus.read(self.pc + 1);
disasm!("LD L, d8");
self.wait = 8;
self.pc += 1;
}
0x3e => {
self.a = bus.read(self.pc + 1);
disasm!("LD A, d8:{:#x}", self.a);
self.wait = 8;
self.pc += 1;
}
0x08 => {
let low = bus.read(self.pc + 1);
let high = bus.read(self.pc + 2);
bus.write16((high as u16) << 8 | low as u16, self.sp);
disasm!("LD (a16), SP");
self.wait = 20;
self.pc += 2;
}
0xe0 => {
let a8 = bus.read(self.pc + 1);
bus.write(a8 as u16 | 0xFF00, self.a);
disasm!("LDH (a8):0xff{:02x}, A", a8);
self.wait = 12;
self.pc += 1;
}
0xf0 => {
let a8 = bus.read(self.pc + 1);
self.a = bus.read(a8 as u16 | 0xFF00);
disasm!("LDH A, (a8):{:#x}=>{:#x}", a8, self.a);
self.wait = 12;
self.pc += 1;
}
0xe2 => {
bus.write(self.c as u16 | 0xFF00, self.a);
disasm!("LDH (C), A");
self.wait = 8;
}
0xf2 => {
self.a = bus.read(self.c as u16 | 0xFF00);
self.wait = 8;
disasm!("LDH A, (C)");
}
0xf8 => {
let r8 = bus.read(self.pc + 1);
let addr = u16::wrapping_add(r8 as i8 as i16 as u16, self.sp);
let (_, overflow) = u8::overflowing_add(r8, (self.sp & 0xff) as u8);
self.carryf = if overflow { 1 } else { 0 };
self.half_carryf = if (((r8 as u16) & 0xF) + (self.sp & 0xF)) & 0x10 != 0 {
1
} else {
0
};
self.zerof = 0;
self.add_subf = 0;
self.h = (addr >> 8) as u8;
self.l = addr as u8;
disasm!("LD HL, SP+(a8):{:#x} => {:#x}", r8, addr);
self.wait = 12;
self.pc += 1;
}
0xf9 => {
self.sp = (self.h as u16) << 8 | self.l as u16;
self.wait = 8;
disasm!("LD SP, HL");
}
0xea => {
let addr = bus.read16(self.pc + 1);
bus.write(addr, self.a);
self.pc += 2;
disasm!("LD ({:#x}), A", addr);
}
0xfa => {
let addr = bus.read16(self.pc + 1);
self.a = bus.read(addr);
self.pc += 2;
disasm!("LD A, ({:#x})", addr);
}
0x04 => inc!(b),
0x14 => inc!(d),
0x24 => inc!(h),
0x0c => inc!(c),
0x1c => inc!(e),
0x2c => inc!(l),
0x3c => inc!(a),
0x05 => dec!(b),
0x15 => dec!(d),
0x25 => dec!(h),
0x0d => dec!(c),
0x1d => dec!(e),
0x2d => dec!(l),
0x3d => dec!(a),
0x34 => {
let hl = (self.h as u16) << 8 | self.l as u16;
let x = bus.read(hl);
let res = u8::wrapping_add(x, 1);
self.zerof = if res == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((x & 0xf) + 1) & 0x10 != 0 { 1 } else { 0 };
bus.write(hl, res);
disasm!("INC (HL)");
self.wait = 12;
}
0x35 => {
let hl = (self.h as u16) << 8 | self.l as u16;
let x = bus.read(hl);
let res = u8::wrapping_sub(x, 1);
self.zerof = if res == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if (x & 0xf) == 0 { 1 } else { 0 };
bus.write(hl, res);
disasm!("DEC (HL)");
self.wait = 12;
}
0x03 => {
let mut bc = (self.b as u16) << 8 | self.c as u16;
bc = u16::wrapping_add(bc, 1);
self.c = (bc & 0xff) as u8;
self.b = (bc >> 8) as u8;
disasm!("INC BC");
self.wait = 8;
}
0x13 => {
let mut de = (self.d as u16) << 8 | self.e as u16;
de = u16::wrapping_add(de, 1);
self.e = (de & 0xff) as u8;
self.d = (de >> 8) as u8;
disasm!("INC DE");
self.wait = 8;
}
0x23 => {
let mut hl = (self.h as u16) << 8 | self.l as u16;
hl = u16::wrapping_add(hl, 1);
self.l = (hl & 0xff) as u8;
self.h = (hl >> 8) as u8;
disasm!("INC HL");
self.wait = 8;
}
0x33 => {
self.sp = u16::wrapping_add(self.sp, 1);
disasm!("INC SP");
self.wait = 8;
}
0x0b => {
let mut bc = (self.b as u16) << 8 | self.c as u16;
bc = u16::wrapping_sub(bc, 1);
self.c = (bc & 0xff) as u8;
self.b = (bc >> 8) as u8;
disasm!("DEC BC");
self.wait = 8;
}
0x1b => {
let mut de = (self.d as u16) << 8 | self.e as u16;
de = u16::wrapping_sub(de, 1);
self.e = (de & 0xff) as u8;
self.d = (de >> 8) as u8;
disasm!("DEC DE");
self.wait = 8;
}
0x2b => {
let mut hl = (self.h as u16) << 8 | self.l as u16;
hl = u16::wrapping_sub(hl, 1);
self.l = (hl & 0xff) as u8;
self.h = (hl >> 8) as u8;
disasm!("DEC HL");
self.wait = 8;
}
0x3b => {
self.sp = u16::wrapping_sub(self.sp, 1);
disasm!("DEC SP");
self.wait = 8;
}
0x80 => addA!(b),
0x81 => addA!(c),
0x82 => addA!(d),
0x83 => addA!(e),
0x84 => addA!(h),
0x85 => addA!(l),
0x87 => addA!(a),
0x90 => subA!(b),
0x91 => subA!(c),
0x92 => subA!(d),
0x93 => subA!(e),
0x94 => subA!(h),
0x95 => subA!(l),
0x97 => subA!(a),
0x88 => adcA!(b),
0x89 => adcA!(c),
0x8a => adcA!(d),
0x8b => adcA!(e),
0x8c => adcA!(h),
0x8d => adcA!(l),
0x8f => adcA!(a),
0x98 => sbcA!(b),
0x99 => sbcA!(c),
0x9a => sbcA!(d),
0x9b => sbcA!(e),
0x9c => sbcA!(h),
0x9d => sbcA!(l),
0x9f => sbcA!(a),
0x86 => {
let val = bus.read((self.h as u16) << 8 | self.l as u16);
let (new_a, carry) = u8::overflowing_add(val, self.a);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((self.a & 0xf) + (val & 0xf)) & 0x10 != 0 {
1
} else {
0
};
self.carryf = if carry { 1 } else { 0 };
self.a = new_a;
self.wait = 8;
disasm!("Add a (HL)");
}
0x96 => {
let val = bus.read((self.h as u16) << 8 | self.l as u16);
let (new_a, carry) = u8::overflowing_sub(self.a, val);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if (self.a & 0xf) < (val & 0xf) { 1 } else { 0 };
self.carryf = if carry { 1 } else { 0 };
self.a = new_a;
self.wait = 8;
disasm!("Sub a (HL)");
}
0x8e => {
let val = bus.read((self.h as u16) << 8 | self.l as u16);
let (new_a, carry) = u8::overflowing_add(self.a, val);
let (new_a2, carry2) = u8::overflowing_add(new_a, self.carryf);
self.zerof = if new_a2 == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((self.a & 0xf) + (val & 0xf) + self.carryf) & 0x10 != 0 {
1
} else {
0
};
self.carryf = if carry || carry2 { 1 } else { 0 };
self.a = new_a2;
self.wait = 8;
disasm!("Adc a, (HL)");
}
0x9e => {
let val = bus.read((self.h as u16) << 8 | self.l as u16);
let (new_a, carry) = u8::overflowing_sub(self.a, val);
let (new_a2, carry2) = u8::overflowing_sub(new_a, self.carryf);
self.zerof = if new_a2 == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if ((self.a & 0xf) - (val & 0xf) - self.carryf) & 0x10 != 0 {
1
} else {
0
};
self.carryf = if carry || carry2 { 1 } else { 0 };
self.a = new_a2;
self.wait = 8;
disasm!("SBC a, (HL)");
}
0xa0 => andA!(self.b),
0xa1 => andA!(self.c),
0xa2 => andA!(self.d),
0xa3 => andA!(self.e),
0xa4 => andA!(self.h),
0xa5 => andA!(self.l),
0xa7 => andA!(self.a),
0xb0 => orA!(self.b),
0xb1 => orA!(self.c),
0xb2 => orA!(self.d),
0xb3 => orA!(self.e),
0xb4 => orA!(self.h),
0xb5 => orA!(self.l),
0xb7 => orA!(self.a),
0xa6 => {
let hl = bus.read((self.h as u16) << 8 | self.l as u16);
andA!((hl));
self.wait = 8;
}
0xb6 => {
let hl = bus.read((self.h as u16) << 8 | self.l as u16);
orA!((hl));
self.wait = 8;
}
0xa8 => xorA!(self.b),
0xa9 => xorA!(self.c),
0xaa => xorA!(self.d),
0xab => xorA!(self.e),
0xac => xorA!(self.h),
0xad => xorA!(self.l),
0xaf => xorA!(self.a),
0xb8 => cmpA!(self.b),
0xb9 => cmpA!(self.c),
0xba => cmpA!(self.d),
0xbb => cmpA!(self.e),
0xbc => cmpA!(self.h),
0xbd => cmpA!(self.l),
0xbf => cmpA!(self.a),
0xae => {
let hl = bus.read((self.h as u16) << 8 | self.l as u16);
xorA!(hl);
self.wait = 8;
}
0xbe => {
let hl = bus.read((self.h as u16) << 8 | self.l as u16);
cmpA!(hl);
self.wait = 8;
}
0xc6 => {
let arg = bus.read(self.pc + 1);
let (new_a, carry) = u8::overflowing_add(arg, self.a);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((arg & 0xf) + (self.a & 0xf)) & 0x10 != 0 {
1
} else {
0
};
self.carryf = if carry { 1 } else { 0 };
self.a = new_a;
self.wait = 8;
self.pc += 1;
disasm!("Add a, {:#x}", arg);
}
0xd6 => {
let arg = bus.read(self.pc + 1);
let (new_a, carry) = u8::overflowing_sub(self.a, arg);
self.zerof = if new_a == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = if self.a & 0xf >= arg & 0xf { 0 } else { 1 };
self.carryf = carry as u8;
self.a = new_a;
self.wait = 8;
self.pc += 1;
disasm!("Sub a, {:#}", arg);
}
0xce => {
let arg = bus.read(self.pc + 1);
let (new_a, carry) = u8::overflowing_add(arg, self.a);
let (new_a2, carry2) = u8::overflowing_add(new_a, self.carryf);
self.zerof = if new_a2 == 0 { 1 } else { 0 };
self.add_subf = 0;
self.half_carryf = if ((arg & 0xf) + (self.a & 0xf) + self.carryf) & 0x10 != 0 {
1
} else {
0
};
self.carryf = if carry || carry2 { 1 } else { 0 };
self.a = new_a2;
self.wait = 8;
self.pc += 1;
disasm!("Adc a, {:#x}", arg);
}
0xde => {
let arg = bus.read(self.pc + 1);
let (new_a, carry) = u8::overflowing_sub(self.a, arg);
let (new_a2, carry2) = u8::overflowing_sub(new_a, self.carryf);
self.zerof = if new_a2 == 0 { 1 } else { 0 };
self.add_subf = 1;
self.half_carryf = ((self.a & 0xf) < (arg & 0xf) + self.carryf) as u8;
self.carryf = if carry || carry2 { 1 } else { 0 };
self.a = new_a2;
self.wait = 8;
self.pc += 1;
disasm!("Sbc a, {:#}", arg);
}
0xe6 => {
let arg8 = bus.read(self.pc + 1);
andA!(arg8);
self.pc += 1;
self.wait = 8;
}
0xf6 => {
let arg8 = bus.read(self.pc + 1);
orA!(arg8);
self.pc += 1;
self.wait = 8;
}
0xee => {
let arg8 = bus.read(self.pc + 1);
xorA!(arg8);
self.pc += 1;
self.wait = 8;
}
0xfe => {
let arg8 = bus.read(self.pc + 1);
cmpA!(arg8);
self.pc += 1;
self.wait = 8;
}
0x09 => {
let bc = ((self.b as u16) << 8) | self.c as u16;
addHL!(bc);
}
0x19 => {
let de = ((self.d as u16) << 8) | self.e as u16;
addHL!(de);
}
0x29 => {
let hl = ((self.h as u16) << 8) | self.l as u16;
addHL!(hl);
}
0x39 => {
let sp = self.sp;
addHL!(sp);
}
0xc5 => {
let bc = ((self.b as u16) << 8) | self.c as u16;
push16!(bc);
}
0xd5 => {
let de = ((self.d as u16) << 8) | self.e as u16;
push16!(de);
}
0xe5 => {
let hl = ((self.h as u16) << 8) | self.l as u16;
push16!(hl);
}
0xf5 => {
let af = ((self.a as u16) << 8) | self.flags() as u16;
push16!(af);
}
0xc1 => {
let b = &mut self.b;
let c = &mut self.c;
pop16!(b, c);
}
0xd1 => {
let d = &mut self.d;
let e = &mut self.e;
pop16!(d, e);
}
0xe1 => {
let h = &mut self.h;
let l = &mut self.l;
pop16!(h, l);
}
0xf1 => {
let mut flags = self.flags();
{
let f = &mut flags;
let a = &mut self.a;
pop16!(a, f);
}
self.set_flags(flags);
}
0xc3 => {
let _pc = self.pc;
let _addr = jump(self, bus);
disasm_pc!(_pc, "JP {:#x}", _addr);
}
0xc2 => {
if self.zerof != 0 {
self.wait = 12;
disasm!("JP NZ, <no_jump>");
self.pc += 2;
} else {
let _pc = self.pc;
let _addr = jump(self, bus);
disasm_pc!(_pc, "JP NZ, {:#x}", _addr);
}
}
0xd2 => {
if self.carryf != 0 {
self.wait = 12;
disasm!("JP NC, <no_jump>");
self.pc += 2;
} else {
let _pc = self.pc;
let _addr = jump(self, bus);
disasm_pc!(_pc, "JP NC, {:#x}", _addr);
}
}
0xca => {
if self.zerof == 0 {
self.wait = 12;
disasm!("JP Z, <no_jump>");
self.pc += 2;
} else {
let _pc = self.pc;
let _addr = jump(self, bus);
disasm_pc!(_pc, "JP Z, {:#x}", _addr);
}
}
0xda => {
if self.carryf == 0 {
self.wait = 12;
disasm!("JP C, <no_jump>");
self.pc += 2;
} else {
let _pc = self.pc;
let _addr = jump(self, bus);
disasm_pc!(_pc, "JP C, {:#x}", _addr);
}
}
0xe9 => {
let hl = ((self.h as u16) << 8) | self.l as u16;
disasm!("JP HL:{:#x}", hl);
self.wait = 4;
self.pc = u16::wrapping_sub(hl, 1);
}
0x18 => {
let _pc = self.pc;
let _addr = jrel(self, bus);
disasm_pc!(_pc, "JR {:#x}", _addr);
}
0x20 => {
if self.zerof == 0 {
let _pc = self.pc;
let _addr = jrel(self, bus);
disasm_pc!(_pc, "JR NZ, {:#x}", _addr);
} else {
self.wait = 8;
disasm!("JR NZ, <no_jump>");
self.pc += 1;
}
}
0x30 => {
if self.carryf == 0 {
let _pc = self.pc;
let _addr = jrel(self, bus);
disasm_pc!(_pc, "JR NC, {:#x}", _addr);
} else {
self.wait = 8;
disasm!("JR NC, <no_jump>");
self.pc += 1;
}
}
0x28 => {
if self.zerof != 0 {
let _pc = self.pc;
let _addr = jrel(self, bus);
disasm_pc!(_pc, "JR Z, {:#x}", _addr);
} else {
self.wait = 8;
disasm!("JR Z, <no_jump>");
self.pc += 1;
}
}
0x38 => {
if self.carryf != 0 {
let _pc = self.pc;
let _addr = jrel(self, bus);
disasm_pc!(_pc, "JR C, {:#x}", _addr);
} else {
self.wait = 8;
disasm!("JR C, <no_jump>");
self.pc += 1;
}
}
0xc7 => {
disasm!("RST 0x00");
self.call(bus, 0x00);
}
0xd7 => {
disasm!("RST 0x10");
self.call(bus, 0x10);
}
0xe7 => {
disasm!("RST 0x20");
self.call(bus, 0x20);
}
0xf7 => {
disasm!("RST 0x30");
self.call(bus, 0x30);
}
0xcf => {
disasm!("RST 0x08");
self.call(bus, 0x08);
}
0xdf => {
disasm!("RST 0x18");
self.call(bus, 0x18);
}
0xef => {
disasm!("RST 0x28");
self.call(bus, 0x28);
}
0xff => {
disasm!("RST 0x38");
self.call(bus, 0x38);
}
0xcd => {
let addr = bus.read16(self.pc + 1);
disasm!("CALL {:#x}", addr);
self.pc += 2;
self.call(bus, addr);
self.wait = 24;
}
0xc4 => {
let addr = bus.read16(self.pc + 1);
self.pc += 2;
if self.zerof == 0 {
disasm!("CALL NZ, {:#x}", addr);
self.call(bus, addr);
} else {
self.wait = 12;
disasm!("CALL NZ, <no_jump>");
}
}
0xd4 => {
let addr = bus.read16(self.pc + 1);
self.pc += 2;
if self.carryf == 0 {
disasm!("CALL NC, {:#x}", addr);
self.call(bus, addr);
self.wait = 24;
} else {
self.wait = 12;
disasm!("CALL NC, <no_jump>");
}
}
0xcc => {
let addr = bus.read16(self.pc + 1);
self.pc += 2;
if self.zerof != 0 {
disasm!("CALL Z, {:#x}", addr);
self.call(bus, addr);
self.wait = 24;
} else {
self.wait = 12;
disasm!("CALL Z, <no_jump>");
}
}
0xdc => {
let addr = bus.read16(self.pc + 1);
self.pc += 2;
if self.carryf != 0 {
disasm!("CALL C, {:#x}", addr);
self.call(bus, addr);
self.wait = 24;
} else {
self.wait = 12;
disasm!("CALL C, <no_jump>");
}
}
0xc9 => {
disasm!("RET");
self.ret(bus);
}
0xd9 => {
disasm!("RETI");
self.interrupts_enabled = true;
self.ret(bus);
}
0xc8 => {
if self.zerof != 0 {
disasm!("RET Z");
self.ret(bus);
self.wait = 20;
} else {
disasm!("RET Z <no jmp>");
self.wait = 8;
}
}
0xd0 => {
if self.carryf == 0 {
disasm!("RET NC");
self.ret(bus);
self.wait = 20;
} else {
disasm!("RET NC <no jmp>");
self.wait = 8;
}
}
0xc0 => {
if self.zerof == 0 {
disasm!("RET NZ");
self.ret(bus);
self.wait = 20;
} else {
disasm!("RET NZ <no jmp>");
self.wait = 8;
}
}
0xd8 => {
if self.carryf != 0 {
disasm!("RET C");
self.ret(bus);
self.wait = 20;
} else {
disasm!("RET C <no jmp>");
self.wait = 8;
}
}
0xF3 => {
self.wait = 4;
self.interrupts_enabled = false;
disasm!("DI");
}
0xfb => {
self.wait = 4;
self.interrupts_enabled = true;
disasm!("EI");
}
0xe8 => {
let r8 = bus.read(self.pc + 1);
disasm!("ADD SP, r8:{:#x}", r8);
self.pc += 1;
let new_sp = u16::wrapping_add(self.sp, r8 as i8 as i16 as u16);
self.zerof = 0;
self.add_subf = 0;
let (_, carry) = u8::overflowing_add(self.sp as u8, r8);
self.carryf = carry as u8;
self.half_carryf = if ((self.sp & 0xf) as u8 + (r8 & 0xf)) & 0x10 != 0 {
1
} else {
0
};
self.sp = new_sp;
}
0x2f => {
self.wait = 4;
self.half_carryf = 1;
self.add_subf = 1;
self.a = !self.a;
disasm!("CPL");
}
0x3f => {
self.wait = 4;
self.half_carryf = 0;
self.add_subf = 0;
self.carryf = if self.carryf != 0 { 0 } else { 1 };
disasm!("CCF");
}
0x07 => {
self.wait = 4;
self.zerof = 0;
self.half_carryf = 0;
self.add_subf = 0;
self.a = u8::rotate_left(self.a, 1);
self.carryf = self.a & 1;
disasm!("RLCA");
}
0x17 => {
self.wait = 4;
self.zerof = 0;
self.half_carryf = 0;
self.add_subf = 0;
let a = (self.a as u16) << 1;
self.a = a as u8 | self.carryf;
self.carryf = (a >> 8 & 1) as u8;
disasm!("RLA");
}
0x0f => {
self.wait = 4;
self.zerof = 0;
self.half_carryf = 0;
self.add_subf = 0;
self.a = u8::rotate_right(self.a, 1);
self.carryf = self.a >> 7 & 1;
disasm!("RRCA");
}
0x1f => {
self.wait = 4;
self.zerof = 0;
self.half_carryf = 0;
self.add_subf = 0;
let prev_cary = self.carryf;
self.carryf = self.a & 1;
self.a = self.a >> 1 | prev_cary << 7;
disasm!("RRA");
}
0x37 => {
self.wait = 4;
self.half_carryf = 0;
self.add_subf = 0;
self.carryf = 1;
disasm!("SCF");
}
0x76 => {
// HALT
self.wait = 4;
self.halted = true;
disasm!("HALT");
if self.interrupts_enabled {
self.pc -= 1;
} else {
self.wait = 8;
}
}
0x10 => {
// STOP
self.wait = 32;
bus.timer.reset_div();
self.halted = true;
disasm!("STOP");
}
0x27 => {
// note: assumes a is a uint8_t and wraps from 0xff to 0
if self.add_subf == 0 {
// after an addition, adjust if (half-)carry occurred or if result is out of bounds
if self.carryf != 0 || self.a > 0x99 {
self.a += 0x60;
self.carryf = 1;
}
if self.half_carryf != 0 || (self.a & 0x0f) > 0x09 {
self.a += 0x6;
}
} else {
// after a subtraction, only adjust if (half-)carry occurred
if self.carryf != 0 {
self.a -= 0x60;
}
if self.half_carryf != 0 {
self.a -= 0x6;
}
}
// these flags are always updated
self.zerof = if self.a == 0 {1} else {0}; // the usual z flag
self.half_carryf = 0; // h flag is always cleared
disasm!("DAA");
}
0xcb => {
self.pc += 1;
self.cb_ext(bus);
}
_ => {
eprintln!("Unknown opcode at 0x{:x} : 0x{:x}", self.pc, op);
}
};
self.pc = u16::wrapping_add(self.pc, 1);
}
fn cb_ext(&mut self, bus: &mut Bus) {
macro_rules! disasm {
($($arg:tt)+) => (
#[cfg(feature = "disasm")]
{
print!("0x{:<8x}: ", self.pc - 1);
println!($($arg)+);
}
)
}
macro_rules! sub_match {
($opcode:ident, $operation:ident) => {
match $opcode & 0x7 {
0x00 => {
self.wait = 8;
self.b = self.$operation(self.b, ($opcode & 0x38) >> 3);
disasm!("{} B, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x01 => {
self.wait = 8;
self.c = self.$operation(self.c, ($opcode & 0x38) >> 3);
disasm!("{} C, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x02 => {
self.wait = 8;
self.d = self.$operation(self.d, ($opcode & 0x38) >> 3);
disasm!("{} D, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x03 => {
self.wait = 8;
self.e = self.$operation(self.e, ($opcode & 0x38) >> 3);
disasm!("{} E, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x04 => {
self.wait = 8;
self.h = self.$operation(self.h, ($opcode & 0x38) >> 3);
disasm!("{} H, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x05 => {
self.wait = 8;
self.l = self.$operation(self.l, ($opcode & 0x38) >> 3);
disasm!("{} L, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x07 => {
self.wait = 8;
self.a = self.$operation(self.a, ($opcode & 0x38) >> 3);
disasm!("{} A, {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
0x06 => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.$operation(bus.read(hl), ($opcode & 0x38) >> 3));
disasm!("{} (HL), {}", stringify!($operation), ($opcode & 0x38) >> 3);
}
_ => panic!("Invalid cb submatch {:#x}", $opcode),
}
};
}
let op = bus.read(self.pc);
match op {
0x00 => {
self.wait = 8;
self.b = self.rlc(self.b);
disasm!("rlc B");
}
0x01 => {
self.wait = 8;
self.c = self.rlc(self.c);
disasm!("rlc C");
}
0x02 => {
self.wait = 8;
self.d = self.rlc(self.d);
disasm!("rlc D");
}
0x03 => {
self.wait = 8;
self.e = self.rlc(self.e);
disasm!("rlc E");
}
0x04 => {
self.wait = 8;
self.h = self.rlc(self.h);
disasm!("rlc H");
}
0x05 => {
self.wait = 8;
self.l = self.rlc(self.l);
disasm!("rlc L");
}
0x07 => {
self.wait = 8;
self.a = self.rlc(self.a);
disasm!("rlc A");
}
0x06 => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.rlc(bus.read(hl)));
disasm!("rlc (HL)");
}
0x08 => {
self.wait = 8;
self.b = self.rrc(self.b);
disasm!("rrc B");
}
0x09 => {
self.wait = 8;
self.c = self.rrc(self.c);
disasm!("rrc C");
}
0x0a => {
self.wait = 8;
self.d = self.rrc(self.d);
disasm!("rrc D");
}
0x0b => {
self.wait = 8;
self.e = self.rrc(self.e);
disasm!("rrc E");
}
0x0c => {
self.wait = 8;
self.h = self.rrc(self.h);
disasm!("rrc H");
}
0x0d => {
self.wait = 8;
self.l = self.rrc(self.l);
disasm!("rrc L");
}
0x0f => {
self.wait = 8;
self.a = self.rrc(self.a);
disasm!("rrc A");
}
0x0e => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.rrc(bus.read(hl)));
disasm!("rrc (HL)");
}
0x10 => {
self.wait = 8;
self.b = self.rl(self.b);
disasm!("rl B");
}
0x11 => {
self.wait = 8;
self.c = self.rl(self.c);
disasm!("rl C");
}
0x12 => {
self.wait = 8;
self.d = self.rl(self.d);
disasm!("rl D");
}
0x13 => {
self.wait = 8;
self.e = self.rl(self.e);
disasm!("rl E");
}
0x14 => {
self.wait = 8;
self.h = self.rl(self.h);
disasm!("rl H");
}
0x15 => {
self.wait = 8;
self.l = self.rl(self.l);
disasm!("rl L");
}
0x17 => {
self.wait = 8;
self.a = self.rl(self.a);
disasm!("rl A");
}
0x16 => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.rl(bus.read(hl)));
disasm!("rl (HL)");
}
0x18 => {
self.wait = 8;
self.b = self.rr(self.b);
disasm!("rr B");
}
0x19 => {
self.wait = 8;
self.c = self.rr(self.c);
disasm!("rr C");
}
0x1a => {
self.wait = 8;
self.d = self.rr(self.d);
disasm!("rr D");
}
0x1b => {
self.wait = 8;
self.e = self.rr(self.e);
disasm!("rr E");
}
0x1c => {
self.wait = 8;
self.h = self.rr(self.h);
disasm!("rr H");
}
0x1d => {
self.wait = 8;
self.l = self.rr(self.l);
disasm!("rr L");
}
0x1f => {
self.wait = 8;
self.a = self.rr(self.a);
disasm!("rr A");
}
0x1e => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.rr(bus.read(hl)));
disasm!("rr (HL)");
}
0x20 => {
self.wait = 8;
self.b = self.sla(self.b);
disasm!("SLA B");
}
0x21 => {
self.wait = 8;
self.c = self.sla(self.c);
disasm!("SLA C");
}
0x22 => {
self.wait = 8;
self.d = self.sla(self.d);
disasm!("SLA D");
}
0x23 => {
self.wait = 8;
self.e = self.sla(self.e);
disasm!("SLA E");
}
0x24 => {
self.wait = 8;
self.h = self.sla(self.h);
disasm!("SLA H");
}
0x25 => {
self.wait = 8;
self.l = self.sla(self.l);
disasm!("SLA L");
}
0x27 => {
self.wait = 8;
self.a = self.sla(self.a);
disasm!("SLA A");
}
0x26 => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.sla(bus.read(hl)));
disasm!("SLA (HL)");
}
0x28 => {
self.wait = 8;
self.b = self.sra(self.b);
disasm!("sra B");
}
0x29 => {
self.wait = 8;
self.c = self.sra(self.c);
disasm!("sra C");
}
0x2a => {
self.wait = 8;
self.d = self.sra(self.d);
disasm!("sra D");
}
0x2b => {
self.wait = 8;
self.e = self.sra(self.e);
disasm!("sra E");
}
0x2c => {
self.wait = 8;
self.h = self.sra(self.h);
disasm!("sra H");
}
0x2d => {
self.wait = 8;
self.l = self.sra(self.l);
disasm!("sra L");
}
0x2f => {
self.wait = 8;
self.a = self.sra(self.a);
disasm!("sra A");
}
0x2e => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.sra(bus.read(hl)));
disasm!("sra (HL)");
}
0x30 => {
self.wait = 8;
self.b = self.swap(self.b);
disasm!("swap B");
}
0x31 => {
self.wait = 8;
self.c = self.swap(self.c);
disasm!("swap C");
}
0x32 => {
self.wait = 8;
self.d = self.swap(self.d);
disasm!("swap D");
}
0x33 => {
self.wait = 8;
self.e = self.swap(self.e);
disasm!("swap E");
}
0x34 => {
self.wait = 8;
self.h = self.swap(self.h);
disasm!("swap H");
}
0x35 => {
self.wait = 8;
self.l = self.swap(self.l);
disasm!("swap L");
}
0x37 => {
self.wait = 8;
self.a = self.swap(self.a);
disasm!("swap A");
}
0x36 => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.swap(bus.read(hl)));
disasm!("swap (HL)");
}
0x38 => {
self.wait = 8;
self.b = self.srl(self.b);
disasm!("srl B");
}
0x39 => {
self.wait = 8;
self.c = self.srl(self.c);
disasm!("srl C");
}
0x3a => {
self.wait = 8;
self.d = self.srl(self.d);
disasm!("srl D");
}
0x3b => {
self.wait = 8;
self.e = self.srl(self.e);
disasm!("srl E");
}
0x3c => {
self.wait = 8;
self.h = self.srl(self.h);
disasm!("srl H");
}
0x3d => {
self.wait = 8;
self.l = self.srl(self.l);
disasm!("srl L");
}
0x3f => {
self.wait = 8;
self.a = self.srl(self.a);
disasm!("srl A");
}
0x3e => {
self.wait = 16;
let hl = (self.h as u16) << 8 | self.l as u16;
bus.write(hl, self.srl(bus.read(hl)));
disasm!("srl (HL)");
}
x if x & 0xc0 == 0x80 => {
sub_match!(x, res);
}
x if x & 0xc0 == 0x40 => {
sub_match!(x, bit);
}
x if x & 0xc0 == 0xC0 => {
sub_match!(x, set);
}
_ => eprintln!("{:#x}: CB not supported : {:#x}", self.pc, op),
}
}
fn sla(&mut self, val: u8) -> u8 {
let res = (val as u16) << 1;
self.carryf = (res >> 8 & 1) as u8;
self.zerof = if res & 0xff != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn sra(&mut self, val: u8) -> u8 {
let mut res = val >> 1;
res |= val & 0x80;
self.carryf = (val & 1) as u8;
self.zerof = if res != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn rlc(&mut self, val: u8) -> u8 {
let res = u8::rotate_left(val, 1);
self.carryf = (res & 1) as u8;
self.zerof = if res != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn rrc(&mut self, val: u8) -> u8 {
let res = u8::rotate_right(val, 1);
self.carryf = (res >> 7 & 1) as u8;
self.zerof = if res != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn rl(&mut self, val: u8) -> u8 {
let mut res = (val as u16) << 1;
res |= self.carryf as u16;
self.carryf = (res >> 8 & 1) as u8;
self.zerof = if res as u8 != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn rr(&mut self, val: u8) -> u8 {
let mut res = (val as u16) << 7;
res |= (self.carryf as u16) << 15;
res >>= 8;
self.carryf = (val & 1) as u8;
self.zerof = if res as u8 != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn swap(&mut self, val: u8) -> u8 {
let h = val >> 4;
let l = val & 0xf;
let res = l << 4 | h;
self.carryf = 0;
self.zerof = if res != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn srl(&mut self, val: u8) -> u8 {
let res = val >> 1;
self.carryf = (val & 1) as u8;
self.zerof = if res != 0 { 0 } else { 1 };
self.half_carryf = 0;
self.add_subf = 0;
res as u8
}
fn res(&self, val: u8, index: u8) -> u8 {
val & !(1 << index)
}
fn set(&self, val: u8, index: u8) -> u8 {
val | (1 << index)
}
fn bit(&mut self, val: u8, index: u8) -> u8 {
self.add_subf = 0;
self.half_carryf = 1;
self.zerof = if val >> index & 1 == 0 { 1 } else { 0 };
val
}
/*
let mut hl = (self.h as u16) << 8 | self.l as u16;
*/
}
|
use crate::{
grammar::gen_arg_list, grammar::param_list, grammar::pure_expr, grammar::ty, grammar::var_name,
grammar::Parser, parser::Marker, SyntaxKind::*, T,
};
pub(crate) fn maybe_par_fn(p: &mut Parser, m: Marker) {
p.bump(T![def]);
ty(p);
if p.at(T![<]) {
gen_arg_list(p);
}
let par = if p.nth_at(1, T![lower_ident]) || p.nth_at(2, T![')']) {
p.expect(T!['(']);
fn_name_list(p);
p.expect(T![')']);
true
} else {
false
};
param_list(p);
p.expect(T![=]);
if par && p.at(T![builtin]) {
p.bump(T![builtin]);
} else {
pure_expr(p);
}
p.expect(T![;]);
m.complete(
p,
if par {
PAR_FUNCTION_DECL
} else {
FUNCTION_DECL
},
);
}
fn fn_name_list(p: &mut Parser) {
let m = p.start();
if p.at(T![lower_ident]) {
var_name(p);
while p.eat(T![,]) {
var_name(p);
}
}
m.complete(p, FUNCTION_NAME_LIST);
}
|
use std::collections::HashMap;
mod aoc_2019_01;
mod aoc_2019_02;
mod aoc_2019_03;
mod aoc_2019_04;
mod aoc_2019_05;
mod aoc_2019_07;
mod aoc_2019_08;
mod aoc_2019_09;
mod aoc_2019_11;
mod aoc_2019_13;
mod aoc_2019_15;
mod aoc_2019_22;
pub mod cli;
pub mod fs;
mod geom2d;
mod guess_number;
mod intcode;
mod plane;
mod temp_convert;
pub struct Utilities<'a> {
utilities: HashMap<&'a str, fn()>,
names: Vec<&'a str>,
}
impl<'a> Utilities<'a> {
pub fn new() -> Utilities<'a> {
let mut utilities: HashMap<&str, fn()> = HashMap::new();
// todo: "add Sally to Engineering" / "show Engineering" interface
// todo: convert strings to pig latin
// todo: mean/median/mode of list of integers
// todo: 12 days of christmas
// todo: fibonacci
utilities.insert("temp", temp_convert::run);
utilities.insert("guess", guess_number::run);
utilities.insert("aoc_2019_01", aoc_2019_01::run);
utilities.insert("aoc_2019_02", aoc_2019_02::run);
utilities.insert("aoc_2019_03", aoc_2019_03::run);
utilities.insert("aoc_2019_04", aoc_2019_04::run);
utilities.insert("aoc_2019_05", aoc_2019_05::run);
utilities.insert("aoc_2019_07", aoc_2019_07::run);
utilities.insert("aoc_2019_08", aoc_2019_08::run);
utilities.insert("aoc_2019_09", aoc_2019_09::run);
utilities.insert("aoc_2019_11", aoc_2019_11::run);
utilities.insert("aoc_2019_13", aoc_2019_13::run);
utilities.insert("aoc_2019_15", aoc_2019_15::run);
utilities.insert("aoc_2019_22", aoc_2019_22::run);
let mut names: Vec<&str> = utilities.iter().map(|(k, _)| *k).collect();
names.sort_unstable();
Utilities { utilities, names }
}
pub fn names(&self) -> &Vec<&str> {
&self.names
}
pub fn by_name(&self, name: &str) -> Option<&fn()> {
self.utilities.get(name)
}
}
#[test]
fn aoc_should_not_smoke() {
let utils = Utilities::new();
utils
.names()
.iter()
.filter(|n| n.starts_with("aoc_"))
// this one takes ~5 seconds, so skip it
.filter(|&&n| n != "aoc_2019_13")
.for_each(|&n| {
println!("-- {} --------------------------------------------", n);
if let Ok(_) = std::fs::read_to_string(n.to_owned() + ".txt") {
utils.by_name(n).unwrap()()
} else {
println!("... no input file found - skipping ...")
}
})
}
|
/// Given two 32-bit numbers `n` and `m`, return the number `m` merged into `n`.
///
/// ## Examples
/// ```
/// use ctci_6th_edition::ch5::insertion;
///
/// assert_eq!(0b10001001100, insertion(0b10000000000, 0b10011, 2, 6));
/// ```
pub fn insertion(n: u32, m: u32, i: u32, j: u32) -> u32 {
let m_shifted = m << i;
let mask = !((1 << (j - i + 2)) - 1 << i);
n & mask | m_shifted
}
|
use bindings::{
Windows::Win32::Graphics::Direct3D11::*, Windows::Win32::Graphics::Direct3D12::*,
Windows::Win32::Graphics::DirectComposition::*, Windows::Win32::Graphics::Dxgi::*,
Windows::Win32::Graphics::Gdi::*, Windows::Win32::Graphics::Hlsl::*,
Windows::Win32::System::SystemServices::*, Windows::Win32::System::Threading::*,
Windows::Win32::UI::DisplayDevices::*, Windows::Win32::UI::KeyboardAndMouseInput::*,
Windows::Win32::UI::MenusAndResources::*, Windows::Win32::UI::WindowsAndMessaging::*,
};
use directx_math::*;
use dx12_common::{
cd3dx12_blend_desc_default, cd3dx12_depth_stencil_desc_default,
cd3dx12_heap_properties_with_type, cd3dx12_rasterizer_desc_default,
cd3dx12_resource_barrier_transition, create_default_buffer, UploadBuffer,
};
use std::{borrow::BorrowMut, ptr::null_mut};
use std::{convert::TryInto, ffi::CString};
use windows::Interface;
const NUM_OF_FRAMES: usize = 3;
#[derive(Debug)]
#[repr(C)]
struct SceneConstantBuffer {
/// Projection transformation matrix
proj: XMFLOAT4X4,
/// View transformation matrix
view: XMFLOAT4X4,
}
#[derive(Debug)]
#[repr(C)]
struct ObjectConstantBuffer {
/// World transformation matrix
///
/// This determines the location/orientation/scale of the single cube in the
/// world
world: XMFLOAT4X4,
}
#[derive(Debug)]
#[repr(C)]
struct Vertex {
position: XMFLOAT3,
color: XMFLOAT4,
}
impl Vertex {
fn new(position: [f32; 3], color: [f32; 4]) -> Self {
Self {
position: position.into(),
color: color.into(),
}
}
}
#[derive(Debug)]
#[repr(C)]
struct InstanceData {
world: XMFLOAT4X4,
}
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
const MAGENTA: [f32; 4] = [1.0, 0.0, 1.0, 1.0];
const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0];
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
#[derive(Debug)]
#[repr(C)]
struct FrameResource {
fence_value: u64,
allocator: ID3D12CommandAllocator,
list: ID3D12GraphicsCommandList,
scene_cb: UploadBuffer<SceneConstantBuffer>,
object_cb: UploadBuffer<ObjectConstantBuffer>,
}
impl FrameResource {
pub fn new(device: &ID3D12Device, pso: &ID3D12PipelineState) -> Self {
// Create allocator for the frame
let allocator = unsafe {
device.CreateCommandAllocator::<ID3D12CommandAllocator>(
D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT,
)
}
.expect("Unable to create allocator");
// Create command list for the frame
let list: ID3D12GraphicsCommandList = unsafe {
device.CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT,
&allocator,
pso,
)
}
.expect("Unable to create command list");
// Command list must be closed on create
unsafe {
list.Close().ok().expect("Unable to close the list");
}
let scene_cb = UploadBuffer::new(
// &cbv_heap,
&device,
&SceneConstantBuffer {
..unsafe { std::mem::zeroed() }
},
)
.unwrap();
let object_cb = UploadBuffer::new(
&device,
&ObjectConstantBuffer {
world: {
// Cube is sized 10x10x10, and placed in the origo
let world = XMMatrixIdentity();
let world = XMMatrixMultiply(world, &XMMatrixScaling(10.0, 10.0, 1.0));
let world = XMMatrixMultiply(world, &XMMatrixTranslation(0.0, 0.0, 0.0));
let mut out: XMFLOAT4X4 = unsafe { std::mem::zeroed() };
XMStoreFloat4x4(&mut out, world);
out
},
},
)
.expect("Got it");
FrameResource {
fence_value: 1,
allocator,
list,
scene_cb,
object_cb,
}
}
pub fn update_constant_buffers(&mut self, camera: &Camera) {
let (proj, view) = camera.get_proj_view(55.0, 1.0, 1020.0, 1024.0, 1024.0);
self.scene_cb.update(&SceneConstantBuffer { view, proj })
}
}
struct Camera {
/// Location of the camera
eye: XMVECTOR,
/// Position the camera is looking at
at: XMVECTOR,
/// Up vector of camera
up: XMVECTOR,
}
/// Camera
///
/// This closely follows:
/// https://github.com/microsoft/DirectX-Graphics-Samples/blob/master/Samples/Desktop/D3D12Multithreading/src/Camera.cpp
impl Camera {
pub fn get_proj_view(
&self,
fov_deg: f32,
near_z: f32,
far_z: f32,
width: f32,
height: f32,
) -> (XMFLOAT4X4, XMFLOAT4X4) {
let ar = width / height;
let fov_angle_y = if ar < 1.0 {
fov_deg * XM_PI / 180.0 / ar
} else {
fov_deg * XM_PI / 180.0
};
let mut view: XMFLOAT4X4 = unsafe { std::mem::zeroed() };
let mut proj: XMFLOAT4X4 = unsafe { std::mem::zeroed() };
// The DirectX math (XMMATRIX) acts on row-major matrices and
// transposing it changes it to column-major format for HLSL
XMStoreFloat4x4(
&mut view,
XMMatrixTranspose(XMMatrixLookAtLH(self.eye, self.at, self.up)),
);
XMStoreFloat4x4(
&mut proj,
XMMatrixTranspose(XMMatrixPerspectiveFovLH(fov_angle_y, ar, near_z, far_z)),
);
(proj, view)
}
pub fn rotate_yaw(&mut self, radians: f32) {
let rotation = XMMatrixRotationAxis(self.up, radians);
self.eye = XMVector3TransformCoord(self.eye, rotation);
}
pub fn rotate_pitch(&mut self, radians: f32) {
let right = XMVector3Normalize(XMVector3Cross(self.eye, self.up));
let rotation = XMMatrixRotationAxis(right, radians);
self.eye = XMVector3TransformCoord(self.eye, rotation);
}
}
#[allow(dead_code)]
struct Window {
hwnd: HWND,
factory: IDXGIFactory4,
adapter: IDXGIAdapter1,
device: ID3D12Device,
queue: ID3D12CommandQueue,
comp_device: IDCompositionDevice,
swap_chain: IDXGISwapChain3,
current_frame: usize,
comp_target: IDCompositionTarget,
comp_visual: IDCompositionVisual,
back_buffer_rtv_heap: ID3D12DescriptorHeap,
back_buffers: [(ID3D12Resource, D3D12_CPU_DESCRIPTOR_HANDLE); NUM_OF_FRAMES],
depth_stencil_heap: ID3D12DescriptorHeap,
depth_stencil_buffer: ID3D12Resource,
root_signature: ID3D12RootSignature,
vertex_shader: ID3DBlob,
pixel_shader: ID3DBlob,
pipeline_state: ID3D12PipelineState,
viewport: D3D12_VIEWPORT,
scissor: RECT,
fence: ID3D12Fence,
fence_event: HANDLE,
fence_value: u64,
// Resources
vertex_buffer: ID3D12Resource,
vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW,
indices_buffer: ID3D12Resource,
indices_buffer_view: D3D12_INDEX_BUFFER_VIEW,
instance_buffer: ID3D12Resource,
frame_resources: [FrameResource; NUM_OF_FRAMES],
camera: Camera,
}
impl Window {
pub fn new(hwnd: HWND) -> windows::Result<Self> {
// Start "DebugView" to listen errors
// https://docs.microsoft.com/en-us/sysinternals/downloads/debugview
let debug = unsafe { D3D12GetDebugInterface::<ID3D12Debug1>() }
.expect("Unable to create debug layer");
unsafe {
debug.EnableDebugLayer();
debug.SetEnableGPUBasedValidation(true);
debug.SetEnableSynchronizedCommandQueueValidation(true);
}
let factory = unsafe { CreateDXGIFactory2::<IDXGIFactory4>(0) }?;
let adapter = (0..99)
.into_iter()
.find_map(|i| unsafe {
let mut ptr: Option<IDXGIAdapter1> = None;
factory.EnumAdapters1(i, &mut ptr).and_some(ptr).ok()
})
.expect("Could not find d3d adapter");
let device: ID3D12Device = unsafe {
D3D12CreateDevice(
&adapter, // None for default adapter
D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_11_0,
)
}?;
let queue = unsafe {
let desc = D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT,
Priority: D3D12_COMMAND_QUEUE_PRIORITY::D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
Flags: D3D12_COMMAND_QUEUE_FLAGS::D3D12_COMMAND_QUEUE_FLAG_NONE,
NodeMask: 0,
};
device.CreateCommandQueue::<ID3D12CommandQueue>(&desc)
}?;
// let allocators: [ID3D12CommandAllocator; NUM_OF_FRAMES] = (0..NUM_OF_FRAMES)
// .map(|_| unsafe {
// let mut ptr: Option<ID3D12CommandAllocator> = None;
// device
// .CreateCommandAllocator(
// D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT,
// &ID3D12CommandAllocator::IID,
// ptr.set_abi(),
// )
// .and_some(ptr)
// .expect("Unable to create allocator")
// })
// .collect::<Vec<_>>()
// .try_into()
// .expect("Unable to create allocators");
// Composition device
let comp_device: IDCompositionDevice = unsafe { DCompositionCreateDevice(None) }?;
// Create swap chain for composition
let swap_chain = unsafe {
let desc = DXGI_SWAP_CHAIN_DESC1 {
AlphaMode: DXGI_ALPHA_MODE::DXGI_ALPHA_MODE_PREMULTIPLIED,
BufferCount: NUM_OF_FRAMES as _,
Width: 1024,
Height: 1024,
Format: DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM,
Flags: 0,
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Scaling: DXGI_SCALING::DXGI_SCALING_STRETCH,
Stereo: BOOL(0),
SwapEffect: DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,
};
let mut ptr: Option<IDXGISwapChain1> = None;
factory
.CreateSwapChainForComposition(&queue, &desc, None, &mut ptr)
.and_some(ptr)
}?
.cast::<IDXGISwapChain3>()?;
// Current frame index
let current_frame = unsafe { swap_chain.GetCurrentBackBufferIndex() as usize };
// Create IDCompositionTarget for the window
let comp_target = unsafe {
let mut ptr = None;
comp_device
.CreateTargetForHwnd(hwnd, BOOL(1), &mut ptr)
.and_some(ptr)
}?;
// Create IDCompositionVisual for the window
let comp_visual = unsafe {
let mut ptr = None;
comp_device.CreateVisual(&mut ptr).and_some(ptr)
}?;
// Set swap_chain and the root visual and commit
unsafe {
comp_visual.SetContent(&swap_chain).ok()?;
comp_target.SetRoot(&comp_visual).ok()?;
comp_device.Commit().ok()?;
}
// Create descriptor heap for back buffer render target views
let back_buffer_rtv_heap = unsafe {
let desc = D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
NumDescriptors: NUM_OF_FRAMES as _,
Flags: D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
NodeMask: 0,
};
device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc)
}?;
// Create back buffers with their rtvs
let back_buffers = {
let rtv = unsafe { back_buffer_rtv_heap.GetCPUDescriptorHandleForHeapStart() };
let rtv_desc_size = unsafe {
device.GetDescriptorHandleIncrementSize(
D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
) as usize
};
(0..NUM_OF_FRAMES)
.map(|i| {
let mut rtv = rtv.clone();
rtv.ptr += rtv_desc_size * i;
let resource = unsafe { swap_chain.GetBuffer::<ID3D12Resource>(i as _) }?;
unsafe {
// let desc = D3D12_TEX2D_RTV {
// Format: DXGI_FORMAT_R8G8B8A8_UNORM,
// u: D3D12_RTV_DIMENSION_UNKNOWN as _,
// ViewDimension: 0,
// };
device.CreateRenderTargetView(&resource, 0 as _, &rtv);
}
Ok((resource, rtv))
})
.collect::<Result<Vec<_>, windows::Error>>()?
.try_into()
.expect("Unable to create resources")
};
// Create depth/stencil heap
let depth_stencil_heap = unsafe {
let desc = D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
NumDescriptors: 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
NodeMask: 0,
};
device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc)
}?;
// Create depth/stencil buffer
let depth_stencil_buffer = unsafe {
device.CreateCommittedResource::<ID3D12Resource>(
&cd3dx12_heap_properties_with_type(D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Alignment: 0,
Width: 1024,
Height: 1024,
// If DXGI_SWAP_CHAIN_DESC1::Stereo is TRUE (3d glasses
// support) following array size needs to be 2:
DepthOrArraySize: 1,
MipLevels: 1,
Dimension: D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Format: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT,
Flags: D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
..std::mem::zeroed()
},
// D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_DEPTH_WRITE,
&D3D12_CLEAR_VALUE {
Format: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT,
Anonymous: D3D12_CLEAR_VALUE_0 {
DepthStencil: D3D12_DEPTH_STENCIL_VALUE {
Depth: 1.0,
Stencil: 0,
},
},
},
)
}?;
unsafe {
device.CreateDepthStencilView(
&depth_stencil_buffer,
null_mut(),
// &D3D12_DEPTH_STENCIL_VIEW_DESC {
// format: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT,
// view_dimension: D3D12_DSV_DIMENSION::D3D12_DSV_DIMENSION_TEXTURE2D,
// flags: D3D12_DSV_FLAGS::D3D12_DSV_FLAG_NONE,
// ..std::mem::zeroed()
// },
depth_stencil_heap.GetCPUDescriptorHandleForHeapStart(),
)
}
// Creation of constant buffer begins here -----------------------------
//
// Steps are roughly:
//
// 1. Create a heap
// 2. Create a constant buffer resource as upload buffer, send your
// initial value there
// 3. Assign your constant buffers to the root_signature
//
// Note that there needs to be as many buffers as there are frames so
// that you don't end up updating in-use buffer. In this example however
// the value is not updated after the initial value.
// Create constant buffer heaps
// let cbv_heap: ID3D12DescriptorHeap = unsafe {
// let mut ptr: Option<ID3D12DescriptorHeap> = None;
// device
// .CreateDescriptorHeap(
// &D3D12_DESCRIPTOR_HEAP_DESC {
// r#type: D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
// num_descriptors: 1,
// flags:
// D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
// node_mask: 0,
// },
// &ID3D12DescriptorHeap::IID,
// ptr.set_abi(),
// )
// .and_some(ptr)
// .unwrap()
// };
// Create root signature
let root_signature = unsafe {
let root = {
let mut blob: Option<ID3DBlob> = None;
let mut error: Option<ID3DBlob> = None;
let mut params = [
D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE::D3D12_ROOT_PARAMETER_TYPE_CBV,
Anonymous: D3D12_ROOT_PARAMETER_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR {
RegisterSpace: 0,
ShaderRegister: 0,
},
},
ShaderVisibility: D3D12_SHADER_VISIBILITY::D3D12_SHADER_VISIBILITY_VERTEX,
},
D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE::D3D12_ROOT_PARAMETER_TYPE_CBV,
Anonymous: D3D12_ROOT_PARAMETER_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR {
RegisterSpace: 0,
ShaderRegister: 1,
},
},
ShaderVisibility: D3D12_SHADER_VISIBILITY::D3D12_SHADER_VISIBILITY_VERTEX,
},
D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE::D3D12_ROOT_PARAMETER_TYPE_SRV,
Anonymous: D3D12_ROOT_PARAMETER_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR {
RegisterSpace: 1,
ShaderRegister: 0,
},
},
ShaderVisibility: D3D12_SHADER_VISIBILITY::D3D12_SHADER_VISIBILITY_ALL,
},
];
let desc = D3D12_ROOT_SIGNATURE_DESC {
NumParameters: params.len() as _,
pParameters: params.as_mut_ptr(),
NumStaticSamplers: 0,
pStaticSamplers: null_mut() as _,
Flags: D3D12_ROOT_SIGNATURE_FLAGS::from(
D3D12_ROOT_SIGNATURE_FLAGS::D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT.0 |
D3D12_ROOT_SIGNATURE_FLAGS::D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS.0 |
D3D12_ROOT_SIGNATURE_FLAGS::D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS.0 |
D3D12_ROOT_SIGNATURE_FLAGS::D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS.0
)
,
};
D3D12SerializeRootSignature(
&desc,
D3D_ROOT_SIGNATURE_VERSION::D3D_ROOT_SIGNATURE_VERSION_1_0,
&mut blob as _,
&mut error as _,
)
.and_then(|| {
if error.is_none() {
blob.unwrap()
} else {
panic!("Root signature failed, error blob contains the error")
}
})
}.expect("Unable to serialize root signature");
device.CreateRootSignature::<ID3D12RootSignature>(
0,
root.GetBufferPointer(),
root.GetBufferSize(),
)
}.expect("Unable to create root signature");
// End of constant buffer changes ----------------------------------
let vertex_shader = unsafe {
let data = include_bytes!("./06-instancing.hlsl");
let mut err: Option<ID3DBlob> = None;
let mut ptr: Option<ID3DBlob> = None;
D3DCompile(
data.as_ptr() as *mut _,
data.len(),
PSTR("shaders.hlsl\0".as_ptr() as _),
null_mut(),
None,
PSTR("VSMain\0".as_ptr() as _),
PSTR("vs_5_1\0".as_ptr() as _),
0,
0,
&mut ptr,
&mut err,
)
.ok()
.expect("Unable to compile shader");
match ptr {
Some(v) => v,
None => {
panic!(
"Shader creation failed with error {}",
CString::from_raw(err.unwrap().GetBufferPointer() as _).to_string_lossy()
)
}
}
};
let pixel_shader = unsafe {
let data = include_bytes!("./06-instancing.hlsl");
let mut err: Option<ID3DBlob> = None;
let mut ptr: Option<ID3DBlob> = None;
D3DCompile(
data.as_ptr() as *mut _,
data.len(),
PSTR("shaders.hlsl\0".as_ptr() as _),
null_mut(),
None,
PSTR("PSMain\0".as_ptr() as _),
PSTR("ps_5_1\0".as_ptr() as _),
0,
0,
&mut ptr,
&mut err,
)
.ok()
.expect("Unable to compile shader");
match ptr {
Some(v) => v,
None => {
panic!(
"Shader creation failed with error {}",
CString::from_raw(err.unwrap().GetBufferPointer() as _).to_string_lossy()
)
}
}
};
let mut els = [
D3D12_INPUT_ELEMENT_DESC {
SemanticName: PSTR("POSITION\0".as_ptr() as _),
SemanticIndex: 0,
Format: DXGI_FORMAT::DXGI_FORMAT_R32G32B32_FLOAT,
InputSlot: 0,
AlignedByteOffset: 0,
InputSlotClass:
D3D12_INPUT_CLASSIFICATION::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
InstanceDataStepRate: 0,
},
D3D12_INPUT_ELEMENT_DESC {
SemanticName: PSTR("COLOR\0".as_ptr() as _),
SemanticIndex: 0,
Format: DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT,
InputSlot: 0,
AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT,
InputSlotClass:
D3D12_INPUT_CLASSIFICATION::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
InstanceDataStepRate: 0,
},
// D3D12_INPUT_ELEMENT_DESC {
// SemanticName: PSTR("POSINSTANCED\0".as_ptr() as _),
// SemanticIndex: 0,
// Format: DXGI_FORMAT::DXGI_FORMAT_R32G32B32_FLOAT,
// InputSlot: 1,
// AlignedByteOffset: 0,
// InputSlotClass:
// D3D12_INPUT_CLASSIFICATION::D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA,
// InstanceDataStepRate: 0,
// },
];
let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// TODO: Can I get rid of this clone? Or do I even have to?
pRootSignature: Some(root_signature.clone()),
// unsafe { std::mem::transmute(root_signature.abi()) },
InputLayout: D3D12_INPUT_LAYOUT_DESC {
NumElements: els.len() as u32,
pInputElementDescs: els.as_mut_ptr(),
},
VS: D3D12_SHADER_BYTECODE {
BytecodeLength: unsafe { vertex_shader.GetBufferSize() },
pShaderBytecode: unsafe { vertex_shader.GetBufferPointer() },
},
PS: D3D12_SHADER_BYTECODE {
BytecodeLength: unsafe { pixel_shader.GetBufferSize() },
pShaderBytecode: unsafe { pixel_shader.GetBufferPointer() },
},
RasterizerState: cd3dx12_rasterizer_desc_default(),
BlendState: cd3dx12_blend_desc_default(),
SampleMask: 0xffffffff,
PrimitiveTopologyType:
D3D12_PRIMITIVE_TOPOLOGY_TYPE::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 1,
RTVFormats: (0..D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT)
.map(|i| {
if i == 0 {
DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM
} else {
DXGI_FORMAT::DXGI_FORMAT_UNKNOWN
}
})
.collect::<Vec<_>>()
.try_into()
.unwrap(),
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
DSVFormat: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT,
DepthStencilState: cd3dx12_depth_stencil_desc_default(),
..D3D12_GRAPHICS_PIPELINE_STATE_DESC::default()
};
let pipeline_state =
unsafe { device.CreateGraphicsPipelineState::<ID3D12PipelineState>(&pso_desc) }
.expect("Unable to create pipeline state");
let allocator = unsafe {
device
.CreateCommandAllocator::<ID3D12CommandAllocator>(
D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT,
)
.expect("Unable to create allocator")
};
// Create direct command list
let list: ID3D12GraphicsCommandList = unsafe {
device.CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT,
&allocator,
&pipeline_state,
)
}?;
unsafe {
list.Close().ok()?;
}
let viewport = D3D12_VIEWPORT {
Width: 1024.0,
Height: 1024.0,
MaxDepth: D3D12_MAX_DEPTH,
MinDepth: D3D12_MIN_DEPTH,
TopLeftX: 0.0,
TopLeftY: 0.0,
};
let scissor = RECT {
top: 0,
left: 0,
bottom: 1024,
right: 1024,
};
let camera = Camera {
// camera location (eye), camera look at position, camera up direction
eye: XMVectorSet(50.0, 50.0, -50.0, 0.0),
at: XMVectorSet(0.0, 0.0, 0.0, 0.0),
up: XMVectorSet(0.0, 1.0, 0.0, 0.0),
};
// Resource initialization ------------------------------------------
// Create fence
let (fence, fence_value, fence_event) = unsafe {
let fence =
device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAGS::D3D12_FENCE_FLAG_NONE)?;
let fence_event = CreateEventA(null_mut(), false, false, PSTR(null_mut()));
if fence_event.0 == 0 {
panic!("Unable to create fence event");
}
(fence, 1, fence_event)
};
// Create constant buffer resources
let frame_resources: [FrameResource; NUM_OF_FRAMES] = (0..NUM_OF_FRAMES)
.map(|_| FrameResource::new(&device, &pipeline_state))
.collect::<Vec<_>>()
.try_into()
.expect("Unable to create frame resources");
unsafe {
// allocators[current_frame].Reset().ok()?;
list.Reset(&allocator, &pipeline_state).ok()?;
}
let (vertex_buffer, vertex_buffer_view, _vertex_buffer_upload) = unsafe {
// -1.0, +1.0 +1.0, +1.0
// │
// │
// │
// │
// 0,│0
// ──────────┼──────────
// │
// │
// │
// │
// │
// -1.0, -1.0 +1.0, -1.0
let vertices: [Vertex; 24] = [
// front
Vertex::new([-0.5, 0.5, -0.5], RED),
Vertex::new([0.5, -0.5, -0.5], RED),
Vertex::new([-0.5, -0.5, -0.5], RED),
Vertex::new([0.5, 0.5, -0.5], RED),
// Right
Vertex::new([0.5, -0.5, -0.5], GREEN),
Vertex::new([0.5, 0.5, 0.5], GREEN),
Vertex::new([0.5, -0.5, 0.5], GREEN),
Vertex::new([0.5, 0.5, -0.5], GREEN),
// Left
Vertex::new([-0.5, 0.5, 0.5], BLUE),
Vertex::new([-0.5, -0.5, -0.5], BLUE),
Vertex::new([-0.5, -0.5, 0.5], BLUE),
Vertex::new([-0.5, 0.5, -0.5], BLUE),
// Back
Vertex::new([0.5, 0.5, 0.5], MAGENTA),
Vertex::new([-0.5, -0.5, 0.5], MAGENTA),
Vertex::new([0.5, -0.5, 0.5], MAGENTA),
Vertex::new([-0.5, 0.5, 0.5], MAGENTA),
// top
Vertex::new([-0.5, 0.5, -0.5], YELLOW),
Vertex::new([0.5, 0.5, 0.5], YELLOW),
Vertex::new([0.5, 0.5, -0.5], YELLOW),
Vertex::new([-0.5, 0.5, 0.5], YELLOW),
// bottom
Vertex::new([0.5, -0.5, 0.5], BLACK),
Vertex::new([-0.5, -0.5, -0.5], BLACK),
Vertex::new([0.5, -0.5, -0.5], BLACK),
Vertex::new([-0.5, -0.5, 0.5], BLACK),
];
let vertices_as_bytes = std::slice::from_raw_parts(
(&vertices as *const _) as *const u8,
std::mem::size_of_val(&vertices),
);
let vertex_buffers = create_default_buffer(&device, &list, vertices_as_bytes)?;
let vertex_buffer_view = D3D12_VERTEX_BUFFER_VIEW {
BufferLocation: vertex_buffers.gpu_buffer.GetGPUVirtualAddress(),
StrideInBytes: std::mem::size_of::<Vertex>() as _,
SizeInBytes: vertices_as_bytes.len() as _,
};
(
vertex_buffers.gpu_buffer,
vertex_buffer_view,
vertex_buffers.upload_buffer,
)
};
let (indices_buffer, indices_buffer_view, _indicies_upload_buffer) = unsafe {
// Vertex indicies which form the two triangles:
let indices: [u32; 36] = [
// front
0, 1, 2, // first triangle
0, 3, 1, // second triangle
// left
4, 5, 6, // first triangle
4, 7, 5, // second triangle
// right
8, 9, 10, // first triangle
8, 11, 9, // second triangle
// back
12, 13, 14, // first triangle
12, 15, 13, // second triangle
// top
16, 17, 18, // first triangle
16, 19, 17, // second triangle
// bottom
20, 21, 22, // first triangle
20, 23, 21, // second triangle
];
let indicies_as_bytes = std::slice::from_raw_parts(
(&indices as *const _) as *const u8,
std::mem::size_of_val(&indices),
);
let buffers = create_default_buffer(&device, &list, indicies_as_bytes)?;
let view = D3D12_INDEX_BUFFER_VIEW {
BufferLocation: buffers.gpu_buffer.GetGPUVirtualAddress(),
SizeInBytes: indicies_as_bytes.len() as _,
Format: DXGI_FORMAT::DXGI_FORMAT_R32_UINT,
};
(buffers.gpu_buffer, view, buffers.upload_buffer)
};
let (instance_buffer, _instance_upload_buffer) = unsafe {
// Creating 10x10 grid of boxes!
let instance_data: [InstanceData; 100] = (0..100)
.into_iter()
.map(|i| {
let col = (i % 10) as f32;
let row = (i / 10) as f32;
InstanceData {
world: {
// Cube is sized 10x10x10, and placed in the origo
let world = XMMatrixIdentity();
let world = XMMatrixMultiply(world, &XMMatrixScaling(10.0, 10.0, 10.0));
let world = XMMatrixMultiply(
world,
&XMMatrixTranslation(20.0 * col - 90.0, 0.0, 20.0 * row - 90.0),
);
// The DirectX math (XMMATRIX) acts on row-major
// matrices and transposing it changes it to
// column-major format for HLSL
let world = XMMatrixTranspose(world);
let mut out: XMFLOAT4X4 = std::mem::zeroed();
XMStoreFloat4x4(&mut out, world);
out
},
}
})
.collect::<Vec<_>>()
.try_into()
.unwrap();
let as_bytes = std::slice::from_raw_parts(
(&instance_data as *const _) as *const u8,
std::mem::size_of_val(&instance_data),
);
let buffers = create_default_buffer(&device, &list, as_bytes)?;
(buffers.gpu_buffer, buffers.upload_buffer)
};
unsafe {
list.Close().ok()?;
let mut lists = [Some(list.cast::<ID3D12CommandList>()?)];
queue.ExecuteCommandLists(lists.len() as _, lists.as_mut_ptr());
}
unsafe {
queue.Signal(&fence, fence_value).ok()?;
fence.SetEventOnCompletion(fence_value, fence_event).ok()?;
WaitForSingleObjectEx(fence_event, 0xFFFFFFFF, false);
}
let win = Window {
hwnd,
factory,
adapter,
device,
queue,
// allocators,
comp_device,
swap_chain,
current_frame,
comp_target,
comp_visual,
back_buffer_rtv_heap,
back_buffers,
depth_stencil_heap,
depth_stencil_buffer,
root_signature,
// list,
pipeline_state,
vertex_shader,
pixel_shader,
viewport,
scissor,
vertex_buffer,
vertex_buffer_view,
indices_buffer,
indices_buffer_view,
instance_buffer,
// constant_buffer_heaps,
// constant_buffers,
camera,
frame_resources,
fence,
fence_value,
fence_event,
};
// Temporary upload buffers _indicies_upload_buffer, and
// _vertex_buffer_upload can now be destroyed.
// End of resource initialization -------------------------------
Ok(win)
}
fn populate_command_list(&mut self) -> ::windows::Result<()> {
unsafe {
// Get the current backbuffer on which to draw
let frame_resource = &self.frame_resources[self.current_frame];
let (back_buffer, back_buffer_rtv) = &self.back_buffers[self.current_frame];
let allocator = &frame_resource.allocator;
let list = &frame_resource.list;
let dsv = self.depth_stencil_heap.GetCPUDescriptorHandleForHeapStart();
// Reset allocator
allocator.Reset().ok()?;
// Reset list
list.Reset(allocator, &self.pipeline_state).ok()?;
// Set root signature, viewport and scissor rect
list.SetGraphicsRootSignature(&self.root_signature);
list.RSSetViewports(1, &self.viewport);
list.RSSetScissorRects(1, &self.scissor);
// Direct the draw commands to the render target resource
list.ResourceBarrier(
1,
&cd3dx12_resource_barrier_transition(
back_buffer,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PRESENT,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RENDER_TARGET,
None,
None,
),
);
list.ClearDepthStencilView(
&dsv,
D3D12_CLEAR_FLAGS::from(
D3D12_CLEAR_FLAGS::D3D12_CLEAR_FLAG_DEPTH.0
| D3D12_CLEAR_FLAGS::D3D12_CLEAR_FLAG_STENCIL.0,
),
1.0,
0,
0,
null_mut(),
);
list.OMSetRenderTargets(1, back_buffer_rtv, false, &dsv);
list.ClearRenderTargetView(
back_buffer_rtv,
[1.0f32, 0.2, 0.4, 0.5].as_ptr(),
0,
null_mut(),
);
list.IASetPrimitiveTopology(
D3D_PRIMITIVE_TOPOLOGY::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
);
list.IASetIndexBuffer(&self.indices_buffer_view);
list.IASetVertexBuffers(0, 1, &self.vertex_buffer_view);
list.SetGraphicsRootConstantBufferView(
0,
frame_resource.scene_cb.gpu_virtual_address(),
);
list.SetGraphicsRootConstantBufferView(
1,
frame_resource.object_cb.gpu_virtual_address(),
);
list.SetGraphicsRootShaderResourceView(2, self.instance_buffer.GetGPUVirtualAddress());
list.DrawIndexedInstanced(36, 100, 0, 0, 0);
// Set render target to be presentable
list.ResourceBarrier(
1,
&cd3dx12_resource_barrier_transition(
back_buffer,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PRESENT,
None,
None,
),
);
// Close list
list.Close().ok()?;
Ok(())
}
}
fn update(&mut self) -> windows::Result<()> {
let frame = self.frame_resources[self.current_frame].borrow_mut();
frame.update_constant_buffers(&self.camera);
Ok(())
}
fn frame_next(&mut self) -> windows::Result<()> {
self.current_frame = unsafe { self.swap_chain.GetCurrentBackBufferIndex() as _ };
let frame = self.frame_resources[self.current_frame].borrow_mut();
// Before update, ensure previous frame resource is done
unsafe {
let last_completed_fence = self.fence.GetCompletedValue();
if frame.fence_value > last_completed_fence {
self.fence
.SetEventOnCompletion(frame.fence_value, self.fence_event)
.ok()?;
println!("Waiting for a frame... {}", self.current_frame);
WaitForSingleObjectEx(self.fence_event, 0xFFFFFFFF, false);
}
}
Ok(())
}
fn frame_done(&mut self) -> windows::Result<()> {
let frame = self.frame_resources[self.current_frame].borrow_mut();
// Signal and increment the fence value.
frame.fence_value = self.fence_value;
unsafe {
self.queue.Signal(&self.fence, self.fence_value).ok()?;
}
self.fence_value += 1;
Ok(())
}
fn render(&mut self) -> windows::Result<()> {
self.populate_command_list()?;
let frame_resource = &self.frame_resources[self.current_frame];
unsafe {
let mut lists = [Some(frame_resource.list.cast::<ID3D12CommandList>()?)];
self.queue
.ExecuteCommandLists(lists.len() as _, lists.as_mut_ptr());
self.swap_chain.Present(1, 0).ok()?;
}
self.update()?;
Ok(())
}
pub fn frame(&mut self) -> windows::Result<()> {
// TODO: This seems really crappy and error prone
self.frame_next()?;
self.update()?;
self.render()?;
self.frame_done()?;
Ok(())
}
pub fn pan(&mut self, dx: f32, dy: f32) {
self.camera.rotate_yaw(dx * 0.005);
self.camera.rotate_pitch(dy * 0.005);
self.frame().unwrap();
}
}
static mut WINDOW: Option<Window> = None;
const fn get_xy(lparam: LPARAM) -> POINT {
POINT {
x: ((lparam.0 as i32) & (u16::MAX as i32)) as i16 as i32,
y: ((lparam.0 as i32) >> 16) as _,
}
}
const fn delta_xy(last: POINT, next: POINT) -> POINT {
POINT {
x: next.x - last.x,
y: next.y - last.y,
}
}
/// Main message loop for the window
extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
static mut LAST_POS: POINT = POINT { x: 0, y: 0 };
static mut GRAB: bool = false;
unsafe {
match msg {
WM_LBUTTONDOWN => {
SetCapture(hwnd);
LAST_POS = get_xy(lparam);
GRAB = true;
SetCursor(LoadCursorW(HINSTANCE(0), IDC_SIZEALL));
LRESULT(0)
}
WM_LBUTTONUP => {
ReleaseCapture();
SetCursor(LoadCursorW(HINSTANCE(0), IDC_ARROW));
GRAB = false;
LRESULT(0)
}
WM_MOUSEMOVE => {
if GRAB {
// Mouse delta from last point
let delta_pos = delta_xy(LAST_POS, get_xy(lparam));
if let Some(window) = WINDOW.as_mut() {
window.pan(delta_pos.x as _, delta_pos.y as _);
}
LAST_POS = get_xy(lparam);
}
LRESULT(0)
}
WM_PAINT => {
if let Some(window) = WINDOW.as_mut() {
window.frame().unwrap();
}
ValidateRect(hwnd, std::ptr::null());
LRESULT(0)
}
WM_DESTROY => {
WINDOW = None;
PostQuitMessage(0);
LRESULT(0)
}
_ => DefWindowProcA(hwnd, msg, wparam, lparam),
}
}
}
fn main() {
unsafe {
// SetProcessDpiAwareness(PROCESS_DPI_AWARENESS::PROCESS_PER_MONITOR_DPI_AWARE).unwrap();
let instance = GetModuleHandleA(None);
let cursor = LoadCursorW(HINSTANCE(0), IDC_ARROW);
let cls = WNDCLASSA {
style: WNDCLASS_STYLES::CS_HREDRAW | WNDCLASS_STYLES::CS_VREDRAW,
lpfnWndProc: Some(wndproc),
hInstance: instance,
lpszClassName: PSTR(b"Dx12LearningCls\0".as_ptr() as _),
cbClsExtra: 0,
cbWndExtra: 0,
hIcon: HICON(0),
hCursor: cursor,
hbrBackground: HBRUSH(0),
lpszMenuName: PSTR(null_mut()),
};
RegisterClassA(&cls);
let hwnd = CreateWindowExA(
WINDOW_EX_STYLE::WS_EX_NOREDIRECTIONBITMAP as _,
PSTR(b"Dx12LearningCls\0".as_ptr() as _),
PSTR(b"Instancing example\0".as_ptr() as _),
WINDOW_STYLE::WS_OVERLAPPEDWINDOW | WINDOW_STYLE::WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
HWND(0),
HMENU(0),
instance,
0 as _,
);
if hwnd == HWND(0) {
panic!("Failed to create window");
}
// Create the window
WINDOW = Some(Window::new(hwnd).unwrap());
let mut message = MSG::default();
while GetMessageA(&mut message, HWND(0), 0, 0).into() {
TranslateMessage(&mut message);
DispatchMessageA(&mut message);
}
/*
while message.message != WM_QUIT {
if PeekMessageA(&mut message, HWND(0), 0, 0, PEEK_MESSAGE_REMOVE_TYPE::PM_REMOVE).into() {
TranslateMessage(&message);
DispatchMessageA(&message);
} else {
if let Some(win) = WINDOW.as_mut() {
win.render().unwrap();
}
}
}
*/
}
}
|
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)]
pub enum AuxVec {
AT_NULL = 0,
// AT_IGNORE should be ignored.
AT_IGNORE = 1,
// AT_EXECFD is the file descriptor of the program.
AT_EXECFD = 2,
// AT_PHDR points to the program headers.
AT_PHDR = 3,
// AT_PHENT is the size of a program header entry.
AT_PHENT = 4,
// AT_PHNUM is the number of program headers.
AT_PHNUM = 5,
// AT_PAGESZ is the system page size.
AT_PAGESZ = 6,
// AT_BASE is the base address of the interpreter.
AT_BASE = 7,
// AT_FLAGS are flags.
AT_FLAGS = 8,
// AT_ENTRY is the program entry point.
AT_ENTRY = 9,
// AT_NOTELF indicates that the program is not an ELF binary.
AT_NOTELF = 10,
// AT_UID is the real UID.
AT_UID = 11,
// AT_EUID is the effective UID.
AT_EUID = 12,
// AT_GID is the real GID.
AT_GID = 13,
// AT_EGID is the effective GID.
AT_EGID = 14,
// AT_PLATFORM is a string identifying the CPU.
AT_PLATFORM = 15,
// AT_HWCAP are arch-dependent CPU capabilities.
AT_HWCAP = 16,
// AT_CLKTCK is the frequency used by times(2).
AT_CLKTCK = 17,
// AT_SECURE indicate secure mode.
AT_SECURE = 23,
// AT_BASE_PLATFORM is a string identifying the "real" platform. It may
// differ from AT_PLATFORM.
AT_BASE_PLATFORM = 24,
// AT_RANDOM points to 16-bytes of random data.
AT_RANDOM = 25,
// AT_HWCAP2 is an extension of AT_HWCAP.
AT_HWCAP2 = 26,
// AT_EXECFN is the path used to execute the program.
AT_EXECFN = 31,
// AT_SYSINFO_EHDR is the address of the VDSO.
AT_SYSINFO_EHDR = 33,
}
#[derive(Debug, Copy, Clone)]
pub struct AuxEntry {
pub Key: AuxVec,
pub Val: u64,
}
|
use http_body::Body;
/// A [`Predicate`] allows filtering requests before they get processed by a [`crate::Sink`].
pub trait Predicate: Clone {
/// If this method returns true, the logger layer will capture gRPC frames for this request
/// and send them to a [`crate::Sink`].
fn should_log<B>(&self, req: &hyper::Request<B>) -> bool
where
B: Body;
}
#[derive(Default, Clone, Debug)]
pub struct LogAll;
impl Predicate for LogAll {
fn should_log<B>(&self, _req: &hyper::Request<B>) -> bool
where
B: Body,
{
true
}
}
/// A [`Predicate`] that filters out all [gRPC server reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md)
#[derive(Default, Clone, Debug, Copy)]
pub struct NoReflection;
impl Predicate for NoReflection {
fn should_log<B>(&self, req: &hyper::Request<B>) -> bool
where
B: Body,
{
let method = req.uri().path();
!method.starts_with("/grpc.reflection.v1alpha.ServerReflection")
}
}
|
//! Handles the command requested by the CLI.
use super::config;
use crate::{
error::AppError,
project_config::ProjectConfig,
tmux::{self, TmuxProject},
};
use dialoguer::Confirm;
use glob::glob;
use std::{env, fs::copy, process::Command};
use std::{fs::remove_file, io::prelude::*};
use std::{fs::File, path::Path};
use which::which;
/// The default template used when create a new project.
macro_rules! default_template {
() => {
"project_name: {}
# project_root: ~/src/project_path
# on_project_start:
# - sudo systemctl start postgresql
# pre_window:
# - workon dummy
# windows:
# - editor: vim
# - shells:
# layout: main-vertical
# panes:
# - #
# - grunt serve
"
};
}
/// List the projects in the configuration directory.
pub(crate) fn list_projects() -> Result<(), AppError> {
let pattern = config::get_path("*.yml")?;
for project in glob(&pattern.to_string_lossy()).expect("Failed to glob config dir") {
match project {
Ok(path) => println!("{}", &path.file_stem().unwrap().to_string_lossy()),
Err(e) => println!("{e:?}"),
}
}
Ok(())
}
/// Parses the project file and prints the shell commands for session creation.
pub(crate) fn debug_project(project_name: &str) -> Result<(), AppError> {
let entries = config::get_project_yaml(project_name)?;
let project = ProjectConfig::try_from(entries)?;
let tmux = TmuxProject::new(&project)?;
println!("{tmux}");
Ok(())
}
/// Parses the project file, runs the commands to create the tmux session.
pub fn run_project(project_name: &str) -> Result<(), AppError> {
println!("Starting project {project_name}");
let entries = config::get_project_yaml(project_name)?;
let project = ProjectConfig::try_from(entries)?;
let tmux = TmuxProject::new(&project)?;
Ok(tmux.run()?)
}
#[doc(hidden)]
/// Helper mapping a [`bool`] value to `"Yes"` or `"No"`.
fn bool_to_yesno(val: bool) -> &'static str {
if val {
"Yes"
} else {
"No"
}
}
/// Checks environment configuration.
///
/// - `tmux` in `$PATH`.
/// - `$SHELL` is set.
/// - `$EDITOR` are set.
pub(crate) fn check_config() -> Result<(), AppError> {
let have_tmux = which(tmux::TMUX_BIN).is_ok();
let have_editor = env::var("EDITOR").is_ok();
let have_shell = env::var("SHELL").is_ok();
println!(
"tmux is installed? {}\n$EDITOR is set? {}\n$SHELL is set? {}",
bool_to_yesno(have_tmux),
bool_to_yesno(have_editor),
bool_to_yesno(have_shell)
);
Ok(())
}
/// Opens an existing project file with `$EDITOR`.
pub(crate) fn edit_project(project_name: &str) -> Result<(), AppError> {
let project_file_path = config::get_project_path(project_name)?;
if !Path::new(&project_file_path).exists() {
return Err(AppError::ProjectFileNotFound(project_file_path));
}
let editor = env::var("EDITOR");
if editor.is_err() {
return Err(AppError::EditorNotSet(project_file_path));
}
let mut binding = Command::new(editor.unwrap());
let cmd = binding.arg(project_file_path);
cmd.status()
.map_err(|_| AppError::CommandRun(format!("{cmd:?}")))?;
Ok(())
}
/// Creates a new project file, optinally from [`default_template`], and
/// opens it with `$EDITOR`.
pub(crate) fn new_project(project_name: &str, blank: bool) -> Result<(), AppError> {
let project_file_path = config::get_project_path(project_name)?;
if project_file_path.exists() {
return Err(AppError::ProjectFileExists(project_file_path));
}
let content = if blank {
format!("project_name: {project_name}")
} else {
format!(default_template!(), project_name)
};
let mut new_file = File::create(&project_file_path)
.map_err(|e| AppError::ProjectFileCreate(project_file_path.clone(), e))?;
new_file
.write_all(content.as_bytes())
.map_err(|e| AppError::ProjectFileWrite(project_file_path.clone(), e))?;
let editor = env::var("EDITOR");
if editor.is_err() {
return Err(AppError::EditorNotSet(project_file_path));
}
let mut binding = Command::new(editor.unwrap());
let cmd = binding.arg(project_file_path);
cmd.status()
.map_err(|_| AppError::CommandRun(format!("{cmd:?}")))?;
Ok(())
}
/// Deletes a project from the configuration directory. Asks for confirmation.
pub(crate) fn delete_project(project_name: &str) -> Result<(), AppError> {
let project_file_path = config::get_project_path(project_name)?;
if !project_file_path.exists() {
return Err(AppError::ProjectFileNotFound(project_file_path));
}
let message = format!("Are you sure you want to delete \"{project_name}\"?");
let confirmation = Confirm::new()
.with_prompt(message)
.interact()
.map_err(AppError::Prompt)?;
if confirmation {
remove_file(&project_file_path)
.map_err(|e| AppError::ProjectFileDelete(project_file_path, e))?;
println!("Deleted \"{project_name}\"");
} else {
println!("Delete aborted");
}
Ok(())
}
/// Copies an existing project to a new one, and opens it with `$EDITOR`.
pub(crate) fn copy_project(existing: &str, new: &str) -> Result<(), AppError> {
let existing_path = config::get_project_path(existing)?;
if !existing_path.exists() {
return Err(AppError::ProjectFileNotFound(existing_path));
}
let new_path = config::get_project_path(new)?;
if new_path.exists() {
return Err(AppError::ProjectFileExists(new_path));
}
copy(&existing_path, &new_path)
.map_err(|e| AppError::ProjectCopy(existing_path, new_path.clone(), e))?;
let editor = env::var("EDITOR");
if editor.is_err() {
return Err(AppError::EditorNotSet(new_path));
}
let mut binding = Command::new(editor.unwrap());
let cmd = binding.arg(&new_path);
cmd.status()
.map_err(|_| AppError::CommandRun(format!("{cmd:?}")))?;
Ok(())
}
/// Kills the project's session.
pub(crate) fn stop(project_name: &str) -> Result<(), AppError> {
let entries = config::get_project_yaml(project_name)?;
let project = ProjectConfig::try_from(entries)?;
let tmux = TmuxProject::new(&project)?;
Ok(tmux.stop()?)
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qquaternion.h
// dst-file: /src/gui/qquaternion.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::qvector3d::*; // 773
use super::qvector4d::*; // 773
// use super::qgenericmatrix::*; // 775
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QQuaternion_Class_Size() -> c_int;
// proto: void QQuaternion::getAxisAndAngle(float * x, float * y, float * z, float * angle);
fn C_ZNK11QQuaternion15getAxisAndAngleEPfS0_S0_S0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_float, arg1: *mut c_float, arg2: *mut c_float, arg3: *mut c_float);
// proto: float QQuaternion::scalar();
fn C_ZNK11QQuaternion6scalarEv(qthis: u64 /* *mut c_void*/) -> c_float;
// proto: void QQuaternion::setX(float x);
fn C_ZN11QQuaternion4setXEf(qthis: u64 /* *mut c_void*/, arg0: c_float);
// proto: void QQuaternion::setVector(const QVector3D & vector);
fn C_ZN11QQuaternion9setVectorERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QQuaternion::QQuaternion(const QVector4D & vector);
fn C_ZN11QQuaternionC2ERK9QVector4D(arg0: *mut c_void) -> u64;
// proto: static QQuaternion QQuaternion::rotationTo(const QVector3D & from, const QVector3D & to);
fn C_ZN11QQuaternion10rotationToERK9QVector3DS2_(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QQuaternion::getEulerAngles(float * pitch, float * yaw, float * roll);
fn C_ZNK11QQuaternion14getEulerAnglesEPfS0_S0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_float, arg1: *mut c_float, arg2: *mut c_float);
// proto: void QQuaternion::setY(float y);
fn C_ZN11QQuaternion4setYEf(qthis: u64 /* *mut c_void*/, arg0: c_float);
// proto: QVector3D QQuaternion::toEulerAngles();
fn C_ZNK11QQuaternion13toEulerAnglesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QQuaternion QQuaternion::inverted();
fn C_ZNK11QQuaternion8invertedEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuaternion::setZ(float z);
fn C_ZN11QQuaternion4setZEf(qthis: u64 /* *mut c_void*/, arg0: c_float);
// proto: void QQuaternion::getAxes(QVector3D * xAxis, QVector3D * yAxis, QVector3D * zAxis);
fn C_ZNK11QQuaternion7getAxesEP9QVector3DS1_S1_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void);
// proto: static QQuaternion QQuaternion::nlerp(const QQuaternion & q1, const QQuaternion & q2, float t);
fn C_ZN11QQuaternion5nlerpERKS_S1_f(arg0: *mut c_void, arg1: *mut c_void, arg2: c_float) -> *mut c_void;
// proto: bool QQuaternion::isIdentity();
fn C_ZNK11QQuaternion10isIdentityEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: static QQuaternion QQuaternion::fromAxes(const QVector3D & xAxis, const QVector3D & yAxis, const QVector3D & zAxis);
fn C_ZN11QQuaternion8fromAxesERK9QVector3DS2_S2_(arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: static QQuaternion QQuaternion::slerp(const QQuaternion & q1, const QQuaternion & q2, float t);
fn C_ZN11QQuaternion5slerpERKS_S1_f(arg0: *mut c_void, arg1: *mut c_void, arg2: c_float) -> *mut c_void;
// proto: static QQuaternion QQuaternion::fromDirection(const QVector3D & direction, const QVector3D & up);
fn C_ZN11QQuaternion13fromDirectionERK9QVector3DS2_(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QQuaternion::QQuaternion();
fn C_ZN11QQuaternionC2Ev() -> u64;
// proto: QQuaternion QQuaternion::normalized();
fn C_ZNK11QQuaternion10normalizedEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QVector4D QQuaternion::toVector4D();
fn C_ZNK11QQuaternion10toVector4DEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static QQuaternion QQuaternion::fromEulerAngles(float pitch, float yaw, float roll);
fn C_ZN11QQuaternion15fromEulerAnglesEfff(arg0: c_float, arg1: c_float, arg2: c_float) -> *mut c_void;
// proto: QQuaternion QQuaternion::conjugate();
fn C_ZNK11QQuaternion9conjugateEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QQuaternion::isNull();
fn C_ZNK11QQuaternion6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QQuaternion::getAxisAndAngle(QVector3D * axis, float * angle);
fn C_ZNK11QQuaternion15getAxisAndAngleEP9QVector3DPf(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_float);
// proto: QMatrix3x3 QQuaternion::toRotationMatrix();
fn C_ZNK11QQuaternion16toRotationMatrixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static QQuaternion QQuaternion::fromEulerAngles(const QVector3D & eulerAngles);
fn C_ZN11QQuaternion15fromEulerAnglesERK9QVector3D(arg0: *mut c_void) -> *mut c_void;
// proto: QVector3D QQuaternion::rotatedVector(const QVector3D & vector);
fn C_ZNK11QQuaternion13rotatedVectorERK9QVector3D(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: float QQuaternion::lengthSquared();
fn C_ZNK11QQuaternion13lengthSquaredEv(qthis: u64 /* *mut c_void*/) -> c_float;
// proto: void QQuaternion::setScalar(float scalar);
fn C_ZN11QQuaternion9setScalarEf(qthis: u64 /* *mut c_void*/, arg0: c_float);
// proto: float QQuaternion::y();
fn C_ZNK11QQuaternion1yEv(qthis: u64 /* *mut c_void*/) -> c_float;
// proto: QVector3D QQuaternion::vector();
fn C_ZNK11QQuaternion6vectorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static float QQuaternion::dotProduct(const QQuaternion & q1, const QQuaternion & q2);
fn C_ZN11QQuaternion10dotProductERKS_S1_(arg0: *mut c_void, arg1: *mut c_void) -> c_float;
// proto: void QQuaternion::setVector(float x, float y, float z);
fn C_ZN11QQuaternion9setVectorEfff(qthis: u64 /* *mut c_void*/, arg0: c_float, arg1: c_float, arg2: c_float);
// proto: void QQuaternion::QQuaternion(float scalar, float xpos, float ypos, float zpos);
fn C_ZN11QQuaternionC2Effff(arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float) -> u64;
// proto: static QQuaternion QQuaternion::fromAxisAndAngle(const QVector3D & axis, float angle);
fn C_ZN11QQuaternion16fromAxisAndAngleERK9QVector3Df(arg0: *mut c_void, arg1: c_float) -> *mut c_void;
// proto: void QQuaternion::QQuaternion(float scalar, const QVector3D & vector);
fn C_ZN11QQuaternionC2EfRK9QVector3D(arg0: c_float, arg1: *mut c_void) -> u64;
// proto: float QQuaternion::length();
fn C_ZNK11QQuaternion6lengthEv(qthis: u64 /* *mut c_void*/) -> c_float;
// proto: void QQuaternion::normalize();
fn C_ZN11QQuaternion9normalizeEv(qthis: u64 /* *mut c_void*/);
// proto: QQuaternion QQuaternion::conjugated();
fn C_ZNK11QQuaternion10conjugatedEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static QQuaternion QQuaternion::fromAxisAndAngle(float x, float y, float z, float angle);
fn C_ZN11QQuaternion16fromAxisAndAngleEffff(arg0: c_float, arg1: c_float, arg2: c_float, arg3: c_float) -> *mut c_void;
// proto: float QQuaternion::x();
fn C_ZNK11QQuaternion1xEv(qthis: u64 /* *mut c_void*/) -> c_float;
// proto: float QQuaternion::z();
fn C_ZNK11QQuaternion1zEv(qthis: u64 /* *mut c_void*/) -> c_float;
} // <= ext block end
// body block begin =>
// class sizeof(QQuaternion)=16
#[derive(Default)]
pub struct QQuaternion {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QQuaternion {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQuaternion {
return QQuaternion{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QQuaternion::getAxisAndAngle(float * x, float * y, float * z, float * angle);
impl /*struct*/ QQuaternion {
pub fn getAxisAndAngle<RetType, T: QQuaternion_getAxisAndAngle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.getAxisAndAngle(self);
// return 1;
}
}
pub trait QQuaternion_getAxisAndAngle<RetType> {
fn getAxisAndAngle(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::getAxisAndAngle(float * x, float * y, float * z, float * angle);
impl<'a> /*trait*/ QQuaternion_getAxisAndAngle<()> for (&'a mut Vec<f32>, &'a mut Vec<f32>, &'a mut Vec<f32>, &'a mut Vec<f32>) {
fn getAxisAndAngle(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion15getAxisAndAngleEPfS0_S0_S0_()};
let arg0 = self.0.as_ptr() as *mut c_float;
let arg1 = self.1.as_ptr() as *mut c_float;
let arg2 = self.2.as_ptr() as *mut c_float;
let arg3 = self.3.as_ptr() as *mut c_float;
unsafe {C_ZNK11QQuaternion15getAxisAndAngleEPfS0_S0_S0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: float QQuaternion::scalar();
impl /*struct*/ QQuaternion {
pub fn scalar<RetType, T: QQuaternion_scalar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scalar(self);
// return 1;
}
}
pub trait QQuaternion_scalar<RetType> {
fn scalar(self , rsthis: & QQuaternion) -> RetType;
}
// proto: float QQuaternion::scalar();
impl<'a> /*trait*/ QQuaternion_scalar<f32> for () {
fn scalar(self , rsthis: & QQuaternion) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion6scalarEv()};
let mut ret = unsafe {C_ZNK11QQuaternion6scalarEv(rsthis.qclsinst)};
return ret as f32; // 1
// return 1;
}
}
// proto: void QQuaternion::setX(float x);
impl /*struct*/ QQuaternion {
pub fn setX<RetType, T: QQuaternion_setX<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setX(self);
// return 1;
}
}
pub trait QQuaternion_setX<RetType> {
fn setX(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::setX(float x);
impl<'a> /*trait*/ QQuaternion_setX<()> for (f32) {
fn setX(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion4setXEf()};
let arg0 = self as c_float;
unsafe {C_ZN11QQuaternion4setXEf(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuaternion::setVector(const QVector3D & vector);
impl /*struct*/ QQuaternion {
pub fn setVector<RetType, T: QQuaternion_setVector<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setVector(self);
// return 1;
}
}
pub trait QQuaternion_setVector<RetType> {
fn setVector(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::setVector(const QVector3D & vector);
impl<'a> /*trait*/ QQuaternion_setVector<()> for (&'a QVector3D) {
fn setVector(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion9setVectorERK9QVector3D()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QQuaternion9setVectorERK9QVector3D(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuaternion::QQuaternion(const QVector4D & vector);
impl /*struct*/ QQuaternion {
pub fn new<T: QQuaternion_new>(value: T) -> QQuaternion {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QQuaternion_new {
fn new(self) -> QQuaternion;
}
// proto: void QQuaternion::QQuaternion(const QVector4D & vector);
impl<'a> /*trait*/ QQuaternion_new for (&'a QVector4D) {
fn new(self) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternionC2ERK9QVector4D()};
let ctysz: c_int = unsafe{QQuaternion_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN11QQuaternionC2ERK9QVector4D(arg0)};
let rsthis = QQuaternion{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static QQuaternion QQuaternion::rotationTo(const QVector3D & from, const QVector3D & to);
impl /*struct*/ QQuaternion {
pub fn rotationTo_s<RetType, T: QQuaternion_rotationTo_s<RetType>>( overload_args: T) -> RetType {
return overload_args.rotationTo_s();
// return 1;
}
}
pub trait QQuaternion_rotationTo_s<RetType> {
fn rotationTo_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::rotationTo(const QVector3D & from, const QVector3D & to);
impl<'a> /*trait*/ QQuaternion_rotationTo_s<QQuaternion> for (&'a QVector3D, &'a QVector3D) {
fn rotationTo_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion10rotationToERK9QVector3DS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN11QQuaternion10rotationToERK9QVector3DS2_(arg0, arg1)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuaternion::getEulerAngles(float * pitch, float * yaw, float * roll);
impl /*struct*/ QQuaternion {
pub fn getEulerAngles<RetType, T: QQuaternion_getEulerAngles<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.getEulerAngles(self);
// return 1;
}
}
pub trait QQuaternion_getEulerAngles<RetType> {
fn getEulerAngles(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::getEulerAngles(float * pitch, float * yaw, float * roll);
impl<'a> /*trait*/ QQuaternion_getEulerAngles<()> for (&'a mut Vec<f32>, &'a mut Vec<f32>, &'a mut Vec<f32>) {
fn getEulerAngles(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion14getEulerAnglesEPfS0_S0_()};
let arg0 = self.0.as_ptr() as *mut c_float;
let arg1 = self.1.as_ptr() as *mut c_float;
let arg2 = self.2.as_ptr() as *mut c_float;
unsafe {C_ZNK11QQuaternion14getEulerAnglesEPfS0_S0_(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QQuaternion::setY(float y);
impl /*struct*/ QQuaternion {
pub fn setY<RetType, T: QQuaternion_setY<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setY(self);
// return 1;
}
}
pub trait QQuaternion_setY<RetType> {
fn setY(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::setY(float y);
impl<'a> /*trait*/ QQuaternion_setY<()> for (f32) {
fn setY(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion4setYEf()};
let arg0 = self as c_float;
unsafe {C_ZN11QQuaternion4setYEf(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QVector3D QQuaternion::toEulerAngles();
impl /*struct*/ QQuaternion {
pub fn toEulerAngles<RetType, T: QQuaternion_toEulerAngles<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toEulerAngles(self);
// return 1;
}
}
pub trait QQuaternion_toEulerAngles<RetType> {
fn toEulerAngles(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QVector3D QQuaternion::toEulerAngles();
impl<'a> /*trait*/ QQuaternion_toEulerAngles<QVector3D> for () {
fn toEulerAngles(self , rsthis: & QQuaternion) -> QVector3D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion13toEulerAnglesEv()};
let mut ret = unsafe {C_ZNK11QQuaternion13toEulerAnglesEv(rsthis.qclsinst)};
let mut ret1 = QVector3D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QQuaternion QQuaternion::inverted();
impl /*struct*/ QQuaternion {
pub fn inverted<RetType, T: QQuaternion_inverted<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.inverted(self);
// return 1;
}
}
pub trait QQuaternion_inverted<RetType> {
fn inverted(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QQuaternion QQuaternion::inverted();
impl<'a> /*trait*/ QQuaternion_inverted<QQuaternion> for () {
fn inverted(self , rsthis: & QQuaternion) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion8invertedEv()};
let mut ret = unsafe {C_ZNK11QQuaternion8invertedEv(rsthis.qclsinst)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuaternion::setZ(float z);
impl /*struct*/ QQuaternion {
pub fn setZ<RetType, T: QQuaternion_setZ<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setZ(self);
// return 1;
}
}
pub trait QQuaternion_setZ<RetType> {
fn setZ(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::setZ(float z);
impl<'a> /*trait*/ QQuaternion_setZ<()> for (f32) {
fn setZ(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion4setZEf()};
let arg0 = self as c_float;
unsafe {C_ZN11QQuaternion4setZEf(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QQuaternion::getAxes(QVector3D * xAxis, QVector3D * yAxis, QVector3D * zAxis);
impl /*struct*/ QQuaternion {
pub fn getAxes<RetType, T: QQuaternion_getAxes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.getAxes(self);
// return 1;
}
}
pub trait QQuaternion_getAxes<RetType> {
fn getAxes(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::getAxes(QVector3D * xAxis, QVector3D * yAxis, QVector3D * zAxis);
impl<'a> /*trait*/ QQuaternion_getAxes<()> for (&'a QVector3D, &'a QVector3D, &'a QVector3D) {
fn getAxes(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion7getAxesEP9QVector3DS1_S1_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZNK11QQuaternion7getAxesEP9QVector3DS1_S1_(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: static QQuaternion QQuaternion::nlerp(const QQuaternion & q1, const QQuaternion & q2, float t);
impl /*struct*/ QQuaternion {
pub fn nlerp_s<RetType, T: QQuaternion_nlerp_s<RetType>>( overload_args: T) -> RetType {
return overload_args.nlerp_s();
// return 1;
}
}
pub trait QQuaternion_nlerp_s<RetType> {
fn nlerp_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::nlerp(const QQuaternion & q1, const QQuaternion & q2, float t);
impl<'a> /*trait*/ QQuaternion_nlerp_s<QQuaternion> for (&'a QQuaternion, &'a QQuaternion, f32) {
fn nlerp_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion5nlerpERKS_S1_f()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2 as c_float;
let mut ret = unsafe {C_ZN11QQuaternion5nlerpERKS_S1_f(arg0, arg1, arg2)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuaternion::isIdentity();
impl /*struct*/ QQuaternion {
pub fn isIdentity<RetType, T: QQuaternion_isIdentity<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isIdentity(self);
// return 1;
}
}
pub trait QQuaternion_isIdentity<RetType> {
fn isIdentity(self , rsthis: & QQuaternion) -> RetType;
}
// proto: bool QQuaternion::isIdentity();
impl<'a> /*trait*/ QQuaternion_isIdentity<i8> for () {
fn isIdentity(self , rsthis: & QQuaternion) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion10isIdentityEv()};
let mut ret = unsafe {C_ZNK11QQuaternion10isIdentityEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: static QQuaternion QQuaternion::fromAxes(const QVector3D & xAxis, const QVector3D & yAxis, const QVector3D & zAxis);
impl /*struct*/ QQuaternion {
pub fn fromAxes_s<RetType, T: QQuaternion_fromAxes_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fromAxes_s();
// return 1;
}
}
pub trait QQuaternion_fromAxes_s<RetType> {
fn fromAxes_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::fromAxes(const QVector3D & xAxis, const QVector3D & yAxis, const QVector3D & zAxis);
impl<'a> /*trait*/ QQuaternion_fromAxes_s<QQuaternion> for (&'a QVector3D, &'a QVector3D, &'a QVector3D) {
fn fromAxes_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion8fromAxesERK9QVector3DS2_S2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN11QQuaternion8fromAxesERK9QVector3DS2_S2_(arg0, arg1, arg2)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QQuaternion QQuaternion::slerp(const QQuaternion & q1, const QQuaternion & q2, float t);
impl /*struct*/ QQuaternion {
pub fn slerp_s<RetType, T: QQuaternion_slerp_s<RetType>>( overload_args: T) -> RetType {
return overload_args.slerp_s();
// return 1;
}
}
pub trait QQuaternion_slerp_s<RetType> {
fn slerp_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::slerp(const QQuaternion & q1, const QQuaternion & q2, float t);
impl<'a> /*trait*/ QQuaternion_slerp_s<QQuaternion> for (&'a QQuaternion, &'a QQuaternion, f32) {
fn slerp_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion5slerpERKS_S1_f()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2 as c_float;
let mut ret = unsafe {C_ZN11QQuaternion5slerpERKS_S1_f(arg0, arg1, arg2)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QQuaternion QQuaternion::fromDirection(const QVector3D & direction, const QVector3D & up);
impl /*struct*/ QQuaternion {
pub fn fromDirection_s<RetType, T: QQuaternion_fromDirection_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fromDirection_s();
// return 1;
}
}
pub trait QQuaternion_fromDirection_s<RetType> {
fn fromDirection_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::fromDirection(const QVector3D & direction, const QVector3D & up);
impl<'a> /*trait*/ QQuaternion_fromDirection_s<QQuaternion> for (&'a QVector3D, &'a QVector3D) {
fn fromDirection_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion13fromDirectionERK9QVector3DS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN11QQuaternion13fromDirectionERK9QVector3DS2_(arg0, arg1)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuaternion::QQuaternion();
impl<'a> /*trait*/ QQuaternion_new for () {
fn new(self) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternionC2Ev()};
let ctysz: c_int = unsafe{QQuaternion_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN11QQuaternionC2Ev()};
let rsthis = QQuaternion{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QQuaternion QQuaternion::normalized();
impl /*struct*/ QQuaternion {
pub fn normalized<RetType, T: QQuaternion_normalized<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.normalized(self);
// return 1;
}
}
pub trait QQuaternion_normalized<RetType> {
fn normalized(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QQuaternion QQuaternion::normalized();
impl<'a> /*trait*/ QQuaternion_normalized<QQuaternion> for () {
fn normalized(self , rsthis: & QQuaternion) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion10normalizedEv()};
let mut ret = unsafe {C_ZNK11QQuaternion10normalizedEv(rsthis.qclsinst)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QVector4D QQuaternion::toVector4D();
impl /*struct*/ QQuaternion {
pub fn toVector4D<RetType, T: QQuaternion_toVector4D<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toVector4D(self);
// return 1;
}
}
pub trait QQuaternion_toVector4D<RetType> {
fn toVector4D(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QVector4D QQuaternion::toVector4D();
impl<'a> /*trait*/ QQuaternion_toVector4D<QVector4D> for () {
fn toVector4D(self , rsthis: & QQuaternion) -> QVector4D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion10toVector4DEv()};
let mut ret = unsafe {C_ZNK11QQuaternion10toVector4DEv(rsthis.qclsinst)};
let mut ret1 = QVector4D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QQuaternion QQuaternion::fromEulerAngles(float pitch, float yaw, float roll);
impl /*struct*/ QQuaternion {
pub fn fromEulerAngles_s<RetType, T: QQuaternion_fromEulerAngles_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fromEulerAngles_s();
// return 1;
}
}
pub trait QQuaternion_fromEulerAngles_s<RetType> {
fn fromEulerAngles_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::fromEulerAngles(float pitch, float yaw, float roll);
impl<'a> /*trait*/ QQuaternion_fromEulerAngles_s<QQuaternion> for (f32, f32, f32) {
fn fromEulerAngles_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion15fromEulerAnglesEfff()};
let arg0 = self.0 as c_float;
let arg1 = self.1 as c_float;
let arg2 = self.2 as c_float;
let mut ret = unsafe {C_ZN11QQuaternion15fromEulerAnglesEfff(arg0, arg1, arg2)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QQuaternion QQuaternion::conjugate();
impl /*struct*/ QQuaternion {
pub fn conjugate<RetType, T: QQuaternion_conjugate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.conjugate(self);
// return 1;
}
}
pub trait QQuaternion_conjugate<RetType> {
fn conjugate(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QQuaternion QQuaternion::conjugate();
impl<'a> /*trait*/ QQuaternion_conjugate<QQuaternion> for () {
fn conjugate(self , rsthis: & QQuaternion) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion9conjugateEv()};
let mut ret = unsafe {C_ZNK11QQuaternion9conjugateEv(rsthis.qclsinst)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QQuaternion::isNull();
impl /*struct*/ QQuaternion {
pub fn isNull<RetType, T: QQuaternion_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QQuaternion_isNull<RetType> {
fn isNull(self , rsthis: & QQuaternion) -> RetType;
}
// proto: bool QQuaternion::isNull();
impl<'a> /*trait*/ QQuaternion_isNull<i8> for () {
fn isNull(self , rsthis: & QQuaternion) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion6isNullEv()};
let mut ret = unsafe {C_ZNK11QQuaternion6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QQuaternion::getAxisAndAngle(QVector3D * axis, float * angle);
impl<'a> /*trait*/ QQuaternion_getAxisAndAngle<()> for (&'a QVector3D, &'a mut Vec<f32>) {
fn getAxisAndAngle(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion15getAxisAndAngleEP9QVector3DPf()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.as_ptr() as *mut c_float;
unsafe {C_ZNK11QQuaternion15getAxisAndAngleEP9QVector3DPf(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QMatrix3x3 QQuaternion::toRotationMatrix();
impl /*struct*/ QQuaternion {
pub fn toRotationMatrix<RetType, T: QQuaternion_toRotationMatrix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toRotationMatrix(self);
// return 1;
}
}
pub trait QQuaternion_toRotationMatrix<RetType> {
fn toRotationMatrix(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QMatrix3x3 QQuaternion::toRotationMatrix();
impl<'a> /*trait*/ QQuaternion_toRotationMatrix<u64> for () {
fn toRotationMatrix(self , rsthis: & QQuaternion) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion16toRotationMatrixEv()};
let mut ret = unsafe {C_ZNK11QQuaternion16toRotationMatrixEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: static QQuaternion QQuaternion::fromEulerAngles(const QVector3D & eulerAngles);
impl<'a> /*trait*/ QQuaternion_fromEulerAngles_s<QQuaternion> for (&'a QVector3D) {
fn fromEulerAngles_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion15fromEulerAnglesERK9QVector3D()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN11QQuaternion15fromEulerAnglesERK9QVector3D(arg0)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QVector3D QQuaternion::rotatedVector(const QVector3D & vector);
impl /*struct*/ QQuaternion {
pub fn rotatedVector<RetType, T: QQuaternion_rotatedVector<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rotatedVector(self);
// return 1;
}
}
pub trait QQuaternion_rotatedVector<RetType> {
fn rotatedVector(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QVector3D QQuaternion::rotatedVector(const QVector3D & vector);
impl<'a> /*trait*/ QQuaternion_rotatedVector<QVector3D> for (&'a QVector3D) {
fn rotatedVector(self , rsthis: & QQuaternion) -> QVector3D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion13rotatedVectorERK9QVector3D()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK11QQuaternion13rotatedVectorERK9QVector3D(rsthis.qclsinst, arg0)};
let mut ret1 = QVector3D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: float QQuaternion::lengthSquared();
impl /*struct*/ QQuaternion {
pub fn lengthSquared<RetType, T: QQuaternion_lengthSquared<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.lengthSquared(self);
// return 1;
}
}
pub trait QQuaternion_lengthSquared<RetType> {
fn lengthSquared(self , rsthis: & QQuaternion) -> RetType;
}
// proto: float QQuaternion::lengthSquared();
impl<'a> /*trait*/ QQuaternion_lengthSquared<f32> for () {
fn lengthSquared(self , rsthis: & QQuaternion) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion13lengthSquaredEv()};
let mut ret = unsafe {C_ZNK11QQuaternion13lengthSquaredEv(rsthis.qclsinst)};
return ret as f32; // 1
// return 1;
}
}
// proto: void QQuaternion::setScalar(float scalar);
impl /*struct*/ QQuaternion {
pub fn setScalar<RetType, T: QQuaternion_setScalar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setScalar(self);
// return 1;
}
}
pub trait QQuaternion_setScalar<RetType> {
fn setScalar(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::setScalar(float scalar);
impl<'a> /*trait*/ QQuaternion_setScalar<()> for (f32) {
fn setScalar(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion9setScalarEf()};
let arg0 = self as c_float;
unsafe {C_ZN11QQuaternion9setScalarEf(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: float QQuaternion::y();
impl /*struct*/ QQuaternion {
pub fn y<RetType, T: QQuaternion_y<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.y(self);
// return 1;
}
}
pub trait QQuaternion_y<RetType> {
fn y(self , rsthis: & QQuaternion) -> RetType;
}
// proto: float QQuaternion::y();
impl<'a> /*trait*/ QQuaternion_y<f32> for () {
fn y(self , rsthis: & QQuaternion) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion1yEv()};
let mut ret = unsafe {C_ZNK11QQuaternion1yEv(rsthis.qclsinst)};
return ret as f32; // 1
// return 1;
}
}
// proto: QVector3D QQuaternion::vector();
impl /*struct*/ QQuaternion {
pub fn vector<RetType, T: QQuaternion_vector<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.vector(self);
// return 1;
}
}
pub trait QQuaternion_vector<RetType> {
fn vector(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QVector3D QQuaternion::vector();
impl<'a> /*trait*/ QQuaternion_vector<QVector3D> for () {
fn vector(self , rsthis: & QQuaternion) -> QVector3D {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion6vectorEv()};
let mut ret = unsafe {C_ZNK11QQuaternion6vectorEv(rsthis.qclsinst)};
let mut ret1 = QVector3D::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static float QQuaternion::dotProduct(const QQuaternion & q1, const QQuaternion & q2);
impl /*struct*/ QQuaternion {
pub fn dotProduct_s<RetType, T: QQuaternion_dotProduct_s<RetType>>( overload_args: T) -> RetType {
return overload_args.dotProduct_s();
// return 1;
}
}
pub trait QQuaternion_dotProduct_s<RetType> {
fn dotProduct_s(self ) -> RetType;
}
// proto: static float QQuaternion::dotProduct(const QQuaternion & q1, const QQuaternion & q2);
impl<'a> /*trait*/ QQuaternion_dotProduct_s<f32> for (&'a QQuaternion, &'a QQuaternion) {
fn dotProduct_s(self ) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion10dotProductERKS_S1_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN11QQuaternion10dotProductERKS_S1_(arg0, arg1)};
return ret as f32; // 1
// return 1;
}
}
// proto: void QQuaternion::setVector(float x, float y, float z);
impl<'a> /*trait*/ QQuaternion_setVector<()> for (f32, f32, f32) {
fn setVector(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion9setVectorEfff()};
let arg0 = self.0 as c_float;
let arg1 = self.1 as c_float;
let arg2 = self.2 as c_float;
unsafe {C_ZN11QQuaternion9setVectorEfff(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QQuaternion::QQuaternion(float scalar, float xpos, float ypos, float zpos);
impl<'a> /*trait*/ QQuaternion_new for (f32, f32, f32, f32) {
fn new(self) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternionC2Effff()};
let ctysz: c_int = unsafe{QQuaternion_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_float;
let arg1 = self.1 as c_float;
let arg2 = self.2 as c_float;
let arg3 = self.3 as c_float;
let qthis: u64 = unsafe {C_ZN11QQuaternionC2Effff(arg0, arg1, arg2, arg3)};
let rsthis = QQuaternion{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static QQuaternion QQuaternion::fromAxisAndAngle(const QVector3D & axis, float angle);
impl /*struct*/ QQuaternion {
pub fn fromAxisAndAngle_s<RetType, T: QQuaternion_fromAxisAndAngle_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fromAxisAndAngle_s();
// return 1;
}
}
pub trait QQuaternion_fromAxisAndAngle_s<RetType> {
fn fromAxisAndAngle_s(self ) -> RetType;
}
// proto: static QQuaternion QQuaternion::fromAxisAndAngle(const QVector3D & axis, float angle);
impl<'a> /*trait*/ QQuaternion_fromAxisAndAngle_s<QQuaternion> for (&'a QVector3D, f32) {
fn fromAxisAndAngle_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion16fromAxisAndAngleERK9QVector3Df()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_float;
let mut ret = unsafe {C_ZN11QQuaternion16fromAxisAndAngleERK9QVector3Df(arg0, arg1)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuaternion::QQuaternion(float scalar, const QVector3D & vector);
impl<'a> /*trait*/ QQuaternion_new for (f32, &'a QVector3D) {
fn new(self) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternionC2EfRK9QVector3D()};
let ctysz: c_int = unsafe{QQuaternion_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_float;
let arg1 = self.1.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN11QQuaternionC2EfRK9QVector3D(arg0, arg1)};
let rsthis = QQuaternion{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: float QQuaternion::length();
impl /*struct*/ QQuaternion {
pub fn length<RetType, T: QQuaternion_length<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.length(self);
// return 1;
}
}
pub trait QQuaternion_length<RetType> {
fn length(self , rsthis: & QQuaternion) -> RetType;
}
// proto: float QQuaternion::length();
impl<'a> /*trait*/ QQuaternion_length<f32> for () {
fn length(self , rsthis: & QQuaternion) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion6lengthEv()};
let mut ret = unsafe {C_ZNK11QQuaternion6lengthEv(rsthis.qclsinst)};
return ret as f32; // 1
// return 1;
}
}
// proto: void QQuaternion::normalize();
impl /*struct*/ QQuaternion {
pub fn normalize<RetType, T: QQuaternion_normalize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.normalize(self);
// return 1;
}
}
pub trait QQuaternion_normalize<RetType> {
fn normalize(self , rsthis: & QQuaternion) -> RetType;
}
// proto: void QQuaternion::normalize();
impl<'a> /*trait*/ QQuaternion_normalize<()> for () {
fn normalize(self , rsthis: & QQuaternion) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion9normalizeEv()};
unsafe {C_ZN11QQuaternion9normalizeEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QQuaternion QQuaternion::conjugated();
impl /*struct*/ QQuaternion {
pub fn conjugated<RetType, T: QQuaternion_conjugated<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.conjugated(self);
// return 1;
}
}
pub trait QQuaternion_conjugated<RetType> {
fn conjugated(self , rsthis: & QQuaternion) -> RetType;
}
// proto: QQuaternion QQuaternion::conjugated();
impl<'a> /*trait*/ QQuaternion_conjugated<QQuaternion> for () {
fn conjugated(self , rsthis: & QQuaternion) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion10conjugatedEv()};
let mut ret = unsafe {C_ZNK11QQuaternion10conjugatedEv(rsthis.qclsinst)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QQuaternion QQuaternion::fromAxisAndAngle(float x, float y, float z, float angle);
impl<'a> /*trait*/ QQuaternion_fromAxisAndAngle_s<QQuaternion> for (f32, f32, f32, f32) {
fn fromAxisAndAngle_s(self ) -> QQuaternion {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QQuaternion16fromAxisAndAngleEffff()};
let arg0 = self.0 as c_float;
let arg1 = self.1 as c_float;
let arg2 = self.2 as c_float;
let arg3 = self.3 as c_float;
let mut ret = unsafe {C_ZN11QQuaternion16fromAxisAndAngleEffff(arg0, arg1, arg2, arg3)};
let mut ret1 = QQuaternion::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: float QQuaternion::x();
impl /*struct*/ QQuaternion {
pub fn x<RetType, T: QQuaternion_x<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.x(self);
// return 1;
}
}
pub trait QQuaternion_x<RetType> {
fn x(self , rsthis: & QQuaternion) -> RetType;
}
// proto: float QQuaternion::x();
impl<'a> /*trait*/ QQuaternion_x<f32> for () {
fn x(self , rsthis: & QQuaternion) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion1xEv()};
let mut ret = unsafe {C_ZNK11QQuaternion1xEv(rsthis.qclsinst)};
return ret as f32; // 1
// return 1;
}
}
// proto: float QQuaternion::z();
impl /*struct*/ QQuaternion {
pub fn z<RetType, T: QQuaternion_z<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.z(self);
// return 1;
}
}
pub trait QQuaternion_z<RetType> {
fn z(self , rsthis: & QQuaternion) -> RetType;
}
// proto: float QQuaternion::z();
impl<'a> /*trait*/ QQuaternion_z<f32> for () {
fn z(self , rsthis: & QQuaternion) -> f32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QQuaternion1zEv()};
let mut ret = unsafe {C_ZNK11QQuaternion1zEv(rsthis.qclsinst)};
return ret as f32; // 1
// return 1;
}
}
// <= body block end
|
use std::collections::HashSet;
use std::fs;
use std::fs::DirEntry;
use std::io;
use std::iter::Peekable;
use std::os::unix::fs::MetadataExt;
use std::rc::Rc;
use std::vec;
use output::Output;
use misc::*;
use database::*;
use types::*;
pub struct DirectoryScanner <'a> {
root_paths: & 'a [PathRef],
in_iterator: Peekable <vec::IntoIter <FileData>>,
out_builder: FileDatabaseBuilder,
root_paths_unordered: HashSet <PathRef>,
root_paths_scanned: HashSet <PathRef>,
progress: u64,
}
impl <'a> DirectoryScanner <'a> {
pub fn new (
root_paths: & [PathRef],
file_database: FileDatabase,
) -> DirectoryScanner {
let root_paths_set: HashSet <PathRef> =
root_paths.iter ().map (
|root_path|
root_path.clone ()
).collect ();
let previous_database_iterator =
file_database.into_iter ();
let previous_database_iterator =
previous_database_iterator.peekable ();
let new_database_builder: FileDatabaseBuilder =
FileDatabaseBuilder::new ();
DirectoryScanner {
root_paths: root_paths,
in_iterator: previous_database_iterator,
out_builder: new_database_builder,
root_paths_unordered: root_paths_set,
root_paths_scanned: HashSet::new (),
progress: 0,
}
}
pub fn scan_directories (
mut self,
output: & Output,
recursive_path_database: & mut RecursivePathDatabase,
) -> Result <FileDatabase, String> {
for root_path in self.root_paths.iter () {
if self.root_paths_scanned.contains (root_path) {
continue;
}
output.message_format (
format_args! (
"Scanning {}",
root_path.to_string_lossy ()));
let root_recursive_path =
recursive_path_database.for_path (
root_path.as_ref (),
).unwrap ();
let metadata =
try! (
fs::symlink_metadata (
root_path.as_ref (),
).map_err (
|error|
format! (
"Error reading metadata for: {}: {}",
root_path.to_string_lossy (),
error)
)
);
loop {
{
let existing_file_data_option =
self.in_iterator.peek ();
if existing_file_data_option.is_none () {
break;
}
let existing_file_data =
existing_file_data_option.unwrap ();
let existing_file_path =
& existing_file_data.path;
if * existing_file_path >= root_recursive_path {
break;
}
}
self.out_builder.insert (
self.in_iterator.next ().unwrap ());
}
self.scan_directory_internal (
output,
recursive_path_database,
root_path.clone (),
root_path.clone (),
metadata.dev (),
) ?;
}
for existing_file_data_ref
in self.in_iterator {
self.out_builder.insert (
existing_file_data_ref);
}
output.clear_status ();
output.message_format (
format_args! (
"Scanned {} files",
self.progress));
output.message_format (
format_args! (
"Total {} files in database",
self.out_builder.len ()));
Ok (self.out_builder.build ())
}
fn scan_directory_internal (
& mut self,
output: & Output,
recursive_path_database: & mut RecursivePathDatabase,
directory: PathRef,
root_path: PathRef,
device_id: u64,
) -> Result <(), String> {
if (
self.root_paths_unordered.contains (
& directory)
) {
self.root_paths_scanned.insert (
directory.clone ());
}
let directory =
directory.as_ref ();
let entry_results: Vec <io::Result <DirEntry>> =
try! (
io_result (
fs::read_dir (
directory),
).map_err (
|error|
format! (
"Error reading directory: {}: {}",
directory.to_string_lossy (),
error)
)
).collect ();
let mut entries: Vec <DirEntry> =
Vec::new ();
for entry_result in entry_results.into_iter () {
entries.push (
try! (
io_result (
entry_result,
).map_err (
|error|
format! (
"Error reading entry: {}",
error)
)
));
}
entries.sort_by_key (
|entry|
entry.file_name ()
);
let mut entry_iterator =
entries.into_iter ().peekable ();
loop {
{
let entry_next =
entry_iterator.peek ();
if entry_next.is_none () {
break;
}
}
let entry =
entry_iterator.next ().unwrap ();
let entry_recursive_path =
recursive_path_database.for_path (
entry.path (),
).unwrap ();
loop {
let exists = {
let in_next_option =
self.in_iterator.peek ();
if in_next_option.is_none () {
break;
}
let in_next =
in_next_option.unwrap ();
if in_next.path >= entry_recursive_path {
break;
}
in_next.path.to_path ().exists ()
};
if exists {
self.out_builder.insert (
self.in_iterator.next ().unwrap ());
} else {
self.in_iterator.next ();
}
}
let entry_metadata =
try! (
fs::symlink_metadata (
entry.path (),
).map_err (
|error|
format! (
"Error reading metadata for: {}: {}",
entry.path ().to_string_lossy (),
error)
)
);
let entry_file_type =
entry_metadata.file_type ();
let (temp_root_path, temp_device_id) =
if self.root_paths_unordered.contains (
& entry.path ()) {
(
Rc::new (entry.path ()),
entry_metadata.dev (),
)
} else {
(
root_path.clone (),
device_id,
)
};
if (
entry_file_type.is_symlink ()
|| entry_metadata.dev () != temp_device_id
) {
// ignore
} else if entry_file_type.is_dir () {
self.scan_directory_internal (
output,
recursive_path_database,
Rc::new (entry.path ()),
temp_root_path,
temp_device_id,
) ?;
} else if entry_file_type.is_file () {
let exists = {
let in_next_option =
self.in_iterator.peek ();
if in_next_option.is_some () {
let in_next =
in_next_option.unwrap ();
let in_next_path =
in_next.path.clone ();
in_next_path == entry_recursive_path
} else {
false
}
};
if exists {
let mut file_data =
self.in_iterator.next ().unwrap ();
let changed = (
entry_metadata.len () !=
file_data.size
||
entry_metadata.mtime () !=
file_data.mtime
);
if changed {
file_data.size = entry_metadata.len ();
file_data.content_hash = ZERO_HASH;
file_data.content_hash_time = 0;
file_data.extent_hash = ZERO_HASH;
file_data.extent_hash_time = 0;
file_data.defragment_time = 0;
file_data.deduplicate_time = 0;
file_data.mtime = entry_metadata.mtime ();
file_data.ctime = entry_metadata.ctime ();
file_data.mode = entry_metadata.mode ();
file_data.uid = entry_metadata.uid ();
file_data.gid = entry_metadata.gid ();
}
self.out_builder.insert (
file_data);
} else {
self.out_builder.insert (
FileData {
path: entry_recursive_path,
root_path: Some (root_path.clone ()),
size: entry_metadata.len (),
content_hash: ZERO_HASH,
content_hash_time: 0,
extent_hash: ZERO_HASH,
extent_hash_time: 0,
defragment_time: 0,
deduplicate_time: 0,
mtime: entry_metadata.mtime (),
ctime: entry_metadata.ctime (),
mode: entry_metadata.mode (),
uid: entry_metadata.uid (),
gid: entry_metadata.gid (),
});
}
};
if self.progress % 0x1000 == 0 {
output.status_format (
format_args! (
"Scanning filesystem: {}",
entry.path ().to_string_lossy ()));
}
self.progress += 1;
}
Ok (())
}
}
// ex: noet ts=4 filetype=rust
|
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::io::{Cursor, Write};
use byteorder::{NetworkEndian, WriteBytesExt};
use super::error::{Error, Result};
pub use option::TftpOption;
mod option;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[allow(dead_code)]
#[repr(u16)]
pub enum TftpError {
Other = 0,
NotFound = 1,
AccessDenied = 2,
DiskFull = 3,
IllegalOperation = 4,
UnknownTid = 5,
AlreadyExists = 6,
NoSuchUser = 7,
}
impl TryFrom<u16> for TftpError {
type Error = u16;
fn try_from(code: u16) -> ::std::result::Result<Self, Self::Error> {
match code {
0 => Ok(Self::Other),
1 => Ok(Self::NotFound),
2 => Ok(Self::AccessDenied),
3 => Ok(Self::DiskFull),
4 => Ok(Self::IllegalOperation),
5 => Ok(Self::UnknownTid),
6 => Ok(Self::AlreadyExists),
7 => Ok(Self::NoSuchUser),
code => Err(code),
}
}
}
impl Into<u16> for TftpError {
fn into(self) -> u16 {
self as u16
}
}
#[derive(Debug)]
pub enum Packet {
RwRequest {
write: bool,
file: String,
options: HashMap<String, option::TftpOption>,
},
Ack {
block: u16,
},
Error {
tag: TftpError,
message: Option<String>,
},
}
#[allow(dead_code)]
impl Packet {
#[inline]
pub fn ack(block: u16) -> Self {
Self::Ack { block }
}
#[inline]
pub fn error(tag: TftpError, message: Option<String>) -> Self {
Self::Error { tag, message }
}
pub fn encode(&self) -> Vec<u8> {
match self {
// server never sends RRQ/WRQ to client, no need to support encoding it
Self::RwRequest { .. } => panic!("attempting to encode RRQ/WRQ"),
Self::Ack { block } => {
// opcode + block number
let packet_len = 2 + 2;
let mut cursor = Cursor::new(Vec::with_capacity(packet_len));
cursor.write_u16::<NetworkEndian>(4).unwrap();
cursor.write_u16::<NetworkEndian>(*block).unwrap();
let buf = cursor.into_inner();
debug_assert_eq!(buf.len(), packet_len);
buf
}
Self::Error { tag, message } => {
// opcode + error_code + message + null byte
let packet_len = 2 + 2 + message.as_deref().map_or(0, |x| x.len()) + 1;
let mut cursor = Cursor::new(Vec::with_capacity(packet_len));
cursor.write_u16::<NetworkEndian>(5).unwrap();
cursor.write_u16::<NetworkEndian>(Into::into(*tag)).unwrap();
if let Some(message) = message.as_deref() {
cursor.write_all(message.as_bytes()).unwrap();
}
cursor.write_u8(0).unwrap();
let buf = cursor.into_inner();
debug_assert_eq!(buf.len(), packet_len);
buf
}
}
}
pub fn decode(buf: &[u8]) -> Result<Self> {
match buf
.get(0..2)
.map(|x| u16::from_be_bytes(TryInto::<[u8; 2]>::try_into(x).unwrap()))
.ok_or(Error::InvalidPacket)?
{
opcode if opcode == 1 || opcode == 2 => {
let write = opcode == 2;
let t = buf[2..]
.iter()
.enumerate()
.find(|(_, &x)| x == 0)
.map(|(i, _)| i + 2)
.ok_or(Error::InvalidPacket)?;
let file = String::from_utf8_lossy(&buf[2..t]).to_string();
let t2 = buf
.get(t + 1..)
.ok_or(Error::InvalidPacket)?
.iter()
.enumerate()
.find(|(_, &x)| x == 0)
.map(|(i, _)| i + t + 1)
.ok_or(Error::InvalidPacket)?;
let mode = String::from_utf8_lossy(&buf[t + 1..t2]).to_ascii_lowercase();
if mode != "octet" {
return Err(Error::UnsupportedMode(mode));
}
let options = &buf[t2 + 1..];
let options = if !options.is_empty() {
TftpOption::decode_options(options)?
} else {
Default::default()
};
Ok(Self::RwRequest {
write,
file,
options,
})
}
4 => {
let block = u16::from_be_bytes(
TryInto::<[u8; 2]>::try_into(buf.get(2..4).ok_or(Error::InvalidPacket)?)
.unwrap(),
);
Ok(Self::Ack { block })
}
5 => {
let error_code = u16::from_be_bytes(
TryInto::<[u8; 2]>::try_into(buf.get(2..4).ok_or(Error::InvalidPacket)?)
.unwrap(),
);
let t = buf
.get(4..)
.ok_or(Error::InvalidPacket)?
.iter()
.enumerate()
.find(|(_, &x)| x == 0)
.map(|(i, _)| i + 4)
.ok_or(Error::InvalidPacket)?;
let message = if t == 4 {
None
} else {
Some(String::from_utf8_lossy(&buf[4..t]).to_string())
};
let tag = TftpError::try_from(error_code).unwrap_or_else(|_| {
warn!("unknown error code {}", error_code);
TftpError::Other
});
Ok(Self::Error { tag, message })
}
opcode => Err(Error::UnknownPacketType { opcode }),
}
}
pub fn type_str(&self) -> &'static str {
match self {
Self::RwRequest { write, .. } => {
if *write {
"write"
} else {
"read"
}
}
Self::Ack { .. } => "ack",
Self::Error { .. } => "error",
}
}
}
#[cfg(test)]
mod tests {
use super::{option::TftpOption, Error, Packet};
#[test]
fn test_decode_rrq_wrq() {
assert!(
matches!(Packet::decode(b"\x00\x01/boot/loader.exe\x00octet\x00").unwrap(),
Packet::RwRequest { write: false, file, options }
if file.as_str() == "/boot/loader.exe" && options.is_empty()
)
);
assert!(matches!(
Packet::decode(b"\x01\xfe"),
Err(Error::UnknownPacketType { opcode: 510 })
));
assert!(
matches!(Packet::decode(b"\x00\x02vmlinuz\x00octet\x00blksize\x001432\x00tsize\x00").unwrap(),
Packet::RwRequest { write: true, file, options }
if file.as_str() == "vmlinuz" && options.len() == 1
&& matches!(options.get("blksize").unwrap(), TftpOption::U32(1432))
)
);
}
}
|
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use cosmwasm_std::Addr;
use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
use crate::state::{State, STATE};
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let state = State {
host: info.sender.clone(),
};
STATE.save(deps.storage, &state)?;
Ok(Response::new()
.add_attribute("method", "instantiate")
.add_attribute("host", info.sender)
)
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::StartGame { opponent } => try_start_game(deps, opponent),
}
}
pub fn try_start_game(deps: DepsMut, opponent: Addr) -> Result<Response, ContractError> {
let rcpt_addr = deps.api.addr_validate(&opponent.to_string())?;
Ok(Response::new().add_attribute("method", "try_start_game"))
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
use cosmwasm_std::{coins, from_binary};
#[test]
fn proper_initialization() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg { };
let info = mock_info("creator", &coins(1000, "earth"));
// we can just call .unwrap() to assert this was a success
let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_eq!(0, res.messages.len());
}
#[test]
fn start_game() {
let info = mock_info("anyone", &coins(2, "token"));
let msg = ExecuteMsg::StartGame { opponent: info.sender};
}
} |
#[allow(dead_code)]
mod front_of_house {
pub mod hosting {
pub fn add_to_wait_list() {
println!("Added to restaurant");
}
}
pub mod server {
fn server_takes_order() {
println!("Can I get your order?");
}
pub mod serving {
pub fn take_order() {
crate::front_of_house::server::server_takes_order();
println!("Done!")
}
}
}
}
fn serve_order() {
println!("Serving order..");
}
pub mod back_of_house {
pub fn fix_incorrect_order() {
cook_order();
super::serve_order();
}
fn cook_order() {
println!("Cooking incorrect order...");
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_wait_list();
crate::front_of_house::server::serving::take_order();
// crate::front_of_house::back_of_house::fix_incorrect_order();
// Relative path
// front_of_house::hosting::add_to_waitlist();
}
|
//! Vectors contains functions to generate test vectors for driver testing
extern crate embedded_spi;
use self::embedded_spi::{PinState};
use self::embedded_spi::mock::{Spi, Pin, Delay};
pub use self::embedded_spi::mock::{Mock, MockTransaction as Mt};
use std::vec::Vec;
use crate::device::*;
pub fn reset(spi: &Spi, _sdn: &Pin, _delay: &Delay) -> Vec<Mt> {
vec![
Mt::reset(spi, PinState::Low),
Mt::delay_ms(1),
Mt::reset(spi, PinState::High),
Mt::delay_ms(10),
]
}
pub fn status(spi: &Spi, _sdn: &Pin, _delay: &Delay) -> Vec<Mt> {
vec![
Mt::busy(&spi, PinState::Low),
Mt::spi_read(&spi, &[Commands::GetStatus as u8, 0], &[0x00]),
Mt::busy(&spi, PinState::Low),
]
}
pub fn firmware_version(spi: &Spi, _sdn: &Pin, _delay: &Delay, version: u16) -> Vec<Mt> {
vec![
Mt::busy(&spi, PinState::Low),
Mt::spi_read(&spi, &[
Commands::ReadRegister as u8,
(Registers::LrFirmwareVersionMsb as u16 >> 8) as u8,
(Registers::LrFirmwareVersionMsb as u16 >> 0) as u8,
0
], &[ (version >> 8) as u8, (version >> 0) as u8 ]),
Mt::busy(&spi, PinState::Low),
]
}
pub fn set_power_ramp(spi: &Spi, _sdn: &Pin, _delay: &Delay, power_reg: u8, ramp_reg: u8) -> Vec<Mt> {
vec![
Mt::busy(&spi, PinState::Low),
Mt::spi_write(&spi, &[
Commands::SetTxParams as u8,
], &[
power_reg,
ramp_reg,
]),
Mt::busy(&spi, PinState::Low),
]
} |
#[cfg(test)]
pub mod tests {
use std::time::SystemTime;
use actix::Actor;
use actix_http::Request;
use actix_service::Service;
use actix_test;
use actix_web::{
body::{BoxBody, EitherBody},
dev::ServiceResponse,
error::Error,
test,
web::Data,
App,
};
use actix_web_actors::ws;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json;
use auth::{create_jwt, get_identity_service, PrivateClaim};
use db;
use crate::routes::routes;
use crate::websocket::{MessageToClient, Server};
#[derive(Deserialize, Serialize, Debug)]
struct CookieValue {
identity: String,
#[serde(skip_serializing_if = "Option::is_none")]
login_timestamp: Option<SystemTime>,
#[serde(skip_serializing_if = "Option::is_none")]
visit_timestamp: Option<SystemTime>,
}
pub async fn get_service(
) -> impl Service<Request, Response = ServiceResponse<EitherBody<BoxBody>>, Error = Error> {
test::init_service(
App::new()
.wrap(get_identity_service())
.app_data(Data::new(db::new_pool()))
.app_data(Data::new(Server::new(db::new_pool()).start()))
.configure(routes),
)
.await
}
pub fn get_test_server() -> actix_test::TestServer {
actix_test::start(|| {
App::new()
.wrap(get_identity_service())
.app_data(Data::new(db::new_pool()))
.app_data(Data::new(Server::new(db::new_pool()).start()))
.configure(routes)
})
}
/// Helper for HTTP GET integration tests
pub async fn test_get<R>(route: &str, token: Option<String>) -> (u16, R)
where
R: DeserializeOwned,
{
let mut app = get_service().await;
let mut req = test::TestRequest::get().uri(route);
if let Some(token) = token {
req = req.append_header(("Authorization", token));
}
let res = test::call_service(&mut app, req.to_request()).await;
let status = res.status().as_u16();
let body = test::read_body(res).await;
let json_body = serde_json::from_slice(&body).unwrap_or_else(|_| {
panic!(
"read_response_json failed during deserialization. response: {} status: {}",
String::from_utf8(body.to_vec())
.unwrap_or_else(|_| "Could not convert Bytes -> String".to_string()),
status
)
});
(status, json_body)
}
/// Helper for HTTP POST integration tests
pub async fn test_post<T: Serialize, R>(
route: &str,
params: T,
token: Option<String>,
) -> (u16, R)
where
R: DeserializeOwned,
{
let mut app = get_service().await;
let mut req = test::TestRequest::post().set_json(¶ms).uri(route);
if let Some(token) = token {
req = req.append_header(("Authorization", token));
}
let res = test::call_service(&mut app, req.to_request()).await;
let status = res.status().as_u16();
let body = test::read_body(res).await;
let json_body = serde_json::from_slice(&body).unwrap_or_else(|_| {
panic!(
"read_response_json failed during deserialization. response: {} status: {}",
String::from_utf8(body.to_vec())
.unwrap_or_else(|_| "Could not convert Bytes -> String".to_string()),
status
)
});
(status, json_body)
}
pub fn get_auth_token(private_claim: PrivateClaim) -> String {
create_jwt(private_claim).unwrap()
}
pub fn get_websocket_frame_data(frame: ws::Frame) -> Option<MessageToClient> {
match frame {
ws::Frame::Text(t) => {
let bytes = t.as_ref();
let data = String::from_utf8(bytes.to_vec()).unwrap();
let value: MessageToClient = serde_json::from_str(&data).unwrap();
return Some(value);
}
_ => {}
}
None
}
}
|
#![cfg_attr(not(feature = "std"), no_std)]
pub use self::whitelist::Whitelist;
use ink_lang as ink;
#[ink::contract]
mod whitelist {
#[cfg(not(feature = "ink-as-dependency"))]
use ink_storage::collections::HashMap as StorageHashMap;
#[ink(storage)]
pub struct Whitelist {
collateral_assets: StorageHashMap<AccountId, u32>,
synthetic_assets: StorageHashMap<AccountId, u8>,
leverage_ratio: (u8, u8),
owner: AccountId,
}
impl Whitelist {
#[ink(constructor)]
pub fn new() -> Self {
Self {
collateral_assets: StorageHashMap::new(),
synthetic_assets: StorageHashMap::new(),
leverage_ratio: (1, 10),
owner: Self::env().caller(),
}
}
#[ink(message)]
pub fn get_collateral_asset(&self, asset: AccountId) -> u32 {
assert_ne!(asset, Default::default());
self.collateral_assets.get(&asset).copied().unwrap_or(0)
}
#[ink(message)]
pub fn set_collateral_asset(&mut self, asset: AccountId, ratio: u32) {
self.is_owner();
assert_ne!(asset, Default::default());
self.collateral_assets.insert(asset, ratio);
}
#[ink(message)]
pub fn remove_collateral_asset(&mut self, asset: AccountId) {
self.is_owner();
assert_ne!(asset, Default::default());
self.collateral_assets.take(&asset);
}
#[ink(message)]
pub fn is_effective_collateral_asset(&self, asset: AccountId) -> bool {
assert_ne!(asset, Default::default());
if self.collateral_assets.contains_key(&asset) {
return true;
}
false
}
#[ink(message)]
pub fn get_synthetic_asset(&self, asset: AccountId) -> u8 {
assert_ne!(asset, Default::default());
self.synthetic_assets.get(&asset).copied().unwrap_or(0)
}
#[ink(message)]
pub fn set_synthetic_asset(&mut self, asset: AccountId, status: u8) {
self.is_owner();
assert_ne!(asset, Default::default());
self.synthetic_assets.insert(asset, status);
}
#[ink(message)]
pub fn remove_synthetic_asset(&mut self, asset: AccountId) {
self.is_owner();
assert_ne!(asset, Default::default());
self.synthetic_assets.take(&asset);
}
#[ink(message)]
pub fn is_effective_synthetic_asset(&self, asset: AccountId) -> bool {
assert_ne!(asset, Default::default());
if self.synthetic_assets.contains_key(&asset) {
return true;
}
false
}
#[ink(message)]
pub fn get_leverage_ratio(&self) -> (u8, u8) {
self.leverage_ratio
}
#[ink(message)]
pub fn set_leverage_ratio(&mut self, min: u8, max: u8) {
self.is_owner();
self.leverage_ratio = (min, max);
}
#[ink(message)]
pub fn transfer_ownership(&mut self, new_owner: AccountId) {
self.is_owner();
assert_ne!(new_owner, Default::default());
self.owner = new_owner;
}
fn is_owner(&self) {
assert_eq!(self.owner, self.env().caller());
}
}
} |
extern crate bytes;
extern crate byteorder;
extern crate iovec;
use bytes::Buf;
use iovec::IoVec;
use std::io::Cursor;
#[test]
fn test_fresh_cursor_vec() {
let mut buf = Cursor::new(b"hello".to_vec());
assert_eq!(buf.remaining(), 5);
assert_eq!(buf.bytes(), b"hello");
buf.advance(2);
assert_eq!(buf.remaining(), 3);
assert_eq!(buf.bytes(), b"llo");
buf.advance(3);
assert_eq!(buf.remaining(), 0);
assert_eq!(buf.bytes(), b"");
}
#[test]
fn test_get_u8() {
let mut buf = Cursor::new(b"\x21zomg");
assert_eq!(0x21, buf.get_u8());
}
#[test]
fn test_get_u16() {
let buf = b"\x21\x54zomg";
assert_eq!(0x2154, Cursor::new(buf).get_u16_be());
assert_eq!(0x5421, Cursor::new(buf).get_u16_le());
}
#[test]
#[should_panic]
fn test_get_u16_buffer_underflow() {
let mut buf = Cursor::new(b"\x21");
buf.get_u16_be();
}
#[test]
fn test_bufs_vec() {
let buf = Cursor::new(b"hello world");
let b1: &[u8] = &mut [0];
let b2: &[u8] = &mut [0];
let mut dst: [&IoVec; 2] =
[b1.into(), b2.into()];
assert_eq!(1, buf.bytes_vec(&mut dst[..]));
}
|
use std::collections::{HashMap, HashSet};
fn neigborhood(
(x, y, z, w): (isize, isize, isize, isize),
p2: bool,
) -> impl Iterator<Item = (isize, isize, isize, isize)> {
(w - 1..=w + 1)
.filter(move |w| p2 || *w == 0)
.flat_map(move |w1| {
(x - 1..=x + 1).flat_map(move |x1| {
(y - 1..=y + 1).flat_map(move |y1| (z - 1..=z + 1).map(move |z1| (x1, y1, z1, w1)))
})
})
.filter(move |co| co != &(x, y, z, w))
}
fn main() {
let input = std::fs::read_to_string("input").unwrap();
dbg!(run(&input));
}
fn run(input: &str) -> (usize, usize) {
let input: HashSet<(isize, isize, isize, isize)> = input
.lines()
.enumerate()
.flat_map(move |(y, l)| {
l.chars().enumerate().filter_map(move |(x, c)| {
if c == '#' {
Some((x as isize, y as isize, 0, 0))
} else {
None
}
})
})
.collect();
let mut res = [false, true].iter().map(|part2| {
let mut state = input.clone();
for _ in 0..6 {
let mut counters = HashMap::<_, usize>::new();
for coords in state.iter().flat_map(|co| neigborhood(*co, *part2)) {
*counters.entry(coords).or_default() += 1;
}
state = counters
.into_iter()
.filter(|(k, v)| (state.contains(&k) && *v == 2) || *v == 3)
.map(|e| e.0)
.collect();
}
state.len()
});
(res.next().unwrap(), res.next().unwrap())
}
#[test]
fn t0() {
assert_eq!(run(".#.\n..#\n###"), (112, 848));
}
|
// 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 an edge case in region inference: the lifetime of the borrow
// of `*x` must be extended to at least 'a.
// pretty-expanded FIXME #23616
fn foo<'a,'b>(x: &'a &'b mut isize) -> &'a isize {
let y = &*x; // should be inferred to have type &'a &'b mut isize...
// ...because if we inferred, say, &'x &'b mut isize where 'x <= 'a,
// this reborrow would be illegal:
&**y
}
pub fn main() {
/* Just want to know that it compiles. */
}
|
/*!
[`RedisListener`]接口的具体实现
[`RedisListener`]: trait.RedisListener.html
*/
use std::cell::RefCell;
use std::io::{BufRead, BufReader, Error, ErrorKind, Read, Result, Write};
use std::net::TcpStream;
use std::ops::DerefMut;
use std::rc::Rc;
use std::result::Result::Ok;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::Arc;
use std::thread::sleep;
use std::time::{Duration, Instant};
use log::{error, info, warn};
use native_tls::{Identity, TlsConnector, TlsStream};
use crate::config::Config;
use crate::io::send;
use crate::rdb::DefaultRDBParser;
use crate::resp::{Resp, RespDecode, Type};
use crate::{cmd, io, EventHandler, ModuleParser, NoOpEventHandler, RDBParser, RedisListener};
use scheduled_thread_pool::{JobHandle, ScheduledThreadPool};
use std::fs::File;
/// 用于监听单个Redis实例的事件
pub struct Listener {
pub config: Config,
conn: Option<Stream>,
rdb_parser: Rc<RefCell<dyn RDBParser>>,
event_handler: Rc<RefCell<dyn EventHandler>>,
heartbeat_thread: HeartbeatWorker,
running: Arc<AtomicBool>,
local_ip: Option<String>,
local_port: Option<u16>,
thread_pool: Arc<ScheduledThreadPool>,
repl_offset: Arc<AtomicI64>,
}
impl Listener {
/// 连接Redis,创建TCP连接
fn connect(&mut self) -> Result<()> {
let addr = format!("{}:{}", &self.config.host, self.config.port);
let stream = TcpStream::connect(&addr)?;
stream
.set_read_timeout(self.config.read_timeout)
.expect("read timeout set failed");
stream
.set_write_timeout(self.config.write_timeout)
.expect("write timeout set failed");
let socket_addr = stream.local_addr().unwrap();
let local_ip = socket_addr.ip().to_string();
self.local_ip = Some(local_ip);
let local_port = socket_addr.port();
self.local_port = Some(local_port);
if self.config.is_tls_enabled {
let mut builder = TlsConnector::builder();
builder.danger_accept_invalid_hostnames(self.config.is_tls_insecure);
builder.danger_accept_invalid_certs(self.config.is_tls_insecure);
if let Some(id) = &self.config.identity {
let mut file = File::open(id)?;
let mut buff = Vec::new();
file.read_to_end(&mut buff)?;
let identity_passwd = match &self.config.identity_passwd {
None => "",
Some(passwd) => passwd.as_str(),
};
let identity = Identity::from_pkcs12(&buff, identity_passwd).expect("解析key失败");
builder.identity(identity);
}
let connector = builder.build().unwrap();
let tls_stream = connector
.connect(&self.config.host, stream)
.expect("TLS connect failed");
self.conn = Option::Some(Stream::Tls(tls_stream));
} else {
self.conn = Option::Some(Stream::Tcp(stream));
}
info!("Connected to server {}", &addr);
Ok(())
}
/// 如果有设置密码,将尝试使用此密码进行认证
fn auth(&mut self) -> Result<()> {
if !self.config.password.is_empty() {
let mut args = Vec::with_capacity(2);
if !self.config.username.is_empty() {
args.push(self.config.username.as_bytes());
}
args.push(self.config.password.as_bytes());
let conn = self.conn.as_mut().unwrap();
let conn: &mut dyn Read = match conn {
Stream::Tcp(tcp_stream) => {
send(tcp_stream, b"AUTH", &args)?;
tcp_stream
}
Stream::Tls(tls_stream) => {
send(tls_stream, b"AUTH", &args)?;
tls_stream
}
};
conn.decode_resp()?;
}
Ok(())
}
/// 发送replica相关信息到redis,此端口展现在`info replication`中
fn send_replica_info(&mut self) -> Result<()> {
let port = self.local_port.unwrap().to_string();
let port = port.as_bytes();
let ip = self.local_ip.as_ref().unwrap();
let ip = ip.as_bytes();
let conn = self.conn.as_mut().unwrap();
match conn {
Stream::Tcp(tcp_stream) => Listener::de_send_replica_info(&port, &ip, tcp_stream)?,
Stream::Tls(tls_stream) => Listener::de_send_replica_info(&port, &ip, tls_stream)?,
};
Ok(())
}
fn de_send_replica_info<T: Write + Read>(port: &&[u8], ip: &&[u8], tcp_stream: &mut T) -> Result<()> {
info!("PING");
send(tcp_stream, b"PING", &vec![])?;
Listener::reply(tcp_stream)?;
info!("REPLCONF listening-port {}", String::from_utf8_lossy(*port));
send(tcp_stream, b"REPLCONF", &[b"listening-port", port])?;
Listener::reply(tcp_stream)?;
info!("REPLCONF ip-address {}", String::from_utf8_lossy(*ip));
send(tcp_stream, b"REPLCONF", &[b"ip-address", ip])?;
Listener::reply(tcp_stream)?;
info!("REPLCONF capa eof");
send(tcp_stream, b"REPLCONF", &[b"capa", b"eof"])?;
Listener::reply(tcp_stream)?;
info!("REPLCONF capa psync2");
send(tcp_stream, b"REPLCONF", &[b"capa", b"psync2"])?;
Listener::reply(tcp_stream)
}
fn reply<T: Read>(tcp_stream: &mut T) -> Result<()> {
match tcp_stream.decode_resp()? {
Resp::String(str) => info!("{}", str),
Resp::Error(err) => {
warn!("{}", &err);
if (err.contains("NOAUTH") || err.contains("NOPERM"))
&& !err.contains("no password")
&& !err.contains("Unrecognized REPLCONF option")
{
return Err(Error::new(ErrorKind::InvalidData, err));
}
}
_ => panic!("Unexpected response type"),
}
Ok(())
}
/// 开启replication
/// 默认使用PSYNC命令,若不支持PSYNC则尝试使用SYNC命令
fn start_sync(&mut self) -> Result<Mode> {
let (next_step, mut length) = self.psync()?;
match next_step {
NextStep::FullSync | NextStep::ChangeMode => {
let mode;
if let NextStep::ChangeMode = next_step {
info!("源Redis不支持PSYNC命令, 使用SYNC命令再次进行尝试");
mode = Mode::Sync;
length = self.sync()?;
} else {
mode = Mode::PSync;
}
if length != -1 {
info!("Full Sync, size: {}bytes", length);
} else {
info!("Disk-less replication.");
}
let conn = self.conn.as_mut().unwrap();
let conn: &mut dyn Read = match conn {
Stream::Tcp(tcp_stream) => tcp_stream,
Stream::Tls(tls_stream) => tls_stream,
};
let mut reader = BufReader::new(conn);
reader.fill_buf()?;
if length != -1 && self.config.is_discard_rdb {
info!("跳过RDB不进行处理");
io::skip(&mut reader, length as isize)?;
} else {
let mut event_handler = self.event_handler.borrow_mut();
let mut rdb_parser = self.rdb_parser.borrow_mut();
rdb_parser.parse(&mut reader, length, event_handler.deref_mut())?;
if length == -1 {
io::skip(&mut reader, 40)?;
}
}
Ok(mode)
}
NextStep::PartialResync => {
info!("PSYNC进度恢复");
Ok(Mode::PSync)
}
NextStep::Wait => Ok(Mode::Wait),
}
}
fn psync(&mut self) -> Result<(NextStep, i64)> {
let offset = self.config.repl_offset.to_string();
let repl_offset = offset.as_bytes();
let repl_id = self.config.repl_id.as_bytes();
let conn = self.conn.as_mut().unwrap();
let conn: &mut dyn Read = match conn {
Stream::Tcp(tcp_stream) => {
send(tcp_stream, b"PSYNC", &[repl_id, repl_offset])?;
tcp_stream
}
Stream::Tls(tls_stream) => {
send(tls_stream, b"PSYNC", &[repl_id, repl_offset])?;
tls_stream
}
};
match conn.decode_resp() {
Ok(response) => {
if let Resp::String(resp) = &response {
info!("{}", resp);
if resp.starts_with("FULLRESYNC") {
let mut iter = resp.split_whitespace();
if let Some(repl_id) = iter.nth(1) {
self.config.repl_id = repl_id.to_owned();
} else {
panic!("Expect replication id, but got None");
}
if let Some(repl_offset) = iter.next() {
self.config.repl_offset = repl_offset.parse::<i64>().unwrap();
} else {
panic!("Expect replication offset, but got None");
}
info!("等待Redis dump完成...");
if let Type::BulkString = conn.decode_type()? {
let reply = conn.decode_string()?;
if reply.starts_with("EOF") {
return Ok((NextStep::FullSync, -1));
} else {
let length = reply.parse::<i64>().unwrap();
return Ok((NextStep::FullSync, length));
}
} else {
panic!("Expect BulkString response");
}
} else if resp.starts_with("CONTINUE") {
let mut iter = resp.split_whitespace();
if let Some(repl_id) = iter.nth(1) {
if !repl_id.eq(&self.config.repl_id) {
self.config.repl_id = repl_id.to_owned();
}
}
return Ok((NextStep::PartialResync, -1));
} else if resp.starts_with("NOMASTERLINK") {
return Ok((NextStep::Wait, -1));
} else if resp.starts_with("LOADING") {
return Ok((NextStep::Wait, -1));
}
}
panic!("Unexpected Response: {:?}", response);
}
Err(error) => {
if error.to_string().eq("ERR unknown command 'PSYNC'") {
return Ok((NextStep::ChangeMode, -1));
} else {
return Err(error);
}
}
}
}
fn sync(&mut self) -> Result<i64> {
let conn = self.conn.as_mut().unwrap();
let conn: &mut dyn Read = match conn {
Stream::Tcp(tcp_stream) => {
send(tcp_stream, b"SYNC", &vec![])?;
tcp_stream
}
Stream::Tls(tls_stream) => {
send(tls_stream, b"SYNC", &vec![])?;
tls_stream
}
};
if let Type::BulkString = conn.decode_type()? {
if let Resp::Int(length) = conn.decode_int()? {
return Ok(length);
} else {
panic!("Expect int response")
}
} else {
panic!("Expect BulkString response");
}
}
/// 开启心跳
fn start_heartbeat(&mut self, mode: &Mode) {
if !self.is_running() {
return;
}
if let Mode::Sync = mode {
return;
}
if self.config.is_tls_enabled {
return;
}
let conn = self.conn.as_ref().unwrap();
let conn = match conn {
Stream::Tcp(tcp_stream) => tcp_stream,
Stream::Tls(_) => panic!("Expect TcpStream"),
};
let mut conn_clone = conn.try_clone().unwrap();
info!("Start heartbeat");
let repl_offset = Arc::clone(&self.repl_offset);
let handle =
self.thread_pool
.execute_with_fixed_delay(Duration::from_secs(0), Duration::from_secs(1), move || {
let offset_str = repl_offset.load(Ordering::Relaxed).to_string();
let offset_bytes = offset_str.as_bytes();
if let Err(error) = send(&mut conn_clone, b"REPLCONF", &[b"ACK", offset_bytes]) {
error!("heartbeat error: {}", error);
}
});
self.heartbeat_thread = HeartbeatWorker { handle: Some(handle) };
}
fn receive_aof(&mut self, mode: &Mode) -> Result<()> {
let mut handler = self.event_handler.as_ref().borrow_mut();
let __conn = self.conn.as_mut().unwrap();
match __conn {
Stream::Tcp(tcp_stream) => {
let mut reader = io::CountReader::new(tcp_stream);
while self.running.load(Ordering::Relaxed) {
reader.mark();
if let Resp::Array(array) = reader.decode_resp()? {
let size = reader.reset()?;
let mut vec = Vec::with_capacity(array.len());
for x in array {
if let Resp::BulkBytes(bytes) = x {
vec.push(bytes);
} else {
panic!("Expected BulkString response");
}
}
cmd::parse(vec, handler.deref_mut());
if let Mode::PSync = mode {
self.config.repl_offset += size;
self.repl_offset.store(self.config.repl_offset, Ordering::SeqCst);
}
} else {
panic!("Expected array response");
}
}
}
Stream::Tls(tls_stream) => {
let mut timer = Instant::now();
let one_sec = Duration::from_secs(1);
while self.running.load(Ordering::Relaxed) {
{
let mut reader = io::CountReader::new(tls_stream);
reader.mark();
if let Resp::Array(array) = reader.decode_resp()? {
let size = reader.reset()?;
let mut vec = Vec::with_capacity(array.len());
for x in array {
if let Resp::BulkBytes(bytes) = x {
vec.push(bytes);
} else {
panic!("Expected BulkString response");
}
}
cmd::parse(vec, handler.deref_mut());
self.config.repl_offset += size;
} else {
panic!("Expected array response");
}
}
let elapsed = timer.elapsed();
if elapsed.ge(&one_sec) {
let offset_str = self.config.repl_offset.to_string();
let offset_bytes = offset_str.as_bytes();
if let Err(error) = send(tls_stream, b"REPLCONF", &[b"ACK", offset_bytes]) {
error!("heartbeat error: {}", error);
break;
}
timer = Instant::now();
}
}
}
};
Ok(())
}
/// 获取当前运行的状态,若为false,程序将有序退出
fn is_running(&self) -> bool {
self.running.load(Ordering::Relaxed)
}
}
impl RedisListener for Listener {
/// 程序运行的整体逻辑都在这个方法里面实现
///
/// 具体的细节体现在各个方法内
fn start(&mut self) -> Result<()> {
self.connect()?;
self.auth()?;
self.send_replica_info()?;
let mut mode;
loop {
mode = self.start_sync()?;
match mode {
Mode::Wait => {
if self.is_running() {
sleep(Duration::from_secs(5));
} else {
return Ok(());
}
}
_ => break,
}
}
if !self.config.is_aof {
Ok(())
} else {
self.start_heartbeat(&mode);
self.receive_aof(&mode)?;
Ok(())
}
}
}
impl Drop for Listener {
fn drop(&mut self) {
if let Some(handle) = &self.heartbeat_thread.handle {
info!("Cancel heartbeat");
handle.cancel();
}
}
}
struct HeartbeatWorker {
handle: Option<JobHandle>,
}
enum NextStep {
FullSync,
PartialResync,
ChangeMode,
Wait,
}
enum Mode {
PSync,
Sync,
Wait,
}
pub struct Builder {
pub config: Option<Config>,
pub rdb_parser: Option<Rc<RefCell<dyn RDBParser>>>,
pub event_handler: Option<Rc<RefCell<dyn EventHandler>>>,
pub module_parser: Option<Rc<RefCell<dyn ModuleParser>>>,
pub control_flag: Option<Arc<AtomicBool>>,
pub thread_pool: Option<Arc<ScheduledThreadPool>>,
}
impl Builder {
pub fn new() -> Builder {
Builder {
config: None,
rdb_parser: None,
event_handler: None,
module_parser: None,
control_flag: None,
thread_pool: None,
}
}
pub fn with_config(&mut self, config: Config) {
self.config = Some(config);
}
pub fn with_rdb_parser(&mut self, parser: Rc<RefCell<dyn RDBParser>>) {
self.rdb_parser = Some(parser);
}
pub fn with_event_handler(&mut self, handler: Rc<RefCell<dyn EventHandler>>) {
self.event_handler = Some(handler);
}
pub fn with_module_parser(&mut self, parser: Rc<RefCell<dyn ModuleParser>>) {
self.module_parser = Some(parser);
}
pub fn with_control_flag(&mut self, flag: Arc<AtomicBool>) {
self.control_flag = Some(flag);
}
pub fn with_thread_pool(&mut self, thread_pool: Arc<ScheduledThreadPool>) {
self.thread_pool = Option::Some(thread_pool);
}
pub fn build(&mut self) -> Listener {
let config = match &self.config {
Some(c) => c,
None => panic!("Parameter Config is required"),
};
let module_parser = match &self.module_parser {
None => None,
Some(parser) => Some(parser.clone()),
};
let running = match &self.control_flag {
None => panic!("Parameter Control_flag is required"),
Some(flag) => flag.clone(),
};
let rdb_parser = match &self.rdb_parser {
None => Rc::new(RefCell::new(DefaultRDBParser {
running: Arc::clone(&running),
module_parser,
})),
Some(parser) => parser.clone(),
};
let event_handler = match &self.event_handler {
None => Rc::new(RefCell::new(NoOpEventHandler {})),
Some(handler) => handler.clone(),
};
let thread_pool = match &self.thread_pool {
None => Arc::new(ScheduledThreadPool::with_name("hearbeat-thread-{}", 1)),
Some(pool) => Arc::clone(pool),
};
Listener {
config: config.clone(),
conn: None,
rdb_parser,
event_handler,
heartbeat_thread: HeartbeatWorker { handle: None },
running,
local_ip: None,
local_port: None,
thread_pool,
repl_offset: Arc::new(AtomicI64::from(config.repl_offset)),
}
}
}
enum Stream {
Tcp(TcpStream),
Tls(TlsStream<TcpStream>),
}
|
use std::cell::Ref;
use std::sync::Arc;
use nalgebra::Vector2;
use smallvec::SmallVec;
use sourcerenderer_core::graphics::{
AddressMode,
AttachmentBlendInfo,
AttachmentInfo,
Backend as GraphicsBackend,
Backend,
BarrierAccess,
BarrierSync,
BindingFrequency,
BlendInfo,
BufferUsage,
CommandBuffer,
CompareFunc,
CullMode,
DepthStencilAttachmentRef,
DepthStencilInfo,
Device,
FillMode,
Filter,
Format,
FrontFace,
IndexFormat,
InputAssemblerElement,
InputRate,
LoadOp,
LogicOp,
OutputAttachmentRef,
PipelineBinding,
PrimitiveType,
RasterizerInfo,
RenderPassAttachment,
RenderPassAttachmentView,
RenderPassBeginInfo,
RenderPassInfo,
RenderpassRecordingMode,
SampleCount,
SamplerInfo,
Scissor,
ShaderInputElement,
StencilInfo,
StoreOp,
SubpassInfo,
Swapchain,
Texture,
TextureDimension,
TextureInfo,
TextureLayout,
TextureUsage,
TextureView,
TextureViewInfo,
VertexLayoutInfo,
Viewport,
WHOLE_BUFFER,
};
use sourcerenderer_core::{
Matrix4,
Platform,
Vec2,
Vec2I,
Vec2UI,
};
use super::draw_prep::DrawPrepPass;
use super::gpu_scene::DRAW_CAPACITY;
use crate::renderer::drawable::View;
use crate::renderer::light::DirectionalLight;
use crate::renderer::passes::light_binning;
use crate::renderer::passes::rt_shadows::RTShadowPass;
use crate::renderer::passes::ssao::SsaoPass;
use crate::renderer::passes::taa::scaled_halton_point;
use crate::renderer::renderer_assets::*;
use crate::renderer::renderer_resources::{
HistoryResourceEntry,
RendererResources,
};
use crate::renderer::renderer_scene::RendererScene;
use crate::renderer::shader_manager::{
GraphicsPipelineHandle,
GraphicsPipelineInfo,
ShaderManager,
};
use crate::renderer::PointLight;
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct FrameData {
swapchain_transform: Matrix4,
jitter: Vec2,
z_near: f32,
z_far: f32,
rt_size: Vector2<u32>,
cluster_z_bias: f32,
cluster_z_scale: f32,
cluster_count: nalgebra::Vector3<u32>,
point_light_count: u32,
directional_light_count: u32,
}
pub struct GeometryPass<P: Platform> {
sampler: Arc<<P::GraphicsBackend as GraphicsBackend>::Sampler>,
pipeline: GraphicsPipelineHandle,
}
impl<P: Platform> GeometryPass<P> {
pub const GEOMETRY_PASS_TEXTURE_NAME: &'static str = "geometry";
pub fn new(
device: &Arc<<P::GraphicsBackend as Backend>::Device>,
swapchain: &Arc<<P::GraphicsBackend as Backend>::Swapchain>,
barriers: &mut RendererResources<P::GraphicsBackend>,
shader_manager: &mut ShaderManager<P>,
) -> Self {
let texture_info = TextureInfo {
dimension: TextureDimension::Dim2D,
format: Format::RGBA8UNorm,
width: swapchain.width(),
height: swapchain.height(),
depth: 1,
mip_levels: 1,
array_length: 1,
samples: SampleCount::Samples1,
usage: TextureUsage::SAMPLED
| TextureUsage::RENDER_TARGET
| TextureUsage::COPY_SRC
| TextureUsage::STORAGE,
supports_srgb: false,
};
barriers.create_texture(Self::GEOMETRY_PASS_TEXTURE_NAME, &texture_info, false);
let sampler = device.create_sampler(&SamplerInfo {
mag_filter: Filter::Linear,
min_filter: Filter::Linear,
mip_filter: Filter::Linear,
address_mode_u: AddressMode::Repeat,
address_mode_v: AddressMode::Repeat,
address_mode_w: AddressMode::Repeat,
mip_bias: 0.0,
max_anisotropy: 0.0,
compare_op: None,
min_lod: 0.0,
max_lod: None,
});
let pipeline_info: GraphicsPipelineInfo = GraphicsPipelineInfo {
vs: "shaders/geometry_bindless.vert.spv",
fs: Some("shaders/geometry_bindless.frag.spv"),
primitive_type: PrimitiveType::Triangles,
vertex_layout: VertexLayoutInfo {
input_assembler: &[InputAssemblerElement {
binding: 0,
stride: 64,
input_rate: InputRate::PerVertex,
}],
shader_inputs: &[
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 0,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 0,
format: Format::RGB32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 1,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 16,
format: Format::RGB32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 2,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 32,
format: Format::RG32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 3,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 40,
format: Format::RG32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 4,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 48,
format: Format::R32Float,
},
],
},
rasterizer: RasterizerInfo {
fill_mode: FillMode::Fill,
cull_mode: CullMode::Back,
front_face: FrontFace::Clockwise,
sample_count: SampleCount::Samples1,
},
depth_stencil: DepthStencilInfo {
depth_test_enabled: true,
depth_write_enabled: true,
depth_func: CompareFunc::LessEqual,
stencil_enable: false,
stencil_read_mask: 0u8,
stencil_write_mask: 0u8,
stencil_front: StencilInfo::default(),
stencil_back: StencilInfo::default(),
},
blend: BlendInfo {
alpha_to_coverage_enabled: false,
logic_op_enabled: false,
logic_op: LogicOp::And,
constants: [0f32, 0f32, 0f32, 0f32],
attachments: &[AttachmentBlendInfo::default()],
},
};
let pipeline = shader_manager.request_graphics_pipeline(
&pipeline_info,
&RenderPassInfo {
attachments: &[
AttachmentInfo {
format: texture_info.format,
samples: texture_info.samples,
},
AttachmentInfo {
format: Format::D24,
samples: SampleCount::Samples1,
},
],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[OutputAttachmentRef {
index: 0,
resolve_attachment_index: None,
}],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 1,
read_only: true,
}),
}],
},
0,
);
Self { sampler, pipeline }
}
#[profiling::function]
pub(super) fn execute(
&mut self,
cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
barriers: &RendererResources<P::GraphicsBackend>,
device: &Arc<<P::GraphicsBackend as Backend>::Device>,
depth_name: &str,
scene: &RendererScene<P::GraphicsBackend>,
view: &View,
gpu_scene: &Arc<<P::GraphicsBackend as Backend>::Buffer>,
zero_texture_view: &Arc<<P::GraphicsBackend as Backend>::TextureView>,
_zero_texture_view_black: &Arc<<P::GraphicsBackend as Backend>::TextureView>,
lightmap: &Arc<RendererTexture<P::GraphicsBackend>>,
swapchain_transform: Matrix4,
frame: u64,
camera_buffer: &Arc<<P::GraphicsBackend as Backend>::Buffer>,
vertex_buffer: &Arc<<P::GraphicsBackend as Backend>::Buffer>,
index_buffer: &Arc<<P::GraphicsBackend as Backend>::Buffer>,
shader_manager: &ShaderManager<P>,
) {
cmd_buffer.begin_label("Geometry pass");
let draw_buffer = barriers.access_buffer(
cmd_buffer,
DrawPrepPass::INDIRECT_DRAW_BUFFER,
BarrierSync::INDIRECT,
BarrierAccess::INDIRECT_READ,
HistoryResourceEntry::Current,
);
let rtv_ref = barriers.access_view(
cmd_buffer,
Self::GEOMETRY_PASS_TEXTURE_NAME,
BarrierSync::RENDER_TARGET,
BarrierAccess::RENDER_TARGET_READ | BarrierAccess::RENDER_TARGET_WRITE,
TextureLayout::RenderTarget,
true,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let rtv = &*rtv_ref;
let prepass_depth_ref = barriers.access_view(
cmd_buffer,
depth_name,
BarrierSync::EARLY_DEPTH | BarrierSync::LATE_DEPTH,
BarrierAccess::DEPTH_STENCIL_READ,
TextureLayout::DepthStencilRead,
false,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let prepass_depth = &*prepass_depth_ref;
let ssao_ref = barriers.access_view(
cmd_buffer,
SsaoPass::<P>::SSAO_TEXTURE_NAME,
BarrierSync::FRAGMENT_SHADER | BarrierSync::COMPUTE_SHADER,
BarrierAccess::SAMPLING_READ,
TextureLayout::Sampled,
false,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
let ssao = &*ssao_ref;
let light_bitmask_buffer_ref = barriers.access_buffer(
cmd_buffer,
light_binning::LightBinningPass::LIGHT_BINNING_BUFFER_NAME,
BarrierSync::FRAGMENT_SHADER,
BarrierAccess::STORAGE_READ,
HistoryResourceEntry::Current,
);
let light_bitmask_buffer = &*light_bitmask_buffer_ref;
let rt_shadows: Ref<Arc<<P::GraphicsBackend as Backend>::TextureView>>;
let shadows = if device.supports_ray_tracing() {
rt_shadows = barriers.access_view(
cmd_buffer,
RTShadowPass::SHADOWS_TEXTURE_NAME,
BarrierSync::FRAGMENT_SHADER,
BarrierAccess::SAMPLING_READ,
TextureLayout::Sampled,
false,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
&*rt_shadows
} else {
zero_texture_view
};
cmd_buffer.begin_render_pass(
&RenderPassBeginInfo {
attachments: &[
RenderPassAttachment {
view: RenderPassAttachmentView::RenderTarget(&rtv),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
},
RenderPassAttachment {
view: RenderPassAttachmentView::DepthStencil(&prepass_depth),
load_op: LoadOp::Load,
store_op: StoreOp::Store,
},
],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[OutputAttachmentRef {
index: 0,
resolve_attachment_index: None,
}],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 1,
read_only: true,
}),
}],
},
RenderpassRecordingMode::Commands,
);
let rtv_info = rtv.texture().info();
let cluster_count = nalgebra::Vector3::<u32>::new(16, 9, 24);
let near = view.near_plane;
let far = view.far_plane;
let cluster_z_scale = (cluster_count.z as f32) / (far / near).log2();
let cluster_z_bias = -(cluster_count.z as f32) * (near).log2() / (far / near).log2();
let per_frame = FrameData {
swapchain_transform,
jitter: scaled_halton_point(rtv_info.width, rtv_info.height, (frame % 8) as u32 + 1),
z_near: near,
z_far: far,
rt_size: Vector2::<u32>::new(rtv_info.width, rtv_info.height),
cluster_z_bias,
cluster_z_scale,
cluster_count,
point_light_count: scene.point_lights().len() as u32,
directional_light_count: scene.directional_lights().len() as u32,
};
let mut point_lights = SmallVec::<[PointLight; 16]>::new();
for point_light in scene.point_lights() {
point_lights.push(PointLight {
position: point_light.position,
intensity: point_light.intensity,
});
}
let mut directional_lights = SmallVec::<[DirectionalLight; 16]>::new();
for directional_light in scene.directional_lights() {
directional_lights.push(DirectionalLight {
direction: directional_light.direction,
intensity: directional_light.intensity,
});
}
let per_frame_buffer = cmd_buffer.upload_dynamic_data(&[per_frame], BufferUsage::CONSTANT);
let point_light_buffer =
cmd_buffer.upload_dynamic_data(&point_lights[..], BufferUsage::STORAGE);
let directional_light_buffer =
cmd_buffer.upload_dynamic_data(&directional_lights[..], BufferUsage::STORAGE);
cmd_buffer.bind_uniform_buffer(
BindingFrequency::Frequent,
3,
&per_frame_buffer,
0,
WHOLE_BUFFER,
);
let pipeline = shader_manager.get_graphics_pipeline(self.pipeline);
cmd_buffer.set_pipeline(PipelineBinding::Graphics(&pipeline));
cmd_buffer.set_viewports(&[Viewport {
position: Vec2::new(0.0f32, 0.0f32),
extent: Vec2::new(rtv_info.width as f32, rtv_info.height as f32),
min_depth: 0.0f32,
max_depth: 1.0f32,
}]);
cmd_buffer.set_scissors(&[Scissor {
position: Vec2I::new(0, 0),
extent: Vec2UI::new(9999, 9999),
}]);
//command_buffer.bind_storage_buffer(BindingFrequency::Frequent, 7, clusters);
cmd_buffer.bind_uniform_buffer(
BindingFrequency::Frequent,
0,
camera_buffer,
0,
WHOLE_BUFFER,
);
cmd_buffer.bind_storage_buffer(
BindingFrequency::Frequent,
1,
&point_light_buffer,
0,
WHOLE_BUFFER,
);
cmd_buffer.bind_storage_buffer(
BindingFrequency::Frequent,
2,
&light_bitmask_buffer,
0,
WHOLE_BUFFER,
);
cmd_buffer.bind_sampling_view_and_sampler(
BindingFrequency::Frequent,
4,
&ssao,
&self.sampler,
);
cmd_buffer.bind_storage_buffer(
BindingFrequency::Frequent,
5,
&directional_light_buffer,
0,
WHOLE_BUFFER,
);
cmd_buffer.bind_sampling_view_and_sampler(
BindingFrequency::Frequent,
6,
&lightmap.view,
&self.sampler,
);
cmd_buffer.bind_sampler(BindingFrequency::Frequent, 7, &self.sampler);
cmd_buffer.bind_sampling_view_and_sampler(
BindingFrequency::Frequent,
8,
&shadows,
&self.sampler,
);
cmd_buffer.bind_storage_buffer(BindingFrequency::Frequent, 9, gpu_scene, 0, WHOLE_BUFFER);
cmd_buffer.set_vertex_buffer(vertex_buffer, 0);
cmd_buffer.set_index_buffer(index_buffer, 0, IndexFormat::U32);
cmd_buffer.finish_binding();
cmd_buffer.draw_indexed_indirect(&draw_buffer, 4, &draw_buffer, 0, DRAW_CAPACITY, 20);
cmd_buffer.end_render_pass();
cmd_buffer.end_label();
}
}
|
/// An error can occur when building dynamic schema
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
#[error("{0}")]
pub struct SchemaError(pub String);
impl<T: Into<String>> From<T> for SchemaError {
fn from(err: T) -> Self {
SchemaError(err.into())
}
}
|
use std::collections::HashMap;
struct Translation {
search: String,
replace: String,
}
impl Translation {
fn make_map(&mut self) -> HashMap<char, char> {
let count = self.search.chars().count();
let results = self.replace.chars().count();
let mut keys = self.search.chars();
for key in keys {
println!("{:?}", key);
}
let mut values = self.replace.chars();
for val in values {
println!("{:?}", val);
}
}
}
fn main() {
}
|
use super::*;
use proptest::collection::SizeRange;
use crate::test::strategy::NON_EMPTY_RANGE_INCLUSIVE;
#[test]
fn with_empty_list_returns_empty_list() {
with_process_arc(|arc_process| {
assert_eq!(result(&arc_process, Term::NIL), Ok(Term::NIL));
});
}
#[test]
fn reverses_order_of_elements_of_list() {
let size_range: SizeRange = NON_EMPTY_RANGE_INCLUSIVE.clone().into();
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(
&proptest::collection::vec(strategy::term(arc_process.clone()), size_range),
|vec| {
let list = arc_process.list_from_slice(&vec);
let reversed_vec: Vec<Term> = vec.iter().rev().copied().collect();
let reversed = arc_process.list_from_slice(&reversed_vec);
prop_assert_eq!(result(&arc_process, list), Ok(reversed));
Ok(())
},
)
.unwrap();
});
}
#[test]
fn reverse_reverse_returns_original_list() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::term::list::proper(arc_process.clone()), |list| {
let reversed = result(&arc_process, list).unwrap();
prop_assert_eq!(result(&arc_process, reversed), Ok(list));
Ok(())
})
.unwrap();
});
}
|
use serenity::collector::CollectComponentInteraction;
use serenity::model::interactions::InteractionResponseType;
use serenity::model::prelude::message_component::ButtonStyle;
use serenity::model::prelude::{InteractionApplicationCommandCallbackDataFlags, ReactionType};
use serenity::{
client::Context,
framework::standard::{macros::command, CommandResult},
model::prelude::Message,
};
use std::time::Duration;
#[command("buttons")]
#[description = "AKA clicky bois"]
pub async fn cmd_buttons(ctx: &Context, msg: &Message) -> CommandResult {
let mut m = msg
.channel_id
.send_message(ctx, |m| {
m.content("here's some clicky bois").components(|c| {
c.create_action_row(|r| {
r.create_button(|b| {
b.custom_id("clickyboi1")
.label("click me first!")
.disabled(false)
.style(ButtonStyle::Success)
.emoji(ReactionType::Unicode("🧠".to_string()))
})
.create_button(|b| {
b.custom_id("clickyboi2")
.label("and then click me")
.disabled(true)
.style(ButtonStyle::Danger)
.emoji(ReactionType::Unicode("🛌".to_string()))
})
})
})
})
.await?;
// these massive match statements could probably be moved into macros but that'd be too complex
// for a boilerplate like this
// maybe later, or maybe this annoys you enough to make a PR 🙃
match CollectComponentInteraction::new(ctx)
.author_id(msg.author.id)
.channel_id(msg.channel_id)
.message_id(m.id)
.collect_limit(1)
.filter(|x| x.data.custom_id.as_str() == "clickyboi1")
.timeout(Duration::from_secs(60))
.await
{
Some(inter) => {
inter
.create_interaction_response(ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| {
d.content("thanks for clicking the second clickyboi")
.flags(InteractionApplicationCommandCallbackDataFlags::EPHEMERAL)
})
})
.await?;
m.edit(ctx, |m| {
m.components(|c| {
c.create_action_row(|r| {
r.create_button(|b| {
b.custom_id("clickyboi1")
.label("don't click me now")
.disabled(true)
.style(ButtonStyle::Danger)
.emoji(ReactionType::Unicode("🧠".to_string()))
})
.create_button(|b| {
b.custom_id("clickyboi2")
.label("click me now")
.disabled(false)
.style(ButtonStyle::Success)
.emoji(ReactionType::Unicode("🛌".to_string()))
})
})
})
})
.await?;
}
None => {
m.edit(ctx, |m| {
m.content("the clicky bois didn't get a click in time 😭")
.components(|c| {
c.create_action_row(|r| {
r.create_button(|b| {
b.custom_id("clickyboi1")
.label("no clicky")
.disabled(true)
.style(ButtonStyle::Danger)
.emoji(ReactionType::Unicode("🧠".to_string()))
})
.create_button(|b| {
b.custom_id("clickyboi2")
.label("also no clicky")
.disabled(true)
.style(ButtonStyle::Danger)
.emoji(ReactionType::Unicode("🛌".to_string()))
})
})
})
})
.await?;
return Ok(());
}
};
match CollectComponentInteraction::new(ctx)
.author_id(msg.author.id)
.channel_id(msg.channel_id)
.message_id(m.id)
.collect_limit(1)
.filter(|x| x.data.custom_id.as_str() == "clickyboi2")
.timeout(Duration::from_secs(60))
.await
{
Some(inter) => {
inter
.create_interaction_response(ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| {
d.content("thanks for clicking the first clickyboi")
.flags(InteractionApplicationCommandCallbackDataFlags::EPHEMERAL)
})
})
.await?;
}
None => {
m.edit(ctx, |m| {
m.content("the clicky bois didn't get a click in time 😭")
.components(|c| {
c.create_action_row(|r| {
r.create_button(|b| {
b.custom_id("clickyboi1")
.label("no clicky")
.disabled(true)
.style(ButtonStyle::Danger)
.emoji(ReactionType::Unicode("🧠".to_string()))
})
.create_button(|b| {
b.custom_id("clickyboi2")
.label("also no clicky")
.disabled(true)
.style(ButtonStyle::Danger)
.emoji(ReactionType::Unicode("🛌".to_string()))
})
})
})
})
.await?;
return Ok(());
}
}
Ok(())
}
|
use crate::crawlers::get_html;
use crate::proxy_addr::ProxyAddr;
use regex::Regex;
pub async fn crawl() -> Result<Vec<ProxyAddr>, anyhow::Error> {
let url = "http://www.ip3366.net/free/?stype=1&page=";
let page = 5usize;
let mut ret = vec![];
for i in 1..=page {
let url = format!("{}{}", url, i);
let html = get_html(&url).await?;
match parse(&html) {
Ok(addrs) => ret.extend(addrs),
Err(_) => continue,
}
}
Ok(ret)
}
fn parse(html: &String) -> Result<Vec<ProxyAddr>, anyhow::Error> {
let mut addrs = vec![];
let pattern = Regex::new(r"<tr>\s*<td>(.*?)</td>\s*<td>(.*?)</td>").unwrap();
for cap in pattern.captures_iter(html) {
addrs.push(ProxyAddr::new(cap[1].to_string(), cap[2].parse().unwrap()));
}
Ok(addrs)
}
|
use krnl::port;
pub unsafe fn halt() {
asm!("hlt" :::: "volatile");
}
pub unsafe fn cli() {
asm!("cli" :::: "volatile");
}
pub unsafe fn sti() {
asm!("sti" :::: "volatile");
}
pub unsafe fn die() {
cli();
halt();
}
pub unsafe fn reboot() {
port::outb(port::Port::new(0x64), 0xfe);
}
pub fn idle() {
unsafe {
loop {
halt();
}
}
}
|
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0x0300"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0300
}
}
#[doc = "Reader of field `RTCPRE1`"]
pub type RTCPRE1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RTCPRE1`"]
pub struct RTCPRE1_W<'a> {
w: &'a mut W,
}
impl<'a> RTCPRE1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `RTCPRE0`"]
pub type RTCPRE0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RTCPRE0`"]
pub struct RTCPRE0_W<'a> {
w: &'a mut W,
}
impl<'a> RTCPRE0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `CSSON`"]
pub type CSSON_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CSSON`"]
pub struct CSSON_W<'a> {
w: &'a mut W,
}
impl<'a> CSSON_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `PLLRDY`"]
pub type PLLRDY_R = crate::R<bool, bool>;
#[doc = "Reader of field `PLLON`"]
pub type PLLON_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PLLON`"]
pub struct PLLON_W<'a> {
w: &'a mut W,
}
impl<'a> PLLON_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `HSEBYP`"]
pub type HSEBYP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HSEBYP`"]
pub struct HSEBYP_W<'a> {
w: &'a mut W,
}
impl<'a> HSEBYP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `HSERDY`"]
pub type HSERDY_R = crate::R<bool, bool>;
#[doc = "Reader of field `HSEON`"]
pub type HSEON_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HSEON`"]
pub struct HSEON_W<'a> {
w: &'a mut W,
}
impl<'a> HSEON_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `MSIRDY`"]
pub type MSIRDY_R = crate::R<bool, bool>;
#[doc = "Reader of field `MSION`"]
pub type MSION_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MSION`"]
pub struct MSION_W<'a> {
w: &'a mut W,
}
impl<'a> MSION_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `HSIRDY`"]
pub type HSIRDY_R = crate::R<bool, bool>;
#[doc = "Reader of field `HSION`"]
pub type HSION_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HSION`"]
pub struct HSION_W<'a> {
w: &'a mut W,
}
impl<'a> HSION_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 30 - TC/LCD prescaler"]
#[inline(always)]
pub fn rtcpre1(&self) -> RTCPRE1_R {
RTCPRE1_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 29 - RTCPRE0"]
#[inline(always)]
pub fn rtcpre0(&self) -> RTCPRE0_R {
RTCPRE0_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 28 - Clock security system enable"]
#[inline(always)]
pub fn csson(&self) -> CSSON_R {
CSSON_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 25 - PLL clock ready flag"]
#[inline(always)]
pub fn pllrdy(&self) -> PLLRDY_R {
PLLRDY_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 24 - PLL enable"]
#[inline(always)]
pub fn pllon(&self) -> PLLON_R {
PLLON_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 18 - HSE clock bypass"]
#[inline(always)]
pub fn hsebyp(&self) -> HSEBYP_R {
HSEBYP_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 17 - HSE clock ready flag"]
#[inline(always)]
pub fn hserdy(&self) -> HSERDY_R {
HSERDY_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16 - HSE clock enable"]
#[inline(always)]
pub fn hseon(&self) -> HSEON_R {
HSEON_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 9 - MSI clock ready flag"]
#[inline(always)]
pub fn msirdy(&self) -> MSIRDY_R {
MSIRDY_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - MSI clock enable"]
#[inline(always)]
pub fn msion(&self) -> MSION_R {
MSION_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 1 - Internal high-speed clock ready flag"]
#[inline(always)]
pub fn hsirdy(&self) -> HSIRDY_R {
HSIRDY_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - Internal high-speed clock enable"]
#[inline(always)]
pub fn hsion(&self) -> HSION_R {
HSION_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 30 - TC/LCD prescaler"]
#[inline(always)]
pub fn rtcpre1(&mut self) -> RTCPRE1_W {
RTCPRE1_W { w: self }
}
#[doc = "Bit 29 - RTCPRE0"]
#[inline(always)]
pub fn rtcpre0(&mut self) -> RTCPRE0_W {
RTCPRE0_W { w: self }
}
#[doc = "Bit 28 - Clock security system enable"]
#[inline(always)]
pub fn csson(&mut self) -> CSSON_W {
CSSON_W { w: self }
}
#[doc = "Bit 24 - PLL enable"]
#[inline(always)]
pub fn pllon(&mut self) -> PLLON_W {
PLLON_W { w: self }
}
#[doc = "Bit 18 - HSE clock bypass"]
#[inline(always)]
pub fn hsebyp(&mut self) -> HSEBYP_W {
HSEBYP_W { w: self }
}
#[doc = "Bit 16 - HSE clock enable"]
#[inline(always)]
pub fn hseon(&mut self) -> HSEON_W {
HSEON_W { w: self }
}
#[doc = "Bit 8 - MSI clock enable"]
#[inline(always)]
pub fn msion(&mut self) -> MSION_W {
MSION_W { w: self }
}
#[doc = "Bit 0 - Internal high-speed clock enable"]
#[inline(always)]
pub fn hsion(&mut self) -> HSION_W {
HSION_W { w: self }
}
}
|
//! Methods for retrieving swagger-related information from an HTTP request.
use hyper::Request;
/// A macro for joining together two or more RequestParsers to create a struct that implements
/// RequestParser with a function parse_operation_id that matches hyper requests against the different
/// RequestParsers in turn until it gets a match (or returns an error if none match)
///
/// The order in which the request parsers are passed to the macro specifies the order in which the request
/// is tested against them. If there is any possibility of two RequestParsers matching the same request
/// this should not be used.
#[macro_export]
macro_rules! request_parser_joiner {
($name:ident ,$($T:ty), *) => {
struct $name;
impl <B> RequestParser<B> for $name
where $($T: RequestParser<B>, )*
{
fn parse_operation_id(request: &hyper::Request<B>) -> Result<&'static str, ()> {
__impl_request_parser_joiner!(request, $($T), *)
}
}
};
}
/// This macro should only be used by the request_parser_joiner macro
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_request_parser_joiner {
($argname:expr, $head:ty) => {<$head as RequestParser<B>>::parse_operation_id(&$argname)};
($argname:expr, $head:ty, $( $tail:ty), *) => {
match <$head as RequestParser<B>>::parse_operation_id(&$argname) {
Ok(s) => Ok(s),
Err(_) => __impl_request_parser_joiner!($argname, $( $tail), *),
}
};
}
/// A trait for retrieving swagger-related information from a request.
///
/// This allows other middlewares to retrieve API-related information from a request that
/// may not have been handled by the autogenerated API code yet. For example, a statistics
/// tracking service may wish to use this to count requests per-operation.
///
/// The trait is automatically implemented by swagger-codegen.
pub trait RequestParser<B> {
/// Retrieve the Swagger operation identifier that matches this request.
///
/// Returns `Err(())` if this request does not match any known operation on this API.
fn parse_operation_id(req: &Request<B>) -> Result<&'static str, ()>;
}
#[cfg(test)]
mod context_tests {
use super::*;
use hyper::{Body, Uri};
use std::str::FromStr;
struct TestParser1;
impl RequestParser<Body> for TestParser1 {
fn parse_operation_id(request: &hyper::Request<Body>) -> Result<&'static str, ()> {
match request.uri().path() {
"/test/t11" => Ok("t11"),
"/test/t12" => Ok("t12"),
_ => Err(()),
}
}
}
struct TestParser2;
impl RequestParser<Body> for TestParser2 {
fn parse_operation_id(request: &hyper::Request<Body>) -> Result<&'static str, ()> {
match request.uri().path() {
"/test/t21" => Ok("t21"),
"/test/t22" => Ok("t22"),
_ => Err(()),
}
}
}
#[test]
fn test_macros() {
let uri = Uri::from_str(&"https://www.rust-lang.org/test/t11").unwrap();
let req1: Request<Body> = Request::get(uri).body(Body::empty()).unwrap();
let uri = Uri::from_str(&"https://www.rust-lang.org/test/t22").unwrap();
let req2: Request<Body> = Request::get(uri).body(Body::empty()).unwrap();
let uri = Uri::from_str(&"https://www.rust-lang.org/test/t33").unwrap();
let req3: Request<Body> = Request::get(uri).body(Body::empty()).unwrap();
request_parser_joiner!(JoinedReqParser, TestParser1, TestParser2);
assert_eq!(JoinedReqParser::parse_operation_id(&req1), Ok("t11"));
assert_eq!(JoinedReqParser::parse_operation_id(&req2), Ok("t22"));
assert_eq!(JoinedReqParser::parse_operation_id(&req3), Err(()));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.