text stringlengths 8 4.13M |
|---|
//! Parse delimited string inputs.
//!
// Taken liberally from https://github.com/Geal/nom/blob/main/examples/string.rs and
// amended for InfluxQL.
use crate::impl_tuple_clause;
use crate::internal::{expect, ParseError, ParseResult};
use nom::branch::alt;
use nom::bytes::complete::{is_not, tag, take_till};
use nom::character::complete::{anychar, char};
use nom::combinator::{map, value, verify};
use nom::error::Error;
use nom::multi::fold_many0;
use nom::sequence::{delimited, preceded};
use nom::Parser;
use std::fmt::{Display, Formatter, Write};
/// Writes `S` to `F`, mapping any characters `FROM` => `TO` their escaped equivalents.
#[macro_export]
macro_rules! write_escaped {
($F: expr, $STRING: expr $(, $FROM:expr => $TO:expr)+) => {
for c in $STRING.chars() {
match c {
$(
$FROM => $F.write_str($TO)?,
)+
_ => $F.write_char(c)?,
}
}
};
}
/// Writes `S` to `F`, optionally surrounding in `QUOTE`s, if FN(S) fails,
/// and mapping any characters `FROM` => `TO` their escaped equivalents.
#[macro_export]
macro_rules! write_quoted_string {
($F: expr, $QUOTE: literal, $STRING: expr, $FN: expr $(, $FROM:expr => $TO:expr)+) => {
if nom::sequence::terminated($FN, nom::combinator::eof)($STRING).is_ok() {
$F.write_str($STRING)?;
} else {
// must be escaped
$F.write_char($QUOTE)?;
for c in $STRING.chars() {
match c {
$(
$FROM => $F.write_str($TO)?,
)+
_ => $F.write_char(c)?,
}
}
$F.write_char($QUOTE)?;
}
};
}
/// A string fragment contains a fragment of a string being parsed: either
/// a non-empty Literal (a series of non-escaped characters) or a single.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StringFragment<'a> {
Literal(&'a str),
EscapedChar(char),
}
/// Parse a single-quoted literal string.
pub(crate) fn single_quoted_string(i: &str) -> ParseResult<&str, String> {
let escaped = preceded(
char('\\'),
expect(
r#"invalid escape sequence, expected \\, \' or \n"#,
alt((char('\\'), char('\''), value('\n', char('n')))),
),
);
string(
'\'',
"unterminated string literal",
verify(is_not("'\\\n"), |s: &str| !s.is_empty()),
escaped,
)(i)
}
/// Parse a double-quoted identifier string.
pub(crate) fn double_quoted_string(i: &str) -> ParseResult<&str, String> {
let escaped = preceded(
char('\\'),
expect(
r#"invalid escape sequence, expected \\, \" or \n"#,
alt((char('\\'), char('"'), value('\n', char('n')))),
),
);
string(
'"',
"unterminated string literal",
verify(is_not("\"\\\n"), |s: &str| !s.is_empty()),
escaped,
)(i)
}
fn string<'a, T, U, E>(
delimiter: char,
unterminated_message: &'static str,
literal: T,
escaped: U,
) -> impl FnMut(&'a str) -> ParseResult<&'a str, String, E>
where
T: Parser<&'a str, &'a str, E>,
U: Parser<&'a str, char, E>,
E: ParseError<'a>,
{
let fragment = alt((
map(literal, StringFragment::Literal),
map(escaped, StringFragment::EscapedChar),
));
let build_string = fold_many0(fragment, String::new, |mut string, fragment| {
match fragment {
StringFragment::Literal(s) => string.push_str(s),
StringFragment::EscapedChar(ch) => string.push(ch),
}
string
});
delimited(
char(delimiter),
build_string,
expect(unterminated_message, char(delimiter)),
)
}
/// Parse regular expression literal characters.
///
/// Consumes i until reaching and escaped delimiter ("\/"), newline or eof.
fn regex_literal(i: &str) -> ParseResult<&str, &str> {
let mut remaining = &i[..i.len()];
let mut consumed = &i[..0];
loop {
// match everything except `\`, `/` or `\n`
let (_, match_i) = take_till(|c| c == '\\' || c == '/' || c == '\n')(remaining)?;
consumed = &i[..(consumed.len() + match_i.len())];
remaining = &i[consumed.len()..];
// If we didn't consume anything, check whether it is a newline or regex delimiter,
// which signals we should leave this parser for outer processing.
if consumed.is_empty() {
is_not("/\n")(remaining)?;
}
// Try and consume '\' followed by a '/'
if let Ok((remaining_i, _)) = char::<_, Error<&str>>('\\')(remaining) {
if char::<_, Error<&str>>('/')(remaining_i).is_ok() {
// If we didn't consume anything, but we found "\/" sequence,
// we need to return an error so the outer fold_many0 parser does not trigger
// an infinite recursion error.
anychar(consumed)?;
// We're escaping a '/' (a regex delimiter), so finish and let
// the outer parser match and unescape
return Ok((remaining, consumed));
}
// Skip the '/' and continue consuming
consumed = &i[..consumed.len() + 1];
remaining = &i[consumed.len()..];
} else {
return Ok((remaining, consumed));
}
}
}
/// An unescaped regular expression.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Regex(pub(crate) String);
impl_tuple_clause!(Regex, String);
impl Display for Regex {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_char('/')?;
write_escaped!(f, self.0, '/' => "\\/");
f.write_char('/')
}
}
impl From<&str> for Regex {
fn from(v: &str) -> Self {
Self(v.into())
}
}
/// Parse a regular expression, delimited by `/`.
pub(crate) fn regex(i: &str) -> ParseResult<&str, Regex> {
map(
string(
'/',
"unterminated regex literal",
regex_literal,
map(tag("\\/"), |_| '/'),
),
Regex,
)(i)
}
#[cfg(test)]
mod test {
use super::*;
use crate::assert_expect_error;
#[test]
fn test_double_quoted_string() {
// ascii
let (_, got) = double_quoted_string(r#""quick draw""#).unwrap();
assert_eq!(got, "quick draw");
// ascii
let (_, got) = double_quoted_string(r#""n.asks""#).unwrap();
assert_eq!(got, "n.asks");
// unicode
let (_, got) = double_quoted_string("\"quick draw\u{1f47d}\"").unwrap();
assert_eq!(
got,
"quick draw\u{1f47d}" // 👽
);
// escaped characters
let (_, got) = double_quoted_string(r#""\n\\\"""#).unwrap();
assert_eq!(got, "\n\\\"");
// literal tab
let (_, got) = double_quoted_string("\"quick\tdraw\"").unwrap();
assert_eq!(got, "quick\tdraw");
// literal carriage return
let (_, got) = double_quoted_string("\"quick\rdraw\"").unwrap();
assert_eq!(got, "quick\rdraw");
// Empty string
let (i, got) = double_quoted_string("\"\"").unwrap();
assert_eq!(i, "");
assert_eq!(got, "");
// ┌─────────────────────────────┐
// │ Fallible tests │
// └─────────────────────────────┘
// Not terminated
assert_expect_error!(
double_quoted_string(r#""quick draw"#),
"unterminated string literal"
);
// Literal newline
assert_expect_error!(
double_quoted_string("\"quick\ndraw\""),
"unterminated string literal"
);
// Invalid escape
assert_expect_error!(
double_quoted_string(r#""quick\idraw""#),
r#"invalid escape sequence, expected \\, \" or \n"#
);
}
#[test]
fn test_single_quoted_string() {
// ascii
let (_, got) = single_quoted_string(r#"'quick draw'"#).unwrap();
assert_eq!(got, "quick draw");
// unicode
let (_, got) = single_quoted_string("'quick draw\u{1f47d}'").unwrap();
assert_eq!(
got,
"quick draw\u{1f47d}" // 👽
);
// escaped characters
let (_, got) = single_quoted_string(r#"'\n\''"#).unwrap();
assert_eq!(got, "\n'");
let (_, got) = single_quoted_string(r#"'\'hello\''"#).unwrap();
assert_eq!(got, "'hello'");
// literal tab
let (_, got) = single_quoted_string("'quick\tdraw'").unwrap();
assert_eq!(got, "quick\tdraw");
// literal carriage return
let (_, got) = single_quoted_string("'quick\rdraw'").unwrap();
assert_eq!(got, "quick\rdraw");
// Empty string
let (i, got) = single_quoted_string("''").unwrap();
assert_eq!(i, "");
assert_eq!(got, "");
// ┌─────────────────────────────┐
// │ Fallible tests │
// └─────────────────────────────┘
// Not terminated
assert_expect_error!(
single_quoted_string(r#"'quick draw"#),
"unterminated string literal"
);
// Invalid escape
assert_expect_error!(
single_quoted_string(r#"'quick\idraw'"#),
r#"invalid escape sequence, expected \\, \' or \n"#
);
}
#[test]
fn test_regex() {
let (_, got) = regex("/hello/").unwrap();
assert_eq!(got, "hello".into());
// handle escaped delimiters "\/"
let (_, got) = regex(r#"/\/this\/is\/a\/path/"#).unwrap();
assert_eq!(got, "/this/is/a/path".into());
// ignores any other possible escape sequence
let (_, got) = regex(r#"/hello\n/"#).unwrap();
assert_eq!(got, "hello\\n".into());
// can parse possible escape sequence at beginning of regex
let (_, got) = regex(r#"/\w.*/"#).unwrap();
assert_eq!(got, "\\w.*".into());
// Empty regex
let (i, got) = regex("//").unwrap();
assert_eq!(i, "");
assert_eq!(got, "".into());
// Fallible cases
// Missing trailing delimiter
assert_expect_error!(regex(r#"/hello"#), "unterminated regex literal");
// Embedded newline
assert_expect_error!(regex("/hello\nworld/"), "unterminated regex literal");
// Single backslash fails, which matches Go implementation
// See: https://go.dev/play/p/_8J1v5-382G
assert_expect_error!(regex(r#"/\/"#), "unterminated regex literal");
}
}
|
mod actions;
mod apt;
mod block;
mod ctdb;
mod hooks;
mod metrics;
mod samba;
mod updatedb;
mod upgrade;
extern crate debian;
extern crate fstab;
extern crate gluster;
extern crate ipnetwork;
extern crate itertools;
#[macro_use]
extern crate juju;
extern crate resolve;
extern crate serde_yaml;
extern crate uuid;
use actions::{disable_volume_quota, enable_volume_quota, list_volume_quotas, set_volume_options};
use hooks::brick_detached::brick_detached;
use hooks::config_changed::config_changed;
use hooks::fuse_relation_joined::fuse_relation_joined;
use hooks::nfs_relation_joined::nfs_relation_joined;
use hooks::server_changed::server_changed;
use hooks::server_removed::server_removed;
use metrics::collect_metrics;
use std::collections::BTreeMap;
use std::env;
use std::error::Error as StdError;
use std::fs;
use std::fs::create_dir;
use std::num::ParseIntError;
use std::io::{Error, ErrorKind, Write};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::thread;
use std::time::Duration;
use debian::version::Version;
use gluster::peer::{peer_probe, peer_status, Peer, State};
use gluster::volume::*;
use ipnetwork::IpNetwork;
use itertools::Itertools;
use juju::{JujuError, unitdata};
use resolve::address::address_name;
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::path::PathBuf;
use super::gluster::volume::{Brick, Transport, Volume, VolumeType};
use super::gluster::peer::{Peer, State};
use super::uuid::Uuid;
#[test]
fn test_all_peers_are_ready() {
let peers: Vec<Peer> = vec![Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
},
Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
}];
let ready = super::peers_are_ready(Ok(peers));
println!("Peers are ready: {}", ready);
assert!(ready);
}
#[test]
fn test_some_peers_are_ready() {
let peers: Vec<Peer> = vec![Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::Connected,
},
Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
}];
let ready = super::peers_are_ready(Ok(peers));
println!("Some peers are ready: {}", ready);
assert_eq!(ready, false);
}
#[test]
fn test_find_new_peers() {
let peer1 = Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
};
let peer2 = Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
};
// peer1 and peer2 are in the cluster but only peer1 is actually serving a brick.
// find_new_peers should return peer2 as a new peer
let peers: Vec<Peer> = vec![peer1.clone(), peer2.clone()];
let existing_brick = Brick {
peer: peer1,
path: PathBuf::from("/mnt/brick1"),
};
let volume_info = Volume {
name: "Test".to_string(),
vol_type: VolumeType::Replicate,
id: Uuid::new_v4(),
status: "online".to_string(),
transport: Transport::Tcp,
bricks: vec![existing_brick],
options: BTreeMap::new(),
};
let new_peers = super::find_new_peers(&peers, &volume_info);
assert_eq!(new_peers, vec![peer2]);
}
#[test]
fn test_cartesian_product() {
let peer1 = Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
};
let peer2 = Peer {
uuid: Uuid::new_v4(),
hostname: format!("host-{}", Uuid::new_v4()),
status: State::PeerInCluster,
};
let peers = vec![peer1.clone(), peer2.clone()];
let paths = vec!["/mnt/brick1".to_string(), "/mnt/brick2".to_string()];
let result = super::brick_and_server_cartesian_product(&peers, &paths);
println!("brick_and_server_cartesian_product: {:?}", result);
assert_eq!(result,
vec![Brick {
peer: peer1.clone(),
path: PathBuf::from("/mnt/brick1"),
},
Brick {
peer: peer2.clone(),
path: PathBuf::from("/mnt/brick1"),
},
Brick {
peer: peer1.clone(),
path: PathBuf::from("/mnt/brick2"),
},
Brick {
peer: peer2.clone(),
path: PathBuf::from("/mnt/brick2"),
}]);
}
}
// Need more expressive return values so we can wait on peers
#[derive(Debug)]
#[allow(dead_code)]
enum Status {
Created,
WaitForMorePeers,
InvalidConfig(String),
FailedToCreate(String),
FailedToStart(String),
}
fn get_config_value(name: &str) -> Result<String, String> {
match juju::config_get(&name.to_string()) {
Ok(v) => Ok(v.unwrap_or_default()),
Err(e) => {
return Err(e.to_string());
}
}
}
// Returns None in the case of any error but logs why it happened
fn get_config_number<T: FromStr<Err = ParseIntError>>(name: &str) -> Option<T> {
match juju::config_get(&name.to_string()) {
Ok(s) => {
match s {
Some(field) => {
match T::from_str(&field) {
Ok(value) => Some(value),
Err(e) => {
log!(format!("Error getting config field: {}. {}", name, e),
Error);
None
}
}
}
None => None,
}
}
Err(e) => {
log!(format!("Error getting config field: {}. {}", name, e),
Error);
None
}
}
}
// sysctl: a YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }"
fn create_sysctl<T: Write>(sysctl: String, f: &mut T) -> Result<usize, String> {
let deserialized_map: BTreeMap<String, String> =
serde_yaml::from_str(&sysctl).map_err(|e| e.to_string())?;
let mut bytes_written = 0;
for (key, value) in deserialized_map {
bytes_written += f.write(&format!("{}={}\n", key, value).as_bytes())
.map_err(|e| e.to_string())?;
}
Ok(bytes_written)
}
// Return all the virtual ip networks that will be used
fn get_cluster_networks() -> Result<Vec<ctdb::VirtualIp>, String> {
let mut cluster_networks: Vec<ctdb::VirtualIp> = Vec::new();
let config_value = match juju::config_get("virtual_ip_addresses").map_err(|e| e.to_string())? {
Some(vips) => vips,
None => return Ok(cluster_networks),
};
let virtual_ips: Vec<&str> = config_value.split(" ").collect();
for vip in virtual_ips {
if vip.is_empty() {
continue;
}
let network = ctdb::ipnetwork_from_str(vip)?;
let interface = ctdb::get_interface_for_address(network)
.ok_or(format!("Failed to find interface for network {:?}", network))?;
cluster_networks.push(ctdb::VirtualIp {
cidr: network,
interface: interface,
});
}
Ok(cluster_networks)
}
fn peers_are_ready(peers: Result<Vec<Peer>, gluster::GlusterError>) -> bool {
match peers {
Ok(peer_list) => {
// Ensure all peers are in a PeerInCluster state
log!(format!("Got peer status: {:?}", peer_list));
return peer_list.iter().all(|peer| peer.status == State::PeerInCluster);
}
Err(err) => {
log!(format!("peers_are_ready failed to get peer status: {:?}", err),
Error);
return false;
}
}
}
// HDD's are so slow that sometimes the peers take long to join the cluster.
// This will loop and wait for them ie spinlock
fn wait_for_peers() -> Result<(), String> {
log!("Waiting for all peers to enter the Peer in Cluster status");
status_set!(Maintenance "Waiting for all peers to enter the \"Peer in Cluster status\"");
let mut iterations = 0;
while !peers_are_ready(peer_status()) {
thread::sleep(Duration::from_secs(1));
iterations += 1;
if iterations > 600 {
return Err("Gluster peers failed to connect after 10 minutes".to_string());
}
}
return Ok(());
}
// Probe in a unit if they haven't joined yet
// This function is confusing because Gluster has weird behavior.
// 1. If you probe in units by their IP address it works. The CLI will show you their resolved
// hostnames however
// 2. If you probe in units by their hostname instead it'll still work but gluster client mount
// commands will fail if it can not resolve the hostname.
// For example: Probing in containers by hostname will cause the glusterfs client to fail to mount
// on the container host. :(
// 3. To get around this I'm converting hostnames to ip addresses in the gluster library to mask
// this from the callers.
//
fn probe_in_units(existing_peers: &Vec<Peer>,
related_units: Vec<juju::Relation>)
-> Result<(), String> {
log!(format!("Adding in related_units: {:?}", related_units));
for unit in related_units {
let address = match juju::relation_get_by_unit(&"private-address".to_string(), &unit)
.map_err(|e| e.to_string())?{
Some(address) => address,
None => {
log!(format!("unit {:?} private-address was blank, skipping.", unit));
continue;
}
};
let address_trimmed = address.trim().to_string();
let already_probed = existing_peers.iter().any(|peer| peer.hostname == address_trimmed);
// Probe the peer in
if !already_probed {
log!(format!("Adding {} to cluster", &address_trimmed));
match peer_probe(&address_trimmed) {
Ok(_) => {
log!("Gluster peer probe was successful");
}
Err(why) => {
log!(format!("Gluster peer probe failed: {:?}", why), Error);
return Err(why.to_string());
}
};
}
}
return Ok(());
}
fn find_new_peers(peers: &Vec<Peer>, volume_info: &Volume) -> Vec<Peer> {
let mut new_peers: Vec<Peer> = Vec::new();
for peer in peers {
// If this peer is already in the volume, skip it
let existing_peer = volume_info.bricks.iter().any(|brick| brick.peer.uuid == peer.uuid);
if !existing_peer {
new_peers.push(peer.clone());
}
}
return new_peers;
}
fn brick_and_server_cartesian_product(peers: &Vec<Peer>,
paths: &Vec<String>)
-> Vec<gluster::volume::Brick> {
let mut product: Vec<gluster::volume::Brick> = Vec::new();
let it = paths.iter().cartesian_product(peers.iter());
for (path, host) in it {
let brick = gluster::volume::Brick {
peer: host.clone(),
path: PathBuf::from(path),
};
product.push(brick);
}
return product;
}
fn ephemeral_unmount() -> Result<(), String> {
match get_config_value("ephemeral_unmount") {
Ok(mountpoint) => {
if mountpoint.is_empty() {
return Ok(());
}
// Remove the entry from the fstab if it's set
let fstab = fstab::FsTab::new(&Path::new("/etc/fstab"));
log!("Removing ephemeral mount from fstab");
fstab.remove_entry(&mountpoint).map_err(|e| e.to_string())?;
if is_mounted(&mountpoint)? {
let mut cmd = std::process::Command::new("umount");
cmd.arg(mountpoint);
let output = cmd.output().map_err(|e| e.to_string())?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).into_owned());
}
// Unmounted Ok
return Ok(());
}
// Not mounted
Ok(())
}
_ => {
// No-op
Ok(())
}
}
}
// Given a dev device path /dev/xvdb this will check to see if the device
// has been formatted and mounted
fn device_initialized(brick_path: &PathBuf) -> Result<bool, JujuError> {
// Connect to the default unitdata database
log!("Connecting to unitdata storage");
let unit_storage = unitdata::Storage::new(None)?;
log!("Getting unit_info");
let unit_info = unit_storage.get::<bool>(&brick_path.to_string_lossy())?;
log!(format!("unit_info: {:?}", unit_info));
// Either it's Some() and we know about the unit
// or it's None and we don't know and therefore it's not initialized
Ok(unit_info.unwrap_or(false))
}
fn finish_initialization(device_path: &PathBuf) -> Result<(), Error> {
let filesystem_config_value =
get_config_value("filesystem_type").map_err(|e| Error::new(ErrorKind::Other, e))?;
let defrag_interval =
get_config_value("defragmentation_interval").map_err(|e| Error::new(ErrorKind::Other, e))?;
let disk_elevator =
get_config_value("disk_elevator").map_err(|e| Error::new(ErrorKind::Other, e))?;
let scheduler =
block::Scheduler::from_str(&disk_elevator).map_err(|e| Error::new(ErrorKind::Other, e))?;
let filesystem_type = block::FilesystemType::from_str(&filesystem_config_value);
let mount_path = format!("/mnt/{}",
device_path.file_name().unwrap().to_string_lossy());
let unit_storage = unitdata::Storage::new(None).map_err(|e| Error::new(ErrorKind::Other, e))?;
let device_info =
block::get_device_info(device_path).map_err(|e| Error::new(ErrorKind::Other, e))?;
log!(format!("device_info: {:?}", device_info), Info);
//Zfs automatically handles mounting the device
if filesystem_type != block::FilesystemType::Zfs {
log!(format!("Mounting block device {:?} at {}", &device_path, mount_path),
Info);
status_set!(Maintenance
format!("Mounting block device {:?} at {}", &device_path, mount_path));
if !Path::new(&mount_path).exists() {
log!(format!("Creating mount directory: {}", &mount_path), Info);
create_dir(&mount_path)?;
}
block::mount_device(&device_info, &mount_path)
.map_err(|e| Error::new(ErrorKind::Other, e))?;
let fstab_entry = fstab::FsEntry {
fs_spec: format!("UUID={}",
device_info.id
.unwrap()
.hyphenated()
.to_string()),
mountpoint: PathBuf::from(&mount_path),
vfs_type: device_info.fs_type.to_string(),
mount_options: vec!["noatime".to_string(), "inode64".to_string()],
dump: false,
fsck_order: 2,
};
log!(format!("Adding {:?} to fstab", fstab_entry));
let fstab = fstab::FsTab::new(&Path::new("/etc/fstab"));
fstab.add_entry(fstab_entry)?;
}
unit_storage.set(&device_path.to_string_lossy(), true)
.map_err(|e| Error::new(ErrorKind::Other, e))?;
log!(format!("Removing mount path from updatedb {:?}", mount_path),
Info);
updatedb::add_to_prunepath(&mount_path, &Path::new("/etc/updatedb.conf"))?;
block::weekly_defrag(&mount_path, &filesystem_type, &defrag_interval)?;
block::set_elevator(&device_path, &scheduler)?;
Ok(())
}
// Format and mount block devices to ready them for consumption by Gluster
// Return an Initialization struct
fn initialize_storage(device: block::BrickDevice) -> Result<block::AsyncInit, String> {
let filesystem_config_value = get_config_value("filesystem_type")?;
//Custom params
let stripe_width = get_config_number::<u64>("raid_stripe_width");
let stripe_size = get_config_number::<u64>("raid_stripe_size");
let inode_size = get_config_number::<u64>("inode_size");
let filesystem_type = block::FilesystemType::from_str(&filesystem_config_value);
let init: block::AsyncInit;
// Format with the default XFS unless told otherwise
match filesystem_type {
block::FilesystemType::Xfs => {
log!(format!("Formatting block device with XFS: {:?}", &device.dev_path),
Info);
status_set!(Maintenance
format!("Formatting block device with XFS: {:?}", &device.dev_path));
let filesystem_type = block::Filesystem::Xfs {
block_size: None,
force: true,
inode_size: inode_size,
stripe_size: stripe_size,
stripe_width: stripe_width,
};
init = block::format_block_device(device, &filesystem_type)?;
}
block::FilesystemType::Ext4 => {
log!(format!("Formatting block device with Ext4: {:?}", &device.dev_path),
Info);
status_set!(Maintenance
format!("Formatting block device with Ext4: {:?}", &device.dev_path));
let filesystem_type = block::Filesystem::Ext4 {
inode_size: inode_size,
reserved_blocks_percentage: 0,
stride: stripe_size,
stripe_width: stripe_width,
};
init = block::format_block_device(device, &filesystem_type)?;
}
block::FilesystemType::Btrfs => {
log!(format!("Formatting block device with Btrfs: {:?}", &device.dev_path),
Info);
status_set!(Maintenance
format!("Formatting block device with Btrfs: {:?}", &device.dev_path));
let filesystem_type = block::Filesystem::Btrfs {
leaf_size: 0,
node_size: 0,
metadata_profile: block::MetadataProfile::Single,
};
init = block::format_block_device(device, &filesystem_type)?;
}
block::FilesystemType::Zfs => {
log!(format!("Formatting block device with ZFS: {:?}", &device.dev_path),
Info);
status_set!(Maintenance
format!("Formatting block device with ZFS: {:?}", &device.dev_path));
let filesystem_type = block::Filesystem::Zfs {
compression: None,
block_size: None,
};
init = block::format_block_device(device, &filesystem_type)?;
}
_ => {
log!(format!("Formatting block device with XFS: {:?}", &device.dev_path),
Info);
status_set!(Maintenance
format!("Formatting block device with XFS: {:?}", &device.dev_path));
let filesystem_type = block::Filesystem::Xfs {
block_size: None,
force: true,
inode_size: inode_size,
stripe_width: stripe_width,
stripe_size: stripe_size,
};
init = block::format_block_device(device, &filesystem_type)?;
}
}
return Ok(init);
}
fn resolve_first_vip_to_dns() -> Result<String, String> {
let cluster_networks = get_cluster_networks()?;
match cluster_networks.first() {
Some(cluster_network) => {
match cluster_network.cidr {
IpNetwork::V4(ref v4_network) => {
// Resolve the ipv4 address back to a dns string
Ok(address_name(&::std::net::IpAddr::V4(v4_network.ip())))
}
IpNetwork::V6(ref v6_network) => {
// Resolve the ipv6 address back to a dns string
Ok(address_name(&::std::net::IpAddr::V6(v6_network.ip())))
}
}
}
None => {
// No vips were set?
Err("virtual_ip_addresses has no addresses set".to_string())
}
}
}
fn get_glusterfs_version() -> Result<Version, String> {
let mut cmd = std::process::Command::new("dpkg");
cmd.arg("-s");
cmd.arg("glusterfs-server");
let output = cmd.output().map_err(|e| e.to_string())?;
if output.status.success() {
let output_str = String::from_utf8_lossy(&output.stdout).into_owned();
for line in output_str.lines() {
if line.starts_with("Version") {
// return the version
let parts: Vec<&str> = line.split(" ").collect();
if parts.len() == 2 {
let parse_version = Version::parse(&parts[1]).map_err(|e| e.msg)?;
return Ok(parse_version);
} else {
return Err(format!("apt-cache Verion string is invalid: {}", line));
}
}
}
} else {
return Err(String::from_utf8_lossy(&output.stderr).into_owned());
}
return Err("Unable to find glusterfs-server version".to_string());
}
fn is_mounted(directory: &str) -> Result<bool, String> {
let path = Path::new(directory);
let parent = path.parent();
let dir_metadata = try!(fs::metadata(directory).map_err(|e| e.to_string()));
let file_type = dir_metadata.file_type();
if file_type.is_symlink() {
// A symlink can never be a mount point
return Ok(false);
}
if parent.is_some() {
let parent_metadata = try!(fs::metadata(parent.unwrap()).map_err(|e| e.to_string()));
if parent_metadata.dev() != dir_metadata.dev() {
// path/.. on a different device as path
return Ok(true);
}
} else {
// If the directory doesn't have a parent it's the root filesystem
return Ok(false);
}
return Ok(false);
}
// Mount the cluster at /mnt/glusterfs using fuse
fn mount_cluster(volume_name: &str) -> Result<(), String> {
if !Path::new("/mnt/glusterfs").exists() {
create_dir("/mnt/glusterfs").map_err(|e| e.to_string())?;
}
if !is_mounted("/mnt/glusterfs")? {
let mut cmd = std::process::Command::new("mount");
cmd.arg("-t");
cmd.arg("glusterfs");
cmd.arg(&format!("localhost:/{}", volume_name));
cmd.arg("/mnt/glusterfs");
let output = cmd.output().map_err(|e| e.to_string())?;
if output.status.success() {
log!("Removing /mnt/glusterfs from updatedb", Info);
updatedb::add_to_prunepath(&String::from("/mnt/glusterfs"),
&Path::new("/etc/updatedb.conf")).map_err(|e| e.to_string())?;
return Ok(());
} else {
return Err(String::from_utf8_lossy(&output.stderr).into_owned());
}
}
return Ok(());
}
// Update the juju status information
fn update_status() -> Result<(), String> {
let version = get_glusterfs_version()?;
juju::application_version_set(&format!("{}", version.upstream_version))
.map_err(|e| e.to_string())?;
let volume_name = get_config_value("volume_name")?;
let local_bricks = gluster::get_local_bricks(&volume_name);
match local_bricks {
Ok(bricks) => {
status_set!(Active format!("Unit is ready ({} bricks)", bricks.len()));
// Ensure the cluster is mounted
mount_cluster(&volume_name)?;
Ok(())
}
Err(gluster::GlusterError::NoVolumesPresent) => {
status_set!(Blocked "No bricks found");
Ok(())
}
_ => Ok(()),
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() > 0 {
// Register our hooks with the Juju library
let hook_registry: Vec<juju::Hook> =
vec![hook!("brick-storage-detaching", brick_detached),
hook!("collect-metrics", collect_metrics),
hook!("config-changed", config_changed),
hook!("create-volume-quota", enable_volume_quota),
hook!("delete-volume-quota", disable_volume_quota),
hook!("fuse-relation-joined", fuse_relation_joined),
hook!("list-volume-quotas", list_volume_quotas),
hook!("nfs-relation-joined", nfs_relation_joined),
hook!("server-relation-changed", server_changed),
hook!("server-relation-departed", server_removed),
hook!("set-volume-options", set_volume_options),
hook!("update-status", update_status)];
let result = juju::process_hooks(hook_registry);
if result.is_err() {
log!(format!("Hook failed with error: {:?}", result.err()), Error);
}
update_status();
}
}
|
use serde::de::IntoDeserializer;
use crate::de::Error;
pub(crate) struct TableDeserializer {
span: Option<std::ops::Range<usize>>,
items: crate::table::KeyValuePairs,
}
// Note: this is wrapped by `Deserializer` and `ValueDeserializer` and any trait methods
// implemented here need to be wrapped there
impl<'de> serde::Deserializer<'de> for TableDeserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_map(crate::de::TableMapAccess::new(self))
}
// `None` is interpreted as a missing field so be sure to implement `Some`
// as a present field.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_some(self)
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_struct<V>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
if serde_spanned::__unstable::is_spanned(name, fields) {
if let Some(span) = self.span.clone() {
return visitor.visit_map(super::SpannedDeserializer::new(self, span));
}
}
self.deserialize_any(visitor)
}
// Called when the type to deserialize is an enum, as opposed to a field in the type.
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
if self.items.is_empty() {
Err(crate::de::Error::custom(
"wanted exactly 1 element, found 0 elements",
self.span,
))
} else if self.items.len() != 1 {
Err(crate::de::Error::custom(
"wanted exactly 1 element, more than 1 element",
self.span,
))
} else {
visitor.visit_enum(crate::de::TableMapAccess::new(self))
}
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map unit
ignored_any unit_struct tuple_struct tuple identifier
}
}
impl<'de> serde::de::IntoDeserializer<'de, crate::de::Error> for TableDeserializer {
type Deserializer = TableDeserializer;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
impl crate::Table {
pub(crate) fn into_deserializer(self) -> TableDeserializer {
TableDeserializer {
span: self.span(),
items: self.items,
}
}
}
impl crate::InlineTable {
pub(crate) fn into_deserializer(self) -> TableDeserializer {
TableDeserializer {
span: self.span(),
items: self.items,
}
}
}
pub(crate) struct TableMapAccess {
iter: indexmap::map::IntoIter<crate::InternalString, crate::table::TableKeyValue>,
span: Option<std::ops::Range<usize>>,
value: Option<(crate::InternalString, crate::Item)>,
}
impl TableMapAccess {
pub(crate) fn new(input: TableDeserializer) -> Self {
Self {
iter: input.items.into_iter(),
span: input.span,
value: None,
}
}
}
impl<'de> serde::de::MapAccess<'de> for TableMapAccess {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: serde::de::DeserializeSeed<'de>,
{
match self.iter.next() {
Some((k, v)) => {
let ret = seed
.deserialize(super::KeyDeserializer::new(k, v.key.span()))
.map(Some)
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(v.key.span());
}
e
});
self.value = Some((v.key.into(), v.value));
ret
}
None => Ok(None),
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: serde::de::DeserializeSeed<'de>,
{
match self.value.take() {
Some((k, v)) => {
let span = v.span();
seed.deserialize(crate::de::ValueDeserializer::new(v))
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e.add_key(k.as_str().to_owned());
e
})
}
None => {
panic!("no more values in next_value_seed, internal error in ValueDeserializer")
}
}
}
}
impl<'de> serde::de::EnumAccess<'de> for TableMapAccess {
type Error = Error;
type Variant = super::TableEnumDeserializer;
fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: serde::de::DeserializeSeed<'de>,
{
let (key, value) = match self.iter.next() {
Some(pair) => pair,
None => {
return Err(Error::custom(
"expected table with exactly 1 entry, found empty table",
self.span,
));
}
};
let val = seed
.deserialize(key.into_deserializer())
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(value.key.span());
}
e
})?;
let variant = super::TableEnumDeserializer::new(value.value);
Ok((val, variant))
}
}
|
// 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.
fn main() {
let args: Vec<String> = std::env::args().collect();
println!("{}", args.join(" "));
}
|
pub fn sort<T: Ord>(input: &mut Vec<T>) {
input.sort();
}
add_common_tests!();
|
use actix_web_validator::JsonConfig;
/// Request struct that will be used to extract data from the request
/// and to run validation on the extracted data.
#[derive(serde::Deserialize, validator::Validate)]
pub struct NewTodoRequest {
#[validate(length(min = 3))]
pub content: Option<String>,
}
// App configuration data that will setup the needed configurations on it.
pub fn app_data() -> JsonConfig {
super::default_app_data::<NewTodoRequest>()
}
|
pub struct Logo;
pub struct Prompt;
pub struct Message;
pub struct Warning;
impl Logo {
pub const HUNT_ASCII: &'static str = "
██░ ██ █ ██ ███▄ █ ▄▄▄█████▓
▓██░ ██▒ ██ ▓██▒ ██ ▀█ █ ▓ ██▒ ▓▒
▒██▀▀██░▓██ ▒██░▓██ ▀█ ██▒▒ ▓██░ ▒░
░▓█ ░██ ▓▓█ ░██░▓██▒ ▐▌██▒░ ▓██▓ ░
░▓█▒░██▓▒▒█████▓ ▒██░ ▓██░ ▒██▒ ░
▒ ░░▒░▒░▒▓▒ ▒ ▒ ░ ▒░ ▒ ▒ ▒ ░░
▒ ░▒░ ░░░▒░ ░ ░ ░ ░░ ░ ▒░ ░
░ ░░ ░ ░░░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░
";
pub const THE_ASCII: &'static str = "
▄▄▄█████▓ ██░ ██ ▓█████
▓ ██▒ ▓▒▓██░ ██▒▓█ ▀
▒ ▓██░ ▒░▒██▀▀██░▒███
░ ▓██▓ ░ ░▓█ ░██ ▒▓█ ▄
▒██▒ ░ ░▓█▒░██▓░▒████▒
▒ ░░ ▒ ░░▒░▒░░ ▒░ ░
░ ▒ ░▒░ ░ ░ ░ ░
░ ░ ░░ ░ ░
░ ░ ░ ░ ░
";
pub const WUMPUS_ASCII: &'static str = "
█ █░█ ██ ███▄ ▄███▓ ██▓███ █ ██ ██████
▓█░ █ ░█░██ ▓██▒▓██▒▀█▀ ██▒▓██░ ██▒ ██ ▓██▒▒██ ▒
▒█░ █ ░█▓██ ▒██░▓██ ▓██░▓██░ ██▓▒▓██ ▒██░░ ▓██▄
░█░ █ ░█▓▓█ ░██░▒██ ▒██ ▒██▄█▓▒ ▒▓▓█ ░██░ ▒ ██▒
░░██▒██▓▒▒█████▓ ▒██▒ ░██▒▒██▒ ░ ░▒▒█████▓ ▒██████▒▒
░ ▓░▒ ▒ ░▒▓▒ ▒ ▒ ░ ▒░ ░ ░▒▓▒░ ░ ░░▒▓▒ ▒ ▒ ▒ ▒▓▒ ▒ ░
▒ ░ ░ ░░▒░ ░ ░ ░ ░ ░░▒ ░ ░░▒░ ░ ░ ░ ░▒ ░ ░
░ ░ ░░░ ░ ░ ░ ░ ░░ ░░░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░
";
}
impl Prompt {
pub const ACTION: &'static str = "Shoot, Move or Quit(S - M - Q)? ";
pub const PLAY: &'static str = "Play again? (Y-N) ";
pub const SETUP: &'static str = "Same Setup? (Y-N) ";
}
impl Message {
pub const BAT_SNATCH: &'static str = "Zap--Super Bat snatch! Elsewhereville for you!";
pub const WUMPUS_BUMP: &'static str = "...Oops! Bumped a wumpus!";
pub const OUT_OF_ARROWS: &'static str = "You've run out of arrows!";
pub const ARROW_GOT_YOU: &'static str = "Ouch! Arrow got you!";
pub const MISSED: &'static str = "Missed!";
pub const TOO_CROOKED: &'static str = "Arrows aren't that crooked - try another room sequence!";
pub const FELL_IN_PIT: &'static str = "YYYIIIIEEEE... fell in a pit!";
pub const WUMPUS_GOT_YOU: &'static str = "Tsk tsk tsk - wumpus got you!";
pub const LOSE: &'static str = "Ha ha ha - you lose!";
pub const WIN: &'static str =
"Aha! You got the Wumpus!\nHee hee hee - the Wumpus'll getcha next time!!";
}
impl Warning {
pub const PIT: &'static str = "I feel a draft!";
pub const WUMPUS: &'static str = "I Smell a Wumpus.";
pub const BAT: &'static str = "Bats nearby!";
}
|
// Thanks for the examples from
// https://github.com/therealprof/microbit/
use nrf51822::{Peripherals, UART0};
pub fn init(p: &Peripherals) {
p.GPIO.pin_cnf[24].write(|w| w.pull().pullup().dir().output());
p.GPIO.pin_cnf[25].write(|w| w.pull().disabled().dir().input());
p.UART0.pseltxd.write(|w| unsafe { w.bits(24) });
p.UART0.pselrxd.write(|w| unsafe { w.bits(25) });
p.UART0.baudrate.write(|w| w.baudrate().baud115200());
p.UART0.enable.write(|w| w.enable().enabled());
}
pub fn write_str(uart0: &UART0, s: &[u8]) -> core::fmt::Result {
uart0.tasks_starttx.write(|w| unsafe { w.bits(1) });
for c in s {
/* Write the current character to the output register */
uart0.txd.write(|w| unsafe { w.bits(u32::from(*c)) });
/* Wait until the UART is clear to send */
while uart0.events_txdrdy.read().bits() == 0 {}
/* And then set it back to 0 again, just because ?!? */
uart0.events_txdrdy.write(|w| unsafe { w.bits(0) });
}
uart0.tasks_stoptx.write(|w| unsafe { w.bits(1) });
Ok(())
}
pub fn read_u8(uart0: &UART0) -> u8 {
/* Fire up receiving task */
uart0.tasks_startrx.write(|w| unsafe { w.bits(1) });
/* Busy wait for reception of data */
while uart0.events_rxdrdy.read().bits() == 0 {
cortex_m::asm::nop();
}
/* We're going to pick up the data soon, let's signal the buffer is already waiting for
* more data */
uart0.events_rxdrdy.write(|w| unsafe { w.bits(0) });
/* Read one 8bit value */
uart0.rxd.read().bits() as u8
}
pub fn read_buf(uart0: &UART0, out: &mut [u8]) {
for (_, v) in out.iter_mut().enumerate() {
*v = read_u8(uart0);
}
}
|
use gophermap::{GopherMenu,ItemType};
use std::io::{self, BufRead, BufReader};
use std::net::{TcpListener, TcpStream};
use std::thread;
const HOST: &str = "localhost";
const PORT: u16 = 1234;
fn handle_client(stream: TcpStream) -> io::Result<()> {
let mut line = String::new();
BufReader::new(stream.try_clone()?).read_line(&mut line)?;
let line = line.trim();
println!("New request: {}", line);
let mut menu = GopherMenu::with_write(&stream);
let menu_link = |text: &str, selector: &str|
menu.write_entry(ItemType::Directory, text, selector, HOST, PORT);
match line {
"/" | "" => {
menu.info("Hi!")?;
menu.info("Welcome to my Gopher server!")?;
menu_link("Tomatoes", "/tomato")?;
menu.info("Opinion piece about tomatoes")?;
menu_link("Potatoes", "/potato")?;
menu.info("Opinion piece about potatoes")?;
menu_link("Go to unknown link", "/lel")?;
}
"/tomato" => {
menu.info("Tomatoes are not good")?;
menu_link("Home page", "/")?;
}
"/potato" => {
menu.info("Potatoes are the best")?;
menu_link("Home page", "/")?;
}
x => {
menu.info(&format!("Unknown link: {}", x))?;
menu_link("Home page", "/")?;
}
};
menu.end()?;
Ok(())
}
fn main() -> io::Result<()> {
let listener = TcpListener::bind(format!("{}:{}", HOST, PORT))?;
for stream in listener.incoming() {
thread::spawn(move || handle_client(stream?));
}
Ok(())
}
|
pub mod Matrix22;
pub mod Matrix33;
pub mod Matrix44;
pub mod MatrixProperties;
|
use crate::Error as OpenrrAppsError;
use async_recursion::async_recursion;
use log::info;
use openrr_client::isometry;
use std::{
error::Error,
fs::File,
io::{BufRead, BufReader},
path::PathBuf,
};
use structopt::StructOpt;
use crate::{RobotClient, RobotConfig};
#[derive(StructOpt, Debug)]
#[structopt(name = "robot_command", about = "An openrr command line tool.")]
pub struct RobotCommand {
#[structopt(short, long, parse(from_os_str))]
config_path: Option<PathBuf>,
#[structopt(subcommand)]
sub_command: RobotSubCommand,
}
fn parse_joints<T, U>(s: &str) -> Result<(T, U), Box<dyn Error>>
where
T: std::str::FromStr,
T::Err: Error + 'static,
U: std::str::FromStr,
U::Err: Error + 'static,
{
let pos = s
.find('=')
.ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}
#[derive(StructOpt, Debug)]
#[structopt(rename_all = "snake_case")]
pub enum RobotSubCommand {
/// Send joint positions.
Joints {
name: String,
#[structopt(short, long, default_value = "3.0")]
duration: f64,
/// Interpolate target in cartesian space.
/// If you use this flag, joint values are not used as references but used in forward kinematics.
#[structopt(name = "interpolate", short, long)]
use_interpolation: bool,
#[structopt(short, parse(try_from_str=parse_joints))]
joint: Vec<(usize, f64)>,
},
/// Move with ik
Ik {
name: String,
#[structopt(short, long)]
x: Option<f64>,
#[structopt(short, long)]
y: Option<f64>,
#[structopt(short, long)]
z: Option<f64>,
#[structopt(long)]
yaw: Option<f64>,
#[structopt(short, long)]
pitch: Option<f64>,
#[structopt(short, long)]
roll: Option<f64>,
#[structopt(short, long, default_value = "3.0")]
duration: f64,
/// Interpolate target in cartesian space.
#[structopt(name = "interpolate", short, long)]
use_interpolation: bool,
#[structopt(name = "local", short, long)]
is_local: bool,
},
/// Get joint positions and end pose if applicable.
Get { name: String },
/// Load commands from file and execute them.
Load {
#[structopt(parse(from_os_str))]
command_file_path: PathBuf,
},
/// List available clients.
List {},
}
impl RobotCommand {
pub async fn execute(&self) -> Result<(), OpenrrAppsError> {
if let Some(config_path) = &self.config_path {
let config = RobotConfig::try_new(config_path)?;
let client = RobotClient::try_new(config)?;
self.execute_sub_command(&client, &self).await
} else {
return Err(OpenrrAppsError::NoConfigPath);
}
}
#[async_recursion]
pub async fn execute_sub_command(
&self,
client: &RobotClient,
command: &RobotCommand,
) -> Result<(), OpenrrAppsError> {
match &command.sub_command {
RobotSubCommand::Joints {
name,
duration,
use_interpolation,
joint,
} => {
let mut positions = client.current_joint_positions(name).await?;
let mut should_send = false;
for (index, position) in joint {
if *index < positions.len() {
should_send = true;
positions[*index] = *position;
}
}
if !should_send {
return Ok(());
}
if *use_interpolation {
client
.send_joint_positions_with_pose_interpolation(name, &positions, *duration)
.await?;
} else {
client
.send_joint_positions(name, &positions, *duration)
.await?;
}
}
RobotSubCommand::Ik {
name,
x,
y,
z,
yaw,
pitch,
roll,
duration,
use_interpolation,
is_local,
} => {
if !client.is_ik_client(name) {
return Err(OpenrrAppsError::NoIkClient(name.clone()));
}
let mut should_send = false;
let current_pose = client.current_end_transform(name).await?;
let target_pose = [
if let Some(x) = x {
should_send = true;
*x
} else if *is_local {
0.0
} else {
current_pose.translation.x
},
if let Some(y) = y {
should_send = true;
*y
} else if *is_local {
0.0
} else {
current_pose.translation.y
},
if let Some(z) = z {
should_send = true;
*z
} else if *is_local {
0.0
} else {
current_pose.translation.z
},
if let Some(roll) = roll {
should_send = true;
*roll
} else if *is_local {
0.0
} else {
current_pose.rotation.euler_angles().0
},
if let Some(pitch) = pitch {
should_send = true;
*pitch
} else if *is_local {
0.0
} else {
current_pose.rotation.euler_angles().1
},
if let Some(yaw) = yaw {
should_send = true;
*yaw
} else if *is_local {
0.0
} else {
current_pose.rotation.euler_angles().2
},
];
if !should_send {
return Ok(());
}
let target_pose = isometry(
target_pose[0],
target_pose[1],
target_pose[2],
target_pose[3],
target_pose[4],
target_pose[5],
);
let target_pose = if *is_local {
client.transform(name, &target_pose).await?
} else {
target_pose
};
if *use_interpolation {
client
.move_ik_with_interpolation(name, &target_pose, *duration)
.await?
} else {
client.move_ik(name, &target_pose, *duration).await?
}
}
RobotSubCommand::Get { name } => {
info!(
"Joint positions : {:?}",
client.current_joint_positions(name).await?
);
if client.is_ik_client(name) {
let pose = client.current_end_transform(name).await?;
info!("End pose");
info!(" translation = {:?}", pose.translation.vector.data);
info!(" rotation = {:?}", pose.rotation.euler_angles());
}
}
RobotSubCommand::Load { command_file_path } => {
for command in load_command_file_and_filter(command_file_path.clone())? {
let command_parsed_iter = command.split_whitespace();
// Parse the command
let read_opt = RobotCommand::from_iter(command_parsed_iter);
// Execute the parsed command
info!("Executing {}", command);
self.execute_sub_command(&client, &read_opt).await?;
}
}
RobotSubCommand::List {} => {
client.list_clients();
}
}
Ok(())
}
}
pub fn load_command_file_and_filter(file_path: PathBuf) -> Result<Vec<String>, OpenrrAppsError> {
let file = File::open(&file_path)
.map_err(|e| OpenrrAppsError::CommandFileOpenFailure(file_path, e.to_string()))?;
let buf = BufReader::new(file);
Ok(buf
.lines()
.map(|line| line.expect("Could not parse line"))
.filter(|command| {
let command_parsed_iter = command.split_whitespace();
// Ignore empty lines and comment lines
command_parsed_iter.clone().count() > 0
&& command_parsed_iter.clone().next().unwrap().find('#') == None
})
.collect())
}
|
use super::JniMemory;
use crate::errors::{self, Result};
use crate::interop;
use crate::store::StoreData;
use jni::objects::{JClass, JObject};
use jni::sys::{jint, jlong, jobject};
use jni::JNIEnv;
use wasmtime::{Limits, Memory, MemoryType, Store};
pub(super) struct JniMemoryImpl;
impl<'a> JniMemory<'a> for JniMemoryImpl {
type Error = errors::Error;
fn dispose(env: &JNIEnv, this: JObject) -> Result<(), Self::Error> {
interop::dispose_inner::<Memory>(&env, this)?;
Ok(())
}
fn native_buffer(
env: &JNIEnv,
this: JObject,
store_ptr: jlong,
) -> Result<jobject, Self::Error> {
let mut store = interop::ref_from_raw::<Store<StoreData>>(store_ptr)?;
let mem = interop::get_inner::<Memory>(&env, this)?;
let ptr = mem.data_mut(&mut *store);
Ok(env.new_direct_byte_buffer(ptr)?.into_inner())
}
fn native_data_size(
env: &JNIEnv,
this: JObject,
store_ptr: jlong,
) -> Result<jlong, Self::Error> {
let mut store = interop::ref_from_raw::<Store<StoreData>>(store_ptr)?;
let mem = interop::get_inner::<Memory>(&env, this)?;
Ok(mem.data_size(&mut *store) as jlong)
}
fn new_memory(
_env: &JNIEnv,
_clazz: JClass,
store_ptr: jlong,
min: jint,
max: jint,
) -> Result<jlong, Self::Error> {
let mut store = interop::ref_from_raw::<Store<StoreData>>(store_ptr)?;
let ty = MemoryType::new(Limits::new(
min as u32,
if max < 0 { None } else { Some(max as u32) },
));
let mem = Memory::new(&mut *store, ty)?;
Ok(interop::into_raw::<Memory>(mem))
}
fn native_size(env: &JNIEnv, this: JObject, store_ptr: jlong) -> Result<jint, Self::Error> {
let mut store = interop::ref_from_raw::<Store<StoreData>>(store_ptr)?;
let mem = interop::get_inner::<Memory>(&env, this)?;
Ok(mem.size(&mut *store) as jint)
}
fn native_grow(
env: &JNIEnv,
this: JObject,
store_ptr: jlong,
delta_pages: jint,
) -> Result<jint, Self::Error> {
let mut store = interop::ref_from_raw::<Store<StoreData>>(store_ptr)?;
let mem = interop::get_inner::<Memory>(&env, this)?;
Ok(mem.grow(&mut *store, delta_pages as u32)? as jint)
}
}
|
mod imp;
use gtk4::prelude::*;
use gtk4::subclass::prelude::*;
use gtk4::{gdk, glib};
use std::cell::RefCell;
glib::wrapper! {
pub struct Canvas(ObjectSubclass<imp::Canvas>) @implements gdk::Paintable;
}
impl Default for Canvas {
fn default() -> Self {
Self::new()
}
}
impl Canvas {
pub fn new() -> Self {
glib::Object::new(&[]).expect("Failed to create a Canvas")
}
// Changes cursor location
pub async fn change(&self, x: f64, y: f64) {
let canvas = imp::Canvas::from_instance(self);
// creates lines if is_drawing is true
if canvas.is_drawing.get() {
let l = canvas.lines.borrow_mut();
match l.last() {
Some(p) => {
p.borrow_mut().push(imp::point {
x: canvas.x.get() - canvas.offset_x.get(),
y: canvas.y.get() - canvas.offset_y.get(),
zoom_x: canvas.x.get() - canvas.offset_x.get(),
zoom_y: canvas.y.get() - canvas.offset_y.get(),
size: 3.0,
});
}
None => (),
}
}
// offsets lines if is_offsetting is true
if canvas.is_offsetting.get() {
canvas
.offset_x
.set(x - (canvas.x.get() - canvas.offset_x.get()));
canvas
.offset_y
.set(y - (canvas.y.get() - canvas.offset_y.get()));
}
canvas.x.set(x);
canvas.y.set(y);
self.invalidate_contents();
}
// zoom functions
pub async fn zoom(&self, delta: f64) {
let canvas = imp::Canvas::from_instance(self);
canvas.zoom_x.set(imp::Canvasimpl::zoom(
canvas,
canvas.zoom_x.get(),
canvas.x.get(),
));
canvas.zoom_y.set(imp::Canvasimpl::zoom(
canvas,
canvas.zoom_y.get(),
canvas.y.get(),
));
canvas.zoom.set(delta);
for line in canvas.lines.borrow_mut().iter() {
let mut l = line.borrow_mut();
for point in 0..l.len() {
l[point] = imp::point {
x: l[point].x,
y: l[point].y,
zoom_x: imp::Canvasimpl::zoom(
canvas,
l[point].zoom_x,
canvas.x.get() - canvas.offset_x.get(),
),
zoom_y: imp::Canvasimpl::zoom(
canvas,
l[point].zoom_y,
canvas.y.get() - canvas.offset_y.get(),
),
size: l[point].size * (1.0 - delta),
}
}
}
self.invalidate_contents();
}
//offset manager functions (how points are translated on the canvas)
pub fn start_offset(&self) {
let canvas = imp::Canvas::from_instance(self);
if !canvas.is_offsetting.get() {
canvas.is_offsetting.set(true);
} else {
canvas.is_offsetting.set(false);
}
}
pub fn end_offset(&self) {
let canvas = imp::Canvas::from_instance(self);
canvas.is_offsetting.set(false);
}
// line manager functions
pub fn start_line(&self, x: f64, y: f64) {
let canvas = imp::Canvas::from_instance(self);
canvas.is_drawing.set(true);
let mut l = canvas.lines.borrow_mut();
let r = RefCell::new(vec![imp::point {
x: canvas.x.get() - canvas.offset_x.get(),
y: canvas.y.get() - canvas.offset_y.get(),
zoom_x: canvas.x.get() - canvas.offset_x.get(),
zoom_y: canvas.y.get() - canvas.offset_y.get(),
size: 3.0,
}]);
l.push(r);
self.invalidate_contents();
}
pub fn end_line(&self, x: f64, y: f64) {
let canvas = imp::Canvas::from_instance(self);
canvas.is_drawing.set(false);
self.invalidate_contents();
}
}
|
use mav::{ChainType, NetType};
use mav::ma::{Dao, MSetting, SettingType};
use crate::{ContextTrait, WalletError};
use crate::deref_type;
#[derive(Debug, Default)]
pub struct Setting {
pub m: MSetting,
}
deref_type!(Setting,MSetting);
impl Setting {
/// 返回当前的wallet and chain,如果没有数据返回None
pub async fn current_wallet_chain(context: &dyn ContextTrait) -> Result<Option<(String, ChainType)>, WalletError> {
let wallet_setting = Setting::get_setting(context, &SettingType::CurrentWallet).await?;
let chain_setting = Setting::get_setting(context, &SettingType::CurrentChain).await?;
match (wallet_setting, chain_setting) {
(Some(w), Some(c)) => {
let chain = ChainType::from(c.value_str.as_str())?;
Ok(Some((w.value_str, chain)))
}
_ => {
Ok(None)
}
}
}
pub async fn current_net_type(context: &dyn ContextTrait) -> Result<String, WalletError> {
let net_type_setting = Setting::get_setting(context, &SettingType::CurrentNetType).await?;
match net_type_setting{
Some(item)=>Ok(item.value_str),
None=>Ok(NetType::Main.to_string()),
}
// net_type_setting.map(|item| item.value_str ).ok_or(WalletError::NotExist)
}
pub async fn change_net_type(context: &dyn ContextTrait,net_type:&NetType) -> Result<u64, WalletError> {
let rb = context.db().wallets_db();
let mut wallet_setting = Setting::get_setting(context, &SettingType::CurrentNetType).await?.unwrap_or_default();
wallet_setting.key_str = SettingType::CurrentNetType.to_string();
wallet_setting.value_str = net_type.to_string();
wallet_setting.save_update(rb, "").await.map(|ret|ret.rows_affected).map_err(|err|WalletError::RbatisError(err))
}
/// save 当前的wallet and chain
pub async fn save_current_wallet_chain(context: &dyn ContextTrait, wallet_id: &str, chain_type: &ChainType) -> Result<(), WalletError> {
let rb = context.db().wallets_db();
let mut wallet_setting = Setting::get_setting(context, &SettingType::CurrentWallet).await?.unwrap_or_default();
let mut chain_setting = Setting::get_setting(context, &SettingType::CurrentChain).await?.unwrap_or_default();
//tx 只处理异常情况下,事务的rollback,所以会在事务提交成功后,调用 tx.manager = None; 阻止 [rbatis::tx::TxGuard]再管理事务
let mut tx = rb.begin_tx_defer(false).await?;
wallet_setting.key_str = SettingType::CurrentWallet.to_string();
wallet_setting.value_str = wallet_id.to_owned();
wallet_setting.save_update(rb, &tx.tx_id).await?;
chain_setting.value_str = chain_type.to_string();
chain_setting.key_str = SettingType::CurrentChain.to_string();
chain_setting.save_update(rb, &tx.tx_id).await?;
rb.commit(&tx.tx_id).await?;
tx.manager = None;
Ok(())
}
pub async fn save_current_database_version(context: &dyn ContextTrait, version_value: &str, )->Result<(),WalletError>{
let rb = context.db().wallets_db();
let mut wallet_setting = Setting::get_setting(context, &SettingType::CurrentDbVersion).await?.unwrap_or_default();
wallet_setting.key_str=SettingType::CurrentDbVersion.to_string();
wallet_setting.value_str=version_value.to_string();
wallet_setting.save_update(rb, "").await?;
Ok(())
}
///如果没有找到返回 none
pub async fn get_setting(context: &dyn ContextTrait, key: &SettingType) -> Result<Option<MSetting>, WalletError> {
let rb = context.db().wallets_db();
let wrapper = rb.new_wrapper().eq(MSetting::key_str, key.to_string());
let r = MSetting::fetch_by_wrapper(rb, "", &wrapper).await?;
Ok(r)
}
}
#[cfg(test)]
mod tests {
use futures::executor::block_on;
use rbatis::crud::CRUDTable;
use mav::ChainType;
use mav::ma::{Dao, Db, DbCreateType, MSetting, SettingType};
use crate::{ContextTrait, Setting};
#[test]
fn setting_test() {
let context = init_table();
let re = block_on(Setting::current_wallet_chain(context.as_ref()));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = re.unwrap();
assert_eq!(true, re.is_none(), "{:?}", re);
let wallet_id = "test".to_owned();
let chain_type = ChainType::EEE;
let rb = context.db().wallets_db();
{//save current wallet
let mut m = MSetting::default();
m.key_str = SettingType::CurrentWallet.to_string();
m.value_str = wallet_id.clone();
let re = block_on(m.save(rb, ""));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = block_on(Setting::current_wallet_chain(context.as_ref()));
assert_eq!(false, re.is_err(), "{:?}", re);
let err = re.unwrap();
assert_eq!(true, err.is_none(), "{:?}", err);
}
{//save current chain
let mut m = MSetting::default();
m.key_str = SettingType::CurrentChain.to_string();
m.value_str = chain_type.to_string();
let re = block_on(m.save(rb, ""));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = block_on(Setting::current_wallet_chain(context.as_ref()));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = re.unwrap();
assert_eq!(false, re.is_none(), "{:?}", re);
let re = re.unwrap();
assert_eq!((wallet_id.clone(), chain_type.clone()), re);
}
{
let context = init_table();
let re = block_on(Setting::current_wallet_chain(context.as_ref()));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = re.unwrap();
assert_eq!(true, re.is_none(), "{:?}", re);
let re = block_on(Setting::save_current_wallet_chain(context.as_ref(), &wallet_id, &chain_type));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = block_on(Setting::current_wallet_chain(context.as_ref()));
assert_eq!(false, re.is_err(), "{:?}", re);
let re = re.unwrap();
assert_eq!(false, re.is_none(), "{:?}", re);
let re = re.unwrap();
assert_eq!((wallet_id.clone(), chain_type.clone()), re);
}
}
fn init_table() -> Box<dyn ContextTrait> {
let context = crate::tests::mock_memory_context();
let rb = context.db().wallets_db();
let re = block_on(Db::create_table(rb, MSetting::create_table_script(), &MSetting::table_name(), &DbCreateType::Drop));
assert_eq!(false, re.is_err(), "{:?}", re);
context
}
}
|
use serde::de::DeserializeOwned;
use super::contract::Contract;
use crate::eos;
use crate::eosio_cdt_bindings;
pub trait Action: DeserializeOwned {
const NAME: eos::Name;
fn execute(self, contract: &Contract);
}
pub fn execute_action<T: Action>(contract: &mut Contract) {
let byte_size = unsafe { eosio_cdt_bindings::action_data_size() };
let mut bytes: Vec<u8> = vec![0; byte_size as usize];
let buffer = bytes.as_mut_ptr().cast();
unsafe { eosio_cdt_bindings::read_action_data(buffer, byte_size) };
let action_instance: T = bincode::deserialize(&bytes[..]).expect("fail to decode action data");
contract.set_data_stream(bytes);
action_instance.execute(contract);
}
|
use specs::prelude::*;
|
// Our first program will print the classic “hello world” message.
// Here’s the full source code.
fn main() {
println!("Hello, world!");
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use common_arrow::arrow_format::flight::data::BasicAuth;
use common_base::base::tokio::select;
use common_base::base::tokio::sync::mpsc;
use common_base::base::tokio::sync::mpsc::Receiver;
use common_base::base::tokio::sync::mpsc::Sender;
use common_base::base::tokio::sync::oneshot;
use common_base::base::tokio::sync::oneshot::Receiver as OneRecv;
use common_base::base::tokio::sync::oneshot::Sender as OneSend;
use common_base::base::tokio::sync::RwLock;
use common_base::base::tokio::time::sleep;
use common_base::containers::ItemManager;
use common_base::containers::Pool;
use common_base::containers::TtlHashMap;
use common_base::runtime::Runtime;
use common_base::runtime::TrySpawn;
use common_base::runtime::UnlimitedFuture;
use common_grpc::ConnectionFactory;
use common_grpc::GrpcConnectionError;
use common_grpc::RpcClientConf;
use common_grpc::RpcClientTlsConfig;
use common_meta_api::reply::reply_to_api_result;
use common_meta_types::anyerror::AnyError;
use common_meta_types::protobuf::meta_service_client::MetaServiceClient;
use common_meta_types::protobuf::ClientInfo;
use common_meta_types::protobuf::Empty;
use common_meta_types::protobuf::ExportedChunk;
use common_meta_types::protobuf::HandshakeRequest;
use common_meta_types::protobuf::MemberListReply;
use common_meta_types::protobuf::MemberListRequest;
use common_meta_types::protobuf::RaftReply;
use common_meta_types::protobuf::RaftRequest;
use common_meta_types::protobuf::WatchRequest;
use common_meta_types::protobuf::WatchResponse;
use common_meta_types::ConnectionError;
use common_meta_types::InvalidArgument;
use common_meta_types::MetaClientError;
use common_meta_types::MetaError;
use common_meta_types::MetaHandshakeError;
use common_meta_types::MetaNetworkError;
use common_meta_types::TxnReply;
use common_meta_types::TxnRequest;
use common_metrics::label_counter_with_val_and_labels;
use common_metrics::label_decrement_gauge_with_val_and_labels;
use common_metrics::label_histogram_with_val;
use common_metrics::label_increment_gauge_with_val_and_labels;
use futures::stream::StreamExt;
use parking_lot::Mutex;
use prost::Message;
use semver::Version;
use serde::de::DeserializeOwned;
use tonic::async_trait;
use tonic::client::GrpcService;
use tonic::codegen::InterceptedService;
use tonic::metadata::MetadataValue;
use tonic::service::Interceptor;
use tonic::transport::Channel;
use tonic::Code;
use tonic::Request;
use tonic::Status;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing::warn;
use crate::from_digit_ver;
use crate::grpc_action::RequestFor;
use crate::message;
use crate::to_digit_ver;
use crate::MetaGrpcReq;
use crate::METACLI_COMMIT_SEMVER;
use crate::MIN_METASRV_SEMVER;
const AUTH_TOKEN_KEY: &str = "auth-token-bin";
const META_GRPC_CLIENT_REQUEST_DURATION_MS: &str = "meta_grpc_client_request_duration_ms";
const META_GRPC_CLIENT_REQUEST_INFLIGHT: &str = "meta_grpc_client_request_inflight";
const META_GRPC_CLIENT_REQUEST_SUCCESS: &str = "meta_grpc_client_request_success";
const META_GRPC_CLIENT_REQUEST_FAILED: &str = "meta_grpc_client_request_fail";
const META_GRPC_MAKE_CLIENT_FAILED: &str = "meta_grpc_make_client_fail";
const LABEL_ENDPOINT: &str = "endpoint";
const LABEL_REQUEST: &str = "request";
const LABEL_ERROR: &str = "error";
#[derive(Debug)]
struct MetaChannelManager {
timeout: Option<Duration>,
conf: Option<RpcClientTlsConfig>,
}
impl MetaChannelManager {
async fn build_channel(&self, addr: &String) -> Result<Channel, MetaNetworkError> {
let ch = ConnectionFactory::create_rpc_channel(addr, self.timeout, self.conf.clone())
.await
.map_err(|e| match e {
GrpcConnectionError::InvalidUri { .. } => MetaNetworkError::BadAddressFormat(
AnyError::new(&e).add_context(|| "while creating rpc channel"),
),
GrpcConnectionError::TLSConfigError { .. } => MetaNetworkError::TLSConfigError(
AnyError::new(&e).add_context(|| "while creating rpc channel"),
),
GrpcConnectionError::CannotConnect { .. } => MetaNetworkError::ConnectionError(
ConnectionError::new(e, "while creating rpc channel"),
),
})?;
Ok(ch)
}
}
#[async_trait]
impl ItemManager for MetaChannelManager {
type Key = String;
type Item = Channel;
type Error = MetaNetworkError;
#[tracing::instrument(level = "debug", err(Debug))]
async fn build(&self, addr: &Self::Key) -> Result<Self::Item, Self::Error> {
self.build_channel(addr).await
}
#[tracing::instrument(level = "debug", err(Debug))]
async fn check(&self, mut ch: Self::Item) -> Result<Self::Item, Self::Error> {
futures::future::poll_fn(|cx| ch.poll_ready(cx))
.await
.map_err(|e| {
MetaNetworkError::ConnectionError(ConnectionError::new(e, "while check item"))
})?;
Ok(ch)
}
}
/// A handle to access meta-client worker.
/// The worker will be actually running in a dedicated runtime: `MetaGrpcClient.rt`.
pub struct ClientHandle {
/// For sending request to meta-client worker.
pub(crate) req_tx: Sender<message::ClientWorkerRequest>,
/// Notify auto sync to stop.
/// `oneshot::Receiver` impl `Drop` by sending a closed notification to the `Sender` half.
#[allow(dead_code)]
cancel_auto_sync_rx: OneRecv<()>,
}
impl ClientHandle {
/// Send a request to the internal worker task, which may be running in another runtime.
pub async fn request<Req, Resp, E>(&self, req: Req) -> Result<Resp, E>
where
Req: RequestFor<Reply = Resp>,
Req: Into<message::Request>,
Result<Resp, E>: TryFrom<message::Response>,
<Result<Resp, E> as TryFrom<message::Response>>::Error: std::fmt::Display,
E: From<MetaClientError>,
{
let request_future = async move {
let (tx, rx) = oneshot::channel();
let req = message::ClientWorkerRequest {
resp_tx: tx,
req: req.into(),
};
label_increment_gauge_with_val_and_labels(
META_GRPC_CLIENT_REQUEST_INFLIGHT,
&vec![],
1.0,
);
let res = self.req_tx.send(req).await.map_err(|e| {
let cli_err = MetaClientError::ClientRuntimeError(
AnyError::new(&e).add_context(|| "when sending req to MetaGrpcClient worker"),
);
cli_err.into()
});
if let Err(err) = res {
label_decrement_gauge_with_val_and_labels(
META_GRPC_CLIENT_REQUEST_INFLIGHT,
&vec![],
1.0,
);
return Err(err);
}
let res = rx.await.map_err(|e| {
label_decrement_gauge_with_val_and_labels(
META_GRPC_CLIENT_REQUEST_INFLIGHT,
&vec![],
1.0,
);
MetaClientError::ClientRuntimeError(
AnyError::new(&e).add_context(|| "when recv resp from MetaGrpcClient worker"),
)
})?;
label_decrement_gauge_with_val_and_labels(
META_GRPC_CLIENT_REQUEST_INFLIGHT,
&vec![],
1.0,
);
let res: Result<Resp, E> = res
.try_into()
.map_err(|e| format!("expect: {}, got: {}", std::any::type_name::<Resp>(), e))
.unwrap();
res
};
UnlimitedFuture::create(request_future).await
}
pub async fn get_client_info(&self) -> Result<ClientInfo, MetaError> {
self.request(message::GetClientInfo {}).await
}
pub async fn make_client(
&self,
) -> Result<MetaServiceClient<InterceptedService<Channel, AuthInterceptor>>, MetaClientError>
{
self.request(message::MakeClient {}).await
}
/// Return the endpoints list cached on this client.
pub async fn get_cached_endpoints(&self) -> Result<Vec<String>, MetaError> {
self.request(message::GetEndpoints {}).await
}
}
// TODO: maybe it just needs a runtime, not a MetaGrpcClientWorker.
//
/// Meta grpc client has a internal worker task that deals with all traffic to remote meta service.
///
/// We expect meta-client should be cloneable.
/// But the underlying hyper client has a worker that runs in its creating tokio-runtime.
/// Thus a cloned meta client may try to talk to a destroyed hyper worker if the creating tokio-runtime is dropped.
/// Thus we have to guarantee that as long as there is a meta-client, the huper worker runtime must not be dropped.
/// Thus a meta client creates a runtime then spawn a MetaGrpcClientWorker.
pub struct MetaGrpcClient {
conn_pool: Pool<MetaChannelManager>,
endpoints: RwLock<Vec<String>>,
username: String,
password: String,
current_endpoint: Arc<Mutex<Option<String>>>,
unhealthy_endpoints: Mutex<TtlHashMap<String, ()>>,
auto_sync_interval: Option<Duration>,
/// Dedicated runtime to support meta client background tasks.
///
/// In order not to let a blocking operation(such as calling the new PipelinePullingExecutor) in a tokio runtime block meta-client background tasks.
/// If a background task is blocked, no meta-client will be able to proceed if meta-client is reused.
///
/// Note that a thread_pool tokio runtime does not help: a scheduled tokio-task resides in `filo_slot` won't be stolen by other tokio-workers.
#[allow(dead_code)]
rt: Arc<Runtime>,
}
impl Debug for MetaGrpcClient {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut de = f.debug_struct("MetaGrpcClient");
de.field("endpoints", &self.endpoints);
de.field("current_endpoints", &self.current_endpoint);
de.field("unhealthy_endpoints", &self.unhealthy_endpoints);
de.field("auto_sync_interval", &self.auto_sync_interval);
de.finish()
}
}
impl MetaGrpcClient {
/// Create a new client of metasrv.
///
/// It creates a new `Runtime` and spawn a background worker task in it that do all the RPC job.
/// A client-handle is returned to communicate with the worker.
///
/// Thus the real work is done in the dedicated runtime to avoid the client spawning tasks in the caller's runtime, which potentially leads to a deadlock if the caller has blocking calls to other components
/// Because `tower` and `hyper` will spawn tasks when handling RPCs.
///
/// The worker is a singleton and the returned handle is cheap to clone.
/// When all handles are dropped the worker will quit, then the runtime will be destroyed.
pub fn try_new(conf: &RpcClientConf) -> Result<Arc<ClientHandle>, MetaClientError> {
Self::try_create(
conf.get_endpoints(),
&conf.username,
&conf.password,
conf.timeout,
conf.auto_sync_interval,
conf.tls_conf.clone(),
)
}
#[tracing::instrument(level = "debug", skip(password))]
pub fn try_create(
endpoints: Vec<String>,
username: &str,
password: &str,
timeout: Option<Duration>,
auto_sync_interval: Option<Duration>,
conf: Option<RpcClientTlsConfig>,
) -> Result<Arc<ClientHandle>, MetaClientError> {
Self::endpoints_non_empty(&endpoints)?;
let mgr = MetaChannelManager { timeout, conf };
let rt =
Runtime::with_worker_threads(1, Some("meta-client-rt".to_string())).map_err(|e| {
MetaClientError::ClientRuntimeError(
AnyError::new(&e).add_context(|| "when creating meta-client"),
)
})?;
let rt = Arc::new(rt);
// Build the handle-worker pair
let (tx, rx) = mpsc::channel(256);
let (one_tx, one_rx) = oneshot::channel::<()>();
let handle = Arc::new(ClientHandle {
req_tx: tx,
cancel_auto_sync_rx: one_rx,
});
let worker = Arc::new(Self {
conn_pool: Pool::new(mgr, Duration::from_millis(50)),
endpoints: RwLock::new(endpoints),
current_endpoint: Arc::new(Mutex::new(None)),
unhealthy_endpoints: Mutex::new(TtlHashMap::new(Duration::from_secs(120))),
auto_sync_interval,
username: username.to_string(),
password: password.to_string(),
rt: rt.clone(),
});
rt.spawn(UnlimitedFuture::create(Self::worker_loop(
worker.clone(),
rx,
)));
rt.spawn(UnlimitedFuture::create(Self::auto_sync_endpoints(
worker, one_tx,
)));
Ok(handle)
}
/// A worker runs a receiving-loop to accept user-request to metasrv and deals with request in the dedicated runtime.
#[tracing::instrument(level = "info", skip_all)]
async fn worker_loop(self: Arc<Self>, mut req_rx: Receiver<message::ClientWorkerRequest>) {
info!("MetaGrpcClient::worker spawned");
loop {
let t = req_rx.recv().await;
let req = match t {
None => {
info!("MetaGrpcClient handle closed. worker quit");
return;
}
Some(x) => x,
};
debug!(req = debug(&req), "MetaGrpcClient recv request");
if req.resp_tx.is_closed() {
debug!(
req = debug(&req),
"MetaGrpcClient request.resp_tx is closed, cancel handling this request"
);
continue;
}
let resp_tx = req.resp_tx;
let req = req.req;
let req_name = req.name();
let req_str = format!("{:?}", req);
let start = Instant::now();
let resp = match req {
message::Request::Get(r) => {
let resp = self.kv_api(r).await;
message::Response::Get(resp)
}
message::Request::MGet(r) => {
let resp = self.kv_api(r).await;
message::Response::MGet(resp)
}
message::Request::PrefixList(r) => {
let resp = self.kv_api(r).await;
message::Response::PrefixList(resp)
}
message::Request::Upsert(r) => {
let resp = self.kv_api(r).await;
message::Response::Upsert(resp)
}
message::Request::Txn(r) => {
let resp = self.transaction(r).await;
message::Response::Txn(resp)
}
message::Request::Watch(r) => {
let resp = self.watch(r).await;
message::Response::Watch(resp)
}
message::Request::Export(r) => {
let resp = self.export(r).await;
message::Response::Export(resp)
}
message::Request::MakeClient(_) => {
let resp = self.make_client().await;
message::Response::MakeClient(resp)
}
message::Request::GetEndpoints(_) => {
let resp = self.get_cached_endpoints().await;
message::Response::GetEndpoints(Ok(resp))
}
message::Request::GetClientInfo(_) => {
let resp = self.get_client_info().await;
message::Response::GetClientInfo(resp)
}
};
debug!(
resp = debug(&resp),
"MetaGrpcClient send response to the handle"
);
let current_endpoint = {
let current_endpoint = self.current_endpoint.lock();
current_endpoint.clone()
};
if let Some(current_endpoint) = current_endpoint {
let elapsed = start.elapsed().as_millis() as f64;
label_histogram_with_val(
META_GRPC_CLIENT_REQUEST_DURATION_MS,
&vec![
(LABEL_ENDPOINT, current_endpoint.to_string()),
(LABEL_REQUEST, req_name.to_string()),
],
elapsed,
);
if elapsed > 1000_f64 {
warn!(
"MetaGrpcClient slow request {} to {} takes {} ms: {}",
req_name, current_endpoint, elapsed, req_str,
);
}
if let Some(err) = resp.err() {
label_counter_with_val_and_labels(
META_GRPC_CLIENT_REQUEST_FAILED,
&vec![
(LABEL_ENDPOINT, current_endpoint.to_string()),
(LABEL_ERROR, err.to_string()),
(LABEL_REQUEST, req_name.to_string()),
],
1,
);
error!("MetaGrpcClient error: {:?}", err);
} else {
label_counter_with_val_and_labels(
META_GRPC_CLIENT_REQUEST_SUCCESS,
&vec![
(LABEL_ENDPOINT, current_endpoint.to_string()),
(LABEL_REQUEST, req_name.to_string()),
],
1,
);
}
}
let send_res = resp_tx.send(resp);
if let Err(err) = send_res {
error!(
err = debug(err),
"MetaGrpcClient failed to send response to the handle. recv-end closed"
);
}
}
}
#[tracing::instrument(level = "debug", skip(self))]
pub async fn make_client(
&self,
) -> Result<MetaServiceClient<InterceptedService<Channel, AuthInterceptor>>, MetaClientError>
{
let mut eps = self.get_cached_endpoints().await;
debug!("service endpoints: {:?}", eps);
debug_assert!(!eps.is_empty());
if eps.len() > 1 {
// remove unhealthy endpoints
let ues = self.unhealthy_endpoints.lock();
eps.retain(|e| !ues.contains_key(e));
}
for (addr, is_last) in eps.iter().enumerate().map(|(i, a)| (a, i == eps.len() - 1)) {
let channel = self.make_channel(Some(addr)).await;
match channel {
Ok(c) => {
let mut client = MetaServiceClient::new(c.clone());
let new_token = Self::handshake(
&mut client,
&METACLI_COMMIT_SEMVER,
&MIN_METASRV_SEMVER,
&self.username,
&self.password,
)
.await;
match new_token {
Ok(token) => {
return Ok(MetaServiceClient::with_interceptor(c, AuthInterceptor {
token,
}));
}
Err(handshake_err) => {
warn!("handshake error when make client: {:?}", handshake_err);
{
let mut ue = self.unhealthy_endpoints.lock();
ue.insert(addr.to_string(), ());
}
if is_last {
// reach to last addr
let cli_err = MetaClientError::HandshakeError(handshake_err);
return Err(cli_err);
}
continue;
}
};
}
Err(net_err) => {
{
let mut ue = self.unhealthy_endpoints.lock();
ue.insert(addr.to_string(), ());
}
if is_last {
let cli_err = MetaClientError::NetworkError(net_err);
return Err(cli_err);
}
continue;
}
}
}
Err(MetaClientError::ConfigError(AnyError::error(
"endpoints is empty",
)))
}
#[tracing::instrument(level = "debug", skip(self), err(Debug))]
async fn make_channel(&self, addr: Option<&String>) -> Result<Channel, MetaNetworkError> {
let addr = if let Some(addr) = addr {
addr.clone()
} else {
let eps = self.endpoints.read().await;
eps.first().unwrap().clone()
};
let ch = self.conn_pool.get(&addr).await;
{
let mut current_endpoint = self.current_endpoint.lock();
*current_endpoint = Some(addr.clone());
}
match ch {
Ok(c) => Ok(c),
Err(e) => {
warn!(
"grpc_client create channel with {} failed, err: {:?}",
addr, e
);
label_counter_with_val_and_labels(
META_GRPC_MAKE_CLIENT_FAILED,
&vec![(LABEL_ENDPOINT, addr.to_string())],
1,
);
Err(e)
}
}
}
pub fn endpoints_non_empty(endpoints: &[String]) -> Result<(), MetaClientError> {
if endpoints.is_empty() {
return Err(MetaClientError::ConfigError(AnyError::error(
"endpoints is empty",
)));
}
Ok(())
}
async fn get_cached_endpoints(&self) -> Vec<String> {
let eps = self.endpoints.read().await;
(*eps).clone()
}
#[tracing::instrument(level = "debug", skip(self))]
pub async fn set_endpoints(&self, endpoints: Vec<String>) -> Result<(), MetaError> {
Self::endpoints_non_empty(&endpoints)?;
// Older meta nodes may not store endpoint information and need to be filtered out.
let distinct_cnt = endpoints.iter().filter(|n| !(*n).is_empty()).count();
// If the fetched endpoints are less than the majority of the current cluster, no replacement should occur.
if distinct_cnt < endpoints.len() / 2 + 1 {
warn!(
"distinct endpoints small than majority of meta cluster nodes {}<{}, endpoints: {:?}",
distinct_cnt,
endpoints.len(),
endpoints
);
return Ok(());
}
let mut eps = self.endpoints.write().await;
*eps = endpoints;
Ok(())
}
#[tracing::instrument(level = "debug", skip(self))]
pub async fn sync_endpoints(&self) -> Result<(), MetaError> {
let mut client = self.make_client().await?;
let result = client
.member_list(Request::new(MemberListRequest {
data: "".to_string(),
}))
.await;
let endpoints: Result<MemberListReply, Status> = match result {
Ok(r) => Ok(r.into_inner()),
Err(s) => {
if status_is_retryable(&s) {
self.mark_as_unhealthy().await;
let mut client = self.make_client().await?;
let req = Request::new(MemberListRequest {
data: "".to_string(),
});
Ok(client.member_list(req).await?.into_inner())
} else {
Err(s)
}
}
};
let result: Vec<String> = endpoints?.data;
debug!("received meta endpoints: {:?}", result);
self.set_endpoints(result).await?;
Ok(())
}
async fn auto_sync_endpoints(self: Arc<Self>, mut cancel_tx: OneSend<()>) {
info!(
"start auto sync endpoints: interval: {:?}",
self.auto_sync_interval
);
if let Some(interval) = self.auto_sync_interval {
loop {
select! {
_ = cancel_tx.closed() => {
return;
}
_ = sleep(interval) => {
let r = self.sync_endpoints().await;
if let Err(e) = r {
warn!("auto sync endpoints failed: {:?}", e);
}
}
}
}
}
}
/// Handshake with metasrv.
///
/// - Check whether the versions of this client(`C`) and the remote metasrv(`S`) are compatible.
/// - Authorize this client.
///
/// ## Check compatibility
///
/// Both client `C` and server `S` maintains two semantic-version:
/// - `C` maintains the its own semver(`C.ver`) and the minimal compatible `S` semver(`C.min_srv_ver`).
/// - `S` maintains the its own semver(`S.ver`) and the minimal compatible `S` semver(`S.min_cli_ver`).
///
/// When handshaking:
/// - `C` sends its ver `C.ver` to `S`,
/// - When `S` receives handshake request, `S` asserts that `C.ver >= S.min_cli_ver`.
/// - Then `S` replies handshake-reply with its `S.ver`.
/// - When `C` receives the reply, `C` asserts that `S.ver >= C.min_srv_ver`.
///
/// Handshake succeeds if both of these two assertions hold.
///
/// E.g.:
/// - `S: (ver=3, min_cli_ver=1)` is compatible with `C: (ver=3, min_srv_ver=2)`.
/// - `S: (ver=4, min_cli_ver=4)` is **NOT** compatible with `C: (ver=3, min_srv_ver=2)`.
/// Because although `S.ver(4) >= C.min_srv_ver(3)` holds,
/// but `C.ver(3) >= S.min_cli_ver(4)` does not hold.
///
/// ```text
/// C.ver: 1 3 4
/// C --------+-------------+------+------------>
/// ^ .------' ^
/// | | |
/// '-------------. |
/// | | |
/// v | |
/// S ---------------+------+------+------------>
/// S.ver: 2 3 4
/// ```
#[tracing::instrument(level = "debug", skip(client, password, client_ver, min_metasrv_ver))]
pub async fn handshake(
client: &mut MetaServiceClient<Channel>,
client_ver: &Version,
min_metasrv_ver: &Version,
username: &str,
password: &str,
) -> Result<Vec<u8>, MetaHandshakeError> {
debug!(
client_ver = display(client_ver),
min_metasrv_ver = display(min_metasrv_ver),
"client version"
);
let auth = BasicAuth {
username: username.to_string(),
password: password.to_string(),
};
let mut payload = vec![];
auth.encode(&mut payload)
.map_err(|e| MetaHandshakeError::new("encode auth payload", &e))?;
let my_ver = to_digit_ver(client_ver);
let req = Request::new(futures::stream::once(async move {
HandshakeRequest {
protocol_version: my_ver,
payload,
}
}));
let rx = client
.handshake(req)
.await
.map_err(|e| MetaHandshakeError::new("when sending handshake rpc", &e))?;
let mut rx = rx.into_inner();
let res = rx.next().await.ok_or_else(|| {
MetaHandshakeError::new(
"when recv from handshake stream",
&AnyError::error("handshake returns nothing"),
)
})?;
let resp =
res.map_err(|status| MetaHandshakeError::new("handshake is refused", &status))?;
assert!(
resp.protocol_version > 0,
"talking to a very old databend-meta: upgrade databend-meta to at least 0.8"
);
let min_compatible = to_digit_ver(min_metasrv_ver);
if resp.protocol_version < min_compatible {
let invalid_err = AnyError::error(format!(
"metasrv protocol_version({}) < meta-client min-compatible({})",
from_digit_ver(resp.protocol_version),
min_metasrv_ver,
));
return Err(MetaHandshakeError::new(
"incompatible protocol version",
&invalid_err,
));
}
let token = resp.payload;
Ok(token)
}
/// Create a watching stream that receives KV change events.
#[tracing::instrument(level = "debug", skip_all)]
pub(crate) async fn watch(
&self,
watch_request: WatchRequest,
) -> Result<tonic::codec::Streaming<WatchResponse>, MetaError> {
debug!(
watch_request = debug(&watch_request),
"MetaGrpcClient worker: handle watch request"
);
let mut client = self.make_client().await?;
let res = client.watch(watch_request).await?;
Ok(res.into_inner())
}
/// Export all data in json from metasrv.
#[tracing::instrument(level = "debug", skip_all)]
pub(crate) async fn export(
&self,
export_request: message::ExportReq,
) -> Result<tonic::codec::Streaming<ExportedChunk>, MetaError> {
debug!(
export_request = debug(&export_request),
"MetaGrpcClient worker: handle export request"
);
let mut client = self.make_client().await?;
let res = client.export(Empty {}).await?;
Ok(res.into_inner())
}
/// Export all data in json from metasrv.
#[tracing::instrument(level = "debug", skip_all)]
pub(crate) async fn get_client_info(&self) -> Result<ClientInfo, MetaError> {
debug!("MetaGrpcClient::get_client_info");
let mut client = self.make_client().await?;
let res = client.get_client_info(Empty {}).await?;
Ok(res.into_inner())
}
#[tracing::instrument(level = "debug", skip(self, v))]
pub(crate) async fn kv_api<T, R>(&self, v: T) -> Result<R, MetaError>
where
T: RequestFor<Reply = R>,
T: Into<MetaGrpcReq>,
R: DeserializeOwned,
{
let read_req: MetaGrpcReq = v.into();
debug!(req = debug(&read_req), "MetaGrpcClient::kv_api request");
let req: Request<RaftRequest> = read_req.clone().try_into().map_err(|e| {
MetaNetworkError::InvalidArgument(InvalidArgument::new(e, "fail to encode request"))
})?;
debug!(
req = debug(&req),
"MetaGrpcClient::kv_api serialized request"
);
let req = common_tracing::inject_span_to_tonic_request(req);
let mut client = self.make_client().await?;
let result = client.kv_api(req).await;
debug!(reply = debug(&result), "MetaGrpcClient::kv_api reply");
let rpc_res: Result<RaftReply, Status> = match result {
Ok(r) => Ok(r.into_inner()),
Err(s) => {
if status_is_retryable(&s) {
self.mark_as_unhealthy().await;
let mut client = self.make_client().await?;
let req: Request<RaftRequest> = read_req.try_into().map_err(|e| {
MetaNetworkError::InvalidArgument(InvalidArgument::new(
e,
"fail to encode request",
))
})?;
let req = common_tracing::inject_span_to_tonic_request(req);
Ok(client.kv_api(req).await?.into_inner())
} else {
Err(s)
}
}
};
let raft_reply = rpc_res?;
let resp: R = reply_to_api_result(raft_reply)?;
Ok(resp)
}
#[tracing::instrument(level = "debug", skip(self, req))]
pub(crate) async fn transaction(&self, req: TxnRequest) -> Result<TxnReply, MetaError> {
let txn: TxnRequest = req;
debug!(req = display(&txn), "MetaGrpcClient::transaction request");
let req: Request<TxnRequest> = Request::new(txn.clone());
let req = common_tracing::inject_span_to_tonic_request(req);
let mut client = self.make_client().await?;
let result = client.transaction(req).await;
let result: Result<TxnReply, Status> = match result {
Ok(r) => return Ok(r.into_inner()),
Err(s) => {
if status_is_retryable(&s) {
self.mark_as_unhealthy().await;
let mut client = self.make_client().await?;
let req: Request<TxnRequest> = Request::new(txn);
let req = common_tracing::inject_span_to_tonic_request(req);
let ret = client.transaction(req).await?.into_inner();
return Ok(ret);
} else {
Err(s)
}
}
};
let reply = result?;
debug!(reply = display(&reply), "MetaGrpcClient::transaction reply");
Ok(reply)
}
async fn mark_as_unhealthy(&self) {
let ca = self.current_endpoint.lock();
let mut ue = self.unhealthy_endpoints.lock();
ue.insert((*ca).as_ref().unwrap().clone(), ());
}
}
fn status_is_retryable(status: &Status) -> bool {
matches!(
status.code(),
Code::Unauthenticated | Code::Unavailable | Code::Internal
)
}
#[derive(Clone)]
pub struct AuthInterceptor {
pub token: Vec<u8>,
}
impl Interceptor for AuthInterceptor {
fn call(&mut self, mut req: tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> {
let metadata = req.metadata_mut();
metadata.insert_bin(AUTH_TOKEN_KEY, MetadataValue::from_bytes(&self.token));
Ok(req)
}
}
|
use crate::types::*;
use neo4rs_macros::BoltStruct;
#[derive(Debug, PartialEq, Clone, BoltStruct)]
#[signature(0xB1, 0x10)]
pub struct Run {
query: BoltString,
parameters: BoltMap,
extra: BoltMap,
}
impl Run {
pub fn new(db: BoltString, query: BoltString, parameters: BoltMap) -> Run {
Run {
query,
parameters,
extra: vec![("db".into(), BoltType::String(db))]
.into_iter()
.collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::version::Version;
#[test]
fn should_serialize_run() {
let run = Run::new(
"test".into(),
"query".into(),
vec![("k".into(), "v".into())].into_iter().collect(),
);
let bytes: Bytes = run.into_bytes(Version::V4_1).unwrap();
assert_eq!(
bytes,
Bytes::from_static(&[
0xB1,
0x10,
string::TINY | 5,
b'q',
b'u',
b'e',
b'r',
b'y',
map::TINY | 1,
string::TINY | 1,
b'k',
string::TINY | 1,
b'v',
map::TINY | 1,
string::TINY | 2,
b'd',
b'b',
string::TINY | 4,
b't',
b'e',
b's',
b't',
])
);
}
#[test]
fn should_serialize_run_with_no_params() {
let run = Run::new("".into(), "query".into(), BoltMap::default());
let bytes: Bytes = run.into_bytes(Version::V4_1).unwrap();
assert_eq!(
bytes,
Bytes::from_static(&[
0xB1,
0x10,
string::TINY | 5,
b'q',
b'u',
b'e',
b'r',
b'y',
map::TINY | 0,
map::TINY | 1,
string::TINY | 2,
b'd',
b'b',
string::TINY | 0,
])
);
}
}
|
use crate::{
database::Database,
debug_adapter::DebugSessionManager,
features::{LanguageFeatures, Reference, RenameError},
features_candy::{
analyzer::{insights::Hint, HintsNotification},
CandyFeatures, ServerStatusNotification,
},
features_ir::{IrFeatures, UpdateIrNotification},
semantic_tokens,
utils::{module_from_url, module_to_url},
};
use async_trait::async_trait;
use candy_frontend::module::{Module, ModuleKind, PackagesPath};
use lsp_types::{
Diagnostic, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
DocumentFilter, DocumentFormattingParams, DocumentHighlight, DocumentHighlightKind,
DocumentHighlightParams, FoldingRange, FoldingRangeParams, GotoDefinitionParams,
GotoDefinitionResponse, InitializeParams, InitializeResult, InitializedParams, Location,
MessageType, Position, PrepareRenameResponse, ReferenceParams, Registration, RenameOptions,
RenameParams, SemanticTokens, SemanticTokensFullOptions, SemanticTokensOptions,
SemanticTokensParams, SemanticTokensRegistrationOptions, SemanticTokensResult,
SemanticTokensServerCapabilities, ServerCapabilities, ServerInfo, StaticRegistrationOptions,
TextDocumentChangeRegistrationOptions, TextDocumentPositionParams,
TextDocumentRegistrationOptions, TextEdit, Url, WorkDoneProgressOptions, WorkspaceEdit,
};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::mem;
use tokio::sync::{Mutex, RwLock, RwLockMappedWriteGuard, RwLockReadGuard, RwLockWriteGuard};
use tower_lsp::{jsonrpc, Client, ClientSocket, LanguageServer, LspService};
use tracing::{debug, span, Level};
pub struct Server {
pub client: Client,
pub db: Mutex<Database>,
pub state: RwLock<ServerState>,
}
#[derive(Debug)]
pub enum ServerState {
Initial {
features: ServerFeatures,
debug_session_manager: DebugSessionManager,
},
Running(RunningServerState),
Shutdown,
}
#[derive(Debug)]
pub struct RunningServerState {
pub features: ServerFeatures,
pub packages_path: PackagesPath,
pub debug_session_manager: DebugSessionManager,
}
impl ServerState {
pub fn require_features(&self) -> &ServerFeatures {
match self {
ServerState::Initial { features, .. } => features,
ServerState::Running(RunningServerState { features, .. }) => features,
ServerState::Shutdown => panic!("Server is shut down."),
}
}
pub fn require_running(&self) -> &RunningServerState {
match self {
ServerState::Running(state) => state,
_ => panic!("Server is not running."),
}
}
pub fn require_running_mut(&mut self) -> &mut RunningServerState {
match self {
ServerState::Running(state) => state,
_ => panic!("Server is not running."),
}
}
}
#[derive(Debug)]
pub struct ServerFeatures {
pub candy: CandyFeatures,
pub ir: IrFeatures,
}
impl ServerFeatures {
fn all_features<'this, 'a>(&'this self) -> [&'a dyn LanguageFeatures; 2]
where
'this: 'a,
{
[&self.candy, &self.ir]
}
fn selectors_where<F>(&self, mut filter: F) -> Vec<DocumentFilter>
where
F: FnMut(&dyn LanguageFeatures) -> bool,
{
let mut selectors = vec![];
let mut add_selectors_for = move |selectors: &mut Vec<DocumentFilter>, features| {
if !filter(features) {
return;
}
let language_id = features.language_id();
let schemes = features.supported_url_schemes();
assert!(!schemes.is_empty());
selectors.extend(schemes.into_iter().map(|scheme| DocumentFilter {
language: language_id.clone(),
scheme: Some(scheme.to_owned()),
pattern: None,
}))
};
for features in self.all_features() {
add_selectors_for(&mut selectors, features);
}
selectors
}
fn registration_options_where<F>(&self, filter: F) -> TextDocumentRegistrationOptions
where
F: FnMut(&dyn LanguageFeatures) -> bool,
{
TextDocumentRegistrationOptions {
document_selector: Some(self.selectors_where(filter)),
}
}
}
pub struct AnalyzerClient {
client: Client,
packages_path: PackagesPath,
}
impl AnalyzerClient {
pub async fn update_status(&self, status: Option<String>) {
self.client
.send_notification::<ServerStatusNotification>(ServerStatusNotification {
text: match status {
Some(status) => format!("🍭 {status}"),
None => "🍭".to_string(),
},
})
.await;
}
pub async fn update_diagnostics(&self, module: Module, diagnostics: Vec<Diagnostic>) {
self.client
.publish_diagnostics(
module_to_url(&module, &self.packages_path).unwrap(),
diagnostics,
None,
)
.await;
}
pub async fn update_hints(&self, module: Module, hints: Vec<Hint>) {
self.client
.send_notification::<HintsNotification>(HintsNotification {
uri: module_to_url(&module, &self.packages_path).unwrap(),
hints,
})
.await;
}
}
impl Server {
pub fn create(packages_path: PackagesPath) -> (LspService<Self>, ClientSocket) {
let (service, client) = LspService::build(|client| {
let state = ServerState::Initial {
features: ServerFeatures {
candy: CandyFeatures::new(
packages_path.clone(),
AnalyzerClient {
client: client.clone(),
packages_path: packages_path.clone(),
},
),
ir: IrFeatures::default(),
},
debug_session_manager: DebugSessionManager::default(),
};
Self {
client,
db: Mutex::new(Database::new_with_file_system_module_provider(
packages_path,
)),
state: RwLock::new(state),
}
})
.custom_method(
"candy/debugAdapter/create",
Server::candy_debug_adapter_create,
)
.custom_method(
"candy/debugAdapter/message",
Server::candy_debug_adapter_message,
)
.custom_method("candy/viewIr", Server::candy_view_ir)
.finish();
(service, client)
}
pub async fn require_features(&self) -> RwLockReadGuard<ServerFeatures> {
RwLockReadGuard::map(self.state.read().await, ServerState::require_features)
}
pub async fn require_running_state(&self) -> RwLockReadGuard<RunningServerState> {
RwLockReadGuard::map(self.state.read().await, |state| state.require_running())
}
pub async fn require_running_state_mut(&self) -> RwLockMappedWriteGuard<RunningServerState> {
RwLockWriteGuard::map(self.state.write().await, |state| {
state.require_running_mut()
})
}
pub async fn features_from_url<'a>(
&self,
server_features: &'a ServerFeatures,
url: &Url,
) -> &'a dyn LanguageFeatures {
let scheme = url.scheme();
server_features
.all_features()
.into_iter()
.find(|it| it.supported_url_schemes().contains(&scheme))
.unwrap()
}
}
#[async_trait]
impl LanguageServer for Server {
async fn initialize(&self, params: InitializeParams) -> jsonrpc::Result<InitializeResult> {
span!(Level::DEBUG, "LSP: initialize");
self.client
.log_message(MessageType::INFO, "Initializing!")
.await;
{
let state = self.state.read().await;
for features in state.require_features().all_features() {
features.initialize().await;
}
}
let packages_path = {
let options = params
.initialization_options
.as_ref()
.expect("No initialization options provided.")
.as_object()
.unwrap();
match PackagesPath::try_from(options.get("packagesPath").unwrap().as_str().unwrap()) {
Ok(packages_path) => packages_path,
Err(err) => {
let message = format!("Failed to initialize: {}", err);
self.client
.show_message(MessageType::ERROR, message.clone())
.await;
return Err(jsonrpc::Error::invalid_params(message));
}
}
};
{
let mut state = self.state.write().await;
let owned_state = mem::replace(&mut *state, ServerState::Shutdown);
let ServerState::Initial {
features,
debug_session_manager,
} = owned_state
else {
panic!("Server is already initialized.");
};
*state = ServerState::Running(RunningServerState {
features,
packages_path,
debug_session_manager,
});
}
Ok(InitializeResult {
// We only support dynamic registration for now.
capabilities: ServerCapabilities::default(),
server_info: Some(ServerInfo {
name: "🍭 Candy Language Server".to_owned(),
version: None,
}),
})
}
async fn initialized(&self, _: InitializedParams) {
debug!("LSP: initialized");
fn registration(method: &'static str, options: impl Serialize) -> Registration {
Registration {
id: method.to_string(),
method: method.to_string(),
register_options: Some(serde_json::to_value(options).unwrap()),
}
}
let state = self.state.read().await;
let features = state.require_features();
self.client
.register_capability(vec![
registration(
"textDocument/didOpen",
features.registration_options_where(|it| it.supports_did_open()),
),
registration(
"textDocument/didChange",
TextDocumentChangeRegistrationOptions {
document_selector: Some(
features.selectors_where(|it| it.supports_did_change()),
),
sync_kind: 2, // incremental
},
),
registration(
"textDocument/didClose",
features.registration_options_where(|it| it.supports_did_close()),
),
registration(
"textDocument/definition",
features.registration_options_where(|it| it.supports_find_definition()),
),
registration(
"textDocument/references",
features.registration_options_where(|it| it.supports_references()),
),
registration(
"textDocument/documentHighlight",
features.registration_options_where(|it| it.supports_references()),
),
registration(
"textDocument/foldingRange",
features.registration_options_where(|it| it.supports_folding_ranges()),
),
registration(
"textDocument/formatting",
features.registration_options_where(|it| it.supports_format()),
),
registration(
"textDocument/rename",
RenameRegistrationOptions {
text_document_registration_options: features
.registration_options_where(|it| it.supports_rename()),
rename_options: RenameOptions {
prepare_provider: Some(true),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
},
},
),
registration(
"textDocument/semanticTokens",
SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
SemanticTokensRegistrationOptions {
text_document_registration_options: features
.registration_options_where(|it| it.supports_semantic_tokens()),
semantic_tokens_options: SemanticTokensOptions {
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
legend: semantic_tokens::LEGEND.clone(),
// TODO
range: Some(false),
full: Some(SemanticTokensFullOptions::Bool(true)),
},
static_registration_options: StaticRegistrationOptions { id: None },
},
),
),
])
.await
.expect("Dynamic capability registration failed.");
self.client
.log_message(MessageType::INFO, "server initialized!")
.await;
}
async fn shutdown(&self) -> jsonrpc::Result<()> {
let state = {
let mut state = self.state.write().await;
mem::replace(&mut *state, ServerState::Shutdown)
};
for features in state.require_features().all_features() {
features.shutdown().await;
}
Ok(())
}
async fn did_open(&self, params: DidOpenTextDocumentParams) {
let state = self.require_running_state().await;
let features = self
.features_from_url(&state.features, ¶ms.text_document.uri)
.await;
assert!(features.supports_did_open());
let content = params.text_document.text.into_bytes();
features
.did_open(&self.db, params.text_document.uri, content)
.await;
}
async fn did_change(&self, params: DidChangeTextDocumentParams) {
let state = self.require_running_state().await;
{
let features = self
.features_from_url(&state.features, ¶ms.text_document.uri)
.await;
assert!(features.supports_did_change());
features
.did_change(
&self.db,
params.text_document.uri.clone(),
params.content_changes,
)
.await;
};
let module_result = module_from_url(
¶ms.text_document.uri,
if params.text_document.uri.path().ends_with(".candy") {
ModuleKind::Code
} else {
ModuleKind::Asset
},
&state.packages_path,
);
if let Ok(module) = module_result {
let notifications = {
let state = self.state.read().await;
state
.require_features()
.ir
.generate_update_notifications(&module)
.await
};
for notification in notifications {
self.client
.send_notification::<UpdateIrNotification>(notification)
.await;
}
}
}
async fn did_close(&self, params: DidCloseTextDocumentParams) {
let state = self.require_running_state().await;
let features = self
.features_from_url(&state.features, ¶ms.text_document.uri)
.await;
assert!(features.supports_did_close());
features.did_close(&self.db, params.text_document.uri).await;
}
async fn goto_definition(
&self,
params: GotoDefinitionParams,
) -> jsonrpc::Result<Option<GotoDefinitionResponse>> {
let state = self.require_running_state().await;
let features = self
.features_from_url(
&state.features,
¶ms.text_document_position_params.text_document.uri,
)
.await;
assert!(features.supports_find_definition());
let response = features
.find_definition(
&self.db,
params.text_document_position_params.text_document.uri,
params.text_document_position_params.position,
)
.await
.map(|link| GotoDefinitionResponse::Link(vec![link]));
Ok(response)
}
async fn references(&self, params: ReferenceParams) -> jsonrpc::Result<Option<Vec<Location>>> {
let uri = params.text_document_position.text_document.uri;
let highlights = self
.references_raw(
uri.clone(),
params.text_document_position.position,
false,
params.context.include_declaration,
)
.await;
let response = highlights
.iter()
.flat_map(|(uri, references)| {
references.iter().map(|highlight| Location {
uri: uri.clone(),
range: highlight.range,
})
})
.collect();
Ok(Some(response))
}
async fn document_highlight(
&self,
params: DocumentHighlightParams,
) -> jsonrpc::Result<Option<Vec<DocumentHighlight>>> {
let mut response = self
.references_raw(
params
.text_document_position_params
.text_document
.uri
.clone(),
params.text_document_position_params.position,
true,
true,
)
.await;
let highlights = response
.remove(¶ms.text_document_position_params.text_document.uri)
.unwrap_or_default()
.iter()
.map(|reference| DocumentHighlight {
range: reference.range,
kind: Some(if reference.is_write {
DocumentHighlightKind::WRITE
} else {
DocumentHighlightKind::READ
}),
})
.collect();
Ok(Some(highlights))
}
async fn folding_range(
&self,
params: FoldingRangeParams,
) -> jsonrpc::Result<Option<Vec<FoldingRange>>> {
let state = self.require_running_state().await;
let features = self
.features_from_url(&state.features, ¶ms.text_document.uri)
.await;
assert!(features.supports_folding_ranges());
Ok(Some(
features
.folding_ranges(&self.db, params.text_document.uri)
.await,
))
}
async fn formatting(
&self,
params: DocumentFormattingParams,
) -> jsonrpc::Result<Option<Vec<TextEdit>>> {
let state = self.require_running_state().await;
let features = self
.features_from_url(&state.features, ¶ms.text_document.uri)
.await;
assert!(features.supports_format());
Ok(Some(
features.format(&self.db, params.text_document.uri).await,
))
}
async fn prepare_rename(
&self,
params: TextDocumentPositionParams,
) -> jsonrpc::Result<Option<PrepareRenameResponse>> {
let state = self.require_running_state().await;
let uri = params.text_document.uri;
let features = self.features_from_url(&state.features, &uri).await;
let result = features
.prepare_rename(&self.db, uri, params.position)
.await;
Ok(result.map(PrepareRenameResponse::Range))
}
async fn rename(&self, params: RenameParams) -> jsonrpc::Result<Option<WorkspaceEdit>> {
let state = self.require_running_state().await;
let uri = params.text_document_position.text_document.uri;
let features = self.features_from_url(&state.features, &uri).await;
let result = features
.rename(
&self.db,
uri,
params.text_document_position.position,
params.new_name,
)
.await;
match result {
Ok(changes) => Ok(Some(WorkspaceEdit {
changes: Some(changes),
..Default::default()
})),
Err(RenameError::NewNameInvalid) => Err(jsonrpc::Error {
code: jsonrpc::ErrorCode::InvalidParams,
message: "The new name is not valid.".to_string(),
data: None,
}),
}
}
async fn semantic_tokens_full(
&self,
params: SemanticTokensParams,
) -> jsonrpc::Result<Option<SemanticTokensResult>> {
let state = self.require_running_state().await;
let uri = params.text_document.uri;
let features = self.features_from_url(&state.features, &uri).await;
let tokens = features.semantic_tokens(&self.db, uri);
let tokens = tokens.await;
Ok(Some(SemanticTokensResult::Tokens(SemanticTokens {
result_id: None,
data: tokens,
})))
}
}
impl Server {
async fn references_raw(
&self,
uri: Url,
position: Position,
only_in_same_document: bool,
include_declaration: bool,
) -> FxHashMap<Url, Vec<Reference>> {
let state = self.state.read().await;
let state = state.require_running();
let features = self.features_from_url(&state.features, &uri).await;
assert!(features.supports_references());
features
.references(
&self.db,
uri,
position,
only_in_same_document,
include_declaration,
)
.await
}
}
/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#renameRegistrationOptions
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RenameRegistrationOptions {
#[serde(flatten)]
pub text_document_registration_options: TextDocumentRegistrationOptions,
#[serde(flatten)]
pub rename_options: RenameOptions,
}
|
test_stdout!(returns_true, "true\ntrue\ntrue\n");
test_stdout!(does_not_flush_existing_message, "true\ntrue\ntrue\n");
test_stdout!(prevents_future_messages, "false\ntrue\nfalse\n");
|
use futures::prelude::*;
use romio::raw::{AsyncReadReady, AsyncReady, AsyncWriteReady};
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::{Context, Poll};
#[derive(Debug)]
pub(crate) struct TcpStream {
pub romio_stream: romio::tcp::TcpStream,
}
#[derive(Debug)]
pub(crate) struct TcpListener {
pub romio_listener: romio::tcp::TcpListener,
}
impl runtime_raw::TcpStream for TcpStream {
fn poll_write_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.romio_stream)
.poll_write_ready(cx)
.map_ok(|_| ())
}
fn poll_read_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.romio_stream)
.poll_read_ready(cx)
.map_ok(|_| ())
}
fn take_error(&self) -> io::Result<Option<io::Error>> {
Ok(None)
}
fn local_addr(&self) -> io::Result<SocketAddr> {
self.romio_stream.local_addr()
}
fn peer_addr(&self) -> io::Result<SocketAddr> {
self.romio_stream.peer_addr()
}
fn shutdown(&self, how: std::net::Shutdown) -> std::io::Result<()> {
self.romio_stream.shutdown(how)
}
#[cfg(unix)]
fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
use std::os::unix::io::AsRawFd;
self.romio_stream.as_raw_fd()
}
}
impl AsyncRead for TcpStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.romio_stream).poll_read(cx, &mut buf)
}
}
impl AsyncWrite for TcpStream {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.romio_stream).poll_write(cx, &buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.romio_stream).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.romio_stream).poll_close(cx)
}
}
impl runtime_raw::TcpListener for TcpListener {
fn local_addr(&self) -> io::Result<SocketAddr> {
self.romio_listener.local_addr()
}
fn poll_accept(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<Pin<Box<dyn runtime_raw::TcpStream>>>> {
Pin::new(&mut self.romio_listener)
.poll_ready(cx)
.map_ok(|(romio_stream, _)| {
Box::pin(TcpStream { romio_stream }) as Pin<Box<dyn runtime_raw::TcpStream>>
})
}
/// Extracts the raw file descriptor.
#[cfg(unix)]
fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
use std::os::unix::io::AsRawFd;
self.romio_listener.as_raw_fd()
}
}
|
struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
fn area(&self) -> u32{//method //方法
self.length * self.width
}
fn can_hold(&self, other: &Rectangle) -> bool{
self.width > other.width && self.length > other.length
}
fn square(size: u32) -> Rectangle{//associated functions //关联函数
Rectangle{ length: size, width: size};
}
}
fn main(){
let rect1 = Rectangle{ length: 10, width: 20};
let rect2 = Rectangle{ length: 20, width: 30};
let rect3 = Rectangle::square(4);//use associated functions to build a 4X4 square
println!("The area of the rect1 is {} square pixels.",
rect1.area() );
println!("The rect1 can hold rect2?: {}", rect1.can_hold(&rect2));
println!("The rect2 can hold rect1?: {}", rect2.can_hold(&rect1));
} |
use crate::{
CoordinateType, GeometryCollection, Line, LineString, MultiLineString, MultiPoint,
MultiPolygon, Point, Polygon, Rect, Triangle,
};
use num_traits::Float;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
/// An enum representing any possible geometry type.
///
/// All `Geo` types can be converted to a `Geometry` member using `.into()` (as part of the
/// `std::convert::Into` pattern), and `Geo` types implement the `TryFrom` trait in order to
/// convert _back_ from enum members.
///
/// # Example
///
/// ```
/// use std::convert::TryFrom;
/// use geo_types::{Point, point, Geometry, GeometryCollection};
/// let p = point!(x: 1.0, y: 1.0);
/// let pe: Geometry<f64> = p.into();
/// let pn = Point::try_from(pe).unwrap();
/// ```
///
#[derive(Eq, PartialEq, Clone, Debug, Hash)]
pub enum Geometry<T>
where
T: CoordinateType,
{
Point(Point<T>),
Line(Line<T>),
LineString(LineString<T>),
Polygon(Polygon<T>),
MultiPoint(MultiPoint<T>),
MultiLineString(MultiLineString<T>),
MultiPolygon(MultiPolygon<T>),
GeometryCollection(GeometryCollection<T>),
Rect(Rect<T>),
Triangle(Triangle<T>),
}
impl<T: CoordinateType> From<Point<T>> for Geometry<T> {
fn from(x: Point<T>) -> Geometry<T> {
Geometry::Point(x)
}
}
impl<T: CoordinateType> From<Line<T>> for Geometry<T> {
fn from(x: Line<T>) -> Geometry<T> {
Geometry::Line(x)
}
}
impl<T: CoordinateType> From<LineString<T>> for Geometry<T> {
fn from(x: LineString<T>) -> Geometry<T> {
Geometry::LineString(x)
}
}
impl<T: CoordinateType> From<Polygon<T>> for Geometry<T> {
fn from(x: Polygon<T>) -> Geometry<T> {
Geometry::Polygon(x)
}
}
impl<T: CoordinateType> From<MultiPoint<T>> for Geometry<T> {
fn from(x: MultiPoint<T>) -> Geometry<T> {
Geometry::MultiPoint(x)
}
}
impl<T: CoordinateType> From<MultiLineString<T>> for Geometry<T> {
fn from(x: MultiLineString<T>) -> Geometry<T> {
Geometry::MultiLineString(x)
}
}
impl<T: CoordinateType> From<MultiPolygon<T>> for Geometry<T> {
fn from(x: MultiPolygon<T>) -> Geometry<T> {
Geometry::MultiPolygon(x)
}
}
impl<T: CoordinateType> From<Rect<T>> for Geometry<T> {
fn from(x: Rect<T>) -> Geometry<T> {
Geometry::Rect(x)
}
}
impl<T: CoordinateType> From<Triangle<T>> for Geometry<T> {
fn from(x: Triangle<T>) -> Geometry<T> {
Geometry::Triangle(x)
}
}
impl<T: CoordinateType> Geometry<T> {
/// If this Geometry is a Point, then return that, else None.
///
/// # Examples
///
/// ```
/// use geo_types::*;
/// let g = Geometry::Point(Point::new(0., 0.));
/// let p2: Point<f32> = g.into_point().unwrap();
/// assert_eq!(p2, Point::new(0., 0.,));
/// ```
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<Point>"
)]
pub fn into_point(self) -> Option<Point<T>> {
if let Geometry::Point(x) = self {
Some(x)
} else {
None
}
}
/// If this Geometry is a LineString, then return that LineString, else None.
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<LineString>"
)]
pub fn into_line_string(self) -> Option<LineString<T>> {
if let Geometry::LineString(x) = self {
Some(x)
} else {
None
}
}
/// If this Geometry is a Line, then return that Line, else None.
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<Line>"
)]
pub fn into_line(self) -> Option<Line<T>> {
if let Geometry::Line(x) = self {
Some(x)
} else {
None
}
}
/// If this Geometry is a Polygon, then return that, else None.
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<Polygon>"
)]
pub fn into_polygon(self) -> Option<Polygon<T>> {
if let Geometry::Polygon(x) = self {
Some(x)
} else {
None
}
}
/// If this Geometry is a MultiPoint, then return that, else None.
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<MultiPoint>"
)]
pub fn into_multi_point(self) -> Option<MultiPoint<T>> {
if let Geometry::MultiPoint(x) = self {
Some(x)
} else {
None
}
}
/// If this Geometry is a MultiLineString, then return that, else None.
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<MultiLineString>"
)]
pub fn into_multi_line_string(self) -> Option<MultiLineString<T>> {
if let Geometry::MultiLineString(x) = self {
Some(x)
} else {
None
}
}
/// If this Geometry is a MultiPolygon, then return that, else None.
#[deprecated(
note = "Will be removed in an upcoming version. Switch to std::convert::TryInto<MultiPolygon>"
)]
pub fn into_multi_polygon(self) -> Option<MultiPolygon<T>> {
if let Geometry::MultiPolygon(x) = self {
Some(x)
} else {
None
}
}
}
#[derive(Debug)]
pub struct FailedToConvertError;
impl fmt::Display for FailedToConvertError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Could not convert from enum member to concrete type")
}
}
impl Error for FailedToConvertError {
fn description(&self) -> &str {
"Could not convert from enum member to concrete type"
}
}
impl<T> TryFrom<Geometry<T>> for Point<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<Point<T>, Self::Error> {
match geom {
Geometry::Point(p) => Ok(p),
_ => Err(FailedToConvertError),
}
}
}
impl<T> TryFrom<Geometry<T>> for Line<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<Line<T>, Self::Error> {
match geom {
Geometry::Line(l) => Ok(l),
_ => Err(FailedToConvertError),
}
}
}
impl<T> TryFrom<Geometry<T>> for LineString<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<LineString<T>, Self::Error> {
match geom {
Geometry::LineString(ls) => Ok(ls),
_ => Err(FailedToConvertError),
}
}
}
impl<T> TryFrom<Geometry<T>> for Polygon<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<Polygon<T>, Self::Error> {
match geom {
Geometry::Polygon(ls) => Ok(ls),
_ => Err(FailedToConvertError),
}
}
}
impl<T> TryFrom<Geometry<T>> for MultiPoint<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<MultiPoint<T>, Self::Error> {
match geom {
Geometry::MultiPoint(mp) => Ok(mp),
_ => Err(FailedToConvertError),
}
}
}
impl<T> TryFrom<Geometry<T>> for MultiLineString<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<MultiLineString<T>, Self::Error> {
match geom {
Geometry::MultiLineString(mls) => Ok(mls),
_ => Err(FailedToConvertError),
}
}
}
impl<T> TryFrom<Geometry<T>> for MultiPolygon<T>
where
T: Float,
{
type Error = FailedToConvertError;
fn try_from(geom: Geometry<T>) -> Result<MultiPolygon<T>, Self::Error> {
match geom {
Geometry::MultiPolygon(mp) => Ok(mp),
_ => Err(FailedToConvertError),
}
}
}
|
//! The core [audio] traits.
//!
//! If you want to build an audio component that is completely agnostic to the
//! shape of any one given audio buffer you can add a dependency directly to
//! these traits instead of depending on all of the [audio] crate.
//!
//! [audio]: https://docs.rs/audio
#![deny(missing_docs, broken_intra_doc_links)]
#![allow(clippy::should_implement_trait)]
mod buf;
pub use self::buf::{
AsInterleaved, AsInterleavedMut, Buf, Channels, ChannelsMut, ExactSizeBuf, InterleavedBuf,
ResizableBuf,
};
mod channel;
pub use self::channel::{Channel, ChannelMut};
mod translate;
pub use self::translate::Translate;
mod sample;
pub use self::sample::Sample;
mod io;
pub use self::io::{ReadBuf, WriteBuf};
|
extern crate rltk;
use specs::prelude::*;
use crate::{CONSOLE_INDEX, Context, InBackpack, Name, State};
use self::rltk::{ColorPair, Point, Rect, RGB, VirtualKeyCode};
#[derive(PartialEq, Copy, Clone)]
pub enum ItemMenuResult { Cancel, NoResponse, Selected(Entity) }
pub fn show_inventory(state: &mut State, context: &mut Context) -> ItemMenuResult {
ItemMenuDrawer {
state,
context,
settings: ItemMenuDrawerSettings {
title: "Inventory",
},
}.show_item_selection_menu()
}
pub fn show_drop_item_menu(state: &mut State, context: &mut Context) -> ItemMenuResult {
ItemMenuDrawer {
state,
context,
settings: ItemMenuDrawerSettings {
title: "Drop which item?",
},
}.show_item_selection_menu()
}
struct ItemMenuDrawer<'a, 'b> {
state: &'a mut State,
context: &'a mut Context<'b>,
settings: ItemMenuDrawerSettings<'a>,
}
struct ItemMenuDrawerSettings<'a> {
pub title: &'a str,
}
impl<'a, 'b> ItemMenuDrawer<'a, 'b> {
pub fn show_item_selection_menu(&mut self) -> ItemMenuResult {
self.context.set_target(CONSOLE_INDEX.ui);
let player_entity = self.state.ecs.fetch::<Entity>();
let names = self.state.ecs.read_storage::<Name>();
let in_backpacks = self.state.ecs.read_storage::<InBackpack>();
let entities = self.state.ecs.entities();
let inventory_count = in_backpacks
.join()
.filter(|in_backpack| {
in_backpack.owner == *player_entity
})
.count();
let (window_width, window_height) = self.context.get_screen_size();
let mut y = window_height as i32 / 2 - (inventory_count / 2) as i32;
let bg = RGB::named(rltk::BLACK);
let highlight_fg = RGB::named(rltk::YELLOW);
let plain_fg = RGB::named(rltk::WHITE);
const INVENTORY_WIDTH: i32 = 31;
const BORDER_TEXT_OFFSET: i32 = 3;
let inventory_x: i32 = window_width as i32 / 2 - (INVENTORY_WIDTH / 2);
self.context.draw_box(
Rect::with_size(inventory_x, y - 2, INVENTORY_WIDTH, (inventory_count + 3) as i32),
ColorPair::new(plain_fg, bg));
self.context.print_color(
Point::new(
inventory_x + BORDER_TEXT_OFFSET,
y - 2),
&self.settings.title,
ColorPair::new(
highlight_fg,
bg));
self.context.print_color(
Point::new(
inventory_x + BORDER_TEXT_OFFSET,
y + inventory_count as i32 + 1),
"ESCAPE to cancel",
ColorPair::new(
highlight_fg,
bg));
let inventory = (&names, &in_backpacks, &entities)
.join()
.filter(|(_, in_backpack, _)| {
in_backpack.owner == *player_entity
});
let mut hotkey = 'a' as u8;
let mut selectable_items: Vec<Entity> = Vec::new();
for (name, _in_backpack, entity) in inventory {
self.context.set(Point::new(inventory_x + 2, y), ColorPair::new(plain_fg, bg), rltk::to_cp437('('));
self.context.set(Point::new(inventory_x + 3, y), ColorPair::new(highlight_fg, bg), hotkey);
self.context.set(Point::new(inventory_x + 4, y), ColorPair::new(plain_fg, bg), rltk::to_cp437(')'));
self.context.print_color(Point::new(inventory_x + 6, y), &name.name, ColorPair::new(plain_fg, bg));
selectable_items.push(entity);
y += 1;
hotkey += 1;
}
self.context.set_target(CONSOLE_INDEX.base);
match self.context.rltk.key {
None => ItemMenuResult::NoResponse,
Some(key) => {
match key {
VirtualKeyCode::Escape => ItemMenuResult::Cancel,
_ => {
let selection = rltk::letter_to_option(key) as usize;
let selected_item_or_none = selectable_items.get(selection);
match selected_item_or_none {
None => ItemMenuResult::NoResponse,
Some(selected_item) => ItemMenuResult::Selected(*selected_item),
}
}
}
}
}
}
} |
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub struct RoomSnapshot {
pub peers: HashMap<u64, PeerSnapshot>,
}
impl RoomSnapshot {
pub fn new() -> Self {
Self {
peers: HashMap::new(),
}
}
pub fn insert_peer(&mut self, peer_id: u64, peer: PeerSnapshot) {
self.peers.insert(peer_id, peer);
}
}
#[derive(Clone, Debug)]
pub struct PeerSnapshot {
pub sdp_offer: Option<String>,
pub sdp_answer: Option<String>,
}
/// This kind of objects will be generated by macros in the real app, so this
/// code isn't important.
pub struct PeerSnapshotDiff {
pub sdp_offer_change: Option<Option<String>>,
pub sdp_answer_change: Option<Option<String>>,
}
pub struct OnMakeSdpOfferPeerSnapshotDiffGroup {
pub sdp_offer: Option<String>,
}
impl PeerSnapshotDiff {
pub fn on_make_sdp_offer(
&self,
) -> Option<OnMakeSdpOfferPeerSnapshotDiffGroup> {
if let Some(sdp_offer) = &self.sdp_offer_change {
return Some(OnMakeSdpOfferPeerSnapshotDiffGroup {
sdp_offer: sdp_offer.clone(),
});
}
None
}
}
impl PeerSnapshot {
pub fn diff(&self, another: &PeerSnapshot) -> PeerSnapshotDiff {
let mut diff = PeerSnapshotDiff {
sdp_answer_change: None,
sdp_offer_change: None,
};
if self.sdp_answer != another.sdp_answer {
diff.sdp_answer_change = Some(another.sdp_answer.clone());
}
if self.sdp_offer != another.sdp_offer {
diff.sdp_offer_change = Some(another.sdp_offer.clone());
}
diff
}
}
#[derive(Debug)]
pub struct TrackSnapshot {
pub is_muted: bool,
}
|
#![feature(ascii_ctype)]
extern crate itertools;
use std::ascii::AsciiExt;
use itertools::Itertools;
pub fn encode(s: &str) -> String {
decode(s)
.chars()
.chunks(5)
.into_iter()
.map(|c| c.collect::<String>())
.join(" ")
}
pub fn decode(s: &str) -> String {
let mut result = String::new();
for c in s.to_lowercase().chars() {
if !c.is_ascii_alphanumeric() {
continue;
}
if c.is_ascii_digit() {
result.push(c)
} else {
result.push(((97 + (122 - (c as u8))) as char))
}
}
result
}
|
//! 提供向量分配器的简单实现 [`BitmapVectorAllocator`]
use super::VectorAllocator;
use bit_field::BitArray;
use core::cmp::min;
/// Bitmap 中的位数(4K bit)
const BITMAP_SIZE: usize = 4096;
/// 向量分配器的简单实现,每字节用一位表示
pub struct BitmapVectorAllocator {
/// 容量,单位为 bitmap 中可以使用的位数,即待分配空间的 字节数
capacity: usize,
/// 每一位 0 表示空闲
bitmap: [u8; BITMAP_SIZE / 8], // 最多支持512Byte的分配管理
}
impl VectorAllocator for BitmapVectorAllocator {
fn new(capacity: usize) -> Self { // 单位是 字节
Self {
capacity: min(BITMAP_SIZE, capacity),
bitmap: [0u8; BITMAP_SIZE / 8],
}
}
// O(capacity / align) ~ O(capacity)
fn alloc(&mut self, size: usize, align: usize) -> Option<usize> { // size, align 单位都是字节
for start in (0..self.capacity - size).step_by(align) {
if (start..start + size).all(|i| !self.bitmap.get_bit(i)) { // [start, start+size)中的所有字节都没有被占用,则该内存块可分配
(start..start + size).for_each(|i| self.bitmap.set_bit(i, true)); // 标记置为1
return Some(start); // 分配成功
}
}
None // 分配失败
}
fn dealloc(&mut self, start: usize, size: usize, _align: usize) { // O(size)
assert!(self.bitmap.get_bit(start)); // 首先是一个已经被分配的页面
(start..start + size).for_each(|i| self.bitmap.set_bit(i, false)); // [start, start+size)的字节标记清零
}
}
|
use glow::{Context, HasContext};
use std::rc::Rc;
pub type ProgramId = <Context as HasContext>::Program;
pub struct Program {
gl: Rc<Context>,
id: ProgramId,
}
impl Program {
pub fn new(gl: Rc<Context>, vertex_shader_source: &str, fragment_shader_source: &str) -> Result<Self, String> {
let id = unsafe {
let vertex_shader_id = gl.create_shader(glow::VERTEX_SHADER)?;
gl.shader_source(vertex_shader_id, vertex_shader_source);
gl.compile_shader(vertex_shader_id);
if !gl.get_shader_compile_status(vertex_shader_id) {
return Err(gl.get_shader_info_log(vertex_shader_id));
}
let fragment_shader_id = gl.create_shader(glow::FRAGMENT_SHADER)?;
gl.shader_source(fragment_shader_id, fragment_shader_source);
gl.compile_shader(fragment_shader_id);
if !gl.get_shader_compile_status(fragment_shader_id) {
return Err(gl.get_shader_info_log(fragment_shader_id));
}
let program_id = gl.create_program()?;
gl.attach_shader(program_id, vertex_shader_id);
gl.attach_shader(program_id, fragment_shader_id);
gl.link_program(program_id);
if !gl.get_program_link_status(program_id) {
return Err(gl.get_program_info_log(program_id));
}
gl.delete_shader(vertex_shader_id);
gl.delete_shader(fragment_shader_id);
program_id
};
Ok(Self { gl, id })
}
pub fn id(&self) -> ProgramId {
self.id
}
pub fn bind(&self) {
unsafe {
self.gl.use_program(Some(self.id));
}
}
pub fn unbind(&self) {
unsafe {
self.gl.use_program(None);
}
}
pub fn set_uniform_matrix_4(&self, name: &str, mat4: &[f32; 16]) {
unsafe {
let location = self.gl.get_uniform_location(self.id, name);
self.gl.uniform_matrix_4_f32_slice(location, false, mat4);
}
}
}
impl Drop for Program {
fn drop(&mut self) {
unsafe {
self.gl.delete_program(self.id);
}
}
}
impl PartialEq for Program {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
|
//use std::sync::{Arc,Mutex};
//use std::vec::Vec;
fn print_thread_name(name: &str) {
let new_name = name.to_string() + " ok";
println!("{}", new_name);
}
fn main() {
let number_of_threads = 20;
let mut thread_names = Vec::new();
for n in 0..number_of_threads {
let thread_name = format!("thread-{}", n + 1);
thread_names.push(thread_name);
}
for n in &thread_names {
print_thread_name(n);
}
}
|
pub struct Solution;
impl Solution {
pub fn number_of_arithmetic_slices(a: Vec<i32>) -> i32 {
if a.len() < 3 {
return 0;
}
let mut res = 0;
let mut diff = a[1] - a[0];
let mut cnt = 1;
for i in 2..a.len() {
if a[i] - a[i - 1] == diff {
res += cnt;
cnt += 1;
} else {
diff = a[i] - a[i - 1];
cnt = 1;
}
}
res
}
}
#[test]
fn test0413() {
fn case(a: Vec<i32>, want: i32) {
let got = Solution::number_of_arithmetic_slices(a);
assert_eq!(got, want);
}
case(vec![1, 2, 3, 4], 3);
}
|
pub fn fizzbuzz(fizz_num: usize, buzz_num: usize, limit: usize){
for i in 1..=limit{
let fizz = i%fizz_num==0;
let buzz = i%buzz_num==0;
match true {
_ if fizz && buzz => print!("Fizzbuzz!"),
_ if fizz => print!("Fizz"),
_ if buzz => print!("Buzz"),
_ => print!("{}", i)
}
print!("\n");
}} |
use std::borrow::Cow;
use common::Error;
use web_sys::Storage;
use crate::state::ModelEvent;
/// A method for handling common errors.
///
/// If an update is returned, it should be used; else, the caller will need to handle the error.
pub fn handle_common_errors(err: &Error) -> Option<ModelEvent> {
match err.status {
401 => Some(ModelEvent::Logout),
_ => None,
}
}
/// Attempt to access a key from session storage.
pub fn get_session_item(key: &str) -> Result<String, Cow<'static, str>> {
get_session_storage()
.and_then(|s| s.get_item(key).map_err(|err| match err.as_string() {
Some(s) => Cow::Owned(s),
None => Cow::Borrowed("Failed to set session storage key."),
}))
.and_then(|opt| match opt {
Some(s) => Ok(s),
None => Err(Cow::Borrowed("Key not found in storage.")),
})
}
/// Set a session storage key.
pub fn set_session_item(key: &str, val: &str) -> Result<(), Cow<'static, str>> {
get_session_storage()
.and_then(|s| s.set_item(key, val).map_err(|err| match err.as_string() {
Some(s) => Cow::Owned(s),
None => Cow::Borrowed("Failed to set session storage key."),
}))
}
/// Set a session storage key.
pub fn del_session_item(key: &str) {
let _ = get_session_storage()
.map_err(|_| ())
.and_then(|s| s.remove_item(key).map_err(|err| {
seed::log!(format!("Failed to remove session storage key '{}': {:?}", key, err));
}));
}
/// Get a handle to the window's session storage.
fn get_session_storage() -> Result<Storage, Cow<'static, str>> {
let err_msg = "Could not access session storage.";
match seed::window().session_storage() {
Ok(opt) => opt.ok_or(Cow::Borrowed(err_msg)),
Err(err) => match err.as_string() {
Some(s) => Err(Cow::Owned(s)),
None => Err(Cow::Borrowed(err_msg)),
}
}
}
|
extern crate rand;
use rand::random;
pub type NodeId = u32;
pub type KeySize = usize; // I'd prefer u32 instead
pub type NodeKey = (KeySize,NodeId); // must match for valid key
pub trait Id {
fn nid(&self) -> NodeId;
fn idx(&self) -> KeySize; // entity idx
}
impl Id for NodeKey {
fn nid(&self) -> NodeId { self.1 }
fn idx(&self) -> KeySize { self.0 }
}
#[derive(Clone)]
pub struct Node<T> {
id: Option<NodeId>, // none represents a dead-node
parent: Option<NodeKey>,
pub data: T,
}
impl<T> Node<T> {
pub fn new (d: T) -> Node<T> {
let id = random::<u32>();
Node {
id: Some(id),
parent: None,
data: d,
}
}
pub fn id(&self) -> &Option<NodeId> { &self.id }
pub fn destroy(&mut self) { self.id = None; }
}
pub struct NodeManager<T> {
nodes: Vec<Node<T>>,
dead: Vec<KeySize>,
}
impl<T> NodeManager<T> {
pub fn new (max: usize) -> NodeManager<T> {
let v = Vec::with_capacity(max);
NodeManager { nodes: v,
dead: vec!(), }
}
pub fn add(&mut self, n: Node<T>) -> NodeKey {
let nid = n.id().unwrap();
let idx;
if let Some(_idx) = self.dead.pop() {
idx = _idx;
self.nodes[idx] = n;
}
else {
idx = self.nodes.len();
self.nodes.push(n);
}
(idx,nid)
}
pub fn remove(&mut self, key: NodeKey) -> bool {
let node = &mut self.nodes[key.idx()];
if let &Some(id) = node.id() {
if id==key.nid() {
node.destroy();
self.dead.push(key.idx());
return true;
}
}
false
}
pub fn get(&self, key: NodeKey) -> Option<&Node<T>> {
let node = &self.nodes[key.idx()];
if let &Some(id) = node.id() {
if id==key.nid() { return Some(node) }
}
None
}
pub fn get_mut(&mut self, key: NodeKey) -> Option<&mut Node<T>> {
let node = &mut self.nodes[key.idx()];
if let &Some(id) = node.id() {
if id==key.nid() { return Some(node) }
}
None
}
pub fn set_parent(&mut self, key: NodeKey, pkey: NodeKey) {
if let Some(node) = self.get_mut(key) {
node.parent = Some(pkey);
}
}
/// gets the node's parent node
pub fn get_parent(&mut self, key: NodeKey) -> Option<&Node<T>> {
if let Some(node) = self.get(key) {
if let Some(pkey) = node.parent {
return self.get(pkey);
}
}
None
}
/// gets the node's parent key
pub fn get_pkey(&mut self, key: NodeKey) -> Option<NodeKey> {
if let Some(node) = self.get(key) {
return node.parent
}
None
}
/* /// update scene, only updates parent nodes once
pub fn update(&mut self, dt: &f64) {
let mut frame: HashSet<NodeKey> = HashSet::new();
let mut keys = vec!();
for (i,n) in self.nodes.iter().enumerate() {
if let &Some(id) = n.id() {
keys.push((i,id));
}
}
for key in keys {
if frame.contains(&key) { continue }
self.updater(key,dt,&mut frame);
}
}*/
pub fn box_iter<'a> (&'a self) -> Box<Iterator<Item=(usize,&'a Node<T>)> + 'a> {
Box::new(self.nodes.iter()
.enumerate()
.filter(|n| n.1.id().is_some()))
}
pub fn box_iter_mut<'a> (&'a mut self) -> Box<Iterator<Item=(usize,&'a mut Node<T>)> + 'a> {
Box::new(self.nodes.iter_mut()
.enumerate()
.filter(|n| n.1.id().is_some()))
}
}
|
pub fn run() {
let mut x = 1;
while x <= 100 {
if x % 15 == 0 {
println!("FizzBazz");
} else if x % 3 == 0 {
println!("Fizz");
} else if x % 5 == 0 {
println!("Bazz");
} else {
println!("{}", x);
}
x += 1;
}
}
|
use super::KeywordPriority;
pub struct Erlang;
impl KeywordPriority for Erlang {
const DEFINITION: &'static [&'static str] = &["fun"];
const REFERENCE: &'static [&'static str] = &[];
const STATEMENT: &'static [&'static str] = &[
"after", "and", "andalso", "band", "begin", "bnot", "bor", "bsl", "bsr", "bxor", "case",
"catch", "cond", "div", "end", "if", "let", "not", "of", "or", "orelse", "receive", "rem",
"try", "when", "xor",
];
}
|
use serenity::{cache::Cache, model::channel::Message, prelude::*,};
use std::env;
use censor::*;
#[derive(Clone, Debug)]
pub struct ParsedCommand {
pub is_command: bool,
pub command: Option<String>,
pub args: Option<Vec<String>>,
}
pub fn author_is_bot(msg: &Message) -> bool {
msg.author.bot
}
// TODO: remove if not used in the future, is the difference between taurak & other bots important?
pub async fn _author_is_taurak(msg: Message, cache: &Cache) -> bool {
msg.is_own(cache).await
}
pub fn send_via_dm(msg: &Message) -> bool {
match msg.guild_id {
Some(_guild_id) => false,
_ => true,
}
}
pub fn parse_command(msg: &Message, prefix: String) -> ParsedCommand {
let mut parsed_message = msg.content.split_whitespace();
let first_word = match parsed_message.next() {
Some(prefix) => prefix,
_ => "".into(),
};
if first_word == prefix {
let command: Option<String> = match parsed_message.next() {
Some(command) => Some(command.into()),
_ => Some("no command".into()),
};
let mut args: Vec<String> = vec![];
let mut more_args: bool = true;
let mut arg: String = "".into();
match parsed_message.next() {
Some(argument) => {
arg = argument.into();
}
_ => {
more_args = false;
}
};
while more_args {
args.push(arg.clone());
match parsed_message.next() {
Some(argument) => {
arg = argument.into();
}
_ => {
more_args = false;
}
};
}
return ParsedCommand {
is_command: true,
command: command,
args: Some(args),
};
} else {
return ParsedCommand {
is_command: false,
command: None,
args: None,
};
}
}
pub async fn _author_has_role(msg: Message, role_name: String, cache: &Cache, ctx: Context) -> bool {
let guild = msg.guild(cache).await.expect("Guild was not in cache");
let guild_id = guild.id;
let role_map = guild.roles;
let mut role_id: Option<&serenity::model::id::RoleId> = None;
if role_map.iter().count() == 0 {
return false;
}
for (key, var) in role_map.iter() {
if var.name.to_ascii_lowercase() == role_name.to_ascii_lowercase() {
role_id = Some(key);
break;
}
}
match role_id {
Some(role_id) => {if msg.author.has_role(ctx.http, guild_id, role_id).await.expect("Err getting role") {
true
}
else {
false
}}
_ => {return false;}
}
}
pub async fn author_has_permission(msg: Message, permission: serenity::model::permissions::Permissions, cache: &Cache, ctx: Context) -> bool {
let guild = msg.guild(cache).await.expect("Guild was not in cache");
let guild_id = guild.id;
let role_map = guild.roles;
if role_map.iter().count() == 0 {
return false;
}
for (key, var) in role_map.iter() {
if var.has_permission(permission) {
if msg.author.has_role(ctx.clone().http, guild_id, key).await.expect("Err getting role") {
return true;
}
}
}
return false;
}
pub fn author_is_owner(msg: &Message) -> bool {
if msg.author.id.as_u64() == &env::var("OWNER_ID").expect("No OWNER_ID in environment").parse::<u64>().expect("OWNER_ID was not a number!") {
true
}
else {
false
}
}
pub fn has_profanity_content(msg: &Message) -> bool {
let censor = Standard + Zealous + Sex;
censor.check(&msg.content)
}
|
extern crate rustplot;
use rustplot::chart_builder;
use rustplot::chart_builder::Chart;
use rustplot::data_parser;
#[test]
fn histogram_tests() {
let data_1 = data_parser::get_num_col(1, 0, 1000, "./resources/histogram_tests.csv");
let histogram_1 =
chart_builder::Histogram::new(String::from("Test Histogram 1"), data_1.clone());
histogram_1.draw();
}
|
//! Parses the public API of classes from their bytecode.
use std::collections::HashMap;
use noak;
use noak::descriptor::MethodDescriptor;
use noak::error::DecodeError;
use noak::reader::cpool::ConstantPool;
use serde::{Deserialize, Serialize};
use crate::bc::get_type_name;
use crate::sconst::{IndexedString, StringConstants};
#[derive(Clone)]
pub struct PublicApi {
pub classes: Vec<JavaClass>,
pub service_interfaces: ServiceInterfaces,
}
impl PublicApi {
pub fn new() -> Self {
Self {
classes: vec![],
service_interfaces: ServiceInterfaces::new(),
}
}
}
pub struct ApiParser<'pool> {
classes: Vec<JavaClass>,
service_interfaces: ServiceInterfaces,
constants: &'pool mut StringConstants,
}
impl<'pool> ApiParser<'pool> {
pub fn new(constants: &'pool mut StringConstants) -> Self {
Self {
classes: vec![],
service_interfaces: ServiceInterfaces::new(),
constants,
}
}
pub fn get_api(self) -> PublicApi {
PublicApi {
classes: self.classes,
service_interfaces: self.service_interfaces,
}
}
pub fn add_class(
&mut self,
class: &mut noak::reader::Class,
) -> Result<(), noak::error::DecodeError> {
if class.access_flags()?.contains(noak::AccessFlags::PRIVATE) {
return Ok(()); // Class isn't public.
}
let class = self.parse_class(class)?;
self.classes.push(class);
Ok(())
}
fn parse_class(&mut self, class: &mut noak::reader::Class) -> Result<JavaClass, DecodeError> {
let class_name = String::from_utf8_lossy(class.this_class_name()?.as_bytes());
let mut api_methods: Vec<JavaMethod> = vec![];
let mut api_fields: Vec<JavaField> = vec![];
let mut interfaces: Vec<IndexedString> = vec![];
let mut superclass = self.constants.put("java/lang/Object");
if let Ok(interface_names) = class.interface_names() {
for interface_name in interface_names {
if let Ok(interface_name) = interface_name {
let interface_name = String::from_utf8_lossy(interface_name.as_bytes());
let interface_name = self.constants.put(&interface_name);
interfaces.push(interface_name);
}
}
}
if let Ok(superclass_name) = class.super_class_name() {
if let Some(superclass_name) = superclass_name {
let superclass_name = String::from_utf8_lossy(superclass_name.as_bytes());
superclass = self.constants.put(&superclass_name);
}
}
if let Ok(methods) = class.methods() {
for method in methods {
if let Ok(method) = method {
// if method.access_flags().contains(noak::AccessFlags::PRIVATE) {
// continue;
// }
// Parse for public api.
if let Ok(method) = self.parse_method(class.pool()?, &method) {
api_methods.push(method);
}
}
}
}
if let Ok(fields) = class.fields() {
for field in fields {
if let Ok(field) = field {
// if field.access_flags().contains(noak::AccessFlags::PRIVATE) {
// continue;
// }
// Parse for public api.
if let Ok(field) = self.parse_field(class.pool()?, &field) {
api_fields.push(field);
}
}
}
}
Ok(self.new_class(
class_name.to_string(),
api_methods,
api_fields,
interfaces,
superclass,
))
}
fn parse_method(
&mut self,
pool: &ConstantPool,
method: &noak::reader::Method,
) -> Result<JavaMethod, DecodeError> {
let method_name = String::from_utf8_lossy(pool.get(method.name())?.content.as_bytes());
let descriptor = MethodDescriptor::parse(pool.get(method.descriptor())?.content)?;
let return_type = descriptor.return_type().map(|r| get_type_name(&r));
let param_types: Vec<String> = descriptor.parameters().map(|p| get_type_name(&p)).collect();
Ok(self.new_method(method_name.to_string(), param_types, return_type))
}
fn parse_field(
&mut self,
pool: &ConstantPool,
field: &noak::reader::Field,
) -> Result<JavaField, DecodeError> {
let field_name = String::from_utf8_lossy(pool.get(field.name())?.content.as_bytes());
let descriptor =
noak::descriptor::TypeDescriptor::parse(pool.get(field.descriptor())?.content)?;
Ok(self.new_field(field_name.to_string(), get_type_name(&descriptor)))
}
pub fn is_empty(&self) -> bool {
self.constants.size() == 0
}
pub fn new_class(
&mut self,
name: String,
methods: Vec<JavaMethod>,
fields: Vec<JavaField>,
interfaces: Vec<IndexedString>,
superclass: IndexedString,
) -> JavaClass {
JavaClass {
class_name: self.constants.put(&name),
methods,
fields,
interfaces,
superclass,
}
}
pub fn new_method(
&mut self,
name: String,
param_types: Vec<String>,
return_type: Option<String>,
) -> JavaMethod {
JavaMethod {
method_name: self.constants.put(&name),
param_types: param_types
.into_iter()
.map(|s| self.constants.put(&s))
.collect(),
return_type: return_type.map(|s| self.constants.put(&s)),
}
}
pub fn new_field(&mut self, field_name: String, field_type: String) -> JavaField {
JavaField {
field_name: self.constants.put(&field_name),
field_type: self.constants.put(&field_type),
}
}
}
#[derive(Clone)]
pub struct JavaClass {
pub class_name: IndexedString,
pub interfaces: Vec<IndexedString>,
pub superclass: IndexedString,
pub fields: Vec<JavaField>,
pub methods: Vec<JavaMethod>,
}
#[derive(Clone)]
pub struct JavaField {
pub field_name: IndexedString,
pub field_type: IndexedString,
}
#[derive(Clone)]
pub struct JavaMethod {
pub method_name: IndexedString,
pub param_types: Vec<IndexedString>,
pub return_type: Option<IndexedString>,
}
impl JavaClass {
pub fn class_name<'a>(&self, pool: &'a StringConstants) -> &'a str {
self.class_name
.get_str(pool)
.expect("Class name not in constants.")
}
pub fn get_package_name(&self, pool: &StringConstants) -> Option<String> {
self.class_name.get_str(pool)
.and_then(|name| Self::parse_package(name))
}
pub fn parse_package(class_name: &str) -> Option<String> {
if let Some(slash) = class_name.rfind("/") {
return Some(class_name[0..slash].replace("/", "."));
}
None
}
}
impl JavaField {
pub fn field_name<'a>(&self, pool: &'a StringConstants) -> &'a str {
self.field_name
.get_str(pool)
.expect("Field name not in constants.")
}
pub fn field_type<'a>(&self, pool: &'a StringConstants) -> &'a str {
self.field_type
.get_str(pool)
.expect("Field type not in constants.")
}
}
impl JavaMethod {
pub fn method_name<'a>(&self, pool: &'a StringConstants) -> &'a str {
self.method_name
.get_str(pool)
.expect("Method name not in constants.")
}
pub fn param_types<'a>(&self, pool: &'a StringConstants) -> Vec<&'a str> {
self.param_types
.iter()
.map(|index| -> &str {
index
.get_str(pool)
.expect("Parameter name not in constants.")
})
.collect()
}
pub fn return_type<'a>(&self, pool: &'a StringConstants) -> Option<&'a str> {
match &self.return_type {
Some(i) => i.get_str(pool),
None => None,
}
}
pub fn signature(&self, pool: &StringConstants) -> String {
let mut text = String::new();
text.push_str(self.method_name(pool));
text.push('(');
for (i, p) in self.param_types(pool).iter().enumerate() {
if i > 0 {
text.push_str(", ");
}
text.push_str(p);
}
text.push(')');
if let Some(ret) = self.return_type(pool) {
text.push_str(": ");
text.push_str(ret);
}
text
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ServiceInterfaces {
mapping: HashMap<String, Vec<String>>,
}
impl ServiceInterfaces {
pub fn new() -> Self {
Self {
mapping: HashMap::new(),
}
}
pub fn add(&mut self, interface: &str, implementation: &str) {
if !self.mapping.contains_key(interface) {
self.mapping
.insert(String::from(interface), vec![String::from(implementation)]);
return;
}
self.mapping
.get_mut(interface)
.unwrap()
.push(String::from(implementation));
}
pub fn add_all(&mut self, interface: &str, implementations: Vec<String>) {
if !self.mapping.contains_key(interface) {
self.mapping
.insert(String::from(interface), implementations);
return;
}
self.mapping
.get_mut(interface)
.unwrap()
.extend(implementations);
}
pub fn interfaces(&self) -> Vec<&str> {
return self.mapping.keys().map(|s| -> &str { s }).collect();
}
pub fn implementations(&self, interface: &str) -> Vec<&str> {
match self.mapping.get(interface) {
None => vec![],
Some(classes) => classes.iter().map(|s| -> &str { s }).collect(),
}
}
pub fn merge_from(&mut self, services: &ServiceInterfaces) -> () {
for interface in services.interfaces() {
self.add_all(
interface,
services
.implementations(interface)
.iter()
.map(|s| String::from(*s))
.collect(),
);
}
}
}
|
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.
use crate::lexer::preprocessor::context::PreprocContext;
use crate::lexer::{Lexer, LocToken, Token};
use crate::parser::attributes::{Attributes, AttributesParser};
use crate::parser::expression::{
ExprNode, ExpressionParser, Operator, Parameters, ParametersParser,
};
use crate::parser::initializer::{Initializer, InitializerParser};
use crate::parser::names::{Name, OperatorParser, Qualified, QualifiedParser};
use crate::parser::statement::{Compound, CompoundStmtParser};
use bitflags::bitflags;
use super::super::r#type::{BaseType, CVQualifier, Type};
use super::decl::{Identifier, TypeDeclarator, TypeDeclaratorParser};
use super::specifier::Specifier;
#[derive(Clone, Debug, PartialEq)]
pub struct Parameter {
pub(crate) attributes: Option<Attributes>,
pub(crate) decl: TypeDeclarator,
}
#[derive(Clone, Debug, PartialEq)]
pub enum RefQualifier {
None,
LValue,
RValue,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Exception {
Noexcept(Option<ExprNode>),
Throw(Option<Parameters>),
}
bitflags! {
pub struct VirtSpecifier: u8 {
const FINAL = 0b1;
const OVERRIDE = 0b10;
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum FunStatus {
None,
Pure,
Default,
Delete,
}
impl VirtSpecifier {
pub(crate) fn from_tok(&mut self, tok: &Token) -> bool {
match tok {
Token::Final => {
*self |= VirtSpecifier::FINAL;
true
}
Token::Override => {
*self |= VirtSpecifier::OVERRIDE;
true
}
_ => false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CtorInit {
pub name: Qualified,
pub init: Initializer,
}
pub type CtorInitializers = Vec<CtorInit>;
pub struct CtorInitializersParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> CtorInitializersParser<'a, 'b, PC> {
pub(crate) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(crate) fn parse(
self,
tok: Option<LocToken>,
) -> (Option<LocToken>, Option<CtorInitializers>) {
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
if tok.tok != Token::Colon {
return (Some(tok), None);
}
let mut inits = Vec::new();
let mut tok = Some(tok);
loop {
let qp = QualifiedParser::new(self.lexer);
let (tk, name) = qp.parse(tok, None);
let name = if let Some(name) = name {
name
} else {
unreachable!("Invalid ctor initializer: {:?}", tk);
};
let ip = InitializerParser::new(self.lexer);
let (tk, init) = ip.parse(tk);
let init = if let Some(init) = init {
init
} else {
unreachable!("Invalid ctor initializer: {:?}", tk);
};
inits.push(CtorInit { name, init });
let tk = tk.unwrap_or_else(|| self.lexer.next_useful());
if tk.tok != Token::Comma {
return (Some(tk), Some(inits));
}
tok = Some(tk);
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum FunctionId {
Qualified(Qualified),
Operator(Operator),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Function {
pub return_type: Option<Type>,
pub params: Vec<Parameter>,
pub cv: CVQualifier,
pub refq: RefQualifier,
pub except: Option<Exception>,
pub attributes: Option<Attributes>,
pub trailing: Option<ExprNode>, // TODO: type here not an expression
pub virt_specifier: VirtSpecifier,
pub status: FunStatus,
pub requires: Option<ExprNode>,
pub ctor_init: Option<CtorInitializers>,
pub body: Option<Compound>,
}
pub struct ParameterListParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> ParameterListParser<'a, 'b, PC> {
pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(super) fn parse(
self,
tok: Option<LocToken>,
skip_lparen: bool,
) -> (Option<LocToken>, Option<Vec<Parameter>>) {
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
let mut tok = if skip_lparen {
Some(tok)
} else {
if tok.tok != Token::LeftParen {
return (Some(tok), None);
}
None
};
let mut params = Vec::new();
loop {
let ap = AttributesParser::new(self.lexer);
let (tk, attributes) = ap.parse(tok);
let dp = TypeDeclaratorParser::new(self.lexer);
let (tk, decl) = dp.parse(tk, None);
let decl = if let Some(decl) = decl {
decl
} else {
return (None, Some(params));
};
let tk = tk.unwrap_or_else(|| self.lexer.next_useful());
match tk.tok {
Token::Comma => {
params.push(Parameter { attributes, decl });
}
Token::RightParen => {
params.push(Parameter { attributes, decl });
return (None, Some(params));
}
_ => {
unreachable!("Parameter list: {:?}", tk);
}
}
tok = None;
}
}
}
pub struct FunctionParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> FunctionParser<'a, 'b, PC> {
pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(super) fn parse(
self,
tok: Option<LocToken>,
skip_lparen: bool,
) -> (Option<LocToken>, Option<Function>) {
let plp = ParameterListParser::new(self.lexer);
let (tok, params) = plp.parse(tok, skip_lparen);
let params = if let Some(params) = params {
params
} else {
return (tok, None);
};
let mut tok = tok.unwrap_or_else(|| self.lexer.next_useful());
let mut cv = CVQualifier::empty();
loop {
if !cv.from_tok(&tok.tok) {
break;
}
tok = self.lexer.next_useful();
}
let (tok, refq) = match tok.tok {
Token::And => (None, RefQualifier::LValue),
Token::AndAnd => (None, RefQualifier::RValue),
_ => (Some(tok), RefQualifier::None),
};
let ep = ExceptionParser::new(self.lexer);
let (tok, except) = ep.parse(tok);
let ap = AttributesParser::new(self.lexer);
let (tok, attributes) = ap.parse(tok);
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
let (tok, trailing) = if tok.tok == Token::Arrow {
let mut ep = ExpressionParser::new(self.lexer, Token::RightParen);
ep.parse(None)
} else {
(Some(tok), None)
};
let mut virt_specifier = VirtSpecifier::empty();
let mut tok = tok.unwrap_or_else(|| self.lexer.next_useful());
while virt_specifier.from_tok(&tok.tok) {
tok = self.lexer.next_useful();
}
let (tok, requires) = if tok.tok == Token::Requires {
let mut ep = ExpressionParser::new(self.lexer, Token::Eof);
let (tok, e) = ep.parse(None);
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
(tok, e)
} else {
(tok, None)
};
let (tok, status) = if tok.tok == Token::Equal {
let tok = self.lexer.next_useful();
match tok.tok {
Token::Default => (self.lexer.next_useful(), FunStatus::Default),
Token::Delete => (self.lexer.next_useful(), FunStatus::Delete),
Token::LiteralInt(0) => (self.lexer.next_useful(), FunStatus::Pure),
_ => {
unreachable!("Invalid token in function declaration: {:?}", tok);
}
}
} else {
(tok, FunStatus::None)
};
let cip = CtorInitializersParser::new(self.lexer);
let (tok, ctor_init) = cip.parse(Some(tok));
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
let (tok, body) = if tok.tok == Token::LeftBrace {
let cp = CompoundStmtParser::new(self.lexer);
cp.parse(None)
} else {
(Some(tok), None)
};
let fun = Function {
return_type: None,
params,
cv,
refq,
except,
attributes,
trailing,
virt_specifier,
status,
requires,
ctor_init,
body,
};
(tok, Some(fun))
}
}
pub struct ExceptionParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> ExceptionParser<'a, 'b, PC> {
pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(super) fn parse(self, tok: Option<LocToken>) -> (Option<LocToken>, Option<Exception>) {
// noexcept
// noexcept(expression)
// throw() (removed in C++20)
// throw(typeid, typeid, ...)
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
match tok.tok {
Token::Noexcept => {
let tok = self.lexer.next_useful();
if tok.tok == Token::LeftParen {
let mut ep = ExpressionParser::new(self.lexer, Token::RightParen);
let (tok, exp) = ep.parse(None);
(tok, Some(Exception::Noexcept(exp)))
} else {
(Some(tok), Some(Exception::Noexcept(None)))
}
}
Token::Throw => {
let tok = self.lexer.next_useful();
if tok.tok == Token::LeftParen {
let pp = ParametersParser::new(self.lexer, Token::RightParen);
let (tok, params) = pp.parse(None, None);
(tok, Some(Exception::Throw(params)))
} else {
unreachable!("throw must be followed by a (");
}
}
_ => (Some(tok), None),
}
}
}
pub(crate) struct ConvOperatorDeclaratorParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> ConvOperatorDeclaratorParser<'a, 'b, PC> {
pub(crate) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(crate) fn parse(
self,
specifier: Specifier,
name: Option<Qualified>,
tok: Option<LocToken>,
) -> (Option<LocToken>, Option<TypeDeclarator>) {
let (tok, name) = if name.is_none() {
let op = OperatorParser::new(self.lexer);
let (tok, op) = op.parse(tok);
if let Some(op) = op {
(
tok,
Some(Qualified {
names: vec![Name::Operator(Box::new(op))],
}),
)
} else {
return (tok, None);
}
} else {
(tok, name)
};
// attributes
let ap = AttributesParser::new(self.lexer);
let (tok, attributes) = ap.parse(tok);
let fp = FunctionParser::new(self.lexer);
let (tok, function) = fp.parse(tok, false);
if let Some(function) = function {
let typ = Type {
base: BaseType::Function(Box::new(function)),
cv: CVQualifier::empty(),
pointers: None,
};
(
tok,
Some(TypeDeclarator {
typ,
specifier,
identifier: Identifier {
identifier: name,
attributes,
},
init: None,
}),
)
} else {
unreachable!("Invalid token in operator name: {:?}", tok);
}
}
}
|
use tokio::net;
use tokio::prelude::*;
use std::net::SocketAddr;
use tokio::io::Error;
struct ConnectionData
{
d: SocketAddr,
msg: String,
}
struct UDPListener
{
socket: net::UdpSocket
}
impl UDPListener
{
async fn new() -> UDPListener//here may be an address
{
UDPListener { socket: net::UdpSocket::bind("127.0.0.1:9878").await.expect("Failed to initialize socket with address: 127.0.0.1:9878") }
}
pub async fn receive_connection(&mut self) -> Result<ConnectionData, Error>
{
let mut buf = [0; 1024];
match self.socket.recv_from(&mut buf).await {
Ok((l, a)) => {
let buf_new = &mut buf[..l];
let buf_result = std::str::from_utf8(&buf_new).expect("data provided till connection is corrupted");
Ok(ConnectionData { d: a, msg: buf_result.to_string() })
}
Err(err) => {
Err(err)
}
}
}
}
#[tokio::main]
async fn main() {
let mut udp_connection_listener = UDPListener::new().await;
let handler = tokio::spawn(async move {
loop {
println!("waiting for connection...");
match udp_connection_listener.receive_connection().await {
Ok(a) => {
println!("congrats msg:{0} and address:{1}", a.msg, a.d.to_string());
if a.msg == "exit"
{
break;
}
}
Err(err) => { println!("Connection Error: {}", err) }
};
}
});
let result = handler.await;
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qmetaobject.h
// dst-file: /src/core/qmetaobject.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::qobjectdefs::*; // 773
use super::qbytearray::*; // 773
// use super::qlist::*; // 775
use super::qobject::*; // 773
use super::qvariant::*; // 773
// use super::qmetaobject::QMetaEnum; // 773
// use super::qmetaobject::QMetaMethod; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QMetaEnum_Class_Size() -> c_int;
// proto: int QMetaEnum::value(int index);
fn C_ZNK9QMetaEnum5valueEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: const char * QMetaEnum::name();
fn C_ZNK9QMetaEnum4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: bool QMetaEnum::isFlag();
fn C_ZNK9QMetaEnum6isFlagEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: const char * QMetaEnum::scope();
fn C_ZNK9QMetaEnum5scopeEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: int QMetaEnum::keyToValue(const char * key, bool * ok);
fn C_ZNK9QMetaEnum10keyToValueEPKcPb(qthis: u64 /* *mut c_void*/, arg0: *mut c_char, arg1: *mut c_char) -> c_int;
// proto: const QMetaObject * QMetaEnum::enclosingMetaObject();
fn C_ZNK9QMetaEnum19enclosingMetaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QByteArray QMetaEnum::valueToKeys(int value);
fn C_ZNK9QMetaEnum11valueToKeysEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QMetaEnum::QMetaEnum();
fn C_ZN9QMetaEnumC2Ev() -> u64;
// proto: int QMetaEnum::keysToValue(const char * keys, bool * ok);
fn C_ZNK9QMetaEnum11keysToValueEPKcPb(qthis: u64 /* *mut c_void*/, arg0: *mut c_char, arg1: *mut c_char) -> c_int;
// proto: const char * QMetaEnum::key(int index);
fn C_ZNK9QMetaEnum3keyEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_char;
// proto: const char * QMetaEnum::valueToKey(int value);
fn C_ZNK9QMetaEnum10valueToKeyEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_char;
// proto: int QMetaEnum::keyCount();
fn C_ZNK9QMetaEnum8keyCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMetaEnum::isValid();
fn C_ZNK9QMetaEnum7isValidEv(qthis: u64 /* *mut c_void*/) -> c_char;
fn QMetaClassInfo_Class_Size() -> c_int;
// proto: void QMetaClassInfo::QMetaClassInfo();
fn C_ZN14QMetaClassInfoC2Ev() -> u64;
// proto: const QMetaObject * QMetaClassInfo::enclosingMetaObject();
fn C_ZNK14QMetaClassInfo19enclosingMetaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const char * QMetaClassInfo::name();
fn C_ZNK14QMetaClassInfo4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: const char * QMetaClassInfo::value();
fn C_ZNK14QMetaClassInfo5valueEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
fn QMetaMethod_Class_Size() -> c_int;
// proto: QList<QByteArray> QMetaMethod::parameterTypes();
fn C_ZNK11QMetaMethod14parameterTypesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QList<QByteArray> QMetaMethod::parameterNames();
fn C_ZNK11QMetaMethod14parameterNamesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QByteArray QMetaMethod::methodSignature();
fn C_ZNK11QMetaMethod15methodSignatureEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const char * QMetaMethod::typeName();
fn C_ZNK11QMetaMethod8typeNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: int QMetaMethod::attributes();
fn C_ZNK11QMetaMethod10attributesEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QMetaMethod::getParameterTypes(int * types);
fn C_ZNK11QMetaMethod17getParameterTypesEPi(qthis: u64 /* *mut c_void*/, arg0: *mut c_int);
// proto: void QMetaMethod::QMetaMethod();
fn C_ZN11QMetaMethodC2Ev() -> u64;
// proto: int QMetaMethod::parameterType(int index);
fn C_ZNK11QMetaMethod13parameterTypeEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: QByteArray QMetaMethod::name();
fn C_ZNK11QMetaMethod4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QMetaMethod::returnType();
fn C_ZNK11QMetaMethod10returnTypeEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaMethod::methodIndex();
fn C_ZNK11QMetaMethod11methodIndexEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaMethod::parameterCount();
fn C_ZNK11QMetaMethod14parameterCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: const QMetaObject * QMetaMethod::enclosingMetaObject();
fn C_ZNK11QMetaMethod19enclosingMetaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QMetaMethod::revision();
fn C_ZNK11QMetaMethod8revisionEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: const char * QMetaMethod::tag();
fn C_ZNK11QMetaMethod3tagEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: bool QMetaMethod::isValid();
fn C_ZNK11QMetaMethod7isValidEv(qthis: u64 /* *mut c_void*/) -> c_char;
fn QMetaProperty_Class_Size() -> c_int;
// proto: bool QMetaProperty::isEnumType();
fn C_ZNK13QMetaProperty10isEnumTypeEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QMetaProperty::QMetaProperty();
fn C_ZN13QMetaPropertyC2Ev() -> u64;
// proto: bool QMetaProperty::isValid();
fn C_ZNK13QMetaProperty7isValidEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QVariant QMetaProperty::readOnGadget(const void * gadget);
fn C_ZNK13QMetaProperty12readOnGadgetEPKv(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: const QMetaObject * QMetaProperty::enclosingMetaObject();
fn C_ZNK13QMetaProperty19enclosingMetaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QMetaProperty::resetOnGadget(void * gadget);
fn C_ZNK13QMetaProperty13resetOnGadgetEPv(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: int QMetaProperty::propertyIndex();
fn C_ZNK13QMetaProperty13propertyIndexEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMetaProperty::isStored(const QObject * obj);
fn C_ZNK13QMetaProperty8isStoredEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: QMetaEnum QMetaProperty::enumerator();
fn C_ZNK13QMetaProperty10enumeratorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QMetaProperty::write(QObject * obj, const QVariant & value);
fn C_ZNK13QMetaProperty5writeEP7QObjectRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: bool QMetaProperty::isResettable();
fn C_ZNK13QMetaProperty12isResettableEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QMetaProperty::isEditable(const QObject * obj);
fn C_ZNK13QMetaProperty10isEditableEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: bool QMetaProperty::hasStdCppSet();
fn C_ZNK13QMetaProperty12hasStdCppSetEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QMetaProperty::hasNotifySignal();
fn C_ZNK13QMetaProperty15hasNotifySignalEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QMetaProperty::isConstant();
fn C_ZNK13QMetaProperty10isConstantEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: const char * QMetaProperty::typeName();
fn C_ZNK13QMetaProperty8typeNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: bool QMetaProperty::isReadable();
fn C_ZNK13QMetaProperty10isReadableEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QMetaProperty::userType();
fn C_ZNK13QMetaProperty8userTypeEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMetaProperty::isWritable();
fn C_ZNK13QMetaProperty10isWritableEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QMetaProperty::writeOnGadget(void * gadget, const QVariant & value);
fn C_ZNK13QMetaProperty13writeOnGadgetEPvRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: int QMetaProperty::notifySignalIndex();
fn C_ZNK13QMetaProperty17notifySignalIndexEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMetaProperty::isUser(const QObject * obj);
fn C_ZNK13QMetaProperty6isUserEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: bool QMetaProperty::isFlagType();
fn C_ZNK13QMetaProperty10isFlagTypeEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QMetaProperty::isFinal();
fn C_ZNK13QMetaProperty7isFinalEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: const char * QMetaProperty::name();
fn C_ZNK13QMetaProperty4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: bool QMetaProperty::reset(QObject * obj);
fn C_ZNK13QMetaProperty5resetEP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: int QMetaProperty::revision();
fn C_ZNK13QMetaProperty8revisionEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMetaProperty::isScriptable(const QObject * obj);
fn C_ZNK13QMetaProperty12isScriptableEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: QVariant QMetaProperty::read(const QObject * obj);
fn C_ZNK13QMetaProperty4readEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QMetaMethod QMetaProperty::notifySignal();
fn C_ZNK13QMetaProperty12notifySignalEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QMetaProperty::isDesignable(const QObject * obj);
fn C_ZNK13QMetaProperty12isDesignableEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
} // <= ext block end
// body block begin =>
// class sizeof(QMetaEnum)=16
#[derive(Default)]
pub struct QMetaEnum {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QMetaClassInfo)=16
#[derive(Default)]
pub struct QMetaClassInfo {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QMetaMethod)=16
#[derive(Default)]
pub struct QMetaMethod {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QMetaProperty)=32
#[derive(Default)]
pub struct QMetaProperty {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QMetaEnum {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMetaEnum {
return QMetaEnum{qclsinst: qthis, ..Default::default()};
}
}
// proto: int QMetaEnum::value(int index);
impl /*struct*/ QMetaEnum {
pub fn value<RetType, T: QMetaEnum_value<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.value(self);
// return 1;
}
}
pub trait QMetaEnum_value<RetType> {
fn value(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: int QMetaEnum::value(int index);
impl<'a> /*trait*/ QMetaEnum_value<i32> for (i32) {
fn value(self , rsthis: & QMetaEnum) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum5valueEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK9QMetaEnum5valueEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: const char * QMetaEnum::name();
impl /*struct*/ QMetaEnum {
pub fn name<RetType, T: QMetaEnum_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QMetaEnum_name<RetType> {
fn name(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: const char * QMetaEnum::name();
impl<'a> /*trait*/ QMetaEnum_name<String> for () {
fn name(self , rsthis: & QMetaEnum) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum4nameEv()};
let mut ret = unsafe {C_ZNK9QMetaEnum4nameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: bool QMetaEnum::isFlag();
impl /*struct*/ QMetaEnum {
pub fn isFlag<RetType, T: QMetaEnum_isFlag<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isFlag(self);
// return 1;
}
}
pub trait QMetaEnum_isFlag<RetType> {
fn isFlag(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: bool QMetaEnum::isFlag();
impl<'a> /*trait*/ QMetaEnum_isFlag<i8> for () {
fn isFlag(self , rsthis: & QMetaEnum) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum6isFlagEv()};
let mut ret = unsafe {C_ZNK9QMetaEnum6isFlagEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: const char * QMetaEnum::scope();
impl /*struct*/ QMetaEnum {
pub fn scope<RetType, T: QMetaEnum_scope<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.scope(self);
// return 1;
}
}
pub trait QMetaEnum_scope<RetType> {
fn scope(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: const char * QMetaEnum::scope();
impl<'a> /*trait*/ QMetaEnum_scope<String> for () {
fn scope(self , rsthis: & QMetaEnum) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum5scopeEv()};
let mut ret = unsafe {C_ZNK9QMetaEnum5scopeEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: int QMetaEnum::keyToValue(const char * key, bool * ok);
impl /*struct*/ QMetaEnum {
pub fn keyToValue<RetType, T: QMetaEnum_keyToValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keyToValue(self);
// return 1;
}
}
pub trait QMetaEnum_keyToValue<RetType> {
fn keyToValue(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: int QMetaEnum::keyToValue(const char * key, bool * ok);
impl<'a> /*trait*/ QMetaEnum_keyToValue<i32> for (&'a String, Option<&'a mut Vec<i8>>) {
fn keyToValue(self , rsthis: & QMetaEnum) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum10keyToValueEPKcPb()};
let arg0 = self.0.as_ptr() as *mut c_char;
let arg1 = (if self.1.is_none() {0 as *const i8} else {self.1.unwrap().as_ptr()}) as *mut c_char;
let mut ret = unsafe {C_ZNK9QMetaEnum10keyToValueEPKcPb(rsthis.qclsinst, arg0, arg1)};
return ret as i32; // 1
// return 1;
}
}
// proto: const QMetaObject * QMetaEnum::enclosingMetaObject();
impl /*struct*/ QMetaEnum {
pub fn enclosingMetaObject<RetType, T: QMetaEnum_enclosingMetaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enclosingMetaObject(self);
// return 1;
}
}
pub trait QMetaEnum_enclosingMetaObject<RetType> {
fn enclosingMetaObject(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: const QMetaObject * QMetaEnum::enclosingMetaObject();
impl<'a> /*trait*/ QMetaEnum_enclosingMetaObject<QMetaObject> for () {
fn enclosingMetaObject(self , rsthis: & QMetaEnum) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum19enclosingMetaObjectEv()};
let mut ret = unsafe {C_ZNK9QMetaEnum19enclosingMetaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QByteArray QMetaEnum::valueToKeys(int value);
impl /*struct*/ QMetaEnum {
pub fn valueToKeys<RetType, T: QMetaEnum_valueToKeys<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.valueToKeys(self);
// return 1;
}
}
pub trait QMetaEnum_valueToKeys<RetType> {
fn valueToKeys(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: QByteArray QMetaEnum::valueToKeys(int value);
impl<'a> /*trait*/ QMetaEnum_valueToKeys<QByteArray> for (i32) {
fn valueToKeys(self , rsthis: & QMetaEnum) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum11valueToKeysEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK9QMetaEnum11valueToKeysEi(rsthis.qclsinst, arg0)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QMetaEnum::QMetaEnum();
impl /*struct*/ QMetaEnum {
pub fn new<T: QMetaEnum_new>(value: T) -> QMetaEnum {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMetaEnum_new {
fn new(self) -> QMetaEnum;
}
// proto: void QMetaEnum::QMetaEnum();
impl<'a> /*trait*/ QMetaEnum_new for () {
fn new(self) -> QMetaEnum {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMetaEnumC2Ev()};
let ctysz: c_int = unsafe{QMetaEnum_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN9QMetaEnumC2Ev()};
let rsthis = QMetaEnum{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QMetaEnum::keysToValue(const char * keys, bool * ok);
impl /*struct*/ QMetaEnum {
pub fn keysToValue<RetType, T: QMetaEnum_keysToValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keysToValue(self);
// return 1;
}
}
pub trait QMetaEnum_keysToValue<RetType> {
fn keysToValue(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: int QMetaEnum::keysToValue(const char * keys, bool * ok);
impl<'a> /*trait*/ QMetaEnum_keysToValue<i32> for (&'a String, Option<&'a mut Vec<i8>>) {
fn keysToValue(self , rsthis: & QMetaEnum) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum11keysToValueEPKcPb()};
let arg0 = self.0.as_ptr() as *mut c_char;
let arg1 = (if self.1.is_none() {0 as *const i8} else {self.1.unwrap().as_ptr()}) as *mut c_char;
let mut ret = unsafe {C_ZNK9QMetaEnum11keysToValueEPKcPb(rsthis.qclsinst, arg0, arg1)};
return ret as i32; // 1
// return 1;
}
}
// proto: const char * QMetaEnum::key(int index);
impl /*struct*/ QMetaEnum {
pub fn key<RetType, T: QMetaEnum_key<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.key(self);
// return 1;
}
}
pub trait QMetaEnum_key<RetType> {
fn key(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: const char * QMetaEnum::key(int index);
impl<'a> /*trait*/ QMetaEnum_key<String> for (i32) {
fn key(self , rsthis: & QMetaEnum) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum3keyEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK9QMetaEnum3keyEi(rsthis.qclsinst, arg0)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: const char * QMetaEnum::valueToKey(int value);
impl /*struct*/ QMetaEnum {
pub fn valueToKey<RetType, T: QMetaEnum_valueToKey<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.valueToKey(self);
// return 1;
}
}
pub trait QMetaEnum_valueToKey<RetType> {
fn valueToKey(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: const char * QMetaEnum::valueToKey(int value);
impl<'a> /*trait*/ QMetaEnum_valueToKey<String> for (i32) {
fn valueToKey(self , rsthis: & QMetaEnum) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum10valueToKeyEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK9QMetaEnum10valueToKeyEi(rsthis.qclsinst, arg0)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: int QMetaEnum::keyCount();
impl /*struct*/ QMetaEnum {
pub fn keyCount<RetType, T: QMetaEnum_keyCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keyCount(self);
// return 1;
}
}
pub trait QMetaEnum_keyCount<RetType> {
fn keyCount(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: int QMetaEnum::keyCount();
impl<'a> /*trait*/ QMetaEnum_keyCount<i32> for () {
fn keyCount(self , rsthis: & QMetaEnum) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum8keyCountEv()};
let mut ret = unsafe {C_ZNK9QMetaEnum8keyCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMetaEnum::isValid();
impl /*struct*/ QMetaEnum {
pub fn isValid<RetType, T: QMetaEnum_isValid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isValid(self);
// return 1;
}
}
pub trait QMetaEnum_isValid<RetType> {
fn isValid(self , rsthis: & QMetaEnum) -> RetType;
}
// proto: bool QMetaEnum::isValid();
impl<'a> /*trait*/ QMetaEnum_isValid<i8> for () {
fn isValid(self , rsthis: & QMetaEnum) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMetaEnum7isValidEv()};
let mut ret = unsafe {C_ZNK9QMetaEnum7isValidEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
impl /*struct*/ QMetaClassInfo {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMetaClassInfo {
return QMetaClassInfo{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QMetaClassInfo::QMetaClassInfo();
impl /*struct*/ QMetaClassInfo {
pub fn new<T: QMetaClassInfo_new>(value: T) -> QMetaClassInfo {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMetaClassInfo_new {
fn new(self) -> QMetaClassInfo;
}
// proto: void QMetaClassInfo::QMetaClassInfo();
impl<'a> /*trait*/ QMetaClassInfo_new for () {
fn new(self) -> QMetaClassInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QMetaClassInfoC2Ev()};
let ctysz: c_int = unsafe{QMetaClassInfo_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN14QMetaClassInfoC2Ev()};
let rsthis = QMetaClassInfo{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QMetaClassInfo::enclosingMetaObject();
impl /*struct*/ QMetaClassInfo {
pub fn enclosingMetaObject<RetType, T: QMetaClassInfo_enclosingMetaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enclosingMetaObject(self);
// return 1;
}
}
pub trait QMetaClassInfo_enclosingMetaObject<RetType> {
fn enclosingMetaObject(self , rsthis: & QMetaClassInfo) -> RetType;
}
// proto: const QMetaObject * QMetaClassInfo::enclosingMetaObject();
impl<'a> /*trait*/ QMetaClassInfo_enclosingMetaObject<QMetaObject> for () {
fn enclosingMetaObject(self , rsthis: & QMetaClassInfo) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QMetaClassInfo19enclosingMetaObjectEv()};
let mut ret = unsafe {C_ZNK14QMetaClassInfo19enclosingMetaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const char * QMetaClassInfo::name();
impl /*struct*/ QMetaClassInfo {
pub fn name<RetType, T: QMetaClassInfo_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QMetaClassInfo_name<RetType> {
fn name(self , rsthis: & QMetaClassInfo) -> RetType;
}
// proto: const char * QMetaClassInfo::name();
impl<'a> /*trait*/ QMetaClassInfo_name<String> for () {
fn name(self , rsthis: & QMetaClassInfo) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QMetaClassInfo4nameEv()};
let mut ret = unsafe {C_ZNK14QMetaClassInfo4nameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: const char * QMetaClassInfo::value();
impl /*struct*/ QMetaClassInfo {
pub fn value<RetType, T: QMetaClassInfo_value<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.value(self);
// return 1;
}
}
pub trait QMetaClassInfo_value<RetType> {
fn value(self , rsthis: & QMetaClassInfo) -> RetType;
}
// proto: const char * QMetaClassInfo::value();
impl<'a> /*trait*/ QMetaClassInfo_value<String> for () {
fn value(self , rsthis: & QMetaClassInfo) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QMetaClassInfo5valueEv()};
let mut ret = unsafe {C_ZNK14QMetaClassInfo5valueEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
impl /*struct*/ QMetaMethod {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMetaMethod {
return QMetaMethod{qclsinst: qthis, ..Default::default()};
}
}
// proto: QList<QByteArray> QMetaMethod::parameterTypes();
impl /*struct*/ QMetaMethod {
pub fn parameterTypes<RetType, T: QMetaMethod_parameterTypes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.parameterTypes(self);
// return 1;
}
}
pub trait QMetaMethod_parameterTypes<RetType> {
fn parameterTypes(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: QList<QByteArray> QMetaMethod::parameterTypes();
impl<'a> /*trait*/ QMetaMethod_parameterTypes<u64> for () {
fn parameterTypes(self , rsthis: & QMetaMethod) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod14parameterTypesEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod14parameterTypesEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: QList<QByteArray> QMetaMethod::parameterNames();
impl /*struct*/ QMetaMethod {
pub fn parameterNames<RetType, T: QMetaMethod_parameterNames<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.parameterNames(self);
// return 1;
}
}
pub trait QMetaMethod_parameterNames<RetType> {
fn parameterNames(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: QList<QByteArray> QMetaMethod::parameterNames();
impl<'a> /*trait*/ QMetaMethod_parameterNames<u64> for () {
fn parameterNames(self , rsthis: & QMetaMethod) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod14parameterNamesEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod14parameterNamesEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: QByteArray QMetaMethod::methodSignature();
impl /*struct*/ QMetaMethod {
pub fn methodSignature<RetType, T: QMetaMethod_methodSignature<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.methodSignature(self);
// return 1;
}
}
pub trait QMetaMethod_methodSignature<RetType> {
fn methodSignature(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: QByteArray QMetaMethod::methodSignature();
impl<'a> /*trait*/ QMetaMethod_methodSignature<QByteArray> for () {
fn methodSignature(self , rsthis: & QMetaMethod) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod15methodSignatureEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod15methodSignatureEv(rsthis.qclsinst)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const char * QMetaMethod::typeName();
impl /*struct*/ QMetaMethod {
pub fn typeName<RetType, T: QMetaMethod_typeName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.typeName(self);
// return 1;
}
}
pub trait QMetaMethod_typeName<RetType> {
fn typeName(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: const char * QMetaMethod::typeName();
impl<'a> /*trait*/ QMetaMethod_typeName<String> for () {
fn typeName(self , rsthis: & QMetaMethod) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod8typeNameEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod8typeNameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: int QMetaMethod::attributes();
impl /*struct*/ QMetaMethod {
pub fn attributes<RetType, T: QMetaMethod_attributes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.attributes(self);
// return 1;
}
}
pub trait QMetaMethod_attributes<RetType> {
fn attributes(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: int QMetaMethod::attributes();
impl<'a> /*trait*/ QMetaMethod_attributes<i32> for () {
fn attributes(self , rsthis: & QMetaMethod) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod10attributesEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod10attributesEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QMetaMethod::getParameterTypes(int * types);
impl /*struct*/ QMetaMethod {
pub fn getParameterTypes<RetType, T: QMetaMethod_getParameterTypes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.getParameterTypes(self);
// return 1;
}
}
pub trait QMetaMethod_getParameterTypes<RetType> {
fn getParameterTypes(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: void QMetaMethod::getParameterTypes(int * types);
impl<'a> /*trait*/ QMetaMethod_getParameterTypes<()> for (&'a mut Vec<i32>) {
fn getParameterTypes(self , rsthis: & QMetaMethod) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod17getParameterTypesEPi()};
let arg0 = self.as_ptr() as *mut c_int;
unsafe {C_ZNK11QMetaMethod17getParameterTypesEPi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QMetaMethod::QMetaMethod();
impl /*struct*/ QMetaMethod {
pub fn new<T: QMetaMethod_new>(value: T) -> QMetaMethod {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMetaMethod_new {
fn new(self) -> QMetaMethod;
}
// proto: void QMetaMethod::QMetaMethod();
impl<'a> /*trait*/ QMetaMethod_new for () {
fn new(self) -> QMetaMethod {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QMetaMethodC2Ev()};
let ctysz: c_int = unsafe{QMetaMethod_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN11QMetaMethodC2Ev()};
let rsthis = QMetaMethod{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QMetaMethod::parameterType(int index);
impl /*struct*/ QMetaMethod {
pub fn parameterType<RetType, T: QMetaMethod_parameterType<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.parameterType(self);
// return 1;
}
}
pub trait QMetaMethod_parameterType<RetType> {
fn parameterType(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: int QMetaMethod::parameterType(int index);
impl<'a> /*trait*/ QMetaMethod_parameterType<i32> for (i32) {
fn parameterType(self , rsthis: & QMetaMethod) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod13parameterTypeEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QMetaMethod13parameterTypeEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QByteArray QMetaMethod::name();
impl /*struct*/ QMetaMethod {
pub fn name<RetType, T: QMetaMethod_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QMetaMethod_name<RetType> {
fn name(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: QByteArray QMetaMethod::name();
impl<'a> /*trait*/ QMetaMethod_name<QByteArray> for () {
fn name(self , rsthis: & QMetaMethod) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod4nameEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod4nameEv(rsthis.qclsinst)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QMetaMethod::returnType();
impl /*struct*/ QMetaMethod {
pub fn returnType<RetType, T: QMetaMethod_returnType<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.returnType(self);
// return 1;
}
}
pub trait QMetaMethod_returnType<RetType> {
fn returnType(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: int QMetaMethod::returnType();
impl<'a> /*trait*/ QMetaMethod_returnType<i32> for () {
fn returnType(self , rsthis: & QMetaMethod) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod10returnTypeEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod10returnTypeEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaMethod::methodIndex();
impl /*struct*/ QMetaMethod {
pub fn methodIndex<RetType, T: QMetaMethod_methodIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.methodIndex(self);
// return 1;
}
}
pub trait QMetaMethod_methodIndex<RetType> {
fn methodIndex(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: int QMetaMethod::methodIndex();
impl<'a> /*trait*/ QMetaMethod_methodIndex<i32> for () {
fn methodIndex(self , rsthis: & QMetaMethod) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod11methodIndexEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod11methodIndexEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaMethod::parameterCount();
impl /*struct*/ QMetaMethod {
pub fn parameterCount<RetType, T: QMetaMethod_parameterCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.parameterCount(self);
// return 1;
}
}
pub trait QMetaMethod_parameterCount<RetType> {
fn parameterCount(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: int QMetaMethod::parameterCount();
impl<'a> /*trait*/ QMetaMethod_parameterCount<i32> for () {
fn parameterCount(self , rsthis: & QMetaMethod) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod14parameterCountEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod14parameterCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: const QMetaObject * QMetaMethod::enclosingMetaObject();
impl /*struct*/ QMetaMethod {
pub fn enclosingMetaObject<RetType, T: QMetaMethod_enclosingMetaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enclosingMetaObject(self);
// return 1;
}
}
pub trait QMetaMethod_enclosingMetaObject<RetType> {
fn enclosingMetaObject(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: const QMetaObject * QMetaMethod::enclosingMetaObject();
impl<'a> /*trait*/ QMetaMethod_enclosingMetaObject<QMetaObject> for () {
fn enclosingMetaObject(self , rsthis: & QMetaMethod) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod19enclosingMetaObjectEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod19enclosingMetaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QMetaMethod::revision();
impl /*struct*/ QMetaMethod {
pub fn revision<RetType, T: QMetaMethod_revision<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.revision(self);
// return 1;
}
}
pub trait QMetaMethod_revision<RetType> {
fn revision(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: int QMetaMethod::revision();
impl<'a> /*trait*/ QMetaMethod_revision<i32> for () {
fn revision(self , rsthis: & QMetaMethod) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod8revisionEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod8revisionEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: const char * QMetaMethod::tag();
impl /*struct*/ QMetaMethod {
pub fn tag<RetType, T: QMetaMethod_tag<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tag(self);
// return 1;
}
}
pub trait QMetaMethod_tag<RetType> {
fn tag(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: const char * QMetaMethod::tag();
impl<'a> /*trait*/ QMetaMethod_tag<String> for () {
fn tag(self , rsthis: & QMetaMethod) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod3tagEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod3tagEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: bool QMetaMethod::isValid();
impl /*struct*/ QMetaMethod {
pub fn isValid<RetType, T: QMetaMethod_isValid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isValid(self);
// return 1;
}
}
pub trait QMetaMethod_isValid<RetType> {
fn isValid(self , rsthis: & QMetaMethod) -> RetType;
}
// proto: bool QMetaMethod::isValid();
impl<'a> /*trait*/ QMetaMethod_isValid<i8> for () {
fn isValid(self , rsthis: & QMetaMethod) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QMetaMethod7isValidEv()};
let mut ret = unsafe {C_ZNK11QMetaMethod7isValidEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
impl /*struct*/ QMetaProperty {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMetaProperty {
return QMetaProperty{qclsinst: qthis, ..Default::default()};
}
}
// proto: bool QMetaProperty::isEnumType();
impl /*struct*/ QMetaProperty {
pub fn isEnumType<RetType, T: QMetaProperty_isEnumType<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEnumType(self);
// return 1;
}
}
pub trait QMetaProperty_isEnumType<RetType> {
fn isEnumType(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isEnumType();
impl<'a> /*trait*/ QMetaProperty_isEnumType<i8> for () {
fn isEnumType(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10isEnumTypeEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty10isEnumTypeEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QMetaProperty::QMetaProperty();
impl /*struct*/ QMetaProperty {
pub fn new<T: QMetaProperty_new>(value: T) -> QMetaProperty {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMetaProperty_new {
fn new(self) -> QMetaProperty;
}
// proto: void QMetaProperty::QMetaProperty();
impl<'a> /*trait*/ QMetaProperty_new for () {
fn new(self) -> QMetaProperty {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QMetaPropertyC2Ev()};
let ctysz: c_int = unsafe{QMetaProperty_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN13QMetaPropertyC2Ev()};
let rsthis = QMetaProperty{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QMetaProperty::isValid();
impl /*struct*/ QMetaProperty {
pub fn isValid<RetType, T: QMetaProperty_isValid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isValid(self);
// return 1;
}
}
pub trait QMetaProperty_isValid<RetType> {
fn isValid(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isValid();
impl<'a> /*trait*/ QMetaProperty_isValid<i8> for () {
fn isValid(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty7isValidEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty7isValidEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QVariant QMetaProperty::readOnGadget(const void * gadget);
impl /*struct*/ QMetaProperty {
pub fn readOnGadget<RetType, T: QMetaProperty_readOnGadget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.readOnGadget(self);
// return 1;
}
}
pub trait QMetaProperty_readOnGadget<RetType> {
fn readOnGadget(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: QVariant QMetaProperty::readOnGadget(const void * gadget);
impl<'a> /*trait*/ QMetaProperty_readOnGadget<QVariant> for (*mut c_void) {
fn readOnGadget(self , rsthis: & QMetaProperty) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty12readOnGadgetEPKv()};
let arg0 = self as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty12readOnGadgetEPKv(rsthis.qclsinst, arg0)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QMetaProperty::enclosingMetaObject();
impl /*struct*/ QMetaProperty {
pub fn enclosingMetaObject<RetType, T: QMetaProperty_enclosingMetaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enclosingMetaObject(self);
// return 1;
}
}
pub trait QMetaProperty_enclosingMetaObject<RetType> {
fn enclosingMetaObject(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: const QMetaObject * QMetaProperty::enclosingMetaObject();
impl<'a> /*trait*/ QMetaProperty_enclosingMetaObject<QMetaObject> for () {
fn enclosingMetaObject(self , rsthis: & QMetaProperty) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty19enclosingMetaObjectEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty19enclosingMetaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QMetaProperty::resetOnGadget(void * gadget);
impl /*struct*/ QMetaProperty {
pub fn resetOnGadget<RetType, T: QMetaProperty_resetOnGadget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.resetOnGadget(self);
// return 1;
}
}
pub trait QMetaProperty_resetOnGadget<RetType> {
fn resetOnGadget(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::resetOnGadget(void * gadget);
impl<'a> /*trait*/ QMetaProperty_resetOnGadget<i8> for (*mut c_void) {
fn resetOnGadget(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty13resetOnGadgetEPv()};
let arg0 = self as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty13resetOnGadgetEPv(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMetaProperty::propertyIndex();
impl /*struct*/ QMetaProperty {
pub fn propertyIndex<RetType, T: QMetaProperty_propertyIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.propertyIndex(self);
// return 1;
}
}
pub trait QMetaProperty_propertyIndex<RetType> {
fn propertyIndex(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: int QMetaProperty::propertyIndex();
impl<'a> /*trait*/ QMetaProperty_propertyIndex<i32> for () {
fn propertyIndex(self , rsthis: & QMetaProperty) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty13propertyIndexEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty13propertyIndexEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isStored(const QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn isStored<RetType, T: QMetaProperty_isStored<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isStored(self);
// return 1;
}
}
pub trait QMetaProperty_isStored<RetType> {
fn isStored(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isStored(const QObject * obj);
impl<'a> /*trait*/ QMetaProperty_isStored<i8> for (Option<&'a QObject>) {
fn isStored(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty8isStoredEPK7QObject()};
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty8isStoredEPK7QObject(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: QMetaEnum QMetaProperty::enumerator();
impl /*struct*/ QMetaProperty {
pub fn enumerator<RetType, T: QMetaProperty_enumerator<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enumerator(self);
// return 1;
}
}
pub trait QMetaProperty_enumerator<RetType> {
fn enumerator(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: QMetaEnum QMetaProperty::enumerator();
impl<'a> /*trait*/ QMetaProperty_enumerator<QMetaEnum> for () {
fn enumerator(self , rsthis: & QMetaProperty) -> QMetaEnum {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10enumeratorEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty10enumeratorEv(rsthis.qclsinst)};
let mut ret1 = QMetaEnum::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QMetaProperty::write(QObject * obj, const QVariant & value);
impl /*struct*/ QMetaProperty {
pub fn write<RetType, T: QMetaProperty_write<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.write(self);
// return 1;
}
}
pub trait QMetaProperty_write<RetType> {
fn write(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::write(QObject * obj, const QVariant & value);
impl<'a> /*trait*/ QMetaProperty_write<i8> for (&'a QObject, &'a QVariant) {
fn write(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty5writeEP7QObjectRK8QVariant()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty5writeEP7QObjectRK8QVariant(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isResettable();
impl /*struct*/ QMetaProperty {
pub fn isResettable<RetType, T: QMetaProperty_isResettable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isResettable(self);
// return 1;
}
}
pub trait QMetaProperty_isResettable<RetType> {
fn isResettable(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isResettable();
impl<'a> /*trait*/ QMetaProperty_isResettable<i8> for () {
fn isResettable(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty12isResettableEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty12isResettableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isEditable(const QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn isEditable<RetType, T: QMetaProperty_isEditable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isEditable(self);
// return 1;
}
}
pub trait QMetaProperty_isEditable<RetType> {
fn isEditable(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isEditable(const QObject * obj);
impl<'a> /*trait*/ QMetaProperty_isEditable<i8> for (Option<&'a QObject>) {
fn isEditable(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10isEditableEPK7QObject()};
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty10isEditableEPK7QObject(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::hasStdCppSet();
impl /*struct*/ QMetaProperty {
pub fn hasStdCppSet<RetType, T: QMetaProperty_hasStdCppSet<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasStdCppSet(self);
// return 1;
}
}
pub trait QMetaProperty_hasStdCppSet<RetType> {
fn hasStdCppSet(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::hasStdCppSet();
impl<'a> /*trait*/ QMetaProperty_hasStdCppSet<i8> for () {
fn hasStdCppSet(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty12hasStdCppSetEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty12hasStdCppSetEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::hasNotifySignal();
impl /*struct*/ QMetaProperty {
pub fn hasNotifySignal<RetType, T: QMetaProperty_hasNotifySignal<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasNotifySignal(self);
// return 1;
}
}
pub trait QMetaProperty_hasNotifySignal<RetType> {
fn hasNotifySignal(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::hasNotifySignal();
impl<'a> /*trait*/ QMetaProperty_hasNotifySignal<i8> for () {
fn hasNotifySignal(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty15hasNotifySignalEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty15hasNotifySignalEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isConstant();
impl /*struct*/ QMetaProperty {
pub fn isConstant<RetType, T: QMetaProperty_isConstant<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isConstant(self);
// return 1;
}
}
pub trait QMetaProperty_isConstant<RetType> {
fn isConstant(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isConstant();
impl<'a> /*trait*/ QMetaProperty_isConstant<i8> for () {
fn isConstant(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10isConstantEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty10isConstantEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: const char * QMetaProperty::typeName();
impl /*struct*/ QMetaProperty {
pub fn typeName<RetType, T: QMetaProperty_typeName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.typeName(self);
// return 1;
}
}
pub trait QMetaProperty_typeName<RetType> {
fn typeName(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: const char * QMetaProperty::typeName();
impl<'a> /*trait*/ QMetaProperty_typeName<String> for () {
fn typeName(self , rsthis: & QMetaProperty) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty8typeNameEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty8typeNameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: bool QMetaProperty::isReadable();
impl /*struct*/ QMetaProperty {
pub fn isReadable<RetType, T: QMetaProperty_isReadable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isReadable(self);
// return 1;
}
}
pub trait QMetaProperty_isReadable<RetType> {
fn isReadable(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isReadable();
impl<'a> /*trait*/ QMetaProperty_isReadable<i8> for () {
fn isReadable(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10isReadableEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty10isReadableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMetaProperty::userType();
impl /*struct*/ QMetaProperty {
pub fn userType<RetType, T: QMetaProperty_userType<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.userType(self);
// return 1;
}
}
pub trait QMetaProperty_userType<RetType> {
fn userType(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: int QMetaProperty::userType();
impl<'a> /*trait*/ QMetaProperty_userType<i32> for () {
fn userType(self , rsthis: & QMetaProperty) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty8userTypeEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty8userTypeEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isWritable();
impl /*struct*/ QMetaProperty {
pub fn isWritable<RetType, T: QMetaProperty_isWritable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isWritable(self);
// return 1;
}
}
pub trait QMetaProperty_isWritable<RetType> {
fn isWritable(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isWritable();
impl<'a> /*trait*/ QMetaProperty_isWritable<i8> for () {
fn isWritable(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10isWritableEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty10isWritableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::writeOnGadget(void * gadget, const QVariant & value);
impl /*struct*/ QMetaProperty {
pub fn writeOnGadget<RetType, T: QMetaProperty_writeOnGadget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.writeOnGadget(self);
// return 1;
}
}
pub trait QMetaProperty_writeOnGadget<RetType> {
fn writeOnGadget(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::writeOnGadget(void * gadget, const QVariant & value);
impl<'a> /*trait*/ QMetaProperty_writeOnGadget<i8> for (*mut c_void, &'a QVariant) {
fn writeOnGadget(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty13writeOnGadgetEPvRK8QVariant()};
let arg0 = self.0 as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty13writeOnGadgetEPvRK8QVariant(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMetaProperty::notifySignalIndex();
impl /*struct*/ QMetaProperty {
pub fn notifySignalIndex<RetType, T: QMetaProperty_notifySignalIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.notifySignalIndex(self);
// return 1;
}
}
pub trait QMetaProperty_notifySignalIndex<RetType> {
fn notifySignalIndex(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: int QMetaProperty::notifySignalIndex();
impl<'a> /*trait*/ QMetaProperty_notifySignalIndex<i32> for () {
fn notifySignalIndex(self , rsthis: & QMetaProperty) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty17notifySignalIndexEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty17notifySignalIndexEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isUser(const QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn isUser<RetType, T: QMetaProperty_isUser<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isUser(self);
// return 1;
}
}
pub trait QMetaProperty_isUser<RetType> {
fn isUser(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isUser(const QObject * obj);
impl<'a> /*trait*/ QMetaProperty_isUser<i8> for (Option<&'a QObject>) {
fn isUser(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty6isUserEPK7QObject()};
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty6isUserEPK7QObject(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isFlagType();
impl /*struct*/ QMetaProperty {
pub fn isFlagType<RetType, T: QMetaProperty_isFlagType<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isFlagType(self);
// return 1;
}
}
pub trait QMetaProperty_isFlagType<RetType> {
fn isFlagType(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isFlagType();
impl<'a> /*trait*/ QMetaProperty_isFlagType<i8> for () {
fn isFlagType(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty10isFlagTypeEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty10isFlagTypeEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isFinal();
impl /*struct*/ QMetaProperty {
pub fn isFinal<RetType, T: QMetaProperty_isFinal<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isFinal(self);
// return 1;
}
}
pub trait QMetaProperty_isFinal<RetType> {
fn isFinal(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isFinal();
impl<'a> /*trait*/ QMetaProperty_isFinal<i8> for () {
fn isFinal(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty7isFinalEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty7isFinalEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: const char * QMetaProperty::name();
impl /*struct*/ QMetaProperty {
pub fn name<RetType, T: QMetaProperty_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QMetaProperty_name<RetType> {
fn name(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: const char * QMetaProperty::name();
impl<'a> /*trait*/ QMetaProperty_name<String> for () {
fn name(self , rsthis: & QMetaProperty) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty4nameEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty4nameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: bool QMetaProperty::reset(QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn reset<RetType, T: QMetaProperty_reset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.reset(self);
// return 1;
}
}
pub trait QMetaProperty_reset<RetType> {
fn reset(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::reset(QObject * obj);
impl<'a> /*trait*/ QMetaProperty_reset<i8> for (&'a QObject) {
fn reset(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty5resetEP7QObject()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty5resetEP7QObject(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMetaProperty::revision();
impl /*struct*/ QMetaProperty {
pub fn revision<RetType, T: QMetaProperty_revision<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.revision(self);
// return 1;
}
}
pub trait QMetaProperty_revision<RetType> {
fn revision(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: int QMetaProperty::revision();
impl<'a> /*trait*/ QMetaProperty_revision<i32> for () {
fn revision(self , rsthis: & QMetaProperty) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty8revisionEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty8revisionEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMetaProperty::isScriptable(const QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn isScriptable<RetType, T: QMetaProperty_isScriptable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isScriptable(self);
// return 1;
}
}
pub trait QMetaProperty_isScriptable<RetType> {
fn isScriptable(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isScriptable(const QObject * obj);
impl<'a> /*trait*/ QMetaProperty_isScriptable<i8> for (Option<&'a QObject>) {
fn isScriptable(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty12isScriptableEPK7QObject()};
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty12isScriptableEPK7QObject(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: QVariant QMetaProperty::read(const QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn read<RetType, T: QMetaProperty_read<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.read(self);
// return 1;
}
}
pub trait QMetaProperty_read<RetType> {
fn read(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: QVariant QMetaProperty::read(const QObject * obj);
impl<'a> /*trait*/ QMetaProperty_read<QVariant> for (&'a QObject) {
fn read(self , rsthis: & QMetaProperty) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty4readEPK7QObject()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty4readEPK7QObject(rsthis.qclsinst, arg0)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QMetaMethod QMetaProperty::notifySignal();
impl /*struct*/ QMetaProperty {
pub fn notifySignal<RetType, T: QMetaProperty_notifySignal<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.notifySignal(self);
// return 1;
}
}
pub trait QMetaProperty_notifySignal<RetType> {
fn notifySignal(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: QMetaMethod QMetaProperty::notifySignal();
impl<'a> /*trait*/ QMetaProperty_notifySignal<QMetaMethod> for () {
fn notifySignal(self , rsthis: & QMetaProperty) -> QMetaMethod {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty12notifySignalEv()};
let mut ret = unsafe {C_ZNK13QMetaProperty12notifySignalEv(rsthis.qclsinst)};
let mut ret1 = QMetaMethod::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QMetaProperty::isDesignable(const QObject * obj);
impl /*struct*/ QMetaProperty {
pub fn isDesignable<RetType, T: QMetaProperty_isDesignable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isDesignable(self);
// return 1;
}
}
pub trait QMetaProperty_isDesignable<RetType> {
fn isDesignable(self , rsthis: & QMetaProperty) -> RetType;
}
// proto: bool QMetaProperty::isDesignable(const QObject * obj);
impl<'a> /*trait*/ QMetaProperty_isDesignable<i8> for (Option<&'a QObject>) {
fn isDesignable(self , rsthis: & QMetaProperty) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QMetaProperty12isDesignableEPK7QObject()};
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QMetaProperty12isDesignableEPK7QObject(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// <= body block end
|
extern crate serde_json;
pub mod csv_params;
pub mod data_set_sli_manifest;
pub mod manifest;
pub mod part;
pub use self::csv_params::*;
pub use self::data_set_sli_manifest::*;
pub use self::manifest::*;
pub use self::part::*;
|
use std::fs;
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::create("/tmp/test.txt")?;
let buffer = "Hello Linux Journal!\n";
file.write_all(buffer.as_bytes())?;
println!("Finish writing...");
fs::rename("/tmp/test.txt", "/tmp/LJ.txt")?;
fs::remove_file("/tmp/LJ.txt")?;
println!("Finish deleting...");
Ok(())
}
|
use std::io::prelude::*;
#[cfg(feature = "color")]
use anstream::eprintln;
#[cfg(feature = "color")]
use anstream::panic;
#[cfg(feature = "color")]
use anstream::stderr;
#[cfg(not(feature = "color"))]
use std::eprintln;
#[cfg(not(feature = "color"))]
use std::io::stderr;
use rayon::prelude::*;
use snapbox::path::FileType;
use snapbox::{DataFormat, NormalizeNewlines, NormalizePaths};
#[derive(Debug)]
pub(crate) struct Runner {
cases: Vec<Case>,
}
impl Runner {
pub(crate) fn new() -> Self {
Self {
cases: Default::default(),
}
}
pub(crate) fn case(&mut self, case: Case) {
self.cases.push(case);
}
pub(crate) fn run(
&self,
mode: &Mode,
bins: &crate::BinRegistry,
substitutions: &snapbox::Substitutions,
) {
let palette = snapbox::report::Palette::color();
if self.cases.is_empty() {
eprintln!("{}", palette.warn("There are no trycmd tests enabled yet"));
} else {
let failures: Vec<_> = self
.cases
.par_iter()
.flat_map(|c| {
let results = c.run(mode, bins, substitutions);
let stderr = stderr();
let mut stderr = stderr.lock();
results
.into_iter()
.filter_map(|s| {
snapbox::debug!("Case: {:#?}", s);
match s {
Ok(status) => {
let _ = writeln!(
stderr,
"{} {} ... {}",
palette.hint("Testing"),
status.name(),
status.spawn.status.summary()
);
if !status.is_ok() {
// Assuming `status` will print the newline
let _ = write!(stderr, "{}", &status);
}
None
}
Err(status) => {
let _ = writeln!(
stderr,
"{} {} ... {}",
palette.hint("Testing"),
status.name(),
palette.error("failed"),
);
// Assuming `status` will print the newline
let _ = write!(stderr, "{}", &status);
Some(status)
}
}
})
.collect::<Vec<_>>()
})
.collect();
if !failures.is_empty() {
let stderr = stderr();
let mut stderr = stderr.lock();
let _ = writeln!(
stderr,
"{}",
palette.hint("Update snapshots with `TRYCMD=overwrite`"),
);
let _ = writeln!(
stderr,
"{}",
palette.hint("Debug output with `TRYCMD=dump`"),
);
panic!("{} of {} tests failed", failures.len(), self.cases.len());
}
}
}
}
impl Default for Runner {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub(crate) struct Case {
pub(crate) path: std::path::PathBuf,
pub(crate) expected: Option<crate::schema::CommandStatus>,
pub(crate) timeout: Option<std::time::Duration>,
pub(crate) default_bin: Option<crate::schema::Bin>,
pub(crate) env: crate::schema::Env,
pub(crate) error: Option<SpawnStatus>,
}
impl Case {
pub(crate) fn with_error(path: std::path::PathBuf, error: crate::Error) -> Self {
Self {
path,
expected: None,
timeout: None,
default_bin: None,
env: Default::default(),
error: Some(SpawnStatus::Failure(error)),
}
}
pub(crate) fn run(
&self,
mode: &Mode,
bins: &crate::BinRegistry,
substitutions: &snapbox::Substitutions,
) -> Vec<Result<Output, Output>> {
if self.expected == Some(crate::schema::CommandStatus::Skipped) {
let output = Output::sequence(self.path.clone());
assert_eq!(output.spawn.status, SpawnStatus::Skipped);
return vec![Ok(output)];
}
if let Some(err) = self.error.clone() {
let mut output = Output::step(self.path.clone(), "setup".into());
output.spawn.status = err;
return vec![Err(output)];
}
let mut sequence = match crate::schema::TryCmd::load(&self.path) {
Ok(sequence) => sequence,
Err(e) => {
let output = Output::step(self.path.clone(), "setup".into());
return vec![Err(output.error(e))];
}
};
if sequence.steps.is_empty() {
let output = Output::sequence(self.path.clone());
assert_eq!(output.spawn.status, SpawnStatus::Skipped);
return vec![Ok(output)];
}
let fs_context = match fs_context(
&self.path,
sequence.fs.base.as_deref(),
sequence.fs.sandbox(),
mode,
) {
Ok(fs_context) => fs_context,
Err(e) => {
let output = Output::step(self.path.clone(), "setup".into());
return vec![Err(
output.error(format!("Failed to initialize sandbox: {}", e).into())
)];
}
};
let cwd = match fs_context
.path()
.map(|p| {
sequence.fs.rel_cwd().map(|rel| {
let p = p.join(rel);
snapbox::path::strip_trailing_slash(&p).to_owned()
})
})
.transpose()
{
Ok(cwd) => cwd.or_else(|| std::env::current_dir().ok()),
Err(e) => {
let output = Output::step(self.path.clone(), "setup".into());
return vec![Err(output.error(e))];
}
};
let mut substitutions = substitutions.clone();
if let Some(root) = fs_context.path() {
substitutions
.insert("[ROOT]", root.display().to_string())
.unwrap();
}
if let Some(cwd) = cwd.clone().or_else(|| std::env::current_dir().ok()) {
substitutions
.insert("[CWD]", cwd.display().to_string())
.unwrap();
}
substitutions
.insert("[EXE]", std::env::consts::EXE_SUFFIX)
.unwrap();
snapbox::debug!("{:?}", substitutions);
let mut outputs = Vec::with_capacity(sequence.steps.len());
let mut prior_step_failed = false;
for step in &mut sequence.steps {
if prior_step_failed {
step.expected_status = Some(crate::schema::CommandStatus::Skipped);
}
let step_status = self.run_step(step, cwd.as_deref(), bins, &substitutions);
if fs_context.is_mutable() && step_status.is_err() && *mode == Mode::Fail {
prior_step_failed = true;
}
outputs.push(step_status);
}
match mode {
Mode::Dump(root) => {
for output in &mut outputs {
let output = match output {
Ok(output) => output,
Err(output) => output,
};
output.stdout =
match self.dump_stream(root, output.id.as_deref(), output.stdout.take()) {
Ok(stream) => stream,
Err(stream) => stream,
};
output.stderr =
match self.dump_stream(root, output.id.as_deref(), output.stderr.take()) {
Ok(stream) => stream,
Err(stream) => stream,
};
}
}
Mode::Overwrite => {
// `rev()` to ensure we don't mess up our line number info
for step_status in outputs.iter_mut().rev() {
if let Err(output) = step_status {
let res = sequence.overwrite(
&self.path,
output.id.as_deref(),
output.stdout.as_ref().map(|s| &s.content),
output.stderr.as_ref().map(|s| &s.content),
output.spawn.exit,
);
if res.is_ok() {
*step_status = Ok(output.clone());
}
}
}
}
Mode::Fail => {}
}
if sequence.fs.sandbox() {
let mut ok = true;
let mut output = Output::step(self.path.clone(), "teardown".into());
output.fs = match self.validate_fs(
fs_context.path().expect("sandbox must be filled"),
output.fs,
mode,
&substitutions,
) {
Ok(fs) => fs,
Err(fs) => {
ok = false;
fs
}
};
if let Err(err) = fs_context.close() {
ok = false;
output.fs.context.push(FileStatus::Failure(
format!("Failed to cleanup sandbox: {}", err).into(),
));
}
let output = if ok {
output.spawn.status = SpawnStatus::Ok;
Ok(output)
} else {
output.spawn.status = SpawnStatus::Failure("Files left in unexpected state".into());
Err(output)
};
outputs.push(output);
}
outputs
}
pub(crate) fn run_step(
&self,
step: &mut crate::schema::Step,
cwd: Option<&std::path::Path>,
bins: &crate::BinRegistry,
substitutions: &snapbox::Substitutions,
) -> Result<Output, Output> {
let output = if let Some(id) = step.id.clone() {
Output::step(self.path.clone(), id)
} else {
Output::sequence(self.path.clone())
};
let mut bin = step.bin.take();
if bin.is_none() {
bin = self.default_bin.clone()
}
bin = bin
.map(|name| bins.resolve_bin(name))
.transpose()
.map_err(|e| output.clone().error(e))?;
step.bin = bin;
if step.timeout.is_none() {
step.timeout = self.timeout;
}
if self.expected.is_some() {
step.expected_status = self.expected;
}
step.env.update(&self.env);
if step.expected_status() == crate::schema::CommandStatus::Skipped {
assert_eq!(output.spawn.status, SpawnStatus::Skipped);
return Ok(output);
}
match &step.bin {
Some(crate::schema::Bin::Path(_)) => {}
Some(crate::schema::Bin::Name(_name)) => {
// Unhandled by resolve
snapbox::debug!("bin={:?} not found", _name);
assert_eq!(output.spawn.status, SpawnStatus::Skipped);
return Ok(output);
}
Some(crate::schema::Bin::Error(_)) => {}
// Unlike `Name`, this always represents a bug
None => {}
Some(crate::schema::Bin::Ignore) => {
// Unhandled by resolve
assert_eq!(output.spawn.status, SpawnStatus::Skipped);
return Ok(output);
}
}
let cmd = step.to_command(cwd).map_err(|e| output.clone().error(e))?;
let cmd_output = cmd
.output()
.map_err(|e| output.clone().error(e.to_string().into()))?;
let output = output.output(cmd_output);
// For Mode::Dump's sake, allow running all
let output = self.validate_spawn(output, step.expected_status());
let output = self.validate_streams(output, step, substitutions);
if output.is_ok() {
Ok(output)
} else {
Err(output)
}
}
fn validate_spawn(&self, mut output: Output, expected: crate::schema::CommandStatus) -> Output {
let status = output.spawn.exit.expect("bale out before now");
match expected {
crate::schema::CommandStatus::Success => {
if !status.success() {
output.spawn.status = SpawnStatus::Expected("success".into());
}
}
crate::schema::CommandStatus::Failed => {
if status.success() || status.code().is_none() {
output.spawn.status = SpawnStatus::Expected("failure".into());
}
}
crate::schema::CommandStatus::Interrupted => {
if status.code().is_some() {
output.spawn.status = SpawnStatus::Expected("interrupted".into());
}
}
crate::schema::CommandStatus::Skipped => unreachable!("handled earlier"),
crate::schema::CommandStatus::Code(expected_code) => {
if Some(expected_code) != status.code() {
output.spawn.status = SpawnStatus::Expected(expected_code.to_string());
}
}
}
output
}
fn validate_streams(
&self,
mut output: Output,
step: &crate::schema::Step,
substitutions: &snapbox::Substitutions,
) -> Output {
output.stdout = self.validate_stream(
output.stdout,
step.expected_stdout.as_ref(),
step.binary,
substitutions,
);
output.stderr = self.validate_stream(
output.stderr,
step.expected_stderr.as_ref(),
step.binary,
substitutions,
);
output
}
fn validate_stream(
&self,
stream: Option<Stream>,
expected_content: Option<&crate::Data>,
binary: bool,
substitutions: &snapbox::Substitutions,
) -> Option<Stream> {
let mut stream = stream?;
if !binary {
stream = stream.make_text();
if !stream.is_ok() {
return Some(stream);
}
}
if let Some(expected_content) = expected_content {
stream.content = stream.content.normalize(snapbox::NormalizeMatches::new(
substitutions,
expected_content,
));
if stream.content != *expected_content {
stream.status = StreamStatus::Expected(expected_content.clone());
return Some(stream);
}
}
Some(stream)
}
fn dump_stream(
&self,
root: &std::path::Path,
id: Option<&str>,
stream: Option<Stream>,
) -> Result<Option<Stream>, Option<Stream>> {
if let Some(stream) = stream {
let file_name = match id {
Some(id) => {
format!(
"{}-{}.{}",
self.path.file_stem().unwrap().to_string_lossy(),
id,
stream.stream.as_str(),
)
}
None => {
format!(
"{}.{}",
self.path.file_stem().unwrap().to_string_lossy(),
stream.stream.as_str(),
)
}
};
let stream_path = root.join(file_name);
stream.content.write_to(&stream_path).map_err(|e| {
let mut stream = stream.clone();
if stream.is_ok() {
stream.status = StreamStatus::Failure(e);
}
stream
})?;
Ok(Some(stream))
} else {
Ok(None)
}
}
fn validate_fs(
&self,
actual_root: &std::path::Path,
mut fs: Filesystem,
mode: &Mode,
substitutions: &snapbox::Substitutions,
) -> Result<Filesystem, Filesystem> {
let mut ok = true;
#[cfg(feature = "filesystem")]
if let Mode::Dump(_) = mode {
// Handled as part of PathFixture
} else {
let fixture_root = self.path.with_extension("out");
if fixture_root.exists() {
for status in snapbox::path::PathDiff::subset_matches_iter(
fixture_root,
actual_root,
substitutions,
) {
match status {
Ok((expected_path, actual_path)) => {
fs.context.push(FileStatus::Ok {
actual_path,
expected_path,
});
}
Err(diff) => {
let mut is_current_ok = false;
if *mode == Mode::Overwrite && diff.overwrite().is_ok() {
is_current_ok = true;
}
fs.context.push(diff.into());
if !is_current_ok {
ok = false;
}
}
}
}
}
}
if ok {
Ok(fs)
} else {
Err(fs)
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Output {
path: std::path::PathBuf,
id: Option<String>,
spawn: Spawn,
stdout: Option<Stream>,
stderr: Option<Stream>,
fs: Filesystem,
}
impl Output {
fn sequence(path: std::path::PathBuf) -> Self {
Self {
path,
id: None,
spawn: Spawn {
exit: None,
status: SpawnStatus::Skipped,
},
stdout: None,
stderr: None,
fs: Default::default(),
}
}
fn step(path: std::path::PathBuf, step: String) -> Self {
Self {
path,
id: Some(step),
spawn: Default::default(),
stdout: None,
stderr: None,
fs: Default::default(),
}
}
fn output(mut self, output: std::process::Output) -> Self {
self.spawn.exit = Some(output.status);
assert_eq!(self.spawn.status, SpawnStatus::Skipped);
self.spawn.status = SpawnStatus::Ok;
self.stdout = Some(Stream {
stream: Stdio::Stdout,
content: output.stdout.into(),
status: StreamStatus::Ok,
});
self.stderr = Some(Stream {
stream: Stdio::Stderr,
content: output.stderr.into(),
status: StreamStatus::Ok,
});
self
}
fn error(mut self, msg: crate::Error) -> Self {
self.spawn.status = SpawnStatus::Failure(msg);
self
}
fn is_ok(&self) -> bool {
self.spawn.is_ok()
&& self.stdout.as_ref().map(|s| s.is_ok()).unwrap_or(true)
&& self.stderr.as_ref().map(|s| s.is_ok()).unwrap_or(true)
&& self.fs.is_ok()
}
fn name(&self) -> String {
self.id
.as_deref()
.map(|id| format!("{}:{}", self.path.display(), id))
.unwrap_or_else(|| self.path.display().to_string())
}
}
impl std::fmt::Display for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.spawn.fmt(f)?;
if let Some(stdout) = &self.stdout {
stdout.fmt(f)?;
}
if let Some(stderr) = &self.stderr {
stderr.fmt(f)?;
}
self.fs.fmt(f)?;
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Spawn {
exit: Option<std::process::ExitStatus>,
status: SpawnStatus,
}
impl Spawn {
fn is_ok(&self) -> bool {
self.status.is_ok()
}
}
impl Default for Spawn {
fn default() -> Self {
Self {
exit: None,
status: SpawnStatus::Skipped,
}
}
}
impl std::fmt::Display for Spawn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let palette = snapbox::report::Palette::color();
match &self.status {
SpawnStatus::Ok => {
if let Some(exit) = self.exit {
if exit.success() {
writeln!(f, "Exit: {}", palette.info("success"))?;
} else if let Some(code) = exit.code() {
writeln!(f, "Exit: {}", palette.error(code))?;
} else {
writeln!(f, "Exit: {}", palette.error("interrupted"))?;
}
}
}
SpawnStatus::Skipped => {
writeln!(f, "{}", palette.warn("Skipped"))?;
}
SpawnStatus::Failure(msg) => {
writeln!(f, "Failed: {}", palette.error(msg))?;
}
SpawnStatus::Expected(expected) => {
if let Some(exit) = self.exit {
if exit.success() {
writeln!(
f,
"Expected {}, was {}",
palette.info(expected),
palette.error("success")
)?;
} else {
writeln!(
f,
"Expected {}, was {}",
palette.info(expected),
palette.error(snapbox::cmd::display_exit_status(exit))
)?;
}
}
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SpawnStatus {
Ok,
Skipped,
Failure(crate::Error),
Expected(String),
}
impl SpawnStatus {
fn is_ok(&self) -> bool {
match self {
Self::Ok | Self::Skipped => true,
Self::Failure(_) | Self::Expected(_) => false,
}
}
fn summary(&self) -> impl std::fmt::Display {
let palette = snapbox::report::Palette::color();
match self {
Self::Ok => palette.info("ok"),
Self::Skipped => palette.warn("ignored"),
Self::Failure(_) | Self::Expected(_) => palette.error("failed"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Stream {
stream: Stdio,
content: crate::Data,
status: StreamStatus,
}
impl Stream {
fn make_text(mut self) -> Self {
let content = self.content.try_coerce(DataFormat::Text);
if content.format() != DataFormat::Text {
self.status = StreamStatus::Failure("Unable to convert underlying Data to Text".into());
}
self.content = content
.normalize(NormalizePaths)
.normalize(NormalizeNewlines);
self
}
fn is_ok(&self) -> bool {
self.status.is_ok()
}
}
impl std::fmt::Display for Stream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let palette = snapbox::report::Palette::color();
match &self.status {
StreamStatus::Ok => {
writeln!(f, "{}:", self.stream)?;
writeln!(f, "{}", palette.info(&self.content))?;
}
StreamStatus::Failure(msg) => {
writeln!(
f,
"{} {}:",
self.stream,
palette.error(format_args!("({})", msg))
)?;
writeln!(f, "{}", palette.info(&self.content))?;
}
StreamStatus::Expected(expected) => {
snapbox::report::write_diff(
f,
expected,
&self.content,
Some(&self.stream),
Some(&self.stream),
palette,
)?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum StreamStatus {
Ok,
Failure(crate::Error),
Expected(crate::Data),
}
impl StreamStatus {
fn is_ok(&self) -> bool {
match self {
Self::Ok => true,
Self::Failure(_) | Self::Expected(_) => false,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Stdio {
Stdout,
Stderr,
}
impl Stdio {
fn as_str(&self) -> &str {
match self {
Self::Stdout => "stdout",
Self::Stderr => "stderr",
}
}
}
impl std::fmt::Display for Stdio {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_str().fmt(f)
}
}
#[derive(Clone, Default, Debug, PartialEq, Eq)]
struct Filesystem {
context: Vec<FileStatus>,
}
impl Filesystem {
fn is_ok(&self) -> bool {
if self.context.is_empty() {
true
} else {
self.context.iter().all(FileStatus::is_ok)
}
}
}
impl std::fmt::Display for Filesystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for status in &self.context {
status.fmt(f)?;
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum FileStatus {
Ok {
expected_path: std::path::PathBuf,
actual_path: std::path::PathBuf,
},
Failure(crate::Error),
TypeMismatch {
expected_path: std::path::PathBuf,
actual_path: std::path::PathBuf,
expected_type: FileType,
actual_type: FileType,
},
LinkMismatch {
expected_path: std::path::PathBuf,
actual_path: std::path::PathBuf,
expected_target: std::path::PathBuf,
actual_target: std::path::PathBuf,
},
ContentMismatch {
expected_path: std::path::PathBuf,
actual_path: std::path::PathBuf,
expected_content: crate::Data,
actual_content: crate::Data,
},
}
impl FileStatus {
fn is_ok(&self) -> bool {
match self {
Self::Ok { .. } => true,
Self::Failure(_)
| Self::TypeMismatch { .. }
| Self::LinkMismatch { .. }
| Self::ContentMismatch { .. } => false,
}
}
}
impl From<snapbox::path::PathDiff> for FileStatus {
fn from(other: snapbox::path::PathDiff) -> Self {
match other {
snapbox::path::PathDiff::Failure(err) => FileStatus::Failure(err),
snapbox::path::PathDiff::TypeMismatch {
expected_path,
actual_path,
expected_type,
actual_type,
} => FileStatus::TypeMismatch {
actual_path,
expected_path,
actual_type,
expected_type,
},
snapbox::path::PathDiff::LinkMismatch {
expected_path,
actual_path,
expected_target,
actual_target,
} => FileStatus::LinkMismatch {
actual_path,
expected_path,
actual_target,
expected_target,
},
snapbox::path::PathDiff::ContentMismatch {
expected_path,
actual_path,
expected_content,
actual_content,
} => FileStatus::ContentMismatch {
actual_path,
expected_path,
actual_content,
expected_content,
},
}
}
}
impl std::fmt::Display for FileStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let palette = snapbox::report::Palette::color();
match &self {
Self::Ok {
expected_path,
actual_path: _actual_path,
} => {
writeln!(
f,
"{}: is {}",
expected_path.display(),
palette.info("good"),
)?;
}
Self::Failure(msg) => {
writeln!(f, "{}", palette.error(msg))?;
}
Self::TypeMismatch {
expected_path,
actual_path: _actual_path,
expected_type,
actual_type,
} => {
writeln!(
f,
"{}: Expected {}, was {}",
expected_path.display(),
palette.info(expected_type),
palette.error(actual_type)
)?;
}
Self::LinkMismatch {
expected_path,
actual_path: _actual_path,
expected_target,
actual_target,
} => {
writeln!(
f,
"{}: Expected {}, was {}",
expected_path.display(),
palette.info(expected_target.display()),
palette.error(actual_target.display())
)?;
}
Self::ContentMismatch {
expected_path,
actual_path,
expected_content,
actual_content,
} => {
snapbox::report::write_diff(
f,
expected_content,
actual_content,
Some(&expected_path.display()),
Some(&actual_path.display()),
palette,
)?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Mode {
Fail,
Overwrite,
Dump(std::path::PathBuf),
}
impl Mode {
pub(crate) fn initialize(&self) -> Result<(), std::io::Error> {
match self {
Self::Fail => {}
Self::Overwrite => {}
Self::Dump(root) => {
std::fs::create_dir_all(root)?;
let gitignore_path = root.join(".gitignore");
std::fs::write(gitignore_path, "*\n")?;
}
}
Ok(())
}
}
#[cfg_attr(not(feature = "filesystem"), allow(unused_variables))]
fn fs_context(
path: &std::path::Path,
cwd: Option<&std::path::Path>,
sandbox: bool,
mode: &crate::Mode,
) -> Result<snapbox::path::PathFixture, crate::Error> {
if sandbox {
#[cfg(feature = "filesystem")]
match mode {
crate::Mode::Dump(root) => {
let target = root.join(path.with_extension("out").file_name().unwrap());
let mut context = snapbox::path::PathFixture::mutable_at(&target)?;
if let Some(cwd) = cwd {
context = context.with_template(cwd)?;
}
Ok(context)
}
crate::Mode::Fail | crate::Mode::Overwrite => {
let mut context = snapbox::path::PathFixture::mutable_temp()?;
if let Some(cwd) = cwd {
context = context.with_template(cwd)?;
}
Ok(context)
}
}
#[cfg(not(feature = "filesystem"))]
Err("Sandboxing is disabled".into())
} else {
Ok(cwd
.map(snapbox::path::PathFixture::immutable)
.unwrap_or_else(snapbox::path::PathFixture::none))
}
}
|
// 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 std::str;
use crate::crypto_provider::CryptoProvider;
use fidl_fuchsia_kms::{AsymmetricKeyAlgorithm, AsymmetricPrivateKeyRequest, KeyOrigin, Status};
use serde_derive::{Deserialize, Serialize};
pub enum KeyRequestType {
AsymmetricPrivateKeyRequest(AsymmetricPrivateKeyRequest),
}
/// The key types.
#[derive(Serialize, Deserialize, PartialEq)]
pub enum KeyType {
/// A type of key used to seal and unseal data. This type of key is generated by KMS and not the
/// user.
SealingKey,
/// A type of key representing an asymmetric private key. It could be used to sign data.
AsymmetricPrivateKey,
}
/// A key object in memory.
///
/// Each key stored in KMS should have a singleton of key object in memory when used. The user are
/// given a handler associated with this unique in memory key object. If a key object does not exist
/// KMS would read from storage and create the key object. After all the handles to this key object
/// is dropped, the key object would be removed from memory. This ensures that all the operations
/// are synchronized based on lock to use this Key object.
pub trait KmsKey: Send {
/// Whether this key is already deleted. A key may be deleted while there are other channels
/// associated with that key. In this case, any operation on the deleted key would return
/// key_not_found.
fn is_deleted(&self) -> bool;
/// Delete the key. This would include telling the crypto provider to delete key (If provider
/// keeps some resource for the key) and set the deleted to true.
fn delete(&mut self) -> Result<(), Status>;
/// Get the name for the current key.
fn get_key_name(&self) -> &str;
/// Handle a request from user. Note that a key should only handle the request for that key
/// and this is enforced by key_manager.
///
/// # Panics
///
/// Panics if request type is invalid.
fn handle_request(&self, req: KeyRequestType) -> Result<(), fidl::Error>;
/// The the type for the current key.
fn get_key_type(&self) -> KeyType;
/// Get the provider's name.
fn get_provider_name(&self) -> &str;
/// Get the key data.
fn get_key_data(&self) -> Vec<u8>;
}
/// A list of all the supported asymmetric key algorithms.
#[cfg(test)]
pub const ASYMMETRIC_KEY_ALGORITHMS: &[AsymmetricKeyAlgorithm] = &[
AsymmetricKeyAlgorithm::EcdsaSha256P256,
AsymmetricKeyAlgorithm::EcdsaSha512P384,
AsymmetricKeyAlgorithm::EcdsaSha512P521,
AsymmetricKeyAlgorithm::RsaSsaPssSha2562048,
AsymmetricKeyAlgorithm::RsaSsaPssSha2563072,
AsymmetricKeyAlgorithm::RsaSsaPssSha2564096,
AsymmetricKeyAlgorithm::RsaSsaPkcs1Sha2562048,
AsymmetricKeyAlgorithm::RsaSsaPkcs1Sha2563072,
AsymmetricKeyAlgorithm::RsaSsaPkcs1Sha2564096,
];
/// The key attributes structure to be stored as attribute file.
pub struct KeyAttributes<'a> {
pub asymmetric_key_algorithm: Option<AsymmetricKeyAlgorithm>,
pub key_type: KeyType,
pub key_origin: KeyOrigin,
pub provider: &'a dyn CryptoProvider,
pub key_data: Vec<u8>,
}
/// Emit a error message and return an error.
///
/// Invoke the `error!` macro on all but the first argument. A call to
/// `debug_err!(err, ...)` is an expression whose value is the expression `err`.
#[macro_export]
macro_rules! debug_err {
($err:expr, $($arg:tt)*) => (
// TODO(joshlf): Uncomment once attributes are allowed on expressions
// #[cfg_attr(feature = "cargo-clippy", allow(block_in_if_condition_stmt))]
{
use ::log::error;
error!($($arg)*);
$err
}
)
}
/// Create a closure which emits a error message and turn original error to a new error.
///
/// Creates a closure that would return the first argument and print an error message with the
/// original error that is used to call the closure as the last argument to the error message.
macro_rules! debug_err_fn {
($return_err:expr, $($arg:tt)*) => (
|err| {
use ::log::error;
error!($($arg)*, err);
$return_err
}
)
}
#[cfg(test)]
pub fn generate_random_data(size: u32) -> Vec<u8> {
use rand::Rng;
let mut random_data = Vec::new();
let mut rng = rand::thread_rng();
for _i in 0..size {
let byte: u8 = rng.gen();
random_data.push(byte);
}
random_data
}
|
use crate::Width;
use crate::*;
#[test]
fn test_solver() {
assert_eq!(EastAsianWidth::Ambiguous, solve_eaw(0xA1));
assert_eq!(EastAsianWidth::Narrow, solve_eaw(0xA2));
assert_eq!(EastAsianWidth::Narrow, solve_eaw(0xA3));
assert_eq!(EastAsianWidth::Ambiguous, solve_eaw(0xA4));
assert_eq!(EastAsianWidth::Narrow, solve_eaw(0xA5));
assert_eq!(EastAsianWidth::Wide, solve_eaw('あ' as u32));
assert_eq!(EastAsianWidth::Half, solve_eaw('ア' as u32));
assert_eq!(EastAsianWidth::Wide, solve_eaw('安' as u32));
assert_eq!(EastAsianWidth::Neutral, solve_eaw(0xA0));
assert_eq!(EastAsianWidth::Neutral, solve_eaw(0xFFFF)); // missing in the database file
}
#[test]
fn test_string_width() {
let s = "AアあA*α𓄿";
assert_eq!(10, s.width(EastAsianContextCharWidthSelector));
assert_eq!(9, s.width(NonEastAsianContextCharWidthSelector));
let s1 = "アあA*α𓄿";
assert_eq!(8, s1.width(EastAsianContextCharWidthSelector));
assert_eq!(7, s1.width(NonEastAsianContextCharWidthSelector));
let s2 = "AあA*α𓄿";
assert_eq!(9, s2.width(EastAsianContextCharWidthSelector));
assert_eq!(8, s2.width(NonEastAsianContextCharWidthSelector));
let s3 = "AアA*α𓄿";
assert_eq!(8, s3.width(EastAsianContextCharWidthSelector));
assert_eq!(7, s3.width(NonEastAsianContextCharWidthSelector));
let s4 = "Aアあ*α𓄿";
assert_eq!(9, s4.width(EastAsianContextCharWidthSelector));
assert_eq!(8, s4.width(NonEastAsianContextCharWidthSelector));
let s5 = "AアあAα𓄿";
assert_eq!(9, s5.width(EastAsianContextCharWidthSelector));
assert_eq!(8, s5.width(NonEastAsianContextCharWidthSelector));
let s6 = "AアあA*𓄿";
assert_eq!(8, s6.width(EastAsianContextCharWidthSelector));
assert_eq!(8, s6.width(NonEastAsianContextCharWidthSelector));
let s7 = "AアあA*α";
assert_eq!(9, s7.width(EastAsianContextCharWidthSelector));
assert_eq!(8, s7.width(NonEastAsianContextCharWidthSelector));
}
|
use std::fmt;
use audio::SoundSource;
use ggez::{
audio,
event::KeyCode,
graphics::{self, DrawMode, FillOptions, BLACK},
Context,
};
use ggez::{
graphics::{DrawParam, Drawable},
GameResult,
};
use graphics::{Mesh, Rect, WHITE};
pub(crate) const GRID_SIZE: (usize, usize) = (64, 32);
const GRID_CELL_SIZE: (usize, usize) = (10, 10);
const GRID_NUMS: usize = GRID_SIZE.0 * GRID_SIZE.1;
pub(crate) const SCREEN_SIZE: (f32, f32) = (
GRID_SIZE.0 as f32 * GRID_CELL_SIZE.0 as f32,
GRID_SIZE.1 as f32 * GRID_CELL_SIZE.1 as f32,
);
pub struct Display {
gfx: [u8; GRID_NUMS],
}
impl Display {
pub fn new() -> Self {
Display {
gfx: [0; GRID_NUMS],
}
}
pub fn clear_window(&mut self) {
for b in &mut self.gfx {
*b = 0;
}
}
//if there is collision ,return true else ruturn false
pub fn draw_sprite(&mut self, x: u8, y: u8, sprite: &[u8]) -> bool {
let mut res = false;
let x: usize = (x % 64).into();
let y: usize = (y % 32).into();
let mut pos = y * GRID_SIZE.0 + x;
for i in 0..sprite.len() {
let curr_byte = sprite[i];
for t in 0..8 {
let b = curr_byte >> (7 - t) & 0b0000_0001;
if b == 1 && self.gfx[pos + t] == 1 {
res = true;
}
self.gfx[pos + t] ^= b;
}
pos += GRID_SIZE.0; //next row
}
res
}
pub fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
for y in 0..GRID_SIZE.1 {
for x in 0..GRID_SIZE.0 {
let p = y * GRID_SIZE.0 + x;
let color = if self.gfx[p] == 1 { WHITE } else { BLACK };
let bounds = Rect {
x: (x * GRID_CELL_SIZE.0) as f32,
y: (y * GRID_CELL_SIZE.1) as f32,
w: GRID_CELL_SIZE.0 as f32,
h: GRID_CELL_SIZE.1 as f32,
};
let mesh = Mesh::new_rectangle(
ctx,
DrawMode::Fill(FillOptions::default()),
bounds,
color,
)?;
mesh.draw(ctx, DrawParam::default())?;
}
}
Ok(())
}
}
pub(crate) fn keyboard_match(keycode: KeyCode) -> Option<u8> {
match keycode {
KeyCode::Key1 => Some(0x1),
KeyCode::Key2 => Some(0x2),
KeyCode::Key3 => Some(0x3),
KeyCode::Key4 => Some(0xC),
KeyCode::Q => Some(0x4),
KeyCode::W => Some(0x5),
KeyCode::E => Some(0x6),
KeyCode::R => Some(0xD),
KeyCode::A => Some(0x7),
KeyCode::S => Some(0x8),
KeyCode::D => Some(0x9),
KeyCode::F => Some(0xE),
KeyCode::Z => Some(0xA),
KeyCode::X => Some(0x0),
KeyCode::C => Some(0xB),
KeyCode::V => Some(0xF),
_ => None,
}
}
pub struct Sound {
sound: audio::Source,
}
impl Sound {
pub fn new(ctx: &mut Context) -> GameResult<Sound> {
let sound = audio::Source::new(ctx, "/pew.ogg")?;
let sd = Sound { sound };
Ok(sd)
}
pub fn play(&mut self) -> GameResult<()> {
self.sound.play()
}
}
impl fmt::Debug for Display {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for row in 0..GRID_SIZE.1 {
for i in 0..GRID_SIZE.0 {
write!(f, "{} ", self.gfx[row * GRID_SIZE.1 + i])?;
}
writeln!(f, "")?;
}
Ok(())
}
}
|
pub use models::user::User;
pub use models::workout::Workout;
pub use models::workout_plan::WorkoutPlan;
use std::collections::HashMap;
use iron::prelude::*;
pub struct Database {
pub users: HashMap<String, User>,
pub workout_plans: HashMap<String, WorkoutPlan>,
pub workouts: HashMap<String, Workout>
}
// This function is executed for every request. Here, we would realistically
// provide a database connection or similar. For this example, we'll be
// creating the database from scratch.
pub fn context_factory(_: &mut Request) -> self::Database {
self::Database {
users: vec![
(
"1000".to_owned(),
User {
id: "1000".to_owned(),
name: "Robin".to_owned(),
friend_ids: vec!["1001".to_owned()],
workout_plan_ids: vec!["1000".to_owned()],
}
),
(
"1001".to_owned(),
User {
id: "1001".to_owned(),
name: "Max".to_owned(),
friend_ids: vec!["1000".to_owned()],
workout_plan_ids: vec!["1001".to_owned()],
}
),
].into_iter().collect(),
workout_plans: vec![
(
"1000".to_owned(),
WorkoutPlan {
id: "1000".to_owned(),
name: "Road to 100k".to_owned(),
start_date: "".to_owned(),
end_date: "".to_owned(),
workout_ids: vec!["1001".to_owned()],
}
),
(
"1001".to_owned(),
WorkoutPlan {
id: "1001".to_owned(),
name: "2016 Season".to_owned(),
start_date: "".to_owned(),
end_date: "".to_owned(),
workout_ids: vec!["1000".to_owned()],
}
),
].into_iter().collect(),
workouts: vec![
(
"1000".to_owned(),
Workout {
id: "1000".to_owned(),
name: "Long Run".to_owned(),
description: "10-15 miler".to_owned(),
date: "".to_owned(),
}
),
(
"1001".to_owned(),
Workout {
id: "1001".to_owned(),
name: "Fartlek".to_owned(),
description: "3x2 mile repeats".to_owned(),
date: "".to_owned(),
}
),
].into_iter().collect(),
}
}
|
pub use VkSharingMode::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkSharingMode {
VK_SHARING_MODE_EXCLUSIVE = 0,
VK_SHARING_MODE_CONCURRENT = 1,
}
impl Default for VkSharingMode {
fn default() -> Self {
VK_SHARING_MODE_EXCLUSIVE
}
}
|
use gl;
use std::error;
use std::ptr;
use program;
use shader_source;
use texture;
use vertex;
use window;
pub struct App {
window: window::Window,
renderer: Renderer,
}
impl App {
pub fn new(width: u32,
height: u32,
title: &str,
source: RenderingSource)
-> Result<App, Box<error::Error>> {
let mut window = try!(window::Window::new(width, height, title));
window.make_main();
let renderer = match source {
RenderingSource::ColorRenderingSource => {
Renderer::new(shader_source::color_pipeline_source())
}
RenderingSource::TextureRenderingSource { tex_def } => {
let r = Renderer::new(shader_source::texture_pipeline_source());
texture::texture_load(r.program.get_addr(), tex_def);
r
}
};
return Ok(App {
window: window,
renderer: renderer,
});
}
pub fn draw<V: vertex::VertexSpecable + ?Sized>(&mut self, rects: &Vec<Box<V>>) {
unsafe {
// Clear the screen to red
gl::ClearColor(0.9, 0.1, 0.2, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT);
}
self.renderer.draw(rects);
self.window.swap_buffers();
}
pub fn handle_events(&mut self) -> Option<window::Action> {
return self.window.handle_events();
}
pub fn close(&self) {
self.renderer.close();
}
}
pub enum RenderingSource {
ColorRenderingSource,
TextureRenderingSource { tex_def: texture::TextureSetupDefinition, },
}
struct Renderer {
program: program::Program,
vertices: vertex::VertexBuffers,
}
impl Renderer {
fn new(p_src: shader_source::RenderingPipelineSource) -> Renderer {
let vertex_buffers = vertex::VertexBuffers::new(p_src.vertex_width);
let program = program::Program::new(p_src.vertex_glsl,
p_src.fragment_glsl,
p_src.all_vertex_attrs,
&vertex_buffers);
return Renderer {
program: program,
vertices: vertex_buffers,
};
}
fn draw<V: vertex::VertexSpecable + ?Sized>(&self, rects: &Vec<Box<V>>) {
// build and copy the vertex data
let element_count = self.vertices.gen_vertex_buffers(rects);
unsafe {
gl::DrawElements(gl::TRIANGLES, element_count, gl::UNSIGNED_INT, ptr::null());
}
}
pub fn close(&self) {
self.vertices.close();
self.program.close();
}
}
|
//! # Custom [`Stream`][crate::stream::Stream]
//!
//! `winnow` is batteries included with support for
//! - Basic inputs like `&str`, newtypes with
//! - Improved debug output like [`Bytes`][crate::Bytes]
//! - [`Stateful`][crate::Stateful] for passing state through your parser, like tracking recursion
//! depth
//! - [`Located`][crate::Located] for looking up the absolute position of a token
//!
//! But that won't always cut it for your parser. For example, you might lex `&str` into
//! a series of tokens and then want to parse a `TokenStream`.
//!
//! ## Implementing a custom stream
//!
//! Let's assume we have an input type we'll call `MyStream`. `MyStream` is a sequence of `MyItem` type.
//! The goal is to define parsers with this signature: `&mut MyStream -> PResult<Output>`.
//!
//! ```rust
//! # use winnow::prelude::*;
//! # use winnow::token::tag;
//! # type MyStream<'i> = &'i str;
//! # type Output<'i> = &'i str;
//! fn parser<'s>(i: &mut MyStream<'s>) -> PResult<Output<'s>> {
//! "test".parse_next(i)
//! }
//! ```
//!
//! Here are the traits we have to implement for `MyStream`:
//!
//! | trait | usage |
//! |---|---|
//! | [`Stream`] |Core trait for driving parsing|
//! | [`StreamIsPartial`] | Marks the input as being the complete buffer or a partial buffer for streaming input |
//! | [`AsBytes`] |Casts the input type to a byte slice|
//! | [`AsBStr`] |Casts the input type to a slice of ASCII / UTF-8-like bytes|
//! | [`Compare`] |Character comparison operations|
//! | [`FindSlice`] |Look for a substring in self|
//! | [`Location`] |Calculate location within initial input|
//! | [`Offset`] |Calculate the offset between slices|
//!
//! Here are the traits we have to implement for `MyItem`:
//!
//! | trait | usage |
//! |---|---|
//! | [`AsChar`] |Transforms common types to a char for basic token parsing|
//! | [`ContainsToken`] |Look for the token in the given set|
//!
//! And traits for slices of `MyItem`:
//!
//! | [`SliceLen`] |Calculate the input length|
//! | [`ParseSlice`] |Used to integrate `&str`'s `parse()` method|
#[allow(unused_imports)] // Here for intra-dock links
use crate::stream::*;
|
// Copyright 2016 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
use std::mem;
struct Foo<T: ?Sized> {
a: i64,
b: bool,
c: T,
}
fn main() {
let foo: &Foo<i32> = &Foo { a: 1, b: false, c: 2i32 };
let foo_unsized: &Foo<Send> = foo;
assert_eq!(mem::size_of_val(foo), mem::size_of_val(foo_unsized));
}
|
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Hangouts {
pub conversations: Vec<Conversation>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Conversation {
#[serde(rename="conversation")] pub header: ConversationHeader,
pub events: Vec<Event>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ConversationHeader {
pub conversation_id: ConversationId,
#[serde(rename="conversation")] pub details: ConversationDetails,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ConversationDetails {
pub id: ConversationId,
#[serde(rename="type")] pub typ: String,
pub name: Option<String>, // set for type="GROUP" only
pub self_conversation_state: SelfConversationState,
pub read_state: Vec<ReadState>,
pub has_active_hangout: bool,
pub otr_status: String,
pub otr_toggle: String,
pub current_participant: Vec<ParticipantId>,
pub participant_data: Vec<ParticipantData>,
pub fork_on_external_invite: bool,
pub network_type: Vec<String>,
pub force_history_state: String,
pub conversation_ttl_days: Option<String>,
pub group_link_sharing_status: String
}
#[derive(Deserialize, Debug, PartialEq)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ConversationId {
pub id: String,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct SelfConversationState {
pub self_read_state: ReadState,
pub status: String,
pub notification_level: NotificationLevel,
pub view: Vec<String>,
pub inviter_id: ParticipantId,
pub invite_timestamp: String,
pub invitation_display_type: Option<String>,
pub invite_affinity: Option<String>,
pub sort_timestamp: String,
pub active_timestamp: Option<String>,
pub delivery_medium_option: Option<serde_json::Value>, // TODO
pub is_guest: Option<bool>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ReadState {
pub participant_id: ParticipantId,
pub latest_read_timestamp: String,
}
#[derive(Deserialize, Debug, PartialEq, Eq, Hash, Clone)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ParticipantId {
pub gaia_id: String,
pub chat_id: String,
}
#[derive(Deserialize, Debug, Clone)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ParticipantData {
pub id: ParticipantId,
pub fallback_name: Option<String>,
pub invitation_status: Option<String>,
pub participant_type: Option<String>,
pub new_invitation_status: Option<String>,
pub in_different_customer_as_requester: Option<bool>,
pub is_anonymous_phone: Option<bool>,
pub domain_id: Option<String>,
pub phone_number: Option<serde_json::Value>, // TODO
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Event {
#[serde(flatten)] pub header: EventHeader,
#[serde(flatten)] pub data: EventData,
pub event_type: String,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct EventHeader {
pub conversation_id: ConversationId,
pub sender_id: ParticipantId,
pub timestamp: String,
pub self_event_state: SelfEventState,
pub event_id: String,
pub advances_sort_timestamp: bool,
pub event_otr: String,
pub delivery_medium: serde_json::Value, // TODO
pub event_version: String,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct SelfEventState {
pub user_id: ParticipantId,
pub client_generated_id: Option<String>,
pub notification_level: Option<NotificationLevel>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub enum NotificationLevel {
#[serde(rename="QUIET")] Quiet,
#[serde(rename="RING")] Ring,
}
#[derive(Deserialize, Debug)]
//#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub enum EventData {
#[serde(rename="chat_message")]
ChatMessage {
message_content: ChatSegments,
annotation: Option<Vec<Annotation>>,
},
#[serde(rename="conversation_rename")]
ConversationRename {
old_name: String,
new_name: String,
},
#[serde(rename="hangout_event")]
HangoutEvent {
#[serde(flatten)] data: HangoutEvent,
media_type: Option<String>,
#[serde(default)] participant_id: Vec<ParticipantId>,
},
#[serde(rename="membership_change")]
MembershipChange {
#[serde(rename="type")] typ: String,
participant_id: Vec<ParticipantId>,
}
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ChatSegments {
#[serde(default, rename="segment")] pub segments: Vec<ChatSegment>,
#[serde(default, rename="attachment")] pub attachments: Vec<AttachmentSegment>,
}
#[derive(Deserialize, Debug)]
#[serde(tag="type")]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub enum ChatSegment {
#[serde(rename="TEXT")]
Text {
text: String,
#[serde(default)] formatting: Formatting,
},
#[serde(rename="LINK")]
Link {
text: String,
link_data: LinkData,
#[serde(default)] formatting: Formatting,
},
#[serde(rename="LINE_BREAK")]
LineBreak {
text: Option<String>,
},
}
#[derive(Deserialize, Debug)]
pub struct Annotation {
#[serde(rename="type")] pub typ: i32,
pub value: String,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct LinkData {
pub link_target: String,
pub display_url: Option<String>,
}
#[derive(Deserialize, Debug, Default)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Formatting {
#[serde(default)] pub bold: bool,
#[serde(default)] pub italics: bool,
#[serde(default)] pub strikethrough: bool,
#[serde(default)] pub underline: bool,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct AttachmentSegment {
pub embed_item: EmbedItem,
pub id: String,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct EmbedItem {
pub id: Option<String>,
pub plus_photo: Option<PlusPhoto>,
pub plus_audio_v2: Option<PlusAudioV2>,
pub place_v2: Option<PlaceV2>,
pub thing_v2: Option<ThingV2>,
#[serde(rename="type")] pub types: Vec<String>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct PlusPhoto {
pub album_id: String,
pub media_type: String,
pub original_content_url: Option<String>,
pub owner_obfuscated_id: Option<String>,
pub photo_id: String,
pub stream_id: Vec<String>,
pub thumbnail: Thumbnail,
pub url: String,
pub download_url: Option<String>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Thumbnail {
pub height_px: u64,
pub width_px: u64,
pub image_url: String,
pub url: Option<String>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct PlaceV2 {
pub url: String,
pub name: Option<String>,
pub address: Address,
pub geo: Geo,
pub representative_image: RepresentativeImage,
pub place_id: Option<String>,
pub cluster_id: Option<String>,
pub reference_id: Option<String>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct PlusAudioV2 {
pub album_id: String,
pub duration: String,
pub embed_url: String,
pub media_key: String,
pub owner_obfuscated_id: Option<String>,
pub photo_id: String,
pub url: String,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Address {
#[serde(rename="type", default)] pub types: Vec<String>,
pub postal_address_v2: PostalAddressV2,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct PostalAddressV2 {
pub name: Option<String>,
pub street_address: Option<String>,
pub address_locality: Option<String>,
pub address_region: Option<String>,
pub address_country: Option<String>,
pub postal_code: Option<String>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Geo {
#[serde(rename="type", default)] pub types: Vec<String>,
pub geo_coordinates_v2: GeoCoordinatesV2,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct GeoCoordinatesV2 {
pub latitude: f64,
pub longitude: f64,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct RepresentativeImage {
#[serde(rename="type")] pub types: Vec<String>,
pub id: String,
pub image_object_v2: ImageObjectV2,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ImageObjectV2 {
pub url: String,
pub width: Option<String>,
pub height: Option<String>,
}
#[derive(Deserialize, Debug)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub struct ThingV2 {
pub url: String,
pub name: Option<String>,
pub representative_image: RepresentativeImage,
}
#[derive(Deserialize, Debug)]
#[serde(tag="event_type")]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
pub enum HangoutEvent {
#[serde(rename="START_HANGOUT")] StartHangout,
#[serde(rename="END_HANGOUT")] EndHangout {
hangout_duration_secs: String,
},
}
|
use super::widget::WidgetKind;
use crate::{
cpu::{Breakpoint, InterruptKind, WatchKind, Watcher, CPU},
debug::{util::FromHexString, widget::Widget},
memory_map::Mem,
register::{Flag, Reg16, Reg8},
};
use crossterm::event::{KeyCode, KeyEvent};
use std::{borrow::Cow, io::Stdout};
use tui::{
backend::CrosstermBackend,
layout::Rect,
style::{Color, Style},
widgets::{Block, Borders, List, ListState, Text},
Frame,
};
fn parse_reg(input: String, cpu: &mut CPU) -> Result<(), Option<String>> {
match input.as_str() {
"af" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg16(Watcher::new(
Reg16::AF,
cpu,
))));
Ok(())
}
"bc" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg16(Watcher::new(
Reg16::BC,
cpu,
))));
Ok(())
}
"de" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg16(Watcher::new(
Reg16::DE,
cpu,
))));
Ok(())
}
"hl" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg16(Watcher::new(
Reg16::HL,
cpu,
))));
Ok(())
}
"sp" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg16(Watcher::new(
Reg16::SP,
cpu,
))));
Ok(())
}
"pc" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg16(Watcher::new(
Reg16::PC,
cpu,
))));
Ok(())
}
"a" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::A,
cpu,
))));
Ok(())
}
"f" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::F,
cpu,
))));
Ok(())
}
"b" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::B,
cpu,
))));
Ok(())
}
"c" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::C,
cpu,
))));
Ok(())
}
"d" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::D,
cpu,
))));
Ok(())
}
"e" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::E,
cpu,
))));
Ok(())
}
"h" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::H,
cpu,
))));
Ok(())
}
"l" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Reg8(Watcher::new(
Reg8::L,
cpu,
))));
Ok(())
}
_ => Err(None),
}
}
fn parse_memory(input: String, cpu: &mut CPU) -> Result<(), Option<String>> {
match u16::from_hex_string(input) {
Ok(addr) => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Mem(Watcher::new(
Mem(addr),
cpu,
))));
Ok(())
}
Err(_) => Err(None),
}
}
fn parse_flag(input: String, cpu: &mut CPU) -> Result<(), Option<String>> {
match input.as_str() {
"z" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Flag(Watcher::new(
Flag::Z,
cpu,
))));
Ok(())
}
"n" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Flag(Watcher::new(
Flag::Z,
cpu,
))));
Ok(())
}
"h" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Flag(Watcher::new(
Flag::Z,
cpu,
))));
Ok(())
}
"c" => {
cpu.breakpoints
.push(Breakpoint::Watch(WatchKind::Flag(Watcher::new(
Flag::Z,
cpu,
))));
Ok(())
}
_ => Err(None),
}
}
type ParseFunction = dyn Fn(String, &mut CPU) -> Result<(), Option<String>>;
enum Command {
Address,
Opcode,
Watch,
Interrupt,
}
/// Represents the widget responsible for displaying the different
/// breakpoints created during the debugging session.
pub struct BreakpointView {
init: bool,
selected: bool,
cursor: Option<usize>,
command: Option<Command>,
breakpoint_count: usize,
}
impl BreakpointView {
/// Creates a new `BreakpointView` widget.
pub fn new() -> Self {
BreakpointView {
init: false,
selected: false,
cursor: None,
command: None,
breakpoint_count: 0,
}
}
}
impl Widget for BreakpointView {
fn refresh(&mut self, cpu: &CPU) {
if self.cursor.is_none() && !cpu.breakpoints.is_empty() {
self.cursor = Some(0);
}
self.breakpoint_count = cpu.breakpoints.len();
}
fn draw(&mut self, f: &mut Frame<CrosstermBackend<Stdout>>, chunk: Rect, cpu: &CPU) {
if !self.init {
self.init = true;
self.refresh(cpu);
}
let items = cpu
.breakpoints
.iter()
.map(|b| Text::Raw(Cow::Owned(b.to_string(cpu))));
let mut list_state = ListState::default();
list_state.select(self.cursor);
let list = List::new(items)
.block(
Block::default()
.title("Breakpoints")
.title_style(self.title_style())
.borders(Borders::ALL),
)
.style(Style::default())
.highlight_style(Style::default().bg(Color::White).fg(Color::Black))
.highlight_symbol("> ");
f.render_stateful_widget(list, chunk, &mut list_state);
}
fn select(&mut self) {
self.selected = true;
}
fn deselect(&mut self) {
self.selected = false;
}
fn is_selected(&self) -> bool {
self.selected
}
fn handle_key(&mut self, key: KeyEvent, cpu: &mut CPU) -> Option<(WidgetKind, String)> {
match key.code {
KeyCode::Char('b') => {
self.command = Some(Command::Address);
Some((WidgetKind::Breakpoints, "Break at address:".to_string()))
}
KeyCode::Char('o') => {
self.command = Some(Command::Opcode);
Some((WidgetKind::Breakpoints, "Break at opcode:".to_string()))
}
KeyCode::Char('w') => {
self.command = Some(Command::Watch);
Some((WidgetKind::Breakpoints, "Watch:".to_string()))
}
KeyCode::Char('i') => {
self.command = Some(Command::Interrupt);
Some((WidgetKind::Breakpoints, "Watch interrupt:".to_string()))
}
KeyCode::Char('d') => {
if let Some(idx) = &self.cursor {
cpu.breakpoints.remove(*idx);
let len = cpu.breakpoints.len();
self.cursor = if len == 0 {
None
} else {
Some((*idx).min(len.saturating_sub(1)))
}
}
None
}
KeyCode::Down => {
if let Some(idx) = &self.cursor {
self.cursor = Some(idx.saturating_add(1).min(self.breakpoint_count - 1));
}
None
}
KeyCode::Up => {
if let Some(idx) = &self.cursor {
self.cursor = Some(idx.saturating_sub(1));
}
None
}
_ => None,
}
}
fn process_input(&mut self, input: String, cpu: &mut CPU) -> Result<(), Option<String>> {
if let Some(command) = &self.command {
match command {
Command::Address => match u16::from_hex_string(input) {
Ok(addr) => {
cpu.breakpoints.push(Breakpoint::Address(addr));
Ok(())
}
Err(_) => Err(None),
},
Command::Opcode => match u8::from_hex_string(input) {
Ok(op) => {
cpu.breakpoints.push(Breakpoint::Opcode(op));
Ok(())
}
Err(_) => Err(None),
},
Command::Watch => {
let kinds: Vec<(&str, &ParseFunction)> = vec![
("memory", &parse_memory),
("register", &parse_reg),
("flag", &parse_flag),
];
kinds
.into_iter()
.filter_map(|(s, f)| {
let lowercase = input.to_lowercase();
let tokens = lowercase.split(' ').take(2).collect::<Vec<&str>>();
if tokens.len() == 2 {
let (kind, input) = (tokens[0], tokens[1]);
if s.starts_with(kind.to_lowercase().as_str()) {
Some((f)(input.to_string(), cpu))
} else {
None
}
} else {
None
}
})
.next()
.unwrap_or(Err(None))
}
Command::Interrupt => {
let kinds: Vec<(&'static str, InterruptKind)> = vec![
("vblank", InterruptKind::VBlank),
("lcd", InterruptKind::LCD),
("timer", InterruptKind::Timer),
("serial", InterruptKind::SerialIO),
("joypad", InterruptKind::Joypad),
];
kinds
.into_iter()
.filter_map(|(k, i)| {
let input = input.to_lowercase();
if k.starts_with(input.as_str()) {
Some(i)
} else {
None
}
})
.next()
.map(|i| {
cpu.add_breakpoint(Breakpoint::Interrupt(i));
Ok(())
})
.unwrap_or(Err(None))
}
}
} else {
Ok(())
}
}
}
|
pub mod macaroon_builder;
pub mod v1;
pub mod v2;
pub mod v2j;
pub enum Format {
V1,
V2,
V2J,
}
|
use std::time::Duration;
use naia_shared::{wrapping_diff, Instant};
/// Manages the current tick for the host
#[derive(Debug)]
pub struct ClientTickManager {
tick_interval: Duration,
tick_interval_f32: f32,
server_tick: u16,
client_tick_adjust: u16,
server_tick_adjust: u16,
server_tick_running_diff: i16,
last_tick_instant: Instant,
pub fraction: f32,
accumulator: f32,
has_ticked: bool,
}
impl ClientTickManager {
/// Create a new HostTickManager with a given tick interval duration
pub fn new(tick_interval: Duration) -> Self {
ClientTickManager {
tick_interval,
tick_interval_f32: tick_interval.as_nanos() as f32 / 1000000000.0,
server_tick: 1,
client_tick_adjust: 0,
server_tick_adjust: 0,
server_tick_running_diff: 0,
last_tick_instant: Instant::now(),
accumulator: 0.0,
fraction: 0.0,
has_ticked: false,
}
}
pub fn mark_frame(&mut self) -> bool {
let mut ticked = false;
let mut frame_time = self.last_tick_instant.elapsed().as_nanos() as f32 / 1000000000.0;
if frame_time > 0.25 {
frame_time = 0.25;
}
self.accumulator += frame_time;
self.last_tick_instant = Instant::now();
if self.accumulator >= self.tick_interval_f32 {
while self.accumulator >= self.tick_interval_f32 {
self.accumulator -= self.tick_interval_f32;
}
// tick has occurred
ticked = true;
self.has_ticked = true;
self.server_tick = self.server_tick.wrapping_add(1);
}
self.fraction = self.accumulator / self.tick_interval_f32;
ticked
}
/// If the tick interval duration has elapsed, increment the current tick
pub fn take_tick(&mut self) -> bool {
if self.has_ticked {
self.has_ticked = false;
return true;
}
return false;
}
/// Use tick data from initial server handshake to set the initial tick
pub fn set_initial_tick(&mut self, server_tick: u16) {
self.server_tick = server_tick;
self.server_tick_adjust = ((1000 / (self.tick_interval.as_millis())) + 1) as u16;
self.client_tick_adjust = ((3000 / (self.tick_interval.as_millis())) + 1) as u16;
}
/// Using information from the Server and RTT/Jitter measurements, determine
/// the appropriate future intended tick
pub fn record_server_tick(
&mut self,
server_tick: u16,
rtt_average: f32,
jitter_deviation: f32,
) {
self.server_tick_running_diff += wrapping_diff(self.server_tick, server_tick);
// Decay the diff so that small fluctuations are acceptable
if self.server_tick_running_diff > 0 {
self.server_tick_running_diff = self.server_tick_running_diff.wrapping_sub(1);
}
if self.server_tick_running_diff < 0 {
self.server_tick_running_diff = self.server_tick_running_diff.wrapping_add(1);
}
// If the server tick is far off enough, reset to the received server tick
if self.server_tick_running_diff.abs() > 8 {
self.server_tick = server_tick;
self.server_tick_running_diff = 0;
}
// Calculate incoming & outgoing jitter buffer tick offsets
self.server_tick_adjust =
((((jitter_deviation * 3.0) / 2.0) / self.tick_interval.as_millis() as f32) + 1.0)
.ceil() as u16;
self.client_tick_adjust = (((rtt_average + (jitter_deviation * 3.0) / 2.0)
/ (self.tick_interval.as_millis() as f32))
+ 1.0)
.ceil() as u16;
}
/// Gets a reference to the tick interval used
pub fn get_tick_interval(&self) -> &Duration {
return &self.tick_interval;
}
/// Gets the server tick with the incoming jitter buffer offset applied
pub fn get_server_tick(&self) -> u16 {
return self.server_tick.wrapping_sub(self.server_tick_adjust);
}
/// Gets the client tick with the outgoing jitter buffer offset applied
pub fn get_client_tick(&self) -> u16 {
return self.server_tick.wrapping_add(self.client_tick_adjust);
}
}
|
use crate::{
database::Database,
debug,
utils::{module_for_path, packages_path},
Exit, ProgramResult,
};
use candy_frontend::{TracingConfig, TracingMode};
use candy_vm::mir_to_lir::compile_lir;
use clap::{Parser, ValueHint};
use std::path::PathBuf;
use tracing::{error, info};
/// Fuzz a Candy module.
///
/// This command runs the given file or, if no file is provided, the package of
/// your current working directory. It finds all fuzzable functions and then
/// fuzzes them.
///
/// Fuzzable functions are functions written without curly braces.
#[derive(Parser, Debug)]
pub(crate) struct Options {
/// The file or package to fuzz. If none is provided, the package of your
/// current working directory will be fuzzed.
#[arg(value_hint = ValueHint::FilePath)]
path: Option<PathBuf>,
}
pub(crate) fn fuzz(options: Options) -> ProgramResult {
let db = Database::new_with_file_system_module_provider(packages_path());
let module = module_for_path(options.path)?;
let tracing = TracingConfig {
register_fuzzables: TracingMode::All,
calls: TracingMode::Off,
evaluated_expressions: TracingMode::Off,
};
let (lir, _) = compile_lir(&db, module.clone(), tracing);
debug!("Fuzzing `{module}`…");
let failing_cases = candy_fuzzer::fuzz(&db, module);
if failing_cases.is_empty() {
info!("All found fuzzable functions seem fine.");
Ok(())
} else {
error!("");
error!("Finished fuzzing.");
error!("These are the failing cases:");
for case in failing_cases {
error!("");
case.dump(&db, &lir.symbol_table);
}
Err(Exit::FuzzingFoundFailingCases)
}
}
|
use async_compression::Level;
use hyper::header::HeaderValue;
#[derive(Copy, Clone, Debug)]
pub enum Encoding {
Gzip(Level),
Deflate(Level),
Br(Level),
}
impl Encoding {
// Response header content-encoding
pub fn to_header_value(self) -> HeaderValue {
let encoding = match self {
Encoding::Gzip(_) => "gzip",
Encoding::Deflate(_) => "deflate",
Encoding::Br(_) => "br",
};
HeaderValue::from_static(encoding)
}
}
#[derive(Debug, Clone, Copy)]
pub enum CompressMode {
Auto(Level),
Gzip(Level),
Deflate(Level),
Br(Level),
None,
}
impl CompressMode {
pub fn new(mode: &str, level: Level) -> Result<Self, String> {
match mode {
"auto" => Ok(CompressMode::Auto(level)),
"gzip" => Ok(CompressMode::Gzip(level)),
"deflate" => Ok(CompressMode::Deflate(level)),
"br" => Ok(CompressMode::Br(level)),
_ => Err(format!(
"Wrong compression mode `{}`, optional value: `auto` `gzip` `deflate` `br`",
mode
)),
}
}
pub fn encoding(self, modes: &[&str]) -> Option<Encoding> {
match self {
CompressMode::Auto(level) => {
for mode in modes {
match *mode {
"gzip" => return Some(Encoding::Gzip(level)),
"deflate" => return Some(Encoding::Deflate(level)),
"br" => return Some(Encoding::Br(level)),
_ => {}
};
}
}
CompressMode::Gzip(level) => {
if modes.contains(&"gzip") {
return Some(Encoding::Gzip(level));
}
}
CompressMode::Deflate(level) => {
if modes.contains(&"deflate") {
return Some(Encoding::Deflate(level));
}
}
CompressMode::Br(level) => {
if modes.contains(&"br") {
return Some(Encoding::Br(level));
}
}
_ => {}
}
None
}
}
|
//! Declarative dataflow infrastructure
//!
//! This crate contains types, traits, and logic for assembling
//! differential dataflow computations from declaratively specified
//! programs, without any additional compilation.
#![forbid(missing_docs)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
pub mod binding;
pub mod derive;
pub mod domain;
pub mod logging;
pub mod operators;
pub mod plan;
pub mod scheduling;
pub mod server;
pub mod sinks;
pub mod sources;
pub mod timestamp;
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::Duration;
use timely::dataflow::operators::CapabilitySet;
use timely::dataflow::scopes::child::Iterative;
use timely::dataflow::*;
use timely::order::Product;
use timely::progress::Timestamp;
use differential_dataflow::lattice::Lattice;
use differential_dataflow::operators::arrange::{ShutdownButton, TraceAgent};
use differential_dataflow::operators::iterate::Variable;
#[cfg(not(feature = "set-semantics"))]
use differential_dataflow::operators::Consolidate;
#[cfg(feature = "set-semantics")]
use differential_dataflow::operators::Threshold;
use differential_dataflow::trace::implementations::ord::{OrdKeySpine, OrdValSpine};
use differential_dataflow::{Collection, ExchangeData};
pub use uuid::Uuid;
pub use num_rational::Rational32;
pub use binding::{AsBinding, AttributeBinding, Binding};
pub use domain::Domain;
pub use plan::{Hector, Implementable, Plan};
pub use timestamp::{Rewind, Time};
/// A unique entity identifier.
pub type Eid = u64;
/// A unique attribute identifier.
pub type Aid = String; // u32
/// A unique attribute identifier.
pub trait AsAid:
Clone + Eq + Ord + std::hash::Hash + std::fmt::Display + std::fmt::Debug + From<String> + 'static
{
/// Moves self into the specified namespace.
fn with_namespace(&self, namespace: Self) -> Self;
/// Converts the aid into a value for use in a query result.
fn into_value(self) -> Value;
}
impl AsAid for String {
fn with_namespace(&self, namespace: Self) -> Self {
format!("{}/{}", namespace, self)
}
fn into_value(self) -> Value {
Value::Aid(self)
}
}
/// Possible data values.
///
/// This enum captures the currently supported data types, and is the
/// least common denominator for the types of records moved around.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub enum Value {
/// An attribute identifier
Aid(Aid),
/// A string
String(String),
/// A boolean
Bool(bool),
/// A 64 bit signed integer
Number(i64),
/// A 32 bit rational
Rational32(Rational32),
/// An entity identifier
Eid(Eid),
/// Milliseconds since midnight, January 1, 1970 UTC
Instant(u64),
/// A 16 byte unique identifier.
Uuid(Uuid),
/// A fixed-precision real number.
#[cfg(feature = "real")]
Real(fixed::types::I16F16),
}
impl Value {
/// Helper to create an Aid value from a string representation.
pub fn aid(v: &str) -> Self {
Value::Aid(v.to_string())
}
/// Helper to create a UUID value from a string representation.
pub fn uuid_str(v: &str) -> Self {
let uuid = Uuid::parse_str(v).expect("failed to parse UUID");
Value::Uuid(uuid)
}
}
impl std::convert::From<&str> for Value {
fn from(v: &str) -> Self {
Value::String(v.to_string())
}
}
#[cfg(feature = "real")]
impl std::convert::From<f64> for Value {
fn from(v: f64) -> Self {
let real =
fixed::types::I16F16::checked_from_float(v).expect("failed to convert to I16F16");
Value::Real(real)
}
}
#[cfg(feature = "serde_json")]
impl std::convert::From<Value> for serde_json::Value {
fn from(v: Value) -> Self {
match v {
Value::Eid(v) => serde_json::Value::String(v.to_string()),
Value::Aid(v) => serde_json::Value::String(v),
Value::String(v) => serde_json::Value::String(v),
Value::Bool(v) => serde_json::Value::Bool(v),
Value::Number(v) => serde_json::Value::Number(serde_json::Number::from(v)),
_ => unimplemented!(),
}
}
}
impl std::convert::From<Value> for Eid {
fn from(v: Value) -> Eid {
if let Value::Eid(eid) = v {
eid
} else {
panic!("Value {:?} can't be converted to Eid", v);
}
}
}
/// A client-facing, non-exceptional error.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Error {
/// Error category.
#[serde(rename = "df.error/category")]
pub category: String,
/// Free-frorm description.
#[serde(rename = "df.error/message")]
pub message: String,
}
impl Error {
/// Fix client bug.
pub fn incorrect<E: std::string::ToString>(error: E) -> Error {
Error {
category: "df.error.category/incorrect".to_string(),
message: error.to_string(),
}
}
/// Fix client noun.
pub fn not_found<E: std::string::ToString>(error: E) -> Error {
Error {
category: "df.error.category/not-found".to_string(),
message: error.to_string(),
}
}
/// Coordinate with worker.
pub fn conflict<E: std::string::ToString>(error: E) -> Error {
Error {
category: "df.error.category/conflict".to_string(),
message: error.to_string(),
}
}
/// Fix worker bug.
pub fn fault<E: std::string::ToString>(error: E) -> Error {
Error {
category: "df.error.category/fault".to_string(),
message: error.to_string(),
}
}
/// Fix client verb.
pub fn unsupported<E: std::string::ToString>(error: E) -> Error {
Error {
category: "df.error.category/unsupported".to_string(),
message: error.to_string(),
}
}
}
/// Transaction data.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub struct Datom<A>(pub Value, pub A, pub Value, pub Option<Time>, pub isize);
impl<A: AsAid + ExchangeData> Datom<A> {
/// Creates a datom representing the addition of a single fact.
pub fn add<X: Into<A>>(e: Eid, a: X, v: Value) -> Self {
Self(Value::Eid(e), a.into(), v, None, 1)
}
/// Creates a datom representing the addition of a single fact at
/// a specific point in time.
pub fn add_at<X: Into<A>>(e: Eid, a: X, v: Value, t: Time) -> Self {
Self(Value::Eid(e), a.into(), v, Some(t), 1)
}
/// Creates a datom representing the retraction of a single fact.
pub fn retract<X: Into<A>>(e: Eid, a: X, v: Value) -> Self {
Self(Value::Eid(e), a.into(), v, None, -1)
}
/// Creates a datom representing the retraction of a single fact
/// at a specific point in time.
pub fn retract_at<X: Into<A>>(e: Eid, a: X, v: Value, t: Time) -> Self {
Self(Value::Eid(e), a.into(), v, Some(t), -1)
}
}
/// A (tuple, time, diff) triple, as sent back to clients.
pub type ResultDiff<T> = (Vec<Value>, T, isize);
/// A worker-local client connection identifier.
pub type Client = usize;
/// Anything that can be returned to clients.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Output {
/// A batch of (tuple, time, diff) triples as returned by Datalog
/// queries.
QueryDiff(String, Vec<ResultDiff<Time>>),
/// A JSON object, e.g. as returned by GraphQL queries.
#[cfg(feature = "serde_json")]
Json(String, serde_json::Value, Time, isize),
/// A message forwarded to a specific client.
#[cfg(feature = "serde_json")]
Message(Client, serde_json::Value),
/// An error forwarded to a specific client.
Error(Client, Error, server::TxId),
}
/// A trace of values indexed by self.
pub type TraceKeyHandle<K, T, R> = TraceAgent<OrdKeySpine<K, T, R>>;
/// A trace of (K, V) pairs indexed by key.
pub type TraceValHandle<K, V, T, R> = TraceAgent<OrdValSpine<K, V, T, R>>;
// A map for keeping track of collections that are being actively
// synthesized (i.e. that are not fully defined yet).
type VariableMap<A, S> = HashMap<A, Variable<S, Vec<Value>, isize>>;
trait Shutdownable {
fn press(&mut self);
}
impl<T> Shutdownable for ShutdownButton<T> {
#[inline(always)]
fn press(&mut self) {
self.press();
}
}
/// A wrapper around a vector of ShutdownButton's. Ensures they will
/// be pressed on dropping the handle.
pub struct ShutdownHandle {
shutdown_buttons: Vec<Box<dyn Shutdownable>>,
}
impl Drop for ShutdownHandle {
fn drop(&mut self) {
for mut button in self.shutdown_buttons.drain(..) {
trace!("pressing shutdown button");
button.press();
}
}
}
impl ShutdownHandle {
/// Returns an empty shutdown handle.
pub fn empty() -> Self {
ShutdownHandle {
shutdown_buttons: Vec::new(),
}
}
/// Wraps a single shutdown button into a shutdown handle.
pub fn from_button<T: Timestamp>(button: ShutdownButton<CapabilitySet<T>>) -> Self {
ShutdownHandle {
shutdown_buttons: vec![Box::new(button)],
}
}
/// Adds another shutdown button to this handle. This button will
/// then also be pressed, whenever the handle is shut down or
/// dropped.
pub fn add_button<T: Timestamp>(&mut self, button: ShutdownButton<CapabilitySet<T>>) {
self.shutdown_buttons.push(Box::new(button));
}
/// Combines the buttons of another handle into self.
pub fn merge_with(&mut self, mut other: Self) {
self.shutdown_buttons.append(&mut other.shutdown_buttons);
}
/// Combines two shutdown handles into a single one, which will
/// control both.
pub fn merge(mut left: Self, mut right: Self) -> Self {
let mut shutdown_buttons =
Vec::with_capacity(left.shutdown_buttons.len() + right.shutdown_buttons.len());
shutdown_buttons.append(&mut left.shutdown_buttons);
shutdown_buttons.append(&mut right.shutdown_buttons);
ShutdownHandle { shutdown_buttons }
}
}
/// Attribute indices can have various operations applied to them,
/// based on their semantics.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub enum InputSemantics {
/// No special semantics enforced. Source is responsible for
/// everything.
Raw,
/// Only the last input for each eid is kept.
LastWriteWins,
// @TODO
// /// Only the first input for each eid is kept, all subsequent ones
// /// ignored.
// FirstWriteWins,
/// Multiple different values for any given eid are allowed, but
/// (e,v) pairs are enforced to be distinct.
Distinct,
// /// @TODO
// CAS,
}
/// Attributes can be indexed in two ways, once from eid to value and
/// the other way around. More powerful query capabilities may rely on
/// both directions being available, whereas simple queries, such as
/// star-joins and pull queries, might get by with just a forward
/// index.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub enum IndexDirection {
/// Forward index only.
Forward,
/// Both directions are maintained.
Both,
}
/// Attributes might only appear in certain classes of queries. If
/// that is the case, indexing overhead can be reduced.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub enum QuerySupport {
/// Simple pull queries and star-joins require only a single
/// index.
Basic = 0,
/// Delta queries require an additional index for validation of
/// proposals.
Delta = 1,
/// Adaptive, worst-case optimal queries require three indices per
/// direction, one for proposals, one for validation, and one for
/// per-key statistics.
AdaptiveWCO = 2,
}
/// Per-attribute semantics.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub struct AttributeConfig {
/// Modifiers to apply on attribute inputs, such as keeping only
/// the most recent value per eid, or compare-and-swap.
pub input_semantics: InputSemantics,
/// How close indexed traces should follow the computation
/// frontier.
pub trace_slack: Option<Time>,
/// Index directions to maintain for this attribute.
pub index_direction: IndexDirection,
/// Query capabilities supported by this attribute.
pub query_support: QuerySupport,
}
impl Default for AttributeConfig {
fn default() -> Self {
AttributeConfig {
input_semantics: InputSemantics::Raw,
trace_slack: None,
index_direction: IndexDirection::Forward,
query_support: QuerySupport::Basic,
}
}
}
impl AttributeConfig {
/// Shortcut to specifying an attribute that will live in some
/// transaction time domain and always compact up to the
/// computation frontier.
pub fn tx_time(input_semantics: InputSemantics) -> Self {
AttributeConfig {
input_semantics,
// @TODO It's not super clear yet, whether this can be
// 0. There might be an off-by-one error hidden somewhere,
// s.t. traces advance to t+1 when we're still accepting
// inputs for t+1.
trace_slack: Some(Time::TxId(1)),
..Default::default()
}
}
/// Shortcut to specifying an attribute that will live in some
/// real-time domain and always compact up to the computation
/// frontier.
pub fn real_time(input_semantics: InputSemantics) -> Self {
AttributeConfig {
input_semantics,
trace_slack: Some(Time::Real(Duration::from_secs(0))),
..Default::default()
}
}
/// Shortcut to specifying an attribute that will live in an
/// arbitrary time domain and never compact its trace.
pub fn uncompacted(input_semantics: InputSemantics) -> Self {
AttributeConfig {
input_semantics,
trace_slack: None,
..Default::default()
}
}
}
/// A variable used in a query.
type Var = u32;
/// A named relation.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub struct Rule<A: AsAid> {
/// The name identifying the relation.
pub name: A,
/// The plan describing contents of the relation.
pub plan: Plan<A>,
}
impl<A: AsAid> Rule<A> {
/// Returns a named rule from a given plan.
pub fn named<X: Into<A>>(name: X, plan: Plan<A>) -> Self {
Rule {
name: name.into(),
plan,
}
}
}
/// A relation between a set of variables.
///
/// Relations can be backed by a collection of records of type
/// `Vec<Value>`, each of a common length (with offsets corresponding
/// to the variable offsets), or by an existing arrangement.
trait Relation<'a, A, S>: AsBinding
where
A: AsAid,
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
/// A collection containing all tuples.
fn tuples(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
);
/// A collection containing all tuples projected onto the
/// specified variables.
fn projected(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
target_variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
);
/// A collection with tuples partitioned by `variables`.
///
/// Each tuple is mapped to a pair `(Vec<Value>, Vec<Value>)`
/// containing first exactly those variables in `variables` in that
/// order, followed by the remaining values in their original
/// order.
fn tuples_by_variables(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, (Vec<Value>, Vec<Value>), isize>,
ShutdownHandle,
);
}
/// A collection and variable bindings.
pub struct CollectionRelation<'a, S: Scope> {
variables: Vec<Var>,
tuples: Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
}
impl<'a, S> AsBinding for CollectionRelation<'a, S>
where
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
fn variables(&self) -> Vec<Var> {
self.variables.clone()
}
fn binds(&self, variable: Var) -> Option<usize> {
self.variables.binds(variable)
}
fn ready_to_extend(&self, _prefix: &AsBinding) -> Option<Var> {
unimplemented!();
}
fn required_to_extend(&self, _prefix: &AsBinding, _target: Var) -> Option<Option<Var>> {
unimplemented!();
}
}
impl<'a, A, S> Relation<'a, A, S> for CollectionRelation<'a, S>
where
A: AsAid,
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
fn tuples(
self,
_nested: &mut Iterative<'a, S, u64>,
_domain: &mut Domain<A, S::Timestamp>,
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
) {
(self.tuples, ShutdownHandle::empty())
}
fn projected(
self,
_nested: &mut Iterative<'a, S, u64>,
_domain: &mut Domain<A, S::Timestamp>,
target_variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
) {
if self.variables() == target_variables {
(self.tuples, ShutdownHandle::empty())
} else {
let relation_variables = self.variables();
let target_variables = target_variables.to_vec();
let tuples = self.tuples.map(move |tuple| {
target_variables
.iter()
.map(|x| {
let idx = relation_variables.binds(*x).unwrap();
tuple[idx].clone()
})
.collect()
});
(tuples, ShutdownHandle::empty())
}
}
fn tuples_by_variables(
self,
_nested: &mut Iterative<'a, S, u64>,
_domain: &mut Domain<A, S::Timestamp>,
variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, (Vec<Value>, Vec<Value>), isize>,
ShutdownHandle,
) {
if variables == &self.variables()[..] {
(
self.tuples.map(|x| (x, Vec::new())),
ShutdownHandle::empty(),
)
} else if variables.is_empty() {
(
self.tuples.map(|x| (Vec::new(), x)),
ShutdownHandle::empty(),
)
} else {
let key_length = variables.len();
let values_length = self.variables().len() - key_length;
let mut key_offsets: Vec<usize> = Vec::with_capacity(key_length);
let mut value_offsets: Vec<usize> = Vec::with_capacity(values_length);
let variable_set: HashSet<Var> = variables.iter().cloned().collect();
// It is important to preserve the key variables in the order
// they were specified.
for variable in variables.iter() {
key_offsets.push(self.binds(*variable).unwrap());
}
// Values we'll just take in the order they were.
for (idx, variable) in self.variables().iter().enumerate() {
if !variable_set.contains(variable) {
value_offsets.push(idx);
}
}
let arranged = self.tuples.map(move |tuple| {
let key: Vec<Value> = key_offsets.iter().map(|i| tuple[*i].clone()).collect();
// @TODO second clone not really neccessary
let values: Vec<Value> = value_offsets
.iter()
.map(move |i| tuple[*i].clone())
.collect();
(key, values)
});
(arranged, ShutdownHandle::empty())
}
}
}
impl<'a, A, S> Relation<'a, A, S> for AttributeBinding<A>
where
A: AsAid,
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
fn tuples(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
) {
let variables = self.variables();
self.projected(nested, domain, &variables)
}
fn projected(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
target_variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
) {
match domain.forward_propose(&self.source_attribute) {
None => panic!("attribute {:?} does not exist", self.source_attribute),
Some(propose_trace) => {
let (propose, shutdown_propose) = propose_trace
.import_frontier(&nested.parent, &format!("{:?}", &self.source_attribute));
let tuples = propose.enter(&nested);
let (e, v) = self.variables;
let projected = if target_variables == [e, v] {
tuples.as_collection(|e, v| vec![e.clone(), v.clone()])
} else if target_variables == [v, e] {
tuples.as_collection(|e, v| vec![v.clone(), e.clone()])
} else if target_variables == [e] {
tuples.as_collection(|e, _v| vec![e.clone()])
} else if target_variables == [v] {
tuples.as_collection(|_e, v| vec![v.clone()])
} else {
panic!("invalid projection")
};
(projected, ShutdownHandle::from_button(shutdown_propose))
}
}
}
fn tuples_by_variables(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, (Vec<Value>, Vec<Value>), isize>,
ShutdownHandle,
) {
match domain.forward_propose(&self.source_attribute) {
None => panic!("attribute {:?} does not exist", self.source_attribute),
Some(propose_trace) => {
let (propose, shutdown_propose) = propose_trace
.import_frontier(&nested.parent, &format!("{:?}", &self.source_attribute));
let tuples = propose.enter(&nested);
let (e, v) = self.variables;
let arranged = if variables == [e, v] {
tuples.as_collection(|e, v| (vec![e.clone(), v.clone()], vec![]))
} else if variables == [v, e] {
tuples.as_collection(|e, v| (vec![v.clone(), e.clone()], vec![]))
} else if variables == [e] {
tuples.as_collection(|e, v| (vec![e.clone()], vec![v.clone()]))
} else if variables == [v] {
tuples.as_collection(|e, v| (vec![v.clone()], vec![e.clone()]))
} else {
panic!("invalid projection")
};
(arranged, ShutdownHandle::from_button(shutdown_propose))
}
}
}
}
/// @TODO
pub enum Implemented<'a, A, S>
where
A: AsAid,
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
/// A relation backed by an attribute.
Attribute(AttributeBinding<A>),
/// A relation backed by a Differential collection.
Collection(CollectionRelation<'a, S>),
// Arranged(ArrangedRelation<'a, S>)
}
impl<'a, A, S> AsBinding for Implemented<'a, A, S>
where
A: AsAid,
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
fn variables(&self) -> Vec<Var> {
match self {
Implemented::Attribute(attribute_binding) => attribute_binding.variables(),
Implemented::Collection(relation) => relation.variables(),
}
}
fn binds(&self, variable: Var) -> Option<usize> {
match self {
Implemented::Attribute(attribute_binding) => attribute_binding.binds(variable),
Implemented::Collection(relation) => relation.binds(variable),
}
}
fn ready_to_extend(&self, prefix: &AsBinding) -> Option<Var> {
match self {
Implemented::Attribute(attribute_binding) => attribute_binding.ready_to_extend(prefix),
Implemented::Collection(relation) => relation.ready_to_extend(prefix),
}
}
fn required_to_extend(&self, prefix: &AsBinding, target: Var) -> Option<Option<Var>> {
match self {
Implemented::Attribute(attribute_binding) => {
attribute_binding.required_to_extend(prefix, target)
}
Implemented::Collection(relation) => relation.required_to_extend(prefix, target),
}
}
}
impl<'a, A, S> Relation<'a, A, S> for Implemented<'a, A, S>
where
A: AsAid,
S: Scope,
S::Timestamp: Lattice + Rewind + ExchangeData,
{
fn tuples(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
) {
match self {
Implemented::Attribute(attribute_binding) => attribute_binding.tuples(nested, domain),
Implemented::Collection(relation) => relation.tuples(nested, domain),
}
}
fn projected(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
target_variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, Vec<Value>, isize>,
ShutdownHandle,
) {
match self {
Implemented::Attribute(attribute_binding) => {
attribute_binding.projected(nested, domain, target_variables)
}
Implemented::Collection(relation) => {
relation.projected(nested, domain, target_variables)
}
}
}
fn tuples_by_variables(
self,
nested: &mut Iterative<'a, S, u64>,
domain: &mut Domain<A, S::Timestamp>,
variables: &[Var],
) -> (
Collection<Iterative<'a, S, u64>, (Vec<Value>, Vec<Value>), isize>,
ShutdownHandle,
) {
match self {
Implemented::Attribute(attribute_binding) => {
attribute_binding.tuples_by_variables(nested, domain, variables)
}
Implemented::Collection(relation) => {
relation.tuples_by_variables(nested, domain, variables)
}
}
}
}
/// A arrangement and variable bindings.
// struct ArrangedRelation<'a, S>
// where
// S: Scope
// S::Timestamp: Lattice+ExchangeData
// {
// variables: Vec<Var>,
// tuples: Arranged<Iterative<'a, S, u64>, Vec<Value>, Vec<Value>, isize,
// TraceValHandle<Vec<Value>, Vec<Value>, Product<S::Timestamp,u64>, isize>>,
// }
/// Helper function to create a query plan. The resulting query will
/// provide values for the requested target variables, under the
/// constraints expressed by the bindings provided.
pub fn q<A: AsAid + timely::ExchangeData>(
target_variables: Vec<Var>,
bindings: Vec<Binding<A>>,
) -> Plan<A> {
Plan::Hector(Hector {
variables: target_variables,
bindings,
})
}
/// Returns a deduplicates list of all rules used in the definition of
/// the specified names. Includes the specified names.
pub fn collect_dependencies<A, T>(domain: &Domain<A, T>, names: &[A]) -> Result<Vec<Rule<A>>, Error>
where
A: AsAid + timely::ExchangeData,
T: Timestamp + Lattice + Rewind,
{
let mut seen = HashSet::new();
let mut rules = Vec::new();
let mut queue = VecDeque::new();
for name in names {
match domain.rule(name) {
None => {
return Err(Error::not_found(format!("Unknown rule {}.", name)));
}
Some(rule) => {
seen.insert(name.clone());
queue.push_back(rule.clone());
}
}
}
while let Some(next) = queue.pop_front() {
let dependencies = next.plan.dependencies();
for dep_name in dependencies.names.into_iter() {
if !seen.contains(&dep_name) {
match domain.rule(&dep_name) {
None => {
return Err(Error::not_found(format!("Unknown rule {}", dep_name)));
}
Some(rule) => {
seen.insert(dep_name);
queue.push_back(rule.clone());
}
}
}
}
// Ensure all required attributes exist.
for aid in dependencies.attributes.iter() {
if !domain.has_attribute(aid) {
return Err(Error::not_found(format!(
"Rule {:?} depends on unknown attribute",
aid
)));
}
}
rules.push(next);
}
Ok(rules)
}
/// Takes a query plan and turns it into a differential dataflow.
pub fn implement<A, S>(
scope: &mut S,
domain: &mut Domain<A, S::Timestamp>,
name: A,
) -> Result<(HashMap<A, Collection<S, Vec<Value>, isize>>, ShutdownHandle), Error>
where
A: AsAid + timely::ExchangeData,
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind + Default,
{
scope.iterative::<u64, _, _>(|nested| {
let publish = vec![name.clone()];
let mut rules = collect_dependencies(domain, &publish[..])?;
let mut local_arrangements = VariableMap::new();
let mut result_map = HashMap::new();
// Step 0: Canonicalize, check uniqueness of bindings.
if rules.is_empty() {
return Err(Error::not_found(format!(
"Couldn't find any rules for name {}.",
name
)));
}
rules.sort_by(|x, y| x.name.cmp(&y.name));
for index in 1..rules.len() - 1 {
if rules[index].name == rules[index - 1].name {
return Err(Error::conflict(format!(
"Duplicate rule definitions for rule {}",
rules[index].name
)));
}
}
// Step 1: Create new recursive variables for each rule.
for rule in rules.iter() {
local_arrangements.insert(
rule.name.clone(),
Variable::new(nested, Product::new(Default::default(), 1)),
);
}
// Step 2: Create public arrangements for published relations.
for name in publish.into_iter() {
if let Some(relation) = local_arrangements.get(&name) {
result_map.insert(name, relation.leave());
} else {
return Err(Error::not_found(format!(
"Attempted to publish undefined name {}.",
name
)));
}
}
// Step 3: Define the executions for each rule.
let mut executions = Vec::with_capacity(rules.len());
let mut shutdown_handle = ShutdownHandle::empty();
for rule in rules.iter() {
info!("planning {:?}", rule.name);
let (relation, shutdown) = rule.plan.implement(nested, domain, &local_arrangements);
executions.push(relation);
shutdown_handle.merge_with(shutdown);
}
// Step 4: Complete named relations in a specific order (sorted by name).
for (rule, execution) in rules.iter().zip(executions.drain(..)) {
match local_arrangements.remove(&rule.name) {
None => {
return Err(Error::not_found(format!(
"Rule {:?} should be in local arrangements, but isn't.",
&rule.name
)));
}
Some(variable) => {
let (tuples, shutdown) = execution.tuples(nested, domain);
shutdown_handle.merge_with(shutdown);
#[cfg(feature = "set-semantics")]
variable.set(&tuples.distinct());
#[cfg(not(feature = "set-semantics"))]
variable.set(&tuples.consolidate());
}
}
}
Ok((result_map, shutdown_handle))
})
}
/// @TODO
pub fn implement_neu<A, S>(
scope: &mut S,
domain: &mut Domain<A, S::Timestamp>,
name: A,
) -> Result<(HashMap<A, Collection<S, Vec<Value>, isize>>, ShutdownHandle), Error>
where
A: AsAid + timely::ExchangeData,
S: Scope,
S::Timestamp: Timestamp + Lattice + Rewind + Default,
{
scope.iterative::<u64, _, _>(move |nested| {
let publish = vec![name.clone()];
let mut rules = collect_dependencies(domain, &publish[..])?;
let mut local_arrangements = VariableMap::new();
let mut result_map = HashMap::new();
// Step 0: Canonicalize, check uniqueness of bindings.
if rules.is_empty() {
return Err(Error::not_found(format!(
"Couldn't find any rules for name {}.",
name
)));
}
rules.sort_by(|x, y| x.name.cmp(&y.name));
for index in 1..rules.len() - 1 {
if rules[index].name == rules[index - 1].name {
return Err(Error::conflict(format!(
"Duplicate rule definitions for rule {}",
rules[index].name
)));
}
}
// @TODO at this point we need to know about...
// @TODO ... which rules require recursion (and thus need wrapping in a Variable)
// @TODO ... which rules are supposed to be re-used
// @TODO ... which rules are supposed to be re-synthesized
//
// but based entirely on control data written to the server by something external
// (for the old implement it could just be a decision based on whether the rule has a namespace)
// Step 1: Create new recursive variables for each rule.
for name in publish.iter() {
local_arrangements.insert(
name.clone(),
Variable::new(nested, Product::new(Default::default(), 1)),
);
}
// Step 2: Create public arrangements for published relations.
for name in publish.into_iter() {
if let Some(relation) = local_arrangements.get(&name) {
result_map.insert(name, relation.leave());
} else {
return Err(Error::not_found(format!(
"Attempted to publish undefined name {}.",
name
)));
}
}
// Step 3: Define the executions for each rule.
let mut executions = Vec::with_capacity(rules.len());
let mut shutdown_handle = ShutdownHandle::empty();
for rule in rules.iter() {
info!("neu_planning {:?}", rule.name);
let plan = q(rule.plan.variables(), rule.plan.into_bindings());
let (relation, shutdown) = plan.implement(nested, domain, &local_arrangements);
executions.push(relation);
shutdown_handle.merge_with(shutdown);
}
// Step 4: Complete named relations in a specific order (sorted by name).
for (rule, execution) in rules.iter().zip(executions.drain(..)) {
match local_arrangements.remove(&rule.name) {
None => {
return Err(Error::not_found(format!(
"Rule {:?} should be in local arrangements, but isn't.",
&rule.name
)));
}
Some(variable) => {
let (tuples, shutdown) = execution.tuples(nested, domain);
shutdown_handle.merge_with(shutdown);
#[cfg(feature = "set-semantics")]
variable.set(&tuples.distinct());
#[cfg(not(feature = "set-semantics"))]
variable.set(&tuples.consolidate());
}
}
}
Ok((result_map, shutdown_handle))
})
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Channel group tasks"]
pub tasks_chg: [TASKS_CHG; 6],
_reserved1: [u8; 1232usize],
#[doc = "0x500 - Channel enable register"]
pub chen: CHEN,
#[doc = "0x504 - Channel enable set register"]
pub chenset: CHENSET,
#[doc = "0x508 - Channel enable clear register"]
pub chenclr: CHENCLR,
_reserved4: [u8; 4usize],
#[doc = "0x510 - PPI Channel"]
pub ch: [CH; 20],
_reserved5: [u8; 592usize],
#[doc = "0x800 - Description collection[n]: Channel group n"]
pub chg: [CHG; 6],
_reserved6: [u8; 248usize],
#[doc = "0x910 - Fork"]
pub fork: [FORK; 32],
}
#[doc = r" Register block"]
#[repr(C)]
pub struct TASKS_CHG {
#[doc = "0x00 - Description cluster[n]: Enable channel group n"]
pub en: self::tasks_chg::EN,
#[doc = "0x04 - Description cluster[n]: Disable channel group n"]
pub dis: self::tasks_chg::DIS,
}
#[doc = r" Register block"]
#[doc = "Channel group tasks"]
pub mod tasks_chg;
#[doc = r" Register block"]
#[repr(C)]
pub struct CH {
#[doc = "0x00 - Description cluster[n]: Channel n event end-point"]
pub eep: self::ch::EEP,
#[doc = "0x04 - Description cluster[n]: Channel n task end-point"]
pub tep: self::ch::TEP,
}
#[doc = r" Register block"]
#[doc = "PPI Channel"]
pub mod ch;
#[doc = r" Register block"]
#[repr(C)]
pub struct FORK {
#[doc = "0x00 - Description cluster[n]: Channel n task end-point"]
pub tep: self::fork::TEP,
}
#[doc = r" Register block"]
#[doc = "Fork"]
pub mod fork;
#[doc = "Channel enable register"]
pub struct CHEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Channel enable register"]
pub mod chen;
#[doc = "Channel enable set register"]
pub struct CHENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Channel enable set register"]
pub mod chenset;
#[doc = "Channel enable clear register"]
pub struct CHENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Channel enable clear register"]
pub mod chenclr;
#[doc = "Description collection[n]: Channel group n"]
pub struct CHG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Description collection[n]: Channel group n"]
pub mod chg;
|
use crate::crypto;
use crate::database;
pub fn register_temporary_user_data(password: &str, email: &str) {
let (hashed, salt, cypher) = crypto::create_hash_from_password(&password, &email);
database::insert_temporary_user(&email, &hashed, &salt, &cypher);
}
pub fn signin_judge(password: &str, email: &str) {
let (salt, user_password) = database::select_temporary_user_salt(&email);
let hashed_password = crypto::hash_salt_and_password(&salt, &password);
if user_password == hashed_password {
println!("password is correct");
}
}
|
use crate::token::Token;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum ParseError {
UnexpectedToken(Token),
ExpectedColon(Token),
ExpectedTypeDefinition(Token),
ExpectedAssignment(Token),
ExpectedIdentifier(Token),
ExpectedOperand(Token),
ExpectedSemiColon(Token),
ExpectedClosingBracket(Token),
ExpectedLeftBracket(Token),
ExpectedIn(Token),
ExpectedDo(Token),
ExpectedRange(Token),
ExpectedFor(Token),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = |expected, token| format!("Expected {} got {}", expected, token);
let output = match self {
ParseError::UnexpectedToken(t) => format!("Unexpected token: {}", t),
ParseError::ExpectedColon(t) => msg(":", t),
ParseError::ExpectedTypeDefinition(t) => msg("type definition", t),
ParseError::ExpectedLeftBracket(t) => msg("(", t),
ParseError::ExpectedClosingBracket(t) => msg(")", t),
ParseError::ExpectedAssignment(t) => msg(":=", t),
ParseError::ExpectedOperand(t) => msg("operand", t),
ParseError::ExpectedSemiColon(t) => msg(";", t),
ParseError::ExpectedIn(t) => msg("in keyword", t),
ParseError::ExpectedDo(t) => msg("do keyword", t),
ParseError::ExpectedRange(t) => msg("..", t),
ParseError::ExpectedFor(t) => msg("for keyword", t),
ParseError::ExpectedIdentifier(t) => msg("identifier", t),
};
write!(f, "{}", output)
}
}
#[derive(Debug)]
pub enum EvalError {
MismatchedTypes,
UnsupportedOperation,
VariableNotInitialized(String),
VariableAlreadyInitialized(String),
SyntaxError,
IOError(String),
}
impl fmt::Display for EvalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = |err| format!("{}", err);
let output = match self {
EvalError::SyntaxError => msg("Syntax Error"),
EvalError::MismatchedTypes => msg("Mismatched types"),
EvalError::UnsupportedOperation => msg("Unsupported operation"),
EvalError::VariableAlreadyInitialized(id) => {
format!("Variable {} is already initialized", id)
}
EvalError::VariableNotInitialized(id) => format!("Variable {} not initialized", id),
EvalError::IOError(err) => msg(err),
};
write!(f, "Failed with Error: {}", output)
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Type {
Boolean,
String,
Integer,
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Type::Boolean => write!(f, "bool"),
Type::String => write!(f, "string"),
Type::Integer => write!(f, "int"),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Bool(bool),
String(String),
Integer(i32),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::Bool(b) => write!(f, "{}", b),
Value::Integer(int) => write!(f, "{}", int),
Value::String(s) => write!(f, "{}", s),
}
}
}
|
use winapi::shared::windef::HWND;
use winapi::shared::minwindef::{LPARAM, WPARAM};
use winapi::um::winuser::{WS_VISIBLE, WS_DISABLED, WS_TABSTOP};
use crate::win32::base_helper::{check_hwnd, to_utf16, from_utf16};
use crate::win32::window_helper as wh;
use crate::{Font, NwgError, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlHandle, ControlBase};
use std::cell::{Ref, RefMut, RefCell};
use std::fmt::Display;
use std::mem;
const NOT_BOUND: &'static str = "Combobox is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Combobox handle is not HWND!";
bitflags! {
/**
The ComboBox flags
* NONE: No flags. Equivalent to a invisible combobox.
* VISIBLE: The combobox is immediatly visible after creation
* DISABLED: The combobox cannot be interacted with by the user. It also has a grayed out look.
* TAB_STOP: The control can be selected using tab navigation
*/
pub struct ComboBoxFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
const TAB_STOP = WS_TABSTOP;
}
}
/**
A combo box consists of a list and a selection field. The list presents the options that a user can select,
and the selection field displays the current selection.
Requires the `combobox` feature.
**Builder parameters:**
* `parent`: **Required.** The combobox parent container.
* `size`: The combobox size.
* `position`: The combobox position.
* `enabled`: If the combobox can be used by the user. It also has a grayed out look if disabled.
* `flags`: A combination of the ComboBoxFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the combobox text
* `collection`: The default collection of the combobox
* `selected_index`: The default selected index. None means no values are selected.
* `focus`: The control receive focus after being created
**Control events:**
* `OnComboBoxClosed`: When the combobox dropdown is closed
* `OnComboBoxDropdown`: When the combobox dropdown is opened
* `OnComboxBoxSelection`: When a new value in a combobox is choosen
* `MousePress(_)`: Generic mouse press events on the checkbox
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
```rust
use native_windows_gui as nwg;
fn build_combobox(combo: &mut nwg::ComboBox<&'static str>, window: &nwg::Window) {
let data = vec!["one", "two"];
nwg::ComboBox::builder()
.size((200, 300))
.collection(data)
.selected_index(Some(0))
.parent(window)
.build(combo);
}
```
*/
#[derive(Default)]
pub struct ComboBox<D: Display+Default> {
pub handle: ControlHandle,
collection: RefCell<Vec<D>>,
handler0: RefCell<Option<RawEventHandler>>,
}
impl<D: Display+Default> ComboBox<D> {
pub fn builder<'a>() -> ComboBoxBuilder<'a, D> {
ComboBoxBuilder {
size: (100, 25),
position: (0, 0),
enabled: true,
focus: false,
flags: None,
ex_flags: 0,
font: None,
collection: None,
selected_index: None,
parent: None
}
}
/// Remove the item at the selected index and returns it.
/// Panic of the index is out of bounds
pub fn remove(&self, index: usize) -> D {
use winapi::um::winuser::CB_DELETESTRING;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, CB_DELETESTRING, index as WPARAM, 0);
let mut col_ref = self.collection.borrow_mut();
col_ref.remove(index)
}
/// Sort the inner collection by the display value of it's items and update the view
/// Internally this uses `Vec.sort_unstable_by`.
pub fn sort(&self) {
use winapi::um::winuser::{CB_ADDSTRING};
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
self.clear_inner(handle);
let mut col = self.collection.borrow_mut();
col.sort_unstable_by(|a, b| {
let astr = format!("{}", a);
let bstr = format!("{}", b);
astr.cmp(&bstr)
});
for item in col.iter() {
let display = format!("{}", item);
let display_os = to_utf16(&display);
wh::send_message(handle, CB_ADDSTRING, 0, display_os.as_ptr() as LPARAM);
}
}
/// Show or hide the dropdown of the combox
pub fn dropdown(&self, v: bool) {
use winapi::um::winuser::CB_SHOWDROPDOWN;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, CB_SHOWDROPDOWN, v as usize, 0);
}
/// Return the index of the currencty selected item. Return `None` if no item is selected.
pub fn selection(&self) -> Option<usize> {
use winapi::um::winuser::{CB_GETCURSEL, CB_ERR};
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let index = wh::send_message(handle, CB_GETCURSEL, 0, 0);
if index == CB_ERR { None }
else { Some(index as usize) }
}
/// Return the display value of the currenctly selected item
/// Return `None` if no item is selected. This reads the visual value.
pub fn selection_string(&self) -> Option<String> {
use winapi::um::winuser::{CB_GETCURSEL, CB_GETLBTEXTLEN, CB_GETLBTEXT, CB_ERR};
use winapi::shared::ntdef::WCHAR;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let index = wh::send_message(handle, CB_GETCURSEL, 0, 0);
if index == CB_ERR { None }
else {
let index = index as usize;
let length = (wh::send_message(handle, CB_GETLBTEXTLEN, index, 0) as usize) + 1; // +1 for the null character
let mut buffer: Vec<WCHAR> = Vec::with_capacity(length);
unsafe {
buffer.set_len(length);
wh::send_message(handle, CB_GETLBTEXT, index, buffer.as_ptr() as LPARAM);
}
Some(from_utf16(&buffer))
}
}
/// Set the currently selected item in the combobox.
/// Does nothing if the index is out of bound
/// If the value is None, remove the selected value
pub fn set_selection(&self, index: Option<usize>) {
use winapi::um::winuser::CB_SETCURSEL;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let index = index.unwrap_or(-1isize as usize);
wh::send_message(handle, CB_SETCURSEL, index, 0);
}
/// Search an item that begins by the value and select the first one found.
/// The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.
/// Return the index of the selected string or None if the search was not successful
pub fn set_selection_string(&self, value: &str) -> Option<usize> {
use winapi::um::winuser::{CB_SELECTSTRING, CB_ERR};
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let os_string = to_utf16(value);
let index = wh::send_message(handle, CB_SELECTSTRING, 0, os_string.as_ptr() as LPARAM);
if index == CB_ERR {
None
} else {
Some(index as usize)
}
}
/// Add a new item to the combobox. Sort the collection if the combobox is sorted.
pub fn push(&self, item: D) {
use winapi::um::winuser::CB_ADDSTRING;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let display = format!("{}", item);
let display_os = to_utf16(&display);
wh::send_message(handle, CB_ADDSTRING, 0, display_os.as_ptr() as LPARAM);
self.collection.borrow_mut().push(item);
}
/// Insert an item in the collection and the control.
///
/// SPECIAL behaviour! If index is `std::usize::MAX`, the item is added at the end of the collection.
/// The method will still panic if `index > len` with every other values.
pub fn insert(&self, index: usize, item: D) {
use winapi::um::winuser::CB_INSERTSTRING;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let display = format!("{}", item);
let display_os = to_utf16(&display);
let mut col = self.collection.borrow_mut();
if index == std::usize::MAX {
col.push(item);
} else {
col.insert(index, item);
}
wh::send_message(handle, CB_INSERTSTRING, index, display_os.as_ptr() as LPARAM);
}
/// Update the visual of the control with the inner collection.
/// This rebuild every item in the combobox and can take some time on big collections.
pub fn sync(&self) {
use winapi::um::winuser::CB_ADDSTRING;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
self.clear_inner(handle);
for item in self.collection.borrow().iter() {
let display = format!("{}", item);
let display_os = to_utf16(&display);
wh::send_message(handle, CB_ADDSTRING, 0, display_os.as_ptr() as LPARAM);
}
}
/// Set the item collection of the combobox. Return the old collection
pub fn set_collection(&self, mut col: Vec<D>) -> Vec<D> {
use winapi::um::winuser::CB_ADDSTRING;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
self.clear_inner(handle);
for item in col.iter() {
let display = format!("{}", item);
let display_os = to_utf16(&display);
wh::send_message(handle, CB_ADDSTRING, 0, display_os.as_ptr() as LPARAM);
}
let mut col_ref = self.collection.borrow_mut();
mem::swap::<Vec<D>>(&mut col_ref, &mut col);
col
}
/// Return the number of items in the control. NOT the inner rust collection
pub fn len(&self) -> usize {
use winapi::um::winuser::CB_GETCOUNT;
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
wh::send_message(handle, CB_GETCOUNT, 0, 0) as usize
}
//
// Common control functions
//
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the button in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the button in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the button in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the button in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Get read-only access to the inner collection of the combobox
/// This call refcell.borrow under the hood. Be sure to drop the value before
/// calling other combobox methods
pub fn collection(&self) -> Ref<Vec<D>> {
self.collection.borrow()
}
/// Get mutable access to the inner collection of the combobox. Does not update the visual
/// control. Call `sync` to update the view. This call refcell.borrow_mut under the hood.
/// Be sure to drop the value before calling other combobox methods
pub fn collection_mut(&self) -> RefMut<Vec<D>> {
self.collection.borrow_mut()
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"COMBOBOX"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
WS_VISIBLE | WS_TABSTOP
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{CBS_DROPDOWNLIST, WS_BORDER, WS_CHILD};
CBS_DROPDOWNLIST | WS_CHILD | WS_BORDER
}
/// Remove all value displayed in the control without touching the rust collection
fn clear_inner(&self, handle: HWND) {
use winapi::um::winuser::CB_RESETCONTENT;
wh::send_message(handle, CB_RESETCONTENT, 0, 0);
}
/// TODO: FIX VERTICAL CENTERING
#[allow(unused)]
fn hook_non_client_size(&self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HGDIOBJ, RECT, HBRUSH, POINT};
use winapi::um::winuser::{WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::ptr;
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let brush = match bg {
Some(c) => unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) },
None => COLOR_WINDOW as HBRUSH
};
unsafe {
let handler0 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
let client_height = r.bottom - 5; // 5 is the combobox padding
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
}
}
impl<D: Display+Default> Drop for ComboBox<D> {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
self.handle.destroy();
}
}
pub struct ComboBoxBuilder<'a, D: Display+Default> {
size: (i32, i32),
position: (i32, i32),
enabled: bool,
focus: bool,
flags: Option<ComboBoxFlags>,
ex_flags: u32,
font: Option<&'a Font>,
collection: Option<Vec<D>>,
selected_index: Option<usize>,
parent: Option<ControlHandle>
}
impl<'a, D: Display+Default> ComboBoxBuilder<'a, D> {
pub fn flags(mut self, flags: ComboBoxFlags) -> ComboBoxBuilder<'a, D> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> ComboBoxBuilder<'a, D> {
self.ex_flags = flags;
self
}
pub fn size(mut self, size: (i32, i32)) -> ComboBoxBuilder<'a, D> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> ComboBoxBuilder<'a, D> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> ComboBoxBuilder<'a, D> {
self.font = font;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> ComboBoxBuilder<'a, D> {
self.parent = Some(p.into());
self
}
pub fn collection(mut self, collection: Vec<D>) -> ComboBoxBuilder<'a, D> {
self.collection = Some(collection);
self
}
pub fn selected_index(mut self, index: Option<usize>) -> ComboBoxBuilder<'a, D> {
self.selected_index = index;
self
}
pub fn enabled(mut self, e: bool) -> ComboBoxBuilder<'a, D> {
self.enabled = e;
self
}
pub fn focus(mut self, focus: bool) -> ComboBoxBuilder<'a, D> {
self.focus = focus;
self
}
pub fn v_align(self, _align: VTextAlign) -> ComboBoxBuilder<'a, D> {
// Disabled for now because of a bug. Keep the method for backward compatibility
self
}
pub fn build(self, out: &mut ComboBox<D>) -> Result<(), NwgError> {
let flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("ComboBox"))
}?;
// Drop the old object
*out = ComboBox::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
if self.collection.is_some() {
out.set_collection(self.collection.unwrap());
}
if self.selected_index.is_some() {
out.set_selection(self.selected_index);
}
out.set_enabled(self.enabled);
if self.focus {
out.set_focus();
}
Ok(())
}
}
impl<D: Display+Default> PartialEq for ComboBox<D> {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
|
mod bufferedstream {
use std::io::{self, Read, Write};
#[derive(Debug)]
pub struct BufferedStream<T: Read + Write> {
stream: io::BufReader<T>,
}
impl<T: Read + Write> BufferedStream<T> {
pub fn new(stream: T) -> Self {
Self {
stream: io::BufReader::new(stream),
}
}
pub fn write(&mut self) -> BufferedStreamWriter<T> {
BufferedStreamWriter(io::BufWriter::new(self))
}
pub fn get_ref(&self) -> &T {
self.stream.get_ref()
}
pub fn get_mut(&mut self) -> &mut T {
self.stream.get_mut()
}
}
impl<T: Read + Write> Read for BufferedStream<T> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.stream.read(buf)
}
}
impl<'a, T: Read + Write + 'a> Write for &'a mut BufferedStream<T> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.stream.get_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.stream.get_mut().flush()
}
}
#[derive(Debug)]
pub struct BufferedStreamWriter<'a, T: Read + Write + 'a>(
io::BufWriter<&'a mut BufferedStream<T>>,
);
impl<'a, T: Read + Write + 'a> Write for BufferedStreamWriter<'a, T> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
impl<'a, T: Read + Write + 'a> Drop for BufferedStreamWriter<'a, T> {
fn drop(&mut self) {
self.0.flush().unwrap();
}
}
}
pub use self::bufferedstream::BufferedStream;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mod to_hex {
use std::fmt;
#[derive(Clone, Debug)]
pub struct Hex<'a>(&'a [u8], bool);
impl<'a> Iterator for Hex<'a> {
type Item = char;
fn next(&mut self) -> Option<char> {
if !self.0.is_empty() {
const CHARS: &[u8] = b"0123456789abcdef";
let byte = self.0[0];
let second = self.1;
if second {
self.0 = self.0.split_first().unwrap().1;
}
self.1 = !self.1;
Some(CHARS[if !second { byte >> 4 } else { byte & 0xf } as usize] as char)
} else {
None
}
}
}
impl<'a> fmt::Display for Hex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for char_ in self.clone() {
write!(f, "{}", char_)?;
}
Ok(())
}
}
pub trait ToHex {
fn to_hex(&self) -> Hex;
}
impl ToHex for [u8] {
fn to_hex(&self) -> Hex {
Hex(&*self, false)
}
}
}
pub use self::to_hex::ToHex;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mod rand_stream {
use rand;
#[derive(Debug)]
pub struct Rand<T> {
res: Option<T>,
count: usize,
}
impl<T> Rand<T> {
pub fn new() -> Self {
Self {
res: None,
count: 0,
}
}
pub fn push<R: rand::Rng>(&mut self, x: T, rng: &mut R) {
self.count += 1;
if rng.gen_range(0, self.count) == 0 {
self.res = Some(x);
}
}
pub fn get(self) -> Option<T> {
self.res
}
}
impl<T> Default for Rand<T> {
fn default() -> Self {
Self::new()
}
}
}
pub use self::rand_stream::Rand;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pub fn parse_binary_size(input: &str) -> Result<u64, ()> {
let mut index = 0;
if index == input.len() {
return Err(());
}
index = input
.chars()
.position(|c| !c.is_ascii_digit())
.unwrap_or(input.len());
let a: u64 = input[..index].parse().unwrap();
if index == input.len() {
return Ok(a);
}
let b: u64 = if input[index..=index].chars().nth(0).ok_or(())? == '.' {
index += 1;
let _zeros = input[index..].chars().position(|c| c != '0').unwrap_or(0);
let index1 = index;
index = index + input[index..]
.chars()
.position(|c| !c.is_ascii_digit())
.unwrap_or(input.len() - index);
if index != index1 {
input[index1..index].parse().unwrap()
} else {
0
}
} else {
0
};
if index == input.len() {
return Ok(a);
}
let c: u64 = match &input[index..] {
"B" => 1,
"KiB" => 1024,
"MiB" => 1024_u64.pow(2),
"GiB" => 1024_u64.pow(3),
"TiB" => 1024_u64.pow(4),
"PiB" => 1024_u64.pow(5),
"EiB" => 1024_u64.pow(6),
_ => return Err(()),
};
if b > 0 {
unimplemented!();
}
Ok(a * c)
}
|
use crate::{CoordinateType, LineString, Point, Rect, Triangle};
use num_traits::{Float, Signed};
/// A bounded two-dimensional area.
///
/// A `Polygon`’s outer boundary (_exterior ring_) is represented by a
/// [`LineString`]. It may contain zero or more holes (_interior rings_), also
/// represented by `LineString`s.
///
/// The `Polygon` structure guarantees that all exterior and interior rings will
/// be _closed_, such that the first and last `Coordinate` of each ring has
/// the same value.
///
/// # Validity
///
/// Besides the closed `LineString` rings guarantee, the `Polygon` structure
/// does not enforce validity at this time. For example, it is possible to
/// construct a `Polygon` that has:
///
/// - fewer than 3 coordinates per `LineString` ring
/// - interior rings that intersect other interior rings
/// - interior rings that extend beyond the exterior ring
///
/// # `LineString` closing operation
///
/// Some APIs on `Polygon` result in a closing operation on a `LineString`. The
/// operation is as follows:
///
/// If a `LineString`’s first and last `Coordinate` have different values, a
/// new `Coordinate` will be appended to the `LineString` with a value equal to
/// the first `Coordinate`.
///
/// [`LineString`]: line_string/struct.LineString.html
#[derive(Eq, PartialEq, Clone, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Polygon<T>
where
T: CoordinateType,
{
exterior: LineString<T>,
interiors: Vec<LineString<T>>,
}
impl<T> Polygon<T>
where
T: CoordinateType,
{
/// Create a new `Polygon` with the provided exterior `LineString` ring and
/// interior `LineString` rings.
///
/// Upon calling `new`, the exterior and interior `LineString` rings [will
/// be closed].
///
/// [will be closed]: #linestring-closing-operation
///
/// # Examples
///
/// Creating a `Polygon` with no interior rings:
///
/// ```
/// use geo_types::{LineString, Polygon};
///
/// let polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![],
/// );
/// ```
///
/// Creating a `Polygon` with an interior ring:
///
/// ```
/// use geo_types::{LineString, Polygon};
///
/// let polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])],
/// );
/// ```
///
/// If the first and last `Coordinate`s of the exterior or interior
/// `LineString`s no longer match, those `LineString`s [will be closed]:
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let mut polygon = Polygon::new(LineString::from(vec![(0., 0.), (1., 1.), (1., 0.)]), vec![]);
///
/// assert_eq!(
/// polygon.exterior(),
/// &LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.),])
/// );
/// ```
pub fn new(mut exterior: LineString<T>, mut interiors: Vec<LineString<T>>) -> Polygon<T> {
exterior.close();
for interior in &mut interiors {
interior.close();
}
Polygon {
exterior,
interiors,
}
}
/// Consume the `Polygon`, returning the exterior `LineString` ring and
/// a vector of the interior `LineString` rings.
///
/// # Examples
///
/// ```
/// use geo_types::{LineString, Polygon};
///
/// let mut polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])],
/// );
///
/// let (exterior, interiors) = polygon.into_inner();
///
/// assert_eq!(
/// exterior,
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.),])
/// );
///
/// assert_eq!(
/// interiors,
/// vec![LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])]
/// );
/// ```
pub fn into_inner(self) -> (LineString<T>, Vec<LineString<T>>) {
(self.exterior, self.interiors)
}
/// Return a reference to the exterior `LineString` ring.
///
/// # Examples
///
/// ```
/// use geo_types::{LineString, Polygon};
///
/// let exterior = LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]);
///
/// let polygon = Polygon::new(exterior.clone(), vec![]);
///
/// assert_eq!(polygon.exterior(), &exterior);
/// ```
pub fn exterior(&self) -> &LineString<T> {
&self.exterior
}
/// Execute the provided closure `f`, which is provided with a mutable
/// reference to the exterior `LineString` ring.
///
/// After the closure executes, the exterior `LineString` [will be closed].
///
/// # Examples
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let mut polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![],
/// );
///
/// polygon.exterior_mut(|exterior| {
/// exterior.0[1] = Coordinate { x: 1., y: 2. };
/// });
///
/// assert_eq!(
/// polygon.exterior(),
/// &LineString::from(vec![(0., 0.), (1., 2.), (1., 0.), (0., 0.),])
/// );
/// ```
///
/// If the first and last `Coordinate`s of the exterior `LineString` no
/// longer match, the `LineString` [will be closed]:
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let mut polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![],
/// );
///
/// polygon.exterior_mut(|exterior| {
/// exterior.0[0] = Coordinate { x: 0., y: 1. };
/// });
///
/// assert_eq!(
/// polygon.exterior(),
/// &LineString::from(vec![(0., 1.), (1., 1.), (1., 0.), (0., 0.), (0., 1.),])
/// );
/// ```
///
/// [will be closed]: #linestring-closing-operation
pub fn exterior_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut LineString<T>),
{
f(&mut self.exterior);
self.exterior.close();
}
/// Return a slice of the interior `LineString` rings.
///
/// # Examples
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let interiors = vec![LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])];
///
/// let polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// interiors.clone(),
/// );
///
/// assert_eq!(interiors, polygon.interiors());
/// ```
pub fn interiors(&self) -> &[LineString<T>] {
&self.interiors
}
/// Execute the provided closure `f`, which is provided with a mutable
/// reference to the interior `LineString` rings.
///
/// After the closure executes, each of the interior `LineString`s [will be
/// closed].
///
/// # Examples
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let mut polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])],
/// );
///
/// polygon.interiors_mut(|interiors| {
/// interiors[0].0[1] = Coordinate { x: 0.8, y: 0.8 };
/// });
///
/// assert_eq!(
/// polygon.interiors(),
/// &[LineString::from(vec![
/// (0.1, 0.1),
/// (0.8, 0.8),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])]
/// );
/// ```
///
/// If the first and last `Coordinate`s of any interior `LineString` no
/// longer match, those `LineString`s [will be closed]:
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let mut polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])],
/// );
///
/// polygon.interiors_mut(|interiors| {
/// interiors[0].0[0] = Coordinate { x: 0.1, y: 0.2 };
/// });
///
/// assert_eq!(
/// polygon.interiors(),
/// &[LineString::from(vec![
/// (0.1, 0.2),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// (0.1, 0.2),
/// ])]
/// );
/// ```
///
/// [will be closed]: #linestring-closing-operation
pub fn interiors_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut [LineString<T>]),
{
f(&mut self.interiors);
for interior in &mut self.interiors {
interior.close();
}
}
/// Add an interior ring to the `Polygon`.
///
/// The new `LineString` interior ring [will be closed]:
///
/// # Examples
///
/// ```
/// use geo_types::{Coordinate, LineString, Polygon};
///
/// let mut polygon = Polygon::new(
/// LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]),
/// vec![],
/// );
///
/// assert_eq!(polygon.interiors().len(), 0);
///
/// polygon.interiors_push(vec![(0.1, 0.1), (0.9, 0.9), (0.9, 0.1)]);
///
/// assert_eq!(
/// polygon.interiors(),
/// &[LineString::from(vec![
/// (0.1, 0.1),
/// (0.9, 0.9),
/// (0.9, 0.1),
/// (0.1, 0.1),
/// ])]
/// );
/// ```
///
/// [will be closed]: #linestring-closing-operation
pub fn interiors_push(&mut self, new_interior: impl Into<LineString<T>>) {
let mut new_interior = new_interior.into();
new_interior.close();
self.interiors.push(new_interior);
}
/// Wrap-around previous-vertex
fn previous_vertex(&self, current_vertex: usize) -> usize
where
T: Float,
{
(current_vertex + (self.exterior.0.len() - 1) - 1) % (self.exterior.0.len() - 1)
}
}
// used to check the sign of a vec of floats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ListSign {
Empty,
Positive,
Negative,
Mixed,
}
impl<T> Polygon<T>
where
T: Float + Signed,
{
/// Determine whether a Polygon is convex
// For each consecutive pair of edges of the polygon (each triplet of points),
// compute the z-component of the cross product of the vectors defined by the
// edges pointing towards the points in increasing order.
// Take the cross product of these vectors
// The polygon is convex if the z-components of the cross products are either
// all positive or all negative. Otherwise, the polygon is non-convex.
// see: http://stackoverflow.com/a/1881201/416626
pub fn is_convex(&self) -> bool {
let convex = self
.exterior
.0
.iter()
.enumerate()
.map(|(idx, _)| {
let prev_1 = self.previous_vertex(idx);
let prev_2 = self.previous_vertex(prev_1);
Point(self.exterior.0[prev_2])
.cross_prod(Point(self.exterior.0[prev_1]), Point(self.exterior.0[idx]))
})
// accumulate and check cross-product result signs in a single pass
// positive implies ccw convexity, negative implies cw convexity
// anything else implies non-convexity
.fold(ListSign::Empty, |acc, n| match (acc, n.is_positive()) {
(ListSign::Empty, true) | (ListSign::Positive, true) => ListSign::Positive,
(ListSign::Empty, false) | (ListSign::Negative, false) => ListSign::Negative,
_ => ListSign::Mixed,
});
convex != ListSign::Mixed
}
}
impl<T: CoordinateType> From<Rect<T>> for Polygon<T> {
fn from(r: Rect<T>) -> Polygon<T> {
Polygon::new(
vec![
(r.min().x, r.min().y),
(r.max().x, r.min().y),
(r.max().x, r.max().y),
(r.min().x, r.max().y),
(r.min().x, r.min().y),
]
.into(),
Vec::new(),
)
}
}
impl<T: CoordinateType> From<Triangle<T>> for Polygon<T> {
fn from(t: Triangle<T>) -> Polygon<T> {
Polygon::new(vec![t.0, t.1, t.2, t.0].into(), Vec::new())
}
}
|
use std::fmt;
use super::Tile;
use super::Direction;
use super::Point;
/// Defines the 2D square Grid trait for using the maze generator
pub trait Grid
{
/// Gets tile data at a given position on a grid
fn get_tile_data(&self, Point) -> Result<Tile, &'static str>;
/// Gets the width and height respectively of the grid
fn get_dimensions(&self) -> Point;
/// Carves a path starting at the given point and moving in the
/// given direction, if possible
fn carve_path(&mut self, Point, Direction) -> Result<Point, &'static str>;
}
/// Basic grid class used for examples
pub struct BasicGrid
{
tiles: Vec<Vec<Tile>>,
width: usize,
height: usize,
}
impl fmt::Display for BasicGrid
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
let mut string_fmt = String::new();
for row in (self.tiles.iter()).rev()
{
for tile in row
{
string_fmt += &format!("{}", tile);
}
string_fmt += &String::from("\n");
}
write!(f, "{}", string_fmt)
}
}
impl Grid for BasicGrid
{
fn get_tile_data(&self, (x, y): Point) -> Result<Tile, &'static str>
{
let (width, height) = self.get_dimensions();
if (x < width) && (y < height)
{
Result::Ok(self.tiles[y][x])
}
else
{
Result::Err("Invalid tile index")
}
}
fn get_dimensions(&self) -> Point
{
(self.width, self.height)
}
fn carve_path(&mut self, (x, y): Point, dir: Direction) -> Result<Point, &'static str>
{
let (width, height) = self.get_dimensions();
let tiles = &mut self.tiles;
// Determine directon to carve into
let (x_c, y_c): Point = match dir
{
Direction::Up => (x, y + 1),
Direction::Right => (x + 1, y),
// Set direction to same as current in case of underflow
Direction::Down => if y != 0 { (x, y - 1) } else { (x, y) },
Direction::Left => if x != 0 { (x - 1, y) } else { (x, y) },
Direction::Stay => return Result::Err("Told carve to stay"),
};
if x == x_c && y == y_c
{
return Result::Err("Cannot carve in desired dirrection");
}
{
let from_tile = &mut tiles[y][x];
// Set full tile as connected
match *from_tile
{
Tile::Connected {
up: ref mut u,
down: ref mut d,
left: ref mut l,
right: ref mut r,
} =>
{
match dir
{
Direction::Up => *u = true,
Direction::Down => *d = true,
Direction::Left => *l = true,
Direction::Right => *r = true,
_ =>
{}
}
}
_ =>
{}
}
}
// start != end and in bounds
if y_c < height && x_c < width
{
let to_tile = &mut tiles[y_c][x_c];
match *to_tile
{
Tile::Connected {
up: ref mut u,
down: ref mut d,
left: ref mut l,
right: ref mut r,
} =>
{
match dir
{
Direction::Up => *d = true,
Direction::Down => *u = true,
Direction::Left => *r = true,
Direction::Right => *l = true,
_ =>
{}
}
}
_ =>
{}
}
Result::Ok((x_c, y_c))
}
else
{
Result::Err("Cannot carve in desired dirrection")
}
}
}
impl BasicGrid
{
/// Creates an empty maze of the given size
pub fn new(width: usize, height: usize) -> BasicGrid
{
let mut maze_temp = BasicGrid {
tiles: vec![],
width: width,
height: height,
};
for j in 0..height
{
// Create new rows
maze_temp.tiles.push(vec![]);
// Push new tiles to the row
for _ in 0..width
{
maze_temp.tiles[j].push(Tile::new());
}
}
maze_temp
}
}
|
extern crate rand;
extern crate milagro_crypto;
use self::milagro_crypto::randapi::Random;
use self::milagro_crypto::big::wrappers::MODBYTES;
use self::milagro_crypto::ff::FF;
use self::milagro_crypto::hash::wrappers::hash256;
use self::rand::os::OsRng;
use self::rand::Rng;
use services::crypto::anoncreds::constants::{
BIG_SIZE,
BN_MASK,
PRIMES,
NUM_PRIMES,
LARGE_PRIME
};
use services::crypto::anoncreds::types::{ByteOrder};
pub fn generate_random_seed() -> [u8; 32] {
let mut seed: [u8; 32] = [0; 32];
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut seed);
seed
}
pub fn generate_big_random(size: usize) -> FF {
let seed = generate_random_seed();
let mut rng = Random::new(seed);
let b_size: usize = size / 8 + 1; // number of bytes for mod value
let big_size: usize = (b_size + MODBYTES - 1) / MODBYTES; // number of BIGs for mod value
// init mod bytes with 0 and set 1 in proper place
let mut bytes = vec![0; big_size * MODBYTES];
bytes[big_size * MODBYTES - b_size] = (1 as u8).wrapping_shl((size - (b_size - 1) * 8) as u32);
let bv = FF::from_bytes(&bytes[0..], big_size * MODBYTES, BIG_SIZE);
let r = FF::randomnum(&bv, &mut rng);
r
}
pub fn generate_prime(size: usize) -> FF {
let seed = generate_random_seed();
let mut rng = Random::new(seed);
let mut iteration = 0;
let mut is_prime = false;
let mut prime = generate_big_random(size);
let mut prime_bytes = prime.to_bytes();
let length = prime_bytes.len();
let last_byte = prime_bytes[length - 1];
prime_bytes[length - 1] = last_byte | 3;
prime = FF::from_bytes(&prime_bytes, length, BIG_SIZE);
while !is_prime {
prime.inc(4);
iteration += 1;
is_prime = FF::is_prime(&prime, &mut rng);
}
debug!("Iteration: {}\nFound prime: {}", iteration, prime);
prime
}
pub fn generate_prime_2p_plus_1(size: usize) -> FF {
let seed = generate_random_seed();
let mut rng = Random::new(seed);
let (mut is_prime, mut iteration) = (false, 0);
let mut prime = FF::new(BIG_SIZE);
while !is_prime {
iteration += 1;
prime = generate_prime(size);
let mut prime_for_check = FF::mul(&prime, &FF::from_hex("2", BIG_SIZE));
prime_for_check.inc(1);
is_prime = FF::is_prime(&prime_for_check, &mut rng);
debug!("Iteration: {}\nFound prime: {}\nis_prime: {}\n", iteration, prime, is_prime);
}
prime
}
pub fn random_qr(n: &FF){
println!("n :{}", n);
let mut random = random_in_range(&FF::from_hex("0", BIG_SIZE), n);
println!("random :{}", random);
random = FF::sqr(&random);
println!("random sqr :{}", random);
// let mut nn = n.clone();
// nn.set_size(32);
// random.set_size(32);
let random1 = FF::modulus(&random, &n);
println!("random1 :{}", random1);
// let (mut ctx, mut random_qr) = (BigNumContext::new().unwrap(), BigNum::new().unwrap());
// random_qr.sqr(&AnoncredsService::random_in_range(&BigNum::from_u32(0).unwrap(), &n), &mut ctx);
// random_qr
}
pub fn random_in_range(start: &FF, end: &FF) -> FF {
let sub = end - start;
let size = significant_bits(&sub);
let mut random_number = generate_big_random(size);
while (&random_number + start) > *end {
random_number = generate_big_random(size);
}
random_number = &random_number + start;
debug!("start: {}\nend: {}\nsub: {}\nrandom: {}", start, end, sub, random_number);
random_number
}
pub fn encode_attribute(attribute: &str, byte_order: ByteOrder) -> FF {
let array_bytes = attribute.as_bytes();
let mut sha256: hash256 = hash256::new();
for byte in array_bytes[..].iter() {
sha256.process(*byte);
}
let mut hashed_array: Vec<u8> =
sha256.hash().iter()
.map(|v| *v as u8)
.collect();
let index = hashed_array.iter().position(|&value| value == 0);
if let Some(position) = index {
hashed_array.truncate(position);
}
if let ByteOrder::Little = byte_order {
hashed_array.reverse();
}
if hashed_array.len() < 32 {
for i in 0..(32 - hashed_array.len()) {
hashed_array.insert(0, 0);
}
}
FF::from_bytes(&hashed_array, MODBYTES, 32)
}
fn significant_bytes(n: &FF) -> Vec<u8> {
let mut bytes = n.to_bytes();
let length = bytes.len();
let index = bytes.iter().position(|&value| value != 0);
if let Some(index) = index {
bytes.reverse();
bytes.truncate(length - index);
bytes.reverse();
}
bytes
}
fn significant_bits(n: &FF) -> usize {
let bytes = significant_bytes(n);
let mut result = (bytes.len() - 1) * 8;
result += format!("{:b}", bytes[0]).len();
result
}
fn generate_probable_prime(size: usize) {
let mut random_number = generate_big_random(size);
let mut mods: Vec<FF> = Vec::new();
for i in 1..NUM_PRIMES {
debug!("{}", i);
let bytes = random_number.to_bytes();
let mut new_random = FF::from_bytes(&bytes, size, BIG_SIZE);
let prime = FF::from_hex(&format!("{:x}", PRIMES[i])[..], BIG_SIZE);
FF::modulus(&mut new_random, &prime);
mods.push(new_random);
}
//TODO loop for mods check
}
pub fn get_hash_as_int(nums: &mut Vec<FF>) -> FF {
let mut sha256: hash256 = hash256::new();
nums.sort();
for num in nums.iter() {
let array_bytes: Vec<u8> = num.to_bytes();
let index = array_bytes.iter().position(|&value| value != 0).unwrap_or(array_bytes.len());
for byte in array_bytes[index..].iter() {
sha256.process(*byte);
}
}
let mut hashed_array: Vec<u8> =
sha256.hash().iter()
.map(|v| *v as u8)
.collect();
hashed_array.reverse();
FF::from_bytes(&hashed_array[..], hashed_array.len(), 2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn random_in_range_works() {
::env_logger::init().unwrap();
let start = generate_big_random(100);
let mut end = generate_big_random(120);
while end < start {
end = generate_big_random(30);
}
let random = random_in_range(&start, &end);
assert!((random > start) && (random < end));
}
#[test]
fn test_random_qr() {
// let n = generate_big_random(10);
// random_qr(&n);
}
#[test]
fn encode_attribute_works() {
let test_str_one = "Alexer5435";
let test_str_two = "Alexer";
let test_answer_one = "f54a";
let test_answer_two = "cf76920dae32802476cc5e8d2518fd21c16b5f83e713a684db1aeb7089c67091";
assert_eq!(FF::from_hex(test_answer_one, BIG_SIZE), encode_attribute(test_str_one, ByteOrder::Big));
assert_eq!(FF::from_hex(test_answer_two, BIG_SIZE), encode_attribute(test_str_two, ByteOrder::Big));
}
#[test]
fn get_hash_as_in_works(){
let mut nums = vec![
FF::from_hex("ff9d2eedfee9cffd9ef6dbffedff3fcbef4caecb9bffe79bfa94d3fdf6abfbff", 32),
FF::from_hex("ff9d2eedfee9cffd9ef6dbffedff3fcbef4caecb9bffe79bfa9168615ccbc546", 32)
];
let res = get_hash_as_int(&mut nums);
assert_eq!("0000000000000000000000000000000000000000000000000000000000000000 9E2A0653691B96A9B55B3D1133F9FEE2F2C37B848DBADF2F70DFFFE9E47C5A5D", res.to_hex());
}
} |
#![crate_name="ndarray"]
#![cfg_attr(has_deprecated, feature(deprecated))]
#![doc(html_root_url = "http://bluss.github.io/rust-ndarray/master/")]
//! The `ndarray` crate provides an N-dimensional container similar to numpy’s
//! ndarray.
//!
//! - [`ArrayBase`](struct.ArrayBase.html):
//! The N-dimensional array type itself.
//! - [`Array`](type.Array.html):
//! An array where the data is shared and copy on write, it
//! can act as both an owner of the data as well as a lightweight view.
//! - [`OwnedArray`](type.OwnedArray.html):
//! An array where the data is owned uniquely.
//! - [`ArrayView`](type.ArrayView.html), [`ArrayViewMut`](type.ArrayViewMut.html):
//! Lightweight array views.
//!
//! ## Highlights
//!
//! - Generic N-dimensional array
//! - Slicing, also with arbitrary step size, and negative indices to mean
//! elements from the end of the axis.
//! - There is both a copy on write array (`Array`), or a regular uniquely owned array
//! (`OwnedArray`), and both can use read-only and read-write array views.
//! - Iteration and most operations are efficient on arrays with contiguous
//! innermost dimension.
//! - Array views can be used to slice and mutate any `[T]` data.
//!
//! ## Crate Status
//!
//! - Still iterating on the API
//! - Performance status:
//! + Arithmetic involving arrays of contiguous inner dimension optimizes very well.
//! + `.fold()` and `.zip_mut_with()` are the most efficient ways to
//! perform single traversal and lock step traversal respectively.
//! + `.iter()` and `.iter_mut()` are efficient for contiguous arrays.
//! - There is experimental bridging to the linear algebra package `rblas`.
//!
//! ## Crate Feature Flags
//!
//! - `assign_ops`
//! - Optional, requires nightly
//! - Enables the compound assignment operators
//! - `rustc-serialize`
//! - Optional, stable
//! - Enables serialization support
//! - `rblas`
//! - Optional, stable
//! - Enables `rblas` integration
//!
#![cfg_attr(feature = "assign_ops", feature(augmented_assignments,
op_assign_traits))]
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(feature = "rustc-serialize")]
extern crate rustc_serialize as serialize;
extern crate itertools as it;
extern crate num as libnum;
use libnum::Float;
use libnum::Complex;
use std::cmp;
use std::mem;
use std::ops::{Add, Sub, Mul, Div, Rem, Neg, Not, Shr, Shl,
BitAnd,
BitOr,
BitXor,
};
use std::rc::Rc;
use std::slice::{self, Iter, IterMut};
use std::marker::PhantomData;
use it::ZipSlices;
pub use dimension::{Dimension, RemoveAxis};
pub use dimension::NdIndex;
pub use indexes::Indexes;
pub use shape_error::ShapeError;
pub use si::{Si, S};
use dimension::stride_offset;
use iterators::Baseiter;
pub use iterators::{
InnerIter,
InnerIterMut,
OuterIter,
OuterIterMut,
};
#[allow(deprecated)]
use linalg::{Field, Ring};
pub mod linalg;
mod arraytraits;
#[cfg(feature = "serde")]
mod arrayserialize;
mod arrayformat;
#[cfg(feature = "rblas")]
pub mod blas;
mod dimension;
mod indexes;
mod iterators;
mod numeric_util;
mod si;
mod shape_error;
// NOTE: In theory, the whole library should compile
// and pass tests even if you change Ix and Ixs.
/// Array index type
pub type Ix = usize;
/// Array index type (signed)
pub type Ixs = isize;
/// An *N*-dimensional array.
///
/// The array is a general container of elements. It cannot grow or shrink, but
/// can be sliced into subsets of its data.
/// The array supports arithmetic operations by applying them elementwise.
///
/// The `ArrayBase<S, D>` is parameterized by:
/// - `S` for the data container
/// - `D` for the number of dimensions
///
/// Type aliases [`Array`], [`OwnedArray`], [`ArrayView`], and [`ArrayViewMut`] refer
/// to `ArrayBase` with different types for the data storage.
///
/// [`Array`]: type.Array.html
/// [`OwnedArray`]: type.OwnedArray.html
/// [`ArrayView`]: type.ArrayView.html
/// [`ArrayViewMut`]: type.ArrayViewMut.html
///
/// ## `Array` and `OwnedArray`
///
/// `OwnedArray` owns the underlying array elements directly (just like
/// a `Vec`), while [`Array`](type.Array.html) is a an array with reference
/// counted data. `Array` can act both as an owner or as a view in that regard.
/// Sharing requires that it uses copy-on-write for mutable operations.
/// Calling a method for mutating elements on `Array`, for example
/// [`view_mut()`](#method.view_mut) or [`get_mut()`](#method.get_mut),
/// will break sharing and require a clone of the data (if it is not uniquely held).
///
/// Note that all `ArrayBase` variants can change their view (slicing) of the
/// data freely, even when their data can’t be mutated.
///
/// ## Indexing and Dimension
///
/// Array indexes are represented by the types `Ix` and `Ixs` (signed).
///
/// The dimensionality of the array determines the number of *axes*, for example
/// a 2D array has two axes. These are listed in “big endian” order, so that
/// the greatest dimension is listed first, the lowest dimension with the most
/// rapidly varying index is the last.
///
/// In a 2D array the index of each element is `(row, column)`
/// as seen in this 3 × 3 example:
///
/// ```ignore
/// [[ (0, 0), (0, 1), (0, 2)], // row 0
/// [ (1, 0), (1, 1), (1, 2)], // row 1
/// [ (2, 0), (2, 1), (2, 2)]] // row 2
/// // \ \ \
/// // column 0 \ column 2
/// // column 1
/// ```
///
/// The number of axes for an array is fixed by the `D` parameter: `Ix` for
/// a 1D array, `(Ix, Ix)` for a 2D array etc. The `D` type is also used
/// for element indices in `.get()` and `array[index]`. The dimension type `Vec<Ix>`
/// allows a dynamic number of axes.
///
/// ## Slicing
///
/// You can use slicing to create a view of a subset of the data in
/// the array. Slicing methods include `.slice()`, `.islice()`,
/// `.slice_mut()`.
///
/// The slicing argument can be passed using the macro [`s![]`](macro.s!.html),
/// which will be used in all examples. (The explicit form is a reference
/// to a fixed size array of [`Si`]; see its docs for more information.)
/// [`Si`]: struct.Si.html
///
/// ```
/// // import the s![] macro
/// #[macro_use(s)]
/// extern crate ndarray;
///
/// use ndarray::arr3;
///
/// fn main() {
///
/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
///
/// let a = arr3(&[[[ 1, 2, 3], // -- 2 rows \_
/// [ 4, 5, 6]], // -- /
/// [[ 7, 8, 9], // \_ 2 submatrices
/// [10, 11, 12]]]); // /
/// // 3 columns ..../.../.../
///
/// assert_eq!(a.shape(), &[2, 2, 3]);
///
/// // Let’s create a slice with
/// //
/// // - Both of the submatrices of the greatest dimension: `..`
/// // - Only the first row in each submatrix: `0..1`
/// // - Every element in each row: `..`
///
/// let b = a.slice(s![.., 0..1, ..]);
/// // without the macro, the explicit argument is `&[S, Si(0, Some(1), 1), S]`
///
/// let c = arr3(&[[[ 1, 2, 3]],
/// [[ 7, 8, 9]]]);
/// assert_eq!(b, c);
/// assert_eq!(b.shape(), &[2, 1, 3]);
///
/// // Let’s create a slice with
/// //
/// // - Both submatrices of the greatest dimension: `..`
/// // - The last row in each submatrix: `-1..`
/// // - Row elements in reverse order: `..;-1`
/// let d = a.slice(s![.., -1.., ..;-1]);
/// let e = arr3(&[[[ 6, 5, 4]],
/// [[12, 11, 10]]]);
/// assert_eq!(d, e);
/// }
/// ```
///
/// ## Subviews
///
/// Subview methods allow you to restrict the array view while removing
/// one axis from the array. Subview methods include `.subview()`,
/// `.isubview()`, `.subview_mut()`.
///
/// Subview takes two arguments: `axis` and `index`.
///
/// ```
/// use ndarray::{arr3, aview2};
///
/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
///
/// let a = arr3(&[[[ 1, 2, 3], // \ axis 0, submatrix 0
/// [ 4, 5, 6]], // /
/// [[ 7, 8, 9], // \ axis 0, submatrix 1
/// [10, 11, 12]]]); // /
/// // \
/// // axis 2, column 0
///
/// assert_eq!(a.shape(), &[2, 2, 3]);
///
/// // Let’s take a subview along the greatest dimension (axis 0),
/// // taking submatrix 0, then submatrix 1
///
/// let sub_0 = a.subview(0, 0);
/// let sub_1 = a.subview(0, 1);
///
/// assert_eq!(sub_0, aview2(&[[ 1, 2, 3],
/// [ 4, 5, 6]]));
/// assert_eq!(sub_1, aview2(&[[ 7, 8, 9],
/// [10, 11, 12]]));
/// assert_eq!(sub_0.shape(), &[2, 3]);
///
/// // This is the subview picking only axis 2, column 0
/// let sub_col = a.subview(2, 0);
///
/// assert_eq!(sub_col, aview2(&[[ 1, 4],
/// [ 7, 10]]));
/// ```
///
/// `.isubview()` modifies the view in the same way as `subview()`, but
/// since it is *in place*, it cannot remove the collapsed axis. It becomes
/// an axis of length 1.
///
/// ## Arithmetic Operations
///
/// Arrays support all arithmetic operations the same way: they apply elementwise.
///
/// Since the trait implementations are hard to overview, here is a summary.
///
/// Let `A` be an array or view of any kind. Let `B` be a mutable
/// array (that is, either `OwnedArray`, `Array`, or `ArrayViewMut`)
/// The following combinations of operands
/// are supported for an arbitrary binary operator denoted by `@`.
///
/// - `&A @ &A` which produces a new `OwnedArray`
/// - `B @ A` which consumes `B`, updates it with the result, and returns it
/// - `B @ &A` which consumes `B`, updates it with the result, and returns it
/// - `B @= &A` which performs an arithmetic operation in place
/// (requires `features = "assign_ops"`)
///
/// The trait [`Scalar`](trait.Scalar.html) marks types that can be used in arithmetic
/// with arrays directly. For a scalar `K` the following combinations of operands
/// are supported (scalar can be on either side).
///
/// - `&A @ K` or `K @ &A` which produces a new `OwnedArray`
/// - `B @ K` or `K @ B` which consumes `B`, updates it with the result and returns it
/// - `B @= K` which performs an arithmetic operation in place
/// (requires `features = "assign_ops"`)
///
/// ## Broadcasting
///
/// Arrays support limited *broadcasting*, where arithmetic operations with
/// array operands of different sizes can be carried out by repeating the
/// elements of the smaller dimension array. See
/// [`.broadcast()`](#method.broadcast) for a more detailed
/// description.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 1.],
/// [1., 2.]]);
/// let b = arr2(&[[0., 1.]]);
///
/// let c = arr2(&[[1., 2.],
/// [1., 3.]]);
/// // We can add because the shapes are compatible even if not equal.
/// assert!(
/// c == a + b
/// );
/// ```
///
pub struct ArrayBase<S, D> where S: Data {
/// Rc data when used as view, Uniquely held data when being mutated
data: S,
/// A pointer into the buffer held by data, may point anywhere
/// in its range.
ptr: *mut S::Elem,
/// The size of each axis
dim: D,
/// The element count stride per axis. To be parsed as `isize`.
strides: D,
}
/// Array’s inner representation.
///
/// ***Note:*** `Data` is not an extension interface at this point.
/// Traits in Rust can serve many different roles. This trait is public because
/// it is used as a bound on public methods.
pub unsafe trait Data {
type Elem;
fn slice(&self) -> &[Self::Elem];
}
/// Array’s writable inner representation.
pub unsafe trait DataMut : Data {
fn slice_mut(&mut self) -> &mut [Self::Elem];
#[inline]
fn ensure_unique<D>(&mut ArrayBase<Self, D>)
where Self: Sized, D: Dimension
{
}
#[inline]
fn is_unique(&mut self) -> bool { true }
}
/// Clone an Array’s storage.
pub unsafe trait DataClone : Data {
/// Unsafe because, `ptr` must point inside the current storage.
unsafe fn clone_with_ptr(&self, ptr: *mut Self::Elem) -> (Self, *mut Self::Elem);
}
unsafe impl<A> Data for Rc<Vec<A>> {
type Elem = A;
fn slice(&self) -> &[A] { self }
}
// NOTE: Copy on write
unsafe impl<A> DataMut for Rc<Vec<A>> where A: Clone {
fn slice_mut(&mut self) -> &mut [A] { &mut Rc::make_mut(self)[..] }
fn ensure_unique<D>(self_: &mut ArrayBase<Self, D>)
where Self: Sized, D: Dimension
{
if Rc::get_mut(&mut self_.data).is_some() {
return
}
if self_.dim.size() <= self_.data.len() / 2 {
unsafe {
*self_ = Array::from_vec_dim(self_.dim.clone(),
self_.iter().map(|x| x.clone()).collect());
}
return;
}
let our_off = (self_.ptr as isize - self_.data.as_ptr() as isize)
/ mem::size_of::<A>() as isize;
let rvec = Rc::make_mut(&mut self_.data);
unsafe {
self_.ptr = rvec.as_mut_ptr().offset(our_off);
}
}
fn is_unique(&mut self) -> bool {
Rc::get_mut(self).is_some()
}
}
unsafe impl<A> DataClone for Rc<Vec<A>> {
unsafe fn clone_with_ptr(&self, ptr: *mut Self::Elem)
-> (Self, *mut Self::Elem)
{
// pointer is preserved
(self.clone(), ptr)
}
}
unsafe impl<A> Data for Vec<A> {
type Elem = A;
fn slice(&self) -> &[A] { self }
}
unsafe impl<A> DataMut for Vec<A> {
fn slice_mut(&mut self) -> &mut [A] { self }
}
unsafe impl<A> DataClone for Vec<A> where A: Clone {
unsafe fn clone_with_ptr(&self, ptr: *mut Self::Elem)
-> (Self, *mut Self::Elem)
{
let mut u = self.clone();
let our_off = (self.as_ptr() as isize - ptr as isize)
/ mem::size_of::<A>() as isize;
let new_ptr = u.as_mut_ptr().offset(our_off);
(u, new_ptr)
}
}
unsafe impl<'a, A> Data for ViewRepr<&'a A> {
type Elem = A;
fn slice(&self) -> &[A] { &[] }
}
unsafe impl<'a, A> DataClone for ViewRepr<&'a A> {
unsafe fn clone_with_ptr(&self, ptr: *mut Self::Elem)
-> (Self, *mut Self::Elem)
{
(*self, ptr)
}
}
unsafe impl<'a, A> Data for ViewRepr<&'a mut A> {
type Elem = A;
fn slice(&self) -> &[A] { &[] }
}
unsafe impl<'a, A> DataMut for ViewRepr<&'a mut A> {
fn slice_mut(&mut self) -> &mut [A] { &mut [] }
}
/// Array representation that is a unique or shared owner of its data.
pub unsafe trait DataOwned : Data {
fn new(elements: Vec<Self::Elem>) -> Self;
fn into_shared(self) -> Rc<Vec<Self::Elem>>;
}
/// Array representation that is a lightweight view.
pub unsafe trait DataShared : Clone + DataClone { }
unsafe impl<A> DataShared for Rc<Vec<A>> { }
unsafe impl<'a, A> DataShared for ViewRepr<&'a A> { }
unsafe impl<A> DataOwned for Vec<A> {
fn new(elements: Vec<A>) -> Self { elements }
fn into_shared(self) -> Rc<Vec<A>> { Rc::new(self) }
}
unsafe impl<A> DataOwned for Rc<Vec<A>> {
fn new(elements: Vec<A>) -> Self { Rc::new(elements) }
fn into_shared(self) -> Rc<Vec<A>> { self }
}
/// Array where the data is reference counted and copy on write, it
/// can act as both an owner as the data as well as a lightweight view.
pub type Array<A, D> = ArrayBase<Rc<Vec<A>>, D>;
/// Array where the data is owned uniquely.
pub type OwnedArray<A, D> = ArrayBase<Vec<A>, D>;
/// A lightweight array view.
///
/// `ArrayView` implements `IntoIterator`.
pub type ArrayView<'a, A, D> = ArrayBase<ViewRepr<&'a A>, D>;
/// A lightweight read-write array view.
///
/// `ArrayViewMut` implements `IntoIterator`.
pub type ArrayViewMut<'a, A, D> = ArrayBase<ViewRepr<&'a mut A>, D>;
/// Array view’s representation.
#[derive(Copy, Clone)]
// This is just a marker type, to carry the lifetime parameter.
pub struct ViewRepr<A> {
life: PhantomData<A>,
}
impl<A> ViewRepr<A> {
#[inline(always)]
fn new() -> Self {
ViewRepr { life: PhantomData, }
}
}
impl<S: DataClone, D: Clone> Clone for ArrayBase<S, D>
{
fn clone(&self) -> ArrayBase<S, D> {
unsafe {
let (data, ptr) = self.data.clone_with_ptr(self.ptr);
ArrayBase {
data: data,
ptr: ptr,
dim: self.dim.clone(),
strides: self.strides.clone(),
}
}
}
}
impl<S: DataClone + Copy, D: Copy> Copy for ArrayBase<S, D> { }
/// Constructor methods for one-dimensional arrays.
impl<S> ArrayBase<S, Ix>
where S: DataOwned,
{
/// Create a one-dimensional array from a vector (no allocation needed).
pub fn from_vec(v: Vec<S::Elem>) -> ArrayBase<S, Ix> {
unsafe {
Self::from_vec_dim(v.len() as Ix, v)
}
}
/// Create a one-dimensional array from an iterable.
pub fn from_iter<I: IntoIterator<Item=S::Elem>>(iterable: I) -> ArrayBase<S, Ix> {
Self::from_vec(iterable.into_iter().collect())
}
/// Create a one-dimensional array from inclusive interval
/// `[start, end]` with `n` elements. `F` must be a floating point type.
pub fn linspace<F>(start: F, end: F, n: usize) -> ArrayBase<S, Ix>
where S: Data<Elem=F>,
F: libnum::Float,
usize: it::misc::ToFloat<F>,
{
Self::from_iter(it::linspace(start, end, n))
}
/// Create a one-dimensional array from interval `[start, end)`
#[cfg_attr(has_deprecated, deprecated(note="use ArrayBase::linspace() instead"))]
pub fn range(start: f32, end: f32) -> ArrayBase<S, Ix>
where S: Data<Elem=f32>,
{
let n = (end - start) as usize;
let span = if n > 0 { (n - 1) as f32 } else { 0. };
Self::linspace(start, start + span, n)
}
}
/// Constructor methods for two-dimensional arrays.
impl<S, A> ArrayBase<S, (Ix, Ix)>
where S: DataOwned<Elem=A>,
{
/// Create an identity matrix of size `n` (square 2D array).
pub fn eye(n: Ix) -> ArrayBase<S, (Ix, Ix)>
where S: DataMut,
A: Clone + libnum::Zero + libnum::One,
{
let mut eye = Self::zeros((n, n));
for a_ii in eye.diag_mut() {
*a_ii = A::one();
}
eye
}
}
/// Constructor methods for arrays.
impl<S, A, D> ArrayBase<S, D>
where S: DataOwned<Elem=A>,
D: Dimension,
{
/// Create an array with copies of `elem`, dimension `dim`.
///
/// ```
/// use ndarray::Array;
/// use ndarray::arr3;
///
/// let a = Array::from_elem((2, 2, 2), 1.);
///
/// assert!(
/// a == arr3(&[[[1., 1.],
/// [1., 1.]],
/// [[1., 1.],
/// [1., 1.]]])
/// );
/// ```
pub fn from_elem(dim: D, elem: A) -> ArrayBase<S, D> where A: Clone
{
let v = vec![elem; dim.size()];
unsafe {
Self::from_vec_dim(dim, v)
}
}
/// Create an array with zeros, dimension `dim`.
pub fn zeros(dim: D) -> ArrayBase<S, D> where A: Clone + libnum::Zero
{
Self::from_elem(dim, libnum::zero())
}
/// Create an array with default values, dimension `dim`.
pub fn default(dim: D) -> ArrayBase<S, D>
where A: Default
{
let v = (0..dim.size()).map(|_| A::default()).collect();
unsafe {
Self::from_vec_dim(dim, v)
}
}
/// Create an array from a vector (with no allocation needed).
///
/// Unsafe because dimension is unchecked, and must be correct.
pub unsafe fn from_vec_dim(dim: D, mut v: Vec<A>) -> ArrayBase<S, D>
{
debug_assert!(dim.size() == v.len());
ArrayBase {
ptr: v.as_mut_ptr(),
data: DataOwned::new(v),
strides: dim.default_strides(),
dim: dim
}
}
}
// ArrayView methods
impl<'a, A> ArrayView<'a, A, Ix> {
#[inline]
fn from_slice(xs: &'a [A]) -> Self {
ArrayView {
data: ViewRepr::new(),
ptr: xs.as_ptr() as *mut A,
dim: xs.len(),
strides: 1,
}
}
}
impl<'a, A, D> ArrayView<'a, A, D>
where D: Dimension,
{
/// Create a new `ArrayView`
///
/// Unsafe because: `ptr` must be valid for the given dimension and strides.
#[inline(always)]
unsafe fn new_(ptr: *const A, dim: D, strides: D) -> Self {
ArrayView {
data: ViewRepr::new(),
ptr: ptr as *mut A,
dim: dim,
strides: strides,
}
}
#[inline]
fn into_base_iter(self) -> Baseiter<'a, A, D> {
unsafe {
Baseiter::new(self.ptr, self.dim.clone(), self.strides.clone())
}
}
#[inline]
fn into_elements_base(self) -> ElementsBase<'a, A, D> {
ElementsBase { inner: self.into_base_iter() }
}
fn into_iter_(self) -> Elements<'a, A, D> {
Elements {
inner:
if let Some(slc) = self.into_slice() {
ElementsRepr::Slice(slc.iter())
} else {
ElementsRepr::Counted(self.into_elements_base())
}
}
}
fn into_slice(&self) -> Option<&'a [A]> {
if self.is_standard_layout() {
unsafe {
Some(slice::from_raw_parts(self.ptr, self.len()))
}
} else {
None
}
}
/// Return an outer iterator for this view.
pub fn into_outer_iter(self) -> OuterIter<'a, A, D::Smaller>
where D: RemoveAxis,
{
iterators::new_outer_iter(self)
}
}
impl<'a, A, D> ArrayViewMut<'a, A, D>
where D: Dimension,
{
/// Create a new `ArrayView`
///
/// Unsafe because: `ptr` must be valid for the given dimension and strides.
#[inline(always)]
unsafe fn new_(ptr: *mut A, dim: D, strides: D) -> Self {
ArrayViewMut {
data: ViewRepr::new(),
ptr: ptr,
dim: dim,
strides: strides,
}
}
#[inline]
fn into_base_iter(self) -> Baseiter<'a, A, D> {
unsafe {
Baseiter::new(self.ptr, self.dim.clone(), self.strides.clone())
}
}
#[inline]
fn into_elements_base(self) -> ElementsBaseMut<'a, A, D> {
ElementsBaseMut { inner: self.into_base_iter() }
}
fn into_iter_(self) -> ElementsMut<'a, A, D> {
ElementsMut {
inner:
if self.is_standard_layout() {
let slc = unsafe {
slice::from_raw_parts_mut(self.ptr, self.len())
};
ElementsRepr::Slice(slc.iter_mut())
} else {
ElementsRepr::Counted(self.into_elements_base())
}
}
}
fn _into_slice_mut(self) -> Option<&'a mut [A]>
{
if self.is_standard_layout() {
unsafe {
Some(slice::from_raw_parts_mut(self.ptr, self.len()))
}
} else {
None
}
}
pub fn into_outer_iter(self) -> OuterIterMut<'a, A, D::Smaller>
where D: RemoveAxis,
{
iterators::new_outer_iter_mut(self)
}
}
impl<A, S, D> ArrayBase<S, D> where S: Data<Elem=A>, D: Dimension
{
/// Return the total number of elements in the Array.
pub fn len(&self) -> usize
{
self.dim.size()
}
/// Return the shape of the array.
pub fn dim(&self) -> D {
self.dim.clone()
}
/// Return the shape of the array as a slice.
pub fn shape(&self) -> &[Ix] {
self.dim.slice()
}
/// Return the strides of the array
pub fn strides(&self) -> &[Ixs] {
let s = self.strides.slice();
// reinterpret unsigned integer as signed
unsafe {
slice::from_raw_parts(s.as_ptr() as *const _, s.len())
}
}
/// Return the number of dimensions (axes) in the array
pub fn ndim(&self) -> usize {
self.dim.ndim()
}
/// Return a read-only view of the array
pub fn view(&self) -> ArrayView<A, D> {
debug_assert!(self.pointer_is_inbounds());
unsafe {
ArrayView::new_(self.ptr, self.dim.clone(), self.strides.clone())
}
}
/// Return a read-write view of the array
pub fn view_mut(&mut self) -> ArrayViewMut<A, D>
where S: DataMut,
{
self.ensure_unique();
unsafe {
ArrayViewMut::new_(self.ptr, self.dim.clone(), self.strides.clone())
}
}
/// Return an uniquely owned copy of the array
pub fn to_owned(&self) -> OwnedArray<A, D>
where A: Clone
{
let data = if let Some(slc) = self.as_slice() {
slc.to_vec()
} else {
self.iter().cloned().collect()
};
unsafe {
ArrayBase::from_vec_dim(self.dim.clone(), data)
}
}
/// Return a shared ownership (copy on write) array.
pub fn to_shared(&self) -> Array<A, D>
where A: Clone
{
// FIXME: Avoid copying if it’s already an Array.
self.to_owned().into_shared()
}
/// Turn the array into a shared ownership (copy on write) array,
/// without any copying.
pub fn into_shared(self) -> Array<A, D>
where S: DataOwned,
{
let data = self.data.into_shared();
ArrayBase {
data: data,
ptr: self.ptr,
dim: self.dim,
strides: self.strides,
}
}
/// Return an iterator of references to the elements of the array.
///
/// Iterator element type is `&A`.
pub fn iter(&self) -> Elements<A, D> {
debug_assert!(self.pointer_is_inbounds());
self.view().into_iter_()
}
/// Return an iterator of references to the elements of the array.
///
/// Iterator element type is `(D, &A)`.
pub fn indexed_iter(&self) -> Indexed<A, D> {
Indexed(self.view().into_elements_base())
}
/// Return an iterator of mutable references to the elements of the array.
///
/// Iterator element type is `&mut A`.
pub fn iter_mut(&mut self) -> ElementsMut<A, D>
where S: DataMut,
{
self.ensure_unique();
self.view_mut().into_iter_()
}
/// Return an iterator of indexes and mutable references to the elements of the array.
///
/// Iterator element type is `(D, &mut A)`.
pub fn indexed_iter_mut(&mut self) -> IndexedMut<A, D>
where S: DataMut,
{
IndexedMut(self.view_mut().into_elements_base())
}
/// Return a sliced array.
///
/// See [*Slicing*](#slicing) for full documentation.
/// See also [`D::SliceArg`].
///
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or stride is zero.<br>
/// (**Panics** if `D` is `Vec` and `indexes` does not match the number of array axes.)
pub fn slice(&self, indexes: &D::SliceArg) -> ArrayView<A, D>
{
let mut arr = self.view();
arr.islice(indexes);
arr
}
/// Slice the array’s view in place.
///
/// See also [`D::SliceArg`].
///
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or stride is zero.<br>
/// (**Panics** if `D` is `Vec` and `indexes` does not match the number of array axes.)
pub fn islice(&mut self, indexes: &D::SliceArg)
{
let offset = Dimension::do_slices(&mut self.dim, &mut self.strides, indexes);
unsafe {
self.ptr = self.ptr.offset(offset);
}
debug_assert!(self.pointer_is_inbounds());
}
/// ***Deprecated: Use `.slice()` instead.***
#[cfg_attr(has_deprecated, deprecated(note="use .slice() instead"))]
pub fn slice_iter(&self, indexes: &D::SliceArg) -> Elements<A, D>
{
self.slice(indexes).into_iter()
}
/// Return a sliced read-write view of the array.
///
/// See also [`D::SliceArg`].
///
/// [`D::SliceArg`]: trait.Dimension.html#associatedtype.SliceArg
///
/// **Panics** if an index is out of bounds or stride is zero.<br>
/// (**Panics** if `D` is `Vec` and `indexes` does not match the number of array axes.)
pub fn slice_mut(&mut self, indexes: &D::SliceArg) -> ArrayViewMut<A, D>
where S: DataMut
{
let mut arr = self.view_mut();
arr.islice(indexes);
arr
}
/// ***Deprecated: use `.slice_mut()`***
#[cfg_attr(has_deprecated, deprecated(note="use .slice_mut() instead"))]
pub fn slice_iter_mut(&mut self, indexes: &D::SliceArg) -> ElementsMut<A, D>
where S: DataMut,
{
self.slice_mut(indexes).into_iter()
}
/// Return a reference to the element at `index`, or return `None`
/// if the index is out of bounds.
///
/// Arrays also support indexing syntax: `array[index]`.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 2.],
/// [3., 4.]]);
///
/// assert!(
/// a.get((0, 1)) == Some(&2.) &&
/// a.get((0, 2)) == None &&
/// a[(0, 1)] == 2. &&
/// a[[0, 1]] == 2.
/// );
/// ```
pub fn get<I>(&self, index: I) -> Option<&A>
where I: NdIndex<Dim=D>,
{
let ptr = self.ptr;
index.index_checked(&self.dim, &self.strides)
.map(move |offset| unsafe {
&*ptr.offset(offset)
})
}
/// ***Deprecated: use .get(i)***
#[cfg_attr(has_deprecated, deprecated(note="use .get() instead"))]
pub fn at(&self, index: D) -> Option<&A> {
self.get(index)
}
/// Return a mutable reference to the element at `index`, or return `None`
/// if the index is out of bounds.
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut A>
where S: DataMut,
I: NdIndex<Dim=D>,
{
self.ensure_unique();
let ptr = self.ptr;
index.index_checked(&self.dim, &self.strides)
.map(move |offset| unsafe {
&mut *ptr.offset(offset)
})
}
/// ***Deprecated: use .get_mut(i)***
#[cfg_attr(has_deprecated, deprecated(note="use .get_mut() instead"))]
pub fn at_mut(&mut self, index: D) -> Option<&mut A>
where S: DataMut,
{
self.get_mut(index)
}
/// Perform *unchecked* array indexing.
///
/// Return a reference to the element at `index`.
///
/// **Note:** only unchecked for non-debug builds of ndarray.
#[inline]
pub unsafe fn uget(&self, index: D) -> &A {
debug_assert!(self.dim.stride_offset_checked(&self.strides, &index).is_some());
let off = Dimension::stride_offset(&index, &self.strides);
&*self.ptr.offset(off)
}
/// ***Deprecated: use `.uget()`***
#[cfg_attr(has_deprecated, deprecated(note="use .uget() instead"))]
#[inline]
pub unsafe fn uchk_at(&self, index: D) -> &A {
self.uget(index)
}
/// Perform *unchecked* array indexing.
///
/// Return a mutable reference to the element at `index`.
///
/// **Note:** Only unchecked for non-debug builds of ndarray.<br>
/// **Note:** The array must be uniquely held when mutating it.
#[inline]
pub unsafe fn uget_mut(&mut self, index: D) -> &mut A
where S: DataMut
{
debug_assert!(self.data.is_unique());
debug_assert!(self.dim.stride_offset_checked(&self.strides, &index).is_some());
let off = Dimension::stride_offset(&index, &self.strides);
&mut *self.ptr.offset(off)
}
/// ***Deprecated: use `.uget_mut()`***
#[cfg_attr(has_deprecated, deprecated(note="use .uget_mut() instead"))]
#[inline]
pub unsafe fn uchk_at_mut(&mut self, index: D) -> &mut A
where S: DataMut
{
self.uget_mut(index)
}
/// Swap axes `ax` and `bx`.
///
/// This does not move any data, it just adjusts the array’s dimensions
/// and strides.
///
/// **Panics** if the axes are out of bounds.
///
/// ```
/// use ndarray::arr2;
///
/// let mut a = arr2(&[[1., 2., 3.]]);
/// a.swap_axes(0, 1);
/// assert!(
/// a == arr2(&[[1.], [2.], [3.]])
/// );
/// ```
pub fn swap_axes(&mut self, ax: usize, bx: usize)
{
self.dim.slice_mut().swap(ax, bx);
self.strides.slice_mut().swap(ax, bx);
}
/// Along `axis`, select the subview `index` and return a
/// view with that axis removed.
///
/// See [*Subviews*](#subviews) for full documentation.
///
/// **Panics** if `axis` or `index` is out of bounds.
///
/// ```
/// use ndarray::{arr1, arr2};
///
/// let a = arr2(&[[1., 2.], // -- axis 0, row 0
/// [3., 4.], // -- axis 0, row 1
/// [5., 6.]]); // -- axis 0, row 2
/// // \ \
/// // \ axis 1, column 1
/// // axis 1, column 0
/// assert!(
/// a.subview(0, 1) == arr1(&[3., 4.]) &&
/// a.subview(1, 1) == arr1(&[2., 4., 6.])
/// );
/// ```
pub fn subview(&self, axis: usize, index: Ix) -> ArrayView<A, <D as RemoveAxis>::Smaller>
where D: RemoveAxis,
{
self.view().into_subview(axis, index)
}
/// Collapse dimension `axis` into length one,
/// and select the subview of `index` along that axis.
///
/// **Panics** if `index` is past the length of the axis.
pub fn isubview(&mut self, axis: usize, index: Ix)
{
dimension::do_sub(&mut self.dim, &mut self.ptr, &self.strides, axis, index)
}
/// Along `axis`, select the subview `index` and return `self`
/// with that axis removed.
///
/// See [`.subview()`](#method.subview) and [*Subviews*](#subviews) for full documentation.
pub fn into_subview(mut self, axis: usize, index: Ix) -> ArrayBase<S, <D as RemoveAxis>::Smaller>
where D: RemoveAxis,
{
self.isubview(axis, index);
// don't use reshape -- we always know it will fit the size,
// and we can use remove_axis on the strides as well
ArrayBase {
data: self.data,
ptr: self.ptr,
dim: self.dim.remove_axis(axis),
strides: self.strides.remove_axis(axis),
}
}
/// Along `axis`, select the subview `index` and return a read-write view
/// with the axis removed.
///
/// **Panics** if `axis` or `index` is out of bounds.
///
/// ```
/// use ndarray::{arr2, aview2};
///
/// let mut a = arr2(&[[1., 2.],
/// [3., 4.]]);
///
/// a.subview_mut(1, 1).iadd_scalar(&10.);
///
/// assert!(
/// a == aview2(&[[1., 12.],
/// [3., 14.]])
/// );
/// ```
pub fn subview_mut(&mut self, axis: usize, index: Ix)
-> ArrayViewMut<A, D::Smaller>
where S: DataMut,
D: RemoveAxis,
{
self.view_mut().into_subview(axis, index)
}
/// ***Deprecated: use `.subview_mut()`***
#[cfg_attr(has_deprecated, deprecated(note="use .subview_mut() instead"))]
pub fn sub_iter_mut(&mut self, axis: usize, index: Ix)
-> ElementsMut<A, D>
where S: DataMut,
{
let mut it = self.view_mut();
dimension::do_sub(&mut it.dim, &mut it.ptr, &it.strides, axis, index);
it.into_iter_()
}
/// Return an iterator that traverses over all dimensions but the innermost,
/// and yields each inner row.
///
/// For example, in a 2 × 2 × 3 array, the iterator element
/// is a row of 3 elements (and there are 2 × 2 = 4 rows in total).
///
/// Iterator element is `ArrayView<A, Ix>` (1D array view).
///
/// ```
/// use ndarray::arr3;
/// let a = arr3(&[[[ 0, 1, 2], // -- row 0, 0
/// [ 3, 4, 5]], // -- row 0, 1
/// [[ 6, 7, 8], // -- row 1, 0
/// [ 9, 10, 11]]]); // -- row 1, 1
/// // `inner_iter` yields the four inner rows of the 3D array.
/// let mut row_sums = a.inner_iter().map(|v| v.scalar_sum());
/// assert_eq!(row_sums.collect::<Vec<_>>(), vec![3, 12, 21, 30]);
/// ```
pub fn inner_iter(&self) -> InnerIter<A, D> {
iterators::new_inner_iter(self.view())
}
/// Return an iterator that traverses over all dimensions but the innermost,
/// and yields each inner row.
///
/// Iterator element is `ArrayViewMut<A, Ix>` (1D read-write array view).
pub fn inner_iter_mut(&mut self) -> InnerIterMut<A, D>
where S: DataMut
{
iterators::new_inner_iter_mut(self.view_mut())
}
/// Return an iterator that traverses over the outermost dimension
/// and yields each subview.
///
/// For example, in a 2 × 2 × 3 array, the iterator element
/// is a 2 × 3 subview (and there are 2 in total).
///
/// Iterator element is `ArrayView<A, D::Smaller>` (read-only array view).
///
/// ```
/// use ndarray::arr3;
/// let a = arr3(&[[[ 0, 1, 2], // \ axis 0, submatrix 0
/// [ 3, 4, 5]], // /
/// [[ 6, 7, 8], // \ axis 0, submatrix 1
/// [ 9, 10, 11]]]); // /
/// // `outer_iter` yields the two submatrices along axis 0.
/// let mut iter = a.outer_iter();
/// assert_eq!(iter.next().unwrap(), a.subview(0, 0));
/// assert_eq!(iter.next().unwrap(), a.subview(0, 1));
/// ```
pub fn outer_iter(&self) -> OuterIter<A, D::Smaller>
where D: RemoveAxis,
{
iterators::new_outer_iter(self.view())
}
/// Return an iterator that traverses over the outermost dimension
/// and yields each subview.
///
/// Iterator element is `ArrayViewMut<A, D::Smaller>` (read-write array view).
pub fn outer_iter_mut(&mut self) -> OuterIterMut<A, D::Smaller>
where S: DataMut,
D: RemoveAxis,
{
iterators::new_outer_iter_mut(self.view_mut())
}
// Return (length, stride) for diagonal
fn diag_params(&self) -> (Ix, Ixs)
{
/* empty shape has len 1 */
let len = self.dim.slice().iter().map(|x| *x).min().unwrap_or(1);
let stride = self.strides.slice().iter()
.map(|x| *x as Ixs)
.fold(0, |sum, s| sum + s);
return (len, stride)
}
/// Return an view of the diagonal elements of the array.
///
/// The diagonal is simply the sequence indexed by *(0, 0, .., 0)*,
/// *(1, 1, ..., 1)* etc as long as all axes have elements.
pub fn diag(&self) -> ArrayView<A, Ix>
{
self.view().into_diag()
}
/// Return a read-write view over the diagonal elements of the array.
pub fn diag_mut(&mut self) -> ArrayViewMut<A, Ix>
where S: DataMut,
{
self.view_mut().into_diag()
}
/// Return the diagonal as a one-dimensional array.
pub fn into_diag(self) -> ArrayBase<S, Ix>
{
let (len, stride) = self.diag_params();
ArrayBase {
data: self.data,
ptr: self.ptr,
dim: len,
strides: stride as Ix,
}
}
/// ***Deprecated: use `.diag()`***
#[cfg_attr(has_deprecated, deprecated(note="use .diag() instead"))]
pub fn diag_iter(&self) -> Elements<A, Ix> {
self.diag().into_iter()
}
/// ***Deprecated: use `.diag_mut()`***
#[cfg_attr(has_deprecated, deprecated(note="use .diag_mut() instead"))]
pub fn diag_iter_mut(&mut self) -> ElementsMut<A, Ix>
where S: DataMut,
{
self.diag_mut().into_iter_()
}
/// Make the array unshared.
///
/// This method is mostly only useful with unsafe code.
fn ensure_unique(&mut self)
where S: DataMut
{
debug_assert!(self.pointer_is_inbounds());
S::ensure_unique(self);
debug_assert!(self.pointer_is_inbounds());
}
#[cfg(feature = "rblas")]
/// If the array is not in the standard layout, copy all elements
/// into the standard layout so that the array is C-contiguous.
fn ensure_standard_layout(&mut self)
where S: DataOwned,
A: Clone
{
if !self.is_standard_layout() {
let mut v: Vec<A> = self.iter().cloned().collect();
self.ptr = v.as_mut_ptr();
self.data = DataOwned::new(v);
self.strides = self.dim.default_strides();
}
}
/*
/// Set the array to the standard layout, without adjusting elements.
/// Useful for overwriting.
fn force_standard_layout(&mut self) {
self.strides = self.dim.default_strides();
}
*/
/// Return `true` if the array data is laid out in contiguous “C order” in
/// memory (where the last index is the most rapidly varying).
///
/// Return `false` otherwise, i.e the array is possibly not
/// contiguous in memory, it has custom strides, etc.
pub fn is_standard_layout(&self) -> bool
{
let defaults = self.dim.default_strides();
if self.strides == defaults {
return true;
}
// check all dimensions -- a dimension of length 1 can have unequal strides
for (&dim, (&s, &ds)) in zipsl(self.dim.slice(),
zipsl(self.strides(), defaults.slice()))
{
if dim != 1 && s != (ds as Ixs) {
return false;
}
}
true
}
/// Return the array’s data as a slice, if it is contiguous and
/// the element order corresponds to the memory order. Return `None` otherwise.
pub fn as_slice(&self) -> Option<&[A]> {
if self.is_standard_layout() {
unsafe {
Some(slice::from_raw_parts(self.ptr, self.len()))
}
} else {
None
}
}
/// Return the array’s data as a slice, if it is contiguous and
/// the element order corresponds to the memory order. Return `None` otherwise.
pub fn as_slice_mut(&mut self) -> Option<&mut [A]>
where S: DataMut
{
if self.is_standard_layout() {
self.ensure_unique();
unsafe {
Some(slice::from_raw_parts_mut(self.ptr, self.len()))
}
} else {
None
}
}
/// Transform the array into `shape`; any shape with the same number of
/// elements is accepted.
///
/// May clone all elements if needed to arrange elements in standard
/// layout (and break sharing).
///
/// **Panics** if shapes are incompatible.
///
/// ```
/// use ndarray::{arr1, arr2};
///
/// assert!(
/// arr1(&[1., 2., 3., 4.]).reshape((2, 2))
/// == arr2(&[[1., 2.],
/// [3., 4.]])
/// );
/// ```
pub fn reshape<E>(&self, shape: E) -> ArrayBase<S, E>
where S: DataShared + DataOwned,
A: Clone,
E: Dimension,
{
if shape.size() != self.dim.size() {
panic!("Incompatible shapes in reshape, attempted from: {:?}, to: {:?}",
self.dim.slice(), shape.slice())
}
// Check if contiguous, if not => copy all, else just adapt strides
if self.is_standard_layout() {
let cl = self.clone();
ArrayBase {
data: cl.data,
ptr: cl.ptr,
strides: shape.default_strides(),
dim: shape,
}
} else {
let v = self.iter().map(|x| x.clone()).collect::<Vec<A>>();
unsafe {
ArrayBase::from_vec_dim(shape, v)
}
}
}
/// Transform the array into `shape`; any shape with the same number of
/// elements is accepted, but the source array or view must be
/// contiguous, otherwise we cannot rearrange the dimension.
///
/// **Errors** if the shapes don't have the same number of elements.<br>
/// **Errors** if the input array is not c-contiguous (this will be
/// slightly improved in the future).
///
/// ```
/// use ndarray::{aview1, aview2};
///
/// assert!(
/// aview1(&[1., 2., 3., 4.]).into_shape((2, 2)).unwrap()
/// == aview2(&[[1., 2.],
/// [3., 4.]])
/// );
/// ```
pub fn into_shape<E>(self, shape: E) -> Result<ArrayBase<S, E>, ShapeError>
where E: Dimension
{
if shape.size() != self.dim.size() {
return Err(Self::incompatible_shapes(&self.dim, &shape));
}
// Check if contiguous, if not => copy all, else just adapt strides
if self.is_standard_layout() {
Ok(ArrayBase {
data: self.data,
ptr: self.ptr,
strides: shape.default_strides(),
dim: shape,
})
} else {
Err(ShapeError::IncompatibleLayout)
}
}
#[inline(never)]
#[cold]
fn incompatible_shapes<E>(a: &D, b: &E) -> ShapeError
where E: Dimension,
{
ShapeError::IncompatibleShapes(
a.slice().to_vec().into_boxed_slice(),
b.slice().to_vec().into_boxed_slice())
}
/// Act like a larger size and/or shape array by *broadcasting*
/// into a larger shape, if possible.
///
/// Return `None` if shapes can not be broadcast together.
///
/// ***Background***
///
/// * Two axes are compatible if they are equal, or one of them is 1.
/// * In this instance, only the axes of the smaller side (self) can be 1.
///
/// Compare axes beginning with the *last* axis of each shape.
///
/// For example (1, 2, 4) can be broadcast into (7, 6, 2, 4)
/// because its axes are either equal or 1 (or missing);
/// while (2, 2) can *not* be broadcast into (2, 4).
///
/// The implementation creates a view with strides set to zero for the
/// axes that are to be repeated.
///
/// The broadcasting documentation for Numpy has more information.
///
/// ```
/// use ndarray::{aview1, aview2};
///
/// assert!(
/// aview1(&[1., 0.]).broadcast((10, 2)).unwrap()
/// == aview2(&[[1., 0.]; 10])
/// );
/// ```
pub fn broadcast<E>(&self, dim: E)
-> Option<ArrayView<A, E>>
where E: Dimension
{
/// Return new stride when trying to grow `from` into shape `to`
///
/// Broadcasting works by returning a "fake stride" where elements
/// to repeat are in axes with 0 stride, so that several indexes point
/// to the same element.
///
/// **Note:** Cannot be used for mutable iterators, since repeating
/// elements would create aliasing pointers.
fn upcast<D: Dimension, E: Dimension>(to: &D, from: &E, stride: &E) -> Option<D> {
let mut new_stride = to.clone();
// begin at the back (the least significant dimension)
// size of the axis has to either agree or `from` has to be 1
if to.ndim() < from.ndim() {
return None
}
{
let mut new_stride_iter = new_stride.slice_mut().iter_mut().rev();
for ((er, es), dr) in from.slice().iter().rev()
.zip(stride.slice().iter().rev())
.zip(new_stride_iter.by_ref())
{
/* update strides */
if *dr == *er {
/* keep stride */
*dr = *es;
} else if *er == 1 {
/* dead dimension, zero stride */
*dr = 0
} else {
return None;
}
}
/* set remaining strides to zero */
for dr in new_stride_iter {
*dr = 0;
}
}
Some(new_stride)
}
// Note: zero strides are safe precisely because we return an read-only view
let broadcast_strides =
match upcast(&dim, &self.dim, &self.strides) {
Some(st) => st,
None => return None,
};
unsafe {
Some(ArrayView::new_(self.ptr, dim, broadcast_strides))
}
}
#[cfg_attr(has_deprecated, deprecated(note="use .broadcast() instead"))]
/// ***Deprecated: Use `.broadcast()` instead.***
pub fn broadcast_iter<E>(&self, dim: E) -> Option<Elements<A, E>>
where E: Dimension,
{
self.broadcast(dim).map(|v| v.into_iter_())
}
#[inline]
fn broadcast_unwrap<E>(&self, dim: E) -> ArrayView<A, E>
where E: Dimension,
{
match self.broadcast(dim.clone()) {
Some(it) => it,
None => Self::broadcast_panic(&self.dim, &dim),
}
}
#[inline(never)]
fn broadcast_panic<E: Dimension>(from: &D, to: &E) -> ! {
panic!("Could not broadcast array from shape: {:?} to: {:?}",
from.slice(), to.slice())
}
/// Return a slice of the array’s backing data in memory order.
///
/// **Note:** Data memory order may not correspond to the index order
/// of the array. Neither is the raw data slice is restricted to just the
/// Array’s view.<br>
/// **Note:** the slice may be empty.
pub fn raw_data(&self) -> &[A] {
self.data.slice()
}
/// Return a mutable slice of the array’s backing data in memory order.
///
/// **Note:** Data memory order may not correspond to the index order
/// of the array. Neither is the raw data slice is restricted to just the
/// Array’s view.<br>
/// **Note:** the slice may be empty.
///
/// **Note:** The data is uniquely held and nonaliased
/// while it is mutably borrowed.
pub fn raw_data_mut(&mut self) -> &mut [A]
where S: DataMut,
{
self.ensure_unique();
self.data.slice_mut()
}
fn pointer_is_inbounds(&self) -> bool {
let slc = self.data.slice();
if slc.is_empty() {
// special case for data-less views
return true;
}
let ptr = slc.as_ptr() as *mut _;
let end = unsafe {
ptr.offset(slc.len() as isize)
};
self.ptr >= ptr && self.ptr <= end
}
/// Perform an elementwise assigment to `self` from `rhs`.
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
pub fn assign<E: Dimension, S2>(&mut self, rhs: &ArrayBase<S2, E>)
where S: DataMut,
A: Clone,
S2: Data<Elem=A>,
{
self.zip_mut_with(rhs, |x, y| *x = y.clone());
}
/// Perform an elementwise assigment to `self` from scalar `x`.
pub fn assign_scalar(&mut self, x: &A)
where S: DataMut, A: Clone,
{
self.unordered_foreach_mut(move |elt| *elt = x.clone());
}
/// Apply closure `f` to each element in the array, in whatever
/// order is the fastest to visit.
fn unordered_foreach_mut<F>(&mut self, mut f: F)
where S: DataMut,
F: FnMut(&mut A)
{
if let Some(slc) = self.as_slice_mut() {
for elt in slc {
f(elt);
}
return;
}
for row in self.inner_iter_mut() {
for elt in row {
f(elt);
}
}
}
fn zip_with_mut_same_shape<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, mut f: F)
where S: DataMut,
S2: Data<Elem=B>,
E: Dimension,
F: FnMut(&mut A, &B)
{
debug_assert_eq!(self.shape(), rhs.shape());
if let Some(self_s) = self.as_slice_mut() {
if let Some(rhs_s) = rhs.as_slice() {
let len = cmp::min(self_s.len(), rhs_s.len());
let s = &mut self_s[..len];
let r = &rhs_s[..len];
for i in 0..len {
f(&mut s[i], &r[i]);
}
return;
}
}
// otherwise, fall back to the outer iter
self.zip_with_mut_outer_iter(rhs, f);
}
#[inline(always)]
fn zip_with_mut_outer_iter<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, mut f: F)
where S: DataMut,
S2: Data<Elem=B>,
E: Dimension,
F: FnMut(&mut A, &B)
{
debug_assert_eq!(self.shape(), rhs.shape());
// otherwise, fall back to the outer iter
let mut try_slices = true;
let mut rows = self.inner_iter_mut().zip(rhs.inner_iter());
for (mut s_row, r_row) in &mut rows {
if try_slices {
if let Some(self_s) = s_row.as_slice_mut() {
if let Some(rhs_s) = r_row.as_slice() {
let len = cmp::min(self_s.len(), rhs_s.len());
let s = &mut self_s[..len];
let r = &rhs_s[..len];
for i in 0..len {
f(&mut s[i], &r[i]);
}
continue;
}
}
try_slices = false;
}
unsafe {
for i in 0..s_row.len() {
f(s_row.uget_mut(i), r_row.uget(i))
}
}
}
}
// FIXME: Guarantee the order here or not?
/// Traverse two arrays in unspecified order, in lock step,
/// calling the closure `f` on each element pair.
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
#[inline]
pub fn zip_mut_with<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, mut f: F)
where S: DataMut,
S2: Data<Elem=B>,
E: Dimension,
F: FnMut(&mut A, &B)
{
if self.dim.ndim() == rhs.dim.ndim() && self.shape() == rhs.shape() {
self.zip_with_mut_same_shape(rhs, f);
} else if rhs.dim.ndim() == 0 {
// Skip broadcast from 0-dim array
// FIXME: Order
unsafe {
let rhs_elem = &*rhs.ptr;
let f_ = &mut f;
self.unordered_foreach_mut(move |elt| f_(elt, rhs_elem));
}
} else {
let rhs_broadcast = rhs.broadcast_unwrap(self.dim());
self.zip_with_mut_outer_iter(&rhs_broadcast, f);
}
}
/// Traverse the array elements in order and apply a fold,
/// returning the resulting value.
pub fn fold<'a, F, B>(&'a self, mut init: B, mut f: F) -> B
where F: FnMut(B, &'a A) -> B, A: 'a
{
if let Some(slc) = self.as_slice() {
for elt in slc {
init = f(init, elt);
}
return init;
}
for row in self.inner_iter() {
for elt in row {
init = f(init, elt);
}
}
init
}
/// Apply `f` elementwise and return a new array with
/// the results.
///
/// Return an array with the same shape as *self*.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[ 0., 1.],
/// [-1., 2.]]);
/// assert!(
/// a.map(|x| *x >= 1.0)
/// == arr2(&[[false, true],
/// [false, true]])
/// );
/// ```
pub fn map<'a, B, F>(&'a self, mut f: F) -> OwnedArray<B, D>
where F: FnMut(&'a A) -> B,
A: 'a,
{
let mut res = Vec::with_capacity(self.dim.size());
for elt in self.iter() {
res.push(f(elt))
}
unsafe {
ArrayBase::from_vec_dim(self.dim.clone(), res)
}
}
}
/// Return an array filled with zeros
pub fn zeros<A, D>(dim: D) -> OwnedArray<A, D>
where A: Clone + libnum::Zero, D: Dimension,
{
ArrayBase::zeros(dim)
}
/// Return a zero-dimensional array with the element `x`.
pub fn arr0<A>(x: A) -> Array<A, ()>
{
unsafe { Array::from_vec_dim((), vec![x]) }
}
/// Return a one-dimensional array with elements from `xs`.
pub fn arr1<A: Clone>(xs: &[A]) -> Array<A, Ix>
{
Array::from_vec(xs.to_vec())
}
/// Return a zero-dimensional array view borrowing `x`.
pub fn aview0<A>(x: &A) -> ArrayView<A, ()> {
unsafe {
ArrayView::new_(x, (), ())
}
}
/// Return a one-dimensional array view with elements borrowing `xs`.
///
/// ```
/// use ndarray::aview1;
///
/// let data = [1.0; 1024];
///
/// // Create a 2D array view from borrowed data
/// let a2d = aview1(&data).into_shape((32, 32)).unwrap();
///
/// assert!(
/// a2d.scalar_sum() == 1024.0
/// );
/// ```
pub fn aview1<A>(xs: &[A]) -> ArrayView<A, Ix> {
ArrayView::from_slice(xs)
}
/// Return a two-dimensional array view with elements borrowing `xs`.
pub fn aview2<A, V: FixedInitializer<Elem=A>>(xs: &[V]) -> ArrayView<A, (Ix, Ix)> {
let cols = V::len();
let rows = xs.len();
let data = unsafe {
std::slice::from_raw_parts(xs.as_ptr() as *const A, cols * rows)
};
let dim = (rows as Ix, cols as Ix);
unsafe {
let strides = dim.default_strides();
ArrayView::new_(data.as_ptr(), dim, strides)
}
}
/// Return a one-dimensional read-write array view with elements borrowing `xs`.
///
/// ```
/// #[macro_use(s)]
/// extern crate ndarray;
///
/// use ndarray::aview_mut1;
///
/// // Create an array view over some data, then slice it and modify it.
/// fn main() {
/// let mut data = [0; 1024];
/// {
/// let mut a = aview_mut1(&mut data).into_shape((32, 32)).unwrap();
/// a.slice_mut(s![.., ..;3]).assign_scalar(&5);
/// }
/// assert_eq!(&data[..10], [5, 0, 0, 5, 0, 0, 5, 0, 0, 5]);
/// }
/// ```
pub fn aview_mut1<A>(xs: &mut [A]) -> ArrayViewMut<A, Ix> {
unsafe {
ArrayViewMut::new_(xs.as_mut_ptr(), xs.len() as Ix, 1)
}
}
/// Slice or fixed-size array used for array initialization
pub unsafe trait Initializer {
type Elem;
fn as_init_slice(&self) -> &[Self::Elem];
fn is_fixed_size() -> bool { false }
}
/// Fixed-size array used for array initialization
pub unsafe trait FixedInitializer: Initializer {
fn len() -> usize;
}
unsafe impl<T> Initializer for [T] {
type Elem = T;
fn as_init_slice(&self) -> &[T] {
self
}
}
macro_rules! impl_arr_init {
(__impl $n: expr) => (
unsafe impl<T> Initializer for [T; $n] {
type Elem = T;
fn as_init_slice(&self) -> &[T] { self }
fn is_fixed_size() -> bool { true }
}
unsafe impl<T> FixedInitializer for [T; $n] {
fn len() -> usize { $n }
}
);
() => ();
($n: expr, $($m:expr,)*) => (
impl_arr_init!(__impl $n);
impl_arr_init!($($m,)*);
)
}
impl_arr_init!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
/// Return a two-dimensional array with elements from `xs`.
///
/// **Panics** if the slices are not all of the same length.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1, 2, 3],
/// [4, 5, 6]]);
/// assert!(
/// a.shape() == [2, 3]
/// );
/// ```
pub fn arr2<A: Clone, V: Initializer<Elem=A>>(xs: &[V]) -> Array<A, (Ix, Ix)>
{
// FIXME: Simplify this when V is fix size array
let (m, n) = (xs.len() as Ix,
xs.get(0).map_or(0, |snd| snd.as_init_slice().len() as Ix));
let dim = (m, n);
let mut result = Vec::<A>::with_capacity(dim.size());
for snd in xs.iter() {
let snd = snd.as_init_slice();
assert!(<V as Initializer>::is_fixed_size() || snd.len() as Ix == n);
result.extend(snd.iter().map(|x| x.clone()))
}
unsafe {
Array::from_vec_dim(dim, result)
}
}
/// Return a three-dimensional array with elements from `xs`.
///
/// **Panics** if the slices are not all of the same length.
///
/// ```
/// use ndarray::arr3;
///
/// let a = arr3(&[[[1, 2],
/// [3, 4]],
/// [[5, 6],
/// [7, 8]],
/// [[9, 0],
/// [1, 2]]]);
/// assert!(
/// a.shape() == [3, 2, 2]
/// );
/// ```
pub fn arr3<A: Clone, V: Initializer<Elem=U>, U: Initializer<Elem=A>>(xs: &[V])
-> Array<A, (Ix, Ix, Ix)>
{
// FIXME: Simplify this when U/V are fix size arrays
let m = xs.len() as Ix;
let fst = xs.get(0).map(|snd| snd.as_init_slice());
let thr = fst.and_then(|elt| elt.get(0).map(|elt2| elt2.as_init_slice()));
let n = fst.map_or(0, |v| v.len() as Ix);
let o = thr.map_or(0, |v| v.len() as Ix);
let dim = (m, n, o);
let mut result = Vec::<A>::with_capacity(dim.size());
for snd in xs.iter() {
let snd = snd.as_init_slice();
assert!(<V as Initializer>::is_fixed_size() || snd.len() as Ix == n);
for thr in snd.iter() {
let thr = thr.as_init_slice();
assert!(<U as Initializer>::is_fixed_size() || thr.len() as Ix == o);
result.extend(thr.iter().map(|x| x.clone()))
}
}
unsafe {
Array::from_vec_dim(dim, result)
}
}
impl<A, S, D> ArrayBase<S, D>
where S: Data<Elem=A>,
D: Dimension,
{
/// Return sum along `axis`.
///
/// ```
/// use ndarray::{aview0, aview1, arr2};
///
/// let a = arr2(&[[1., 2.],
/// [3., 4.]]);
/// assert!(
/// a.sum(0) == aview1(&[4., 6.]) &&
/// a.sum(1) == aview1(&[3., 7.]) &&
///
/// a.sum(0).sum(0) == aview0(&10.)
/// );
/// ```
///
/// **Panics** if `axis` is out of bounds.
pub fn sum(&self, axis: usize) -> OwnedArray<A, <D as RemoveAxis>::Smaller>
where A: Clone + Add<Output=A>,
D: RemoveAxis,
{
let n = self.shape()[axis];
let mut res = self.subview(axis, 0).to_owned();
for i in 1..n {
let view = self.subview(axis, i);
res.iadd(&view);
}
res
}
/// Return the sum of all elements in the array.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 2.],
/// [3., 4.]]);
/// assert_eq!(a.scalar_sum(), 10.);
/// ```
pub fn scalar_sum(&self) -> A
where A: Clone + Add<Output=A> + libnum::Zero,
{
if let Some(slc) = self.as_slice() {
return Self::unrolled_sum(slc);
}
let mut sum = A::zero();
for row in self.inner_iter() {
if let Some(slc) = row.as_slice() {
sum = sum + Self::unrolled_sum(slc);
} else {
sum = sum + row.fold(A::zero(), |acc, elt| acc + elt.clone());
}
}
sum
}
fn unrolled_sum(mut xs: &[A]) -> A
where A: Clone + Add<Output=A> + libnum::Zero,
{
// eightfold unrolled so that floating point can be vectorized
// (even with strict floating point accuracy semantics)
let mut sum = A::zero();
let (mut p0, mut p1, mut p2, mut p3,
mut p4, mut p5, mut p6, mut p7) =
(A::zero(), A::zero(), A::zero(), A::zero(),
A::zero(), A::zero(), A::zero(), A::zero());
while xs.len() >= 8 {
p0 = p0 + xs[0].clone();
p1 = p1 + xs[1].clone();
p2 = p2 + xs[2].clone();
p3 = p3 + xs[3].clone();
p4 = p4 + xs[4].clone();
p5 = p5 + xs[5].clone();
p6 = p6 + xs[6].clone();
p7 = p7 + xs[7].clone();
xs = &xs[8..];
}
sum = sum.clone() + (p0 + p4);
sum = sum.clone() + (p1 + p5);
sum = sum.clone() + (p2 + p6);
sum = sum.clone() + (p3 + p7);
for elt in xs {
sum = sum.clone() + elt.clone();
}
sum
}
/// Return mean along `axis`.
///
/// ```
/// use ndarray::{aview1, arr2};
///
/// let a = arr2(&[[1., 2.],
/// [3., 4.]]);
/// assert!(
/// a.mean(0) == aview1(&[2.0, 3.0]) &&
/// a.mean(1) == aview1(&[1.5, 3.5])
/// );
/// ```
///
///
/// **Panics** if `axis` is out of bounds.
#[allow(deprecated)]
pub fn mean(&self, axis: usize) -> OwnedArray<A, <D as RemoveAxis>::Smaller>
where A: Copy + Field,
D: RemoveAxis,
{
let n = self.shape()[axis];
let mut sum = self.sum(axis);
let one = libnum::one::<A>();
let mut cnt = one;
for _ in 1..n {
cnt = cnt + one;
}
sum.idiv_scalar(&cnt);
sum
}
/// Return `true` if the arrays' elementwise differences are all within
/// the given absolute tolerance.<br>
/// Return `false` otherwise, or if the shapes disagree.
pub fn allclose<S2>(&self, rhs: &ArrayBase<S2, D>, tol: A) -> bool
where A: Float,
S2: Data<Elem=A>,
{
self.shape() == rhs.shape() &&
self.iter().zip(rhs.iter()).all(|(x, y)| (*x - *y).abs() <= tol)
}
}
impl<A, S> ArrayBase<S, Ix>
where S: Data<Elem=A>,
{
/// Compute the dot product of one-dimensional arrays.
///
/// The dot product is a sum of the elementwise products (no conjugation
/// of complex operands, and thus not their inner product).
///
/// **Panics** if the arrays are not of the same length.
pub fn dot<S2>(&self, rhs: &ArrayBase<S2, Ix>) -> A
where S2: Data<Elem=A>,
A: Clone + Add<Output=A> + Mul<Output=A> + libnum::Zero,
{
assert_eq!(self.len(), rhs.len());
if let Some(self_s) = self.as_slice() {
if let Some(rhs_s) = rhs.as_slice() {
return numeric_util::unrolled_dot(self_s, rhs_s);
}
}
let mut sum = A::zero();
for i in 0..self.len() {
unsafe {
sum = sum.clone() + self.uget(i).clone() * rhs.uget(i).clone();
}
}
sum
}
}
impl<A, S> ArrayBase<S, (Ix, Ix)>
where S: Data<Elem=A>,
{
unsafe fn one_dimensional_iter<'a>(ptr: *mut A, len: Ix, stride: Ix)
-> Elements<'a, A, Ix>
{
ArrayView::new_(ptr, len, stride).into_iter_()
}
/// Return an array view of row `index`.
///
/// **Panics** if `index` is out of bounds.
pub fn row(&self, index: Ix) -> ArrayView<A, Ix>
{
self.subview(0, index)
}
/// Return an array view of column `index`.
///
/// **Panics** if `index` is out of bounds.
pub fn column(&self, index: Ix) -> ArrayView<A, Ix>
{
self.subview(1, index)
}
/// Return a mutable array view of row `index`.
///
/// **Panics** if `index` is out of bounds.
pub fn row_mut(&mut self, index: Ix) -> ArrayViewMut<A, Ix>
where S: DataMut
{
self.subview_mut(0, index)
}
/// Return a mutable array view of column `index`.
///
/// **Panics** if `index` is out of bounds.
pub fn column_mut(&mut self, index: Ix) -> ArrayViewMut<A, Ix>
where S: DataMut
{
self.subview_mut(1, index)
}
#[cfg_attr(has_deprecated, deprecated(note="use .row() instead"))]
/// ***Deprecated: Use `.row()` instead.***
pub fn row_iter(&self, index: Ix) -> Elements<A, Ix>
{
let (m, n) = self.dim;
let (sr, sc) = self.strides;
assert!(index < m);
unsafe {
Self::one_dimensional_iter(self.ptr.offset(stride_offset(index, sr)), n, sc)
}
}
#[cfg_attr(has_deprecated, deprecated(note="use .column() instead"))]
/// ***Deprecated: Use `.column()` instead.***
pub fn col_iter(&self, index: Ix) -> Elements<A, Ix>
{
let (m, n) = self.dim;
let (sr, sc) = self.strides;
assert!(index < n);
unsafe {
Self::one_dimensional_iter(self.ptr.offset(stride_offset(index, sc)), m, sr)
}
}
/// Perform matrix multiplication of rectangular arrays `self` and `rhs`.
///
/// The array shapes must agree in the way that
/// if `self` is *M* × *N*, then `rhs` is *N* × *K*.
///
/// Return a result array with shape *M* × *K*.
///
/// **Panics** if shapes are incompatible.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 2.],
/// [0., 1.]]);
/// let b = arr2(&[[1., 2.],
/// [2., 3.]]);
///
/// assert!(
/// a.mat_mul(&b) == arr2(&[[5., 8.],
/// [2., 3.]])
/// );
/// ```
///
#[allow(deprecated)]
pub fn mat_mul(&self, rhs: &ArrayBase<S, (Ix, Ix)>) -> OwnedArray<A, (Ix, Ix)>
where A: Copy + Ring
{
// NOTE: Matrix multiplication only defined for Copy types to
// avoid trouble with panicking + and *, and destructors
let ((m, a), (b, n)) = (self.dim, rhs.dim);
let (self_columns, other_rows) = (a, b);
assert!(self_columns == other_rows);
// Avoid initializing the memory in vec -- set it during iteration
// Panic safe because A: Copy
let mut res_elems = Vec::<A>::with_capacity(m as usize * n as usize);
unsafe {
res_elems.set_len(m as usize * n as usize);
}
let mut i = 0;
let mut j = 0;
for rr in res_elems.iter_mut() {
unsafe {
*rr = (0..a).fold(libnum::zero::<A>(),
move |s, k| s + *self.uget((i, k)) * *rhs.uget((k, j))
);
}
j += 1;
if j == n {
j = 0;
i += 1;
}
}
unsafe {
ArrayBase::from_vec_dim((m, n), res_elems)
}
}
/// Perform the matrix multiplication of the rectangular array `self` and
/// column vector `rhs`.
///
/// The array shapes must agree in the way that
/// if `self` is *M* × *N*, then `rhs` is *N*.
///
/// Return a result array with shape *M*.
///
/// **Panics** if shapes are incompatible.
#[allow(deprecated)]
pub fn mat_mul_col(&self, rhs: &ArrayBase<S, Ix>) -> OwnedArray<A, Ix>
where A: Copy + Ring
{
let ((m, a), n) = (self.dim, rhs.dim);
let (self_columns, other_rows) = (a, n);
assert!(self_columns == other_rows);
// Avoid initializing the memory in vec -- set it during iteration
let mut res_elems = Vec::<A>::with_capacity(m as usize);
unsafe {
res_elems.set_len(m as usize);
}
let mut i = 0;
for rr in res_elems.iter_mut() {
unsafe {
*rr = (0..a).fold(libnum::zero::<A>(),
move |s, k| s + *self.uget((i, k)) * *rhs.uget(k)
);
}
i += 1;
}
unsafe {
ArrayBase::from_vec_dim(m, res_elems)
}
}
}
// Array OPERATORS
macro_rules! impl_binary_op_inherent(
($trt:ident, $mth:ident, $imethod:ident, $imth_scalar:ident, $doc:expr) => (
/// Perform elementwise
#[doc=$doc]
/// between `self` and `rhs`,
/// *in place*.
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
pub fn $imethod <E: Dimension, S2> (&mut self, rhs: &ArrayBase<S2, E>)
where A: Clone + $trt<A, Output=A>,
S2: Data<Elem=A>,
{
self.zip_mut_with(rhs, |x, y| {
*x = x.clone().$mth(y.clone());
});
}
/// Perform elementwise
#[doc=$doc]
/// between `self` and the scalar `x`,
/// *in place*.
pub fn $imth_scalar (&mut self, x: &A)
where A: Clone + $trt<A, Output=A>,
{
self.unordered_foreach_mut(move |elt| {
*elt = elt.clone(). $mth (x.clone());
});
}
);
);
/// *In-place* arithmetic operations.
impl<A, S, D> ArrayBase<S, D>
where S: DataMut<Elem=A>,
D: Dimension,
{
impl_binary_op_inherent!(Add, add, iadd, iadd_scalar, "addition");
impl_binary_op_inherent!(Sub, sub, isub, isub_scalar, "subtraction");
impl_binary_op_inherent!(Mul, mul, imul, imul_scalar, "multiplication");
impl_binary_op_inherent!(Div, div, idiv, idiv_scalar, "division");
impl_binary_op_inherent!(Rem, rem, irem, irem_scalar, "remainder");
impl_binary_op_inherent!(BitAnd, bitand, ibitand, ibitand_scalar, "bit and");
impl_binary_op_inherent!(BitOr, bitor, ibitor, ibitor_scalar, "bit or");
impl_binary_op_inherent!(BitXor, bitxor, ibitxor, ibitxor_scalar, "bit xor");
impl_binary_op_inherent!(Shl, shl, ishl, ishl_scalar, "left shift");
impl_binary_op_inherent!(Shr, shr, ishr, ishr_scalar, "right shift");
/// Perform an elementwise negation of `self`, *in place*.
pub fn ineg(&mut self)
where A: Clone + Neg<Output=A>,
{
self.unordered_foreach_mut(|elt| {
*elt = elt.clone().neg()
});
}
/// Perform an elementwise unary not of `self`, *in place*.
pub fn inot(&mut self)
where A: Clone + Not<Output=A>,
{
self.unordered_foreach_mut(|elt| {
*elt = elt.clone().not()
});
}
}
/// Elements that can be used as direct operands in arithmetic with arrays.
///
/// This trait ***does not*** limit which elements can be stored in an `ArrayBase`.
///
/// `Scalar` simply determines which types are applicable for direct operator
/// overloading, e.g. `B @ K` or `B @= K` where `B` is a mutable array,
/// `K` a scalar, and `@` arbitrary arithmetic operator that the scalar supports.
///
/// Left hand side operands must instead be implemented one by one (it does not
/// involve the `Scalar` trait). Scalar left hand side operations: `K @ &A`
/// and `K @ B`, are implemented for the primitive numerical types and for
/// `Complex<f32>, Complex<f64>`.
///
/// Non-`Scalar` types can still participate in arithmetic as array elements in
/// in array-array operations.
pub trait Scalar { }
impl Scalar for bool { }
impl Scalar for i8 { }
impl Scalar for u8 { }
impl Scalar for i16 { }
impl Scalar for u16 { }
impl Scalar for i32 { }
impl Scalar for u32 { }
impl Scalar for i64 { }
impl Scalar for u64 { }
impl Scalar for f32 { }
impl Scalar for f64 { }
impl Scalar for Complex<f32> { }
impl Scalar for Complex<f64> { }
macro_rules! impl_binary_op(
($trt:ident, $mth:ident, $imth:ident, $imth_scalar:ident, $doc:expr) => (
/// Perform elementwise
#[doc=$doc]
/// between `self` and `rhs`,
/// and return the result (based on `self`).
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
impl<A, S, S2, D, E> $trt<ArrayBase<S2, E>> for ArrayBase<S, D>
where A: Clone + $trt<A, Output=A>,
S: DataMut<Elem=A>,
S2: Data<Elem=A>,
D: Dimension,
E: Dimension,
{
type Output = ArrayBase<S, D>;
fn $mth(self, rhs: ArrayBase<S2, E>) -> ArrayBase<S, D>
{
self.$mth(&rhs)
}
}
/// Perform elementwise
#[doc=$doc]
/// between `self` and reference `rhs`,
/// and return the result (based on `self`).
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
impl<'a, A, S, S2, D, E> $trt<&'a ArrayBase<S2, E>> for ArrayBase<S, D>
where A: Clone + $trt<A, Output=A>,
S: DataMut<Elem=A>,
S2: Data<Elem=A>,
D: Dimension,
E: Dimension,
{
type Output = ArrayBase<S, D>;
fn $mth (mut self, rhs: &ArrayBase<S2, E>) -> ArrayBase<S, D>
{
self.$imth(rhs);
self
}
}
/// Perform elementwise
#[doc=$doc]
/// between references `self` and `rhs`,
/// and return the result as a new `OwnedArray`.
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
impl<'a, A, S, S2, D, E> $trt<&'a ArrayBase<S2, E>> for &'a ArrayBase<S, D>
where A: Clone + $trt<A, Output=A>,
S: Data<Elem=A>,
S2: Data<Elem=A>,
D: Dimension,
E: Dimension,
{
type Output = OwnedArray<A, D>;
fn $mth (self, rhs: &'a ArrayBase<S2, E>) -> OwnedArray<A, D>
{
// FIXME: Can we co-broadcast arrays here? And how?
self.to_owned().$mth(rhs.view())
}
}
/// Perform elementwise
#[doc=$doc]
/// between `self` and the scalar `x`,
/// and return the result (based on `self`).
impl<A, S, D, B> $trt<B> for ArrayBase<S, D>
where A: Clone + $trt<B, Output=A>,
S: DataMut<Elem=A>,
D: Dimension,
B: Clone + Scalar,
{
type Output = ArrayBase<S, D>;
fn $mth (mut self, x: B) -> ArrayBase<S, D>
{
self.unordered_foreach_mut(move |elt| {
*elt = elt.clone().$mth(x.clone());
});
self
}
}
/// Perform elementwise
#[doc=$doc]
/// between the reference `self` and the scalar `x`,
/// and return the result as a new `OwnedArray`.
impl<'a, A, S, D, B> $trt<B> for &'a ArrayBase<S, D>
where A: Clone + $trt<B, Output=A>,
S: Data<Elem=A>,
D: Dimension,
B: Clone + Scalar,
{
type Output = OwnedArray<A, D>;
fn $mth(self, x: B) -> OwnedArray<A, D>
{
self.to_owned().$mth(x)
}
}
);
);
macro_rules! impl_scalar_op {
($scalar:ty, $trt:ident, $mth:ident, $doc:expr) => (
// these have no doc -- they are not visible in rustdoc
// Perform elementwise
// between the scalar `self` and array `rhs`,
// and return the result (based on `self`).
impl<S, D> $trt<ArrayBase<S, D>> for $scalar
where S: DataMut<Elem=$scalar>,
D: Dimension,
{
type Output = ArrayBase<S, D>;
fn $mth (self, mut rhs: ArrayBase<S, D>) -> ArrayBase<S, D>
{
rhs.unordered_foreach_mut(move |elt| {
*elt = self.$mth(*elt);
});
rhs
}
}
// Perform elementwise
// between the scalar `self` and array `rhs`,
// and return the result as a new `OwnedArray`.
impl<'a, S, D> $trt<&'a ArrayBase<S, D>> for $scalar
where S: Data<Elem=$scalar>,
D: Dimension,
{
type Output = OwnedArray<$scalar, D>;
fn $mth (self, rhs: &ArrayBase<S, D>) -> OwnedArray<$scalar, D>
{
self.$mth(rhs.to_owned())
}
}
);
}
mod arithmetic_ops {
use super::*;
use std::ops::*;
use libnum::Complex;
impl_binary_op!(Add, add, iadd, iadd_scalar, "addition");
impl_binary_op!(Sub, sub, isub, isub_scalar, "subtraction");
impl_binary_op!(Mul, mul, imul, imul_scalar, "multiplication");
impl_binary_op!(Div, div, idiv, idiv_scalar, "division");
impl_binary_op!(Rem, rem, irem, irem_scalar, "remainder");
impl_binary_op!(BitAnd, bitand, ibitand, ibitand_scalar, "bit and");
impl_binary_op!(BitOr, bitor, ibitor, ibitor_scalar, "bit or");
impl_binary_op!(BitXor, bitxor, ibitxor, ibitxor_scalar, "bit xor");
impl_binary_op!(Shl, shl, ishl, ishl_scalar, "left shift");
impl_binary_op!(Shr, shr, ishr, ishr_scalar, "right shift");
macro_rules! all_scalar_ops {
($int_scalar:ty) => (
impl_scalar_op!($int_scalar, Add, add, "addition");
impl_scalar_op!($int_scalar, Sub, sub, "subtraction");
impl_scalar_op!($int_scalar, Mul, mul, "multiplication");
impl_scalar_op!($int_scalar, Div, div, "division");
impl_scalar_op!($int_scalar, Rem, rem, "remainder");
impl_scalar_op!($int_scalar, BitAnd, bitand, "bit and");
impl_scalar_op!($int_scalar, BitOr, bitor, "bit or");
impl_scalar_op!($int_scalar, BitXor, bitxor, "bit xor");
impl_scalar_op!($int_scalar, Shl, shl, "left shift");
impl_scalar_op!($int_scalar, Shr, shr, "right shift");
);
}
all_scalar_ops!(i8);
all_scalar_ops!(u8);
all_scalar_ops!(i16);
all_scalar_ops!(u16);
all_scalar_ops!(i32);
all_scalar_ops!(u32);
all_scalar_ops!(i64);
all_scalar_ops!(u64);
impl_scalar_op!(bool, BitAnd, bitand, "bit and");
impl_scalar_op!(bool, BitOr, bitor, "bit or");
impl_scalar_op!(bool, BitXor, bitxor, "bit xor");
impl_scalar_op!(f32, Add, add, "addition");
impl_scalar_op!(f32, Sub, sub, "subtraction");
impl_scalar_op!(f32, Mul, mul, "multiplication");
impl_scalar_op!(f32, Div, div, "division");
impl_scalar_op!(f32, Rem, rem, "remainder");
impl_scalar_op!(f64, Add, add, "addition");
impl_scalar_op!(f64, Sub, sub, "subtraction");
impl_scalar_op!(f64, Mul, mul, "multiplication");
impl_scalar_op!(f64, Div, div, "division");
impl_scalar_op!(f64, Rem, rem, "remainder");
impl_scalar_op!(Complex<f32>, Add, add, "addition");
impl_scalar_op!(Complex<f32>, Sub, sub, "subtraction");
impl_scalar_op!(Complex<f32>, Mul, mul, "multiplication");
impl_scalar_op!(Complex<f32>, Div, div, "division");
impl_scalar_op!(Complex<f64>, Add, add, "addition");
impl_scalar_op!(Complex<f64>, Sub, sub, "subtraction");
impl_scalar_op!(Complex<f64>, Mul, mul, "multiplication");
impl_scalar_op!(Complex<f64>, Div, div, "division");
impl<A, S, D> Neg for ArrayBase<S, D>
where A: Clone + Neg<Output=A>,
S: DataMut<Elem=A>,
D: Dimension
{
type Output = Self;
/// Perform an elementwise negation of `self` and return the result.
fn neg(mut self) -> Self {
self.ineg();
self
}
}
impl<A, S, D> Not for ArrayBase<S, D>
where A: Clone + Not<Output=A>,
S: DataMut<Elem=A>,
D: Dimension
{
type Output = Self;
/// Perform an elementwise unary not of `self` and return the result.
fn not(mut self) -> Self {
self.inot();
self
}
}
}
#[cfg(feature = "assign_ops")]
mod assign_ops {
use super::*;
macro_rules! impl_assign_op {
($trt:ident, $method:ident, $doc:expr) => {
use std::ops::$trt;
#[doc=$doc]
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// **Panics** if broadcasting isn’t possible.
///
/// **Requires `feature = "assign_ops"`**
impl<'a, A, S, S2, D, E> $trt<&'a ArrayBase<S2, E>> for ArrayBase<S, D>
where A: Clone + $trt<A>,
S: DataMut<Elem=A>,
S2: Data<Elem=A>,
D: Dimension,
E: Dimension,
{
fn $method(&mut self, rhs: &ArrayBase<S2, E>) {
self.zip_mut_with(rhs, |x, y| {
x.$method(y.clone());
});
}
}
#[doc=$doc]
/// **Requires `feature = "assign_ops"`**
impl<A, S, D, B> $trt<B> for ArrayBase<S, D>
where A: $trt<B>,
S: DataMut<Elem=A>,
D: Dimension,
B: Clone + Scalar,
{
fn $method(&mut self, rhs: B) {
self.unordered_foreach_mut(move |elt| {
elt.$method(rhs.clone());
});
}
}
};
}
impl_assign_op!(AddAssign, add_assign,
"Perform `self += rhs` as elementwise addition (in place).\n");
impl_assign_op!(SubAssign, sub_assign,
"Perform `self -= rhs` as elementwise subtraction (in place).\n");
impl_assign_op!(MulAssign, mul_assign,
"Perform `self *= rhs` as elementwise multiplication (in place).\n");
impl_assign_op!(DivAssign, div_assign,
"Perform `self /= rhs` as elementwise division (in place).\n");
impl_assign_op!(RemAssign, rem_assign,
"Perform `self %= rhs` as elementwise remainder (in place).\n");
impl_assign_op!(BitAndAssign, bitand_assign,
"Perform `self &= rhs` as elementwise bit and (in place).\n");
impl_assign_op!(BitOrAssign, bitor_assign,
"Perform `self |= rhs` as elementwise bit or (in place).\n");
impl_assign_op!(BitXorAssign, bitxor_assign,
"Perform `self ^= rhs` as elementwise bit xor (in place).\n");
}
/// An iterator over the elements of an array.
///
/// Iterator element type is `&'a A`.
///
/// See [`.iter()`](struct.ArrayBase.html#method.iter) for more information.
pub struct Elements<'a, A: 'a, D> {
inner: ElementsRepr<Iter<'a, A>, ElementsBase<'a, A, D>>,
}
/// Counted read only iterator
struct ElementsBase<'a, A: 'a, D> {
inner: Baseiter<'a, A, D>,
}
/// An iterator over the elements of an array (mutable).
///
/// Iterator element type is `&'a mut A`.
///
/// See [`.iter_mut()`](struct.ArrayBase.html#method.iter_mut) for more information.
pub struct ElementsMut<'a, A: 'a, D> {
inner: ElementsRepr<IterMut<'a, A>, ElementsBaseMut<'a, A, D>>,
}
/// An iterator over the elements of an array.
///
/// Iterator element type is `&'a mut A`.
struct ElementsBaseMut<'a, A: 'a, D> {
inner: Baseiter<'a, A, D>,
}
/// An iterator over the indexes and elements of an array.
///
/// See [`.indexed_iter()`](struct.ArrayBase.html#method.indexed_iter) for more information.
#[derive(Clone)]
pub struct Indexed<'a, A: 'a, D>(ElementsBase<'a, A, D>);
/// An iterator over the indexes and elements of an array (mutable).
///
/// See [`.indexed_iter_mut()`](struct.ArrayBase.html#method.indexed_iter_mut) for more information.
pub struct IndexedMut<'a, A: 'a, D>(ElementsBaseMut<'a, A, D>);
fn zipsl<T, U>(t: T, u: U) -> ZipSlices<T, U>
where T: it::misc::Slice, U: it::misc::Slice
{
ZipSlices::from_slices(t, u)
}
enum ElementsRepr<S, C> {
Slice(S),
Counted(C),
}
|
use super::{Agent, Direction, Game, Turn::*};
use std::iter;
use rustneat::Organism;
impl Direction {
#[inline(always)]
fn input_enc(&self) -> f64 {
match self {
Direction::CW => 0.0,
Direction::CCW => 1.0,
}
}
}
pub struct TrainingAgent<'o> {
organism: &'o mut Organism,
input: [f64; 33],
output: Vec<f64>,
indexed_output: [(usize, f64); 16],
}
impl<'o> TrainingAgent<'o> {
pub fn new(organism: &'o mut Organism) -> Self {
Self {
organism,
input: [0.0; 33],
output: vec![0.0; 16], // must be a vec because of activate()
indexed_output: [(0, 0.0); 16],
}
}
}
impl Agent for TrainingAgent<'_> {
fn pick_index(&mut self, game: &Game) -> usize {
let (player, opponent) = if game.turn() == Player1 {
(&game.player1, &game.player2)
} else {
(&game.player2, &game.player1)
};
for (src, dst) in player
.board_half
.iter()
.chain(opponent.board_half.iter())
.map(|&val| val as f64)
.chain(iter::once(game.direction.input_enc()))
.zip(&mut self.input[..])
{
*dst = src;
}
self.organism.activate(&self.input, &mut self.output);
for (src, dst) in self
.output
.iter()
.copied()
.enumerate()
.zip(&mut self.indexed_output)
{
*dst = src;
}
self.indexed_output
.sort_unstable_by(|(_, a), (_, b)| b.partial_cmp(a).expect("NaN?"));
// Select the best index that is valid.
self.indexed_output
.iter()
.find(|&&(index, _)| player.is_valid_index(index))
.expect("No valid index?")
.0
}
}
|
use crate::parser::tokens::*;
pub fn print_token (token: &Token) {
match token {
Token::Keyword(kwd) => eprintln!("Keyword: \"{}\"", kwd),
Token::Identifier(ident) => eprintln!("Identifier: \"{}\"", ident),
Token::Integer(int) => eprintln!("Integer literal: {}", int),
Token::Punctuation(pnc) => eprintln!("Punctuation: {}", pnc),
Token::Operator(op) => eprintln!("Operator: {}", op),
Token::Character(ch) => eprint!("Character: {}", ch),
Token::String(st) => eprintln!("String: \"{}\"", st)
}
}
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//! Some programming utilities
/// Returns a float rounded upto a certain number of decimal digits
#[inline]
pub fn round_upto_digits(float: f64, decimal_digits: u32) -> f64
{
let mut d = 1.0;
for _ in 1..(decimal_digits + 1) {
d *= 10.0;
}
(float * d).round() / d
}
/**
Evaluates a polynomial using Horner's algorithm
# Arguments
* `$x` : The value of the independent variable `f32 or f64`
* `$c` : The constant term `f32 or f64`
* `$($a),*`: Sequence of coefficient terms for `$x`, in ascending
powers of `$x`
**/
#[macro_export]
macro_rules! Horner_eval
{
($x:expr, $c:expr, $($a:expr),*) =>
{
{
let mut y = $c;
let mut u = 1.0;
$(
u *= $x;
y += u * $a;
)*
y
}
}
}
|
use io::*;
use std::*;
use std::cmp::max;
fn solve(N: i64, M: i64, K: i64, A: Vec<i64>, B: Vec<i64>) {
let mut desk_a = Desk::new(A);
let mut desk_b = Desk::new(B);
let mut time = init(&mut desk_a, &mut desk_b, K);
let mut n_read = desk_a.read + desk_b.read;
loop {
match desk_a.prev() {
Some(t) => {
time -= t;
time -= desk_b.read_as_possible(time);
n_read = max(n_read, desk_a.read + desk_b.read);
}
None => break
}
}
println!("{}", n_read)
}
fn init(a: &mut Desk, b: &mut Desk, rest_time: i64) -> i64 {
let rest_time = rest_time - a.read_as_possible(rest_time);
rest_time - b.read_as_possible(rest_time)
}
struct Desk {
books: Vec<i64>,
read: usize,
}
impl Desk {
pub fn new(books: Vec<i64>) -> Desk {
Desk{
books,
read: 0,
}
}
pub fn next(&mut self) -> Option<i64> {
if self.read == self.books.len() {
None
} else {
self.read += 1;
Some(self.books[self.read - 1])
}
}
pub fn prev(&mut self) -> Option<i64> {
if self.read == 0 {
None
} else {
self.read -= 1;
Some(-self.books[self.read])
}
}
pub fn read_as_possible(&mut self, rest_time: i64) -> i64 {
let mut total_time = 0;
loop {
match self.next() {
Some(t) if (t + total_time) <= rest_time => total_time += t,
Some(_) => {
self.prev();
break
}
None => break
}
}
total_time
}
}
// Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
fn main() {
let con = read_string();
let mut scanner = Scanner::new(&con);
let mut N: i64;
N = scanner.next();
let mut M: i64;
M = scanner.next();
let mut K: i64;
K = scanner.next();
let mut A: Vec<i64> = vec![0i64; (N) as usize];
for i in 0..(N) as usize {
A[i] = scanner.next();
}
let mut B: Vec<i64> = vec![0i64; (M) as usize];
for i in 0..(M) as usize {
B[i] = scanner.next();
}
// In order to avoid potential stack overflow, spawn a new thread.
let stack_size = 104_857_600; // 100 MB
let thd = std::thread::Builder::new().stack_size(stack_size);
thd.spawn(move || solve(N, M, K, A, B)).unwrap().join().unwrap();
}
pub mod io {
use std;
use std::str::FromStr;
pub struct Scanner<'a> {
iter: std::str::SplitWhitespace<'a>,
}
impl<'a> Scanner<'a> {
pub fn new(s: &'a str) -> Scanner<'a> {
Scanner {
iter: s.split_whitespace(),
}
}
pub fn next<T: FromStr>(&mut self) -> T {
let s = self.iter.next().unwrap();
if let Ok(v) = s.parse::<T>() {
v
} else {
panic!("Parse error")
}
}
pub fn next_vec_len<T: FromStr>(&mut self) -> Vec<T> {
let n: usize = self.next();
self.next_vec(n)
}
pub fn next_vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
(0..n).map(|_| self.next()).collect()
}
}
pub fn read_string() -> String {
use std::io::Read;
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).unwrap();
s
}
pub fn read_line() -> String {
let mut s = String::new();
std::io::stdin().read_line(&mut s).unwrap();
s.trim_right().to_owned()
}
}
|
#![allow(unused_imports)]
#[cfg(not(any(feature = "runtime-tokio", feature = "runtime-async-std")))]
compile_error!("'runtime-async-std' or 'runtime-tokio' features which one of must be enabled");
#[cfg(all(feature = "runtime-tokio", feature = "runtime-async-std"))]
compile_error!("'runtime-async-std' or 'runtime-tokio' features which one of must be enabled");
#[cfg(feature = "runtime-async-std")]
pub(crate) use async_std::{
fs,
future::timeout,
io::prelude::ReadExt as AsyncReadExt,
io::{Read as AsyncRead, Write as AsyncWrite},
net::TcpStream,
task::sleep,
task::spawn,
sync::Mutex,
sync::MutexGuard
};
#[cfg(feature = "runtime-tokio")]
pub(crate) use tokio::{
fs,
io::{AsyncRead, AsyncReadExt, AsyncWrite},
net::TcpStream,
task::spawn,
time::delay_for as sleep,
time::timeout,
sync::Mutex,
sync::MutexGuard
};
|
use utopia_core::math::{Size, Vector2};
use utopia_core::widgets::pod::WidgetPod;
use utopia_core::widgets::{TypedWidget, Widget};
use utopia_core::{Backend, BoxConstraints};
/// A Widget that fills its parent.
///
/// Will align the inner child following the given arguments
pub struct Align<T, B: Backend> {
widget: WidgetPod<T, B>,
vertical: VerticalAlignment,
horizontal: HorizontalAlignment,
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum VerticalAlignment {
Top,
Center,
Bottom,
}
impl Default for VerticalAlignment {
fn default() -> Self {
VerticalAlignment::Center
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum HorizontalAlignment {
Left,
Center,
Right,
}
impl Default for HorizontalAlignment {
fn default() -> Self {
HorizontalAlignment::Center
}
}
impl<T, B: Backend> Align<T, B> {
pub fn new<TW: TypedWidget<T, B> + 'static>(widget: TW) -> Self {
Align {
widget: WidgetPod::new(widget),
vertical: VerticalAlignment::default(),
horizontal: HorizontalAlignment::default(),
}
}
pub fn horizontal(mut self, horizontal_alignment: HorizontalAlignment) -> Self {
self.horizontal = horizontal_alignment;
self
}
pub fn vertical(mut self, vertical_alignment: VerticalAlignment) -> Self {
self.vertical = vertical_alignment;
self
}
}
impl<T, B: Backend> Widget<T> for Align<T, B> {
type Primitive = B::Primitive;
type Context = B;
type Event = B::Event;
type Reaction = B::EventReaction;
fn layout(&mut self, bc: &BoxConstraints, context: &Self::Context, data: &T) -> Size {
let child_size = TypedWidget::<T, B>::layout(&mut self.widget, bc, context, data);
let mut bc_size = child_size.clone();
if bc.is_width_bounded() {
bc_size.width = bc.max.width;
}
if bc.is_height_bounded() {
bc_size.height = bc.max.height;
}
let left = match self.horizontal {
HorizontalAlignment::Left => 0.,
HorizontalAlignment::Center => bc_size.width / 2. - child_size.width / 2.,
HorizontalAlignment::Right => bc_size.width - child_size.width,
};
let top = match self.vertical {
VerticalAlignment::Top => 0.,
VerticalAlignment::Center => bc_size.height / 2. - child_size.height / 2.,
VerticalAlignment::Bottom => bc_size.height - child_size.height,
};
self.widget.set_origin(Vector2 { x: left, y: top });
bc.constrain(bc_size)
}
fn draw(&self, origin: Vector2, size: Size, data: &T) -> Self::Primitive {
TypedWidget::<T, B>::draw(&self.widget, origin, size, data)
}
fn event(
&mut self,
origin: Vector2,
size: Size,
data: &mut T,
event: Self::Event,
) -> Option<Self::Reaction> {
TypedWidget::<T, B>::event(&mut self.widget, origin, size, data, event)
}
}
|
//! Buffer protocol
//! https://docs.python.org/3/c-api/buffer.html
use crate::{
common::{
borrow::{BorrowedValue, BorrowedValueMut},
lock::{MapImmutable, PyMutex, PyMutexGuard},
},
object::PyObjectPayload,
sliceable::SequenceIndexOp,
types::{Constructor, Unconstructible},
Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, VirtualMachine,
};
use itertools::Itertools;
use std::{borrow::Cow, fmt::Debug, ops::Range};
pub struct BufferMethods {
pub obj_bytes: fn(&PyBuffer) -> BorrowedValue<[u8]>,
pub obj_bytes_mut: fn(&PyBuffer) -> BorrowedValueMut<[u8]>,
pub release: fn(&PyBuffer),
pub retain: fn(&PyBuffer),
}
impl Debug for BufferMethods {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BufferMethods")
.field("obj_bytes", &(self.obj_bytes as usize))
.field("obj_bytes_mut", &(self.obj_bytes_mut as usize))
.field("release", &(self.release as usize))
.field("retain", &(self.retain as usize))
.finish()
}
}
#[derive(Debug, Clone, Traverse)]
pub struct PyBuffer {
pub obj: PyObjectRef,
#[pytraverse(skip)]
pub desc: BufferDescriptor,
#[pytraverse(skip)]
methods: &'static BufferMethods,
}
impl PyBuffer {
pub fn new(obj: PyObjectRef, desc: BufferDescriptor, methods: &'static BufferMethods) -> Self {
let zelf = Self {
obj,
desc: desc.validate(),
methods,
};
zelf.retain();
zelf
}
pub fn as_contiguous(&self) -> Option<BorrowedValue<[u8]>> {
self.desc
.is_contiguous()
.then(|| unsafe { self.contiguous_unchecked() })
}
pub fn as_contiguous_mut(&self) -> Option<BorrowedValueMut<[u8]>> {
(!self.desc.readonly && self.desc.is_contiguous())
.then(|| unsafe { self.contiguous_mut_unchecked() })
}
pub fn from_byte_vector(bytes: Vec<u8>, vm: &VirtualMachine) -> Self {
let bytes_len = bytes.len();
PyBuffer::new(
PyPayload::into_pyobject(VecBuffer::from(bytes), vm),
BufferDescriptor::simple(bytes_len, true),
&VEC_BUFFER_METHODS,
)
}
/// # Safety
/// assume the buffer is contiguous
pub unsafe fn contiguous_unchecked(&self) -> BorrowedValue<[u8]> {
self.obj_bytes()
}
/// # Safety
/// assume the buffer is contiguous and writable
pub unsafe fn contiguous_mut_unchecked(&self) -> BorrowedValueMut<[u8]> {
self.obj_bytes_mut()
}
pub fn append_to(&self, buf: &mut Vec<u8>) {
if let Some(bytes) = self.as_contiguous() {
buf.extend_from_slice(&bytes);
} else {
let bytes = &*self.obj_bytes();
self.desc.for_each_segment(true, |range| {
buf.extend_from_slice(&bytes[range.start as usize..range.end as usize])
});
}
}
pub fn contiguous_or_collect<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
let borrowed;
let mut collected;
let v = if let Some(bytes) = self.as_contiguous() {
borrowed = bytes;
&*borrowed
} else {
collected = vec![];
self.append_to(&mut collected);
&collected
};
f(v)
}
pub fn obj_as<T: PyObjectPayload>(&self) -> &Py<T> {
unsafe { self.obj.downcast_unchecked_ref() }
}
pub fn obj_bytes(&self) -> BorrowedValue<[u8]> {
(self.methods.obj_bytes)(self)
}
pub fn obj_bytes_mut(&self) -> BorrowedValueMut<[u8]> {
(self.methods.obj_bytes_mut)(self)
}
pub fn release(&self) {
(self.methods.release)(self)
}
pub fn retain(&self) {
(self.methods.retain)(self)
}
// drop PyBuffer without calling release
// after this function, the owner should use forget()
// or wrap PyBuffer in the ManaullyDrop to prevent drop()
pub(crate) unsafe fn drop_without_release(&mut self) {
std::ptr::drop_in_place(&mut self.obj);
std::ptr::drop_in_place(&mut self.desc);
}
}
impl<'a> TryFromBorrowedObject<'a> for PyBuffer {
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
let cls = obj.class();
let as_buffer = cls.mro_find_map(|cls| cls.slots.as_buffer);
if let Some(f) = as_buffer {
return f(obj, vm);
}
Err(vm.new_type_error(format!(
"a bytes-like object is required, not '{}'",
cls.name()
)))
}
}
impl Drop for PyBuffer {
fn drop(&mut self) {
self.release();
}
}
#[derive(Debug, Clone)]
pub struct BufferDescriptor {
/// product(shape) * itemsize
/// bytes length, but not the length for obj_bytes() even is contiguous
pub len: usize,
pub readonly: bool,
pub itemsize: usize,
pub format: Cow<'static, str>,
/// (shape, stride, suboffset) for each dimension
pub dim_desc: Vec<(usize, isize, isize)>,
// TODO: flags
}
impl BufferDescriptor {
pub fn simple(bytes_len: usize, readonly: bool) -> Self {
Self {
len: bytes_len,
readonly,
itemsize: 1,
format: Cow::Borrowed("B"),
dim_desc: vec![(bytes_len, 1, 0)],
}
}
pub fn format(
bytes_len: usize,
readonly: bool,
itemsize: usize,
format: Cow<'static, str>,
) -> Self {
Self {
len: bytes_len,
readonly,
itemsize,
format,
dim_desc: vec![(bytes_len / itemsize, itemsize as isize, 0)],
}
}
#[cfg(debug_assertions)]
pub fn validate(self) -> Self {
assert!(self.itemsize != 0);
assert!(self.ndim() != 0);
let mut shape_product = 1;
for (shape, stride, suboffset) in self.dim_desc.iter().cloned() {
shape_product *= shape;
assert!(suboffset >= 0);
assert!(stride != 0);
}
assert!(shape_product * self.itemsize == self.len);
self
}
#[cfg(not(debug_assertions))]
pub fn validate(self) -> Self {
self
}
pub fn ndim(&self) -> usize {
self.dim_desc.len()
}
pub fn is_contiguous(&self) -> bool {
if self.len == 0 {
return true;
}
let mut sd = self.itemsize;
for (shape, stride, _) in self.dim_desc.iter().cloned().rev() {
if shape > 1 && stride != sd as isize {
return false;
}
sd *= shape;
}
true
}
/// this function do not check the bound
/// panic if indices.len() != ndim
pub fn fast_position(&self, indices: &[usize]) -> isize {
let mut pos = 0;
for (i, (_, stride, suboffset)) in indices
.iter()
.cloned()
.zip_eq(self.dim_desc.iter().cloned())
{
pos += i as isize * stride + suboffset;
}
pos
}
/// panic if indices.len() != ndim
pub fn position(&self, indices: &[isize], vm: &VirtualMachine) -> PyResult<isize> {
let mut pos = 0;
for (i, (shape, stride, suboffset)) in indices
.iter()
.cloned()
.zip_eq(self.dim_desc.iter().cloned())
{
let i = i.wrapped_at(shape).ok_or_else(|| {
vm.new_index_error(format!("index out of bounds on dimension {i}"))
})?;
pos += i as isize * stride + suboffset;
}
Ok(pos)
}
pub fn for_each_segment<F>(&self, try_conti: bool, mut f: F)
where
F: FnMut(Range<isize>),
{
if self.ndim() == 0 {
f(0..self.itemsize as isize);
return;
}
if try_conti && self.is_last_dim_contiguous() {
self._for_each_segment::<_, true>(0, 0, &mut f);
} else {
self._for_each_segment::<_, false>(0, 0, &mut f);
}
}
fn _for_each_segment<F, const CONTI: bool>(&self, mut index: isize, dim: usize, f: &mut F)
where
F: FnMut(Range<isize>),
{
let (shape, stride, suboffset) = self.dim_desc[dim];
if dim + 1 == self.ndim() {
if CONTI {
f(index..index + (shape * self.itemsize) as isize);
} else {
for _ in 0..shape {
let pos = index + suboffset;
f(pos..pos + self.itemsize as isize);
index += stride;
}
}
return;
}
for _ in 0..shape {
self._for_each_segment::<F, CONTI>(index + suboffset, dim + 1, f);
index += stride;
}
}
/// zip two BufferDescriptor with the same shape
pub fn zip_eq<F>(&self, other: &Self, try_conti: bool, mut f: F)
where
F: FnMut(Range<isize>, Range<isize>) -> bool,
{
if self.ndim() == 0 {
f(0..self.itemsize as isize, 0..other.itemsize as isize);
return;
}
if try_conti && self.is_last_dim_contiguous() {
self._zip_eq::<_, true>(other, 0, 0, 0, &mut f);
} else {
self._zip_eq::<_, false>(other, 0, 0, 0, &mut f);
}
}
fn _zip_eq<F, const CONTI: bool>(
&self,
other: &Self,
mut a_index: isize,
mut b_index: isize,
dim: usize,
f: &mut F,
) where
F: FnMut(Range<isize>, Range<isize>) -> bool,
{
let (shape, a_stride, a_suboffset) = self.dim_desc[dim];
let (_b_shape, b_stride, b_suboffset) = other.dim_desc[dim];
debug_assert_eq!(shape, _b_shape);
if dim + 1 == self.ndim() {
if CONTI {
if f(
a_index..a_index + (shape * self.itemsize) as isize,
b_index..b_index + (shape * other.itemsize) as isize,
) {
return;
}
} else {
for _ in 0..shape {
let a_pos = a_index + a_suboffset;
let b_pos = b_index + b_suboffset;
if f(
a_pos..a_pos + self.itemsize as isize,
b_pos..b_pos + other.itemsize as isize,
) {
return;
}
a_index += a_stride;
b_index += b_stride;
}
}
return;
}
for _ in 0..shape {
self._zip_eq::<F, CONTI>(
other,
a_index + a_suboffset,
b_index + b_suboffset,
dim + 1,
f,
);
a_index += a_stride;
b_index += b_stride;
}
}
fn is_last_dim_contiguous(&self) -> bool {
let (_, stride, suboffset) = self.dim_desc[self.ndim() - 1];
suboffset == 0 && stride == self.itemsize as isize
}
pub fn is_zero_in_shape(&self) -> bool {
for (shape, _, _) in self.dim_desc.iter().cloned() {
if shape == 0 {
return true;
}
}
false
}
// TODO: support fortain order
}
pub trait BufferResizeGuard {
type Resizable<'a>: 'a
where
Self: 'a;
fn try_resizable_opt(&self) -> Option<Self::Resizable<'_>>;
fn try_resizable(&self, vm: &VirtualMachine) -> PyResult<Self::Resizable<'_>> {
self.try_resizable_opt().ok_or_else(|| {
vm.new_buffer_error("Existing exports of data: object cannot be re-sized".to_owned())
})
}
}
#[pyclass(module = false, name = "vec_buffer")]
#[derive(Debug, PyPayload)]
pub struct VecBuffer {
data: PyMutex<Vec<u8>>,
}
#[pyclass(flags(BASETYPE), with(Constructor))]
impl VecBuffer {
pub fn take(&self) -> Vec<u8> {
std::mem::take(&mut self.data.lock())
}
}
impl From<Vec<u8>> for VecBuffer {
fn from(data: Vec<u8>) -> Self {
Self {
data: PyMutex::new(data),
}
}
}
impl Unconstructible for VecBuffer {}
impl PyRef<VecBuffer> {
pub fn into_pybuffer(self, readonly: bool) -> PyBuffer {
let len = self.data.lock().len();
PyBuffer::new(
self.into(),
BufferDescriptor::simple(len, readonly),
&VEC_BUFFER_METHODS,
)
}
pub fn into_pybuffer_with_descriptor(self, desc: BufferDescriptor) -> PyBuffer {
PyBuffer::new(self.into(), desc, &VEC_BUFFER_METHODS)
}
}
static VEC_BUFFER_METHODS: BufferMethods = BufferMethods {
obj_bytes: |buffer| {
PyMutexGuard::map_immutable(buffer.obj_as::<VecBuffer>().data.lock(), |x| x.as_slice())
.into()
},
obj_bytes_mut: |buffer| {
PyMutexGuard::map(buffer.obj_as::<VecBuffer>().data.lock(), |x| {
x.as_mut_slice()
})
.into()
},
release: |_| {},
retain: |_| {},
};
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_base::base::tokio;
use common_exception::Result;
use common_sql::plans::DeletePlan;
use common_sql::plans::Plan;
use common_sql::Planner;
use common_storages_factory::Table;
use common_storages_fuse::FuseTable;
use databend_query::pipelines::executor::ExecutorSettings;
use databend_query::pipelines::executor::PipelineCompleteExecutor;
use databend_query::sessions::QueryContext;
use databend_query::sessions::TableContext;
use crate::storages::fuse::table_test_fixture::execute_command;
use crate::storages::fuse::table_test_fixture::execute_query;
use crate::storages::fuse::table_test_fixture::expects_ok;
use crate::storages::fuse::table_test_fixture::TestFixture;
#[tokio::test(flavor = "multi_thread")]
async fn test_deletion_mutator_multiple_empty_segments() -> Result<()> {
let fixture = TestFixture::new().await;
let ctx = fixture.ctx();
let tbl_name = fixture.default_table_name();
let db_name = fixture.default_db_name();
fixture.create_normal_table().await?;
// insert
for i in 0..10 {
let qry = format!("insert into {}.{}(id) values({})", db_name, tbl_name, i);
execute_command(ctx.clone(), qry.as_str()).await?;
}
let catalog = ctx.get_catalog(fixture.default_catalog_name().as_str())?;
let table = catalog
.get_table(ctx.get_tenant().as_str(), &db_name, &tbl_name)
.await?;
// delete
let query = format!("delete from {}.{} where id=1", db_name, tbl_name);
let mut planner = Planner::new(ctx.clone());
let (plan, _) = planner.plan_sql(&query).await?;
if let Plan::Delete(delete) = plan {
do_deletion(ctx.clone(), table.clone(), *delete).await?;
}
// check count
let expected = vec![
"+----------+----------+",
"| Column 0 | Column 1 |",
"+----------+----------+",
"| 9 | 9 |",
"+----------+----------+",
];
let qry = format!(
"select segment_count, block_count as count from fuse_snapshot('{}', '{}') limit 1",
db_name, tbl_name
);
expects_ok(
"check segment and block count",
execute_query(fixture.ctx(), qry.as_str()).await,
expected,
)
.await?;
Ok(())
}
pub async fn do_deletion(
ctx: Arc<QueryContext>,
table: Arc<dyn Table>,
plan: DeletePlan,
) -> Result<()> {
let (filter, col_indices) = if let Some(scalar) = &plan.selection {
(
Some(scalar.as_expr_with_col_name()?.as_remote_expr()),
scalar.used_columns().into_iter().collect(),
)
} else {
(None, vec![])
};
let fuse_table = FuseTable::try_from_table(table.as_ref())?;
let settings = ctx.get_settings();
let mut pipeline = common_pipeline_core::Pipeline::create();
fuse_table
.delete(ctx.clone(), filter, col_indices, &mut pipeline)
.await?;
if !pipeline.is_empty() {
pipeline.set_max_threads(settings.get_max_threads()? as usize);
let query_id = ctx.get_id();
let executor_settings = ExecutorSettings::try_create(&settings, query_id)?;
let executor = PipelineCompleteExecutor::try_create(pipeline, executor_settings)?;
ctx.set_executor(Arc::downgrade(&executor.get_inner()));
executor.execute()?;
drop(executor);
}
Ok(())
}
|
// ---------------------------------------------------------------------------------------------------------
// address trait
//
// 1、不同加密解决方案在生成地址的时候,需要实现以下方法
// 2、该 trait 是对外的 public 接口
//
// ---------------------------------------------------------------------------------------------------------
pub trait AddressI {
/*
需要 seed
【计算过程】
透明调用 generater 的 human_readable_public_key 方法
【输出】
对应 wallet 结构中的 `account_id` 字段
*/
fn human_account_id(&self) -> String;
/*
需要 seed
【计算过程】
1、透明调用 generater 的 generate_public_key 方法
2、checksum(35 + public_key)
3、base58(0 + public_key + checksum)
【输出】
对应 wallet 结构中的 `public_key` 字段
*/
fn public_key(&self) -> String;
/*
需要 public_key
【计算过程】
1、透明调用 generater 的 generate_public_key 方法
2、大写的十六进制编码
【输出】
对应 wallet 结构中的 `public_key_hex` 字段
*/
fn public_key_hex(&self) -> String;
/*
需要 seed
【计算过程】
1、透明调用 generater 的 generate_private_key 方法
2、大写的十六进制编码
【输出】
导出 私钥
*/
fn private_key(&self) -> String;
}
// ---------------------------------------------------------------------------------------------------------
// address 的有效性检查
// ---------------------------------------------------------------------------------------------------------
pub trait AddressCheckI {
/*
需要地址
Wallet数据结构中的account_id字段。
*/
fn check(&self, address: &String) -> bool;
} |
use crate::{FunctionData, Value, Map, Set, CapacityExt};
#[derive(Default)]
struct Values {
next_value: Value,
map: Map<Value, Value>,
}
impl Values {
fn allocate(&mut self, previous: Value) -> Value {
let value = self.next_value;
self.next_value = Value(value.0.checked_add(1)
.expect("Value IDs overflowed."));
self.map.insert(previous, value);
value
}
}
pub struct RewriteValuesPass;
impl super::Pass for RewriteValuesPass {
fn name(&self) -> &str {
"rewrite values"
}
fn time(&self) -> crate::timing::TimedBlock {
crate::timing::rewrite_values()
}
fn run_on_function(&self, function: &mut FunctionData) -> bool {
// This is not an optimization pass. We need to be careful here because `validate_ssa`
// won't be called after this pass is run.
let mut values = Values::default();
// Use DFS traversal to match value order in `dump` routines.
let labels = function.reachable_labels_dfs();
// Allocate new values for function arguments.
for &argument in &function.argument_values {
let value = values.allocate(argument);
// Old value and new value must be the same.
assert_eq!(value, argument, "Argument value allocations don't match.");
}
// Allocate new values for all created IR values.
function.for_each_instruction_with_labels_mut(&labels, |_location, instruction| {
if let Some(value) = instruction.created_value() {
values.allocate(value);
}
});
// Allocate new values for undefined values.
for &undefined in &function.undefined_set {
values.allocate(undefined);
}
// Allocate new values for constant values.
for &constant in function.constants.keys() {
values.allocate(constant);
}
// We have now allocated and assigned all required values.
let values = values;
// Update inputs and outputs for every instruction.
function.for_each_instruction_with_labels_mut(&labels, |_location, instruction| {
let transform = |value: &mut Value| {
*value = values.map[value];
};
instruction.transform_output(transform);
instruction.transform_inputs(transform);
});
// Argument values are the same so we don't need to update them.
// Update undefined values.
{
let mut undefined_set = Set::new_with_capacity(function.undefined.len());
for value in function.undefined.values_mut() {
let new_value = values.map[&value];
*value = new_value;
assert!(undefined_set.insert(new_value), "Multiple entries \
in undefined set for the same value.");
}
function.undefined_set = undefined_set;
}
// Update constant values.
{
let mut constants = Map::new_with_capacity(function.constants.len());
for (&(ty, constant), value) in &mut function.constant_to_value {
let new_value = values.map[value];
*value = new_value;
assert!(constants.insert(new_value, (ty, constant)).is_none(), "Multiple entries \
in constants map for the same value.");
}
function.constants = constants;
}
// Update next value index.
function.next_value = values.next_value;
// Update function type information.
function.type_info = function.type_info.take().map(|old_type_info| {
let mut type_info = Map::new_with_capacity(old_type_info.len());
for (value, ty) in old_type_info {
// Previous type information can include types of now non-existent values.
if let Some(&value) = values.map.get(&value) {
assert!(type_info.insert(value, ty).is_none(), "Multiple entries \
in type info for the same value.");
}
}
type_info
});
// `phi_locations` should be empty and shouldn't require update.
assert!(function.phi_locations.is_empty(), "PHI locations map \
wasn't empty during rewrite.");
// This pass doesn't optimize anything.
false
}
}
|
fn main() {
println!("🔓 Challenge 2");
println!("Try running: `cargo test fixed_xor`");
println!("Code in 'xor/src/lib.rs'");
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "ApplicationModel_Search_Core")]
pub mod Core;
#[repr(transparent)]
#[doc(hidden)]
pub struct ILocalContentSuggestionSettings(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILocalContentSuggestionSettings {
type Vtable = ILocalContentSuggestionSettings_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeeaeb062_743d_456e_84a3_23f06f2d15d7);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILocalContentSuggestionSettings_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation_Collections", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Storage")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPane(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPane {
type Vtable = ISearchPane_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfdacec38_3700_4d73_91a1_2f998674238a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPane_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: 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, value: ::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, value: ::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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, settings: ::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, query: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: 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, query: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISearchPaneQueryChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneQueryChangedEventArgs {
type Vtable = ISearchPaneQueryChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c064fe9_2351_4248_a529_7110f464a785);
}
impl ISearchPaneQueryChangedEventArgs {
#[cfg(feature = "deprecated")]
pub fn QueryText(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn Language(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn LinguisticDetails(&self) -> ::windows::core::Result<SearchPaneQueryLinguisticDetails> {
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::<SearchPaneQueryLinguisticDetails>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ISearchPaneQueryChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{3c064fe9-2351-4248-a529-7110f464a785}");
}
impl ::core::convert::From<ISearchPaneQueryChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: ISearchPaneQueryChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISearchPaneQueryChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &ISearchPaneQueryChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISearchPaneQueryChangedEventArgs {
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 ISearchPaneQueryChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISearchPaneQueryChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: ISearchPaneQueryChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&ISearchPaneQueryChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &ISearchPaneQueryChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISearchPaneQueryChangedEventArgs {
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 ISearchPaneQueryChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneQueryChangedEventArgs_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 ::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)]
#[doc(hidden)]
pub struct ISearchPaneQueryLinguisticDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneQueryLinguisticDetails {
type Vtable = ISearchPaneQueryLinguisticDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82fb460e_0940_4b6d_b8d0_642b30989e15);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneQueryLinguisticDetails_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneQuerySubmittedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneQuerySubmittedEventArgs {
type Vtable = ISearchPaneQuerySubmittedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x143ba4fc_e9c5_4736_91b2_e8eb9cb88356);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneQuerySubmittedEventArgs_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails {
type Vtable = ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x460c92e5_4c32_4538_a4d4_b6b4400d140f);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneResultSuggestionChosenEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneResultSuggestionChosenEventArgs {
type Vtable = ISearchPaneResultSuggestionChosenEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc8316cc0_aed2_41e0_bce0_c26ca74f85ec);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneResultSuggestionChosenEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneStatics {
type Vtable = ISearchPaneStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9572adf1_8f1d_481f_a15b_c61655f16a0e);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneStaticsWithHideThisApplication(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneStaticsWithHideThisApplication {
type Vtable = ISearchPaneStaticsWithHideThisApplication_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00732830_50f1_4d03_99ac_c6644c8ed8b5);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneStaticsWithHideThisApplication_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)]
#[doc(hidden)]
pub struct ISearchPaneSuggestionsRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneSuggestionsRequest {
type Vtable = ISearchPaneSuggestionsRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x81b10b1c_e561_4093_9b4d_2ad482794a53);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneSuggestionsRequest_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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneSuggestionsRequestDeferral(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneSuggestionsRequestDeferral {
type Vtable = ISearchPaneSuggestionsRequestDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa0d009f7_8748_4ee2_ad44_afa6be997c51);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneSuggestionsRequestDeferral_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)]
#[doc(hidden)]
pub struct ISearchPaneSuggestionsRequestedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneSuggestionsRequestedEventArgs {
type Vtable = ISearchPaneSuggestionsRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc89b8a2f_ac56_4460_8d2f_80023bec4fc5);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneSuggestionsRequestedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchPaneVisibilityChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchPaneVisibilityChangedEventArgs {
type Vtable = ISearchPaneVisibilityChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c4d3046_ac4b_49f2_97d6_020e6182cb9c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchPaneVisibilityChangedEventArgs_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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchQueryLinguisticDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchQueryLinguisticDetails {
type Vtable = ISearchQueryLinguisticDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46a1205b_69c9_4745_b72f_a8a4fc8f24ae);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchQueryLinguisticDetails_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchQueryLinguisticDetailsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchQueryLinguisticDetailsFactory {
type Vtable = ISearchQueryLinguisticDetailsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcac6c3b8_3c64_4dfd_ad9f_479e4d4065a4);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchQueryLinguisticDetailsFactory_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, querytextalternatives: ::windows::core::RawPtr, querytextcompositionstart: u32, querytextcompositionlength: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchSuggestionCollection(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchSuggestionCollection {
type Vtable = ISearchSuggestionCollection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x323a8a4b_fbea_4446_abbc_3da7915fdd3a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchSuggestionCollection_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 u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, text: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, suggestions: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, text: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, detailtext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, tag: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, image: ::windows::core::RawPtr, imagealternatetext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, label: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchSuggestionsRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchSuggestionsRequest {
type Vtable = ISearchSuggestionsRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e4e26a7_44e5_4039_9099_6000ead1f0c6);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchSuggestionsRequest_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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISearchSuggestionsRequestDeferral(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISearchSuggestionsRequestDeferral {
type Vtable = ISearchSuggestionsRequestDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb71598a9_c065_456d_a845_1eccec5dc28b);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISearchSuggestionsRequestDeferral_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 LocalContentSuggestionSettings(pub ::windows::core::IInspectable);
impl LocalContentSuggestionSettings {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<LocalContentSuggestionSettings, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn SetEnabled(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Enabled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation_Collections", feature = "Storage"))]
pub fn Locations(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<super::super::Storage::StorageFolder>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<super::super::Storage::StorageFolder>>(result__)
}
}
pub fn SetAqsFilter<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn AqsFilter(&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__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn PropertiesToMatch(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for LocalContentSuggestionSettings {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.LocalContentSuggestionSettings;{eeaeb062-743d-456e-84a3-23f06f2d15d7})");
}
unsafe impl ::windows::core::Interface for LocalContentSuggestionSettings {
type Vtable = ILocalContentSuggestionSettings_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeeaeb062_743d_456e_84a3_23f06f2d15d7);
}
impl ::windows::core::RuntimeName for LocalContentSuggestionSettings {
const NAME: &'static str = "Windows.ApplicationModel.Search.LocalContentSuggestionSettings";
}
impl ::core::convert::From<LocalContentSuggestionSettings> for ::windows::core::IUnknown {
fn from(value: LocalContentSuggestionSettings) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&LocalContentSuggestionSettings> for ::windows::core::IUnknown {
fn from(value: &LocalContentSuggestionSettings) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for LocalContentSuggestionSettings {
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 LocalContentSuggestionSettings {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<LocalContentSuggestionSettings> for ::windows::core::IInspectable {
fn from(value: LocalContentSuggestionSettings) -> Self {
value.0
}
}
impl ::core::convert::From<&LocalContentSuggestionSettings> for ::windows::core::IInspectable {
fn from(value: &LocalContentSuggestionSettings) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for LocalContentSuggestionSettings {
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 LocalContentSuggestionSettings {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPane(pub ::windows::core::IInspectable);
impl SearchPane {
#[cfg(feature = "deprecated")]
pub fn SetSearchHistoryEnabled(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn SearchHistoryEnabled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetSearchHistoryContext<'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() }
}
#[cfg(feature = "deprecated")]
pub fn SearchHistoryContext(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetPlaceholderText<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn PlaceholderText(&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).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn QueryText(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn Language(&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).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Visible(&self) -> ::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), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn VisibilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SearchPane, SearchPaneVisibilityChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveVisibilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn QueryChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SearchPane, SearchPaneQueryChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveQueryChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SuggestionsRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSuggestionsRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn QuerySubmitted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveQuerySubmitted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn ResultSuggestionChosen<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SearchPane, SearchPaneResultSuggestionChosenEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveResultSuggestionChosen<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn SetLocalContentSuggestionSettings<'a, Param0: ::windows::core::IntoParam<'a, LocalContentSuggestionSettings>>(&self, settings: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), settings.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn ShowOverloadDefault(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn ShowOverloadWithQuery<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, query: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), query.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn SetShowOnKeyboardInput(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn ShowOnKeyboardInput(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn TrySetQueryText<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, query: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), query.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn GetForCurrentView() -> ::windows::core::Result<SearchPane> {
Self::ISearchPaneStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SearchPane>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn HideThisApplication() -> ::windows::core::Result<()> {
Self::ISearchPaneStaticsWithHideThisApplication(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() })
}
pub fn ISearchPaneStatics<R, F: FnOnce(&ISearchPaneStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SearchPane, ISearchPaneStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ISearchPaneStaticsWithHideThisApplication<R, F: FnOnce(&ISearchPaneStaticsWithHideThisApplication) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SearchPane, ISearchPaneStaticsWithHideThisApplication> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SearchPane {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPane;{fdacec38-3700-4d73-91a1-2f998674238a})");
}
unsafe impl ::windows::core::Interface for SearchPane {
type Vtable = ISearchPane_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfdacec38_3700_4d73_91a1_2f998674238a);
}
impl ::windows::core::RuntimeName for SearchPane {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPane";
}
impl ::core::convert::From<SearchPane> for ::windows::core::IUnknown {
fn from(value: SearchPane) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPane> for ::windows::core::IUnknown {
fn from(value: &SearchPane) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPane {
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 SearchPane {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPane> for ::windows::core::IInspectable {
fn from(value: SearchPane) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPane> for ::windows::core::IInspectable {
fn from(value: &SearchPane) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPane {
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 SearchPane {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneQueryChangedEventArgs(pub ::windows::core::IInspectable);
impl SearchPaneQueryChangedEventArgs {
#[cfg(feature = "deprecated")]
pub fn QueryText(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn Language(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn LinguisticDetails(&self) -> ::windows::core::Result<SearchPaneQueryLinguisticDetails> {
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::<SearchPaneQueryLinguisticDetails>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneQueryChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneQueryChangedEventArgs;{3c064fe9-2351-4248-a529-7110f464a785})");
}
unsafe impl ::windows::core::Interface for SearchPaneQueryChangedEventArgs {
type Vtable = ISearchPaneQueryChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c064fe9_2351_4248_a529_7110f464a785);
}
impl ::windows::core::RuntimeName for SearchPaneQueryChangedEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneQueryChangedEventArgs";
}
impl ::core::convert::From<SearchPaneQueryChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: SearchPaneQueryChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneQueryChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SearchPaneQueryChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneQueryChangedEventArgs {
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 SearchPaneQueryChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneQueryChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: SearchPaneQueryChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneQueryChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SearchPaneQueryChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneQueryChangedEventArgs {
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 SearchPaneQueryChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<SearchPaneQueryChangedEventArgs> for ISearchPaneQueryChangedEventArgs {
fn from(value: SearchPaneQueryChangedEventArgs) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&SearchPaneQueryChangedEventArgs> for ISearchPaneQueryChangedEventArgs {
fn from(value: &SearchPaneQueryChangedEventArgs) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, ISearchPaneQueryChangedEventArgs> for SearchPaneQueryChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ISearchPaneQueryChangedEventArgs> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, ISearchPaneQueryChangedEventArgs> for &SearchPaneQueryChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ISearchPaneQueryChangedEventArgs> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
unsafe impl ::core::marker::Send for SearchPaneQueryChangedEventArgs {}
unsafe impl ::core::marker::Sync for SearchPaneQueryChangedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneQueryLinguisticDetails(pub ::windows::core::IInspectable);
impl SearchPaneQueryLinguisticDetails {
#[cfg(feature = "Foundation_Collections")]
pub fn QueryTextAlternatives(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
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::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
pub fn QueryTextCompositionStart(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn QueryTextCompositionLength(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneQueryLinguisticDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneQueryLinguisticDetails;{82fb460e-0940-4b6d-b8d0-642b30989e15})");
}
unsafe impl ::windows::core::Interface for SearchPaneQueryLinguisticDetails {
type Vtable = ISearchPaneQueryLinguisticDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82fb460e_0940_4b6d_b8d0_642b30989e15);
}
impl ::windows::core::RuntimeName for SearchPaneQueryLinguisticDetails {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneQueryLinguisticDetails";
}
impl ::core::convert::From<SearchPaneQueryLinguisticDetails> for ::windows::core::IUnknown {
fn from(value: SearchPaneQueryLinguisticDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneQueryLinguisticDetails> for ::windows::core::IUnknown {
fn from(value: &SearchPaneQueryLinguisticDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneQueryLinguisticDetails {
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 SearchPaneQueryLinguisticDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneQueryLinguisticDetails> for ::windows::core::IInspectable {
fn from(value: SearchPaneQueryLinguisticDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneQueryLinguisticDetails> for ::windows::core::IInspectable {
fn from(value: &SearchPaneQueryLinguisticDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneQueryLinguisticDetails {
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 SearchPaneQueryLinguisticDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchPaneQueryLinguisticDetails {}
unsafe impl ::core::marker::Sync for SearchPaneQueryLinguisticDetails {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneQuerySubmittedEventArgs(pub ::windows::core::IInspectable);
impl SearchPaneQuerySubmittedEventArgs {
#[cfg(feature = "deprecated")]
pub fn QueryText(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn Language(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn LinguisticDetails(&self) -> ::windows::core::Result<SearchPaneQueryLinguisticDetails> {
let this = &::windows::core::Interface::cast::<ISearchPaneQuerySubmittedEventArgsWithLinguisticDetails>(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::<SearchPaneQueryLinguisticDetails>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneQuerySubmittedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneQuerySubmittedEventArgs;{143ba4fc-e9c5-4736-91b2-e8eb9cb88356})");
}
unsafe impl ::windows::core::Interface for SearchPaneQuerySubmittedEventArgs {
type Vtable = ISearchPaneQuerySubmittedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x143ba4fc_e9c5_4736_91b2_e8eb9cb88356);
}
impl ::windows::core::RuntimeName for SearchPaneQuerySubmittedEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneQuerySubmittedEventArgs";
}
impl ::core::convert::From<SearchPaneQuerySubmittedEventArgs> for ::windows::core::IUnknown {
fn from(value: SearchPaneQuerySubmittedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneQuerySubmittedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SearchPaneQuerySubmittedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneQuerySubmittedEventArgs {
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 SearchPaneQuerySubmittedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneQuerySubmittedEventArgs> for ::windows::core::IInspectable {
fn from(value: SearchPaneQuerySubmittedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneQuerySubmittedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SearchPaneQuerySubmittedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneQuerySubmittedEventArgs {
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 SearchPaneQuerySubmittedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchPaneQuerySubmittedEventArgs {}
unsafe impl ::core::marker::Sync for SearchPaneQuerySubmittedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneResultSuggestionChosenEventArgs(pub ::windows::core::IInspectable);
impl SearchPaneResultSuggestionChosenEventArgs {
#[cfg(feature = "deprecated")]
pub fn Tag(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneResultSuggestionChosenEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneResultSuggestionChosenEventArgs;{c8316cc0-aed2-41e0-bce0-c26ca74f85ec})");
}
unsafe impl ::windows::core::Interface for SearchPaneResultSuggestionChosenEventArgs {
type Vtable = ISearchPaneResultSuggestionChosenEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc8316cc0_aed2_41e0_bce0_c26ca74f85ec);
}
impl ::windows::core::RuntimeName for SearchPaneResultSuggestionChosenEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneResultSuggestionChosenEventArgs";
}
impl ::core::convert::From<SearchPaneResultSuggestionChosenEventArgs> for ::windows::core::IUnknown {
fn from(value: SearchPaneResultSuggestionChosenEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneResultSuggestionChosenEventArgs> for ::windows::core::IUnknown {
fn from(value: &SearchPaneResultSuggestionChosenEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneResultSuggestionChosenEventArgs {
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 SearchPaneResultSuggestionChosenEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneResultSuggestionChosenEventArgs> for ::windows::core::IInspectable {
fn from(value: SearchPaneResultSuggestionChosenEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneResultSuggestionChosenEventArgs> for ::windows::core::IInspectable {
fn from(value: &SearchPaneResultSuggestionChosenEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneResultSuggestionChosenEventArgs {
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 SearchPaneResultSuggestionChosenEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchPaneResultSuggestionChosenEventArgs {}
unsafe impl ::core::marker::Sync for SearchPaneResultSuggestionChosenEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneSuggestionsRequest(pub ::windows::core::IInspectable);
impl SearchPaneSuggestionsRequest {
#[cfg(feature = "deprecated")]
pub fn IsCanceled(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn SearchSuggestionCollection(&self) -> ::windows::core::Result<SearchSuggestionCollection> {
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::<SearchSuggestionCollection>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn GetDeferral(&self) -> ::windows::core::Result<SearchPaneSuggestionsRequestDeferral> {
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::<SearchPaneSuggestionsRequestDeferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneSuggestionsRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneSuggestionsRequest;{81b10b1c-e561-4093-9b4d-2ad482794a53})");
}
unsafe impl ::windows::core::Interface for SearchPaneSuggestionsRequest {
type Vtable = ISearchPaneSuggestionsRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x81b10b1c_e561_4093_9b4d_2ad482794a53);
}
impl ::windows::core::RuntimeName for SearchPaneSuggestionsRequest {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneSuggestionsRequest";
}
impl ::core::convert::From<SearchPaneSuggestionsRequest> for ::windows::core::IUnknown {
fn from(value: SearchPaneSuggestionsRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneSuggestionsRequest> for ::windows::core::IUnknown {
fn from(value: &SearchPaneSuggestionsRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneSuggestionsRequest {
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 SearchPaneSuggestionsRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneSuggestionsRequest> for ::windows::core::IInspectable {
fn from(value: SearchPaneSuggestionsRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneSuggestionsRequest> for ::windows::core::IInspectable {
fn from(value: &SearchPaneSuggestionsRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneSuggestionsRequest {
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 SearchPaneSuggestionsRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchPaneSuggestionsRequest {}
unsafe impl ::core::marker::Sync for SearchPaneSuggestionsRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneSuggestionsRequestDeferral(pub ::windows::core::IInspectable);
impl SearchPaneSuggestionsRequestDeferral {
#[cfg(feature = "deprecated")]
pub fn Complete(&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 SearchPaneSuggestionsRequestDeferral {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestDeferral;{a0d009f7-8748-4ee2-ad44-afa6be997c51})");
}
unsafe impl ::windows::core::Interface for SearchPaneSuggestionsRequestDeferral {
type Vtable = ISearchPaneSuggestionsRequestDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa0d009f7_8748_4ee2_ad44_afa6be997c51);
}
impl ::windows::core::RuntimeName for SearchPaneSuggestionsRequestDeferral {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestDeferral";
}
impl ::core::convert::From<SearchPaneSuggestionsRequestDeferral> for ::windows::core::IUnknown {
fn from(value: SearchPaneSuggestionsRequestDeferral) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneSuggestionsRequestDeferral> for ::windows::core::IUnknown {
fn from(value: &SearchPaneSuggestionsRequestDeferral) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneSuggestionsRequestDeferral {
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 SearchPaneSuggestionsRequestDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneSuggestionsRequestDeferral> for ::windows::core::IInspectable {
fn from(value: SearchPaneSuggestionsRequestDeferral) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneSuggestionsRequestDeferral> for ::windows::core::IInspectable {
fn from(value: &SearchPaneSuggestionsRequestDeferral) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneSuggestionsRequestDeferral {
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 SearchPaneSuggestionsRequestDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchPaneSuggestionsRequestDeferral {}
unsafe impl ::core::marker::Sync for SearchPaneSuggestionsRequestDeferral {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneSuggestionsRequestedEventArgs(pub ::windows::core::IInspectable);
impl SearchPaneSuggestionsRequestedEventArgs {
#[cfg(feature = "deprecated")]
pub fn Request(&self) -> ::windows::core::Result<SearchPaneSuggestionsRequest> {
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::<SearchPaneSuggestionsRequest>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn QueryText(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ISearchPaneQueryChangedEventArgs>(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__)
}
}
#[cfg(feature = "deprecated")]
pub fn Language(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ISearchPaneQueryChangedEventArgs>(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__)
}
}
#[cfg(feature = "deprecated")]
pub fn LinguisticDetails(&self) -> ::windows::core::Result<SearchPaneQueryLinguisticDetails> {
let this = &::windows::core::Interface::cast::<ISearchPaneQueryChangedEventArgs>(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::<SearchPaneQueryLinguisticDetails>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneSuggestionsRequestedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs;{c89b8a2f-ac56-4460-8d2f-80023bec4fc5})");
}
unsafe impl ::windows::core::Interface for SearchPaneSuggestionsRequestedEventArgs {
type Vtable = ISearchPaneSuggestionsRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc89b8a2f_ac56_4460_8d2f_80023bec4fc5);
}
impl ::windows::core::RuntimeName for SearchPaneSuggestionsRequestedEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs";
}
impl ::core::convert::From<SearchPaneSuggestionsRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: SearchPaneSuggestionsRequestedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneSuggestionsRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SearchPaneSuggestionsRequestedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneSuggestionsRequestedEventArgs {
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 SearchPaneSuggestionsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneSuggestionsRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: SearchPaneSuggestionsRequestedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneSuggestionsRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SearchPaneSuggestionsRequestedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneSuggestionsRequestedEventArgs {
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 SearchPaneSuggestionsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<SearchPaneSuggestionsRequestedEventArgs> for ISearchPaneQueryChangedEventArgs {
type Error = ::windows::core::Error;
fn try_from(value: SearchPaneSuggestionsRequestedEventArgs) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&SearchPaneSuggestionsRequestedEventArgs> for ISearchPaneQueryChangedEventArgs {
type Error = ::windows::core::Error;
fn try_from(value: &SearchPaneSuggestionsRequestedEventArgs) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISearchPaneQueryChangedEventArgs> for SearchPaneSuggestionsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ISearchPaneQueryChangedEventArgs> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISearchPaneQueryChangedEventArgs> for &SearchPaneSuggestionsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ISearchPaneQueryChangedEventArgs> {
::core::convert::TryInto::<ISearchPaneQueryChangedEventArgs>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for SearchPaneSuggestionsRequestedEventArgs {}
unsafe impl ::core::marker::Sync for SearchPaneSuggestionsRequestedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchPaneVisibilityChangedEventArgs(pub ::windows::core::IInspectable);
impl SearchPaneVisibilityChangedEventArgs {
#[cfg(feature = "deprecated")]
pub fn Visible(&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__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchPaneVisibilityChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchPaneVisibilityChangedEventArgs;{3c4d3046-ac4b-49f2-97d6-020e6182cb9c})");
}
unsafe impl ::windows::core::Interface for SearchPaneVisibilityChangedEventArgs {
type Vtable = ISearchPaneVisibilityChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c4d3046_ac4b_49f2_97d6_020e6182cb9c);
}
impl ::windows::core::RuntimeName for SearchPaneVisibilityChangedEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchPaneVisibilityChangedEventArgs";
}
impl ::core::convert::From<SearchPaneVisibilityChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: SearchPaneVisibilityChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchPaneVisibilityChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SearchPaneVisibilityChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchPaneVisibilityChangedEventArgs {
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 SearchPaneVisibilityChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchPaneVisibilityChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: SearchPaneVisibilityChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchPaneVisibilityChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SearchPaneVisibilityChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchPaneVisibilityChangedEventArgs {
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 SearchPaneVisibilityChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchPaneVisibilityChangedEventArgs {}
unsafe impl ::core::marker::Sync for SearchPaneVisibilityChangedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchQueryLinguisticDetails(pub ::windows::core::IInspectable);
impl SearchQueryLinguisticDetails {
#[cfg(feature = "Foundation_Collections")]
pub fn QueryTextAlternatives(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
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::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
pub fn QueryTextCompositionStart(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn QueryTextCompositionLength(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(querytextalternatives: Param0, querytextcompositionstart: u32, querytextcompositionlength: u32) -> ::windows::core::Result<SearchQueryLinguisticDetails> {
Self::ISearchQueryLinguisticDetailsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), querytextalternatives.into_param().abi(), querytextcompositionstart, querytextcompositionlength, &mut result__).from_abi::<SearchQueryLinguisticDetails>(result__)
})
}
pub fn ISearchQueryLinguisticDetailsFactory<R, F: FnOnce(&ISearchQueryLinguisticDetailsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SearchQueryLinguisticDetails, ISearchQueryLinguisticDetailsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SearchQueryLinguisticDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchQueryLinguisticDetails;{46a1205b-69c9-4745-b72f-a8a4fc8f24ae})");
}
unsafe impl ::windows::core::Interface for SearchQueryLinguisticDetails {
type Vtable = ISearchQueryLinguisticDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46a1205b_69c9_4745_b72f_a8a4fc8f24ae);
}
impl ::windows::core::RuntimeName for SearchQueryLinguisticDetails {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchQueryLinguisticDetails";
}
impl ::core::convert::From<SearchQueryLinguisticDetails> for ::windows::core::IUnknown {
fn from(value: SearchQueryLinguisticDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchQueryLinguisticDetails> for ::windows::core::IUnknown {
fn from(value: &SearchQueryLinguisticDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchQueryLinguisticDetails {
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 SearchQueryLinguisticDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchQueryLinguisticDetails> for ::windows::core::IInspectable {
fn from(value: SearchQueryLinguisticDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchQueryLinguisticDetails> for ::windows::core::IInspectable {
fn from(value: &SearchQueryLinguisticDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchQueryLinguisticDetails {
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 SearchQueryLinguisticDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchQueryLinguisticDetails {}
unsafe impl ::core::marker::Sync for SearchQueryLinguisticDetails {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchSuggestionCollection(pub ::windows::core::IInspectable);
impl SearchSuggestionCollection {
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn AppendQuerySuggestion<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), text.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn AppendQuerySuggestions<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(&self, suggestions: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), suggestions.into_param().abi()).ok() }
}
#[cfg(feature = "Storage_Streams")]
pub fn AppendResultSuggestion<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStreamReference>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(
&self,
text: Param0,
detailtext: Param1,
tag: Param2,
image: Param3,
imagealternatetext: Param4,
) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), text.into_param().abi(), detailtext.into_param().abi(), tag.into_param().abi(), image.into_param().abi(), imagealternatetext.into_param().abi()).ok() }
}
pub fn AppendSearchSeparator<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, label: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), label.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for SearchSuggestionCollection {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchSuggestionCollection;{323a8a4b-fbea-4446-abbc-3da7915fdd3a})");
}
unsafe impl ::windows::core::Interface for SearchSuggestionCollection {
type Vtable = ISearchSuggestionCollection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x323a8a4b_fbea_4446_abbc_3da7915fdd3a);
}
impl ::windows::core::RuntimeName for SearchSuggestionCollection {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchSuggestionCollection";
}
impl ::core::convert::From<SearchSuggestionCollection> for ::windows::core::IUnknown {
fn from(value: SearchSuggestionCollection) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchSuggestionCollection> for ::windows::core::IUnknown {
fn from(value: &SearchSuggestionCollection) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchSuggestionCollection {
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 SearchSuggestionCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchSuggestionCollection> for ::windows::core::IInspectable {
fn from(value: SearchSuggestionCollection) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchSuggestionCollection> for ::windows::core::IInspectable {
fn from(value: &SearchSuggestionCollection) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchSuggestionCollection {
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 SearchSuggestionCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchSuggestionCollection {}
unsafe impl ::core::marker::Sync for SearchSuggestionCollection {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchSuggestionsRequest(pub ::windows::core::IInspectable);
impl SearchSuggestionsRequest {
pub fn IsCanceled(&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 SearchSuggestionCollection(&self) -> ::windows::core::Result<SearchSuggestionCollection> {
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::<SearchSuggestionCollection>(result__)
}
}
pub fn GetDeferral(&self) -> ::windows::core::Result<SearchSuggestionsRequestDeferral> {
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::<SearchSuggestionsRequestDeferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SearchSuggestionsRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchSuggestionsRequest;{4e4e26a7-44e5-4039-9099-6000ead1f0c6})");
}
unsafe impl ::windows::core::Interface for SearchSuggestionsRequest {
type Vtable = ISearchSuggestionsRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e4e26a7_44e5_4039_9099_6000ead1f0c6);
}
impl ::windows::core::RuntimeName for SearchSuggestionsRequest {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchSuggestionsRequest";
}
impl ::core::convert::From<SearchSuggestionsRequest> for ::windows::core::IUnknown {
fn from(value: SearchSuggestionsRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchSuggestionsRequest> for ::windows::core::IUnknown {
fn from(value: &SearchSuggestionsRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchSuggestionsRequest {
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 SearchSuggestionsRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchSuggestionsRequest> for ::windows::core::IInspectable {
fn from(value: SearchSuggestionsRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchSuggestionsRequest> for ::windows::core::IInspectable {
fn from(value: &SearchSuggestionsRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchSuggestionsRequest {
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 SearchSuggestionsRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchSuggestionsRequest {}
unsafe impl ::core::marker::Sync for SearchSuggestionsRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SearchSuggestionsRequestDeferral(pub ::windows::core::IInspectable);
impl SearchSuggestionsRequestDeferral {
pub fn Complete(&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 SearchSuggestionsRequestDeferral {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Search.SearchSuggestionsRequestDeferral;{b71598a9-c065-456d-a845-1eccec5dc28b})");
}
unsafe impl ::windows::core::Interface for SearchSuggestionsRequestDeferral {
type Vtable = ISearchSuggestionsRequestDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb71598a9_c065_456d_a845_1eccec5dc28b);
}
impl ::windows::core::RuntimeName for SearchSuggestionsRequestDeferral {
const NAME: &'static str = "Windows.ApplicationModel.Search.SearchSuggestionsRequestDeferral";
}
impl ::core::convert::From<SearchSuggestionsRequestDeferral> for ::windows::core::IUnknown {
fn from(value: SearchSuggestionsRequestDeferral) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SearchSuggestionsRequestDeferral> for ::windows::core::IUnknown {
fn from(value: &SearchSuggestionsRequestDeferral) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SearchSuggestionsRequestDeferral {
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 SearchSuggestionsRequestDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SearchSuggestionsRequestDeferral> for ::windows::core::IInspectable {
fn from(value: SearchSuggestionsRequestDeferral) -> Self {
value.0
}
}
impl ::core::convert::From<&SearchSuggestionsRequestDeferral> for ::windows::core::IInspectable {
fn from(value: &SearchSuggestionsRequestDeferral) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SearchSuggestionsRequestDeferral {
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 SearchSuggestionsRequestDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SearchSuggestionsRequestDeferral {}
unsafe impl ::core::marker::Sync for SearchSuggestionsRequestDeferral {}
|
//
// Copyright 2018 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use std::cell::RefCell;
use std::io::{Read, Write};
type Handle = u64;
// Keep in sync with /oak/server/oak_node.h.
pub const LOGGING_CHANNEL_HANDLE: Handle = 1;
pub const GRPC_CHANNEL_HANDLE: Handle = 2;
pub const GRPC_METHOD_NAME_CHANNEL_HANDLE: Handle = 3;
// TODO: Implement panic handler.
mod wasm {
// See https://rustwasm.github.io/book/reference/js-ffi.html
#[link(wasm_import_module = "oak")]
extern "C" {
pub fn channel_read(handle: u64, buf: *mut u8, size: usize) -> usize;
pub fn channel_write(handle: u64, buf: *const u8, size: usize) -> usize;
}
}
pub struct Channel {
handle: Handle,
}
impl Channel {
pub fn new(handle: Handle) -> Channel {
Channel { handle }
}
}
pub fn logging_channel() -> impl Write {
let logging_channel = Channel::new(LOGGING_CHANNEL_HANDLE);
// Only flush logging channel on newlines.
std::io::LineWriter::new(logging_channel)
}
impl Read for Channel {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
Ok(unsafe { wasm::channel_read(self.handle, buf.as_mut_ptr(), buf.len()) })
}
}
impl Write for Channel {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
Ok(unsafe { wasm::channel_write(self.handle, buf.as_ptr(), buf.len()) })
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Trait encapsulating the operations required for an Oak Node.
pub trait Node {
fn new() -> Self
where
Self: Sized;
fn invoke(&mut self, grpc_method_name: &str, grpc_channel: &mut Channel);
}
thread_local! {
static NODE: RefCell<Option<Box<dyn Node>>> = RefCell::new(None);
}
/// Sets the Oak Node to execute in the current instance.
///
/// This function may only be called once, and only from an exported `oak_initialize` function:
///
/// ```rust
/// struct Node;
///
/// impl oak::Node for Node {
/// fn new() -> Self { Node }
/// fn invoke(&mut self, grpc_method_name: &str, grpc_channel: &mut oak::Channel) { /* ... */ }
/// }
///
/// #[no_mangle]
/// pub extern "C" fn oak_initialize() {
/// oak::set_node::<Node>();
/// }
/// ```
pub fn set_node<T: Node + 'static>() {
NODE.with(|node| {
match *node.borrow_mut() {
Some(_) => {
writeln!(logging_channel(), "attempt to set_node() when already set!").unwrap();
panic!("attempt to set_node when already set");
}
None => {
writeln!(logging_channel(), "setting current node instance").unwrap();
}
}
*node.borrow_mut() = Some(Box::new(T::new()));
});
}
#[no_mangle]
pub extern "C" fn oak_handle_grpc_call() {
NODE.with(|node| match *node.borrow_mut() {
Some(ref mut node) => {
let mut grpc_method_channel = Channel::new(GRPC_METHOD_NAME_CHANNEL_HANDLE);
let mut grpc_method_name = String::new();
grpc_method_channel
.read_to_string(&mut grpc_method_name)
.unwrap();
let mut grpc_channel = Channel::new(GRPC_CHANNEL_HANDLE);
node.invoke(&grpc_method_name, &mut grpc_channel);
}
None => {
writeln!(logging_channel(), "gRPC call with no loaded Node").unwrap();
panic!("gRPC call with no loaded Node");
}
});
}
|
extern crate winapi;
extern crate opengl32;
extern crate gdi32;
extern crate user32;
extern crate kernel32;
use std::{mem, ptr};
use self::winapi::*;
pub type DeviceContext = HDC;
pub type Context = (HDC, HGLRC);
pub unsafe fn create_context(device_context: DeviceContext) -> Option<Context> {
let tmp_context = opengl32::wglCreateContext(device_context);
if tmp_context.is_null() {
return None;
}
make_current((device_context, tmp_context));
let render_context = create_context_attribs(device_context, ptr::null_mut(), ptr::null());
clear_current();
opengl32::wglDeleteContext(tmp_context);
if render_context.is_null() {
let error = kernel32::GetLastError();
println!("WARNING: Failed to created OpenGL context, last error: {:#x}", error);
None
} else {
make_current((device_context, render_context));
// TODO: Don't do this in context creation.
if set_swap_interval(0) != ::types::Boolean::True {
println!("WARNING: Failed to set swap interval of setting swap interval");
}
clear_current();
Some((device_context, render_context))
}
}
pub unsafe fn destroy_context(context: Context) {
let (_, render_context) = context;
clear_current();
let result = opengl32::wglDeleteContext(render_context);
assert!(result == 1, "Failed to delete context: {:?}", render_context);
}
pub unsafe fn load_proc(proc_name: &str) -> Option<extern "system" fn()> {
let string = proc_name.as_bytes();
debug_assert!(
string[string.len() - 1] == 0,
"Proc name \"{}\" is not null terminated",
proc_name,
);
let mut ptr = opengl32::wglGetProcAddress(string.as_ptr() as *const _);
if ptr.is_null() {
let module = kernel32::LoadLibraryA(b"opengl32.dll\0".as_ptr() as *const _);
// TODO: What do we want to do in this case? Probably just return `None`, right?
assert!(!module.is_null(), "Failed to load opengl32.dll");
ptr = kernel32::GetProcAddress(module, string.as_ptr() as *const _);
}
if ptr.is_null() {
let actual_dc = opengl32::wglGetCurrentDC();
let actual_context = opengl32::wglGetCurrentContext();
println!(
"pointer for {} was null, last error: 0x{:X}, active dc: {:?}, active context: {:?}",
proc_name,
kernel32::GetLastError(),
actual_dc,
actual_context,
);
return None;
}
Some(mem::transmute(ptr))
}
pub unsafe fn swap_buffers(context: Context) {
let (device_context, _) = context;
if gdi32::SwapBuffers(device_context) != TRUE {
let (device_context, render_context) = context;
let hwnd = user32::GetActiveWindow();
panic!(
"Swap buffers failed, dc: {:?}, context: {:?} last error: 0x:{:X}, hwnd: {:?}",
device_context,
render_context,
kernel32::GetLastError(),
hwnd,
);
}
}
pub unsafe fn make_current(context: Context) -> Context {
let old_device_context = opengl32::wglGetCurrentDC();
let old_render_context = opengl32::wglGetCurrentContext();
let (device_context, render_context) = context;
let result = opengl32::wglMakeCurrent(device_context, render_context);
if result != TRUE {
let hwnd = user32::GetActiveWindow();
panic!(
"Failed to make context current, dc: {:?}, context: {:?} last error: 0x:{:X}, actual dc and context: {:?} and {:?}, hwnd: {:?}",
device_context,
render_context,
kernel32::GetLastError(),
old_device_context,
old_render_context,
hwnd,
);
}
(old_device_context, old_render_context)
}
pub unsafe fn clear_current() {
make_current((ptr::null_mut(), ptr::null_mut()));
}
gl_proc!(wglGetExtensionsStringARB:
fn get_extension_string(hdc: ::platform::winapi::HDC) -> *const u8);
gl_proc!(wglCreateContextAttribsARB:
fn create_context_attribs(
hdc: ::platform::winapi::HDC,
share_context: ::platform::winapi::HGLRC,
attrib_list: *const i32
) -> ::platform::winapi::HGLRC);
gl_proc!(wglGetSwapIntervalEXT:
fn get_swap_interval() -> i32);
gl_proc!(wglSwapIntervalEXT:
fn set_swap_interval(interval: i32) -> ::types::Boolean);
|
#[doc = "Reader of register C0CR"]
pub type R = crate::R<u32, super::C0CR>;
#[doc = "Writer for register C0CR"]
pub type W = crate::W<u32, super::C0CR>;
#[doc = "Register C0CR `reset()`'s with value 0"]
impl crate::ResetValue for super::C0CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `EN`"]
pub type EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EN`"]
pub struct EN_W<'a> {
w: &'a mut W,
}
impl<'a> EN_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 `TEIE`"]
pub type TEIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TEIE`"]
pub struct TEIE_W<'a> {
w: &'a mut W,
}
impl<'a> TEIE_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 `CTCIE`"]
pub type CTCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CTCIE`"]
pub struct CTCIE_W<'a> {
w: &'a mut W,
}
impl<'a> CTCIE_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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `BRTIE`"]
pub type BRTIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BRTIE`"]
pub struct BRTIE_W<'a> {
w: &'a mut W,
}
impl<'a> BRTIE_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 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `BTIE`"]
pub type BTIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BTIE`"]
pub struct BTIE_W<'a> {
w: &'a mut W,
}
impl<'a> BTIE_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 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `TCIE`"]
pub type TCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TCIE`"]
pub struct TCIE_W<'a> {
w: &'a mut W,
}
impl<'a> TCIE_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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `PL`"]
pub type PL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PL`"]
pub struct PL_W<'a> {
w: &'a mut W,
}
impl<'a> PL_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 & !(0x03 << 6)) | (((value as u32) & 0x03) << 6);
self.w
}
}
#[doc = "Reader of field `BEX`"]
pub type BEX_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BEX`"]
pub struct BEX_W<'a> {
w: &'a mut W,
}
impl<'a> BEX_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 `HEX`"]
pub type HEX_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HEX`"]
pub struct HEX_W<'a> {
w: &'a mut W,
}
impl<'a> HEX_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 `WEX`"]
pub type WEX_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WEX`"]
pub struct WEX_W<'a> {
w: &'a mut W,
}
impl<'a> WEX_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 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Write proxy for field `SWRQ`"]
pub struct SWRQ_W<'a> {
w: &'a mut W,
}
impl<'a> SWRQ_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
}
}
impl R {
#[doc = "Bit 0 - channel enable"]
#[inline(always)]
pub fn en(&self) -> EN_R {
EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Transfer error interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn teie(&self) -> TEIE_R {
TEIE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Channel Transfer Complete interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn ctcie(&self) -> CTCIE_R {
CTCIE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Block Repeat transfer interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn brtie(&self) -> BRTIE_R {
BRTIE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Block Transfer interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn btie(&self) -> BTIE_R {
BTIE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - buffer Transfer Complete interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn tcie(&self) -> TCIE_R {
TCIE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bits 6:7 - Priority level These bits are set and cleared by software. These bits are protected and can be written only if EN is 0."]
#[inline(always)]
pub fn pl(&self) -> PL_R {
PL_R::new(((self.bits >> 6) & 0x03) as u8)
}
#[doc = "Bit 12 - byte Endianness exchange"]
#[inline(always)]
pub fn bex(&self) -> BEX_R {
BEX_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Half word Endianes exchange"]
#[inline(always)]
pub fn hex(&self) -> HEX_R {
HEX_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Word Endianness exchange"]
#[inline(always)]
pub fn wex(&self) -> WEX_R {
WEX_R::new(((self.bits >> 14) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - channel enable"]
#[inline(always)]
pub fn en(&mut self) -> EN_W {
EN_W { w: self }
}
#[doc = "Bit 1 - Transfer error interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn teie(&mut self) -> TEIE_W {
TEIE_W { w: self }
}
#[doc = "Bit 2 - Channel Transfer Complete interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn ctcie(&mut self) -> CTCIE_W {
CTCIE_W { w: self }
}
#[doc = "Bit 3 - Block Repeat transfer interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn brtie(&mut self) -> BRTIE_W {
BRTIE_W { w: self }
}
#[doc = "Bit 4 - Block Transfer interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn btie(&mut self) -> BTIE_W {
BTIE_W { w: self }
}
#[doc = "Bit 5 - buffer Transfer Complete interrupt enable This bit is set and cleared by software."]
#[inline(always)]
pub fn tcie(&mut self) -> TCIE_W {
TCIE_W { w: self }
}
#[doc = "Bits 6:7 - Priority level These bits are set and cleared by software. These bits are protected and can be written only if EN is 0."]
#[inline(always)]
pub fn pl(&mut self) -> PL_W {
PL_W { w: self }
}
#[doc = "Bit 12 - byte Endianness exchange"]
#[inline(always)]
pub fn bex(&mut self) -> BEX_W {
BEX_W { w: self }
}
#[doc = "Bit 13 - Half word Endianes exchange"]
#[inline(always)]
pub fn hex(&mut self) -> HEX_W {
HEX_W { w: self }
}
#[doc = "Bit 14 - Word Endianness exchange"]
#[inline(always)]
pub fn wex(&mut self) -> WEX_W {
WEX_W { w: self }
}
#[doc = "Bit 16 - SW ReQuest Writing a 1 into this bit sets the CRQAx in MDMA_ISRy register, activating the request on Channel x Note: Either the whole CxCR register or the 8-bit/16-bit register @ Address offset: 0x4E + 0x40 chn may be used for SWRQ activation. In case of a SW request, acknowledge is not generated (neither HW signal, nor CxMAR write access)."]
#[inline(always)]
pub fn swrq(&mut self) -> SWRQ_W {
SWRQ_W { w: self }
}
}
|
use std::borrow::{Borrow, Cow};
use std::fmt;
use std::mem::MaybeUninit;
use std::ops::Deref;
use anyhow::anyhow;
use firefly_session::{Options, ProjectType};
use firefly_target::{CodeModel, Endianness, RelocModel};
use crate::codegen::{self, CodeGenFileType, CodeGenOptLevel, CodeGenOptSize};
use crate::ir::*;
use crate::support::{OwnedStringRef, StringRef};
extern "C" {
type LlvmTargetMachine;
type LlvmTarget;
type LlvmTargetDataLayout;
}
/// Initialize all targets
pub fn init() {
extern "C" {
fn LLVM_InitializeAllTargetInfos();
fn LLVM_InitializeAllTargets();
fn LLVM_InitializeAllTargetMCs();
fn LLVM_InitializeAllAsmPrinters();
fn LLVM_InitializeAllAsmParsers();
fn LLVM_InitializeAllDisassemblers();
}
unsafe {
LLVM_InitializeAllTargetInfos();
LLVM_InitializeAllTargets();
LLVM_InitializeAllTargetMCs();
LLVM_InitializeAllAsmPrinters();
LLVM_InitializeAllAsmParsers();
LLVM_InitializeAllDisassemblers();
}
}
/// Returns the triple for the host machine as a string
pub fn default_triple() -> OwnedStringRef {
extern "C" {
fn LLVMGetDefaultTargetTriple() -> *const std::os::raw::c_char;
}
unsafe { OwnedStringRef::from_ptr(LLVMGetDefaultTargetTriple()) }
}
/// Normalizes the given triple, returning the normalized value as a new string
pub fn normalize_triple<S: Into<StringRef>>(triple: S) -> OwnedStringRef {
extern "C" {
fn LLVMNormalizeTargetTriple(
triple: *const std::os::raw::c_char,
) -> *const std::os::raw::c_char;
}
let triple = triple.into();
let c_str = triple.to_cstr();
unsafe { OwnedStringRef::from_ptr(LLVMNormalizeTargetTriple(c_str.as_ptr())) }
}
/// Returns the host CPU as a string
pub fn host_cpu() -> OwnedStringRef {
extern "C" {
fn LLVMGetHostCPUName() -> *const std::os::raw::c_char;
}
unsafe { OwnedStringRef::from_ptr(LLVMGetHostCPUName()) }
}
/// Returns the specific cpu architecture being targeted as defined by the given compiler options
pub fn target_cpu(options: &Options) -> Cow<'static, str> {
let name = match options.codegen_opts.target_cpu.as_ref().map(|s| s.as_str()) {
Some(s) => s.to_string().into(),
None => options.target.options.cpu.clone(),
};
if name != "native" {
return name;
}
let native = host_cpu();
native.to_string().into()
}
/// Returns the host's CPU features as a string
pub fn host_cpu_features() -> OwnedStringRef {
extern "C" {
fn LLVMGetHostCPUFeatures() -> *const std::os::raw::c_char;
}
unsafe { OwnedStringRef::from_ptr(LLVMGetHostCPUFeatures()) }
}
/// Iterates all of the default + custom target features defined by the provided compiler options
///
/// See firefly_target for the default features defined for each supported target
///
/// In addition to those defaults, manually-specified target features can be enabled via compiler flags
pub fn llvm_target_features(options: &Options) -> impl Iterator<Item = &str> {
const FIREFLY_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
let cmdline = options
.codegen_opts
.target_features
.as_ref()
.map(|s| s.as_str())
.unwrap_or("")
.split(',')
.filter(|f| !FIREFLY_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
options
.target
.options
.features
.split(',')
.chain(cmdline)
.filter(|l| l.is_empty())
}
/// Represents a reference to a specific codegen target
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct Target(*const LlvmTarget);
impl Target {
#[inline(always)]
fn is_null(&self) -> bool {
self.0.is_null()
}
/// Get a target by name, e.g. x86-64 or wasm32
pub fn by_name<S: Into<StringRef>>(name: S) -> Option<Target> {
extern "C" {
fn LLVMGetTargetFromName(name: *const std::os::raw::c_char) -> Target;
}
let name = name.into();
let c_str = name.to_cstr();
let target = unsafe { LLVMGetTargetFromName(c_str.as_ptr()) };
if target.is_null() {
None
} else {
Some(target)
}
}
/// Get a target by its triple, e.g. aarch64-apple-darwin, wasm32-unknown-unknown
pub fn by_triple<S: Into<StringRef>>(triple: S) -> Option<Target> {
extern "C" {
fn LLVMGetTargetFromTriple(
triple: *const std::os::raw::c_char,
t: *mut Target,
error: *mut *mut std::os::raw::c_char,
) -> bool;
}
let triple = triple.into();
let c_str = triple.to_cstr();
let mut target = MaybeUninit::uninit();
let failed = unsafe {
LLVMGetTargetFromTriple(c_str.as_ptr(), target.as_mut_ptr(), core::ptr::null_mut())
};
if failed {
None
} else {
Some(unsafe { target.assume_init() })
}
}
/// Returns the name of this target
pub fn name(self) -> StringRef {
extern "C" {
fn LLVMGetTargetName(t: Target) -> *const std::os::raw::c_char;
}
unsafe { StringRef::from_ptr(LLVMGetTargetName(self)) }
}
/// Returns the description of this target
pub fn description(self) -> StringRef {
extern "C" {
fn LLVMGetTargetDescription(t: Target) -> *const std::os::raw::c_char;
}
unsafe { StringRef::from_ptr(LLVMGetTargetDescription(self)) }
}
/// Returns true if this target has a JIT
pub fn has_jit(self) -> bool {
extern "C" {
fn LLVMTargetHasJIT(t: Target) -> bool;
}
unsafe { LLVMTargetHasJIT(self) }
}
/// Returns true if this target has a TargetMachine associated
pub fn has_target_machine(self) -> bool {
extern "C" {
fn LLVMTargetHasTargetMachine(t: Target) -> bool;
}
unsafe { LLVMTargetHasTargetMachine(self) }
}
/// Returns true if this target has an ASM backend (required for emitting output)
pub fn has_asm_backend(self) -> bool {
extern "C" {
fn LLVMTargetHasAsmBackend(t: Target) -> bool;
}
unsafe { LLVMTargetHasAsmBackend(self) }
}
pub fn iter() -> impl Iterator<Item = Target> {
TargetIter::new()
}
}
/// Used to walk the set of available targets
///
/// NOTE: Targets are more abstract than a TargetMachine, so there is not a direct
/// correlation from target to triple, as a target is often shared across many triples.
/// As a result, you can't walk the targets to get a list of triples. However, you can
/// walk the targets, and for each target print the available cpus/features for that target,
/// which can be used to select a specific target configuration (i.e. triple).
struct TargetIter(Target);
impl TargetIter {
fn new() -> Self {
extern "C" {
fn LLVMGetFirstTarget() -> Target;
}
Self(unsafe { LLVMGetFirstTarget() })
}
}
impl Iterator for TargetIter {
type Item = Target;
fn next(&mut self) -> Option<Self::Item> {
extern "C" {
fn LLVMGetNextTarget(t: Target) -> Target;
}
if self.0.is_null() {
return None;
}
let next = unsafe { LLVMGetNextTarget(self.0) };
if next.is_null() {
self.0 = next;
None
} else {
self.0 = next;
Some(next)
}
}
}
impl std::iter::FusedIterator for TargetIter {}
/// Used to pass a target machine configuration to C++
#[repr(C)]
struct TargetMachineConfig {
pub triple: StringRef,
pub cpu: StringRef,
pub abi: StringRef,
pub features: *const StringRef,
pub features_len: u32,
pub relax_elf_relocations: bool,
pub position_independent_code: bool,
pub data_sections: bool,
pub function_sections: bool,
pub emit_stack_size_section: bool,
pub preserve_asm_comments: bool,
pub enable_threading: bool,
pub code_model: CodeModel,
pub reloc_model: RelocModel,
pub opt_level: CodeGenOptLevel,
pub size_level: CodeGenOptSize,
}
/// Represents a non-owning reference to an LLVM target machine
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct TargetMachine(*const LlvmTargetMachine);
impl TargetMachine {
/// Creates a target machine from the current compiler options
///
/// NOTE: This assumes the compiler options represent a valid target configuration, i.e.
/// a target must have been selected, and the various configuration options must not be
/// contradictory or invalid for the selected target. This is largely taken care of by the
/// firefly_target crate, but it is worth calling out here. If the configuration is invalid,
/// creation should fail and we'll raise an error, but if there are issues in LLVM itself it
/// may cause issues with produced binaries.
pub fn create(options: &Options) -> anyhow::Result<OwnedTargetMachine> {
extern "C" {
fn LLVMFireflyCreateTargetMachine(
config: *const TargetMachineConfig,
error: *mut *mut std::os::raw::c_char,
) -> TargetMachine;
}
crate::require_inited();
let features_owned = llvm_target_features(options)
.map(|f| f.to_string())
.collect::<Vec<_>>();
let triple: &str = options.target.llvm_target.borrow();
let cpu = target_cpu(options);
let cpu: &str = cpu.borrow();
let abi: &str = options.target.options.llvm_abiname.borrow();
let relax_elf_relocations = options.target.options.relax_elf_relocations;
let default_reloc_model = options.target.options.relocation_model;
let reloc_model = options
.codegen_opts
.relocation_model
.unwrap_or(default_reloc_model);
let position_independent_code =
options.app_type == ProjectType::Executable && reloc_model == RelocModel::Pic;
let function_sections = options.target.options.function_sections;
let data_sections = function_sections;
let emit_stack_size_section = options.debugging_opts.emit_stack_sizes;
let preserve_asm_comments = options.debugging_opts.asm_comments;
let enable_threading = if options.target.options.singlethread {
// On the wasm target once the `atomics` feature is enabled that means that
// we're no longer single-threaded, or otherwise we don't want LLVM to
// lower atomic operations to single-threaded operations.
if options.target.llvm_target.contains("wasm32")
&& features_owned.iter().any(|s| s == "+atomics")
{
true
} else {
false
}
} else {
true
};
let default_code_model = options.target.options.code_model;
let code_model = options
.codegen_opts
.code_model
.or(default_code_model)
.unwrap_or(CodeModel::None);
let (opt_level, size_level) = codegen::to_llvm_opt_settings(options.opt_level);
let features = features_owned
.iter()
.map(StringRef::from)
.collect::<Vec<_>>();
let config = TargetMachineConfig {
triple: StringRef::from(triple),
cpu: StringRef::from(cpu),
abi: StringRef::from(abi),
features: features.as_ptr(),
features_len: features.len().try_into().unwrap(),
relax_elf_relocations,
position_independent_code,
data_sections,
function_sections,
emit_stack_size_section,
preserve_asm_comments,
enable_threading,
code_model,
reloc_model,
opt_level,
size_level,
};
let mut error = MaybeUninit::uninit();
let tm = unsafe { LLVMFireflyCreateTargetMachine(&config, error.as_mut_ptr()) };
if tm.is_null() {
let error = unsafe { OwnedStringRef::from_ptr(error.assume_init()) };
Err(anyhow!(
"Target machine creation for {} failed: {}",
triple,
&error
))
} else {
Ok(OwnedTargetMachine(tm))
}
}
#[inline]
fn is_null(&self) -> bool {
self.0.is_null()
}
/// Returns the target for this target machine
pub fn target(self) -> Target {
extern "C" {
fn LLVMGetTargetMachineTarget(t: TargetMachine) -> Target;
}
unsafe { LLVMGetTargetMachineTarget(self) }
}
/// Returns the triple used in creating this target machine
pub fn triple(self) -> StringRef {
extern "C" {
fn LLVMGetTargetMachineTriple(t: TargetMachine) -> *const std::os::raw::c_char;
}
unsafe { StringRef::from_ptr(LLVMGetTargetMachineTriple(self)) }
}
/// Returns the cpu used in creating this target machine
pub fn cpu(self) -> StringRef {
extern "C" {
fn LLVMGetTargetMachineCPU(t: TargetMachine) -> *const std::os::raw::c_char;
}
unsafe { StringRef::from_ptr(LLVMGetTargetMachineCPU(self)) }
}
/// Returns the feature string used in creating this target machine
pub fn features(self) -> StringRef {
extern "C" {
fn LLVMGetTargetMachineFeatureString(t: TargetMachine) -> *const std::os::raw::c_char;
}
unsafe { StringRef::from_ptr(LLVMGetTargetMachineFeatureString(self)) }
}
/// Prints the available set of target CPUs to stdout
pub fn print_target_cpus(self) {
extern "C" {
fn PrintTargetCPUs(tm: TargetMachine);
}
unsafe { PrintTargetCPUs(self) }
}
/// Prints the available set of target features to stdout
pub fn print_target_features(self) {
extern "C" {
fn PrintTargetFeatures(tm: TargetMachine);
}
unsafe { PrintTargetFeatures(self) };
}
/// Get a reference to the target data layout for this target
pub fn data_layout(self) -> TargetDataLayout {
extern "C" {
fn LLVMCreateTargetDataLayout(t: TargetMachine) -> TargetDataLayout;
}
let ptr = unsafe { LLVMCreateTargetDataLayout(self) };
assert!(!ptr.is_null());
ptr
}
/// Sets the target machine's ASM verbosity
pub fn set_asm_verbosity(self, verbose: bool) {
extern "C" {
fn LLVMSetTargetMachineAsmVerbosity(t: TargetMachine, verbose: bool);
}
unsafe { LLVMSetTargetMachineAsmVerbosity(self, verbose) }
}
pub fn emit_to_file<S: Into<StringRef>>(
self,
module: Module,
filename: S,
codegen: CodeGenFileType,
) -> anyhow::Result<()> {
extern "C" {
fn LLVMTargetMachineEmitToFile(
t: TargetMachine,
m: Module,
filename: *const i8,
codegen: CodeGenFileType,
error: *mut *mut std::os::raw::c_char,
) -> bool;
}
let filename = filename.into();
let filename = filename.to_cstr();
let mut error = MaybeUninit::uninit();
let failed = unsafe {
LLVMTargetMachineEmitToFile(
self,
module,
filename.as_ptr(),
codegen,
error.as_mut_ptr(),
)
};
if failed {
let error = unsafe { OwnedStringRef::from_ptr(error.assume_init()) };
Err(anyhow!("{}", &error))
} else {
Ok(())
}
}
#[cfg(not(windows))]
pub fn emit_to_fd(
self,
module: Module,
fd: std::os::unix::io::RawFd,
codegen: CodeGenFileType,
) -> anyhow::Result<()> {
extern "C" {
fn LLVMTargetMachineEmitToFileDescriptor(
t: TargetMachine,
module: Module,
fd: std::os::unix::io::RawFd,
codegen: CodeGenFileType,
error: *mut *mut std::os::raw::c_char,
) -> bool;
}
let mut error = MaybeUninit::uninit();
let failed = unsafe {
LLVMTargetMachineEmitToFileDescriptor(self, module, fd, codegen, error.as_mut_ptr())
};
if failed {
let error = unsafe { OwnedStringRef::from_ptr(error.assume_init()) };
Err(anyhow!("{}", &error))
} else {
Ok(())
}
}
#[cfg(windows)]
pub fn emit_to_fd(
self,
module: Module,
fd: std::os::windows::io::RawHandle,
codegen: CodeGenFileType,
) -> anyhow::Result<()> {
extern "C" {
fn LLVMTargetMachineEmitToFileDescriptor(
t: TargetMachine,
module: Module,
fd: std::os::windows::io::RawHandle,
codegen: CodeGenFileType,
error: *mut *mut std::os::raw::c_char,
) -> bool;
}
let mut error = MaybeUninit::uninit();
let failed = unsafe {
LLVMTargetMachineEmitToFileDescriptor(self, module, fd, codegen, error.as_mut_ptr())
};
if failed {
let error = unsafe { OwnedStringRef::from_ptr(error.assume_init()) };
Err(anyhow!("{}", &error))
} else {
Ok(())
}
}
}
impl Eq for TargetMachine {}
impl PartialEq for TargetMachine {
fn eq(&self, other: &Self) -> bool {
core::ptr::eq(self.0, other.0)
}
}
impl fmt::Pointer for TargetMachine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TargetMachine({:p})", self.0)
}
}
impl fmt::Debug for TargetMachine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TargetMachine({:p})", self.0)
}
}
/// Represents an owned reference to a TargetMachine
#[repr(transparent)]
pub struct OwnedTargetMachine(TargetMachine);
impl OwnedTargetMachine {
/// Returns the underlying TargetMachine handle
///
/// NOTE: It is up to the caller to ensure that the handle does not outlive this struct
pub fn handle(&self) -> TargetMachine {
self.0
}
}
unsafe impl Send for TargetMachine {}
unsafe impl Sync for TargetMachine {}
impl Eq for OwnedTargetMachine {}
impl PartialEq for OwnedTargetMachine {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl fmt::Pointer for OwnedTargetMachine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:p}", self.0)
}
}
impl fmt::Debug for OwnedTargetMachine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl Deref for OwnedTargetMachine {
type Target = TargetMachine;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Drop for OwnedTargetMachine {
fn drop(&mut self) {
extern "C" {
fn LLVMDisposeTargetMachine(t: TargetMachine);
}
unsafe {
LLVMDisposeTargetMachine(self.0);
}
}
}
/// Represents the target data layout for some target
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct TargetDataLayout(*const LlvmTargetDataLayout);
impl TargetDataLayout {
#[inline(always)]
pub fn is_null(&self) -> bool {
self.0.is_null()
}
/// Creates target data from the given target layout string
pub fn new<S: Into<StringRef>>(layout: S) -> Result<OwnedTargetDataLayout, ()> {
extern "C" {
fn LLVMCreateTargetData(layout: *const std::os::raw::c_char) -> TargetDataLayout;
}
let layout = layout.into();
let c_str = layout.to_cstr();
let ptr = unsafe { LLVMCreateTargetData(c_str.as_ptr()) };
if ptr.is_null() {
Err(())
} else {
Ok(OwnedTargetDataLayout(ptr))
}
}
/// Returns the endianness of this target's data layout
pub fn byte_order(self) -> Endianness {
extern "C" {
fn LLVMByteOrder(t: TargetDataLayout) -> u8;
}
match unsafe { LLVMByteOrder(self) } {
0 => Endianness::Big,
1 => Endianness::Little,
n => panic!("invalid byte ordering variant {}", n),
}
}
/// Gets the size of pointers in bytes, e.g. 8 for x86_64
pub fn get_pointer_byte_size(self) -> usize {
extern "C" {
fn LLVMPointerSize(t: TargetDataLayout) -> u32;
}
unsafe { LLVMPointerSize(self) as usize }
}
/// Gets the LLVM type representing a pointer-sized integer for this data layout
pub fn get_int_ptr_type(self, context: Context) -> IntegerType {
extern "C" {
fn LLVMIntPtrTypeInContext(context: Context, t: TargetDataLayout) -> IntegerType;
}
unsafe { LLVMIntPtrTypeInContext(context, self) }
}
/// Provides sizeof facilities for the given LLVM type in this data layout
pub fn size_of_type<T: Type>(self, ty: T) -> usize {
extern "C" {
fn LLVMSizeOfTypeInBits(t: TargetDataLayout, ty: TypeBase) -> u64;
}
unsafe { LLVMSizeOfTypeInBits(self, ty.base()) }
.try_into()
.unwrap()
}
/// Provides the ABI-defined alignment of the given type in this data layout
pub fn abi_alignment_of_type<T: Type>(self, ty: T) -> usize {
extern "C" {
fn LLVMABIAlignmentOfType(t: TargetDataLayout, ty: TypeBase) -> u32;
}
unsafe { LLVMABIAlignmentOfType(self, ty.base()) as usize }
}
}
impl fmt::Display for TargetDataLayout {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
extern "C" {
fn LLVMCopyStringRepOfTargetData(t: TargetDataLayout) -> *const std::os::raw::c_char;
}
let rep = unsafe { OwnedStringRef::from_ptr(LLVMCopyStringRepOfTargetData(*self)) };
write!(f, "{}", &rep)
}
}
/// Represents an owned reference to an llvm::TargetData instance
pub struct OwnedTargetDataLayout(TargetDataLayout);
impl Deref for OwnedTargetDataLayout {
type Target = TargetDataLayout;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Drop for OwnedTargetDataLayout {
fn drop(&mut self) {
extern "C" {
fn LLVMDisposeTargetData(t: TargetDataLayout);
}
unsafe { LLVMDisposeTargetData(self.0) }
}
}
impl fmt::Display for OwnedTargetDataLayout {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.0)
}
}
|
//! `rustix` provides efficient memory-safe and [I/O-safe] wrappers to
//! POSIX-like, Unix-like, Linux, and Winsock2 syscall-like APIs, with
//! configurable backends.
//!
//! With rustix, you can write code like this:
//!
//! ```
//! # #[cfg(feature = "net")]
//! # fn read(sock: std::net::TcpStream, buf: &mut [u8]) -> std::io::Result<()> {
//! # use rustix::net::RecvFlags;
//! let nread: usize = rustix::net::recv(&sock, buf, RecvFlags::PEEK)?;
//! # let _ = nread;
//! # Ok(())
//! # }
//! ```
//!
//! instead of like this:
//!
//! ```
//! # #[cfg(feature = "net")]
//! # fn read(sock: std::net::TcpStream, buf: &mut [u8]) -> std::io::Result<()> {
//! # #[cfg(unix)]
//! # use std::os::unix::io::AsRawFd;
//! # #[cfg(target_os = "wasi")]
//! # use std::os::wasi::io::AsRawFd;
//! # #[cfg(windows)]
//! # use windows_sys::Win32::Networking::WinSock as libc;
//! # #[cfg(windows)]
//! # use std::os::windows::io::AsRawSocket;
//! # const MSG_PEEK: i32 = libc::MSG_PEEK;
//! let nread: usize = unsafe {
//! #[cfg(any(unix, target_os = "wasi"))]
//! let raw = sock.as_raw_fd();
//! #[cfg(windows)]
//! let raw = sock.as_raw_socket();
//! match libc::recv(
//! raw as _,
//! buf.as_mut_ptr().cast(),
//! buf.len().try_into().unwrap_or(i32::MAX as _),
//! MSG_PEEK,
//! ) {
//! -1 => return Err(std::io::Error::last_os_error()),
//! nread => nread as usize,
//! }
//! };
//! # let _ = nread;
//! # Ok(())
//! # }
//! ```
//!
//! rustix's APIs perform the following tasks:
//! - Error values are translated to [`Result`]s.
//! - Buffers are passed as Rust slices.
//! - Out-parameters are presented as return values.
//! - Path arguments use [`Arg`], so they accept any string type.
//! - File descriptors are passed and returned via [`AsFd`] and [`OwnedFd`]
//! instead of bare integers, ensuring I/O safety.
//! - Constants use `enum`s and [`bitflags`] types.
//! - Multiplexed functions (eg. `fcntl`, `ioctl`, etc.) are de-multiplexed.
//! - Variadic functions (eg. `openat`, etc.) are presented as non-variadic.
//! - Functions that return strings automatically allocate sufficient memory
//! and retry the syscall as needed to determine the needed length.
//! - Functions and types which need `l` prefixes or `64` suffixes to enable
//! large-file support (LFS) are used automatically. File sizes and offsets
//! are always presented as `u64` and `i64`.
//! - Behaviors that depend on the sizes of C types like `long` are hidden.
//! - In some places, more human-friendly and less historical-accident names
//! are used (and documentation aliases are used so that the original names
//! can still be searched for).
//! - Provide y2038 compatibility, on platforms which support this.
//! - Correct selected platform bugs, such as behavioral differences when
//! running under seccomp.
//!
//! Things they don't do include:
//! - Detecting whether functions are supported at runtime, except in specific
//! cases where new interfaces need to be detected to support y2038 and LFS.
//! - Hiding significant differences between platforms.
//! - Restricting ambient authorities.
//! - Imposing sandboxing features such as filesystem path or network address
//! sandboxing.
//!
//! See [`cap-std`], [`system-interface`], and [`io-streams`] for libraries
//! which do hide significant differences between platforms, and [`cap-std`]
//! which does perform sandboxing and restricts ambient authorities.
//!
//! [`cap-std`]: https://crates.io/crates/cap-std
//! [`system-interface`]: https://crates.io/crates/system-interface
//! [`io-streams`]: https://crates.io/crates/io-streams
//! [`getrandom`]: https://crates.io/crates/getrandom
//! [`bitflags`]: https://crates.io/crates/bitflags
//! [`AsFd`]: https://doc.rust-lang.org/stable/std/os/fd/trait.AsFd.html
//! [`OwnedFd`]: https://doc.rust-lang.org/stable/std/os/fd/struct.OwnedFd.html
//! [I/O-safe]: https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md
//! [`Result`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html
//! [`Arg`]: https://docs.rs/rustix/*/rustix/path/trait.Arg.html
#![deny(missing_docs)]
#![allow(stable_features)]
#![cfg_attr(linux_raw, deny(unsafe_code))]
#![cfg_attr(rustc_attrs, feature(rustc_attrs))]
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![cfg_attr(all(wasi_ext, target_os = "wasi", feature = "std"), feature(wasi_ext))]
#![cfg_attr(core_ffi_c, feature(core_ffi_c))]
#![cfg_attr(core_c_str, feature(core_c_str))]
#![cfg_attr(alloc_c_string, feature(alloc_c_string))]
#![cfg_attr(alloc_ffi, feature(alloc_ffi))]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "rustc-dep-of-std", feature(ip))]
#![cfg_attr(
any(feature = "rustc-dep-of-std", core_intrinsics),
feature(core_intrinsics)
)]
#![cfg_attr(asm_experimental_arch, feature(asm_experimental_arch))]
#![cfg_attr(not(feature = "all-apis"), allow(dead_code))]
// It is common in linux and libc APIs for types to vary between platforms.
#![allow(clippy::unnecessary_cast)]
// It is common in linux and libc APIs for types to vary between platforms.
#![allow(clippy::useless_conversion)]
// Redox and WASI have enough differences that it isn't worth precisely
// conditionalizing all the `use`s for them.
#![cfg_attr(any(target_os = "redox", target_os = "wasi"), allow(unused_imports))]
#[cfg(not(feature = "rustc-dep-of-std"))]
extern crate alloc;
// Use `static_assertions` macros if we have them, or a polyfill otherwise.
#[cfg(all(test, static_assertions))]
#[macro_use]
#[allow(unused_imports)]
extern crate static_assertions;
#[cfg(all(test, not(static_assertions)))]
#[macro_use]
#[allow(unused_imports)]
mod static_assertions;
// Internal utilities.
#[cfg(not(windows))]
#[macro_use]
pub(crate) mod cstr;
pub(crate) mod utils;
// Polyfill for `std` in `no_std` builds.
#[cfg_attr(feature = "std", path = "maybe_polyfill/std/mod.rs")]
#[cfg_attr(not(feature = "std"), path = "maybe_polyfill/no_std/mod.rs")]
pub(crate) mod maybe_polyfill;
#[cfg(test)]
#[macro_use]
pub(crate) mod check_types;
#[macro_use]
pub(crate) mod bitcast;
// linux_raw: Weak symbols are used by the use-libc-auxv feature for
// glibc 2.15 support.
//
// libc: Weak symbols are used to call various functions available in some
// versions of libc and not others.
#[cfg(any(
all(linux_raw, feature = "use-libc-auxv"),
all(libc, not(any(windows, target_os = "espidf", target_os = "wasi")))
))]
#[macro_use]
mod weak;
// Pick the backend implementation to use.
#[cfg_attr(libc, path = "backend/libc/mod.rs")]
#[cfg_attr(linux_raw, path = "backend/linux_raw/mod.rs")]
#[cfg_attr(wasi, path = "backend/wasi/mod.rs")]
mod backend;
/// Export the `*Fd` types and traits that are used in rustix's public API.
///
/// Users can use this to avoid needing to import anything else to use the same
/// versions of these types and traits.
pub mod fd {
use super::backend;
// Re-export `AsSocket` etc. too, as users can't implement `AsFd` etc. on
// Windows due to them having blanket impls on Windows, so users must
// implement `AsSocket` etc.
#[cfg(windows)]
pub use backend::fd::{AsRawSocket, AsSocket, FromRawSocket, IntoRawSocket};
pub use backend::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
}
// The public API modules.
#[cfg(feature = "event")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "event")))]
pub mod event;
#[cfg(not(windows))]
pub mod ffi;
#[cfg(not(windows))]
#[cfg(any(
feature = "fs",
all(
linux_raw,
not(feature = "use-libc-auxv"),
not(target_vendor = "mustang"),
any(
feature = "param",
feature = "runtime",
feature = "time",
target_arch = "x86",
)
)
))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "fs")))]
pub mod fs;
pub mod io;
#[cfg(linux_kernel)]
#[cfg(feature = "io_uring")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "io_uring")))]
pub mod io_uring;
#[cfg(not(any(windows, target_os = "espidf", target_os = "wasi")))]
#[cfg(feature = "mm")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "mm")))]
pub mod mm;
#[cfg(linux_kernel)]
#[cfg(feature = "mount")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "mount")))]
pub mod mount;
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
#[cfg(feature = "net")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "net")))]
pub mod net;
#[cfg(not(any(windows, target_os = "espidf")))]
#[cfg(feature = "param")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "param")))]
pub mod param;
#[cfg(not(windows))]
#[cfg(any(
feature = "fs",
feature = "mount",
feature = "net",
all(
linux_raw,
not(feature = "use-libc-auxv"),
not(target_vendor = "mustang"),
any(
feature = "param",
feature = "runtime",
feature = "time",
target_arch = "x86",
)
)
))]
#[cfg_attr(
doc_cfg,
doc(cfg(any(feature = "fs", feature = "mount", feature = "net")))
)]
pub mod path;
#[cfg(feature = "pipe")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "pipe")))]
#[cfg(not(any(windows, target_os = "wasi")))]
pub mod pipe;
#[cfg(not(windows))]
#[cfg(feature = "process")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "process")))]
pub mod process;
#[cfg(feature = "procfs")]
#[cfg(linux_kernel)]
#[cfg_attr(doc_cfg, doc(cfg(feature = "procfs")))]
pub mod procfs;
#[cfg(not(windows))]
#[cfg(not(target_os = "wasi"))]
#[cfg(feature = "pty")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "pty")))]
pub mod pty;
#[cfg(not(windows))]
#[cfg(feature = "rand")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "rand")))]
pub mod rand;
#[cfg(not(windows))]
#[cfg(feature = "stdio")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "stdio")))]
pub mod stdio;
#[cfg(feature = "system")]
#[cfg(not(any(windows, target_os = "wasi")))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "system")))]
pub mod system;
#[cfg(not(windows))]
#[cfg(feature = "termios")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "termios")))]
pub mod termios;
#[cfg(not(windows))]
#[cfg(feature = "thread")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "thread")))]
pub mod thread;
#[cfg(not(any(windows, target_os = "espidf")))]
#[cfg(feature = "time")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "time")))]
pub mod time;
// "runtime" is also a public API module, but it's only for libc-like users.
#[cfg(not(windows))]
#[cfg(feature = "runtime")]
#[cfg(linux_raw)]
#[doc(hidden)]
#[cfg_attr(doc_cfg, doc(cfg(feature = "runtime")))]
pub mod runtime;
// Temporarily provide some mount functions for use in the fs module for
// backwards compatibility.
#[cfg(linux_kernel)]
#[cfg(all(feature = "fs", not(feature = "mount")))]
pub(crate) mod mount;
// Private modules used by multiple public modules.
#[cfg(not(any(windows, target_os = "espidf")))]
#[cfg(any(feature = "thread", feature = "time", target_arch = "x86"))]
mod clockid;
#[cfg(not(any(windows, target_os = "wasi")))]
#[cfg(any(
feature = "procfs",
feature = "process",
feature = "runtime",
feature = "termios",
feature = "thread",
all(bsd, feature = "event")
))]
mod pid;
#[cfg(any(feature = "process", feature = "thread"))]
#[cfg(linux_kernel)]
mod prctl;
#[cfg(not(any(windows, target_os = "espidf", target_os = "wasi")))]
#[cfg(any(feature = "process", feature = "runtime", all(bsd, feature = "event")))]
mod signal;
#[cfg(not(windows))]
#[cfg(any(
feature = "fs",
feature = "runtime",
feature = "thread",
feature = "time",
all(
linux_raw,
not(feature = "use-libc-auxv"),
not(target_vendor = "mustang"),
any(
feature = "param",
feature = "runtime",
feature = "time",
target_arch = "x86",
)
)
))]
mod timespec;
#[cfg(not(any(windows, target_os = "wasi")))]
#[cfg(any(
feature = "fs",
feature = "process",
feature = "thread",
all(
linux_raw,
not(feature = "use-libc-auxv"),
not(target_vendor = "mustang"),
any(
feature = "param",
feature = "runtime",
feature = "time",
target_arch = "x86",
)
)
))]
mod ugid;
|
#[doc = "Reader of register MPCBB2_VCTR26"]
pub type R = crate::R<u32, super::MPCBB2_VCTR26>;
#[doc = "Writer for register MPCBB2_VCTR26"]
pub type W = crate::W<u32, super::MPCBB2_VCTR26>;
#[doc = "Register MPCBB2_VCTR26 `reset()`'s with value 0"]
impl crate::ResetValue for super::MPCBB2_VCTR26 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `B832`"]
pub type B832_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B832`"]
pub struct B832_W<'a> {
w: &'a mut W,
}
impl<'a> B832_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 `B833`"]
pub type B833_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B833`"]
pub struct B833_W<'a> {
w: &'a mut W,
}
impl<'a> B833_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 `B834`"]
pub type B834_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B834`"]
pub struct B834_W<'a> {
w: &'a mut W,
}
impl<'a> B834_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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `B835`"]
pub type B835_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B835`"]
pub struct B835_W<'a> {
w: &'a mut W,
}
impl<'a> B835_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 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `B836`"]
pub type B836_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B836`"]
pub struct B836_W<'a> {
w: &'a mut W,
}
impl<'a> B836_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 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `B837`"]
pub type B837_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B837`"]
pub struct B837_W<'a> {
w: &'a mut W,
}
impl<'a> B837_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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `B838`"]
pub type B838_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B838`"]
pub struct B838_W<'a> {
w: &'a mut W,
}
impl<'a> B838_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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `B839`"]
pub type B839_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B839`"]
pub struct B839_W<'a> {
w: &'a mut W,
}
impl<'a> B839_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 `B840`"]
pub type B840_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B840`"]
pub struct B840_W<'a> {
w: &'a mut W,
}
impl<'a> B840_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 `B841`"]
pub type B841_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B841`"]
pub struct B841_W<'a> {
w: &'a mut W,
}
impl<'a> B841_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `B842`"]
pub type B842_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B842`"]
pub struct B842_W<'a> {
w: &'a mut W,
}
impl<'a> B842_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `B843`"]
pub type B843_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B843`"]
pub struct B843_W<'a> {
w: &'a mut W,
}
impl<'a> B843_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 `B844`"]
pub type B844_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B844`"]
pub struct B844_W<'a> {
w: &'a mut W,
}
impl<'a> B844_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 `B845`"]
pub type B845_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B845`"]
pub struct B845_W<'a> {
w: &'a mut W,
}
impl<'a> B845_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 `B846`"]
pub type B846_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B846`"]
pub struct B846_W<'a> {
w: &'a mut W,
}
impl<'a> B846_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 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `B847`"]
pub type B847_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B847`"]
pub struct B847_W<'a> {
w: &'a mut W,
}
impl<'a> B847_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 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `B848`"]
pub type B848_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B848`"]
pub struct B848_W<'a> {
w: &'a mut W,
}
impl<'a> B848_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 `B849`"]
pub type B849_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B849`"]
pub struct B849_W<'a> {
w: &'a mut W,
}
impl<'a> B849_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 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `B850`"]
pub type B850_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B850`"]
pub struct B850_W<'a> {
w: &'a mut W,
}
impl<'a> B850_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 `B851`"]
pub type B851_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B851`"]
pub struct B851_W<'a> {
w: &'a mut W,
}
impl<'a> B851_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 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `B852`"]
pub type B852_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B852`"]
pub struct B852_W<'a> {
w: &'a mut W,
}
impl<'a> B852_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 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `B853`"]
pub type B853_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B853`"]
pub struct B853_W<'a> {
w: &'a mut W,
}
impl<'a> B853_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 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `B854`"]
pub type B854_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B854`"]
pub struct B854_W<'a> {
w: &'a mut W,
}
impl<'a> B854_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 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `B855`"]
pub type B855_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B855`"]
pub struct B855_W<'a> {
w: &'a mut W,
}
impl<'a> B855_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `B856`"]
pub type B856_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B856`"]
pub struct B856_W<'a> {
w: &'a mut W,
}
impl<'a> B856_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 `B857`"]
pub type B857_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B857`"]
pub struct B857_W<'a> {
w: &'a mut W,
}
impl<'a> B857_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `B858`"]
pub type B858_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B858`"]
pub struct B858_W<'a> {
w: &'a mut W,
}
impl<'a> B858_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `B859`"]
pub type B859_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B859`"]
pub struct B859_W<'a> {
w: &'a mut W,
}
impl<'a> B859_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 `B860`"]
pub type B860_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B860`"]
pub struct B860_W<'a> {
w: &'a mut W,
}
impl<'a> B860_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 `B861`"]
pub type B861_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B861`"]
pub struct B861_W<'a> {
w: &'a mut W,
}
impl<'a> B861_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 `B862`"]
pub type B862_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B862`"]
pub struct B862_W<'a> {
w: &'a mut W,
}
impl<'a> B862_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 `B863`"]
pub type B863_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B863`"]
pub struct B863_W<'a> {
w: &'a mut W,
}
impl<'a> B863_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - B832"]
#[inline(always)]
pub fn b832(&self) -> B832_R {
B832_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - B833"]
#[inline(always)]
pub fn b833(&self) -> B833_R {
B833_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - B834"]
#[inline(always)]
pub fn b834(&self) -> B834_R {
B834_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - B835"]
#[inline(always)]
pub fn b835(&self) -> B835_R {
B835_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - B836"]
#[inline(always)]
pub fn b836(&self) -> B836_R {
B836_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - B837"]
#[inline(always)]
pub fn b837(&self) -> B837_R {
B837_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - B838"]
#[inline(always)]
pub fn b838(&self) -> B838_R {
B838_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - B839"]
#[inline(always)]
pub fn b839(&self) -> B839_R {
B839_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - B840"]
#[inline(always)]
pub fn b840(&self) -> B840_R {
B840_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - B841"]
#[inline(always)]
pub fn b841(&self) -> B841_R {
B841_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - B842"]
#[inline(always)]
pub fn b842(&self) -> B842_R {
B842_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - B843"]
#[inline(always)]
pub fn b843(&self) -> B843_R {
B843_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - B844"]
#[inline(always)]
pub fn b844(&self) -> B844_R {
B844_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - B845"]
#[inline(always)]
pub fn b845(&self) -> B845_R {
B845_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - B846"]
#[inline(always)]
pub fn b846(&self) -> B846_R {
B846_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - B847"]
#[inline(always)]
pub fn b847(&self) -> B847_R {
B847_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - B848"]
#[inline(always)]
pub fn b848(&self) -> B848_R {
B848_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - B849"]
#[inline(always)]
pub fn b849(&self) -> B849_R {
B849_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - B850"]
#[inline(always)]
pub fn b850(&self) -> B850_R {
B850_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - B851"]
#[inline(always)]
pub fn b851(&self) -> B851_R {
B851_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - B852"]
#[inline(always)]
pub fn b852(&self) -> B852_R {
B852_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - B853"]
#[inline(always)]
pub fn b853(&self) -> B853_R {
B853_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - B854"]
#[inline(always)]
pub fn b854(&self) -> B854_R {
B854_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - B855"]
#[inline(always)]
pub fn b855(&self) -> B855_R {
B855_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - B856"]
#[inline(always)]
pub fn b856(&self) -> B856_R {
B856_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - B857"]
#[inline(always)]
pub fn b857(&self) -> B857_R {
B857_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - B858"]
#[inline(always)]
pub fn b858(&self) -> B858_R {
B858_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - B859"]
#[inline(always)]
pub fn b859(&self) -> B859_R {
B859_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - B860"]
#[inline(always)]
pub fn b860(&self) -> B860_R {
B860_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - B861"]
#[inline(always)]
pub fn b861(&self) -> B861_R {
B861_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - B862"]
#[inline(always)]
pub fn b862(&self) -> B862_R {
B862_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - B863"]
#[inline(always)]
pub fn b863(&self) -> B863_R {
B863_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - B832"]
#[inline(always)]
pub fn b832(&mut self) -> B832_W {
B832_W { w: self }
}
#[doc = "Bit 1 - B833"]
#[inline(always)]
pub fn b833(&mut self) -> B833_W {
B833_W { w: self }
}
#[doc = "Bit 2 - B834"]
#[inline(always)]
pub fn b834(&mut self) -> B834_W {
B834_W { w: self }
}
#[doc = "Bit 3 - B835"]
#[inline(always)]
pub fn b835(&mut self) -> B835_W {
B835_W { w: self }
}
#[doc = "Bit 4 - B836"]
#[inline(always)]
pub fn b836(&mut self) -> B836_W {
B836_W { w: self }
}
#[doc = "Bit 5 - B837"]
#[inline(always)]
pub fn b837(&mut self) -> B837_W {
B837_W { w: self }
}
#[doc = "Bit 6 - B838"]
#[inline(always)]
pub fn b838(&mut self) -> B838_W {
B838_W { w: self }
}
#[doc = "Bit 7 - B839"]
#[inline(always)]
pub fn b839(&mut self) -> B839_W {
B839_W { w: self }
}
#[doc = "Bit 8 - B840"]
#[inline(always)]
pub fn b840(&mut self) -> B840_W {
B840_W { w: self }
}
#[doc = "Bit 9 - B841"]
#[inline(always)]
pub fn b841(&mut self) -> B841_W {
B841_W { w: self }
}
#[doc = "Bit 10 - B842"]
#[inline(always)]
pub fn b842(&mut self) -> B842_W {
B842_W { w: self }
}
#[doc = "Bit 11 - B843"]
#[inline(always)]
pub fn b843(&mut self) -> B843_W {
B843_W { w: self }
}
#[doc = "Bit 12 - B844"]
#[inline(always)]
pub fn b844(&mut self) -> B844_W {
B844_W { w: self }
}
#[doc = "Bit 13 - B845"]
#[inline(always)]
pub fn b845(&mut self) -> B845_W {
B845_W { w: self }
}
#[doc = "Bit 14 - B846"]
#[inline(always)]
pub fn b846(&mut self) -> B846_W {
B846_W { w: self }
}
#[doc = "Bit 15 - B847"]
#[inline(always)]
pub fn b847(&mut self) -> B847_W {
B847_W { w: self }
}
#[doc = "Bit 16 - B848"]
#[inline(always)]
pub fn b848(&mut self) -> B848_W {
B848_W { w: self }
}
#[doc = "Bit 17 - B849"]
#[inline(always)]
pub fn b849(&mut self) -> B849_W {
B849_W { w: self }
}
#[doc = "Bit 18 - B850"]
#[inline(always)]
pub fn b850(&mut self) -> B850_W {
B850_W { w: self }
}
#[doc = "Bit 19 - B851"]
#[inline(always)]
pub fn b851(&mut self) -> B851_W {
B851_W { w: self }
}
#[doc = "Bit 20 - B852"]
#[inline(always)]
pub fn b852(&mut self) -> B852_W {
B852_W { w: self }
}
#[doc = "Bit 21 - B853"]
#[inline(always)]
pub fn b853(&mut self) -> B853_W {
B853_W { w: self }
}
#[doc = "Bit 22 - B854"]
#[inline(always)]
pub fn b854(&mut self) -> B854_W {
B854_W { w: self }
}
#[doc = "Bit 23 - B855"]
#[inline(always)]
pub fn b855(&mut self) -> B855_W {
B855_W { w: self }
}
#[doc = "Bit 24 - B856"]
#[inline(always)]
pub fn b856(&mut self) -> B856_W {
B856_W { w: self }
}
#[doc = "Bit 25 - B857"]
#[inline(always)]
pub fn b857(&mut self) -> B857_W {
B857_W { w: self }
}
#[doc = "Bit 26 - B858"]
#[inline(always)]
pub fn b858(&mut self) -> B858_W {
B858_W { w: self }
}
#[doc = "Bit 27 - B859"]
#[inline(always)]
pub fn b859(&mut self) -> B859_W {
B859_W { w: self }
}
#[doc = "Bit 28 - B860"]
#[inline(always)]
pub fn b860(&mut self) -> B860_W {
B860_W { w: self }
}
#[doc = "Bit 29 - B861"]
#[inline(always)]
pub fn b861(&mut self) -> B861_W {
B861_W { w: self }
}
#[doc = "Bit 30 - B862"]
#[inline(always)]
pub fn b862(&mut self) -> B862_W {
B862_W { w: self }
}
#[doc = "Bit 31 - B863"]
#[inline(always)]
pub fn b863(&mut self) -> B863_W {
B863_W { w: self }
}
}
|
use std::ops::{Add, AddAssign, Mul, MulAssign};
use std::ops::{Index, IndexMut};
use super::{Vec2, Vec3, Vec4};
// Type Definitions ////////////////////////////////////////////////////////////
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct Mat2<T: Copy> {
cols: [[T; 2]; 2]
}
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct Mat3<T: Copy> {
cols: [[T; 3]; 3]
}
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct Mat4<T: Copy> {
cols: [[T; 4]; 4]
}
// Constructors ////////////////////////////////////////////////////////////////
impl<T> Mat2<T> where T: Default + Copy {
pub fn new(rows: [[T; 2]; 2]) -> Self {
Mat2 {
cols: rows
}.transpose()
}
pub fn diagnonal(i: T) -> Self {
let o = Default::default();
Mat2 {
cols: [[i, o],
[o, i]]
}
}
}
impl<T> Mat3<T> where T: Default + Copy {
pub fn new(rows: [[T; 3]; 3]) -> Self {
Mat3 {
cols: rows
}.transpose()
}
pub fn diagonal(i: T) -> Self {
let o = Default::default();
Mat3 {
cols: [[i, o, o],
[o, i, o],
[o, o, i]]
}
}
}
impl<T> Mat4<T> where T: Default + Copy {
pub fn new(rows: [[T; 4]; 4]) -> Self {
Mat4 {
cols: rows
}.transpose()
}
pub fn diagonal(i: T) -> Self {
let o = Default::default();
Mat4 {
cols: [[i, o, o, o],
[o, i, o, o],
[o, o, i, o],
[o, o, o, i]]
}
}
}
impl Mat2<f32> {
pub fn identity() -> Self { Mat2::diagnonal(1.0) }
}
impl Mat3<f32> {
pub fn identity() -> Self { Mat3::diagonal(1.0) }
}
impl Mat4<f32> {
pub fn identity() -> Self { Mat4::diagonal(1.0) }
pub fn perspective(c: f32) -> Self {
let mut p = Mat4::identity();
p[(3, 2)] = -1.0 / c;
p
}
pub fn lookat(eye: Vec3<f32>, center: Vec3<f32>, up: Vec3<f32>) -> Self {
let z = (center-eye).normalized();
let x = up.cross(z).normalized();
let y = z.cross(x).normalized();
let mut minv = Mat4::identity();
let mut tr = Mat4::identity();
for i in 0..3 {
minv[(0, i)] = x[i];
minv[(1, i)] = y[i];
minv[(2, i)] = z[i];
tr[(i, 3)] = -center[i];
}
minv * tr
}
pub fn viewport(w: i32, h: i32) -> Self {
let mut m = Mat4::identity();
let depth = 256.0;
m[(0, 3)] = w as f32 / 2.0;
m[(1, 3)] = h as f32 / 2.0;
m[(2, 3)] = depth / 2.0;
m[(0, 0)] = w as f32 / 2.0;
m[(1, 1)] = -h as f32 / 2.0;
m[(2, 2)] = depth / 2.0;
m
}
pub fn translate(offset: Vec3<f32>) -> Self {
let mut m = Mat4::identity();
for i in 0..3 { m[(0, i)] = offset[i]; }
m
}
pub fn scale(factor: Vec3<f32>) -> Self {
let mut m = Mat4::identity();
for i in 0..3 { m[(i, i)] = factor[i]; }
m
}
}
// Indexing ////////////////////////////////////////////////////////////////////
macro_rules! impl_indexing {
($M:ident $n:expr) => {
impl<T> Index<(usize, usize)> for $M<T> where T: Copy {
type Output = T;
fn index(&self, (row, col): (usize, usize)) -> &Self::Output {
assert!(row < $n);
assert!(col < $n);
&self.cols[col][row]
}
}
impl<T> IndexMut<(usize, usize)> for $M<T> where T: Copy {
fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut Self::Output {
assert!(row < $n);
assert!(col < $n);
&mut self.cols[col][row]
}
}
}
}
impl_indexing!(Mat2 2);
impl_indexing!(Mat3 3);
impl_indexing!(Mat4 4);
// Row Operations //////////////////////////////////////////////////////////////
macro_rules! impl_row_ops {
($M:ident , $V:ident , $n:expr ; $($x:expr),*) => {
impl $M<f32> {
pub fn swap_rows(&mut self, a: usize, b: usize) {
if a == b { return; }
for i in 0..$n {
let c = self[(a, i)];
self[(a, i)] = self[(b, i)];
self[(b, i)] = c;
}
}
pub fn add_row(&mut self, row: usize, other_row: $V<f32>) {
for i in 0..$n {
self[(row, i)] += other_row[i];
}
}
pub fn mul_row(&mut self, row: usize, factor: f32) {
for i in 0..$n {
self[(row, i)] *= factor;
}
}
}
impl<T> $M<T> where T: Copy {
pub fn row(&self, row: usize) -> $V<T> {
assert!(row < 4);
$V($(self[(row, $x)]),*)
}
pub fn col(&self, col: usize) -> $V<T> {
assert!(col < 4);
let col = self.cols[col];
$V($(col[$x]),*)
}
}
}
}
impl_row_ops!(Mat2, Vec2, 2; 0, 1);
impl_row_ops!(Mat3, Vec3, 3; 0, 1, 2);
impl_row_ops!(Mat4, Vec4, 4; 0, 1, 2, 3);
// Matrix Arithmetic ///////////////////////////////////////////////////////////
macro_rules! impl_ops {
($M:ident , $V:ident , $n:expr ; $($x:tt),* ) => {
impl Mul for $M<f32> {
type Output = $M<f32>;
fn mul(self, other: $M<f32>) -> Self::Output {
let mut out = $M::identity();
for row in 0..$n {
for col in 0..$n {
out[(row, col)] = self.row(row).dot(other.col(col));
}
}
out
}
}
impl<T> Mul<T> for $M<T> where T: MulAssign + Copy {
type Output = $M<T>;
fn mul(mut self, other: T) -> Self::Output {
for col in self.cols.iter_mut() {
for entry in col.iter_mut() {
*entry *= other;
}
}
self
}
}
impl Mul<$V<f32>> for $M<f32> {
type Output = $V<f32>;
fn mul(self, other: $V<f32>) -> Self::Output {
$V($(self.row($x).dot(other)),*)
// self.row(0).dot(other),
// self.row(1).dot(other),
// self.row(2).dot(other),
// self.row(3).dot(other))
}
}
impl<T> Add for $M<T> where T: AddAssign + Copy {
type Output = $M<T>;
fn add(mut self, other: $M<T>) -> Self::Output {
for row in 0..$n {
for col in 0..$n {
self[(row, col)] += other[(row, col)]
}
}
self
}
}
}
}
impl_ops!(Mat2, Vec2, 2; 0, 1);
impl_ops!(Mat3, Vec3, 3; 0, 1, 2);
impl_ops!(Mat4, Vec4, 4; 0, 1, 2, 3);
// Inversion ///////////////////////////////////////////////////////////////////
impl Mat2<f32> {
pub fn inverted(&self) -> Result<Self, ()> {
let mut other = *self;
other.invert()?;
Ok(other)
}
pub fn invert(&mut self) -> Result<(), ()> {
let (a, b, c, d) = (self[(0, 0)], self[(0, 1)], self[(1, 0)], self[(1, 1)]);
let det = a*d - b*c;
if det == 0.0 {
return Err(());
}
let fac = 1.0 / det;
*self = Mat2::new([[d * fac, -b * fac],
[-c * fac, a * fac]]);
Ok(())
}
}
macro_rules! impl_invert {
($M:ident , $n:expr) => {
impl $M<f32> {
pub fn inverted(&self) -> Result<Self, ()> {
let mut other = *self;
other.invert()?;
Ok(other)
}
pub fn invert(&mut self) -> Result<(), ()> {
let mut id: Self = Self::identity();
// Perform partial pivoting: for each row, make all of the entries above
// and below the largest number in that row a zero by performing
// elementary row operations.
for row_idx in 0..$n {
let row = self.row(row_idx);
let row_array: [f32; $n] = row.into();
let (row_max_idx, pivot) =
row_array.iter().enumerate()
.fold((0, 0.0_f32), |(i, a), (j, &b)| {
if a.abs() > b.abs() { (i, a) } else { (j, b) }
});
if pivot == 0.0 {
return Err(());
}
let id_row = id.row(row_idx);
for other_row_idx in 0..$n {
if row_idx == other_row_idx {
continue;
}
let entry = self[(other_row_idx, row_max_idx)];
let factor = -entry / pivot;
self.add_row(other_row_idx, row * factor);
self[(other_row_idx, row_max_idx)] = 0.0;
id.add_row(other_row_idx, id_row * factor);
}
}
// Swap rows to place the pivots along the diagonal
for row_idx in 0..$n {
let row = self.row(row_idx);
let row_array: [f32; $n] = row.into();
let pos = row_array.iter().position(|&x| x != 0.0)
.expect("Every row should have a nonzero value due to the early return above");
self.swap_rows(row_idx, pos);
id.swap_rows(row_idx, pos);
}
// Scale each diagonal entry to be 1
for idx in 0..$n {
let factor = 1.0/self[(idx, idx)];
// Debug
// self.mul_row(idx, factor);
id.mul_row(idx, factor);
}
*self = id;
Ok(())
}
}
}
}
impl_invert!(Mat3, 3);
impl_invert!(Mat4, 4);
// Transpose ///////////////////////////////////////////////////////////////////
macro_rules! impl_transpose {
($M:ident , $n:expr) => {
impl<T> $M<T> where T: Copy + Default {
pub fn transpose(&self) -> Self {
let mut copy = Self::default();
for i in 0..$n {
for j in 0..$n {
copy[(i, j)] = self[(j, i)];
copy[(j, i)] = self[(i, j)];
}
}
copy
}
}
}
}
impl_transpose!(Mat2, 2);
impl_transpose!(Mat3, 3);
impl_transpose!(Mat4, 4);
|
#![cfg(feature = "__ui")]
mod ui_tests {
#[test]
fn ui() {
let t = trybuild::TestCases::new();
for dir in ["nonexhaustive_ui_tests", "sabi_trait_ui_tests"] {
t.compile_fail(format!("tests/ui_tests/{}/*err.rs", dir));
t.pass(format!("tests/ui_tests/{}/*ok.rs", dir));
}
}
}
|
mod evening;
mod last_words;
mod lobby;
mod morning;
mod night;
mod vote;
pub use evening::Evening;
pub use last_words::LastWords;
pub use lobby::Lobby;
pub use morning::Morning;
pub use night::Night;
pub use vote::Vote;
|
extern crate efc_syntax;
use efc_syntax as syntax;
fn main() {
let filename = "./examples/main.ef";
let file = load_entire_file(filename).unwrap(); // TODO(zac, 4/NOV/2017): Proper error handling.
let tokens = syntax::Tokenizer::new(filename.into(), &file).tokenize();
match syntax::parse(tokens) {
Ok(_) => (),
Err(msg) => println!("{}", msg),
}
}
///
/// Load an entire file into memory in the returned string.
///
fn load_entire_file(filename: &str) -> std::io::Result<String> {
use std::fs::File;
use std::io::Read;
let mut file = File::open(filename)?;
let filesize = file.metadata()?.len() as usize;
let mut buffer = String::with_capacity(filesize);
file.read_to_string(&mut buffer)?;
Ok(buffer)
}
|
use crate::{Point, MEAN_EARTH_RADIUS};
use num_traits::{Float, FromPrimitive};
/// Determine the distance between two geometries using the [haversine formula].
///
/// [haversine formula]: https://en.wikipedia.org/wiki/Haversine_formula
pub trait HaversineDistance<T, Rhs = Self> {
/// Determine the distance between two geometries using the [haversine
/// formula].
///
/// # Units
///
/// - return value: meters
///
/// # Examples
///
/// ```
/// use geo::prelude::*;
/// use geo::Point;
///
/// // New York City
/// let p1 = Point::<f64>::from((-74.006, 40.7128));
/// // London
/// let p2 = Point::<f64>::from((-0.1278, 51.5074));
///
/// let distance = p1.haversine_distance(&p2);
///
/// assert_eq!(
/// 5_570_222., // meters
/// distance.round()
/// );
/// ```
///
/// [haversine formula]: https://en.wikipedia.org/wiki/Haversine_formula
fn haversine_distance(&self, rhs: &Rhs) -> T;
}
impl<T> HaversineDistance<T, Point<T>> for Point<T>
where
T: Float + FromPrimitive,
{
fn haversine_distance(&self, rhs: &Point<T>) -> T {
let two = T::one() + T::one();
let theta1 = self.y().to_radians();
let theta2 = rhs.y().to_radians();
let delta_theta = (rhs.y() - self.y()).to_radians();
let delta_lambda = (rhs.x() - self.x()).to_radians();
let a = (delta_theta / two).sin().powi(2)
+ theta1.cos() * theta2.cos() * (delta_lambda / two).sin().powi(2);
let c = two * a.sqrt().asin();
T::from(MEAN_EARTH_RADIUS).unwrap() * c
}
}
#[cfg(test)]
mod test {
use crate::algorithm::haversine_distance::HaversineDistance;
use crate::Point;
#[test]
fn distance1_test() {
let a = Point::<f64>::new(0., 0.);
let b = Point::<f64>::new(1., 0.);
assert_relative_eq!(
a.haversine_distance(&b),
111194.92664455874_f64,
epsilon = 1.0e-6
);
}
#[test]
fn distance2_test() {
let a = Point::new(-72.1235, 42.3521);
let b = Point::new(72.1260, 70.612);
assert_relative_eq!(
a.haversine_distance(&b),
7130570.458772508_f64,
epsilon = 1.0e-6
);
}
#[test]
fn distance3_test() {
// this input comes from issue #100
let a = Point::<f64>::new(-77.036585, 38.897448);
let b = Point::<f64>::new(-77.009080, 38.889825);
assert_relative_eq!(
a.haversine_distance(&b),
2526.820014113592_f64,
epsilon = 1.0e-6
);
}
#[test]
fn distance3_test_f32() {
// this input comes from issue #100
let a = Point::<f32>::new(-77.036585, 38.897448);
let b = Point::<f32>::new(-77.009080, 38.889825);
assert_relative_eq!(a.haversine_distance(&b), 2526.8318_f32, epsilon = 1.0e-6);
}
}
|
#[doc = "Reader of register ITLINE3"]
pub type R = crate::R<u32, super::ITLINE3>;
#[doc = "Reader of field `FLASH_ITF`"]
pub type FLASH_ITF_R = crate::R<bool, bool>;
#[doc = "Reader of field `FLASH_ECC`"]
pub type FLASH_ECC_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - FLASH_ITF"]
#[inline(always)]
pub fn flash_itf(&self) -> FLASH_ITF_R {
FLASH_ITF_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - FLASH_ECC"]
#[inline(always)]
pub fn flash_ecc(&self) -> FLASH_ECC_R {
FLASH_ECC_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
|
use std::i32;
use std::sync::atomic::Ordering;
use std::fmt::{Debug, Formatter, Result as FmtResult};
use sys::{futex_wait_bitset, futex_wake_bitset};
use integer_atomics::AtomicU32;
use lock_wrappers::raw::RwLock;
#[cfg(feature = "nightly")]
use std::intrinsics::likely;
#[inline(always)]
#[cfg(not(feature = "nightly"))]
unsafe fn likely(b: bool) -> bool { b }
/// An efficient reader-writer lock (rwlock).
///
/// To recap, the invariant is: Either multiple readers or a single writer.
///
/// This is not designed for direct use but as a building block for locks.
///
/// Thus, it is not reentrant and it may misbehave if used incorrectly
/// (i.e. you can release even if you're not even holding it).
/// It's also not fair and it is designed to always prefer writers over readers.
///
/// The lock is heavily optimized for uncontended scenarios but performance
/// should be close to ideal in any case except for when multiple writers
/// are competing with each other.
///
/// The only drawback of the implementation is that it only supports a
/// maximum of 511 simultaneous readers, queued readers and writers each.
/// Anything beyond that overflows, causing all operations on the lock
/// (starting from and including the one that overflowed it) to panic.
/// This means that the rwlock invariant can never be compromised this way.
pub struct RwFutex2 {
futex: AtomicU32,
}
const M_DEATH: u32 = 0b10100000000010000000001000000000;
const F_WRITE_SHOVE: u32 = 0b01000000000000000000000000000000;
const M_WRITERS: u32 = 0b00011111111100000000000000000000;
const M_READERS_QUEUED: u32 = 0b00000000000001111111110000000000;
const M_READERS: u32 = 0b00000000000000000000000111111111;
const ONE_WRITER: u32 = 0b00000000000100000000000000000000;
const ONE_READER_QUEUED: u32 =0b00000000000000000000010000000000;
const ONE_READER: u32 = 0b00000000000000000000000000000001;
const ID_READER: i32 = 1;
const ID_WRITER: i32 = 2;
#[inline(always)]
fn safe_add(dst: &AtomicU32, val: u32, ordering: Ordering) -> u32 {
let mut ret = dst.fetch_add(val, ordering);
if ret & M_DEATH != 0 { die(dst) }
ret = ret.wrapping_add(val);
if ret & M_DEATH != 0 { die(dst) }
ret
}
#[inline(always)]
fn safe_sub(dst: &AtomicU32, val: u32, ordering: Ordering) -> u32 {
safe_add(dst, val.wrapping_neg(), ordering)
}
#[cold]
#[inline(never)]
fn die(dst: &AtomicU32) -> ! {
// make it as unlikely as possible for any possible group
// of concurrent operations to accidentally revive this
dst.store(M_DEATH, Ordering::SeqCst);
panic!("Spontaneous futex combustion! (overflow)");
}
impl RwFutex2 {
#[inline(never)]
fn acquire_read_slow(&self, mut val: u32) {
loop {
if val & M_WRITERS == 0 {
// got it
break;
}
// writer lock - move from readers to readers_queued
val = safe_add(&self.futex, ONE_READER_QUEUED - ONE_READER, Ordering::Acquire);
if val & M_WRITERS == 0 {
// writer unlocked in the meantime - leave queue and retry
} else {
if (val & M_READERS == 0) && (val & M_WRITERS != 0) {
// fix deadlock if our temporary new reader
// interleaved with release_read() calls
// so that we reach zero HERE => might have to wake up writers
futex_wake_bitset(&self.futex, 1, ID_WRITER);
}
futex_wait_bitset(&self.futex, val, ID_READER);
}
// no longer waiting - leave the queue
val = safe_add(&self.futex, ONE_READER.wrapping_sub(ONE_READER_QUEUED), Ordering::Acquire);
}
}
#[inline(never)]
fn acquire_write_slow(&self, mut val: u32) {
let mut have_lock = false;
loop {
if have_lock {
// I'm just waiting for readers to finish
if val & M_READERS == 0 {
// got it
break;
}
} else if val & F_WRITE_SHOVE != 0 {
// I'm one of (potentially many) waiting writers
// (slow path)
// hunger games: whoever manages to eat the shove flag wins
let newval = self.futex.compare_and_swap(val, val & !F_WRITE_SHOVE, Ordering::Acquire);
if val == newval {
// we won the race -> lock is ours
break;
} else {
val = newval;
continue;
}
} else if val & M_WRITERS == ONE_WRITER {
// I'm the only writer
have_lock = true;
if val & M_READERS == 0 {
// got it!
break;
}
} // else a writer is active right now
// (slowest path - we wait)
futex_wait_bitset(&self.futex, val, ID_WRITER);
val = self.futex.load(Ordering::Acquire);
}
}
#[inline(never)]
fn release_write_slow(&self, val: u32) {
if val & M_WRITERS != 0 {
// there are other writers waiting
// we set the shove flag to signal that one of them may wake up now
self.futex.fetch_or(F_WRITE_SHOVE, Ordering::Release);
futex_wake_bitset(&self.futex, 1, ID_WRITER);
} else {
// no writers -> wake up readers (if any)
if val & M_READERS_QUEUED != 0 {
futex_wake_bitset(&self.futex, i32::MAX as u32, ID_READER);
}
}
}
}
impl RwLock for RwFutex2 {
type ReadLockState = ();
type WriteLockState = ();
/// Acquires a read lock.
///
/// This blocks until the lock is ours.
#[inline]
fn acquire_read(&self) {
let val = safe_add(&self.futex, ONE_READER, Ordering::Acquire);
if unsafe { likely(val & M_WRITERS == 0) } {
// got it
return;
}
self.acquire_read_slow(val)
}
/// Acquries a write lock.
///
/// This blocks until the lock is ours.
#[inline]
fn acquire_write(&self) {
let val = safe_add(&self.futex, ONE_WRITER, Ordering::Acquire);
if unsafe { likely((val & F_WRITE_SHOVE == 0)
&& (val & M_WRITERS == ONE_WRITER)
&& (val & M_READERS == 0)) } {
// got it
return;
}
self.acquire_write_slow(val)
}
/// Releases a read lock.
#[inline]
fn release_read(&self, _: ()) {
let val = safe_sub(&self.futex, ONE_READER, Ordering::Release);
if (val & M_READERS == 0) && (val & M_WRITERS != 0) {
// was 1 => now 0 => no more readers => writers queued => wake one up
futex_wake_bitset(&self.futex, 1, ID_WRITER);
}
}
/// Releases a write lock.
#[inline]
fn release_write(&self, _: ()) {
let val = safe_sub(&self.futex, ONE_WRITER, Ordering::Release);
if unsafe { likely((val & M_WRITERS == 0)
&& (val & M_READERS_QUEUED == 0)) } {
return;
}
self.release_write_slow(val)
}
}
impl Default for RwFutex2 {
/// Creates a new instance.
fn default() -> RwFutex2 {
RwFutex2 {
futex: AtomicU32::new(0),
}
}
}
impl Debug for RwFutex2 {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "RwFutex@{:p} (=0x{:08x})", &self.futex as *const _,
self.futex.load(Ordering::SeqCst))
}
}
|
#[cfg(feature = "redis-backend")]
use redis::RedisError;
use serde_json::Error as SerdeError;
use std::error::Error;
use std::fmt;
// use api::error::APIError;
#[cfg(feature = "dynamo-backend")]
use storage::dynamo::DynamoError;
#[cfg(feature = "mongo-backend")]
use storage::mongo::MongoError;
#[derive(Debug)]
pub enum BannerError {
// APIError(APIError),
CachePoisonedError,
FailedToParsePath,
#[cfg(feature = "dynamo-backend")] DynamoFailure(DynamoError),
#[cfg(feature = "mongo-backend")] MongoFailure(MongoError),
#[cfg(feature = "redis-backend")] RedisFailure(RedisError),
#[cfg(feature = "redis-backend")] InvalidRedisConfig,
AllCacheMissing,
FailedToSerializeItem,
UpdatedAtPoisoned
}
#[cfg(feature = "dynamo-backend")]
impl From<DynamoError> for BannerError {
fn from(err: DynamoError) -> BannerError {
BannerError::DynamoFailure(err)
}
}
#[cfg(feature = "redis-backend")]
impl From<RedisError> for BannerError {
fn from(err: RedisError) -> BannerError {
BannerError::RedisFailure(err)
}
}
#[cfg(feature = "mongo-backend")]
impl From<MongoError> for BannerError {
fn from(err: MongoError) -> BannerError {
BannerError::MongoFailure(err)
}
}
impl From<SerdeError> for BannerError {
fn from(_: SerdeError) -> BannerError {
BannerError::FailedToSerializeItem
}
}
impl Error for BannerError {
fn description(&self) -> &str {
""
}
}
impl fmt::Display for BannerError {
fn fmt(&self, _: &mut fmt::Formatter) -> Result<(), fmt::Error> {
Ok(())
}
}
|
extern crate oxygengine_animation as anim;
extern crate oxygengine_core as core;
#[cfg(feature = "script-flow")]
extern crate oxygengine_script_flow as flow;
pub mod background;
pub mod character;
pub mod dialogue;
pub mod resource;
pub mod scene;
pub mod script;
pub mod story;
pub mod system;
pub mod vn_story_asset_protocol;
#[cfg(test)]
mod tests;
pub mod prelude {
pub use crate::background::*;
pub use crate::character::*;
pub use crate::dialogue::*;
pub use crate::resource::*;
pub use crate::scene::*;
pub use crate::script::*;
pub use crate::story::*;
pub use crate::system::*;
pub use crate::vn_story_asset_protocol::*;
}
use crate::system::VnStorySystem;
use anim::curve::{Curved, CurvedDistance, CurvedOffset};
use core::{app::AppBuilder, assets::database::AssetsDatabase, Ignite, Scalar};
use serde::{Deserialize, Serialize};
use std::ops::{Add, Mul, Sub};
pub type Scale = Position;
#[derive(Ignite, Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct Position(pub Scalar, pub Scalar);
impl Curved for Position {
fn zero() -> Self {
Self(0.0, 0.0)
}
fn one() -> Self {
Self(1.0, 1.0)
}
fn negate(&self) -> Self {
Self(-self.0, -self.1)
}
fn get_axis(&self, index: usize) -> Option<Scalar> {
match index {
0 => Some(self.0),
1 => Some(self.1),
_ => None,
}
}
fn interpolate(&self, other: &Self, factor: Scalar) -> Self {
let diff = *other - *self;
diff * factor + *self
}
}
impl CurvedDistance for Position {
fn curved_distance(&self, other: &Self) -> Scalar {
let diff0 = other.0 - self.0;
let diff1 = other.1 - self.1;
(diff0 * diff0 + diff1 * diff1).sqrt()
}
}
impl CurvedOffset for Position {
fn curved_offset(&self, other: &Self) -> Self {
*self + *other
}
}
impl Add<Self> for Position {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0, self.1 + other.1)
}
}
impl Sub<Self> for Position {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self(self.0 - other.0, self.1 - other.1)
}
}
impl Mul<Scalar> for Position {
type Output = Self;
fn mul(self, other: Scalar) -> Self {
Self(self.0 * other, self.1 * other)
}
}
impl From<(Scalar, Scalar)> for Position {
fn from(value: (Scalar, Scalar)) -> Self {
Self(value.0, value.1)
}
}
impl From<[Scalar; 2]> for Position {
fn from(value: [Scalar; 2]) -> Self {
Self(value[0], value[1])
}
}
#[derive(Ignite, Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct Color(pub Scalar, pub Scalar, pub Scalar);
impl Curved for Color {
fn zero() -> Self {
Self(0.0, 0.0, 0.0)
}
fn one() -> Self {
Self(1.0, 1.0, 1.0)
}
fn negate(&self) -> Self {
Self(-self.0, -self.1, -self.2)
}
fn get_axis(&self, index: usize) -> Option<Scalar> {
match index {
0 => Some(self.0),
1 => Some(self.1),
2 => Some(self.2),
_ => None,
}
}
fn interpolate(&self, other: &Self, factor: Scalar) -> Self {
let diff = *other - *self;
diff * factor + *self
}
}
impl CurvedDistance for Color {
fn curved_distance(&self, other: &Self) -> Scalar {
let diff0 = other.0 - self.0;
let diff1 = other.1 - self.1;
let diff2 = other.2 - self.2;
(diff0 * diff0 + diff1 * diff1 + diff2 * diff2).sqrt()
}
}
impl CurvedOffset for Color {
fn curved_offset(&self, other: &Self) -> Self {
*self + *other
}
}
impl Add<Self> for Color {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(self.0 + other.0, self.1 + other.1, self.2 + other.2)
}
}
impl Sub<Self> for Color {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self(self.0 - other.0, self.1 - other.1, self.2 - other.2)
}
}
impl Mul<Scalar> for Color {
type Output = Self;
fn mul(self, other: Scalar) -> Self {
Self(self.0 * other, self.1 * other, self.2 * other)
}
}
impl From<(Scalar, Scalar, Scalar)> for Color {
fn from(value: (Scalar, Scalar, Scalar)) -> Self {
Self(value.0, value.1, value.2)
}
}
impl From<[Scalar; 3]> for Color {
fn from(value: [Scalar; 3]) -> Self {
Self(value[0], value[1], value[2])
}
}
pub fn bundle_installer(builder: &mut AppBuilder, _: ()) {
builder.install_system(VnStorySystem::default(), "vn-story", &[]);
}
pub fn protocols_installer(database: &mut AssetsDatabase) {
database.register(vn_story_asset_protocol::VnStoryAssetProtocol);
}
|
// vim: et sw=4 ts=4
extern crate chrono;
extern crate hyper;
extern crate hyper_tls;
extern crate irc;
extern crate serde;
extern crate serde_json;
extern crate tokio_core;
extern crate url;
mod dark_sky;
mod serde_utils;
//mod formatters;
use std::rc::Rc;
//use formatters::standard;
use futures::Future;
use futures::IntoFuture;
use irc::client::prelude::*;
use irc::client::Client;
use tokio_core::reactor;
//use open_weather_map::response::CityResponse;
fn process_message(reactor_handle: Rc<reactor::Handle>, irc_client: Rc<IrcClient>, message: Message) -> Result<(), irc::error::IrcError>
{
println!("{:?}", message);
if let Command::PRIVMSG(ref _target, ref msg) = message.command {
if msg.starts_with("!w ") {
let irc_client = Rc::clone(&irc_client);
match irc_client.config().get_option("darksky_key") {
Some(key) => {
let target = message.response_target().unwrap().to_owned();
let (latitude, longitude) = (29.7594,-95.3594);
let response = dark_sky::forecast(key, latitude, longitude)
.and_then(move |forecast| {
println!("Forecast: {:?}", forecast);
irc_client.send_privmsg(target, format!("{:?}", forecast)).unwrap();
Ok(())
})
.map_err(|e| {
println!("Error requesting API response: {:?}", e);
});
reactor_handle.spawn(response);
}
None => irc_client.send_privmsg(message.response_target().unwrap(), format!("Error: I can't find my Open Weather Map API Key. Set openweathermap_appid in my config.toml.")).unwrap(),
}
}
}
Ok(())
}
fn main() {
let config = Config::load("config.toml").expect("Error loading config file");
let mut irc_reactor = IrcReactor::new().unwrap();
let client = Rc::new(irc_reactor.prepare_client_and_connect(&config).unwrap());
client.identify().unwrap();
let reactor_handle = Rc::new(irc_reactor.inner_handle());
let processor = client.stream().for_each(move |message| {
reactor_handle.spawn(process_message(Rc::clone(&reactor_handle), Rc::clone(&client), message).into_future().map_err(|_| (())));
Ok(())
});
irc_reactor.register_future(processor);
irc_reactor.run().unwrap();
}
|
use std::fmt::Write as FormatWrite;
use std::io;
use std::io::Write;
use termion;
use backend::*;
use output_log::*;
pub struct Console <'a> {
status_tick_sequence: & 'a [String],
error_handler: Box <Fn (io::Error) + Send>,
columns: u16,
status_lines: u16,
}
impl <'a> Console <'a> {
pub fn new (
error_handler: Box <Fn (io::Error) + Send>,
status_tick_sequence: & 'a [String],
) -> Console <'a> {
let columns =
match termion::terminal_size () {
Ok ((columns, _rows)) =>
columns,
Err (_) => 80,
};
Console {
status_tick_sequence: status_tick_sequence,
error_handler: error_handler,
columns: columns,
status_lines: 0,
}
}
fn write_message (
& self,
target: & mut FormatWrite,
message: & str,
) {
write! (
target,
"{}{}\r\n",
message,
termion::clear::AfterCursor,
).unwrap ();
}
fn write_running (
& self,
target: & mut FormatWrite,
message: & str,
status: Option <& str>,
) {
if let Some (status) = status {
write! (
target,
"{} ... {}{}\r\n",
if message.len () <= self.columns as usize - status.len () - 5 {
& message
} else {
& message [0 .. self.columns as usize - status.len () - 5]
},
status,
termion::clear::AfterCursor,
).unwrap ();
} else {
write! (
target,
"{} ...{}\r\n",
if message.len () <= self.columns as usize - 4 {
& message
} else {
& message [0 .. self.columns as usize - 4]
},
termion::clear::AfterCursor,
).unwrap ();
}
}
}
impl <'a> Backend for Console <'a> {
fn update (
& mut self,
logs: & [OutputLogInternal],
) {
let mut buffer =
String::new ();
// move up to the start
if self.status_lines > 0 {
write! (
buffer,
"\r{}",
termion::cursor::Up (
self.status_lines),
).unwrap ();
}
// output logs
let old_status_lines = self.status_lines;
self.status_lines = 0;
for log in logs {
if log.state () == OutputLogState::Message {
self.write_message (
& mut buffer,
log.message ());
} else if log.state () == OutputLogState::Complete {
self.write_running (
& mut buffer,
log.message (),
Some ("done"));
}
}
for log in logs {
if log.state () == OutputLogState::Removed
|| log.state () == OutputLogState::Message
|| log.state () == OutputLogState::Complete {
continue;
}
if log.state () == OutputLogState::Running
|| self.status_lines > 0 {
self.status_lines += 1;
}
if log.state () == OutputLogState::Running {
if log.denominator () > 0 {
let percent_string =
format! (
"{}%",
log.numerator () * 100 / log.denominator ());
self.write_running (
& mut buffer,
log.message (),
Some (& percent_string));
} else if log.tick () > 0 {
let tick_string =
& self.status_tick_sequence [
(log.tick () as usize - 1)
% self.status_tick_sequence.len ()];
self.write_running (
& mut buffer,
log.message (),
Some (& tick_string));
} else {
self.write_running (
& mut buffer,
log.message (),
None);
}
} else if log.state () == OutputLogState::Incomplete {
self.write_running (
& mut buffer,
log.message (),
Some ("abort"));
} else {
unreachable! ();
}
}
if self.status_lines < old_status_lines {
for _index in 0 .. (old_status_lines - self.status_lines) {
write! (
buffer,
"{}\n",
termion::clear::CurrentLine,
).unwrap ();
}
write! (
buffer,
"{}",
termion::cursor::Up (
old_status_lines - self.status_lines),
).unwrap ();
}
write! (
io::stderr (),
"{}",
buffer,
).unwrap_or_else (
|error|
(self.error_handler) (
error)
);
}
fn synchronous (& self) -> bool {
false
}
}
// ex: noet ts=4 filetype=rust
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::convert::TryInto;
use std::error::Error;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use async_channel::Receiver;
use async_channel::Sender;
use common_arrow::arrow_format::flight::data::Action;
use common_arrow::arrow_format::flight::data::FlightData;
use common_arrow::arrow_format::flight::data::Ticket;
use common_arrow::arrow_format::flight::service::flight_service_client::FlightServiceClient;
use common_base::base::tokio::time::Duration;
use common_base::runtime::GlobalIORuntime;
use common_base::runtime::TrySpawn;
use common_exception::ErrorCode;
use common_exception::Result;
use futures::StreamExt;
use tonic::transport::channel::Channel;
use tonic::Request;
use tonic::Status;
use tonic::Streaming;
use crate::api::rpc::flight_actions::FlightAction;
use crate::api::rpc::packets::DataPacket;
use crate::api::rpc::request_builder::RequestBuilder;
pub struct FlightClient {
inner: FlightServiceClient<Channel>,
}
// TODO: Integration testing required
impl FlightClient {
pub fn new(inner: FlightServiceClient<Channel>) -> FlightClient {
FlightClient { inner }
}
pub async fn execute_action(&mut self, action: FlightAction, timeout: u64) -> Result<()> {
if let Err(cause) = self.do_action(action, timeout).await {
return Err(cause.add_message_back("(while in query flight)"));
}
Ok(())
}
pub async fn request_server_exchange(
&mut self,
query_id: &str,
target: &str,
) -> Result<FlightExchange> {
let mut streaming = self
.get_streaming(
RequestBuilder::create(Ticket::default())
.with_metadata("x-type", "request_server_exchange")?
.with_metadata("x-target", target)?
.with_metadata("x-query-id", query_id)?
.build(),
)
.await?;
let (tx, rx) = async_channel::bounded(1);
GlobalIORuntime::instance().spawn({
async move {
while let Some(message) = streaming.next().await {
if tx.send(message.map_err(ErrorCode::from)).await.is_err() {
break;
}
}
tx.close();
}
});
Ok(FlightExchange::create_receiver(rx))
}
pub async fn do_get(
&mut self,
query_id: &str,
target: &str,
fragment: usize,
) -> Result<FlightExchange> {
let mut streaming = self
.get_streaming(
RequestBuilder::create(Ticket::default())
.with_metadata("x-type", "exchange_fragment")?
.with_metadata("x-target", target)?
.with_metadata("x-query-id", query_id)?
.with_metadata("x-fragment-id", &fragment.to_string())?
.build(),
)
.await?;
let (tx, rx) = async_channel::bounded(1);
GlobalIORuntime::instance().spawn({
async move {
while let Some(message) = streaming.next().await {
if tx.send(message.map_err(ErrorCode::from)).await.is_err() {
break;
}
}
tx.close();
}
});
Ok(FlightExchange::create_receiver(rx))
}
async fn get_streaming(&mut self, request: Request<Ticket>) -> Result<Streaming<FlightData>> {
match self.inner.do_get(request).await {
Ok(res) => Ok(res.into_inner()),
Err(status) => Err(ErrorCode::from(status).add_message_back("(while in query flight)")),
}
}
// Execute do_action.
#[tracing::instrument(level = "debug", skip_all)]
async fn do_action(&mut self, action: FlightAction, timeout: u64) -> Result<Vec<u8>> {
let action: Action = action.try_into()?;
let action_type = action.r#type.clone();
let request = Request::new(action);
let mut request = common_tracing::inject_span_to_tonic_request(request);
request.set_timeout(Duration::from_secs(timeout));
let response = self.inner.do_action(request).await?;
match response.into_inner().message().await? {
Some(response) => Ok(response.body),
None => Err(ErrorCode::EmptyDataFromServer(format!(
"Can not receive data from flight server, action: {:?}",
action_type
))),
}
}
}
pub struct FlightReceiver {
state: Arc<State>,
dropped: AtomicBool,
rx: Receiver<Result<FlightData>>,
}
impl Drop for FlightReceiver {
fn drop(&mut self) {
self.close();
}
}
impl FlightReceiver {
pub fn create(rx: Receiver<Result<FlightData>>) -> FlightReceiver {
FlightReceiver {
rx,
state: State::create(),
dropped: AtomicBool::new(false),
}
}
pub async fn recv(&self) -> Result<Option<DataPacket>> {
match self.rx.recv().await {
Err(_) => Ok(None),
Ok(Err(error)) => Err(error),
Ok(Ok(message)) => Ok(Some(DataPacket::try_from(message)?)),
}
}
pub fn close(&self) {
#[allow(clippy::collapsible_if)]
if !self.dropped.fetch_or(true, Ordering::SeqCst) {
if self.state.strong_count.fetch_sub(1, Ordering::SeqCst) == 1 {
self.rx.close();
}
}
}
}
pub struct FlightSender {
state: Arc<State>,
dropped: AtomicBool,
tx: Sender<Result<FlightData, Status>>,
}
impl Clone for FlightSender {
fn clone(&self) -> Self {
self.state.strong_count.fetch_add(1, Ordering::SeqCst);
FlightSender {
tx: self.tx.clone(),
state: self.state.clone(),
dropped: AtomicBool::new(false),
}
}
}
impl Drop for FlightSender {
fn drop(&mut self) {
self.close();
}
}
impl FlightSender {
pub fn create(tx: Sender<Result<FlightData, Status>>) -> FlightSender {
FlightSender {
state: State::create(),
dropped: AtomicBool::new(false),
tx,
}
}
pub async fn send(&self, data: DataPacket) -> Result<()> {
if let Err(_cause) = self.tx.send(Ok(FlightData::from(data))).await {
return Err(ErrorCode::AbortedQuery(
"Aborted query, because the remote flight channel is closed.",
));
}
Ok(())
}
pub fn close(&self) {
#[allow(clippy::collapsible_if)]
if !self.dropped.fetch_or(true, Ordering::SeqCst) {
if self.state.strong_count.fetch_sub(1, Ordering::SeqCst) == 1 {
self.tx.close();
}
}
}
}
pub struct State {
strong_count: AtomicUsize,
}
impl State {
pub fn create() -> Arc<State> {
Arc::new(State {
strong_count: AtomicUsize::new(0),
})
}
}
pub enum FlightExchange {
Dummy,
Receiver {
state: Arc<State>,
receiver: Receiver<Result<FlightData>>,
},
Sender {
state: Arc<State>,
sender: Sender<Result<FlightData, Status>>,
},
}
impl FlightExchange {
pub fn create_sender(sender: Sender<Result<FlightData, Status>>) -> FlightExchange {
FlightExchange::Sender {
sender,
state: State::create(),
}
}
pub fn create_receiver(receiver: Receiver<Result<FlightData>>) -> FlightExchange {
FlightExchange::Receiver {
receiver,
state: State::create(),
}
}
pub fn as_sender(&self) -> FlightSender {
match self {
FlightExchange::Sender { state, sender } => {
state.strong_count.fetch_add(1, Ordering::SeqCst);
FlightSender {
tx: sender.clone(),
state: state.clone(),
dropped: AtomicBool::new(false),
}
}
_ => unreachable!(),
}
}
pub fn as_receiver(&self) -> FlightReceiver {
match self {
FlightExchange::Receiver { state, receiver } => {
state.strong_count.fetch_add(1, Ordering::SeqCst);
FlightReceiver {
rx: receiver.clone(),
state: state.clone(),
dropped: AtomicBool::new(false),
}
}
_ => unreachable!(),
}
}
}
#[allow(dead_code)]
fn match_for_io_error(err_status: &Status) -> Option<&std::io::Error> {
let mut err: &(dyn Error + 'static) = err_status;
loop {
if let Some(io_err) = err.downcast_ref::<std::io::Error>() {
return Some(io_err);
}
// h2::Error do not expose std::io::Error with `source()`
// https://github.com/hyperium/h2/pull/462
use h2::Error as h2Error;
if let Some(h2_err) = err.downcast_ref::<h2Error>() {
if let Some(io_err) = h2_err.get_io() {
return Some(io_err);
}
}
err = match err.source() {
Some(err) => err,
None => return None,
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.