text stringlengths 8 4.13M |
|---|
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add_two_ints(a: u32, b: u32) -> u32 {
a + b
}
#[wasm_bindgen]
pub fn fib(n: i32) -> i32 {
if n == 0 || n == 1 {
return n;
}
fib(n - 1) + fib(n + 2)
}
fn main() {
println!("Hello World");
let r = add_two_ints(1, 2);
println!("{}", r);
} |
pub mod http_status;
pub mod response_helper;
|
use axgeom::*;
pub struct Symbol<'a>{
inner:&'a [Vec2<usize>]
}
impl<'a> Symbol<'a>{
pub fn get(&self)->&[Vec2<usize>]{
self.inner
}
pub fn into_inner(self)->&'a [Vec2<usize>]{
self.inner
}
}
pub struct SymbolTable{
inner:Vec<Vec<Vec2<usize>>>
}
impl SymbolTable{
pub fn lookup(&self,num:usize)->Symbol{
Symbol{inner:&self.inner[num]}
}
pub fn new(table:&str,word_height:usize,num_words:usize)->SymbolTable{
let mut words=Vec::with_capacity(num_words);
for index in 0..num_words{
words.push(Self::get(table,word_height,index));
}
SymbolTable{inner:words}
}
///Create some misc symbols. Look at static strings in the source code
///to figure out which ones.
fn get(table:&str,word_height:usize,num:usize)->Vec<Vec2<usize>>{
let b=table.lines().skip(1).skip(word_height*num).take(word_height);
let mut vec=Vec::new();
for (y,line) in b.enumerate(){
for (x,c) in line.chars().enumerate(){
if c=="0".chars().next().unwrap(){
vec.push(vec2(x,y));
}
}
}
vec
}
} |
//! The AUTHENTICATE_MESSAGE defines an NTLM authenticate message that is sent from the client
//! to the server after the CHALLENGE_MESSAGE is processed by the client.
use super::{AvPair, DomainNameFields, Version, WorkstationFields};
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Authenticate {
/// LmChallengeResponseFields (8 bytes): A field containing LmChallengeResponse information.
///
/// If the client chooses to send an LmChallengeResponse to the server, the fields are set.
///
/// Otherwise, if the client chooses not to send an LmChallengeResponse to the server,
/// the fields take the following values:
/// - LmChallengeResponseLen and LmChallengeResponseMaxLen MUST be set to zero on transmission.
/// - LmChallengeResponseBufferOffset field SHOULD be set to the offset from the beginning of
/// the AUTHENTICATE_MESSAGE to where the LmChallengeResponse would be in Payload if it was present.
pub lm_challenge_response_fields: LmChallengeResponseFields,
/// NtChallengeResponseFields (8 bytes): A field containing NtChallengeResponse information.
///
/// If the client chooses to send an NtChallengeResponse to the server, the fields are set.
///
/// Otherwise, if the client chooses not to send an NtChallengeResponse to the server,
/// the fields take the following values:
/// - NtChallengeResponseLen, and NtChallengeResponseMaxLen MUST be set to zero on transmission.
/// - NtChallengeResponseBufferOffset field SHOULD be set to the offset from the beginning of the
/// AUTHENTICATE_MESSAGE to where the NtChallengeResponse would be in Payload if it was present.
pub nt_challenge_response_fields: NtChallengeResponseFields,
/// DomainNameFields (8 bytes): A field containing DomainName information.
///
/// If the client chooses to send a DomainName to the server, the fields are set.
///
/// Otherwise, if the client chooses not to send a DomainName to the server,
/// the fields take the following values:
/// - DomainNameLen and DomainNameMaxLen MUST be set to zero on transmission.
/// - DomainNameBufferOffset field SHOULD be set to the offset from the beginning
/// of the AUTHENTICATE_MESSAGE to where the DomainName would be in Payload if it was present.
pub domain_name_fields: DomainNameFields,
/// UserNameFields (8 bytes): A field containing UserName information.
///
/// If the client chooses to send a UserName to the server, the fields are set.
///
/// Otherwise, if the client chooses not to send a UserName to the server,
/// the fields take the following values:
/// - UserNameLen and UserNameMaxLen MUST be set to zero on transmission.
/// - UserNameBufferOffset field SHOULD be set to the offset from the beginning of the
/// AUTHENTICATE_MESSAGE to where the UserName would be in Payload if it were present.
pub user_name_fields: UserNameFields,
/// WorkstationFields (8 bytes): A field containing Workstation information.
///
/// If the client chooses to send a Workstation to the server, the fields are set.
///
/// Othewise, if the client chooses not to send a Workstation to the server,
/// the fields take the following values:
/// - WorkstationLen and WorkstationMaxLen MUST be set to zero on transmission.
/// - WorkstationBufferOffset field SHOULD be set to the offset from the beginning
/// of the AUTHENTICATE_MESSAGE to where the Workstation would be in Payload if it was present.
pub workstation_fields: WorkstationFields,
/// EncryptedRandomSessionKeyFields (8 bytes): A field containing EncryptedRandomSessionKey information.
///
/// If the NTLMSSP_NEGOTIATE_KEY_EXCH flag is set in NegotiateFlags, indicating that an
/// EncryptedRandomSessionKey is supplied, the fields are set.
///
/// Otherwise, if the NTLMSSP_NEGOTIATE_KEY_EXCH flag is not set in NegotiateFlags, indicating that an
/// EncryptedRandomSessionKey is not supplied, the fields take the following values, and must be
/// ignored upon receipt:
/// - EncryptedRandomSessionKeyLen and EncryptedRandomSessionKeyMaxLen SHOULD be set to zero on transmission.
/// - EncryptedRandomSessionKeyBufferOffset field SHOULD be set to the offset from the beginning of the
/// AUTHENTICATE_MESSAGE to where the EncryptedRandomSessionKey would be in Payload if it was present.
pub encrypted_random_session_key_fields: EncryptedRandomSessionKeyFields,
/// NegotiateFlags (4 bytes): In connectionless mode, a NEGOTIATE structure that contains a set of
/// flags and represents the conclusion of negotiation—the choices the client has made from the
/// options the server offered in the CHALLENGE_MESSAGE. In connection-oriented mode, a NEGOTIATE
/// structure that contains the set of bit flags negotiated in the previous messages.
/// The values for the negotiate flags should be taken from the Corresponding bitflag struct.
pub negotiate_flags: Vec<u8>,
/// Version (8 bytes): A VERSION structure that is populated only when the NTLMSSP_NEGOTIATE_VERSION
/// flag is set in the NegotiateFlags field. This structure is used for debugging purposes only.
/// In normal protocol messages, it is ignored and does not affect the NTLM message processing.
pub version: Version,
/// MIC (16 bytes): The message integrity for the NTLM NEGOTIATE_MESSAGE, CHALLENGE_MESSAGE, and AUTHENTICATE_MESSAGE.
pub mic: Vec<u8>,
/// Payload (variable): A byte array that contains the data referred to by the LmChallengeResponseBufferOffset,
/// NtChallengeResponseBufferOffset, DomainNameBufferOffset, UserNameBufferOffset, WorkstationBufferOffset,
/// and EncryptedRandomSessionKeyBufferOffset message fields. Payload data can be present in any order within
/// the Payload field, with variable-length padding before or after the data. The data that can be present
/// in the Payload field of this message, in no particular order.
pub payload: Payload,
}
impl Authenticate {
/// Creates a new instance of the NTLM Authenticate message.
pub fn default() -> Self {
Authenticate {
lm_challenge_response_fields: LmChallengeResponseFields::default(),
nt_challenge_response_fields: NtChallengeResponseFields::default(),
domain_name_fields: DomainNameFields::default(),
user_name_fields: UserNameFields::default(),
workstation_fields: WorkstationFields::default(),
encrypted_random_session_key_fields: EncryptedRandomSessionKeyFields::default(),
negotiate_flags: Vec::new(),
version: Version::default(),
mic: Vec::new(),
payload: Payload::default(),
}
}
}
/// LmChallengeResponseFields (8 bytes): A field containing LmChallengeResponse information.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LmChallengeResponseFields {
/// LmChallengeResponseLen (2 bytes): A 16-bit unsigned integer that defines the size,
/// in bytes, of LmChallengeResponse in Payload.
pub lm_challenge_response_len: Vec<u8>,
/// LmChallengeResponseMaxLen (2 bytes): A 16-bit unsigned integer that SHOULD be set
/// to the value of LmChallengeResponseLen and MUST be ignored on receipt.
pub lm_challenge_response_max_len: Vec<u8>,
/// LmChallengeResponseBufferOffset (4 bytes): A 32-bit unsigned integer that defines
/// the offset, in bytes, from the beginning of the AUTHENTICATE_MESSAGE to
/// LmChallengeResponse in Payload.
pub lm_challenge_response_buffer_offset: Vec<u8>,
}
impl LmChallengeResponseFields {
/// Creates a new instance of Lm Challenge Response Fields.
pub fn default() -> Self {
LmChallengeResponseFields {
lm_challenge_response_len: Vec::new(),
lm_challenge_response_max_len: Vec::new(),
lm_challenge_response_buffer_offset: Vec::new(),
}
}
}
/// NtChallengeResponseFields (8 bytes): A field containing NtChallengeResponse information.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NtChallengeResponseFields {
/// NtChallengeResponseLen (2 bytes): A 16-bit unsigned integer that defines the size,
/// in bytes, of NtChallengeResponse in Payload.
pub nt_challenge_response_len: Vec<u8>,
/// NtChallengeResponseMaxLen (2 bytes): A 16-bit unsigned integer that SHOULD be set
/// to the value of NtChallengeResponseLen and MUST be ignored on receipt.
pub nt_challenge_response_max_len: Vec<u8>,
/// NtChallengeResponseBufferOffset (4 bytes): A 32-bit unsigned integer that
/// defines the offset, in bytes, from the beginning of the AUTHENTICATE_MESSAGE to
/// NtChallengeResponse in Payload.
pub nt_challenge_response_buffer_offset: Vec<u8>,
}
impl NtChallengeResponseFields {
/// Creates a new instance of the NT Challenge Response Fields.
pub fn default() -> Self {
NtChallengeResponseFields {
nt_challenge_response_len: Vec::new(),
nt_challenge_response_max_len: Vec::new(),
nt_challenge_response_buffer_offset: Vec::new(),
}
}
}
/// UserNameFields (8 bytes): A field containing UserName information.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct UserNameFields {
/// UserNameLen (2 bytes): A 16-bit unsigned integer that defines the size,
/// in bytes, of UserName in Payload, not including a NULL terminator.
pub user_name_len: Vec<u8>,
/// UserNameMaxLen (2 bytes): A 16-bit unsigned integer that SHOULD
/// be set to the value of UserNameLen and MUST be ignored on receipt.
pub user_name_max_len: Vec<u8>,
/// UserNameBufferOffset (4 bytes): A 32-bit unsigned integer that defines the offset,
/// in bytes, from the beginning of the AUTHENTICATE_MESSAGE to UserName in Payload.
/// If the UserName to be sent contains a Unicode string, the values of UserNameBufferOffset
/// and UserNameLen MUST be multiples of 2.
pub user_name_buffer_offset: Vec<u8>,
}
impl UserNameFields {
/// Creates a new intance of user name fields.
pub fn default() -> Self {
UserNameFields {
user_name_len: Vec::new(),
user_name_max_len: Vec::new(),
user_name_buffer_offset: Vec::new(),
}
}
}
/// EncryptedRandomSessionKeyFields (8 bytes): A field containing EncryptedRandomSessionKey information.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct EncryptedRandomSessionKeyFields {
/// EncryptedRandomSessionKeyLen (2 bytes): A 16-bit unsigned integer that
/// defines the size, in bytes, of EncryptedRandomSessionKey in Payload.
pub encrypted_random_session_key_len: Vec<u8>,
/// EncryptedRandomSessionKeyMaxLen (2 bytes): A 16-bit unsigned integer
/// that SHOULD be set to the value of EncryptedRandomSessionKeyLen and
/// MUST be ignored on receipt.
pub encrypted_random_session_key_max_len: Vec<u8>,
/// EncryptedRandomSessionKeyBufferOffset (4 bytes): A 32-bit unsigned
/// integer that defines the offset, in bytes, from the beginning of the
/// AUTHENTICATE_MESSAGE to EncryptedRandomSessionKey in Payload.
pub encrypted_random_session_key_buffer_offset: Vec<u8>,
}
impl EncryptedRandomSessionKeyFields {
/// Creates a new instance of Encrypted Random Session Key Fields.
pub fn default() -> Self {
EncryptedRandomSessionKeyFields {
encrypted_random_session_key_len: Vec::new(),
encrypted_random_session_key_max_len: Vec::new(),
encrypted_random_session_key_buffer_offset: Vec::new(),
}
}
}
/// Payload (variable): A byte array that contains the data referred to by the LmChallengeResponseBufferOffset,
/// NtChallengeResponseBufferOffset, DomainNameBufferOffset, UserNameBufferOffset, WorkstationBufferOffset,
/// and EncryptedRandomSessionKeyBufferOffset message fields. Payload data can be present in any order within
/// the Payload field, with variable-length padding before or after the data. The data that can be present in
/// the Payload field of this message, in no particular order.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Payload {
/// LmChallengeResponse (variable): An LM_RESPONSE structure or an LMv2_RESPONSE structure
/// that contains the computed LM response to the challenge. If NTLM v2 authentication is configured,
/// then LmChallengeResponse MUST be an LMv2_RESPONSE structure. Otherwise, it MUST be an LM_RESPONSE structure.
pub lm_challenge_response: Vec<u8>,
/// NtChallengeResponse (variable): An NTLM_RESPONSE structure or NTLMv2_RESPONSE structure that contains the
/// computed NT response to the challenge. If NTLM v2 authentication is configured, NtChallengeResponse
/// MUST be an NTLMv2_RESPONSE. Otherwise, it MUST be an NTLM_RESPONSE.
pub nt_challenge_response: NtlmV2Response,
/// DomainName (variable): The domain or computer name hosting the user account.
/// DomainName MUST be encoded in the negotiated character set.
pub domain_name: Vec<u8>,
/// UserName (variable): The name of the user to be authenticated.
/// UserName MUST be encoded in the negotiated character set.
pub user_name: Vec<u8>,
/// Workstation (variable): The name of the computer to which the user is logged on.
/// Workstation MUST be encoded in the negotiated character set.
pub workstation: Vec<u8>,
/// EncryptedRandomSessionKey (variable): The client's encrypted random session key.
pub encrypted_random_session_key: Vec<u8>,
}
impl Payload {
/// Creates a new instance of the NTLM Authenticate Payload.
pub fn default() -> Self {
Payload {
lm_challenge_response: Vec::new(),
nt_challenge_response: NtlmV2Response::default(),
domain_name: Vec::new(),
user_name: Vec::new(),
workstation: Vec::new(),
encrypted_random_session_key: Vec::new(),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NtlmV2Response {
/// Response (16 bytes): A 16-byte array of unsigned char that contains the
/// client's NTChallengeResponse. Response corresponds to the NTProofStr variable.
pub response: Vec<u8>,
/// NTLMv2_CLIENT_CHALLENGE (variable): A variable-length byte array, that contains
/// the ClientChallenge. ChallengeFromClient corresponds to the temp variable.
pub ntlmv2_client_challenge: NtlmV2ClientChallenge,
}
impl NtlmV2Response {
pub fn default() -> Self {
NtlmV2Response {
response: Vec::new(),
ntlmv2_client_challenge: NtlmV2ClientChallenge::default(),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NtlmV2ClientChallenge {
/// RespType (1 byte): An 8-bit unsigned char that
/// contains the current version of the challenge response type.
/// This field MUST be 0x01.
pub resp_type: Vec<u8>,
/// HiRespType (1 byte): An 8-bit unsigned char that contains
/// the maximum supported version of the challenge response type.
/// This field MUST be 0x01.
pub hi_resp_type: Vec<u8>,
/// Reserved1 (2 bytes): A 16-bit unsigned integer that SHOULD
/// be 0x0000 and MUST be ignored on receipt.
pub reserved1: Vec<u8>,
/// Reserved2 (4 bytes): A 32-bit unsigned integer that SHOULD
/// be 0x00000000 and MUST be ignored on receipt.
pub reserved2: Vec<u8>,
/// TimeStamp (8 bytes): A 64-bit unsigned integer that contains
/// the current system time, represented as the number of 100
/// nanosecond ticks elapsed since midnight of January 1, 1601 (UTC).
pub time_stamp: Vec<u8>,
/// ChallengeFromClient (8 bytes): An 8-byte array of unsigned char
/// that contains the client's ClientChallenge.
pub challenge_from_client: Vec<u8>,
/// Reserved3 (4 bytes): A 32-bit unsigned integer that SHOULD
/// be 0x00000000 and MUST be ignored on receipt.
pub reserved3: Vec<u8>,
/// AvPairs (variable): A byte array that contains a sequence of
/// AV_PAIR structures. The sequence contains the server-naming
/// context and is terminated by an AV_PAIR structure with an AvId field of MsvAvEOL.
pub av_pairs: Vec<AvPair>,
}
impl NtlmV2ClientChallenge {
pub fn default() -> Self {
NtlmV2ClientChallenge {
resp_type: vec![1],
hi_resp_type: vec![1],
reserved1: vec![0; 2],
reserved2: vec![0; 4],
time_stamp: vec![0; 8],
challenge_from_client: b"\x22\x10\x50\xcd\x22\xf4\xa4\x14".to_vec(),
reserved3: vec![0; 4],
av_pairs: Vec::new(),
}
}
}
|
extern crate gl;
use cgmath::{Matrix4, perspective, Deg};
use std::ptr;
use crate::entities::entity::Entity;
use crate::shaders::static_shader::StaticShader;
use crate::toolbox::math;
const FOV: f32 = 70.0;
const NEAR_PLANE: f32 = 0.1;
const FAR_PLANE: f32 = 1000.0;
pub fn initialize(shader: &StaticShader) {
let projection_matrix = create_projection_matrix();
shader.program.start();
shader.load_projection_matrix(&projection_matrix);
shader.program.stop();
}
fn create_projection_matrix() -> Matrix4<f32> {
let aspect_ratio = crate::WIDTH as f32 / crate::HEIGHT as f32;
return perspective(Deg(FOV), aspect_ratio, NEAR_PLANE, FAR_PLANE);
}
pub fn prepare() {
unsafe {
gl::Enable(gl::DEPTH_TEST);
gl::Clear(gl::COLOR_BUFFER_BIT|gl::DEPTH_BUFFER_BIT);
gl::ClearColor(1.0, 0.0, 0.0, 1.0);
}
}
pub fn render(entity: &Entity, shader: &StaticShader) {
let model = entity.get_model();
let raw_model = model.get_raw_model();
unsafe {
gl::BindVertexArray(*raw_model.vao_id());
gl::EnableVertexAttribArray(0);
gl::EnableVertexAttribArray(1);
let transformation_matrix = math::create_transformation_matrix(
entity.get_position(),
*entity.get_rot_x(),
*entity.get_rot_y(),
*entity.get_rot_z(),
*entity.get_scale()
);
shader.load_transformation_matrix(&transformation_matrix);
gl::ActiveTexture(gl::TEXTURE0);
gl::BindTexture(gl::TEXTURE_2D, *model.get_texture().get_texture_id());
gl::DrawElements(gl::TRIANGLES, *raw_model.vertex_count(), gl::UNSIGNED_INT, ptr::null());
gl::DisableVertexAttribArray(0);
gl::DisableVertexAttribArray(1);
gl::BindVertexArray(0);
}
}
|
//https://leetcode.com/problems/find-center-of-star-graph/submissions/
impl Solution {
pub fn find_center(edges: Vec<Vec<i32>>) -> i32 {
let mut ans = 0;
let mut cnt: Vec<i32> = vec![0; 100001];
for i in 0..edges.len() {
cnt[edges[i][0] as usize] += 1;
cnt[edges[i][1] as usize] += 1;
if cnt[edges[i][0] as usize] == 2 {
ans = edges[i][0];
} else if cnt[edges[i][1] as usize] == 2 {
ans = edges[i][1];
}
}
ans
}
} |
use std::io::Cursor;
use crate::end_to_end_cases::{
server::TestService,
test_utils::{Fixture, RecordingSink},
};
use assert_matches::assert_matches;
use grpc_binary_logger_proto::{
grpc_log_entry::{EventType, Payload},
ClientHeader, Message, Metadata, MetadataEntry, ServerHeader, Trailer,
};
use grpc_binary_logger_test_proto::{TestRequest, TestResponse};
use prost::Message as _;
use tonic::{metadata::MetadataValue, Code};
#[tokio::test]
async fn test_unary() {
let sink = RecordingSink::new();
let fixture = Fixture::new(TestService, sink.clone())
.await
.expect("fixture");
const BASE: u64 = 1;
{
let mut client = fixture.client.clone();
let mut req = tonic::Request::new(TestRequest { question: BASE });
req.metadata_mut().insert(
"my-client-header",
MetadataValue::from_static("my-client-header-value"),
);
let res = client.test_unary(req).await.expect("no errors");
assert_eq!(res.into_inner().answer, BASE + 1);
}
let entries = sink.entries();
assert_eq!(entries.len(), 5);
let entry = &entries[0];
assert_eq!(entry.r#type(), EventType::ClientHeader);
assert_matches!(
entry.payload,
Some(Payload::ClientHeader(ClientHeader {
ref method_name,
metadata: Some(Metadata{ref entry}), ..
})) => {
assert_eq!(method_name, "/test.Test/TestUnary");
assert_matches!(entry[..], [
MetadataEntry{ref key, ref value, ..},
] if key == "my-client-header" && value == b"my-client-header-value");
}
);
let entry = &entries[1];
assert_eq!(entry.r#type(), EventType::ClientMessage);
assert_matches!(
entry.payload,
Some(Payload::Message(Message{length, ref data})) => {
assert_eq!(data.len(), length as usize);
let message = TestRequest::decode(Cursor::new(data)).expect("valid proto");
assert_eq!(message.question, BASE);
}
);
let entry = &entries[2];
assert_eq!(entry.r#type(), EventType::ServerHeader);
assert_matches!(
entry.payload,
Some(Payload::ServerHeader(ServerHeader {
metadata: Some(Metadata{ref entry}), ..
})) => {
assert_matches!(entry[..], [
MetadataEntry{ref key, ref value, ..},
] if key == "my-server-header" && value == b"my-server-header-value");
}
);
let entry = &entries[3];
assert_eq!(entry.r#type(), EventType::ServerMessage);
assert_matches!(
entry.payload,
Some(Payload::Message(Message{length, ref data})) => {
assert_eq!(data.len(), length as usize);
let message = TestResponse::decode(Cursor::new(data)).unwrap();
assert_eq!(message.answer, BASE+1);
}
);
let entry = &entries[4];
assert_eq!(entry.r#type(), EventType::ServerTrailer);
assert_matches!(entry.payload, Some(Payload::Trailer(Trailer { .. })));
}
#[tokio::test]
async fn test_unary_error() {
let sink = RecordingSink::new();
let fixture = Fixture::new(TestService, sink.clone())
.await
.expect("fixture");
{
let mut client = fixture.client.clone();
let err = client
.test_unary(TestRequest { question: 42 })
.await
.expect_err("should fail");
assert_eq!(err.code(), Code::InvalidArgument);
assert_eq!(err.message(), "The Answer is not a question");
}
let entries = sink.entries();
assert_eq!(entries.len(), 4);
let entry = &entries[3];
assert_eq!(entry.r#type(), EventType::ServerTrailer);
assert_matches!(
entry.payload,
Some(Payload::Trailer(Trailer { status_code, .. })) => {
assert_eq!(status_code, Code::InvalidArgument as u32);
}
);
}
|
use std::{
pin::Pin,
task::{Context, Poll},
};
use crate::{actor::Actor, fut::future::ActorFuture};
mod and_then;
mod map_err;
mod map_ok;
pub use and_then::AndThen;
pub use map_err::MapErr;
pub use map_ok::MapOk;
mod private_try_act_future {
use super::{Actor, ActorFuture};
pub trait Sealed<A> {}
impl<A, F, T, E> Sealed<A> for F
where
A: Actor,
F: ?Sized + ActorFuture<A, Output = Result<T, E>>,
{
}
}
/// A convenience for actor futures that return `Result` values that includes
/// a variety of adapters tailored to such actor futures.
pub trait ActorTryFuture<A: Actor>: ActorFuture<A> + private_try_act_future::Sealed<A> {
/// The type of successful values yielded by this actor future
type Ok;
/// The type of failures yielded by this actor future
type Error;
/// Poll this `ActorTryFuture` as if it were a `ActorFuture`.
///
/// This method is a stopgap for a compiler limitation that prevents us from
/// directly inheriting from the `ActorFuture` trait; in the actor future it
/// won't be needed.
fn try_poll(
self: Pin<&mut Self>,
srv: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<Result<Self::Ok, Self::Error>>;
}
impl<A, F, T, E> ActorTryFuture<A> for F
where
A: Actor,
F: ActorFuture<A, Output = Result<T, E>> + ?Sized,
{
type Ok = T;
type Error = E;
fn try_poll(
self: Pin<&mut Self>,
srv: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<F::Output> {
self.poll(srv, ctx, task)
}
}
/// Adapters specific to [`Result`]-returning actor futures
pub trait ActorTryFutureExt<A: Actor>: ActorTryFuture<A> {
/// Executes another actor future after this one resolves successfully.
/// The success value is passed to a closure to create this subsequent
/// actor future.
///
/// The provided closure `f` will only be called if this actor future is
/// resolved to an [`Ok`]. If this actor future resolves to an [`Err`],
/// panics, or is dropped, then the provided closure will never
/// be invoked. The [`Error`](ActorTryFuture::Error) type of
/// this actor future and the actor future returned by `f` have to match.
///
/// Note that this method consumes the actor future it is called on and
/// returns a wrapped version of it.
fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where
F: FnOnce(Self::Ok, &mut A, &mut A::Context) -> Fut,
Fut: ActorTryFuture<A, Error = Self::Error>,
Self: Sized,
{
and_then::new(self, f)
}
/// Maps this actor future's success value to a different value.
///
/// This method can be used to change the [`Ok`](ActorTryFuture::Ok) type
/// of the actor future into a different type. It is similar to the
/// [`Result::map`] method. You can use this method to chain along a
/// computation once the actor future has been resolved.
///
/// The provided closure `f` will only be called if this actor future is
/// resolved to an [`Ok`]. If it resolves to an [`Err`], panics, or is
/// dropped, then the provided closure will never be invoked.
///
/// Note that this method consumes the actor future it is called on and
/// returns a wrapped version of it.
fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where
F: FnOnce(Self::Ok, &mut A, &mut A::Context) -> T,
Self: Sized,
{
MapOk::new(self, f)
}
/// Maps this actor future's error value to a different value.
///
/// This method can be used to change the [`Error`](ActorTryFuture::Error)
/// type of the actor future into a different type. It is similar to the
/// [`Result::map_err`] method.
///
/// The provided closure `f` will only be called if this actor future is
/// resolved to an [`Err`]. If it resolves to an [`Ok`], panics, or is
/// dropped, then the provided closure will never be invoked.
///
/// Note that this method consumes the actor future it is called on and
/// returns a wrapped version of it.
fn map_err<T, F>(self, f: F) -> MapErr<Self, F>
where
F: FnOnce(Self::Error, &mut A, &mut A::Context) -> T,
Self: Sized,
{
MapErr::new(self, f)
}
}
impl<A, F> ActorTryFutureExt<A> for F
where
A: Actor,
F: ActorTryFuture<A> + ?Sized,
{
}
|
use super::*;
pub struct SincronizadorCoordinador {
pub jugadores_handler: Vec<thread::JoinHandle<()>>,
pub jugadores_channels: Vec<Sender<mazo::Carta>>,
pub jugadores_ronda: Vec<Sender<bool>>,
pub pilon_central_cartas: Receiver<juego::Jugada>,
pub barrier: Arc<Barrier>
}
pub struct SincronizadorJugador{
pub cartas_receiver: Receiver<mazo::Carta>,
pub ronda_receiver: Receiver<bool>,
pub pilon_central_cartas: Sender<juego::Jugada>,
pub barrier: Arc<Barrier>
} |
extern crate winrt_notification;
use std::path::Path;
use winrt_notification::{
IconCrop,
Toast,
};
fn main() {
Toast::new("application that needs a toast with an image")
.hero(&Path::new("C:\\absolute\\path\\to\\image.jpeg"), "alt text")
.icon(
&Path::new("c:/this/style/works/too/image.png"),
IconCrop::Circular,
"alt text",
)
.title("Lots of pictures here")
.text1("One above the text as the hero")
.text2("One to the left as an icon, and several below")
.image(&Path::new("c:/photos/sun.png"), "the sun")
.image(&Path::new("c:/photos/moon.png"), "the moon")
.sound(None) // will be silent
.show()
.expect("notification failed");
}
|
//! inversion id type
use std::sync::Arc;
/// inversion id type
#[derive(
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
serde::Serialize,
serde::Deserialize,
)]
pub struct InvId(Arc<str>);
impl InvId {
/// inversion id constructor
pub fn new_raw(s: Box<str>) -> Self {
Self(s.into())
}
/// construct a new anonymous InvId
pub fn new_anon() -> Self {
Self::new_categorized(
"anon",
"anon",
crate::inv_uniq::InvUniq::default().as_ref(),
)
}
/// construct a new category prefixed InvId
pub fn new_categorized(
prefix_1: &str,
prefix_2: &str,
identity: &str,
) -> Self {
Self::new_raw(
format!("{}.{}.{}", prefix_1, prefix_2, identity).into_boxed_str(),
)
}
}
impl std::fmt::Debug for InvId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvId:{}", self.0)
}
}
impl std::fmt::Display for InvId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl AsRef<str> for InvId {
fn as_ref(&self) -> &str {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_inv_id() {
println!("{}", InvId::new_anon());
println!("{}", InvId::new_categorized("net", "rpc", "json"));
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use common_datavalues as dv;
use common_expression::ColumnId;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ColumnStatistics {
pub min: dv::DataValue,
pub max: dv::DataValue,
// A non-backward compatible change has been introduced by [PR#6067](https://github.com/datafuselabs/databend/pull/6067/files#diff-20030750809780d6492d2fe215a8eb80294aa6a8a5af2cf1bebe17eb740cae35)
// , please also see [issue#6556](https://github.com/datafuselabs/databend/issues/6556)
// therefore, we alias `null_count` with `unset_bits`, to make subsequent versions backward compatible again
#[serde(alias = "unset_bits")]
pub null_count: u64,
pub in_memory_size: u64,
pub distinct_of_values: Option<u64>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ClusterStatistics {
#[serde(default = "default_cluster_key_id")]
pub cluster_key_id: u32,
pub min: Vec<dv::DataValue>,
pub max: Vec<dv::DataValue>,
// The number of times the data in that block has been clustered. New blocks has zero level.
#[serde(default = "default_level")]
pub level: i32,
}
fn default_cluster_key_id() -> u32 {
0
}
fn default_level() -> i32 {
0
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Statistics {
pub row_count: u64,
pub block_count: u64,
#[serde(default)]
pub perfect_block_count: u64,
pub uncompressed_byte_size: u64,
pub compressed_byte_size: u64,
#[serde(default)]
pub index_size: u64,
pub col_stats: HashMap<ColumnId, ColumnStatistics>,
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Web_Http_Diagnostics")]
pub mod Diagnostics;
#[cfg(feature = "Web_Http_Filters")]
pub mod Filters;
#[cfg(feature = "Web_Http_Headers")]
pub mod Headers;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpBufferContent(pub ::windows::core::IInspectable);
impl HttpBufferContent {
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Storage_Streams")]
pub fn CreateFromBuffer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(content: Param0) -> ::windows::core::Result<HttpBufferContent> {
Self::IHttpBufferContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), content.into_param().abi(), &mut result__).from_abi::<HttpBufferContent>(result__)
})
}
#[cfg(feature = "Storage_Streams")]
pub fn CreateFromBufferWithOffset<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IBuffer>>(content: Param0, offset: u32, count: u32) -> ::windows::core::Result<HttpBufferContent> {
Self::IHttpBufferContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), content.into_param().abi(), offset, count, &mut result__).from_abi::<HttpBufferContent>(result__)
})
}
pub fn IHttpBufferContentFactory<R, F: FnOnce(&IHttpBufferContentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpBufferContent, IHttpBufferContentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpBufferContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpBufferContent;{6b14a441-fba7-4bd2-af0a-839de7c295da})");
}
unsafe impl ::windows::core::Interface for HttpBufferContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl ::windows::core::RuntimeName for HttpBufferContent {
const NAME: &'static str = "Windows.Web.Http.HttpBufferContent";
}
impl ::core::convert::From<HttpBufferContent> for ::windows::core::IUnknown {
fn from(value: HttpBufferContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpBufferContent> for ::windows::core::IUnknown {
fn from(value: &HttpBufferContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpBufferContent {
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 HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpBufferContent> for ::windows::core::IInspectable {
fn from(value: HttpBufferContent) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpBufferContent> for ::windows::core::IInspectable {
fn from(value: &HttpBufferContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpBufferContent {
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 HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<HttpBufferContent> for IHttpContent {
fn from(value: HttpBufferContent) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&HttpBufferContent> for IHttpContent {
fn from(value: &HttpBufferContent) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for &HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpBufferContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpBufferContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpBufferContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpBufferContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpBufferContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpBufferContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpBufferContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpBufferContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpBufferContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpBufferContent {}
unsafe impl ::core::marker::Sync for HttpBufferContent {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpClient(pub ::windows::core::IInspectable);
impl HttpClient {
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<HttpClient, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Foundation")]
pub fn DeleteAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetWithOptionAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0, completionoption: HttpCompletionOption) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), uri.into_param().abi(), completionoption, &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn GetBufferAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, HttpProgress>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn GetInputStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetStringAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn PostAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, IHttpContent>>(&self, uri: Param0, content: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), uri.into_param().abi(), content.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn PutAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, IHttpContent>>(&self, uri: Param0, content: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), uri.into_param().abi(), content.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SendRequestAsync<'a, Param0: ::windows::core::IntoParam<'a, HttpRequestMessage>>(&self, request: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), request.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SendRequestWithOptionAsync<'a, Param0: ::windows::core::IntoParam<'a, HttpRequestMessage>>(&self, request: Param0, completionoption: HttpCompletionOption) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), request.into_param().abi(), completionoption, &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>>(result__)
}
}
#[cfg(feature = "Web_Http_Headers")]
pub fn DefaultRequestHeaders(&self) -> ::windows::core::Result<Headers::HttpRequestHeaderCollection> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<Headers::HttpRequestHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Web_Http_Filters")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, Filters::IHttpFilter>>(filter: Param0) -> ::windows::core::Result<HttpClient> {
Self::IHttpClientFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), filter.into_param().abi(), &mut result__).from_abi::<HttpClient>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn TryDeleteAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryGetAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryGetAsync2<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0, completionoption: HttpCompletionOption) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), uri.into_param().abi(), completionoption, &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryGetBufferAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpGetBufferResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpGetBufferResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryGetInputStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpGetInputStreamResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpGetInputStreamResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryGetStringAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpGetStringResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpGetStringResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryPostAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, IHttpContent>>(&self, uri: Param0, content: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), uri.into_param().abi(), content.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryPutAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, IHttpContent>>(&self, uri: Param0, content: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), uri.into_param().abi(), content.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TrySendRequestAsync<'a, Param0: ::windows::core::IntoParam<'a, HttpRequestMessage>>(&self, request: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), request.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TrySendRequestAsync2<'a, Param0: ::windows::core::IntoParam<'a, HttpRequestMessage>>(&self, request: Param0, completionoption: HttpCompletionOption) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>> {
let this = &::windows::core::Interface::cast::<IHttpClient2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), request.into_param().abi(), completionoption, &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<HttpRequestResult, HttpProgress>>(result__)
}
}
pub fn IHttpClientFactory<R, F: FnOnce(&IHttpClientFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpClient, IHttpClientFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpClient {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpClient;{7fda1151-3574-4880-a8ba-e6b1e0061f3d})");
}
unsafe impl ::windows::core::Interface for HttpClient {
type Vtable = IHttpClient_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7fda1151_3574_4880_a8ba_e6b1e0061f3d);
}
impl ::windows::core::RuntimeName for HttpClient {
const NAME: &'static str = "Windows.Web.Http.HttpClient";
}
impl ::core::convert::From<HttpClient> for ::windows::core::IUnknown {
fn from(value: HttpClient) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpClient> for ::windows::core::IUnknown {
fn from(value: &HttpClient) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpClient {
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 HttpClient {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpClient> for ::windows::core::IInspectable {
fn from(value: HttpClient) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpClient> for ::windows::core::IInspectable {
fn from(value: &HttpClient) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpClient {
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 HttpClient {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpClient> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpClient) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpClient> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpClient) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpClient {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpClient {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpClient> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpClient) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpClient> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpClient) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpClient {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpClient {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpClient {}
unsafe impl ::core::marker::Sync for HttpClient {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HttpCompletionOption(pub i32);
impl HttpCompletionOption {
pub const ResponseContentRead: HttpCompletionOption = HttpCompletionOption(0i32);
pub const ResponseHeadersRead: HttpCompletionOption = HttpCompletionOption(1i32);
}
impl ::core::convert::From<i32> for HttpCompletionOption {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HttpCompletionOption {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for HttpCompletionOption {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Web.Http.HttpCompletionOption;i4)");
}
impl ::windows::core::DefaultType for HttpCompletionOption {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpCookie(pub ::windows::core::IInspectable);
impl HttpCookie {
pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Domain(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Path(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Expires(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetExpires<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Foundation::DateTime>>>(&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() }
}
pub fn HttpOnly(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetHttpOnly(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Secure(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetSecure(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Value(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetValue<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Create<'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>>(name: Param0, domain: Param1, path: Param2) -> ::windows::core::Result<HttpCookie> {
Self::IHttpCookieFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), name.into_param().abi(), domain.into_param().abi(), path.into_param().abi(), &mut result__).from_abi::<HttpCookie>(result__)
})
}
pub fn IHttpCookieFactory<R, F: FnOnce(&IHttpCookieFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpCookie, IHttpCookieFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpCookie {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpCookie;{1f5488e2-cc2d-4779-86a7-88f10687d249})");
}
unsafe impl ::windows::core::Interface for HttpCookie {
type Vtable = IHttpCookie_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f5488e2_cc2d_4779_86a7_88f10687d249);
}
impl ::windows::core::RuntimeName for HttpCookie {
const NAME: &'static str = "Windows.Web.Http.HttpCookie";
}
impl ::core::convert::From<HttpCookie> for ::windows::core::IUnknown {
fn from(value: HttpCookie) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpCookie> for ::windows::core::IUnknown {
fn from(value: &HttpCookie) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpCookie {
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 HttpCookie {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpCookie> for ::windows::core::IInspectable {
fn from(value: HttpCookie) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpCookie> for ::windows::core::IInspectable {
fn from(value: &HttpCookie) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpCookie {
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 HttpCookie {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpCookie> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpCookie) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpCookie> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpCookie) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpCookie {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpCookie {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpCookie {}
unsafe impl ::core::marker::Sync for HttpCookie {}
#[cfg(feature = "Foundation_Collections")]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpCookieCollection(pub ::windows::core::IInspectable);
#[cfg(feature = "Foundation_Collections")]
impl HttpCookieCollection {
#[cfg(feature = "Foundation_Collections")]
pub fn GetAt(&self, index: u32) -> ::windows::core::Result<HttpCookie> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), index, &mut result__).from_abi::<HttpCookie>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Size(&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__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn IndexOf<'a, Param0: ::windows::core::IntoParam<'a, HttpCookie>>(&self, value: Param0, index: &mut u32) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi(), index, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn GetMany(&self, startindex: u32, items: &mut [<HttpCookie as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), startindex, items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn First(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IIterator<HttpCookie>> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::Collections::IIterable<HttpCookie>>(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::IIterator<HttpCookie>>(result__)
}
}
}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::windows::core::RuntimeType for HttpCookieCollection {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpCookieCollection;pinterface({bbe1fa4c-b0e3-4583-baef-1f1b2e483e56};rc(Windows.Web.Http.HttpCookie;{1f5488e2-cc2d-4779-86a7-88f10687d249})))");
}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::windows::core::Interface for HttpCookieCollection {
type Vtable = super::super::Foundation::Collections::IVectorView_abi<HttpCookie>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::Foundation::Collections::IVectorView<HttpCookie> as ::windows::core::RuntimeType>::SIGNATURE);
}
#[cfg(feature = "Foundation_Collections")]
impl ::windows::core::RuntimeName for HttpCookieCollection {
const NAME: &'static str = "Windows.Web.Http.HttpCookieCollection";
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<HttpCookieCollection> for ::windows::core::IUnknown {
fn from(value: HttpCookieCollection) -> Self {
value.0 .0
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<&HttpCookieCollection> for ::windows::core::IUnknown {
fn from(value: &HttpCookieCollection) -> Self {
value.0 .0.clone()
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<HttpCookieCollection> for ::windows::core::IInspectable {
fn from(value: HttpCookieCollection) -> Self {
value.0
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<&HttpCookieCollection> for ::windows::core::IInspectable {
fn from(value: &HttpCookieCollection) -> Self {
value.0.clone()
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<HttpCookieCollection> for super::super::Foundation::Collections::IVectorView<HttpCookie> {
fn from(value: HttpCookieCollection) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<&HttpCookieCollection> for super::super::Foundation::Collections::IVectorView<HttpCookie> {
fn from(value: &HttpCookieCollection) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVectorView<HttpCookie>> for HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IVectorView<HttpCookie>> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVectorView<HttpCookie>> for &HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IVectorView<HttpCookie>> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<HttpCookieCollection> for super::super::Foundation::Collections::IIterable<HttpCookie> {
type Error = ::windows::core::Error;
fn try_from(value: HttpCookieCollection) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<&HttpCookieCollection> for super::super::Foundation::Collections::IIterable<HttpCookie> {
type Error = ::windows::core::Error;
fn try_from(value: &HttpCookieCollection) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<HttpCookie>> for HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<HttpCookie>> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<HttpCookie>> for &HttpCookieCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<HttpCookie>> {
::core::convert::TryInto::<super::super::Foundation::Collections::IIterable<HttpCookie>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::core::marker::Send for HttpCookieCollection {}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::core::marker::Sync for HttpCookieCollection {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for HttpCookieCollection {
type Item = HttpCookie;
type IntoIter = super::super::Foundation::Collections::VectorViewIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &HttpCookieCollection {
type Item = HttpCookie;
type IntoIter = super::super::Foundation::Collections::VectorViewIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
super::super::Foundation::Collections::VectorViewIterator::new(::core::convert::TryInto::try_into(self).ok())
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpCookieManager(pub ::windows::core::IInspectable);
impl HttpCookieManager {
pub fn SetCookie<'a, Param0: ::windows::core::IntoParam<'a, HttpCookie>>(&self, cookie: Param0) -> ::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), cookie.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetCookieWithThirdParty<'a, Param0: ::windows::core::IntoParam<'a, HttpCookie>>(&self, cookie: Param0, thirdparty: bool) -> ::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), cookie.into_param().abi(), thirdparty, &mut result__).from_abi::<bool>(result__)
}
}
pub fn DeleteCookie<'a, Param0: ::windows::core::IntoParam<'a, HttpCookie>>(&self, cookie: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() }
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn GetCookies<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, uri: Param0) -> ::windows::core::Result<HttpCookieCollection> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<HttpCookieCollection>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for HttpCookieManager {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpCookieManager;{7a431780-cd4f-4e57-a84a-5b0a53d6bb96})");
}
unsafe impl ::windows::core::Interface for HttpCookieManager {
type Vtable = IHttpCookieManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a431780_cd4f_4e57_a84a_5b0a53d6bb96);
}
impl ::windows::core::RuntimeName for HttpCookieManager {
const NAME: &'static str = "Windows.Web.Http.HttpCookieManager";
}
impl ::core::convert::From<HttpCookieManager> for ::windows::core::IUnknown {
fn from(value: HttpCookieManager) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpCookieManager> for ::windows::core::IUnknown {
fn from(value: &HttpCookieManager) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpCookieManager {
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 HttpCookieManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpCookieManager> for ::windows::core::IInspectable {
fn from(value: HttpCookieManager) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpCookieManager> for ::windows::core::IInspectable {
fn from(value: &HttpCookieManager) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpCookieManager {
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 HttpCookieManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for HttpCookieManager {}
unsafe impl ::core::marker::Sync for HttpCookieManager {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpFormUrlEncodedContent(pub ::windows::core::IInspectable);
impl HttpFormUrlEncodedContent {
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Foundation_Collections")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>>>(content: Param0) -> ::windows::core::Result<HttpFormUrlEncodedContent> {
Self::IHttpFormUrlEncodedContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), content.into_param().abi(), &mut result__).from_abi::<HttpFormUrlEncodedContent>(result__)
})
}
pub fn IHttpFormUrlEncodedContentFactory<R, F: FnOnce(&IHttpFormUrlEncodedContentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpFormUrlEncodedContent, IHttpFormUrlEncodedContentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpFormUrlEncodedContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpFormUrlEncodedContent;{6b14a441-fba7-4bd2-af0a-839de7c295da})");
}
unsafe impl ::windows::core::Interface for HttpFormUrlEncodedContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl ::windows::core::RuntimeName for HttpFormUrlEncodedContent {
const NAME: &'static str = "Windows.Web.Http.HttpFormUrlEncodedContent";
}
impl ::core::convert::From<HttpFormUrlEncodedContent> for ::windows::core::IUnknown {
fn from(value: HttpFormUrlEncodedContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpFormUrlEncodedContent> for ::windows::core::IUnknown {
fn from(value: &HttpFormUrlEncodedContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpFormUrlEncodedContent {
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 HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpFormUrlEncodedContent> for ::windows::core::IInspectable {
fn from(value: HttpFormUrlEncodedContent) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpFormUrlEncodedContent> for ::windows::core::IInspectable {
fn from(value: &HttpFormUrlEncodedContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpFormUrlEncodedContent {
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 HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<HttpFormUrlEncodedContent> for IHttpContent {
fn from(value: HttpFormUrlEncodedContent) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&HttpFormUrlEncodedContent> for IHttpContent {
fn from(value: &HttpFormUrlEncodedContent) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for &HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpFormUrlEncodedContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpFormUrlEncodedContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpFormUrlEncodedContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpFormUrlEncodedContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpFormUrlEncodedContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpFormUrlEncodedContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpFormUrlEncodedContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpFormUrlEncodedContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpFormUrlEncodedContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpFormUrlEncodedContent {}
unsafe impl ::core::marker::Sync for HttpFormUrlEncodedContent {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpGetBufferResult(pub ::windows::core::IInspectable);
impl HttpGetBufferResult {
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ExtendedError(&self) -> ::windows::core::Result<::windows::core::HRESULT> {
let this = self;
unsafe {
let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HRESULT>(result__)
}
}
pub fn RequestMessage(&self) -> ::windows::core::Result<HttpRequestMessage> {
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::<HttpRequestMessage>(result__)
}
}
pub fn ResponseMessage(&self) -> ::windows::core::Result<HttpResponseMessage> {
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::<HttpResponseMessage>(result__)
}
}
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Storage_Streams")]
pub fn Value(&self) -> ::windows::core::Result<super::super::Storage::Streams::IBuffer> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IBuffer>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for HttpGetBufferResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpGetBufferResult;{53d08e7c-e209-404e-9a49-742d8236fd3a})");
}
unsafe impl ::windows::core::Interface for HttpGetBufferResult {
type Vtable = IHttpGetBufferResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53d08e7c_e209_404e_9a49_742d8236fd3a);
}
impl ::windows::core::RuntimeName for HttpGetBufferResult {
const NAME: &'static str = "Windows.Web.Http.HttpGetBufferResult";
}
impl ::core::convert::From<HttpGetBufferResult> for ::windows::core::IUnknown {
fn from(value: HttpGetBufferResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpGetBufferResult> for ::windows::core::IUnknown {
fn from(value: &HttpGetBufferResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpGetBufferResult {
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 HttpGetBufferResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpGetBufferResult> for ::windows::core::IInspectable {
fn from(value: HttpGetBufferResult) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpGetBufferResult> for ::windows::core::IInspectable {
fn from(value: &HttpGetBufferResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpGetBufferResult {
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 HttpGetBufferResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpGetBufferResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpGetBufferResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpGetBufferResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpGetBufferResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpGetBufferResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpGetBufferResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpGetBufferResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpGetBufferResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpGetBufferResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpGetBufferResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpGetBufferResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpGetBufferResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpGetBufferResult {}
unsafe impl ::core::marker::Sync for HttpGetBufferResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpGetInputStreamResult(pub ::windows::core::IInspectable);
impl HttpGetInputStreamResult {
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ExtendedError(&self) -> ::windows::core::Result<::windows::core::HRESULT> {
let this = self;
unsafe {
let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HRESULT>(result__)
}
}
pub fn RequestMessage(&self) -> ::windows::core::Result<HttpRequestMessage> {
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::<HttpRequestMessage>(result__)
}
}
pub fn ResponseMessage(&self) -> ::windows::core::Result<HttpResponseMessage> {
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::<HttpResponseMessage>(result__)
}
}
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Storage_Streams")]
pub fn Value(&self) -> ::windows::core::Result<super::super::Storage::Streams::IInputStream> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IInputStream>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for HttpGetInputStreamResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpGetInputStreamResult;{d5d63463-13aa-4ee0-be95-a0c39fe91203})");
}
unsafe impl ::windows::core::Interface for HttpGetInputStreamResult {
type Vtable = IHttpGetInputStreamResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5d63463_13aa_4ee0_be95_a0c39fe91203);
}
impl ::windows::core::RuntimeName for HttpGetInputStreamResult {
const NAME: &'static str = "Windows.Web.Http.HttpGetInputStreamResult";
}
impl ::core::convert::From<HttpGetInputStreamResult> for ::windows::core::IUnknown {
fn from(value: HttpGetInputStreamResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpGetInputStreamResult> for ::windows::core::IUnknown {
fn from(value: &HttpGetInputStreamResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpGetInputStreamResult {
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 HttpGetInputStreamResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpGetInputStreamResult> for ::windows::core::IInspectable {
fn from(value: HttpGetInputStreamResult) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpGetInputStreamResult> for ::windows::core::IInspectable {
fn from(value: &HttpGetInputStreamResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpGetInputStreamResult {
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 HttpGetInputStreamResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpGetInputStreamResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpGetInputStreamResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpGetInputStreamResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpGetInputStreamResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpGetInputStreamResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpGetInputStreamResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpGetInputStreamResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpGetInputStreamResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpGetInputStreamResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpGetInputStreamResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpGetInputStreamResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpGetInputStreamResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpGetInputStreamResult {}
unsafe impl ::core::marker::Sync for HttpGetInputStreamResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpGetStringResult(pub ::windows::core::IInspectable);
impl HttpGetStringResult {
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ExtendedError(&self) -> ::windows::core::Result<::windows::core::HRESULT> {
let this = self;
unsafe {
let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HRESULT>(result__)
}
}
pub fn RequestMessage(&self) -> ::windows::core::Result<HttpRequestMessage> {
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::<HttpRequestMessage>(result__)
}
}
pub fn ResponseMessage(&self) -> ::windows::core::Result<HttpResponseMessage> {
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::<HttpResponseMessage>(result__)
}
}
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Value(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for HttpGetStringResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpGetStringResult;{9bac466d-8509-4775-b16d-8953f47a7f5f})");
}
unsafe impl ::windows::core::Interface for HttpGetStringResult {
type Vtable = IHttpGetStringResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9bac466d_8509_4775_b16d_8953f47a7f5f);
}
impl ::windows::core::RuntimeName for HttpGetStringResult {
const NAME: &'static str = "Windows.Web.Http.HttpGetStringResult";
}
impl ::core::convert::From<HttpGetStringResult> for ::windows::core::IUnknown {
fn from(value: HttpGetStringResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpGetStringResult> for ::windows::core::IUnknown {
fn from(value: &HttpGetStringResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpGetStringResult {
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 HttpGetStringResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpGetStringResult> for ::windows::core::IInspectable {
fn from(value: HttpGetStringResult) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpGetStringResult> for ::windows::core::IInspectable {
fn from(value: &HttpGetStringResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpGetStringResult {
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 HttpGetStringResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpGetStringResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpGetStringResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpGetStringResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpGetStringResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpGetStringResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpGetStringResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpGetStringResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpGetStringResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpGetStringResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpGetStringResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpGetStringResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpGetStringResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpGetStringResult {}
unsafe impl ::core::marker::Sync for HttpGetStringResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpMethod(pub ::windows::core::IInspectable);
impl HttpMethod {
pub fn Method(&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 = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(method: Param0) -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), method.into_param().abi(), &mut result__).from_abi::<HttpMethod>(result__)
})
}
pub fn Delete() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|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::<HttpMethod>(result__)
})
}
pub fn Get() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|this| 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::<HttpMethod>(result__)
})
}
pub fn Head() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|this| 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::<HttpMethod>(result__)
})
}
pub fn Options() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpMethod>(result__)
})
}
pub fn Patch() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpMethod>(result__)
})
}
pub fn Post() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|this| 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::<HttpMethod>(result__)
})
}
pub fn Put() -> ::windows::core::Result<HttpMethod> {
Self::IHttpMethodStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpMethod>(result__)
})
}
pub fn IHttpMethodFactory<R, F: FnOnce(&IHttpMethodFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpMethod, IHttpMethodFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IHttpMethodStatics<R, F: FnOnce(&IHttpMethodStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpMethod, IHttpMethodStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpMethod {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpMethod;{728d4022-700d-4fe0-afa5-40299c58dbfd})");
}
unsafe impl ::windows::core::Interface for HttpMethod {
type Vtable = IHttpMethod_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x728d4022_700d_4fe0_afa5_40299c58dbfd);
}
impl ::windows::core::RuntimeName for HttpMethod {
const NAME: &'static str = "Windows.Web.Http.HttpMethod";
}
impl ::core::convert::From<HttpMethod> for ::windows::core::IUnknown {
fn from(value: HttpMethod) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpMethod> for ::windows::core::IUnknown {
fn from(value: &HttpMethod) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpMethod {
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 HttpMethod {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpMethod> for ::windows::core::IInspectable {
fn from(value: HttpMethod) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpMethod> for ::windows::core::IInspectable {
fn from(value: &HttpMethod) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpMethod {
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 HttpMethod {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpMethod> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpMethod) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpMethod> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMethod) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpMethod {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpMethod {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpMethod {}
unsafe impl ::core::marker::Sync for HttpMethod {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpMultipartContent(pub ::windows::core::IInspectable);
impl HttpMultipartContent {
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<HttpMultipartContent, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Foundation_Collections")]
pub fn First(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IIterator<IHttpContent>> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::Collections::IIterable<IHttpContent>>(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::IIterator<IHttpContent>>(result__)
}
}
pub fn Add<'a, Param0: ::windows::core::IntoParam<'a, IHttpContent>>(&self, content: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IHttpMultipartContent>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), content.into_param().abi()).ok() }
}
pub fn CreateWithSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(subtype: Param0) -> ::windows::core::Result<HttpMultipartContent> {
Self::IHttpMultipartContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), subtype.into_param().abi(), &mut result__).from_abi::<HttpMultipartContent>(result__)
})
}
pub fn CreateWithSubtypeAndBoundary<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(subtype: Param0, boundary: Param1) -> ::windows::core::Result<HttpMultipartContent> {
Self::IHttpMultipartContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), subtype.into_param().abi(), boundary.into_param().abi(), &mut result__).from_abi::<HttpMultipartContent>(result__)
})
}
pub fn IHttpMultipartContentFactory<R, F: FnOnce(&IHttpMultipartContentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpMultipartContent, IHttpMultipartContentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpMultipartContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpMultipartContent;{6b14a441-fba7-4bd2-af0a-839de7c295da})");
}
unsafe impl ::windows::core::Interface for HttpMultipartContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl ::windows::core::RuntimeName for HttpMultipartContent {
const NAME: &'static str = "Windows.Web.Http.HttpMultipartContent";
}
impl ::core::convert::From<HttpMultipartContent> for ::windows::core::IUnknown {
fn from(value: HttpMultipartContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpMultipartContent> for ::windows::core::IUnknown {
fn from(value: &HttpMultipartContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpMultipartContent {
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 HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpMultipartContent> for ::windows::core::IInspectable {
fn from(value: HttpMultipartContent) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpMultipartContent> for ::windows::core::IInspectable {
fn from(value: &HttpMultipartContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpMultipartContent {
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 HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<HttpMultipartContent> for IHttpContent {
fn from(value: HttpMultipartContent) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&HttpMultipartContent> for IHttpContent {
fn from(value: &HttpMultipartContent) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for &HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpMultipartContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpMultipartContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpMultipartContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMultipartContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpMultipartContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpMultipartContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpMultipartContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMultipartContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<HttpMultipartContent> for super::super::Foundation::Collections::IIterable<IHttpContent> {
type Error = ::windows::core::Error;
fn try_from(value: HttpMultipartContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<&HttpMultipartContent> for super::super::Foundation::Collections::IIterable<IHttpContent> {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMultipartContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> for HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> for &HttpMultipartContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> {
::core::convert::TryInto::<super::super::Foundation::Collections::IIterable<IHttpContent>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpMultipartContent {}
unsafe impl ::core::marker::Sync for HttpMultipartContent {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for HttpMultipartContent {
type Item = IHttpContent;
type IntoIter = super::super::Foundation::Collections::IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &HttpMultipartContent {
type Item = IHttpContent;
type IntoIter = super::super::Foundation::Collections::IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpMultipartFormDataContent(pub ::windows::core::IInspectable);
impl HttpMultipartFormDataContent {
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<HttpMultipartFormDataContent, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Foundation_Collections")]
pub fn First(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IIterator<IHttpContent>> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::Collections::IIterable<IHttpContent>>(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::IIterator<IHttpContent>>(result__)
}
}
pub fn Add<'a, Param0: ::windows::core::IntoParam<'a, IHttpContent>>(&self, content: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IHttpMultipartFormDataContent>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), content.into_param().abi()).ok() }
}
pub fn AddWithName<'a, Param0: ::windows::core::IntoParam<'a, IHttpContent>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, content: Param0, name: Param1) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IHttpMultipartFormDataContent>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), content.into_param().abi(), name.into_param().abi()).ok() }
}
pub fn AddWithNameAndFileName<'a, Param0: ::windows::core::IntoParam<'a, IHttpContent>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, content: Param0, name: Param1, filename: Param2) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IHttpMultipartFormDataContent>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), content.into_param().abi(), name.into_param().abi(), filename.into_param().abi()).ok() }
}
pub fn CreateWithBoundary<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(boundary: Param0) -> ::windows::core::Result<HttpMultipartFormDataContent> {
Self::IHttpMultipartFormDataContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), boundary.into_param().abi(), &mut result__).from_abi::<HttpMultipartFormDataContent>(result__)
})
}
pub fn IHttpMultipartFormDataContentFactory<R, F: FnOnce(&IHttpMultipartFormDataContentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpMultipartFormDataContent, IHttpMultipartFormDataContentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpMultipartFormDataContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpMultipartFormDataContent;{6b14a441-fba7-4bd2-af0a-839de7c295da})");
}
unsafe impl ::windows::core::Interface for HttpMultipartFormDataContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl ::windows::core::RuntimeName for HttpMultipartFormDataContent {
const NAME: &'static str = "Windows.Web.Http.HttpMultipartFormDataContent";
}
impl ::core::convert::From<HttpMultipartFormDataContent> for ::windows::core::IUnknown {
fn from(value: HttpMultipartFormDataContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpMultipartFormDataContent> for ::windows::core::IUnknown {
fn from(value: &HttpMultipartFormDataContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpMultipartFormDataContent {
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 HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpMultipartFormDataContent> for ::windows::core::IInspectable {
fn from(value: HttpMultipartFormDataContent) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpMultipartFormDataContent> for ::windows::core::IInspectable {
fn from(value: &HttpMultipartFormDataContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpMultipartFormDataContent {
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 HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<HttpMultipartFormDataContent> for IHttpContent {
fn from(value: HttpMultipartFormDataContent) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&HttpMultipartFormDataContent> for IHttpContent {
fn from(value: &HttpMultipartFormDataContent) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for &HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpMultipartFormDataContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpMultipartFormDataContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpMultipartFormDataContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMultipartFormDataContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpMultipartFormDataContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpMultipartFormDataContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpMultipartFormDataContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMultipartFormDataContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<HttpMultipartFormDataContent> for super::super::Foundation::Collections::IIterable<IHttpContent> {
type Error = ::windows::core::Error;
fn try_from(value: HttpMultipartFormDataContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<&HttpMultipartFormDataContent> for super::super::Foundation::Collections::IIterable<IHttpContent> {
type Error = ::windows::core::Error;
fn try_from(value: &HttpMultipartFormDataContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> for HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> for &HttpMultipartFormDataContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<IHttpContent>> {
::core::convert::TryInto::<super::super::Foundation::Collections::IIterable<IHttpContent>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpMultipartFormDataContent {}
unsafe impl ::core::marker::Sync for HttpMultipartFormDataContent {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for HttpMultipartFormDataContent {
type Item = IHttpContent;
type IntoIter = super::super::Foundation::Collections::IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &HttpMultipartFormDataContent {
type Item = IHttpContent;
type IntoIter = super::super::Foundation::Collections::IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
#[cfg(feature = "Foundation")]
pub struct HttpProgress {
pub Stage: HttpProgressStage,
pub BytesSent: u64,
pub TotalBytesToSend: ::core::option::Option<super::super::Foundation::IReference<u64>>,
pub BytesReceived: u64,
pub TotalBytesToReceive: ::core::option::Option<super::super::Foundation::IReference<u64>>,
pub Retries: u32,
}
#[cfg(feature = "Foundation")]
impl HttpProgress {}
#[cfg(feature = "Foundation")]
impl ::core::default::Default for HttpProgress {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Foundation")]
impl ::core::fmt::Debug for HttpProgress {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("HttpProgress").field("Stage", &self.Stage).field("BytesSent", &self.BytesSent).field("TotalBytesToSend", &self.TotalBytesToSend).field("BytesReceived", &self.BytesReceived).field("TotalBytesToReceive", &self.TotalBytesToReceive).field("Retries", &self.Retries).finish()
}
}
#[cfg(feature = "Foundation")]
impl ::core::cmp::PartialEq for HttpProgress {
fn eq(&self, other: &Self) -> bool {
self.Stage == other.Stage && self.BytesSent == other.BytesSent && self.TotalBytesToSend == other.TotalBytesToSend && self.BytesReceived == other.BytesReceived && self.TotalBytesToReceive == other.TotalBytesToReceive && self.Retries == other.Retries
}
}
#[cfg(feature = "Foundation")]
impl ::core::cmp::Eq for HttpProgress {}
#[cfg(feature = "Foundation")]
unsafe impl ::windows::core::Abi for HttpProgress {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[cfg(feature = "Foundation")]
unsafe impl ::windows::core::RuntimeType for HttpProgress {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Web.Http.HttpProgress;enum(Windows.Web.Http.HttpProgressStage;i4);u8;pinterface({61c17706-2d65-11e0-9ae8-d48564015472};u8);u8;pinterface({61c17706-2d65-11e0-9ae8-d48564015472};u8);u4)");
}
#[cfg(feature = "Foundation")]
impl ::windows::core::DefaultType for HttpProgress {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HttpProgressStage(pub i32);
impl HttpProgressStage {
pub const None: HttpProgressStage = HttpProgressStage(0i32);
pub const DetectingProxy: HttpProgressStage = HttpProgressStage(10i32);
pub const ResolvingName: HttpProgressStage = HttpProgressStage(20i32);
pub const ConnectingToServer: HttpProgressStage = HttpProgressStage(30i32);
pub const NegotiatingSsl: HttpProgressStage = HttpProgressStage(40i32);
pub const SendingHeaders: HttpProgressStage = HttpProgressStage(50i32);
pub const SendingContent: HttpProgressStage = HttpProgressStage(60i32);
pub const WaitingForResponse: HttpProgressStage = HttpProgressStage(70i32);
pub const ReceivingHeaders: HttpProgressStage = HttpProgressStage(80i32);
pub const ReceivingContent: HttpProgressStage = HttpProgressStage(90i32);
}
impl ::core::convert::From<i32> for HttpProgressStage {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HttpProgressStage {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for HttpProgressStage {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Web.Http.HttpProgressStage;i4)");
}
impl ::windows::core::DefaultType for HttpProgressStage {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpRequestMessage(pub ::windows::core::IInspectable);
impl HttpRequestMessage {
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<HttpRequestMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Content(&self) -> ::windows::core::Result<IHttpContent> {
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::<IHttpContent>(result__)
}
}
pub fn SetContent<'a, Param0: ::windows::core::IntoParam<'a, IHttpContent>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpRequestHeaderCollection> {
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::<Headers::HttpRequestHeaderCollection>(result__)
}
}
pub fn Method(&self) -> ::windows::core::Result<HttpMethod> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpMethod>(result__)
}
}
pub fn SetMethod<'a, Param0: ::windows::core::IntoParam<'a, HttpMethod>>(&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 = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
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::IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestUri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetRequestUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn TransportInformation(&self) -> ::windows::core::Result<HttpTransportInformation> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpTransportInformation>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Foundation")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, HttpMethod>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(method: Param0, uri: Param1) -> ::windows::core::Result<HttpRequestMessage> {
Self::IHttpRequestMessageFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), method.into_param().abi(), uri.into_param().abi(), &mut result__).from_abi::<HttpRequestMessage>(result__)
})
}
pub fn IHttpRequestMessageFactory<R, F: FnOnce(&IHttpRequestMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpRequestMessage, IHttpRequestMessageFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpRequestMessage {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpRequestMessage;{f5762b3c-74d4-4811-b5dc-9f8b4e2f9abf})");
}
unsafe impl ::windows::core::Interface for HttpRequestMessage {
type Vtable = IHttpRequestMessage_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5762b3c_74d4_4811_b5dc_9f8b4e2f9abf);
}
impl ::windows::core::RuntimeName for HttpRequestMessage {
const NAME: &'static str = "Windows.Web.Http.HttpRequestMessage";
}
impl ::core::convert::From<HttpRequestMessage> for ::windows::core::IUnknown {
fn from(value: HttpRequestMessage) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpRequestMessage> for ::windows::core::IUnknown {
fn from(value: &HttpRequestMessage) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpRequestMessage {
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 HttpRequestMessage {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpRequestMessage> for ::windows::core::IInspectable {
fn from(value: HttpRequestMessage) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpRequestMessage> for ::windows::core::IInspectable {
fn from(value: &HttpRequestMessage) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpRequestMessage {
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 HttpRequestMessage {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpRequestMessage> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpRequestMessage) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpRequestMessage> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpRequestMessage) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpRequestMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpRequestMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpRequestMessage> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpRequestMessage) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpRequestMessage> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpRequestMessage) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpRequestMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpRequestMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpRequestMessage {}
unsafe impl ::core::marker::Sync for HttpRequestMessage {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpRequestResult(pub ::windows::core::IInspectable);
impl HttpRequestResult {
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ExtendedError(&self) -> ::windows::core::Result<::windows::core::HRESULT> {
let this = self;
unsafe {
let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HRESULT>(result__)
}
}
pub fn RequestMessage(&self) -> ::windows::core::Result<HttpRequestMessage> {
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::<HttpRequestMessage>(result__)
}
}
pub fn ResponseMessage(&self) -> ::windows::core::Result<HttpResponseMessage> {
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::<HttpResponseMessage>(result__)
}
}
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for HttpRequestResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpRequestResult;{6acf4da8-b5eb-4a35-a902-4217fbe820c5})");
}
unsafe impl ::windows::core::Interface for HttpRequestResult {
type Vtable = IHttpRequestResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6acf4da8_b5eb_4a35_a902_4217fbe820c5);
}
impl ::windows::core::RuntimeName for HttpRequestResult {
const NAME: &'static str = "Windows.Web.Http.HttpRequestResult";
}
impl ::core::convert::From<HttpRequestResult> for ::windows::core::IUnknown {
fn from(value: HttpRequestResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpRequestResult> for ::windows::core::IUnknown {
fn from(value: &HttpRequestResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpRequestResult {
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 HttpRequestResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpRequestResult> for ::windows::core::IInspectable {
fn from(value: HttpRequestResult) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpRequestResult> for ::windows::core::IInspectable {
fn from(value: &HttpRequestResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpRequestResult {
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 HttpRequestResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpRequestResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpRequestResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpRequestResult> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpRequestResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpRequestResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpRequestResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpRequestResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpRequestResult) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpRequestResult> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpRequestResult) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpRequestResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpRequestResult {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpRequestResult {}
unsafe impl ::core::marker::Sync for HttpRequestResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpResponseMessage(pub ::windows::core::IInspectable);
impl HttpResponseMessage {
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<HttpResponseMessage, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Content(&self) -> ::windows::core::Result<IHttpContent> {
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::<IHttpContent>(result__)
}
}
pub fn SetContent<'a, Param0: ::windows::core::IntoParam<'a, IHttpContent>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpResponseHeaderCollection> {
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::<Headers::HttpResponseHeaderCollection>(result__)
}
}
pub fn IsSuccessStatusCode(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn ReasonPhrase(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetReasonPhrase<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn RequestMessage(&self) -> ::windows::core::Result<HttpRequestMessage> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpRequestMessage>(result__)
}
}
pub fn SetRequestMessage<'a, Param0: ::windows::core::IntoParam<'a, HttpRequestMessage>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Source(&self) -> ::windows::core::Result<HttpResponseMessageSource> {
let this = self;
unsafe {
let mut result__: HttpResponseMessageSource = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpResponseMessageSource>(result__)
}
}
pub fn SetSource(&self, value: HttpResponseMessageSource) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn StatusCode(&self) -> ::windows::core::Result<HttpStatusCode> {
let this = self;
unsafe {
let mut result__: HttpStatusCode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpStatusCode>(result__)
}
}
pub fn SetStatusCode(&self, value: HttpStatusCode) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Version(&self) -> ::windows::core::Result<HttpVersion> {
let this = self;
unsafe {
let mut result__: HttpVersion = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpVersion>(result__)
}
}
pub fn SetVersion(&self, value: HttpVersion) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn EnsureSuccessStatusCode(&self) -> ::windows::core::Result<HttpResponseMessage> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HttpResponseMessage>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Create(statuscode: HttpStatusCode) -> ::windows::core::Result<HttpResponseMessage> {
Self::IHttpResponseMessageFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), statuscode, &mut result__).from_abi::<HttpResponseMessage>(result__)
})
}
pub fn IHttpResponseMessageFactory<R, F: FnOnce(&IHttpResponseMessageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpResponseMessage, IHttpResponseMessageFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpResponseMessage {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpResponseMessage;{fee200fb-8664-44e0-95d9-42696199bffc})");
}
unsafe impl ::windows::core::Interface for HttpResponseMessage {
type Vtable = IHttpResponseMessage_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfee200fb_8664_44e0_95d9_42696199bffc);
}
impl ::windows::core::RuntimeName for HttpResponseMessage {
const NAME: &'static str = "Windows.Web.Http.HttpResponseMessage";
}
impl ::core::convert::From<HttpResponseMessage> for ::windows::core::IUnknown {
fn from(value: HttpResponseMessage) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpResponseMessage> for ::windows::core::IUnknown {
fn from(value: &HttpResponseMessage) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpResponseMessage {
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 HttpResponseMessage {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpResponseMessage> for ::windows::core::IInspectable {
fn from(value: HttpResponseMessage) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpResponseMessage> for ::windows::core::IInspectable {
fn from(value: &HttpResponseMessage) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpResponseMessage {
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 HttpResponseMessage {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpResponseMessage> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpResponseMessage) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpResponseMessage> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpResponseMessage) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpResponseMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpResponseMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpResponseMessage> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpResponseMessage) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpResponseMessage> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpResponseMessage) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpResponseMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpResponseMessage {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpResponseMessage {}
unsafe impl ::core::marker::Sync for HttpResponseMessage {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HttpResponseMessageSource(pub i32);
impl HttpResponseMessageSource {
pub const None: HttpResponseMessageSource = HttpResponseMessageSource(0i32);
pub const Cache: HttpResponseMessageSource = HttpResponseMessageSource(1i32);
pub const Network: HttpResponseMessageSource = HttpResponseMessageSource(2i32);
}
impl ::core::convert::From<i32> for HttpResponseMessageSource {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HttpResponseMessageSource {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for HttpResponseMessageSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Web.Http.HttpResponseMessageSource;i4)");
}
impl ::windows::core::DefaultType for HttpResponseMessageSource {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HttpStatusCode(pub i32);
impl HttpStatusCode {
pub const None: HttpStatusCode = HttpStatusCode(0i32);
pub const Continue: HttpStatusCode = HttpStatusCode(100i32);
pub const SwitchingProtocols: HttpStatusCode = HttpStatusCode(101i32);
pub const Processing: HttpStatusCode = HttpStatusCode(102i32);
pub const Ok: HttpStatusCode = HttpStatusCode(200i32);
pub const Created: HttpStatusCode = HttpStatusCode(201i32);
pub const Accepted: HttpStatusCode = HttpStatusCode(202i32);
pub const NonAuthoritativeInformation: HttpStatusCode = HttpStatusCode(203i32);
pub const NoContent: HttpStatusCode = HttpStatusCode(204i32);
pub const ResetContent: HttpStatusCode = HttpStatusCode(205i32);
pub const PartialContent: HttpStatusCode = HttpStatusCode(206i32);
pub const MultiStatus: HttpStatusCode = HttpStatusCode(207i32);
pub const AlreadyReported: HttpStatusCode = HttpStatusCode(208i32);
pub const IMUsed: HttpStatusCode = HttpStatusCode(226i32);
pub const MultipleChoices: HttpStatusCode = HttpStatusCode(300i32);
pub const MovedPermanently: HttpStatusCode = HttpStatusCode(301i32);
pub const Found: HttpStatusCode = HttpStatusCode(302i32);
pub const SeeOther: HttpStatusCode = HttpStatusCode(303i32);
pub const NotModified: HttpStatusCode = HttpStatusCode(304i32);
pub const UseProxy: HttpStatusCode = HttpStatusCode(305i32);
pub const TemporaryRedirect: HttpStatusCode = HttpStatusCode(307i32);
pub const PermanentRedirect: HttpStatusCode = HttpStatusCode(308i32);
pub const BadRequest: HttpStatusCode = HttpStatusCode(400i32);
pub const Unauthorized: HttpStatusCode = HttpStatusCode(401i32);
pub const PaymentRequired: HttpStatusCode = HttpStatusCode(402i32);
pub const Forbidden: HttpStatusCode = HttpStatusCode(403i32);
pub const NotFound: HttpStatusCode = HttpStatusCode(404i32);
pub const MethodNotAllowed: HttpStatusCode = HttpStatusCode(405i32);
pub const NotAcceptable: HttpStatusCode = HttpStatusCode(406i32);
pub const ProxyAuthenticationRequired: HttpStatusCode = HttpStatusCode(407i32);
pub const RequestTimeout: HttpStatusCode = HttpStatusCode(408i32);
pub const Conflict: HttpStatusCode = HttpStatusCode(409i32);
pub const Gone: HttpStatusCode = HttpStatusCode(410i32);
pub const LengthRequired: HttpStatusCode = HttpStatusCode(411i32);
pub const PreconditionFailed: HttpStatusCode = HttpStatusCode(412i32);
pub const RequestEntityTooLarge: HttpStatusCode = HttpStatusCode(413i32);
pub const RequestUriTooLong: HttpStatusCode = HttpStatusCode(414i32);
pub const UnsupportedMediaType: HttpStatusCode = HttpStatusCode(415i32);
pub const RequestedRangeNotSatisfiable: HttpStatusCode = HttpStatusCode(416i32);
pub const ExpectationFailed: HttpStatusCode = HttpStatusCode(417i32);
pub const UnprocessableEntity: HttpStatusCode = HttpStatusCode(422i32);
pub const Locked: HttpStatusCode = HttpStatusCode(423i32);
pub const FailedDependency: HttpStatusCode = HttpStatusCode(424i32);
pub const UpgradeRequired: HttpStatusCode = HttpStatusCode(426i32);
pub const PreconditionRequired: HttpStatusCode = HttpStatusCode(428i32);
pub const TooManyRequests: HttpStatusCode = HttpStatusCode(429i32);
pub const RequestHeaderFieldsTooLarge: HttpStatusCode = HttpStatusCode(431i32);
pub const InternalServerError: HttpStatusCode = HttpStatusCode(500i32);
pub const NotImplemented: HttpStatusCode = HttpStatusCode(501i32);
pub const BadGateway: HttpStatusCode = HttpStatusCode(502i32);
pub const ServiceUnavailable: HttpStatusCode = HttpStatusCode(503i32);
pub const GatewayTimeout: HttpStatusCode = HttpStatusCode(504i32);
pub const HttpVersionNotSupported: HttpStatusCode = HttpStatusCode(505i32);
pub const VariantAlsoNegotiates: HttpStatusCode = HttpStatusCode(506i32);
pub const InsufficientStorage: HttpStatusCode = HttpStatusCode(507i32);
pub const LoopDetected: HttpStatusCode = HttpStatusCode(508i32);
pub const NotExtended: HttpStatusCode = HttpStatusCode(510i32);
pub const NetworkAuthenticationRequired: HttpStatusCode = HttpStatusCode(511i32);
}
impl ::core::convert::From<i32> for HttpStatusCode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HttpStatusCode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for HttpStatusCode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Web.Http.HttpStatusCode;i4)");
}
impl ::windows::core::DefaultType for HttpStatusCode {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpStreamContent(pub ::windows::core::IInspectable);
impl HttpStreamContent {
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 = "Storage_Streams")]
pub fn CreateFromInputStream<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IInputStream>>(content: Param0) -> ::windows::core::Result<HttpStreamContent> {
Self::IHttpStreamContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), content.into_param().abi(), &mut result__).from_abi::<HttpStreamContent>(result__)
})
}
pub fn IHttpStreamContentFactory<R, F: FnOnce(&IHttpStreamContentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpStreamContent, IHttpStreamContentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpStreamContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpStreamContent;{6b14a441-fba7-4bd2-af0a-839de7c295da})");
}
unsafe impl ::windows::core::Interface for HttpStreamContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl ::windows::core::RuntimeName for HttpStreamContent {
const NAME: &'static str = "Windows.Web.Http.HttpStreamContent";
}
impl ::core::convert::From<HttpStreamContent> for ::windows::core::IUnknown {
fn from(value: HttpStreamContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpStreamContent> for ::windows::core::IUnknown {
fn from(value: &HttpStreamContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpStreamContent {
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 HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpStreamContent> for ::windows::core::IInspectable {
fn from(value: HttpStreamContent) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpStreamContent> for ::windows::core::IInspectable {
fn from(value: &HttpStreamContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpStreamContent {
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 HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<HttpStreamContent> for IHttpContent {
fn from(value: HttpStreamContent) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&HttpStreamContent> for IHttpContent {
fn from(value: &HttpStreamContent) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for &HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpStreamContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpStreamContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpStreamContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpStreamContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpStreamContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpStreamContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpStreamContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpStreamContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpStreamContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpStreamContent {}
unsafe impl ::core::marker::Sync for HttpStreamContent {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpStringContent(pub ::windows::core::IInspectable);
impl HttpStringContent {
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn CreateFromString<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(content: Param0) -> ::windows::core::Result<HttpStringContent> {
Self::IHttpStringContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), content.into_param().abi(), &mut result__).from_abi::<HttpStringContent>(result__)
})
}
#[cfg(feature = "Storage_Streams")]
pub fn CreateFromStringWithEncoding<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(content: Param0, encoding: super::super::Storage::Streams::UnicodeEncoding) -> ::windows::core::Result<HttpStringContent> {
Self::IHttpStringContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), content.into_param().abi(), encoding, &mut result__).from_abi::<HttpStringContent>(result__)
})
}
#[cfg(feature = "Storage_Streams")]
pub fn CreateFromStringWithEncodingAndMediaType<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(content: Param0, encoding: super::super::Storage::Streams::UnicodeEncoding, mediatype: Param2) -> ::windows::core::Result<HttpStringContent> {
Self::IHttpStringContentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), content.into_param().abi(), encoding, mediatype.into_param().abi(), &mut result__).from_abi::<HttpStringContent>(result__)
})
}
pub fn IHttpStringContentFactory<R, F: FnOnce(&IHttpStringContentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<HttpStringContent, IHttpStringContentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for HttpStringContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpStringContent;{6b14a441-fba7-4bd2-af0a-839de7c295da})");
}
unsafe impl ::windows::core::Interface for HttpStringContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl ::windows::core::RuntimeName for HttpStringContent {
const NAME: &'static str = "Windows.Web.Http.HttpStringContent";
}
impl ::core::convert::From<HttpStringContent> for ::windows::core::IUnknown {
fn from(value: HttpStringContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpStringContent> for ::windows::core::IUnknown {
fn from(value: &HttpStringContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpStringContent {
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 HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpStringContent> for ::windows::core::IInspectable {
fn from(value: HttpStringContent) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpStringContent> for ::windows::core::IInspectable {
fn from(value: &HttpStringContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpStringContent {
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 HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<HttpStringContent> for IHttpContent {
fn from(value: HttpStringContent) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&HttpStringContent> for IHttpContent {
fn from(value: &HttpStringContent) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IHttpContent> for &HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, IHttpContent> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpStringContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: HttpStringContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpStringContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpStringContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpStringContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpStringContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpStringContent> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpStringContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpStringContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpStringContent {}
unsafe impl ::core::marker::Sync for HttpStringContent {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct HttpTransportInformation(pub ::windows::core::IInspectable);
impl HttpTransportInformation {
#[cfg(feature = "Security_Cryptography_Certificates")]
pub fn ServerCertificate(&self) -> ::windows::core::Result<super::super::Security::Cryptography::Certificates::Certificate> {
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::Security::Cryptography::Certificates::Certificate>(result__)
}
}
#[cfg(feature = "Networking_Sockets")]
pub fn ServerCertificateErrorSeverity(&self) -> ::windows::core::Result<super::super::Networking::Sockets::SocketSslErrorSeverity> {
let this = self;
unsafe {
let mut result__: super::super::Networking::Sockets::SocketSslErrorSeverity = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Networking::Sockets::SocketSslErrorSeverity>(result__)
}
}
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))]
pub fn ServerCertificateErrors(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::ChainValidationResult>> {
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::IVectorView<super::super::Security::Cryptography::Certificates::ChainValidationResult>>(result__)
}
}
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))]
pub fn ServerIntermediateCertificates(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::Certificate>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::Certificate>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(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 HttpTransportInformation {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Web.Http.HttpTransportInformation;{70127198-c6a7-4ed0-833a-83fd8b8f178d})");
}
unsafe impl ::windows::core::Interface for HttpTransportInformation {
type Vtable = IHttpTransportInformation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x70127198_c6a7_4ed0_833a_83fd8b8f178d);
}
impl ::windows::core::RuntimeName for HttpTransportInformation {
const NAME: &'static str = "Windows.Web.Http.HttpTransportInformation";
}
impl ::core::convert::From<HttpTransportInformation> for ::windows::core::IUnknown {
fn from(value: HttpTransportInformation) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&HttpTransportInformation> for ::windows::core::IUnknown {
fn from(value: &HttpTransportInformation) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HttpTransportInformation {
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 HttpTransportInformation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<HttpTransportInformation> for ::windows::core::IInspectable {
fn from(value: HttpTransportInformation) -> Self {
value.0
}
}
impl ::core::convert::From<&HttpTransportInformation> for ::windows::core::IInspectable {
fn from(value: &HttpTransportInformation) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HttpTransportInformation {
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 HttpTransportInformation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<HttpTransportInformation> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: HttpTransportInformation) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&HttpTransportInformation> for super::super::Foundation::IStringable {
type Error = ::windows::core::Error;
fn try_from(value: &HttpTransportInformation) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for HttpTransportInformation {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &HttpTransportInformation {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> {
::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for HttpTransportInformation {}
unsafe impl ::core::marker::Sync for HttpTransportInformation {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HttpVersion(pub i32);
impl HttpVersion {
pub const None: HttpVersion = HttpVersion(0i32);
pub const Http10: HttpVersion = HttpVersion(1i32);
pub const Http11: HttpVersion = HttpVersion(2i32);
pub const Http20: HttpVersion = HttpVersion(3i32);
}
impl ::core::convert::From<i32> for HttpVersion {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HttpVersion {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for HttpVersion {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Web.Http.HttpVersion;i4)");
}
impl ::windows::core::DefaultType for HttpVersion {
type DefaultType = Self;
}
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpBufferContentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpBufferContentFactory {
type Vtable = IHttpBufferContentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc20c193_c41f_4ff7_9123_6435736eadc2);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpBufferContentFactory_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 = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::windows::core::RawPtr, offset: u32, count: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpClient(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpClient {
type Vtable = IHttpClient_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7fda1151_3574_4880_a8ba_e6b1e0061f3d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpClient_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, completionoption: HttpCompletionOption, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, request: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, request: ::windows::core::RawPtr, completionoption: HttpCompletionOption, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Web_Http_Headers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Web_Http_Headers"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpClient2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpClient2 {
type Vtable = IHttpClient2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcdd83348_e8b7_4cec_b1b0_dc455fe72c92);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpClient2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, completionoption: HttpCompletionOption, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, request: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, request: ::windows::core::RawPtr, completionoption: HttpCompletionOption, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpClientFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpClientFactory {
type Vtable = IHttpClientFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc30c4eca_e3fa_4f99_afb4_63cc65009462);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpClientFactory_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 = "Web_Http_Filters")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, filter: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Web_Http_Filters"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IHttpContent(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpContent {
type Vtable = IHttpContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b14a441_fba7_4bd2_af0a_839de7c295da);
}
impl IHttpContent {
#[cfg(feature = "Web_Http_Headers")]
pub fn Headers(&self) -> ::windows::core::Result<Headers::HttpContentHeaderCollection> {
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::<Headers::HttpContentHeaderCollection>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BufferAllAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
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::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsBufferAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>> {
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::IAsyncOperationWithProgress<super::super::Storage::Streams::IBuffer, u64>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn ReadAsInputStreamAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<super::super::Storage::Streams::IInputStream, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReadAsStringAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<::windows::core::HSTRING, u64>>(result__)
}
}
pub fn TryComputeLength(&self, length: &mut u64) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), length, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn WriteToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<u64, u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IHttpContent {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{6b14a441-fba7-4bd2-af0a-839de7c295da}");
}
impl ::core::convert::From<IHttpContent> for ::windows::core::IUnknown {
fn from(value: IHttpContent) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IHttpContent> for ::windows::core::IUnknown {
fn from(value: &IHttpContent) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IHttpContent {
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 IHttpContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IHttpContent> for ::windows::core::IInspectable {
fn from(value: IHttpContent) -> Self {
value.0
}
}
impl ::core::convert::From<&IHttpContent> for ::windows::core::IInspectable {
fn from(value: &IHttpContent) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IHttpContent {
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 IHttpContent {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<IHttpContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: IHttpContent) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&IHttpContent> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &IHttpContent) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for IHttpContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &IHttpContent {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpContent_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 = "Web_Http_Headers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Web_Http_Headers"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, length: *mut u64, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputstream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpCookie(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpCookie {
type Vtable = IHttpCookie_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f5488e2_cc2d_4779_86a7_88f10687d249);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpCookie_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
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: 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: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpCookieFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpCookieFactory {
type Vtable = IHttpCookieFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6a0585a9_931c_4cd1_a96d_c21701785c5f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpCookieFactory_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, domain: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, path: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpCookieManager(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpCookieManager {
type Vtable = IHttpCookieManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a431780_cd4f_4e57_a84a_5b0a53d6bb96);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpCookieManager_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, cookie: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: ::windows::core::RawPtr, thirdparty: bool, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpFormUrlEncodedContentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpFormUrlEncodedContentFactory {
type Vtable = IHttpFormUrlEncodedContentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x43f0138c_2f73_4302_b5f3_eae9238a5e01);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpFormUrlEncodedContentFactory_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, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpGetBufferResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpGetBufferResult {
type Vtable = IHttpGetBufferResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53d08e7c_e209_404e_9a49_742d8236fd3a);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpGetBufferResult_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::HRESULT) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpGetInputStreamResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpGetInputStreamResult {
type Vtable = IHttpGetInputStreamResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5d63463_13aa_4ee0_be95_a0c39fe91203);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpGetInputStreamResult_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::HRESULT) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpGetStringResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpGetStringResult {
type Vtable = IHttpGetStringResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9bac466d_8509_4775_b16d_8953f47a7f5f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpGetStringResult_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::HRESULT) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpMethod(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMethod {
type Vtable = IHttpMethod_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x728d4022_700d_4fe0_afa5_40299c58dbfd);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMethod_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 IHttpMethodFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMethodFactory {
type Vtable = IHttpMethodFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c51d10d_36d7_40f8_a86d_e759caf2f83f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMethodFactory_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, method: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpMethodStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMethodStatics {
type Vtable = IHttpMethodStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64d171f0_d99a_4153_8dc6_d68cc4cce317);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMethodStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
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,
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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpMultipartContent(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMultipartContent {
type Vtable = IHttpMultipartContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdf916aff_9926_4ac9_aaf1_e0d04ef09bb9);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMultipartContent_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, content: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpMultipartContentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMultipartContentFactory {
type Vtable = IHttpMultipartContentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7eb42e62_0222_4f20_b372_47d5db5d33b4);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMultipartContentFactory_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, subtype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, subtype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, boundary: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpMultipartFormDataContent(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMultipartFormDataContent {
type Vtable = IHttpMultipartFormDataContent_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64d337e2_e967_4624_b6d1_cf74604a4a42);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMultipartFormDataContent_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, content: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, filename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpMultipartFormDataContentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpMultipartFormDataContentFactory {
type Vtable = IHttpMultipartFormDataContentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa04d7311_5017_4622_93a8_49b24a4fcbfc);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpMultipartFormDataContentFactory_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, boundary: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpRequestMessage(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpRequestMessage {
type Vtable = IHttpRequestMessage_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5762b3c_74d4_4811_b5dc_9f8b4e2f9abf);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpRequestMessage_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Web_Http_Headers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Web_Http_Headers"))] usize,
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, value: ::windows::core::RawPtr) -> ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpRequestMessageFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpRequestMessageFactory {
type Vtable = IHttpRequestMessageFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5bac994e_3886_412e_aec3_52ec7f25616f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpRequestMessageFactory_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, method: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpRequestResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpRequestResult {
type Vtable = IHttpRequestResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6acf4da8_b5eb_4a35_a902_4217fbe820c5);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpRequestResult_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::HRESULT) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpResponseMessage(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpResponseMessage {
type Vtable = IHttpResponseMessage_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfee200fb_8664_44e0_95d9_42696199bffc);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpResponseMessage_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Web_Http_Headers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Web_Http_Headers"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
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, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut HttpResponseMessageSource) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: HttpResponseMessageSource) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut HttpStatusCode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: HttpStatusCode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut HttpVersion) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: HttpVersion) -> ::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 IHttpResponseMessageFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpResponseMessageFactory {
type Vtable = IHttpResponseMessageFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x52a8af99_f095_43da_b60f_7cfc2bc7ea2f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpResponseMessageFactory_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, statuscode: HttpStatusCode, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpStreamContentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpStreamContentFactory {
type Vtable = IHttpStreamContentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf3e64d9d_f725_407e_942f_0eda189809f4);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpStreamContentFactory_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 = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpStringContentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpStringContentFactory {
type Vtable = IHttpStringContentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46649d5b_2e93_48eb_8e61_19677878e57f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpStringContentFactory_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, content: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, encoding: super::super::Storage::Streams::UnicodeEncoding, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, content: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, encoding: super::super::Storage::Streams::UnicodeEncoding, mediatype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IHttpTransportInformation(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IHttpTransportInformation {
type Vtable = IHttpTransportInformation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x70127198_c6a7_4ed0_833a_83fd8b8f178d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHttpTransportInformation_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 = "Security_Cryptography_Certificates")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Security_Cryptography_Certificates"))] usize,
#[cfg(feature = "Networking_Sockets")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Networking::Sockets::SocketSslErrorSeverity) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Networking_Sockets"))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates")))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates")))] usize,
);
|
// 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_exception::Result;
use crate::base::GlobalInstance;
use crate::runtime::Runtime;
pub struct GlobalIORuntime;
pub struct GlobalQueryRuntime(pub Runtime);
impl GlobalQueryRuntime {
#[inline(always)]
pub fn runtime<'a>(self: &'a Arc<Self>) -> &'a Runtime {
&self.0
}
}
impl GlobalIORuntime {
pub fn init(num_cpus: usize) -> Result<()> {
let thread_num = std::cmp::max(num_cpus, num_cpus::get() / 2);
let thread_num = std::cmp::max(2, thread_num);
GlobalInstance::set(Arc::new(Runtime::with_worker_threads(
thread_num,
Some("IO-worker".to_owned()),
)?));
Ok(())
}
pub fn instance() -> Arc<Runtime> {
GlobalInstance::get()
}
}
impl GlobalQueryRuntime {
pub fn init(num_cpus: usize) -> Result<()> {
let thread_num = std::cmp::max(num_cpus, num_cpus::get() / 2);
let thread_num = std::cmp::max(2, thread_num);
let rt = Runtime::with_worker_threads(thread_num, Some("g-query-worker".to_owned()))?;
GlobalInstance::set(Arc::new(GlobalQueryRuntime(rt)));
Ok(())
}
pub fn instance() -> Arc<GlobalQueryRuntime> {
GlobalInstance::get()
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_arrow::parquet::metadata::FileMetaData;
use common_arrow::parquet::read::read_metadata_async;
use common_exception::ErrorCode;
use common_exception::Result;
use opendal::Operator;
use storages_common_cache::InMemoryItemCacheReader;
use storages_common_cache::LoadParams;
use storages_common_cache::Loader;
use storages_common_cache_manager::CacheManager;
pub struct LoaderWrapper<T>(T);
pub type FileMetaDataReader = InMemoryItemCacheReader<FileMetaData, LoaderWrapper<Operator>>;
pub struct MetaDataReader;
impl MetaDataReader {
pub fn meta_data_reader(dal: Operator) -> FileMetaDataReader {
FileMetaDataReader::new(
CacheManager::instance().get_file_meta_data_cache(),
LoaderWrapper(dal),
)
}
}
#[async_trait::async_trait]
impl Loader<FileMetaData> for LoaderWrapper<Operator> {
async fn load(&self, params: &LoadParams) -> Result<FileMetaData> {
let mut reader = if let Some(len) = params.len_hint {
self.0.range_reader(¶ms.location, 0..len).await?
} else {
self.0.reader(¶ms.location).await?
};
read_metadata_async(&mut reader).await.map_err(|err| {
ErrorCode::Internal(format!(
"read file meta failed, {}, {:?}",
params.location, err
))
})
}
}
|
use crate::decode::Decode;
use crate::encode::Encode;
use crate::io::{Buf, BufMut};
use crate::postgres::protocol::TypeId;
use crate::postgres::{PgData, PgRawBuffer, PgTypeInfo, PgValue, Postgres};
use crate::types::{Json, Type};
use crate::value::RawValue;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as JsonRawValue;
use serde_json::Value as JsonValue;
// <https://www.postgresql.org/docs/12/datatype-json.html>
// In general, most applications should prefer to store JSON data as jsonb,
// unless there are quite specialized needs, such as legacy assumptions
// about ordering of object keys.
impl Type<Postgres> for JsonValue {
fn type_info() -> PgTypeInfo {
<Json<Self> as Type<Postgres>>::type_info()
}
}
impl Encode<Postgres> for JsonValue {
fn encode(&self, buf: &mut PgRawBuffer) {
Json(self).encode(buf)
}
}
impl<'de> Decode<'de, Postgres> for JsonValue {
fn decode(value: PgValue<'de>) -> crate::Result<Self> {
<Json<Self> as Decode<Postgres>>::decode(value).map(|item| item.0)
}
}
impl Type<Postgres> for &'_ JsonRawValue {
fn type_info() -> PgTypeInfo {
<Json<Self> as Type<Postgres>>::type_info()
}
}
impl Encode<Postgres> for &'_ JsonRawValue {
fn encode(&self, buf: &mut PgRawBuffer) {
Json(self).encode(buf)
}
}
impl<'de> Decode<'de, Postgres> for &'de JsonRawValue {
fn decode(value: PgValue<'de>) -> crate::Result<Self> {
<Json<Self> as Decode<Postgres>>::decode(value).map(|item| item.0)
}
}
impl<T> Type<Postgres> for Json<T> {
fn type_info() -> PgTypeInfo {
PgTypeInfo::new(TypeId::JSONB, "JSONB")
}
}
impl<T> Encode<Postgres> for Json<T>
where
T: Serialize,
{
fn encode(&self, buf: &mut PgRawBuffer) {
// JSONB version (as of 2020-03-20)
buf.put_u8(1);
serde_json::to_writer(&mut **buf, &self.0)
.expect("failed to serialize json for encoding to database");
}
}
impl<'de, T> Decode<'de, Postgres> for Json<T>
where
T: 'de,
T: Deserialize<'de>,
{
fn decode(value: PgValue<'de>) -> crate::Result<Self> {
(match value.try_get()? {
PgData::Text(s) => serde_json::from_str(s),
PgData::Binary(mut buf) => {
if value.type_info().as_ref().and_then(|info| info.id) == Some(TypeId::JSONB) {
let version = buf.get_u8()?;
assert_eq!(
version, 1,
"unsupported JSONB format version {}; please open an issue",
version
);
}
serde_json::from_slice(buf)
}
})
.map(Json)
.map_err(crate::Error::decode)
}
}
|
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
pub fn read_lines<P>(path: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(path)?;
Ok(io::BufReader::new(file).lines())
}
pub fn is_numeric_string_in_range(s: &str, min: usize, max: usize) -> bool {
if let Ok(num) = s.parse::<usize>() {
return min <= num && num <= max;
}
return false;
}
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
base_node::{
chain_metadata_service::ChainMetadataEvent,
comms_interface::OutboundNodeCommsInterface,
states,
states::{BaseNodeState, BlockSyncConfig, StateEvent},
},
chain_storage::{BlockchainBackend, BlockchainDatabase},
};
use futures::{future, future::Either, SinkExt};
use log::*;
use std::{future::Future, sync::Arc};
use tari_broadcast_channel::{bounded, Publisher, Subscriber};
use tari_comms::{connection_manager::ConnectionManagerRequester, PeerManager};
use tari_shutdown::ShutdownSignal;
const LOG_TARGET: &str = "c::bn::base_node";
/// Configuration for the BaseNodeStateMachine.
#[derive(Clone, Copy)]
pub struct BaseNodeStateMachineConfig {
pub block_sync_config: BlockSyncConfig,
}
impl Default for BaseNodeStateMachineConfig {
fn default() -> Self {
Self {
block_sync_config: BlockSyncConfig::default(),
}
}
}
/// A Tari full node, aka Base Node.
///
/// The Base Node is essentially a finite state machine that synchronises its blockchain state with its peers and
/// then listens for new blocks to add to the blockchain. See the [SynchronizationSate] documentation for more details.
///
/// This struct holds fields that will be used by all the various FSM state instances, including the local blockchain
/// database and hooks to the p2p network
pub struct BaseNodeStateMachine<B: BlockchainBackend> {
pub(super) db: BlockchainDatabase<B>,
pub(super) comms: OutboundNodeCommsInterface,
pub(super) peer_manager: Arc<PeerManager>,
pub(super) connection_manager: ConnectionManagerRequester,
pub(super) metadata_event_stream: Subscriber<ChainMetadataEvent>,
pub(super) config: BaseNodeStateMachineConfig,
event_sender: Publisher<StateEvent>,
event_receiver: Subscriber<StateEvent>,
interrupt_signal: ShutdownSignal,
}
impl<B: BlockchainBackend + 'static> BaseNodeStateMachine<B> {
/// Instantiate a new Base Node.
pub fn new(
db: &BlockchainDatabase<B>,
comms: &OutboundNodeCommsInterface,
peer_manager: Arc<PeerManager>,
connection_manager: ConnectionManagerRequester,
metadata_event_stream: Subscriber<ChainMetadataEvent>,
config: BaseNodeStateMachineConfig,
shutdown_signal: ShutdownSignal,
) -> Self
{
let (event_sender, event_receiver): (Publisher<_>, Subscriber<_>) = bounded(10);
Self {
db: db.clone(),
comms: comms.clone(),
peer_manager,
connection_manager,
metadata_event_stream,
interrupt_signal: shutdown_signal,
config,
event_sender,
event_receiver,
}
}
/// Describe the Finite State Machine for the base node. This function describes _every possible_ state
/// transition for the node given its current state and an event that gets triggered.
pub fn transition(&self, state: BaseNodeState, event: StateEvent) -> BaseNodeState {
use crate::base_node::states::{BaseNodeState::*, StateEvent::*, SyncStatus::*};
match (state, event) {
(Starting(s), Initialized) => Listening(s.into()),
(BlockSync(s, _, _), BlocksSynchronized) => Listening(s.into()),
(BlockSync(s, _, _), BlockSyncFailure) => Waiting(s.into()),
(Listening(_), FallenBehind(Lagging(network_tip, sync_peers))) => {
BlockSync(self.config.block_sync_config.sync_strategy, network_tip, sync_peers)
},
(Waiting(s), Continue) => Listening(s.into()),
(_, FatalError(s)) => Shutdown(states::Shutdown::with_reason(s)),
(_, UserQuit) => Shutdown(states::Shutdown::with_reason("Shutdown initiated by user".to_string())),
(s, e) => {
warn!(
target: LOG_TARGET,
"No state transition occurs for event {:?} in state {}", e, s
);
s
},
}
}
/// This clones the receiver end of the channel and gives out a copy to the caller
/// This allows multiple subscribers to this channel by only keeping one channel and cloning the receiver for every
/// caller.
pub fn get_state_change_event_stream(&self) -> Subscriber<StateEvent> {
self.event_receiver.clone()
}
/// Start the base node runtime.
pub async fn run(mut self) {
use crate::base_node::states::BaseNodeState::*;
let mut state = Starting(states::Starting);
loop {
if let Shutdown(reason) = &state {
debug!(
target: LOG_TARGET,
"=== Base Node state machine is shutting down because {}", reason
);
break;
}
let interrupt_signal = self.get_interrupt_signal();
let next_state_future = self.next_state_event(&mut state);
// Get the next `StateEvent`, returning a `UserQuit` state event if the interrupt signal is triggered
let next_event = select_next_state_event(interrupt_signal, next_state_future).await;
// Publish the event on the event bus
let _ = self.event_sender.send(next_event.clone()).await;
debug!(
target: LOG_TARGET,
"=== Base Node event in State [{}]: {}", state, next_event
);
state = self.transition(state, next_event);
}
}
/// Processes and returns the next `StateEvent`
async fn next_state_event(&mut self, state: &mut BaseNodeState) -> StateEvent {
use states::BaseNodeState::*;
let shared_state = self;
match state {
Starting(s) => s.next_event(shared_state).await,
BlockSync(s, network_tip, sync_peers) => s.next_event(shared_state, network_tip, sync_peers).await,
Listening(s) => s.next_event(shared_state).await,
Waiting(s) => s.next_event().await,
Shutdown(_) => unreachable!("called get_next_state_event while in Shutdown state"),
}
}
/// Return a copy of the `interrupt_signal` for this node. This is a `ShutdownSignal` future that will be ready when
/// the node will enter a `Shutdown` state.
pub fn get_interrupt_signal(&self) -> ShutdownSignal {
self.interrupt_signal.clone()
}
}
/// Polls both the interrupt signal and the given future. If the given future `state_fut` is ready first it's value is
/// returned, otherwise if the interrupt signal is triggered, `StateEvent::UserQuit` is returned.
async fn select_next_state_event<F>(interrupt_signal: ShutdownSignal, state_fut: F) -> StateEvent
where F: Future<Output = StateEvent> {
futures::pin_mut!(state_fut);
// If future A and B are both ready `future::select` will prefer A
match future::select(interrupt_signal, state_fut).await {
Either::Left(_) => StateEvent::UserQuit,
Either::Right((state, _)) => state,
}
}
|
//! libuefi clone of the ::std::borrow module
pub enum Cow<'heap, 'd, T: ?Sized>
where
T: 'd + ToOwned<'heap>
{
Owned(T::Owned),
Borrowed(&'d T)
}
impl<'bs, 'd, T: ?Sized> From<&'d T> for Cow<'bs, 'd, T>
where
T: 'd + ToOwned<'bs>
{
fn from(v: &'d T) -> Self {
Cow::Borrowed(v)
}
}
impl<'bs, 'd, T: ?Sized> ::core::ops::Deref for Cow<'bs, 'd, T>
where
T: 'd + ToOwned<'bs>
{
type Target = T;
fn deref(&self) -> &T {
match self
{
&Cow::Owned(ref v) => v.borrow(),
&Cow::Borrowed(v) => v,
}
}
}
impl<'bs, 'd, T: ?Sized> ::core::fmt::Display for Cow<'bs, 'd, T>
where
T: 'd + ToOwned<'bs> + ::core::fmt::Display
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
(**self).fmt(f)
}
}
pub trait Borrow<T: ?Sized>
{
fn borrow(&self) -> &T;
}
pub trait ToOwned<'heap>
{
type Owned: 'heap + Borrow<Self>;
fn to_owned(&self, &'heap ::boot_services::BootServices) -> Self::Owned;
}
|
//! Operator and utilities to source data from plain files containing
//! arbitrary json structures.
use std::cell::RefCell;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::rc::Weak;
use std::time::{Duration, Instant};
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
// use sources::json_file::flate2::read::GzDecoder;
use crate::scheduling::Scheduler;
use crate::sources::Sourceable;
use crate::{AttributeConfig, InputSemantics};
use crate::{AsAid, Eid, Value};
use Value::{Bool, Number};
/// A local filesystem data source containing JSON objects.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub struct JsonFile<A: AsAid> {
/// Path to a file on each workers local filesystem.
pub path: String,
/// Attributes to ingest.
pub attributes: Vec<A>,
}
impl<A: AsAid> Sourceable<A, Duration> for JsonFile<A> {
fn source<S: Scope<Timestamp = Duration>>(
&self,
scope: &mut S,
t0: Instant,
_scheduler: Weak<RefCell<Scheduler<Duration>>>,
) -> Vec<(A, AttributeConfig, Stream<S, ((Value, Value), Duration, isize)>)> {
let filename = self.path.clone();
// The following is mostly the innards of
// `generic::source`. We use a builder directly, because we
// need multiple outputs (one for each attribute the user has
// epxressed interest in).
let mut demux = OperatorBuilder::new(format!("JsonFile({})", filename), scope.clone());
let operator_info = demux.operator_info();
demux.set_notify(false);
let mut wrappers = Vec::with_capacity(self.attributes.len());
let mut streams = Vec::with_capacity(self.attributes.len());
for _ in self.attributes.iter() {
let (wrapper, stream) = demux.new_output();
wrappers.push(wrapper);
streams.push(stream);
}
let scope_handle = scope.clone();
let attributes = self.attributes.clone();
demux.build(move |mut capabilities| {
let scope = scope_handle;
let activator = scope.activator_for(&operator_info.address[..]);
let worker_index = scope.index();
let num_workers = scope.peers();
let path = Path::new(&filename);
let file = File::open(&path).unwrap();
// let reader = BufReader::new(GzDecoder::new(file));
let reader = BufReader::new(file);
let mut iterator = reader.lines().peekable();
let mut num_objects_read = 0;
let mut object_index = 0;
move |_frontiers| {
let mut handles = Vec::with_capacity(attributes.len());
for wrapper in wrappers.iter_mut() {
handles.push(wrapper.activate());
}
if iterator.peek().is_some() {
let mut sessions = Vec::with_capacity(attributes.len());
for (idx, handle) in handles.iter_mut().enumerate() {
sessions.push(handle.session(capabilities.get(idx).unwrap()));
}
let time = Instant::now().duration_since(t0);
for readline in iterator.by_ref().take(256 - 1) {
let line = readline.expect("read error");
if (object_index % num_workers == worker_index) && !line.is_empty() {
// @TODO parse only the names we are interested in
// @TODO run with Value = serde_json::Value
let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
let obj_map = obj.as_object().unwrap();
// In the common case we assume that all objects share
// roughly the same number of attributes, a (potentially small)
// subset of which is actually requested downstream.
//
// otherwise:
// for (k, v) in obj.as_object().unwrap() {
for (idx, aid) in attributes.iter().enumerate() {
match obj_map.get(aid) {
None => {}
Some(json_value) => {
let v = match *json_value {
serde_json::Value::String(ref s) => Value::String(s.to_string()),
serde_json::Value::Number(ref num) => {
match num.as_i64() {
None => panic!("only i64 supported at the moment"),
Some(num) => Number(num),
}
},
serde_json::Value::Bool(ref b) => Bool(*b),
_ => panic!("only strings, booleans, and i64 types supported at the moment"),
};
let tuple = (Value::Eid(object_index as Eid), v);
sessions.get_mut(idx)
.unwrap()
.give((tuple, time, 1));
}
}
}
num_objects_read += 1;
}
object_index += 1;
}
// println!("[W{}] read {} out of {} objects", worker_index, num_objects_read, object_index);
activator.activate();
} else {
capabilities.drain(..);
}
}
});
streams
}
}
|
// Crates
extern crate chrono;
extern crate docopt;
extern crate rustc_serialize;
// Standard library imports
// Local modules
mod altdate;
// Crate imports
use chrono::Datelike;
use docopt::Docopt;
static VERSION: &'static str = "ddate (RUST implementaion of gnucoreutils) 0.1
Copyright (C) 2016 Marco Kaulea
License GPLv2: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Marco 'don' Kaulea.
";
const USAGE: &'static str = "
ddate
USAGE:
ddate [options] [<date>]
Options:
-h --help Dispaly this help message and exit
-v --version Output version information and exit
-d --discordian Switch to output discordian dates. This is the default
-t --timestamp Date specifies a timestamp, instead of an isodate
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_date: Option<String>,
flag_help: bool,
flag_version: bool,
flag_discordian: bool,
flag_timestamp: bool,
}
/// Determines which time format should be parsed
fn get_input_type(args: &Args) -> altdate::InputType {
if args.flag_timestamp {
altdate::InputType::UnixTimestamp
} else {
altdate::InputType::Iso6801
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if args.flag_version {
println!("{}", VERSION);
return;
}
let input_type = get_input_type(&args);
let input_date = match args.arg_date {
None => {
let today = chrono::offset::local::Local::today();
today.naive_local()
},
Some(raw_date) => altdate::parse_date(&raw_date, input_type),
};
let date = altdate::ddate::convert(input_date.ordinal0() as u16,
input_date.year() as i32).unwrap();
println!("{:?}, ", date);
}
|
use std::io;
use std::path::PathBuf;
#[derive(Debug)]
pub enum Error {
Json(serde_json::Error),
Io(io::Error),
Ini(ini::ini::ParseError),
SectionMissing,
FileNotFound(PathBuf),
HomeNotFound,
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Error::Json(error)
}
}
impl From<ini::ini::ParseError> for Error {
fn from(error: ini::ini::ParseError) -> Self {
Error::Ini(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Error::Io(error)
}
}
|
#[cfg(all(not(target_arch = "wasm32"), feature = "gamepads"))]
use gilrs;
#[cfg(not(target_arch = "wasm32"))]
use glutin;
use image;
#[cfg(all(not(target_arch = "wasm32"), feature = "rodio"))]
use rodio;
use crate::graphics::{AtlasError, ImageError};
#[cfg(feature = "rusttype")]
use rusttype::Error as FontError;
#[cfg(feature = "saving")]
use crate::saving::SaveError;
#[cfg(feature = "sounds")]
use crate::sound::SoundError;
use std::{fmt, error::Error, io::Error as IOError};
#[derive(Debug)]
/// An error generated by some Quicksilver subsystem
pub enum QuicksilverError {
/// An error from an image atlas
AtlasError(AtlasError),
/// Creating or manipulating the OpenGL Context failed
ContextError(String),
/// An error from loading an image
ImageError(ImageError),
/// An error from loading a file
IOError(IOError),
/// An error when creating a gilrs context
#[cfg(feature = "gamepads")]
GilrsError(gilrs::Error),
/// An error from loading a sound
#[cfg(feature = "sounds")]
SoundError(SoundError),
/// A serialize or deserialize error
#[cfg(feature = "saving")]
SaveError(SaveError),
/// There was an error loading a font file
#[cfg(feature = "rusttype")]
FontError(FontError),
}
impl fmt::Display for QuicksilverError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for QuicksilverError {
fn description(&self) -> &str {
match self {
QuicksilverError::AtlasError(err) => err.description(),
QuicksilverError::ContextError(string) => string.as_str(),
QuicksilverError::ImageError(err) => err.description(),
QuicksilverError::IOError(err) => err.description(),
#[cfg(feature = "gamepads")]
QuicksilverError::GilrsError(err) => err.description(),
#[cfg(feature = "sounds")]
QuicksilverError::SoundError(err) => err.description(),
#[cfg(feature = "saving")]
QuicksilverError::SaveError(err) => err.description(),
#[cfg(feature = "rusttype")]
QuicksilverError::FontError(err) => err.description(),
}
}
fn cause(&self) -> Option<&dyn Error> {
match self {
QuicksilverError::AtlasError(err) => Some(err),
QuicksilverError::ContextError(_) => None,
QuicksilverError::ImageError(err) => Some(err),
QuicksilverError::IOError(err) => Some(err),
#[cfg(feature = "gamepads")]
QuicksilverError::GilrsError(err) => Some(err),
#[cfg(feature = "sounds")]
QuicksilverError::SoundError(err) => Some(err),
#[cfg(feature = "saving")]
QuicksilverError::SaveError(err) => Some(err),
#[cfg(feature = "rusttype")]
QuicksilverError::FontError(err) => Some(err),
}
}
}
#[doc(hidden)]
impl From<ImageError> for QuicksilverError {
fn from(err: ImageError) -> QuicksilverError {
QuicksilverError::ImageError(err)
}
}
#[doc(hidden)]
#[cfg(feature = "sounds")]
impl From<SoundError> for QuicksilverError {
fn from(err: SoundError) -> QuicksilverError {
QuicksilverError::SoundError(err)
}
}
#[doc(hidden)]
impl From<AtlasError> for QuicksilverError {
fn from(err: AtlasError) -> QuicksilverError {
QuicksilverError::AtlasError(err)
}
}
impl From<IOError> for QuicksilverError {
fn from(err: IOError) -> QuicksilverError {
QuicksilverError::IOError(err)
}
}
#[cfg(feature = "saving")]
impl From<SaveError> for QuicksilverError {
fn from(err: SaveError) -> QuicksilverError {
QuicksilverError::SaveError(err)
}
}
#[doc(hidden)]
impl From<image::ImageError> for QuicksilverError {
fn from(img: image::ImageError) -> QuicksilverError {
let image_error: ImageError = img.into();
image_error.into()
}
}
#[doc(hidden)]
#[cfg(all(feature = "sounds", not(target_arch = "wasm32")))]
impl From<rodio::decoder::DecoderError> for QuicksilverError {
fn from(snd: rodio::decoder::DecoderError) -> QuicksilverError {
let sound_error: SoundError = snd.into();
sound_error.into()
}
}
#[doc(hidden)]
#[cfg(feature = "rusttype")]
impl From<FontError> for QuicksilverError {
fn from(fnt: FontError) -> QuicksilverError {
QuicksilverError::FontError(fnt)
}
}
#[cfg(not(target_arch = "wasm32"))]
const ROBUST_ERROR: &str = r#"Internal Quicksilver error: robustness not supported
Please file a bug report at https://github.com/ryanisaacg/quicksilver that includes:
- A minimum reproducing code snippet
- The error message above
"#;
#[cfg(not(target_arch = "wasm32"))]
fn creation_to_str(err: &glutin::CreationError) -> String {
match err {
glutin::CreationError::OsError(string) => string.to_owned(),
glutin::CreationError::NotSupported(err) => (*err).to_owned(),
glutin::CreationError::NoBackendAvailable(error) => error.to_string(),
glutin::CreationError::RobustnessNotSupported => ROBUST_ERROR.to_owned(),
glutin::CreationError::OpenGlVersionNotSupported => {
"OpenGL version not supported".to_owned()
}
glutin::CreationError::NoAvailablePixelFormat => "No available pixel format".to_owned(),
glutin::CreationError::PlatformSpecific(string) => string.to_owned(),
glutin::CreationError::Window(error) => match error {
glutin::WindowCreationError::OsError(string) => string.to_owned(),
glutin::WindowCreationError::NotSupported => {
"Window creation failed: not supported".to_owned()
}
},
glutin::CreationError::CreationErrors(errors) => {
format!("{:?}", errors)
}
}
}
#[doc(hidden)]
#[cfg(not(target_arch = "wasm32"))]
impl From<glutin::CreationError> for QuicksilverError {
fn from(err: glutin::CreationError) -> QuicksilverError {
QuicksilverError::ContextError(creation_to_str(&err))
}
}
#[doc(hidden)]
#[cfg(not(target_arch = "wasm32"))]
impl From<glutin::ContextError> for QuicksilverError {
fn from(err: glutin::ContextError) -> QuicksilverError {
match err {
glutin::ContextError::IoError(err) => QuicksilverError::IOError(err),
glutin::ContextError::OsError(err) => QuicksilverError::ContextError(err),
glutin::ContextError::ContextLost => {
QuicksilverError::ContextError("Context lost".to_owned())
}
}
}
}
#[doc(hidden)]
#[cfg(feature = "gamepads")]
impl From<gilrs::Error> for QuicksilverError {
fn from(err: gilrs::Error) -> QuicksilverError {
QuicksilverError::GilrsError(err)
}
}
|
#[derive(Debug)]
struct RectangularArray<T> {
width: usize,
height: usize,
data: Vec<Vec<T>>,
}
fn main() {
let two_by_three_data = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
let two_by_three = RectangularArray::<i32> {
width: 2,
height: 3,
data: two_by_three_data,
};
println!("{:?}", two_by_three);
let three_by_two_data = vec![vec![1, 2, 3], vec![4, 5, 6]];
let three_by_two = RectangularArray::<i32> {
width: 3,
height: 2,
data: three_by_two_data,
};
println!("{:?}", three_by_two);
}
|
use std::cell::RefCell;
use resource::Resource;
thread_local! {
static STDIN: RefCell<Resource> = RefCell::new(
Resource::open(b"std://in").unwrap()
);
static STDOUT: RefCell<Resource> = RefCell::new(
Resource::open(b"std://out").unwrap()
);
static STDERR: RefCell<Resource> = RefCell::new(
Resource::open(b"std://err").unwrap()
);
}
pub fn with_stdin<F: FnOnce(&mut Resource) -> T, T>(f: F) -> T {
STDIN.with(|h| f(&mut *h.borrow_mut()))
}
pub fn with_stdout<F: FnOnce(&mut Resource) -> T, T>(f: F) -> T {
STDOUT.with(|h| f(&mut *h.borrow_mut()))
}
pub fn with_stderr<F: FnOnce(&mut Resource) -> T, T>(f: F) -> T {
STDERR.with(|h| f(&mut *h.borrow_mut()))
}
|
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
fn main() {
let n: usize = parse_line().unwrap();
if n % 2 == 1 {
return;
}
dfs("".to_string(), n / 2, n / 2);
}
fn dfs(now: String, leftleft: usize, rightleft: usize) {
if leftleft == 0 && rightleft == 0 {
if check(now.clone()) {
println!("{}", now);
}
} else if leftleft != 0 && rightleft != 0 {
dfs(now.clone() + "(", leftleft - 1, rightleft);
dfs(now.clone() + ")", leftleft, rightleft - 1);
} else if rightleft != 0 {
dfs(now.clone() + ")", leftleft, rightleft - 1);
} else if leftleft != 0 {
dfs(now.clone() + "(", leftleft - 1, rightleft);
}
}
fn check(s: String) -> bool {
let mut left = 0;
let mut right = 0;
for c in s.chars() {
if c == '(' {
left += 1;
} else if c == ')' {
right += 1;
}
if left < right {
return false;
}
}
true
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qsharedmemory.h
// dst-file: /src/core/qsharedmemory.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::qobject::*; // 773
use std::ops::Deref;
use super::qstring::*; // 773
use super::qobjectdefs::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QSharedMemory_Class_Size() -> c_int;
// proto: int QSharedMemory::size();
fn C_ZNK13QSharedMemory4sizeEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QSharedMemory::setNativeKey(const QString & key);
fn C_ZN13QSharedMemory12setNativeKeyERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QSharedMemory::QSharedMemory(const QString & key, QObject * parent);
fn C_ZN13QSharedMemoryC2ERK7QStringP7QObject(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: QString QSharedMemory::errorString();
fn C_ZNK13QSharedMemory11errorStringEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QSharedMemory::setKey(const QString & key);
fn C_ZN13QSharedMemory6setKeyERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QString QSharedMemory::key();
fn C_ZNK13QSharedMemory3keyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const void * QSharedMemory::constData();
fn C_ZNK13QSharedMemory9constDataEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void * QSharedMemory::data();
fn C_ZN13QSharedMemory4dataEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QSharedMemory::isAttached();
fn C_ZNK13QSharedMemory10isAttachedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QSharedMemory::lock();
fn C_ZN13QSharedMemory4lockEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QSharedMemory::~QSharedMemory();
fn C_ZN13QSharedMemoryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: bool QSharedMemory::unlock();
fn C_ZN13QSharedMemory6unlockEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QSharedMemory::detach();
fn C_ZN13QSharedMemory6detachEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QString QSharedMemory::nativeKey();
fn C_ZNK13QSharedMemory9nativeKeyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const QMetaObject * QSharedMemory::metaObject();
fn C_ZNK13QSharedMemory10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QSharedMemory::QSharedMemory(QObject * parent);
fn C_ZN13QSharedMemoryC2EP7QObject(arg0: *mut c_void) -> u64;
} // <= ext block end
// body block begin =>
// class sizeof(QSharedMemory)=1
#[derive(Default)]
pub struct QSharedMemory {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QSharedMemory {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSharedMemory {
return QSharedMemory{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QSharedMemory {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QSharedMemory {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: int QSharedMemory::size();
impl /*struct*/ QSharedMemory {
pub fn size<RetType, T: QSharedMemory_size<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.size(self);
// return 1;
}
}
pub trait QSharedMemory_size<RetType> {
fn size(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: int QSharedMemory::size();
impl<'a> /*trait*/ QSharedMemory_size<i32> for () {
fn size(self , rsthis: & QSharedMemory) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory4sizeEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory4sizeEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QSharedMemory::setNativeKey(const QString & key);
impl /*struct*/ QSharedMemory {
pub fn setNativeKey<RetType, T: QSharedMemory_setNativeKey<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setNativeKey(self);
// return 1;
}
}
pub trait QSharedMemory_setNativeKey<RetType> {
fn setNativeKey(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: void QSharedMemory::setNativeKey(const QString & key);
impl<'a> /*trait*/ QSharedMemory_setNativeKey<()> for (&'a QString) {
fn setNativeKey(self , rsthis: & QSharedMemory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemory12setNativeKeyERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN13QSharedMemory12setNativeKeyERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QSharedMemory::QSharedMemory(const QString & key, QObject * parent);
impl /*struct*/ QSharedMemory {
pub fn new<T: QSharedMemory_new>(value: T) -> QSharedMemory {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QSharedMemory_new {
fn new(self) -> QSharedMemory;
}
// proto: void QSharedMemory::QSharedMemory(const QString & key, QObject * parent);
impl<'a> /*trait*/ QSharedMemory_new for (&'a QString, Option<&'a QObject>) {
fn new(self) -> QSharedMemory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemoryC2ERK7QStringP7QObject()};
let ctysz: c_int = unsafe{QSharedMemory_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN13QSharedMemoryC2ERK7QStringP7QObject(arg0, arg1)};
let rsthis = QSharedMemory{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QString QSharedMemory::errorString();
impl /*struct*/ QSharedMemory {
pub fn errorString<RetType, T: QSharedMemory_errorString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.errorString(self);
// return 1;
}
}
pub trait QSharedMemory_errorString<RetType> {
fn errorString(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: QString QSharedMemory::errorString();
impl<'a> /*trait*/ QSharedMemory_errorString<QString> for () {
fn errorString(self , rsthis: & QSharedMemory) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory11errorStringEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory11errorStringEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QSharedMemory::setKey(const QString & key);
impl /*struct*/ QSharedMemory {
pub fn setKey<RetType, T: QSharedMemory_setKey<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setKey(self);
// return 1;
}
}
pub trait QSharedMemory_setKey<RetType> {
fn setKey(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: void QSharedMemory::setKey(const QString & key);
impl<'a> /*trait*/ QSharedMemory_setKey<()> for (&'a QString) {
fn setKey(self , rsthis: & QSharedMemory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemory6setKeyERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN13QSharedMemory6setKeyERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QString QSharedMemory::key();
impl /*struct*/ QSharedMemory {
pub fn key<RetType, T: QSharedMemory_key<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.key(self);
// return 1;
}
}
pub trait QSharedMemory_key<RetType> {
fn key(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: QString QSharedMemory::key();
impl<'a> /*trait*/ QSharedMemory_key<QString> for () {
fn key(self , rsthis: & QSharedMemory) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory3keyEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory3keyEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const void * QSharedMemory::constData();
impl /*struct*/ QSharedMemory {
pub fn constData<RetType, T: QSharedMemory_constData<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.constData(self);
// return 1;
}
}
pub trait QSharedMemory_constData<RetType> {
fn constData(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: const void * QSharedMemory::constData();
impl<'a> /*trait*/ QSharedMemory_constData<*mut c_void> for () {
fn constData(self , rsthis: & QSharedMemory) -> *mut c_void {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory9constDataEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory9constDataEv(rsthis.qclsinst)};
return ret as *mut c_void; // 1
// return 1;
}
}
// proto: void * QSharedMemory::data();
impl /*struct*/ QSharedMemory {
pub fn data<RetType, T: QSharedMemory_data<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.data(self);
// return 1;
}
}
pub trait QSharedMemory_data<RetType> {
fn data(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: void * QSharedMemory::data();
impl<'a> /*trait*/ QSharedMemory_data<*mut c_void> for () {
fn data(self , rsthis: & QSharedMemory) -> *mut c_void {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemory4dataEv()};
let mut ret = unsafe {C_ZN13QSharedMemory4dataEv(rsthis.qclsinst)};
return ret as *mut c_void; // 1
// return 1;
}
}
// proto: bool QSharedMemory::isAttached();
impl /*struct*/ QSharedMemory {
pub fn isAttached<RetType, T: QSharedMemory_isAttached<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isAttached(self);
// return 1;
}
}
pub trait QSharedMemory_isAttached<RetType> {
fn isAttached(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: bool QSharedMemory::isAttached();
impl<'a> /*trait*/ QSharedMemory_isAttached<i8> for () {
fn isAttached(self , rsthis: & QSharedMemory) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory10isAttachedEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory10isAttachedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QSharedMemory::lock();
impl /*struct*/ QSharedMemory {
pub fn lock<RetType, T: QSharedMemory_lock<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.lock(self);
// return 1;
}
}
pub trait QSharedMemory_lock<RetType> {
fn lock(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: bool QSharedMemory::lock();
impl<'a> /*trait*/ QSharedMemory_lock<i8> for () {
fn lock(self , rsthis: & QSharedMemory) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemory4lockEv()};
let mut ret = unsafe {C_ZN13QSharedMemory4lockEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QSharedMemory::~QSharedMemory();
impl /*struct*/ QSharedMemory {
pub fn free<RetType, T: QSharedMemory_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QSharedMemory_free<RetType> {
fn free(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: void QSharedMemory::~QSharedMemory();
impl<'a> /*trait*/ QSharedMemory_free<()> for () {
fn free(self , rsthis: & QSharedMemory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemoryD2Ev()};
unsafe {C_ZN13QSharedMemoryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QSharedMemory::unlock();
impl /*struct*/ QSharedMemory {
pub fn unlock<RetType, T: QSharedMemory_unlock<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.unlock(self);
// return 1;
}
}
pub trait QSharedMemory_unlock<RetType> {
fn unlock(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: bool QSharedMemory::unlock();
impl<'a> /*trait*/ QSharedMemory_unlock<i8> for () {
fn unlock(self , rsthis: & QSharedMemory) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemory6unlockEv()};
let mut ret = unsafe {C_ZN13QSharedMemory6unlockEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QSharedMemory::detach();
impl /*struct*/ QSharedMemory {
pub fn detach<RetType, T: QSharedMemory_detach<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.detach(self);
// return 1;
}
}
pub trait QSharedMemory_detach<RetType> {
fn detach(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: bool QSharedMemory::detach();
impl<'a> /*trait*/ QSharedMemory_detach<i8> for () {
fn detach(self , rsthis: & QSharedMemory) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemory6detachEv()};
let mut ret = unsafe {C_ZN13QSharedMemory6detachEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QString QSharedMemory::nativeKey();
impl /*struct*/ QSharedMemory {
pub fn nativeKey<RetType, T: QSharedMemory_nativeKey<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.nativeKey(self);
// return 1;
}
}
pub trait QSharedMemory_nativeKey<RetType> {
fn nativeKey(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: QString QSharedMemory::nativeKey();
impl<'a> /*trait*/ QSharedMemory_nativeKey<QString> for () {
fn nativeKey(self , rsthis: & QSharedMemory) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory9nativeKeyEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory9nativeKeyEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QSharedMemory::metaObject();
impl /*struct*/ QSharedMemory {
pub fn metaObject<RetType, T: QSharedMemory_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QSharedMemory_metaObject<RetType> {
fn metaObject(self , rsthis: & QSharedMemory) -> RetType;
}
// proto: const QMetaObject * QSharedMemory::metaObject();
impl<'a> /*trait*/ QSharedMemory_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QSharedMemory) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QSharedMemory10metaObjectEv()};
let mut ret = unsafe {C_ZNK13QSharedMemory10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QSharedMemory::QSharedMemory(QObject * parent);
impl<'a> /*trait*/ QSharedMemory_new for (Option<&'a QObject>) {
fn new(self) -> QSharedMemory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QSharedMemoryC2EP7QObject()};
let ctysz: c_int = unsafe{QSharedMemory_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN13QSharedMemoryC2EP7QObject(arg0)};
let rsthis = QSharedMemory{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
//https://leetcode.com/problems/determine-color-of-a-chessboard-square/
impl Solution {
pub fn square_is_white(coordinates: String) -> bool {
let position_parity = coordinates.chars().nth(0).unwrap() as u8 - 'a' as u8
+ coordinates.chars().nth(1).unwrap() as u8 - '1' as u8;
position_parity%2 == 1
}
} |
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that we can combine a default impl that supplies one method with a
// full impl that supplies the other, and they can invoke one another.
#![feature(specialization)]
trait Foo {
fn foo_one(&self) -> &'static str;
fn foo_two(&self) -> &'static str;
fn foo_three(&self) -> &'static str;
}
struct MyStruct;
default impl<T> Foo for T {
fn foo_one(&self) -> &'static str {
self.foo_three()
}
}
impl Foo for MyStruct {
fn foo_two(&self) -> &'static str {
self.foo_one()
}
fn foo_three(&self) -> &'static str {
"generic"
}
}
fn main() {
assert!(MyStruct.foo_two() == "generic");
}
|
//! https://github.com/lumen/otp/tree/lumen/lib/megaco/src/engine
use super::*;
test_compiles_lumen_otp!(megaco_config);
test_compiles_lumen_otp!(megaco_config_misc);
test_compiles_lumen_otp!(megaco_digit_map);
test_compiles_lumen_otp!(megaco_edist_compress);
test_compiles_lumen_otp!(megaco_encoder);
test_compiles_lumen_otp!(megaco_erl_dist_encoder);
test_compiles_lumen_otp!(megaco_erl_dist_encoder_mc);
test_compiles_lumen_otp!(megaco_filter);
test_compiles_lumen_otp!(megaco_messenger);
test_compiles_lumen_otp!(megaco_messenger_misc);
test_compiles_lumen_otp!(megaco_misc_sup);
test_compiles_lumen_otp!(megaco_monitor);
test_compiles_lumen_otp!(megaco_sdp);
test_compiles_lumen_otp!(megaco_stats);
test_compiles_lumen_otp!(megaco_sup);
test_compiles_lumen_otp!(megaco_timer);
test_compiles_lumen_otp!(megaco_trans_sender);
test_compiles_lumen_otp!(megaco_trans_sup);
test_compiles_lumen_otp!(megaco_transport);
test_compiles_lumen_otp!(megaco_user);
test_compiles_lumen_otp!(megaco_user_default);
fn includes() -> Vec<&'static str> {
let mut includes = super::includes();
includes.push("lib/megaco/src/engine");
includes
}
fn relative_directory_path() -> PathBuf {
super::relative_directory_path().join("engine")
}
|
#[macro_use]
extern crate serde_derive;
use futures::future::ok;
use futures::prelude::*;
use hyper::{client::Client, Body, Uri};
use std::vec::Vec;
use tokio_core::reactor::Core;
use serde::de::DeserializeOwned;
#[derive(Deserialize, Serialize, Debug)]
struct Todo {
id: usize,
#[serde(rename = "userId")]
user_id: usize,
title: String,
completed: bool,
}
#[derive(Deserialize, Debug)]
struct Image {
#[serde(rename = "albumId")]
album_id : usize,
id: usize,
title: String,
url: String,
#[serde(rename = "thumbnailUrl")]
thumbnail_url: String
}
type ResponseResult<T> = Result<T, hyper::error::Error>;
type HttpsConnector = hyper_rustls::HttpsConnector<hyper::client::HttpConnector>;
struct RequestExecutor {
client: Client<HttpsConnector, Body>,
}
impl RequestExecutor {
pub fn new() -> RequestExecutor {
RequestExecutor {
client: Client::builder().build(HttpsConnector::new(4)),
}
}
pub fn get<S, T>(&mut self, url: S) -> ResponseResult<T>
where
S: Into<String>,
T: DeserializeOwned,
{
let work = self
.client
.get(url.into().parse::<Uri>().unwrap())
.and_then(|resp| {
resp.into_body()
.fold(Vec::new(), |mut v, chunk| {
v.extend(&chunk[..]);
ok::<_, hyper::Error>(v)
})
.map(move |chunks| serde_json::from_slice::<T>(&chunks).unwrap())
});
Core::new().unwrap().run(work)
}
}
fn main() {
let mut req_executor = RequestExecutor::new();
let todo : ResponseResult<Todo> = req_executor.get("https://jsonplaceholder.typicode.com/todos/1");
let todo3 : ResponseResult<Todo>= req_executor.get("https://jsonplaceholder.typicode.com/todos/3");
let todo7 : ResponseResult<Todo> = req_executor.get("https://jsonplaceholder.typicode.com/todos/7");
let todo15 : ResponseResult<Todo> = req_executor.get("https://jsonplaceholder.typicode.com/todos/15");
println!("{:?}", todo.unwrap());
println!("{:?}", todo3.unwrap());
println!("{:?}", todo7.unwrap());
println!("{:?}", todo15.unwrap());
let photo10 : ResponseResult<Image> = req_executor.get("https://jsonplaceholder.typicode.com/photos/10");
let photo12 : ResponseResult<Image> = req_executor.get("https://jsonplaceholder.typicode.com/photos/12");
let photo20 : ResponseResult<Image> = req_executor.get("https://jsonplaceholder.typicode.com/photos/20");
println!("{:?}", photo10.unwrap());
println!("{:?}", photo12.unwrap());
println!("{:?}", photo20.unwrap());
}
|
use yew::prelude::*;
pub struct SmsTry {}
pub enum Msg {}
impl Component for SmsTry {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
SmsTry {}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<div class="p-2" style="font-size: 14px;">
<div class="mt-2 mb-3">
<div class="alert alert-primary d-flex align-items-center" role="alert">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-exclamation-triangle-fill flex-shrink-0 me-2" viewBox="0 0 16 16" role="img" aria-label="Warning:">
<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
</svg>
<div>
{"You need to enable one application at least in order to be able to try this connection."}
</div>
</div>
</div>
<div class="mb-3">
<p class="text-muted">{"Try this connection by specifying an application and a recipient. An SMS will be sent to the specified number."}</p>
</div>
<div class="mb-3">
<label class="form-label text-muted">{"Application"}</label>
<select class="form-select" aria-label="Disabled select example" disabled=true>
<option selected=true>{""}</option>
<option value="1">{""}</option>
<option value="2">{""}</option>
<option value="3">{""}</option>
</select>
<div class="pt-1">
<p class="text-muted">{"The application on which you want to try this connection."}</p>
</div>
</div>
<div class="mb-3">
<label class="form-label text-muted">{"SMS recipient"}</label>
<input type="text" id="disabledTextInput" class="form-control" placeholder="+15555555" disabled=true />
<div class="pt-1">
<p class="text-muted">{"The cellphone number to receive the test sms."}</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">{"Try"}</button>
</div>
</div>
}
}
}
|
use tokio::net::TcpListener;
use tokio::prelude::*;
use futures::stream::StreamExt;
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:6142";
let mut listener = TcpListener::bind(addr).await.unwrap();
// Here we convert the `TcpListener` to a stream of incoming connections
// with the `incoming` method. We then define how to process each element in
// the stream with the `for_each` combinator method
let server = async move {
let mut incoming = listener.incoming();
while let Some(socket_res) = incoming.for_each(|_a|{_a}).await {
match socket_res {
Ok(socket) => {
println!("Accepted connection from {:?}", socket.peer_addr());
// TODO: Process socket
}
Err(err) => {
// Handle error by printing to STDOUT.
println!("accept error = {:?}", err);
}
}
}
};
println!("Server running on localhost:6142");
// Start the server and block this async fn until `server` spins down.
server.await;
} |
extern crate core;
extern crate ggez;
extern crate rand;
use ggez::{GameResult, Context};
use ggez::event::{self, Keycode, Mod};
use ggez::graphics::{self, Font};
use ggez::timer;
use rand::Rng;
mod ai;
mod animation;
mod bg;
mod bomb;
mod car;
mod center;
mod checkpoint;
mod globals;
mod hex;
mod map;
mod racer;
mod text;
mod vector;
use ai::Ai;
use animation::*;
use globals::*;
use hex::{HexPoint};
use map::Map;
use racer::Racer;
#[derive(Debug)]
struct Assets {
bg: bg::Assets,
bomb: bomb::Assets,
car: car::Assets,
checkpoint: checkpoint::Assets,
hex: hex::Assets,
map: map::Assets,
}
fn load_assets(ctx: &mut Context) -> GameResult<Assets> {
let font = Font::default_font()?;
Ok(Assets {
bg: bg::load_assets(ctx)?,
bomb: bomb::load_assets(ctx)?,
car: car::load_assets(ctx)?,
checkpoint: checkpoint::load_assets(ctx, &font)?,
hex: hex::load_assets(ctx)?,
map: map::load_assets(ctx)?,
})
}
#[derive(Clone, Copy, Debug)]
enum State {
WaitingForInput,
WaitingForAnimation(
Option<(TranslationAnimation, Racer)>,
Option<(TranslationAnimation, Ai)>,
Option<(TranslationAnimation, Ai)>,
),
}
#[derive(Debug)]
struct Globals {
assets: Assets,
exec_time: f32,
map: Map,
car3: Ai,
car2: Ai,
car1: Racer,
state: State,
race_result: Option<bool>,
}
impl Globals {
fn new(ctx: &mut Context) -> GameResult<Globals> {
let (exec_time, map, car3, car2, car1, state, race_result) = Globals::new_everything();
Ok(Globals {
assets: load_assets(ctx)?,
exec_time,
map,
car3,
car2,
car1,
state,
race_result,
})
}
fn reset(&mut self) {
let (exec_time, map, car3, car2, car1, state, race_result) = Globals::new_everything();
self.exec_time = exec_time;
self.map = map;
self.car3 = car3;
self.car2 = car2;
self.car1 = car1;
self.state = state;
self.race_result = race_result;
}
fn new_everything() -> (f32, Map, Ai, Ai, Racer, State, Option<bool>) {
let mut map = Map::load();
let car3 = Racer::new(3, HexPoint::new(CENTRAL_OBSTACLE_RADIUS+1, 0));
car3.insert(&mut map);
let car2 = Racer::new(2, HexPoint::new(CENTRAL_OBSTACLE_RADIUS+2, 0));
car2.insert(&mut map);
let car1 = Racer::new(1, HexPoint::new(CENTRAL_OBSTACLE_RADIUS+3, 0));
car1.insert(&mut map);
let mut rng = rand::thread_rng();
for _i in 0..15 {
if let Some(hex_point) = map.random_available_spot() {
let fuse_length = rng.gen_range(1, MAX_FUSE_LENGTH+1);
map.insert_bomb(hex_point, fuse_length);
}
}
(0.0, map, Ai::new(car3), Ai::new(car2), car1, State::WaitingForInput, None)
}
fn set_car3(&mut self, ctx: &Context, car3: Ai) {
self.car3.racer.remove(&mut self.map);
let animation = TranslationAnimation::new(
get_current_time(ctx),
0.25,
self.car3.racer.position.to_point(),
car3.racer.position.to_point(),
DrawableObject::DrawableCar(car3.racer.to_car()),
);
match self.state {
State::WaitingForAnimation(a1, a2, _a3) =>
self.state = State::WaitingForAnimation(a1, a2, Some((animation, car3))),
_ => {
self.state = State::WaitingForAnimation(None, None, Some((animation, car3)));
},
}
// self.state = State::WaitingForAnimation(animation, car3: car3.racer);
// self.car3 = car3;
// self.car3.racer.insert(&mut self.map);
}
fn set_car2(&mut self, ctx: &Context, car2: Ai) {
self.car2.racer.remove(&mut self.map);
let animation = TranslationAnimation::new(
get_current_time(ctx),
0.25,
self.car2.racer.position.to_point(),
car2.racer.position.to_point(),
DrawableObject::DrawableCar(car2.racer.to_car()),
);
match self.state {
State::WaitingForAnimation(a1, _a2, a3) =>
self.state = State::WaitingForAnimation(a1, Some((animation, car2)), a3),
_ => {
self.state = State::WaitingForAnimation(None, Some((animation, car2)), None);
},
}
}
fn set_car1(&mut self, ctx: &Context, car1: Racer) {
self.car1.remove(&mut self.map);
let animation = TranslationAnimation::new(
get_current_time(ctx),
0.25,
self.car1.position.to_point(),
car1.position.to_point(),
DrawableObject::DrawableCar(car1.to_car()),
);
match self.state {
State::WaitingForAnimation(_a1, a2, a3) =>
self.state = State::WaitingForAnimation(Some((animation, car1)), a2, a3),
_ => {
self.state = State::WaitingForAnimation(Some((animation, car1)), None, None);
},
}
}
fn turn_left(&mut self, ctx: &Context) {
let car1 = self.car1.turn_left();
self.set_car1(ctx, car1)
}
fn turn_right(&mut self, ctx: &Context) {
let car1 = self.car1.turn_right();
self.set_car1(ctx, car1)
}
fn go_forward(&mut self, ctx: &Context) {
if let Some(car1) = self.car1.go_forward(&self.map) {
self.set_car1(ctx, car1);
}
}
fn go_backwards(&mut self, ctx: &Context) {
if let Some(car1) = self.car1.go_backwards(&self.map) {
self.set_car1(ctx, car1);
}
}
fn go_back_to_checkpoint(&mut self, ctx: &Context) {
let car1 = self.car1.go_back_to_checkpoint(&self.map);
self.set_car1(ctx, car1);
}
}
impl event::EventHandler for Globals {
fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
match self.state {
State::WaitingForAnimation(mut a1, mut a2, mut a3) => {
let current_time = get_current_time(ctx);
if let Some((animation1, car1)) = a1 {
if animation1.is_finished(current_time) {
self.car1 = car1;
self.car1.insert(&mut self.map);
a1 = None;
}
}
if let Some((animation2, car2)) = a2 {
if animation2.is_finished(current_time) {
self.car2 = car2;
self.car2.racer.insert(&mut self.map);
a2 = None;
}
}
if let Some((animation3, car3)) = a3 {
if animation3.is_finished(current_time) {
self.car3 = car3;
self.car3.racer.insert(&mut self.map);
a3 = None;
}
}
if a1.is_none() && a2.is_none() && a3.is_none() {
self.map.decrement_all_bombs();
self.state = State::WaitingForInput;
} else {
self.state = State::WaitingForAnimation(a1, a2, a3);
}
},
State::WaitingForInput => (),
}
Ok(())
}
fn key_up_event(&mut self, ctx: &mut Context, keycode: Keycode, _keymod: Mod, _repeat: bool) {
match self.state {
State::WaitingForInput => {
let action3 = self.car3.next_action();
let car3 = self.car3.perform_action(action3, &mut self.map);
self.set_car3(ctx, car3);
let action2 = self.car2.next_action();
let car2 = self.car2.perform_action(action2, &mut self.map);
self.set_car2(ctx, car2);
match keycode {
Keycode::Left => self.turn_left(ctx),
Keycode::Right => self.turn_right(ctx),
Keycode::Up => self.go_forward(ctx),
Keycode::Down => self.go_backwards(ctx),
Keycode::K => self.go_back_to_checkpoint(ctx),
Keycode::R => self.reset(),
_ => (),
}
},
_ => (),
}
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
bg::draw_bg(ctx, &self.assets.bg)?;
hex::draw_hex_grid(
ctx,
&self.assets.hex,
)?;
self.map.draw(ctx, &self.assets.map, &self.assets.bomb, &self.assets.car)?;
match self.state {
State::WaitingForAnimation(a1, a2, a3) => {
let current_time = get_current_time(ctx);
if let Some((animation1, _car1)) = a1 {
animation1.draw(ctx, &self.assets.car, current_time)?;
}
if let Some((animation2, _car2)) = a2 {
animation2.draw(ctx, &self.assets.car, current_time)?;
}
if let Some((animation3, _car3)) = a3 {
animation3.draw(ctx, &self.assets.car, current_time)?;
}
},
State::WaitingForInput => (),
}
match self.race_result {
None =>
if checkpoint::checkpoint_to_lap(self.car3.racer.checkpoint) >= 3
|| checkpoint::checkpoint_to_lap(self.car2.racer.checkpoint) >= 3
{
self.race_result = Some(false);
checkpoint::draw_loss_message(ctx, &self.assets.checkpoint)?;
} else {
let lap = checkpoint::checkpoint_to_lap(self.car1.checkpoint);
if lap >= 3 {
self.race_result = Some(true);
}
checkpoint::draw_lap_message(ctx, &self.assets.checkpoint, lap)?;
},
Some(true) => {
checkpoint::draw_lap_message(ctx, &self.assets.checkpoint, 3)?;
},
Some(false) => {
checkpoint::draw_loss_message(ctx, &self.assets.checkpoint)?;
},
}
graphics::present(ctx);
timer::yield_now();
Ok(())
}
}
pub fn main() {
let ctx = &mut Context::load_from_conf(
GAME_NAME,
"Patrick Marchand, Samuel Gélineau, and Yen-Kuan Wu",
ggez::conf::Conf {
window_mode: ggez::conf::WindowMode {
width: WINDOW_WIDTH,
height: WINDOW_HEIGHT,
.. Default::default()
},
window_setup: ggez::conf::WindowSetup {
title: GAME_NAME.to_owned(),
.. Default::default()
},
.. Default::default()
},
).unwrap();
let globals = &mut Globals::new(ctx).unwrap();
event::run(ctx, globals).unwrap();
}
|
use super::widget::WidgetKind;
use crate::{
cpu::CPU,
debug::{util::FromHexString, widget::Widget},
memory_map::Mem,
Dst, Src,
};
use crossterm::event::{KeyCode, KeyEvent};
use std::{borrow::Cow, io::Stdout};
use tui::{
backend::CrosstermBackend,
layout::{Alignment, Rect},
style::{Color, Style},
widgets::{Block, Borders, Paragraph, Text},
Frame,
};
enum Command {
Goto,
Set,
}
/// Represents the widget responsible for the memory map, able to navigate through the address
/// space and display the content of the memory.
pub struct MemoryView<'a> {
text: Vec<Text<'a>>,
start: u16,
pos: u16,
init: bool,
height: usize,
selected: bool,
title_style: Style,
command: Option<Command>,
}
impl<'a> Widget for MemoryView<'a> {
fn refresh(&mut self, cpu: &CPU) {
let location = cpu.memory_map.location(self.pos);
let top = (0u8..0x10)
.map(|i| format!(" {:02x}", i))
.collect::<String>();
let top = Text::Raw(Cow::Owned(format!("{} │{}\n", location, top)));
let line = Text::Raw(Cow::Borrowed(
"─────┼────────────────────────────────────────────────\n",
));
let mut text = vec![top, line];
let mut lines = (0u16..(self.height as u16).saturating_sub(2))
.filter_map(|h| {
if let Some(addr) = self.start.checked_add(0x10 * h) {
if addr < 0xFFFF {
let values = (0u16..0x10)
.map(|a| {
let addr = addr.saturating_add(a);
let end = if a == 0xF { "\n" } else { "" };
let data = if let Ok(data) = Mem(addr).try_read(cpu) {
format!("{:02x}", data)
} else {
String::from("??")
};
if addr == self.pos {
Text::Styled(
Cow::Owned(format!(" {}{}", data, end)),
Style::default().fg(Color::Black).bg(Color::White),
)
} else {
Text::Raw(Cow::Owned(format!(" {}{}", data, end)))
}
})
.collect::<Vec<Text>>();
Some(
std::iter::once(Text::Raw(Cow::Owned(format!("{:04x} │", addr))))
.chain(values.into_iter()),
)
} else {
None
}
} else {
None
}
})
.flatten()
.collect::<Vec<Text>>();
text.append(&mut lines);
self.text = text;
}
fn draw(&mut self, f: &mut Frame<CrosstermBackend<Stdout>>, chunk: Rect, cpu: &CPU) {
self.height = chunk.height as usize;
if !self.init {
self.init = true;
self.refresh(cpu);
}
let paragraph = Paragraph::new(self.text.iter())
.block(
Block::default()
.borders(Borders::ALL)
.title("Memory")
.title_style(self.title_style),
)
.alignment(Alignment::Center);
f.render_widget(paragraph, chunk);
}
fn select(&mut self) {
self.selected = true;
self.title_style = Style::default().fg(Color::Yellow);
}
fn deselect(&mut self) {
self.selected = false;
self.title_style = Style::default();
}
fn is_selected(&self) -> bool {
self.selected
}
fn handle_key(&mut self, key: KeyEvent, _: &mut CPU) -> Option<(WidgetKind, String)> {
match key.code {
KeyCode::Char('g') => {
self.command = Some(Command::Goto);
Some((WidgetKind::Memory, String::from("Go to address:")))
}
KeyCode::Char('s') => {
self.command = Some(Command::Set);
Some((
WidgetKind::Memory,
format!("Set memory at $0x{:04x}", self.pos),
))
}
KeyCode::Up => {
self.pos = self.pos.checked_sub(0x10).unwrap_or(self.pos);
if self.pos < self.start {
self.start = self.start.saturating_sub(0x10);
}
None
}
KeyCode::Down => {
self.pos = self.pos.checked_add(0x10).unwrap_or(self.pos);
if self.pos < 0xFFFF
&& self.pos >= self.start.saturating_add(0x10 * (self.height as u16 - 4))
{
self.start = self.start.saturating_add(0x10);
}
None
}
KeyCode::Left => {
self.pos = self.pos.saturating_sub(1);
if self.pos < self.start {
self.start = self.start.saturating_sub(0x10);
}
None
}
KeyCode::Right => {
self.pos = self.pos.saturating_add(1);
if self.pos < 0xFFFF
&& self.pos >= self.start.saturating_add(0x10 * (self.height as u16 - 4))
{
self.start = self.start.saturating_add(0x10);
}
None
}
_ => None,
}
}
fn process_input(&mut self, input: String, cpu: &mut CPU) -> Result<(), Option<String>> {
match &self.command {
Some(c) => match c {
Command::Goto => match input.to_lowercase().as_str() {
"boot" | "rom" => {
self.goto(0x0000);
Ok(())
}
"vram" | "video ram" => {
self.goto(0x8000);
Ok(())
}
"wram" | "work ram" | "ram" | "working ram" => {
self.goto(0xC000);
Ok(())
}
"oam" | "object attribute memory" | "object attributes memory" => {
self.goto(0xFE00);
Ok(())
}
"io" | "io registers" | "i/o registers" | "i/o" => {
self.goto(0xFF00);
Ok(())
}
"hram" | "high ram" => {
self.goto(0xFF80);
Ok(())
}
_ => match u16::from_hex_string(input) {
Ok(addr) => {
self.goto(addr);
Ok(())
}
Err(_) => Err(None),
},
},
Command::Set => match u8::from_hex_string(input) {
Ok(value) => Mem(self.pos)
.try_write(cpu, value)
.map_err(|e| Some(format!("{}", e))),
Err(_) => Err(None),
},
},
None => Ok(()),
}
}
}
impl<'a> MemoryView<'a> {
/// Creates a new `MemoryView` widget.
pub fn new() -> MemoryView<'a> {
MemoryView {
text: vec![],
start: 0,
pos: 0,
init: false,
height: 0,
selected: false,
title_style: Style::default(),
command: None,
}
}
fn goto(&mut self, addr: u16) {
let start = addr & 0xFFF0;
self.start = start;
self.pos = addr;
}
}
|
use std::{
error::Error,
fmt,
fs::File,
path::Path
};
use amethyst::{
assets::{AssetStorage, Handle, Loader},
core::{
math::Vector3,
transform::Transform
},
ecs::{Entity, Builder, World, WorldExt},
renderer::{
formats::texture::ImageFormat,
sprite::{Sprite, SpriteSheet, SpriteSheetHandle},
Texture
},
tiles::{Tile, TileMap as AmethystTileMap}
};
use tiled;
// Example path: "./resources/desert.tmx"
pub struct TmxFilePath<'a>(pub &'a str);
#[derive(Debug)]
pub struct TilesetNotFoundError;
impl Error for TilesetNotFoundError {}
impl fmt::Display for TilesetNotFoundError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "No tilesets were found.")
}
}
#[derive(Debug)]
pub struct TilesetImageNotFoundError;
impl Error for TilesetImageNotFoundError {}
impl fmt::Display for TilesetImageNotFoundError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "No images for the tileset were found.")
}
}
struct TileMapDimensions(u32, u32);
struct TileDimensions(u32, u32);
pub struct TileMap {
tiled_map: tiled::Map
}
pub fn create_map<TileType: Tile>(
tmx_file_path: TmxFilePath,
world: &mut World
) -> Result<(AmethystTileMap<TileType>, TileMap), Box<dyn Error>> {
let tile_map = TileMap::load_map(tmx_file_path)?;
let TileMapDimensions(width, height) = tile_map.dimensions();
let TileDimensions(tile_width, tile_height) = tile_map.tile_dimensions();
let tileset_handle = tile_map.load_tileset(world)?;
let map = AmethystTileMap::<TileType>::new(
Vector3::new(width, height, 1),
Vector3::new(tile_width, tile_height, 1),
Some(tileset_handle),
);
Ok((map, tile_map))
}
impl TileMap {
fn load_map(tmx_file_path: TmxFilePath) -> Result<Self, Box<dyn Error>> {
let map_file = File::open(&Path::new(&tmx_file_path.0))?;
let tiled_map = tiled::parse(map_file)?;
Ok(TileMap {
tiled_map
})
}
pub fn tiles(&self) -> Option<&Vec<Vec<u32>>> {
self.tiled_map.layers.get(0).map(|layer| &layer.tiles)
}
fn dimensions(&self) -> TileMapDimensions {
TileMapDimensions(self.tiled_map.width, self.tiled_map.height)
}
fn tile_dimensions(&self) -> TileDimensions {
TileDimensions(self.tiled_map.tile_width, self.tiled_map.tile_height)
}
fn load_tileset(&self, world: &mut World) -> Result<SpriteSheetHandle, Box<dyn Error>> {
let tiled_image = self.get_tile_set_image()?;
Ok(self.load_sprite_sheet(world, tiled_image))
}
fn get_tile_set_image(&self) -> Result<&tiled::Image, Box<dyn Error>> {
// This will always use index 0 because we won't have more than 1 image per tileset
// and we also won't have more than 1 tileset per tile map
let tilesets = &self.tiled_map.tilesets;
let first_tileset = tilesets.get(0).ok_or_else(|| TilesetNotFoundError)?;
let first_image = first_tileset.images.get(0).ok_or_else(|| TilesetImageNotFoundError)?;
Ok(first_image)
}
fn load_sprite_sheet(&self, world: &mut World, tiled_image: &tiled::Image) -> SpriteSheetHandle {
let texture_handle: Handle<Texture> = {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture>>();
loader.load(
tiled_image.source.as_str(),
ImageFormat::default(),
(),
&texture_storage,
)
};
let sprite_sheet = self.create_sprite_sheet(texture_handle, tiled_image);
let loader = world.read_resource::<Loader>();
loader.load_from_data(
sprite_sheet,
(),
&world.read_resource::<AssetStorage<SpriteSheet>>(),
)
}
fn create_sprite_sheet(&self, texture: Handle<Texture>, tiled_image: &tiled::Image) -> SpriteSheet {
let image_w = tiled_image.width as u32;
let image_h = tiled_image.height as u32;
let sprite_w = self.tiled_map.tile_width;
let sprite_h = self.tiled_map.tile_height;
let offsets = [0.0; 2];
let column_count = image_w / sprite_w;
let row_count = image_h / sprite_h;
let sprite_count = column_count * row_count;
let sprites = (0..sprite_count).map(move |index| {
let offset_x = index % column_count * sprite_w;
let offset_y = index / column_count * sprite_h;
Sprite::from_pixel_values(
image_w,
image_h,
sprite_w,
sprite_h,
offset_x,
offset_y,
offsets,
false,
false
)
}).collect::<Vec<Sprite>>();
SpriteSheet {
texture,
sprites,
}
}
}
|
use projecteuler::digits;
use projecteuler::helper;
use projecteuler::primes;
fn main() {
helper::check_bench(|| {
solve(4, 3);
});
//helper::check_bench(|| {
// solve(6, 4);
//});
assert_eq!(solve(4, 3)[1], [2969, 6299, 9629]);
dbg!(solve(6, 4));
//dbg!(solve(10, 5));
}
//n represents the number of digits
//m represents the length of the sequence to find
fn solve(n: usize, m: usize) -> Vec<Vec<usize>> {
let primes = primes::primes(10usize.pow(n as u32));
let barrier = primes
.binary_search(&10usize.pow((n - 1) as u32))
.expect_err("1000 is not prime");
let primes: Vec<usize> = primes[barrier..].iter().cloned().collect();
let mut prime_digits: Vec<(usize, usize)> = primes
.iter()
.map(|p| {
(*p, {
let mut d = digits::digits(*p);
d.sort();
digits::from_digits(&d)
})
})
.collect();
prime_digits.sort_by(|(_, d1), (_, d2)| d1.cmp(d2));
//dbg!(&prime_digits);
let mut candidates = Vec::new();
{
let mut i = 0;
for j in 1..prime_digits.len() {
if prime_digits[j].1 == prime_digits[i].1 {
} else {
if j - i >= m {
candidates.push(&prime_digits[i..j]);
}
i = j;
}
}
}
//dbg!(&candidates);
let results: Vec<_> = candidates
.iter()
.flat_map(|c| check_contains_sequence(c, m))
.collect();
//dbg!(&results);
results
}
fn check_contains_sequence(prime_digits: &[(usize, usize)], m: usize) -> Vec<Vec<usize>> {
let mut acc = Vec::new();
for i in 0..prime_digits.len() {
'j: for j in i + 1..prime_digits.len() {
let d = prime_digits[j].0 - prime_digits[i].0;
for k in 1..=m - 2 {
match prime_digits.binary_search(&(prime_digits[j].0 + d * k, prime_digits[i].1)) {
Ok(_) => {}
_ => {
continue 'j;
}
}
}
acc.push((0..m).map(|k| prime_digits[i].0 + d * k).collect());
}
}
acc
}
|
use std::io;
use std::fs::File;
use std::io::BufRead;
use std::path::Path;
use std::str::FromStr;
pub fn read_lines<P>(filename: P) -> impl Iterator<Item = String> where P: AsRef<Path> {
let file = File::open(filename).expect("Failed to read file.");
io::BufReader::new(file)
.lines()
.map(|line| line.expect("Failed reading line."))
}
pub fn read_non_blank_lines<P>(filename: P) -> impl Iterator<Item = String> where P: AsRef<Path> {
read_lines(filename)
.filter(|line| !line.is_empty())
}
pub fn read_lines_as_u32<P>(filename: P) -> impl Iterator<Item = u32> where P: AsRef<Path> {
read_non_blank_lines(filename)
.map(|line| u32::from_str(line.as_str()).expect("Failed to convert to u32."))
}
|
use super::map::Map;
use super::math::vector::Vec2;
use super::data_structures::heap::Heap;
extern crate ahash;
struct Node {
father: Option<std::rc::Rc<Node>>,
position: Vec2<i32>,
real_distance: i32,
}
fn heuristic(start_point: Vec2<i32>, mid_point: Vec2<i32>, end_point: Vec2<i32>) -> f32 {
let diff = mid_point - end_point;
let line_diff = end_point - start_point;
let l1 = diff.x.abs() + diff.y.abs();
let cross = (mid_point.x * line_diff.y - mid_point.y * line_diff.x).abs();
l1 as f32 + 0.001 * cross as f32
}
// std::collections::BTreeSet
pub fn path_find(map: &Map, start_point: Vec2<i32>, end_point: Vec2<i32>) -> Vec<Vec2<i32>>{
let mut hash : ahash::AHashMap<Vec2<i32>, i32> = ahash::AHashMap::new();
let start: Node = Node {
position: start_point,
father: None,
real_distance: 0,
};
let value = heuristic(start_point, start_point, end_point);
let neighbors_delta = vec!(Vec2{x:0,y:1},Vec2{x:1,y:0},Vec2{x:-1,y:0},Vec2{x:0,y:-1});
let path =
{
let mut heap: Heap<f32, Node> = Heap::new();
heap.push(value, start);
let mut result = None;
'whileHeapNotEmpty : while let Some(popped) = heap.pop() {
let node = popped.1;
let position = node.position;
let real_distance = node.real_distance;
if let Some(&hash_pos) = hash.get(&position) {
if real_distance < hash_pos {
continue;
}
}
let boxed = std::rc::Rc::new(node);
for &delta in &neighbors_delta {
let new_position = position + delta;
if new_position.x >= map.width || new_position.y >= map.height || new_position.x < 0 || new_position.y < 0 {
continue;
}
if *map.value((new_position.x, new_position.y)) != 3 {
continue;
}
let new_real_distance = real_distance + 1;
let h = heuristic(start_point, new_position, end_point);
let curr_value = h + (new_real_distance as f32);
let new_node = Node{
position:new_position,
real_distance:new_real_distance,
father: Some((&boxed).clone()),
};
if new_position == end_point {
result = Some(new_node);
break 'whileHeapNotEmpty;
}
if let Some(&old_dist) = hash.get(&new_position) {
if new_real_distance < old_dist {
heap.push(curr_value, new_node);
}
} else {
heap.push(curr_value, new_node);
}
}
if let Some(hash_pos) = hash.get_mut(&position) {
*hash_pos = real_distance.max(*hash_pos);
} else {
hash.insert(position, real_distance);
}
}
result
};
let mut result_vector = vec!();
let mut iter_path = path;
while let Some(p) = iter_path {
result_vector.insert(0, p.position);
if p.father.is_none() {
break;
} else {
let option = std::rc::Rc::try_unwrap(p.father.unwrap());
iter_path = option.ok();
}
}
result_vector
}
|
//!
//! Objects are accessed usually through Object Group layers.
//!
//! Objects in Tiled describe just a couple of things:
//! - Text
//! - Points
//! - Ellipses
//! - Polygons
//! - Polylines
//!
//! How you use these things is up to you. For example, Tile definitions in
//! Tilesets contain objects when collision or locations within tiles have been
//! identified in the Tiled editor. You might use these to describe common paths
//! for NPCs to take or collisions or meshes or text-on-map.
//!
//! Please see: <https://doc.mapeditor.org/en/stable/reference/json-map-format/#object>
//!
//! Objects implement the HasProperty trait in order to provide access to
//! Properties. The relevant functions are:
//! tiled_json::Object::get_property(&self, name: &str) -> Option<&tiled_json::Property>;
//! tiled_json::Object::get_property_vector(&self) -> &Vec<tiled_json::Property>;
//! tiled_json::Object::get_property_value(&self, name: &str) -> Option<&tiled_json::PropertyValue>;
//! // See the tiled_json::Property struct to see functionality offered.
//!
use crate::color::Color;
use crate::property::HasProperty;
use crate::property::Property;
use serde::Deserialize;
const ALIGN_LEFT: &str = "left";
const ALIGN_RIGHT: &str = "right";
const ALIGN_JUSTIFY: &str = "justify";
const ALIGN_CENTER: &str = "center";
const ALIGN_TOP: &str = "top";
const ALIGN_BOTTOM: &str = "bottom";
#[derive(Deserialize)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// Means of describing nodes in objectgroup layers.
pub struct Object {
pub id: u32,
pub x: f64,
pub y: f64,
#[serde(default)]
pub gid: Option<u32>, // only if represents tile.
#[serde(default)]
pub name: String,
#[serde(default, rename = "type")]
pub otype: String,
#[serde(default)]
pub height: f64,
#[serde(default)]
pub width: f64,
#[serde(default)]
pub rotation: f64,
#[serde(default = "default_to_true")]
pub visible: bool,
#[serde(default = "default_to_false")]
pub ellipse: bool,
#[serde(default = "default_to_false")]
pub point: bool,
#[serde(default)]
pub polygon: Option<Vec<Point>>,
#[serde(default)]
pub polyline: Option<Vec<Point>>,
#[serde(default)]
pub text: Option<Text>,
#[serde(default)]
pub properties: Vec<Property>,
}
impl HasProperty for Object {
/// Access properties of Objects.
fn get_property_vector(&self) -> &Vec<Property> {
&self.properties
}
}
impl Object {
/// Get the object id, unique across all objects.
pub fn id(&self) -> u32 {
self.id
}
/// Horizontal position.
pub fn x(&self) -> f64 {
self.x
}
/// Vertical position.
pub fn y(&self) -> f64 {
self.y
}
/// Get object gid if it represents a tile.
pub fn gid(&self) -> Option<u32> {
self.gid
}
/// Get the name of the object.
pub fn name(&self) -> &String {
&self.name
}
/// Get the user-defined type of the object.
pub fn obj_type(&self) -> &String {
&self.otype
}
/// Height of the object
pub fn height(&self) -> f64 {
self.height
}
/// Width of the object.
pub fn width(&self) -> f64 {
self.width
}
/// Get the rotation of the object.
pub fn rotation(&self) -> f64 {
self.rotation
}
/// Is the object visible in Tiled.
pub fn visible(&self) -> bool {
self.visible
}
/// Does the object describe an ellipse?
pub fn is_ellipse(&self) -> bool {
self.ellipse
}
/// Does the object describe a point?
pub fn is_point(&self) -> bool {
self.point
}
/// Does the object describe a polygon?
pub fn is_polygon(&self) -> bool {
self.polygon.is_some()
}
/// Does the object describe a polyline?
pub fn is_polyline(&self) -> bool {
self.polyline.is_some()
}
/// Does the object describe text?
pub fn is_text(&self) -> bool {
self.text.is_some()
}
/// Get a reference to the polygon vector of points.
pub fn polygon(&self) -> Option<&Vec<Point>> {
self.polygon.as_ref()
}
/// Gets a reference of the polyline vector of points.
pub fn polyline(&self) -> Option<&Vec<Point>> {
self.polyline.as_ref()
}
/// Gets a reference to the Text data of the object.
pub fn text(&self) -> Option<&Text> {
self.text.as_ref()
}
}
#[derive(Deserialize, Copy, Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// Points describe single points on maps and are generally used to describe
/// polygons and polylines. They only have x and y components.
pub struct Point {
pub x: f64,
pub y: f64,
}
impl Point {
/// Get the x value of the point.
pub fn x(&self) -> f64 {
self.x
}
/// Get the y value of the point.
pub fn y(&self) -> f64 {
self.y
}
}
#[derive(Deserialize, Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// Text is an oject that contains all kinds of characteristics of text that Tiled
/// is able to display, including the string itself.
pub struct Text {
pub text: String,
#[serde(default = "default_to_false")]
pub bold: bool,
#[serde(default = "default_to_false")]
pub italic: bool,
#[serde(default = "default_to_false")]
pub strikeout: bool,
#[serde(default = "default_to_false")]
pub underline: bool,
#[serde(default = "default_to_true")]
pub kerning: bool,
#[serde(default = "default_to_false")]
pub wrap: bool,
#[serde(default = "default_to_16")]
pub pixelsize: u16,
#[serde(default = "default_to_black")]
pub color: Color,
#[serde(default = "default_to_sansserif")]
pub fontfamily: String,
#[serde(default = "default_to_halign_left")]
pub halign: HAlign,
#[serde(default = "default_to_valign_top")]
pub valign: VAlign, // default top
}
impl Text {
/// Get the string of text needing displayed.
pub fn text(&self) -> &String {
&self.text
}
/// Is the text supposed to be bold?
pub fn is_bold(&self) -> bool {
self.bold
}
/// Is the text supposed to be italic?
pub fn is_italic(&self) -> bool {
self.italic
}
/// Does the text have a striekout?
pub fn is_strikeout(&self) -> bool {
self.strikeout
}
/// Is the text supposed to be underlined?
pub fn is_underline(&self) -> bool {
self.underline
}
/// Does the text use kerning for display?
pub fn is_kerning(&self) -> bool {
self.kerning
}
/// Does the text wrap around? If it does, the containing Object structure
/// probably contains more relevant information for wrapping.
pub fn is_wrap(&self) -> bool {
self.wrap
}
/// Discribe the size in pixels of the text.
pub fn pixel_size(&self) -> u16 {
self.pixelsize
}
/// Retrieve the color the text is supposed to be.
pub fn color(&self) -> Color {
self.color
}
/// Get the font-family of the text.
pub fn font_family(&self) -> &String {
&self.fontfamily
}
/// Get the horizontal alignment in the form of an HAlign enum.
/// You can call to_string() on the enum if necessary.
pub fn horizontal_alignment(&self) -> HAlign {
self.halign
}
/// Get the horizontal alignment of the text as a string.
pub fn halign_as_string(&self) -> String {
self.halign.to_string()
}
/// Get the vertical alignment in the form of a VAlign enum.
/// You can call to_string() on the enum if necessary.
pub fn vertical_alignment(&self) -> VAlign {
self.valign
}
/// Get the vertical alignment of the text as a string.
pub fn valign_as_string(&self) -> String {
self.valign.to_string()
}
}
#[derive(Deserialize, Copy, Clone)]
#[serde(from = "String")]
#[cfg_attr(debug_assertions, derive(Debug))]
/// This enum describes the horizontal alignment of text. It has 4 variants:
/// - Center
/// - Right
/// - Justify
/// - Left
///
/// to_string() can be called on this enum if required.
pub enum HAlign {
Center,
Right,
Justify,
Left,
}
impl std::fmt::Display for HAlign {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
HAlign::Center => ALIGN_CENTER,
HAlign::Right => ALIGN_RIGHT,
HAlign::Justify => ALIGN_JUSTIFY,
HAlign::Left => ALIGN_LEFT,
};
std::fmt::Display::fmt(s, f)
}
}
#[derive(Deserialize, Copy, Clone)]
#[serde(from = "String")]
#[cfg_attr(debug_assertions, derive(Debug))]
/// This enum describes the vertical alignment of text. It has 3 variants:
/// - Center
/// - Bottom
/// - Top
///
/// to_string() can be called on this enum if required.
pub enum VAlign {
Center,
Bottom,
Top,
}
impl std::fmt::Display for VAlign {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
VAlign::Center => ALIGN_CENTER,
VAlign::Bottom => ALIGN_BOTTOM,
VAlign::Top => ALIGN_TOP,
};
std::fmt::Display::fmt(s, f)
}
}
impl From<String> for HAlign {
fn from(hal: String) -> Self {
match hal.as_str() {
ALIGN_LEFT => HAlign::Left,
ALIGN_RIGHT => HAlign::Right,
ALIGN_JUSTIFY => HAlign::Justify,
ALIGN_CENTER => HAlign::Center,
_ => HAlign::Left,
}
}
}
impl From<String> for VAlign {
fn from(val: String) -> Self {
match val.as_str() {
ALIGN_TOP => VAlign::Top,
ALIGN_BOTTOM => VAlign::Bottom,
ALIGN_CENTER => VAlign::Center,
_ => VAlign::Top,
}
}
}
fn default_to_true() -> bool {
true
}
fn default_to_false() -> bool {
false
}
fn default_to_16() -> u16 {
16 as u16
}
fn default_to_black() -> Color {
Color {
r: 0,
b: 0,
g: 0,
a: 255,
}
}
fn default_to_sansserif() -> String {
"sans-serif".to_string()
}
fn default_to_halign_left() -> HAlign {
HAlign::Left
}
fn default_to_valign_top() -> VAlign {
VAlign::Top
}
|
use std::cell::{ RefCell, RefMut };
use std::rc::Rc;
use graphics::math::{ Scalar, Matrix2d };
use gfx_device_gl::{ Resources };
use util::texture_register::TextureRegister;
use game::input_state::InputState;
use game::Game;
pub struct UpdateContext<'a> {
pub width: u32,
pub height: u32,
pub input_state: &'a mut InputState,
pub dt: Scalar,
}
pub struct DrawingContext<'a> {
pub width: u32,
pub height: u32,
pub transform: Matrix2d,
pub tile_textures: &'a TextureRegister<Resources>,
}
|
//! Pretty print logs.
use crate::{Femme, Logger};
use log::{kv, Level, Log, Metadata, Record};
use std::io::{self, StdoutLock, Write};
// ANSI term codes.
const RESET: &'static str = "\x1b[0m";
const BOLD: &'static str = "\x1b[1m";
const RED: &'static str = "\x1b[31m";
const GREEN: &'static str = "\x1b[32m";
const YELLOW: &'static str = "\x1b[33m";
/// Format Key/Value pairs that have been passed to a `Log` macro (such as `info!`)
///
/// # Arguments
/// * `handle` - Exclusive handle to `stdout`
/// * `record` - Record to write
fn format_kv_pairs<'b>(mut handle: &mut StdoutLock<'b>, record: &Record) {
struct Visitor<'a, 'b> {
stdout: &'a mut StdoutLock<'b>,
}
impl<'kvs, 'a, 'b> kv::Visitor<'kvs> for Visitor<'a, 'b> {
fn visit_pair(
&mut self,
key: kv::Key<'kvs>,
val: kv::Value<'kvs>,
) -> Result<(), kv::Error> {
write!(self.stdout, "\n {}{}{} {}", BOLD, key, RESET, val).unwrap();
Ok(())
}
}
let mut visitor = Visitor {
stdout: &mut handle,
};
record.key_values().visit(&mut visitor).unwrap();
}
/// Uses a pretty-print format to print to stdout
///
/// # Arguments
/// * `handle` - Exclusive handle to `stdout`
/// * `record` - Record to write
fn write_pretty(handle: &mut StdoutLock, record: &Record) {
// Format lines
let msg = record.target();
match record.level() {
Level::Trace | Level::Debug | Level::Info => {
write!(handle, "{}{}{}{}", GREEN, BOLD, msg, RESET).unwrap();
}
Level::Warn => write!(handle, "{}{}{}{}", YELLOW, BOLD, msg, RESET).unwrap(),
Level::Error => write!(handle, "{}{}{}{}", RED, BOLD, msg, RESET).unwrap(),
}
write!(handle, " {}", record.args()).unwrap();
// Format Key/Value pairs
format_kv_pairs(handle, record);
writeln!(handle, "").unwrap();
}
/// Uses a pretty-print format to print to stdout using the
/// Newline Delimited JSON format
///
/// # Arguments
/// * `handle` - Exclusive handle to `stdout`
/// * `record` - Record to write
fn write_ndjson(handle: &mut StdoutLock, record: &Record) {
fn get_level(level: log::Level) -> u8 {
use log::Level::*;
match level {
Trace => 10,
Debug => 20,
Info => 30,
Warn => 40,
Error => 50,
}
}
write!(handle, "{}", '{').unwrap();
write!(handle, "\"level\":{}", get_level(record.level())).unwrap();
let now = std::time::UNIX_EPOCH.elapsed().unwrap().as_millis();
write!(handle, ",\"time\":{}", now).unwrap();
write!(handle, ",\"msg\":\"{}\"", record.args()).unwrap();
format_kv_pairs(handle, record);
writeln!(handle, "{}", "}").unwrap();
}
impl Log for Femme {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.level() <= log::max_level()
}
fn log(&self, record: &Record<'_>) {
let level = self.module_level(record);
if record.level() <= *level {
// acquire stdout lock
let stdout = io::stdout();
let mut handle = stdout.lock();
match self.logger {
Logger::Pretty => write_pretty(&mut handle, &record),
Logger::NDJson => write_ndjson(&mut handle, &record),
}
}
}
fn flush(&self) {}
}
|
// Copyright 2016 Serde YAML Developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", deny(clippy))] // turn warnings into errors
extern crate linked_hash_map;
#[macro_use]
extern crate serde;
extern crate yaml_rust;
pub use self::de::{from_iter, from_reader, from_slice, from_str};
pub use self::ser::{to_string, to_vec, to_writer};
pub use self::value::{Mapping, Sequence, Value, from_value, to_value};
pub use self::error::{Error, Result};
mod de;
mod ser;
mod value;
mod error;
mod path;
|
use std::fmt;
use std::ops::{Mul, Neg, MulAssign};
use rand::{Rand, Rng};
use num::One;
use structs::matrix::{Matrix3, Matrix4};
use traits::structure::{Dimension, Column, BaseFloat, BaseNum};
use traits::operations::{Inverse, ApproxEq};
use traits::geometry::{Rotation, Transform, Transformation, Translation, ToHomogeneous};
use structs::vector::{Vector1, Vector2, Vector3};
use structs::point::{Point2, Point3};
use structs::rotation::{Rotation2, Rotation3};
use structs::isometry::{Isometry2, Isometry3};
#[cfg(feature="arbitrary")]
use quickcheck::{Arbitrary, Gen};
// FIXME: the name is not explicit at all but coherent with the other tree-letters names…
/// A two-dimensional similarity transformation.
///
/// This is a composition of a uniform scale, followed by a rotation, followed by a translation.
/// Vectors `Vector2` are not affected by the translational component of this transformation while
/// points `Point2` are.
/// Similarity transformations conserve angles. Distances are multiplied by some constant (the
/// scale factor). The scale factor cannot be zero.
#[repr(C)]
#[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)]
pub struct Similarity2<N> {
/// The uniform scale applicable by this similarity transformation.
scale: N,
/// The isometry applicable by this similarity transformation.
pub isometry: Isometry2<N>
}
/// A three-dimensional similarity transformation.
///
/// This is a composition of a scale, followed by a rotation, followed by a translation.
/// Vectors `Vector3` are not affected by the translational component of this transformation while
/// points `Point3` are.
/// Similarity transformations conserve angles. Distances are multiplied by some constant (the
/// scale factor). The scale factor cannot be zero.
#[repr(C)]
#[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)]
pub struct Similarity3<N> {
/// The uniform scale applicable by this similarity transformation.
scale: N,
/// The isometry applicable by this similarity transformation.
pub isometry: Isometry3<N>
}
sim_impl!(Similarity2, Isometry2, Rotation2, Vector2, Vector1);
dim_impl!(Similarity2, 2);
sim_scale_impl!(Similarity2);
sim_one_impl!(Similarity2);
sim_mul_sim_impl!(Similarity2);
sim_mul_isometry_impl!(Similarity2, Isometry2);
sim_mul_rotation_impl!(Similarity2, Rotation2);
sim_mul_point_vec_impl!(Similarity2, Point2);
sim_mul_point_vec_impl!(Similarity2, Vector2);
transformation_impl!(Similarity2);
sim_transform_impl!(Similarity2, Point2);
sim_inverse_impl!(Similarity2);
sim_to_homogeneous_impl!(Similarity2, Matrix3);
sim_approx_eq_impl!(Similarity2);
sim_rand_impl!(Similarity2);
sim_arbitrary_impl!(Similarity2);
sim_display_impl!(Similarity2);
sim_impl!(Similarity3, Isometry3, Rotation3, Vector3, Vector3);
dim_impl!(Similarity3, 3);
sim_scale_impl!(Similarity3);
sim_one_impl!(Similarity3);
sim_mul_sim_impl!(Similarity3);
sim_mul_isometry_impl!(Similarity3, Isometry3);
sim_mul_rotation_impl!(Similarity3, Rotation3);
sim_mul_point_vec_impl!(Similarity3, Point3);
sim_mul_point_vec_impl!(Similarity3, Vector3);
transformation_impl!(Similarity3);
sim_transform_impl!(Similarity3, Point3);
sim_inverse_impl!(Similarity3);
sim_to_homogeneous_impl!(Similarity3, Matrix4);
sim_approx_eq_impl!(Similarity3);
sim_rand_impl!(Similarity3);
sim_arbitrary_impl!(Similarity3);
sim_display_impl!(Similarity3);
|
// 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::collections::HashMap;
use std::ops::Range;
use std::time::Instant;
use common_base::rangemap::RangeMerger;
use common_base::runtime::UnlimitedFuture;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::ColumnId;
use futures::future::try_join_all;
use opendal::Operator;
use storages_common_cache::CacheAccessor;
use storages_common_cache::TableDataCacheKey;
use storages_common_cache_manager::CacheManager;
use storages_common_table_meta::meta::ColumnMeta;
use crate::io::read::block::block_reader_merge_io::OwnerMemory;
use crate::io::read::ReadSettings;
use crate::io::BlockReader;
use crate::metrics::*;
use crate::MergeIOReadResult;
impl BlockReader {
/// This is an optimized for data read, works like the Linux kernel io-scheduler IO merging.
/// If the distance between two IO request ranges to be read is less than storage_io_min_bytes_for_seek(Default is 48Bytes),
/// will read the range that contains both ranges, thus avoiding extra seek.
///
/// It will *NOT* merge two requests:
/// if the last io request size is larger than storage_io_page_bytes_for_read(Default is 512KB).
async fn merge_io_read(
read_settings: &ReadSettings,
op: Operator,
location: &str,
raw_ranges: Vec<(ColumnId, Range<u64>)>,
) -> Result<MergeIOReadResult> {
if raw_ranges.is_empty() {
// shortcut
let read_res = MergeIOReadResult::create(
OwnerMemory::create(vec![]),
raw_ranges.len(),
location.to_string(),
CacheManager::instance().get_table_data_cache(),
);
return Ok(read_res);
}
// Build merged read ranges.
let ranges = raw_ranges
.iter()
.map(|(_, r)| r.clone())
.collect::<Vec<_>>();
let range_merger = RangeMerger::from_iter(
ranges,
read_settings.storage_io_min_bytes_for_seek,
read_settings.storage_io_max_page_bytes_for_read,
);
let merged_ranges = range_merger.ranges();
// Read merged range data.
let mut read_handlers = Vec::with_capacity(merged_ranges.len());
for (idx, range) in merged_ranges.iter().enumerate() {
// Perf.
{
metrics_inc_remote_io_seeks_after_merged(1);
metrics_inc_remote_io_read_bytes_after_merged(range.end - range.start);
}
read_handlers.push(UnlimitedFuture::create(Self::read_range(
op.clone(),
location,
idx,
range.start,
range.end,
)));
}
let start = Instant::now();
let owner_memory = OwnerMemory::create(try_join_all(read_handlers).await?);
let table_data_cache = CacheManager::instance().get_table_data_cache();
let mut read_res = MergeIOReadResult::create(
owner_memory,
raw_ranges.len(),
location.to_string(),
table_data_cache,
);
// Perf.
{
metrics_inc_remote_io_read_milliseconds(start.elapsed().as_millis() as u64);
}
for (raw_idx, raw_range) in &raw_ranges {
let column_range = raw_range.start..raw_range.end;
// Find the range index and Range from merged ranges.
let (merged_range_idx, merged_range) = match range_merger.get(column_range.clone()) {
None => Err(ErrorCode::Internal(format!(
"It's a terrible bug, not found raw range:[{:?}], path:{} from merged ranges\n: {:?}",
column_range, location, merged_ranges
))),
Some((index, range)) => Ok((index, range)),
}?;
// Fetch the raw data for the raw range.
let start = (column_range.start - merged_range.start) as usize;
let end = (column_range.end - merged_range.start) as usize;
let column_id = *raw_idx as ColumnId;
read_res.add_column_chunk(merged_range_idx, column_id, start..end);
}
Ok(read_res)
}
pub async fn read_columns_data_by_merge_io(
&self,
settings: &ReadSettings,
location: &str,
columns_meta: &HashMap<ColumnId, ColumnMeta>,
) -> Result<MergeIOReadResult> {
// Perf
{
metrics_inc_remote_io_read_parts(1);
}
let mut ranges = vec![];
// for async read, try using table data cache (if enabled in settings)
let column_data_cache = CacheManager::instance().get_table_data_cache();
let column_array_cache = CacheManager::instance().get_table_data_array_cache();
let mut cached_column_data = vec![];
let mut cached_column_array = vec![];
for (_index, (column_id, ..)) in self.project_indices.iter() {
let column_cache_key = TableDataCacheKey::new(location, *column_id);
// first, check column array object cache
if let Some(cache_array) = column_array_cache.get(&column_cache_key) {
cached_column_array.push((*column_id, cache_array));
continue;
}
// and then, check column data cache
if let Some(cached_column_raw_data) = column_data_cache.get(&column_cache_key) {
cached_column_data.push((*column_id, cached_column_raw_data));
continue;
}
// if all cache missed, prepare the ranges to be read
if let Some(column_meta) = columns_meta.get(column_id) {
let (offset, len) = column_meta.offset_length();
ranges.push((*column_id, offset..(offset + len)));
// Perf
{
metrics_inc_remote_io_seeks(1);
metrics_inc_remote_io_read_bytes(len);
}
}
}
let mut merge_io_read_res =
Self::merge_io_read(settings, self.operator.clone(), location, ranges).await?;
// TODO set
merge_io_read_res.cached_column_data = cached_column_data;
merge_io_read_res.cached_column_array = cached_column_array;
Ok(merge_io_read_res)
}
#[inline]
pub async fn read_range(
op: Operator,
path: &str,
index: usize,
start: u64,
end: u64,
) -> Result<(usize, Vec<u8>)> {
let chunk = op.range_read(path, start..end).await?;
Ok((index, chunk))
}
}
|
fn main() {
let a = [1.0, 2.0, 3.0];
println!("{:?} {:?}", a[1], a[3]); // thread '<main>' panicked at 'index out of bounds: the len is 3 but the index is 3', main.rs:4
}
|
mod body;
mod calibration;
mod capture;
mod device;
mod device_configuration;
mod error;
mod frame;
mod tracker;
mod tracker_configuration;
mod playback;
pub use body::{
Body, Float2, Float3, Joint, Quaternion, Skeleton, joint_id,
};
pub use calibration::Calibration;
pub use capture::Capture;
pub use device::{Device, RunningDevice};
pub use device_configuration::{ColorResolution, DepthMode, DeviceConfiguration};
pub use error::{Error, WaitError, StreamError};
pub use frame::Frame;
pub use tracker::Tracker;
pub use tracker_configuration::TrackerConfiguration;
pub use playback::Playback;
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::String;
use super::super::runc::container::container::*;
use super::super::qlib::control_msg::*;
// ControlSocketAddr generates an abstract unix socket name for the given ID.
pub fn ControlSocketAddr(id: &str) -> String {
return format!("\x00qvisor-sandbox.{}", id)
}
pub const UCALL_BUF_LEN : usize = 4096;
#[derive(Serialize, Deserialize, Debug)]
pub enum UCallReq {
RootContainerStart(RootContainerStart),
ExecProcess(ExecArgs),
Pause,
Unpause,
Ps(String),
WaitContainer,
WaitPid(WaitPid),
Signal(SignalArgs),
ContainerDestroy,
}
impl FileDescriptors for UCallReq {
fn GetFds(&self) -> Option<&[i32]> {
match self {
UCallReq::ExecProcess(args) => return args.GetFds(),
_ => return None,
}
}
fn SetFds(&mut self, fds: &[i32]) {
match self {
UCallReq::ExecProcess(ref mut args) => return args.SetFds(fds),
_ => ()
}
}
}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct RootContainerStart {
pub cid: String
}
pub trait FileDescriptors {
fn GetFds(&self) -> Option<&[i32]>;
fn SetFds(&mut self, fds: &[i32]);
} |
use crate::error::Error;
use math::{
partition::integer_interval_map::IntegerIntervalMap,
set::{
contiguous_integer_set::ContiguousIntegerSet,
ordered_integer_set::OrderedIntegerSet, traits::Intersect,
},
};
use num::{Integer, Num};
use std::collections::HashMap;
pub trait ChromIntervalValue<T, V>
where
T: Copy + Integer, {
fn chrom_interval_value(&self) -> (String, ContiguousIntegerSet<T>, V);
}
pub trait ToChromIntervalValueIter<I, C, T, V>
where
I: Iterator<Item = C>,
C: ChromIntervalValue<T, V>,
T: Copy + Integer, {
fn to_chrom_interval_value_iter(&self) -> I;
}
pub type Chrom = String;
type Coordinate = i64;
impl<I, C, V> dyn ToChromIntervalValueIter<I, C, Coordinate, V>
where
I: Iterator<Item = C>,
C: ChromIntervalValue<Coordinate, V>,
V: Copy + Num,
{
/// Will discard the lines in the bed file if the corresponding range has a
/// non-empty intersection with any of the intervals in `exclude`.
pub fn get_chrom_to_interval_to_val(
&self,
exclude: Option<&HashMap<Chrom, OrderedIntegerSet<Coordinate>>>,
) -> Result<HashMap<String, IntegerIntervalMap<V>>, Error> {
let mut chrom_to_interval_map = HashMap::new();
for item in self.to_chrom_interval_value_iter() {
let (chrom, interval, value) = item.chrom_interval_value();
if let Some(chrom_to_excluded_intervals) = exclude {
if let Some(excluded_intervals) =
chrom_to_excluded_intervals.get(&chrom)
{
if interval
.has_non_empty_intersection_with(excluded_intervals)
{
continue;
}
}
}
let interval_map = chrom_to_interval_map
.entry(chrom)
.or_insert_with(IntegerIntervalMap::new);
interval_map.aggregate(interval, value);
}
Ok(chrom_to_interval_map)
}
}
|
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
impl Solution {
pub fn max_depth(root: Tree) -> i32 {
match root {
None => 0,
Some(cell) => {
let node = cell.borrow();
let left_depth = Solution::max_depth(node.left.clone());
let right_depth = Solution::max_depth(node.right.clone());
1 + left_depth.max(right_depth)
}
}
}
}
#[test]
fn test0104() {
fn tree(left: Tree, val: i32, right: Tree) -> Tree {
Some(Rc::new(RefCell::new(TreeNode { val, left, right })))
}
assert_eq!(
Solution::max_depth(tree(
tree(None, 9, None),
3,
tree(tree(None, 15, None), 20, tree(None, 7, None))
)),
3
);
}
|
use crate::backend::{self, Backend};
use crate::config::Config;
use crate::dir_cleaner::DirCleaner;
use anyhow::{Context, Result};
use base64::encode;
use sha1::{Digest, Sha1};
use std::cell::RefCell;
use std::fs;
use std::path::{Path, PathBuf};
pub trait RendererTrait {
fn render(
&self,
plantuml_code: &str,
rel_img_url: &str,
image_format: String,
) -> Result<String>;
}
/// Create the image names with the appropriate extension and path
/// The base name of the file is a SHA1 of the code block to avoid collisions
/// with existing and as a bonus prevent duplicate files.
pub fn image_filename(img_root: &Path, plantuml_code: &str, image_format: &str) -> PathBuf {
// See https://plantuml.com/command-line "Types of output files" for additional info
let extension = {
if plantuml_code.contains("@startditaa") {
// ditaa only has png format support afaik
"png"
} else if image_format.is_empty() {
"svg"
} else if image_format == "txt" {
// -ttxt outputs an .atxt file
"atxt"
} else if image_format == "braille" {
// -tbraille outputs a .braille.png file
"braille.png"
} else {
image_format
}
};
let mut output_file = img_root.join(hash_string(plantuml_code));
output_file.set_extension(extension);
output_file
}
fn hash_string(code: &str) -> String {
let hash = Sha1::new_with_prefix(code).finalize();
base16ct::lower::encode_string(&hash)
}
pub struct Renderer {
backend: Box<dyn Backend>,
cleaner: RefCell<DirCleaner>,
img_root: PathBuf,
clickable_img: bool,
use_data_uris: bool,
}
impl Renderer {
pub fn new(cfg: &Config, img_root: PathBuf) -> Self {
let renderer = Self {
backend: backend::factory::create(cfg),
cleaner: RefCell::new(DirCleaner::new(img_root.as_path())),
img_root,
clickable_img: cfg.clickable_img,
use_data_uris: cfg.use_data_uris,
};
renderer
}
fn create_md_link(rel_img_url: &str, image_path: &Path, clickable: bool) -> String {
let img_url = format!(
"{}/{}",
rel_img_url,
image_path.file_name().unwrap().to_str().unwrap()
);
if clickable {
format!("[]({img_url})\n\n")
} else {
format!("\n\n")
}
}
fn create_datauri(image_path: &Path) -> Result<String> {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs#syntax
let media_type = match image_path
.extension()
.map(|s| s.to_str())
.unwrap_or(Some(""))
{
Some("jpg" | "jpeg") => "image/jpeg",
Some("png") => "image/png",
Some("svg") => "image/svg+xml",
Some("atxt" | "utxt" | "txt") => "text/plain",
_ => "",
};
let image_data = fs::read(image_path)
.with_context(|| format!("Could not open image file {image_path:?}"))?;
let encoded_value = encode(image_data);
Ok(format!("data:{media_type};base64,{encoded_value}"))
}
fn create_image_datauri_element(image_path: &Path, clickable: bool) -> Result<String> {
let uri = Self::create_datauri(image_path)?;
if clickable {
// Note that both Edge and Firefox do not allow clicking on data URI links
// So this probably won't work. Kept in here regardless for consistency
Ok(format!("[]({uri})\n\n"))
} else {
Ok(format!("\n\n"))
}
}
fn create_inline_txt_image(image_path: &Path) -> Result<String> {
log::debug!("Creating inline image from {:?}", image_path);
let raw_source = fs::read(image_path).unwrap();
let txt = String::from_utf8(raw_source)?;
Ok(format!("\n```txt\n{txt}```\n"))
}
pub fn render(
&self,
plantuml_code: &str,
rel_img_url: &str,
image_format: &str,
) -> Result<String> {
// When operating in data-uri mode the images are written to in .mdbook-plantuml, otherwise
// they are written to src/mdbook-plantuml-images (cannot write to the book output dir, because
// mdbook deletes the files in there after preprocessing)
let output_file = image_filename(&self.img_root, plantuml_code, image_format);
if !output_file.exists() {
// File is not cached, render the image
let data = self
.backend
.render_from_string(plantuml_code, image_format)?;
// Save the file even if we inline images
std::fs::write(&output_file, data).with_context(|| {
format!(
"Failed to save PlantUML diagram to {}.",
output_file.to_string_lossy()
)
})?;
}
// Let the dir cleaner know this file should be kept
self.cleaner.borrow_mut().keep(&output_file);
let extension = output_file.extension().unwrap_or_default();
if extension == "atxt" || extension == "utxt" {
Self::create_inline_txt_image(&output_file)
} else if self.use_data_uris {
Self::create_image_datauri_element(&output_file, self.clickable_img)
} else {
Ok(Self::create_md_link(
rel_img_url,
&output_file,
self.clickable_img,
))
}
}
}
impl RendererTrait for Renderer {
fn render(
&self,
plantuml_code: &str,
rel_img_url: &str,
image_format: String,
) -> Result<String> {
Self::render(self, plantuml_code, rel_img_url, &image_format)
}
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{bail, Result};
use pretty_assertions::assert_eq;
use std::fs::File;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn test_create_md_link() {
assert_eq!(
String::from("\n\n"),
Renderer::create_md_link("foo/bar", Path::new("/froboz/baz.svg"), false)
);
assert_eq!(
"\n\n",
Renderer::create_md_link("", Path::new("baz.svg"), false)
);
assert_eq!(
String::from("\n\n"),
Renderer::create_md_link("", Path::new("foo/baz.svg"), false)
);
}
#[test]
fn test_create_datauri() {
let temp_directory = tempdir().unwrap();
let content = "test content";
let svg_path = temp_directory.path().join("file.svg");
let mut svg_file = File::create(&svg_path).unwrap();
writeln!(svg_file, "{content}").unwrap();
drop(svg_file); // Close and flush content to file
assert_eq!(
String::from("data:image/svg+xml;base64,dGVzdCBjb250ZW50Cg=="),
Renderer::create_datauri(&svg_path).unwrap()
);
let png_path = temp_directory.path().join("file.png");
let mut png_file = File::create(&png_path).unwrap();
writeln!(png_file, "{content}").unwrap();
drop(png_file); // Close and flush content to file
assert_eq!(
String::from("data:image/png;base64,dGVzdCBjb250ZW50Cg=="),
Renderer::create_datauri(&png_path).unwrap()
);
let txt_path = temp_directory.path().join("file.txt");
let mut txt_file = File::create(&txt_path).unwrap();
writeln!(txt_file, "{content}").unwrap();
drop(txt_file); // Close and flush content to file
assert_eq!(
String::from("data:text/plain;base64,dGVzdCBjb250ZW50Cg=="),
Renderer::create_datauri(&txt_path).unwrap()
);
let jpeg_path = temp_directory.path().join("file.jpeg");
let mut jpeg_file = File::create(&jpeg_path).unwrap();
writeln!(jpeg_file, "{content}").unwrap();
drop(jpeg_file); // Close and flush content to file
assert_eq!(
String::from("data:image/jpeg;base64,dGVzdCBjb250ZW50Cg=="),
Renderer::create_datauri(&jpeg_path).unwrap()
);
}
struct BackendMock {
is_ok: bool,
}
impl Backend for BackendMock {
fn render_from_string(&self, plantuml_code: &str, image_format: &str) -> Result<Vec<u8>> {
if self.is_ok {
return Ok(Vec::from(
format!("{plantuml_code}\n{image_format}").as_bytes(),
));
}
bail!("Oh no");
}
}
#[test]
fn test_rendering_md_link() {
let output_dir = tempdir().unwrap();
let renderer = Renderer {
backend: Box::new(BackendMock { is_ok: true }),
cleaner: RefCell::new(DirCleaner::new(output_dir.path())),
img_root: output_dir.path().to_path_buf(),
clickable_img: false,
use_data_uris: false,
};
let plantuml_code = "some puml code";
let code_hash = hash_string(plantuml_code);
assert_eq!(
format!("\n\n"),
renderer.render(plantuml_code, "rel/url", "svg").unwrap()
);
// png extension
assert_eq!(
format!("\n\n"),
renderer.render(plantuml_code, "rel/url", "png").unwrap()
);
// txt extension
assert_eq!(
format!("\n```txt\n{plantuml_code}\ntxt```\n"), /* image format is appended by
* fake backend */
renderer.render(plantuml_code, "rel/url", "txt").unwrap()
);
// utxt extension
assert_eq!(
format!("\n```txt\n{plantuml_code}\ntxt```\n"), /* image format is appended by
* fake backend */
renderer.render(plantuml_code, "rel/url", "txt").unwrap()
);
}
#[test]
fn test_rendering_datauri() {
let output_dir = tempdir().unwrap();
let renderer = Renderer {
backend: Box::new(BackendMock { is_ok: true }),
cleaner: RefCell::new(DirCleaner::new(output_dir.path())),
img_root: output_dir.path().to_path_buf(),
clickable_img: false,
use_data_uris: true,
};
let plantuml_code = "some puml code";
// svg extension
assert_eq!(
format!(
"\n\n",
"data:image/svg+xml;base64,c29tZSBwdW1sIGNvZGUKc3Zn"
),
renderer.render(plantuml_code, "rel/url", "svg").unwrap()
);
// png extension
assert_eq!(
format!(
"\n\n",
"data:image/png;base64,c29tZSBwdW1sIGNvZGUKcG5n"
),
renderer.render(plantuml_code, "rel/url", "png").unwrap()
);
// txt extension
assert_eq!(
String::from("\n```txt\nsome puml code\ntxt```\n"),
renderer.render(plantuml_code, "rel/url", "txt").unwrap()
);
// utxt extension
assert_eq!(
String::from("\n```txt\nsome puml code\ntxt```\n"),
renderer.render(plantuml_code, "rel/url", "txt").unwrap()
);
}
#[test]
fn test_rendering_failure() {
let output_dir = tempdir().unwrap();
let renderer = Renderer {
backend: Box::new(BackendMock { is_ok: false }),
cleaner: RefCell::new(DirCleaner::new(output_dir.path())),
img_root: output_dir.path().to_path_buf(),
clickable_img: false,
use_data_uris: false,
};
let result = renderer.render("", "rel/url", "svg");
let error_str = format!("{}", result.err().unwrap());
assert_eq!("Oh no", error_str);
}
#[test]
fn test_image_filename_extension() {
let extension_from_filename = |code: &str, img_format: &str| -> String {
let file_path = image_filename(Path::new("foo"), code, img_format)
.to_string_lossy()
.to_string();
let firstdot = file_path.find('.').unwrap();
file_path[firstdot + 1..].to_string()
};
assert_eq!(String::from("svg"), extension_from_filename("", "svg"));
assert_eq!(String::from("eps"), extension_from_filename("", "eps"));
assert_eq!(String::from("png"), extension_from_filename("", "png"));
assert_eq!(String::from("svg"), extension_from_filename("", ""));
assert_eq!(String::from("svg"), extension_from_filename("", "svg"));
assert_eq!(String::from("atxt"), extension_from_filename("", "txt"));
// Plantuml does this 'braille.png' extension
assert_eq!(
String::from("braille.png"),
extension_from_filename("", "braille")
);
{
// ditaa graphs
// Note the format is overridden when rendering ditaa
assert_eq!(
String::from("png"),
extension_from_filename("@startditaa", "svg")
);
assert_eq!(
String::from("png"),
extension_from_filename("@startditaa", "png")
);
assert_eq!(
String::from("png"),
extension_from_filename(
"Also when not at the start of the code block @startditaa",
"svg"
)
);
}
}
#[test]
fn test_image_filename() {
let code = "asgtfgl";
let file_path = image_filename(Path::new("foo"), code, "svg");
assert_eq!(PathBuf::from("foo"), file_path.parent().unwrap());
assert_eq!(
hash_string(code),
file_path.file_stem().unwrap().to_str().unwrap()
);
assert_eq!(PathBuf::from("svg"), file_path.extension().unwrap());
}
}
|
// `without_boolean_right_errors_badarg` in unit tests
test_stdout!(with_false_right_returns_false, "false\n");
test_stdout!(with_true_right_returns_true, "true\n");
|
#![allow(dead_code)] // for now
use dynasmrt::x64::Assembler;
use dynasmrt::DynasmApi;
type GPR = u8;
struct GPRs {
bits: u16,
}
impl GPRs {
fn new() -> Self {
Self { bits: 0 }
}
}
static RAX: u8 = 0;
static RCX: u8 = 1;
static RDX: u8 = 2;
static RBX: u8 = 3;
static RSP: u8 = 4;
static RBP: u8 = 5;
static RSI: u8 = 6;
static RDI: u8 = 7;
static R8: u8 = 8;
static R9: u8 = 9;
static R10: u8 = 10;
static R11: u8 = 11;
static R12: u8 = 12;
static R13: u8 = 13;
static R14: u8 = 14;
static R15: u8 = 15;
impl GPRs {
fn take(&mut self) -> GPR {
let lz = self.bits.trailing_zeros();
assert!(lz < 32, "ran out of free GPRs");
self.bits &= !(1 << lz);
lz as GPR
}
fn release(&mut self, gpr: GPR) {
assert_eq!(
self.bits & (1 << gpr),
0,
"released register was already free"
);
self.bits |= 1 << gpr;
}
}
pub struct Registers {
scratch_gprs: GPRs,
}
impl Registers {
pub fn new() -> Self {
let mut result = Self {
scratch_gprs: GPRs::new(),
};
// Give ourselves a few scratch registers to work with, for now.
result.release_scratch_gpr(RAX);
result.release_scratch_gpr(RCX);
result.release_scratch_gpr(RDX);
result
}
pub fn take_scratch_gpr(&mut self) -> GPR {
self.scratch_gprs.take()
}
pub fn release_scratch_gpr(&mut self, gpr: GPR) {
self.scratch_gprs.release(gpr);
}
}
fn push_i32(ops: &mut Assembler, regs: &mut Registers, gpr: GPR) {
// For now, do an actual push (and pop below). In the future, we could
// do on-the-fly register allocation here.
dynasm!(ops
; push Rq(gpr)
);
regs.release_scratch_gpr(gpr);
}
fn pop_i32(ops: &mut Assembler, regs: &mut Registers) -> GPR {
let gpr = regs.take_scratch_gpr();
dynasm!(ops
; pop Rq(gpr)
);
gpr
}
pub fn add_i32(ops: &mut Assembler, regs: &mut Registers) {
let op0 = pop_i32(ops, regs);
let op1 = pop_i32(ops, regs);
dynasm!(ops
; add Rq(op0), Rq(op1)
);
push_i32(ops, regs, op0);
regs.release_scratch_gpr(op1);
}
pub fn unsupported_opcode(ops: &mut Assembler) {
dynasm!(ops
; ud2
);
}
|
use crate::prelude::*;
use super::Api;
use crate::cache::Cache;
use std::collections::BTreeSet;
pub struct UpdatesApi;
#[derive(Debug, Deserialize, Clone)]
pub struct ModuleSpec {
module_name: String,
module_stream: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct UpdatesReq {
package_list: Vec<String>,
repository_list: Option<Vec<String>>,
modules_list: Option<Vec<ModuleSpec>>,
releasever: Option<String>,
basearch: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PkgUpdate {
package: Nevra,
erratum: String,
repository : Option<String>,
basearch : Option<String>,
releasever : Option<String>
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdatesPkgDetail {
#[serde(skip_serializing_if = "Option::is_none")]
summary : Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
description : Option<String>,
available_updates: Vec<PkgUpdate>,
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdatesData {
update_list: Map<String, UpdatesPkgDetail>,
#[serde(skip_serializing_if = "Option::is_none")]
repository_list: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
releasever: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
basearch: Option<String>,
}
impl UpdatesApi {
fn related_products(cache: &Cache, original_repo_ids: &Set<u64>) -> Set<u64> {
let mut product_ids = Set::default();
for original_pkg_repo_id in original_repo_ids.iter() {
if let Some(ref pid) = cache.repo_detail[original_pkg_repo_id].product_id {
product_ids.insert(pid.clone());
}
}
return product_ids;
}
fn valid_releasevers(cache: &Cache, original_repo_ids: &Set<u64>) -> Set<String> {
let mut valid_releasevers = Set::default();
for original_pkg_repo_id in original_repo_ids.iter() {
if let Some(ref rv) = cache.repo_detail[original_pkg_repo_id].releasever {
valid_releasevers.insert(rv.clone());
}
}
return valid_releasevers;
}
fn build_nevra(cache: &Cache, update_pkg_id: u64) -> Nevra {
let det = &cache.pkg_details[&update_pkg_id];
let name = &cache.id_to_name[&det.name_id];
let evr = &cache.id_to_evr[&det.evr_id];
let arh = &cache.id_to_arch[&det.arch_id];
return Nevra::from_name_evr_arch(name, evr.clone(), arh);
}
fn get_repositories(
cache: &Cache,
product_ids: &Set<u64>,
update_pkg_id: u64,
errata_ids: &[u64],
available_repo_ids: &Set<u64>,
valid_releasevers: &Set<String>,
) -> Set<u64> {
let mut errata_repo_ids = Set::default();
for errata_id in errata_ids {
errata_repo_ids.extend(&cache.errataid_to_repoids[errata_id]);
}
let mut repo_ids = Set::from_iter(&cache.pkgid_to_repoids[&update_pkg_id])
.intersection(&errata_repo_ids).map(|s| **s).collect::<Set<u64>>()
.intersection(available_repo_ids).map(|s| *s).collect::<Set<u64>>();
repo_ids.retain(|repo_id| {
valid_releasevers.contains(
cache.repo_detail[&repo_id]
.releasever
.as_ref()
.unwrap_or(&String::new())
.as_str(),
) && errata_repo_ids.contains(&repo_id)
});
return repo_ids;
}
fn process_updates(
cache: &Cache,
packages_to_process: &Map<&str, Nevra>,
available_repo_ids: &Set<u64>,
response: &mut UpdatesData,
) -> Result<(), Box<dyn Error>> {
for (pkg, nevra) in packages_to_process.iter() {
let nevra: &Nevra = nevra;
let name_id = if let Some(x) = cache.name_to_id.get(&nevra.name) {
x
} else {
continue;
};
let evr_id = cache.evr_to_id.get(&nevra.evr());
let arch_id = cache.arch_to_id.get(&nevra.arch).ok_or("Arch id not found".to_string())?;
// If nothing is found, use empty list
let current_evr_idxs: &[_] = evr_id
.and_then(|evr_id| cache.updates_index[&name_id].data.get(&evr_id))
.map(|v| v.as_ref())
.unwrap_or(&[][..]);
if current_evr_idxs.is_empty() {
//error!("package {:?} has no updates", name_id);
continue ;
}
let mut current_nevra_pkg_id = None;
for current_evr_idx in current_evr_idxs {
//error!("current evr idx : => {:?}", current_evr_idx);
let pkg_id = cache.updates[&name_id][*current_evr_idx as usize];
let current_nevra_arch_id = &cache.pkg_details[&pkg_id].arch_id;
//trace!("Package archs : {:?}, {:?}", current_nevra_arch_id, arch_id);
if current_nevra_arch_id == arch_id {
current_nevra_pkg_id = Some(pkg_id);
break ;
}
}
if current_nevra_pkg_id.is_none() {
//error!("Package with NEVRA: {:?} not found", nevra);
continue;
} else {
//error!("Package with NEVRA: {:?} Found", nevra);
}
let current_nevra_pkg_id = current_nevra_pkg_id.unwrap();
let resp_pkg_detail = response.update_list.entry(pkg.to_string()).or_default();
// TODO: for api version 1 only
resp_pkg_detail.summary = cache.pkg_details[¤t_nevra_pkg_id].summary.clone();
resp_pkg_detail.description = cache.pkg_details[¤t_nevra_pkg_id].desc.clone();
let last_version_pkg_id = cache.updates[&name_id].last();
if last_version_pkg_id == Some(¤t_nevra_pkg_id) {
//error!("Package is last, no updates");
continue ;
}
let mut original_package_repo_ids = Set::default();
if let Some(repoids) = cache.pkgid_to_repoids.get(¤t_nevra_pkg_id) {
original_package_repo_ids.extend(repoids.iter());
}
let product_ids = Self::related_products(cache, &original_package_repo_ids);
let valid_releasevers = Self::valid_releasevers(cache, &original_package_repo_ids);
//error!("Valid prods : {:#?}, valid vers : {:#?}", product_ids, valid_releasevers);
let update_pkg_ids =
&cache.updates[name_id][(*current_evr_idxs.last().unwrap() as usize) + 1..];
for update_pkg_id in update_pkg_ids {
//error!("Update pkg id : {:?}", update_pkg_id);
let errata_ids = &cache.pkgid_to_errataids.get(update_pkg_id);
if errata_ids.is_none() {
//error!("Filtering out :{:?}, no errata", update_pkg_id);
continue
}
let errata_ids = errata_ids.unwrap();
let updated_nevra_arch_id = cache.pkg_details[update_pkg_id].arch_id;
if updated_nevra_arch_id != *arch_id
&& !cache.arch_compat[&arch_id].contains(&updated_nevra_arch_id)
{
//error!("Filteroing out id : {:?}, wrong arch", update_pkg_id);
continue
}
let nevra = Self::build_nevra(cache, *update_pkg_id);
//error!("update nvera: {:?}", nevra);
for errata_id in errata_ids {
let mut repo_ids = Self::get_repositories(
cache,
&product_ids,
*update_pkg_id,
&[*errata_id],
&available_repo_ids,
&valid_releasevers,
);
//error!("Repoids avail : {:#?} : {:#?}", available_repo_ids, repo_ids);
for repo_id in repo_ids {
let repo_det = &cache.repo_detail[&repo_id];
resp_pkg_detail.available_updates.push(PkgUpdate {
package: nevra.clone(),
erratum: cache.errataid_to_name[errata_id].clone(),
repository : Some(repo_det.label.clone()),
basearch : repo_det.basearch.clone(),
releasever : repo_det.releasever.clone()
})
}
}
}
}
Ok(())
}
fn process_repositories(
cache: &Cache,
data: &UpdatesReq,
response: &mut UpdatesData,
) -> Set<u64> {
let mut available_repo_ids = Vec::new();
if let Some(ref repos) = data.repository_list {
for repo in repos {
if let Some(ids) = cache.repolabel_to_ids.get(repo) {
available_repo_ids.extend_from_slice(&ids)
}
}
response.repository_list = Some(repos.clone());
} else {
available_repo_ids = cache.repo_detail.keys().map(|v| *v).collect::<Vec<_>>();
}
if let Some(ref releasever) = data.releasever {
available_repo_ids.retain(|oid| {
!(cache.repo_detail[oid].releasever.as_ref() == Some(&releasever)
|| (cache.repo_detail[oid].releasever.is_none()
&& cache.repo_detail[oid].url.contains(releasever)))
});
response.releasever = Some(releasever.clone())
}
if let Some(ref basearch) = data.basearch {
available_repo_ids.retain(|oid| {
!(cache.repo_detail[oid].basearch.as_ref() == Some(&basearch)
|| (cache.repo_detail[oid].basearch.is_none()
&& cache.repo_detail[oid].url.contains(basearch)))
});
response.basearch = Some(basearch.clone())
}
return Set::from_iter(available_repo_ids);
}
fn process_input_packages<'a>(
cache: &'a Cache,
data: &'a UpdatesReq,
response: &mut UpdatesData,
) -> Map<&'a str, Nevra> {
let mut filtered_pkgs_to_process = Map::default();
for pkg in &data.package_list {
let nevra = Nevra::from_str(&pkg).unwrap();
if let Some(id) = cache.name_to_id.get(&nevra.name) {
if let Some(up) = cache.updates_index.get(id) {
filtered_pkgs_to_process.insert(pkg.as_str(), nevra);
}
}
}
filtered_pkgs_to_process
}
}
impl Api for UpdatesApi {
type PostReqType = UpdatesReq;
type RespType = UpdatesData;
const ENDPOINT_NAME: &'static str = "/updates";
fn process_list(cache: &Cache, data: Self::PostReqType) -> Result<Self::RespType, Box<dyn Error>> {
let mut response = UpdatesData::default();
let available_repo_ids = Self::process_repositories(cache, &data, &mut response);
if let Some(ref modules_list) = data.modules_list {
for m in modules_list {}
}
let mut packages_to_process = Self::process_input_packages(cache, &data, &mut response);
Self::process_updates(
cache,
&packages_to_process,
&available_repo_ids,
&mut response,
);
Ok(response)
}
} |
use super::InlineObjectTrait;
use crate::{
heap::{
object_heap::HeapObject, symbol_table::impl_ord_with_symbol_table_via_ord, Heap,
InlineObject,
},
utils::{impl_debug_display_via_debugdisplay, DebugDisplay},
};
use candy_frontend::builtin_functions::{self, BuiltinFunction};
use derive_more::Deref;
use rustc_hash::FxHashMap;
use std::{
cmp::Ordering,
fmt::{self, Formatter},
hash::{Hash, Hasher},
num::NonZeroU64,
};
#[derive(Clone, Copy, Deref)]
pub struct InlineBuiltin(InlineObject);
impl InlineBuiltin {
const INDEX_SHIFT: usize = 3;
pub fn new_unchecked(object: InlineObject) -> Self {
Self(object)
}
fn index(self) -> usize {
(self.raw_word().get() >> Self::INDEX_SHIFT) as usize
}
pub fn get(self) -> BuiltinFunction {
builtin_functions::VALUES[self.index()]
}
}
impl DebugDisplay for InlineBuiltin {
fn fmt(&self, f: &mut Formatter, _is_debug: bool) -> fmt::Result {
write!(f, "{}", self.get())
}
}
impl_debug_display_via_debugdisplay!(InlineBuiltin);
impl Eq for InlineBuiltin {}
impl PartialEq for InlineBuiltin {
fn eq(&self, other: &Self) -> bool {
self.index() == other.index()
}
}
impl Hash for InlineBuiltin {
fn hash<H: Hasher>(&self, state: &mut H) {
self.index().hash(state)
}
}
impl Ord for InlineBuiltin {
fn cmp(&self, other: &Self) -> Ordering {
self.index().cmp(&other.index())
}
}
impl PartialOrd for InlineBuiltin {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl From<BuiltinFunction> for InlineObject {
fn from(builtin_function: BuiltinFunction) -> Self {
*InlineBuiltin::from(builtin_function)
}
}
impl From<BuiltinFunction> for InlineBuiltin {
fn from(builtin_function: BuiltinFunction) -> Self {
let index = builtin_function as usize;
debug_assert_eq!(
(index << Self::INDEX_SHIFT) >> Self::INDEX_SHIFT,
index,
"Builtin function index is too large.",
);
let header_word = InlineObject::KIND_BUILTIN | ((index as u64) << Self::INDEX_SHIFT);
let header_word = unsafe { NonZeroU64::new_unchecked(header_word) };
Self(InlineObject::new(header_word))
}
}
impl InlineObjectTrait for InlineBuiltin {
fn clone_to_heap_with_mapping(
self,
_heap: &mut Heap,
_address_map: &mut FxHashMap<HeapObject, HeapObject>,
) -> Self {
self
}
}
impl_ord_with_symbol_table_via_ord!(InlineBuiltin);
|
extern crate core;
#[derive(Debug)]
pub struct Error;
/// Trait governing random number generation.
///
/// Generators may be infallible (never failing) or fallible. In the latter
/// case, only `try_fill` allows error handling; other functions may panic.
pub trait Rng {
/// Fill dest with random bytes.
///
/// Panics if the underlying generator has an error; use `try_fill` if you
/// wish to handle errors.
fn fill(&mut self, dest: &mut [u8]);
/// Fill dest with random bytes.
///
/// In infallible generators this is identical to `fill`; in fallible
/// generators this function may return an `Error`, and `fill` simply
/// unwraps the `Result`.
fn try_fill(&mut self, dest: &mut [u8]) -> Result<(), Error> {
// we asume infallable generator in default impl
self.fill(dest);
Ok(())
}
/// Generate a random number.
///
/// Panics if the underlying generator has an error.
fn next_u64(&mut self) -> u64;
// also next_u32, next_u128
}
/// Extension trait marking a generator as "cryptographically secure".
///
/// This exists so that code taking a generator as a parameter and requiring
/// *cryptographically-secure random numbers* may mark this requirement and
/// make use of type safety to enforce it.
///
/// Generators which should be secure when correctly initialised should
/// implement this trait (it is noted that no algorithmic generator can be
/// secure without a secret seed, and such seeding cannot be checked at
/// compile time, therefore this trait is more of a guideline than a guarantee).
pub trait CryptoRng: Rng {}
// ——— utility functions ———
/// Convenient implementation for `fill` in terms of `next_u64`.
// TODO: Also for u32, u128 via macro internals.
pub fn impl_fill_from_u64<R: Rng+?Sized>(rng: &mut R, dest: &mut [u8]) {
use core::cmp::min;
use core::intrinsics::copy_nonoverlapping;
use core::mem::size_of;
let mut pos = 0;
let len = dest.len();
while len > pos {
// Cast pointer, effectively to `&[u8; 8]`, and copy as many bytes
// as required. Byte-swap x on BE architectures.
let x = rng.next_u64().to_le();
let xp = &x as *const u64 as *const u8;
let p: *mut u8 = unsafe{ dest.as_mut_ptr().offset(pos as isize) };
let n = min(len - pos, size_of::<u64>());
unsafe{ copy_nonoverlapping(xp, p, n); }
pos += n;
}
}
macro_rules! impl_uint_from_fill {
($ty:ty, $N:expr, $rng:expr) => ({
assert_eq!($N, ::core::mem::size_of::<$ty>());
let mut buf = [0u8; $N];
$rng.fill(&mut buf);
unsafe{ *(&buf[0] as *const u8 as *const $ty) }.to_le()
});
}
/// Convenient implementation of `next_u64` in terms of `fill`.
///
/// High-performance generators will probably need to implement some `next_*`
/// variant directly and others in terms of that. But this provides a convenient
/// solution for other generators focussed mainly on byte streams.
pub fn impl_next_u64_from_fill<R: Rng+?Sized>(rng: &mut R) -> u64 {
impl_uint_from_fill!(u64, 8, rng)
}
// ——— test RNGs ———
// A non-crypto Rng
#[derive(Debug)]
struct TestRng(u64);
impl Rng for TestRng {
fn fill(&mut self, dest: &mut [u8]) {
impl_fill_from_u64(self, dest)
}
fn next_u64(&mut self) -> u64 {
self.0
}
}
// A CryptoRng
#[derive(Debug)]
struct TestCRng(u64);
impl Rng for TestCRng {
fn fill(&mut self, dest: &mut [u8]) {
impl_fill_from_u64(self, dest)
}
fn next_u64(&mut self) -> u64 {
self.0
}
}
impl CryptoRng for TestCRng {}
// ——— usage ———
fn main() {
let mut t = TestRng(0x20216F6C6C6548);
let mut c = TestCRng(0x3F556572416F6857);
let mut buf = [0u8; 16];
t.fill(&mut buf);
println!("t: {:?} says: {}", t, String::from_utf8_lossy(&buf));
c.fill(&mut buf);
println!("c: {:?} says: {}", c, String::from_utf8_lossy(&buf));
{
// Static dispatch
println!("t, static dispatch, using Rng: {:?}", t.next_u64());
println!("c, static dispatch, using Rng: {:?}", c.next_u64());
}
{
// Dynamic dispatch using CryptoRng
let cr = &mut c as &mut CryptoRng;
println!("c, dynamic dispatch, using CryptoRng: {:?}", cr.next_u64());
}
{
// Dynamic dispatch using Rng
let tr = &mut t as &mut Rng;
println!("t, dynamic dispatch, using Rng: {:?}", tr.next_u64());
let cr = &mut c as &mut Rng;
println!("c, dynamic dispatch, using Rng: {:?}", cr.next_u64());
}
}
|
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use coruscant_nbt::as_nbt_array;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct EntityData {
#[serde(rename = "id")]
pub id: Option<String>,
#[serde(rename = "Pos")]
pub pos: [f64; 3],
#[serde(rename = "Motion")]
pub motion: [f64; 3],
#[serde(rename = "Rotation")]
pub rotation: [f32; 2],
#[serde(rename = "FallDistance")]
pub fall_distance: f32,
#[serde(rename = "Fire")]
pub fire: i16,
#[serde(rename = "Air")]
pub air: i16,
#[serde(rename = "OnGround")]
pub on_ground: bool,
#[serde(rename = "NoGravity")]
pub no_gravity: bool,
#[serde(rename = "Dimension")]
pub dimension: i32,
#[serde(rename = "Invulnerable")]
pub invulnerable: bool,
#[serde(rename = "PortalCooldown")]
pub portal_cooldown: i32,
#[serde(rename = "UUIDMost")]
pub uuid_most: i64,
#[serde(rename = "UUIDLeast")]
pub uuid_least: i64,
#[serde(rename = "CustomName")]
pub custom_name: String,
#[serde(rename = "CustomNameVisible")]
pub custom_name_visible: bool,
#[serde(rename = "Slient")]
pub slient: bool,
#[serde(rename = "Passengers")]
pub passengers: Vec<EntityData>,
#[serde(rename = "Glowing")]
pub glowing: bool,
#[serde(rename = "Tags")]
pub tags: Vec<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Mob {
#[serde(rename = "Health")]
pub health: f32,
#[serde(rename = "AbsorptionAmount")]
pub absorption_amount: f32,
#[serde(rename = "HurtTime")]
pub hurt_time: i16,
#[serde(rename = "HurtByTimestamp")]
pub hurt_by_timestamp: i32,
#[serde(rename = "DeathTime")]
pub death_time: i16,
#[serde(rename = "FallFlying")]
pub fall_flying: bool,
#[serde(flatten)]
pub sleeping_pos: Option<SleepingPos>,
#[serde(rename = "Brain")]
pub brain: Brain,
#[serde(rename = "Attributes")]
pub attributes: Vec<Attribute>,
#[serde(rename = "ActiveEffects")]
pub active_effects: Vec<ActiveEffect>,
// #[serde(rename = "HandItems")]
// pub hand_items: Vec<Item>,
// #[serde(rename = "ArmorItems")]
// pub armor_items: Vec<Item>,
#[serde(rename = "HandDropChances")]
pub hand_drop_chances: Vec<f32>,
#[serde(rename = "ArmorDropChances")]
pub armor_drop_chances: Vec<f32>,
#[serde(rename = "DeathLootTable")]
pub death_loot_table: Option<String>,
#[serde(rename = "DeathLootTableSeed")]
pub death_loot_table_seed: Option<i64>,
#[serde(rename = "CanPickUpLoot")]
pub can_pick_up_loot: bool,
#[serde(rename = "NoAI")]
pub no_ai: bool,
#[serde(rename = "PersistenceRequired")]
pub persistence_required: bool,
#[serde(rename = "LeftHanded")]
pub left_handed: bool,
#[serde(rename = "Team")]
pub team: String,
#[serde(rename = "Leashed")]
pub leashed: bool,
#[serde(rename = "Leash")]
pub leash: Option<Leash>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct SleepingPos {
#[serde(rename = "SleepingX")]
pub sleeping_x: i32,
#[serde(rename = "SleepingY")]
pub sleeping_y: i32,
#[serde(rename = "SleepingZ")]
pub sleeping_z: i32,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Brain {
#[serde(rename = "memories")]
pub memories: HashMap<String, Memory>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Memory {
MemoryPosition {
#[serde(rename = "pos")]
#[serde(serialize_with = "as_nbt_array")]
pos: [i32; 3],
#[serde(rename = "dimension")]
dimension: String,
},
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Attribute {
#[serde(rename = "Name")]
pub name: String,
#[serde(rename = "Base")]
pub base: f64,
#[serde(rename = "Modifiers")]
pub modifiers: Vec<Modifier>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Modifier {
#[serde(rename = "Name")]
pub name: String,
#[serde(rename = "Amount")]
pub amount: f64,
#[serde(rename = "Operation")]
pub operation: i32,
#[serde(rename = "UUIDMost")]
pub uuid_most: i64,
#[serde(rename = "UUIDLeast")]
pub uuid_least: i64,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ActiveEffect {
#[serde(rename = "Id")]
pub id: i8,
#[serde(rename = "Amplifier")]
pub amplifier: i8,
#[serde(rename = "Duration")]
pub duration: i32,
#[serde(rename = "Ambient")]
pub ambient: bool,
#[serde(rename = "ShowParticles")]
pub show_particles: bool,
#[serde(rename = "ShowIcon")]
pub show_icon: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Leash {
ToEntity {
#[serde(rename = "UUIDMost")]
uuid_most: i64,
#[serde(rename = "UUIDLeast")]
uuid_least: i64,
},
ToFence {
#[serde(rename = "X")]
x: i32,
#[serde(rename = "Y")]
y: i32,
#[serde(rename = "Z")]
z: i32,
},
}
|
// actor/mod.rs
mod player;
//mod computer;
pub use actor::player::Player;
//pub use actor::computer::Computer;
|
#![allow(dead_code)]
extern crate stackvec;
use stackvec::prelude::*;
use ::std::iter::{
self,
Iterator,
};
static NUMBERS: [u8; 9] = [
5, 8, 9, 10, 6, 7, 4, 6, 7
];
mod counted_instances {
use ::std::cell::Cell;
thread_local! {
static INSTANCES_COUNT: Cell<isize> = Cell::new(0);
}
#[derive(Debug)]
pub struct Instance(());
impl Default for Instance {
fn default() -> Self
{
INSTANCES_COUNT.with(|slf| slf.set(slf.get() + 1));
Instance(())
}
}
impl Instance {
#[allow(non_upper_case_globals)]
pub const new
: fn() -> Self
= Self::default;
pub fn clone (&self) -> Self { Self::new() }
pub fn total_count () -> isize
{
INSTANCES_COUNT.with(Cell::get)
}
pub fn count_assert_balanced ()
{
use ::std::cmp::Ordering::*;
let instance_count = Self::total_count();
match instance_count.cmp(&0) {
Less => panic!(
concat!(
"Error, instance count {} < 0 ",
r"=> /!\ double free /!\",
),
instance_count,
),
Greater => panic!(
concat!(
"Error, instance count {} > 0 ",
r"=> /!\ memory leak /!\",
),
instance_count,
),
Equal =>(),
}
}
}
impl Drop for Instance {
fn drop (&mut self)
{
INSTANCES_COUNT.with(|slf| slf.set(slf.get() - 1))
}
}
}
#[test]
fn build ()
{
let array = StackVec::<[u8; 10]>::from_iter(
NUMBERS.iter().cloned()
);
println!("{:?}", array);
}
#[test]
fn build_with_drop_full ()
{
use counted_instances::*;
{
let array = StackVec::<[Instance; 3]>::from_iter(
iter::repeat_with(Instance::new)
);
println!("{:?}", array);
}
Instance::count_assert_balanced();
}
#[test]
fn build_with_drop_partial ()
{
use counted_instances::*;
{
let mut array = StackVec::<[Instance; 3]>::default();
array.try_push(
Instance::new()
).unwrap();
println!("{:?}", array);
}
Instance::count_assert_balanced();
}
#[test]
fn extend ()
{
let mut array = StackVec::<[u8; 0x40]>::
default();
array.extend(Iterator::chain(
(0 .. 56).map(|_| 0),
b"Stackvec".iter().cloned(),
));
println!("{:?}", array);
}
#[test]
fn iter ()
{
let array = StackVec::<[u8; 10]>::from_iter(
NUMBERS.iter().cloned()
);
for (value, expected_value) in Iterator::zip(array.iter(), &NUMBERS)
{
assert_eq!(value, expected_value);
};
}
#[test]
fn iter_mut ()
{
let mut array = StackVec::from([0_u8; 10]);
for (array_i, &value) in Iterator::zip(array.iter_mut(), &NUMBERS)
{
*array_i = value;
};
for (value, expected_value) in Iterator::zip(array.iter(), &NUMBERS)
{
assert_eq!(value, expected_value);
};
}
#[test]
fn into_iter ()
{
let array = StackVec::<[u8; 10]>::from_iter(
NUMBERS.iter().cloned()
);
assert_eq!(
Vec::from_iter(array),
Vec::from_iter(NUMBERS.iter().cloned()),
);
}
#[test]
fn array_into_iter ()
{
assert_eq!(
Vec::from_iter(NUMBERS.into_iter()),
Vec::from_iter(NUMBERS.iter().cloned()),
);
}
#[test]
fn into_iter_with_drop_full ()
{
use counted_instances::*;
{
let array = StackVec::<[_; 3]>::from_iter(
iter::repeat_with(Instance::new)
);
println!("{:?}", array);
for _ in array {}
}
Instance::count_assert_balanced();
}
#[test]
fn into_iter_with_drop_partial_left ()
{
use counted_instances::*;
{
let array = StackVec::<[_; 3]>::from_iter(
iter::repeat_with(Instance::new)
);
println!("{:?}", array);
let mut iterator = array.into_iter();
let _ = iterator.next();
}
Instance::count_assert_balanced();
}
#[test]
fn into_iter_with_drop_partial_right ()
{
use counted_instances::*;
{
let array = StackVec::<[_; 3]>::from_iter(
iter::repeat_with(Instance::new)
);
println!("{:?}", array);
let mut iterator = array.into_iter();
let _ = iterator.next_back();
}
Instance::count_assert_balanced();
}
|
pub mod parsed_env;
|
// Copyright © 2017-2023 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
use bs58::{decode::Result, Alphabet};
pub fn encode(input: &[u8], alphabet: &Alphabet) -> String {
bs58::encode(input).with_alphabet(alphabet).into_string()
}
pub fn decode(input: &str, alphabet: &Alphabet) -> Result<Vec<u8>> {
bs58::decode(input).with_alphabet(alphabet).into_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_base58_encode() {
let data = b"Hello, world!";
let expected = "72k1xXWG59wUsYv7h2";
let result = encode(data, Alphabet::BITCOIN);
assert_eq!(result, expected);
}
#[test]
fn test_base58_decode() {
let data = "72k1xXWG59wUsYv7h2";
let expected = b"Hello, world!";
let result = decode(data, Alphabet::BITCOIN).unwrap();
assert_eq!(result, expected.to_vec());
}
}
|
#![no_std]
extern crate cortex_m;
extern crate embedded_hal;
#[cfg(feature = "chip-efm32gg")]
extern crate efm32gg990 as registers;
#[cfg(feature = "chip-efr32xg1")]
extern crate efr32xg1 as registers;
pub mod time_util;
pub mod cmu;
pub mod gpio;
// Right now that's implemented only there, and does not have the internal cfgs yet to run on
// efm32gg as well
#[cfg(feature = "chip-efr32xg1")]
pub mod i2c;
pub mod systick;
pub mod timer;
mod bitband;
mod routing;
|
pub struct Pmu;
const TEST_FAIL: u32 = 0x3333;
const TEST_PASS: u32 = 0x5555;
const TEST_RESET: u32 = 0x7777;
impl rustsbi::Pmu for Pmu {
fn pmu_counter_start(&mut self, counter_idx_base: usize, counter_idx_mask: usize, start_flags: usize, initial_value:u64) -> rustsbi::SbiRet{
rustsbi::SbiRet {
error: 0,
value: 0,
}
}
/// Stop or disable a set of counters on the calling HART. The `counter_idx_base`
///and `counter_idx_mask` parameters represent the set of counters. The bit
///definitions of the `stop_flags` parameter are shown in the below table.
///
/// # Flags
/// | Flag Name | Bits | Description
/// | SBI_PMU_STOP_FLAG_RESET | 0:0 | Reset the counter to event mapping.
/// | *RESERVED* | 1:(XLEN-1) | All non-zero values are reserved
///
/// # Errors
///
/// | Error code | Description
/// | SBI_SUCCESS | counter stopped successfully.
/// | SBI_ERR_INVALID_PARAM | some of the counters specified in parameters
/// are invalid.
/// | SBI_ERR_ALREADY_STOPPED | some of the counters specified in parameters
/// are already stopped.
fn pmu_counter_stop(&mut self, counter_idx_base: usize, counter_idx_mask: usize, stop_flags: usize) -> rustsbi::SbiRet{
rustsbi::SbiRet {
error: 0,
value: 0,
}
}
/// | Function Name | SBI Version | FID | EID
/// | sbi_pmu_num_counters | 0.3 | 0 | 0x504D55
/// | sbi_pmu_counter_get_info | 0.3 | 1 | 0x504D55
/// | sbi_pmu_counter_config_matching | 0.3 | 2 | 0x504D55
/// | sbi_pmu_counter_start | 0.3 | 3 | 0x504D55
/// | sbi_pmu_counter_stop | 0.3 | 4 | 0x504D55
/// | sbi_pmu_counter_fw_read | 0.3 | 5 | 0x504D55
/// Low bits is SBI implementation ID. The firmware specific SBI extensions are
/// for SBI implementations. It provides firmware specific SBI functions which
/// are defined in the external firmware specification.
fn pmu_counter_fw_read(&self, counter_idx: usize) -> rustsbi::SbiRet{
rustsbi::SbiRet {
error: 0,
value: 0,
}
}
}
|
use core::cmp;
use utils::ipoint::IPoint;
use utils::fpoint::FPoint;
#[derive(Clone, Copy, Debug)]
pub struct IRange {
pub start: IPoint,
pub end: IPoint,
}
impl IRange {
pub fn center(self) -> FPoint {
(self.end + self.start).float() * (0.5)
}
pub fn size(self) -> IPoint {
self.end - self.start
}
pub fn clip(self, point: IPoint) -> IPoint {
point.top(self.start).bottom(self.end)
}
pub fn rdist(self, other: IRange) -> i32 {
let max = self.end.bottom(other.end);
let min = self.start.top(other.start);
let diff = max - min;
-cmp::min(diff.x, diff.y)
}
pub fn inside(self, point: IPoint) -> bool {
return point.x < self.end.x && point.y < self.end.y &&
point.x >= self.start.x && point.y >= self.start.y;
}
pub fn iter(self) -> IITer {
IITer::new(self)
}
pub fn intersect(self, other: IRange) -> IRange {
IRange {
start: self.start.top(other.start),
end: self.end.bottom(other.end)
}
}
}
impl IntoIterator for IRange {
type Item = IPoint;
type IntoIter = IITer;
fn into_iter(self) -> IITer {
IITer::new(self)
}
}
pub struct IITer {
range: IRange,
x: i32,
y: i32
}
impl IITer {
fn new(range: IRange) -> IITer {
IITer {
range,
x: range.start.x,
y: range.start.y,
}
}
}
impl Iterator for IITer {
type Item = IPoint;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
if self.y >= self.range.end.y {
return None
}
let result = IPoint { x: self.x, y: self.y };
self.x += 1;
if self.x >= self.range.end.x {
self.x = self.range.start.x;
self.y += 1;
}
Some(result)
}
}
|
//! Implementation of command line option for running the querier
use crate::process_info::setup_metric_registry;
use super::main;
use clap_blocks::{
catalog_dsn::CatalogDsnConfig, object_store::make_object_store, querier::QuerierConfig,
run_config::RunConfig,
};
use iox_query::exec::Executor;
use iox_time::{SystemProvider, TimeProvider};
use ioxd_common::{
server_type::{CommonServerState, CommonServerStateError},
Service,
};
use ioxd_querier::{create_querier_server_type, QuerierServerTypeArgs};
use object_store::DynObjectStore;
use object_store_metrics::ObjectStoreMetrics;
use observability_deps::tracing::*;
use std::{num::NonZeroUsize, sync::Arc};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Run: {0}")]
Run(#[from] main::Error),
#[error("Invalid config: {0}")]
InvalidConfigCommon(#[from] CommonServerStateError),
#[error("Catalog error: {0}")]
Catalog(#[from] iox_catalog::interface::Error),
#[error("Catalog DSN error: {0}")]
CatalogDsn(#[from] clap_blocks::catalog_dsn::Error),
#[error("Cannot parse object store config: {0}")]
ObjectStoreParsing(#[from] clap_blocks::object_store::ParseError),
#[error("Querier error: {0}")]
Querier(#[from] ioxd_querier::Error),
#[error("Authz service error: {0}")]
AuthzService(#[from] authz::Error),
}
#[derive(Debug, clap::Parser)]
#[clap(
name = "run",
about = "Runs in querier mode",
long_about = "Run the IOx querier server.\n\nThe configuration options below can be \
set either with the command line flags or with the specified environment \
variable. If there is a file named '.env' in the current working directory, \
it is sourced before loading the configuration.
Configuration is loaded from the following sources (highest precedence first):
- command line arguments
- user set environment variables
- .env file contents
- pre-configured default values"
)]
pub struct Config {
#[clap(flatten)]
pub(crate) run_config: RunConfig,
#[clap(flatten)]
pub(crate) catalog_dsn: CatalogDsnConfig,
#[clap(flatten)]
pub(crate) querier_config: QuerierConfig,
}
pub async fn command(config: Config) -> Result<(), Error> {
let common_state = CommonServerState::from_config(config.run_config.clone())?;
let time_provider = Arc::new(SystemProvider::new()) as Arc<dyn TimeProvider>;
let metric_registry = setup_metric_registry();
let catalog = config
.catalog_dsn
.get_catalog("querier", Arc::clone(&metric_registry))
.await?;
let object_store = make_object_store(config.run_config.object_store_config())
.map_err(Error::ObjectStoreParsing)?;
// Decorate the object store with a metric recorder.
let object_store: Arc<DynObjectStore> = Arc::new(ObjectStoreMetrics::new(
object_store,
Arc::clone(&time_provider),
&metric_registry,
));
let time_provider = Arc::new(SystemProvider::new());
let num_query_threads = config.querier_config.num_query_threads();
let num_threads = num_query_threads.unwrap_or_else(|| {
NonZeroUsize::new(num_cpus::get()).unwrap_or_else(|| NonZeroUsize::new(1).unwrap())
});
info!(%num_threads, "using specified number of threads per thread pool");
let ingester_addresses = &config.querier_config.ingester_addresses;
info!(?ingester_addresses, "using ingester addresses");
let exec = Arc::new(Executor::new(
num_threads,
config.querier_config.exec_mem_pool_bytes,
Arc::clone(&metric_registry),
));
let server_type = create_querier_server_type(QuerierServerTypeArgs {
common_state: &common_state,
metric_registry: Arc::clone(&metric_registry),
catalog,
object_store,
exec,
time_provider,
querier_config: config.querier_config,
trace_context_header_name: config
.run_config
.tracing_config()
.traces_jaeger_trace_context_header_name
.clone(),
})
.await?;
info!("starting querier");
let services = vec![Service::create(server_type, common_state.run_config())];
Ok(main::main(common_state, services, metric_registry).await?)
}
|
pub struct Register {
pub v0: u8,
pub v1: u8,
pub v2: u8,
pub v3: u8,
pub v4: u8,
pub v5: u8,
pub v6: u8,
pub v7: u8,
pub v8: u8,
pub v9: u8,
pub va: u8,
pub vb: u8,
pub vc: u8,
pub vd: u8,
pub ve: u8,
pub vf: u8,
}
impl Register {
pub fn set_register(&mut self, register: u16, value: u8) {
match register {
0x0 => self.v0 = value,
0x1 => self.v1 = value,
0x2 => self.v2 = value,
0x3 => self.v3 = value,
0x4 => self.v4 = value,
0x5 => self.v5 = value,
0x6 => self.v6 = value,
0x7 => self.v7 = value,
0x8 => self.v8 = value,
0x9 => self.v9 = value,
0xa => self.va = value,
0xb => self.vb = value,
0xc => self.vc = value,
0xd => self.vd = value,
0xe => self.ve = value,
0xf => self.vf = value,
_ => ()
}
}
pub fn get_register(&mut self, register: u16) -> u8 {
match register {
0x0 => self.v0,
0x1 => self.v1,
0x2 => self.v2,
0x3 => self.v3,
0x4 => self.v4,
0x5 => self.v5,
0x6 => self.v6,
0x7 => self.v7,
0x8 => self.v8,
0x9 => self.v9,
0xa => self.va,
0xb => self.vb,
0xc => self.vc,
0xd => self.vd,
0xe => self.ve,
0xf => self.vf,
_ => 0
}
}
} |
#[macro_use]
extern crate serde_json;
mod calculations;
use calculations::percentages;
fn main() {
println!(
"{}\n{}\n{}\n{}",
percentages::change_by_percentage(100.47, 25.0),
percentages::find_percentage_value(50.0, 30.0),
percentages::find_percentage_difference(25.0, 40.0),
percentages::find_percentage(25.0, 40.0),
);
}
|
/*
Aim: wrap generated parser fns in struct
*/
use super::smtp::{command, session};
pub use super::smtp::{ParseError, ParseResult};
use model::command::{SmtpCommand, SmtpInput};
static PARSER: SmtpParser = SmtpParser;
pub trait Parser {
fn command<'input>(&self, input: &'input str) -> ParseResult<SmtpCommand>;
}
#[derive(Clone)]
pub struct SmtpParser;
impl SmtpParser {
pub fn new() -> SmtpParser {
PARSER.clone()
}
pub fn session<'input>(&self, input: &'input str) -> ParseResult<Vec<SmtpInput>> {
session(input)
}
pub fn command<'input>(&self, input: &'input str) -> ParseResult<SmtpCommand> {
command(input)
}
}
impl Parser for SmtpParser {
fn command<'input>(&self, input: &'input str) -> ParseResult<SmtpCommand> {
self.command(input)
}
}
|
use std::io::{
Error as IOError,
ErrorKind,
Read,
Result as IOResult,
};
use sourcerenderer_mdl::PrimitiveRead;
pub struct GlbHeader {
magic: u32,
version: u32,
pub length: u32,
}
impl GlbHeader {
pub fn read<R: Read>(reader: &mut R) -> IOResult<Self> {
let magic = reader.read_u32()?;
let version = reader.read_u32()?;
let length = reader.read_u32()?;
if magic != 0x46546c67 {
// glTF
return Err(IOError::new(ErrorKind::Other, "Invalid format"));
}
if version != 2 {
return Err(IOError::new(ErrorKind::Other, "Invalid version"));
}
Ok(Self {
magic,
version,
length,
})
}
pub fn size() -> u64 {
12
}
}
pub struct GlbChunkHeader {
pub length: u32,
chunk_type: u32,
}
impl GlbChunkHeader {
pub fn read<R: Read>(reader: &mut R) -> IOResult<Self> {
let length = reader.read_u32()?;
let chunk_type = reader.read_u32()?;
if chunk_type != 0x4E4F534A && chunk_type != 0x004E4942 {
// "JSON" || "BIN"
return Err(IOError::new(ErrorKind::Other, "Invalid chunk type"));
}
Ok(Self { length, chunk_type })
}
pub fn size() -> u64 {
8
}
}
pub fn read_chunk<R: Read>(reader: &mut R) -> IOResult<Vec<u8>> {
let header = GlbChunkHeader::read(reader)?;
let mut data = Vec::with_capacity(header.length as usize);
unsafe {
data.set_len(header.length as usize);
}
reader.read_exact(&mut data)?;
Ok(data)
}
|
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use super::base::{BuildArgs, BuildCode};
use super::graph::Args;
impl<'a> BuildCode<'a> for n3_program::Program {
type Args = ();
type Output = &'a PyAny;
fn build(&'a self, py: Python<'a>, (): Self::Args) -> PyResult<Self::Output> {
// Step 1. Convert the args
let args = Args(&self.graph).into_py_dict(py);
if let Some(env) = &self.env {
let env = Args(env).into_py_dict(py);
args.set_item("env", env)?;
}
let build_args = BuildArgs {
args: &args,
scripts: &self.scripts,
};
// Step 2. Build the nodes
let nodes: Vec<_> = self
.nodes
.iter()
.map(|(k, v)| Ok((k, v.build(py, &build_args)?)))
.collect::<PyResult<_>>()?;
let nodes = nodes.into_iter().into_py_dict(py);
// Step 3. Get the main program
let main = &self.scripts["__main__"];
// Step 4. Define the node in REPL
py.run(&main.source, None, None)?;
// Step 5. Instantiate
py.eval(
&format!("{name}(args, nodes)", name = &main.name),
None,
Some([("args", args), ("nodes", nodes)].into_py_dict(py)),
)
}
}
|
extern crate env_logger;
/// Tool that generates constraints from stdin to stdout.
extern crate telamon_gen;
use std::path::Path;
use std::process;
fn main() {
env_logger::init();
if let Err(process_error) = telamon_gen::process(
Some(&mut std::io::stdin()),
&mut std::io::stdout(),
&Path::new("exh"),
) {
eprintln!("error: {}", process_error);
process::exit(-1);
}
}
|
use crate::blog_clusters::TagHandle;
fn valid_date(year: i64, month: i64, day: i64) -> bool {
if year > 2200 || year < 2000 {
return false;
}
let leap = (((year % 4) == 0) && (year % 100 != 0)) || ((year % 400) == 0);
return match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => day <= 31 && day >= 1,
4 | 6 | 9 | 11 => day <= 30 && day >= 1,
2 => (day <= if leap { 29 } else { 28 }) && (day >= 1),
_ => false,
};
}
#[derive(Debug, Clone)]
pub struct Blog {
pub year: u16,
pub month: u16,
pub day: u16,
pub title: String,
pub tags: Vec<TagHandle>,
pub preview: String,
pub content: String, // reference to the blog content
}
impl Blog {
pub fn new(
year: i64,
month: i64,
day: i64,
title: String,
tags: Vec<TagHandle>,
preview: String,
content: String,
) -> Self {
// This isn't a program for others, I would use it myself so I will panic whenever possible
if !valid_date(year, month, day) {
panic!("Blog's date is invalid!");
}
Blog {
year: year as u16,
month: month as u16,
day: day as u16,
title: title,
tags: tags,
preview: preview,
content: content,
}
}
}
#[cfg(test)]
mod blog_tests {
use super::*;
#[test]
fn test_valid_date() {
assert_eq!(true, valid_date(2000, 2, 29));
assert_eq!(true, valid_date(2004, 2, 29));
assert_eq!(true, valid_date(2019, 12, 15));
assert_eq!(true, valid_date(2001, 2, 28));
assert_eq!(true, valid_date(2002, 2, 28));
assert_eq!(true, valid_date(2003, 2, 28));
assert_eq!(true, valid_date(2003, 3, 31));
}
#[test]
fn test_invalid_date() {
assert_eq!(false, valid_date(2001, 2, 29));
assert_eq!(false, valid_date(2002, 2, 29));
assert_eq!(false, valid_date(2003, 2, 29));
assert_eq!(false, valid_date(2003, 4, 31));
assert_eq!(false, valid_date(1999, 1, 1));
assert_eq!(false, valid_date(2099, 0, 1));
assert_eq!(false, valid_date(2099, 1, 0));
}
}
|
use super::*;
use std::cmp::{min, max, Ordering};
/// [0..1] should probably be somewhere close to 0.1
const MAX_DIFFICULTY_DELTA: f32 = 0.2;
/// Allows for evaluation of content for inclusion to dungeon.
pub trait Evaluate: Clone {
fn theme(&self) -> &[Keyword];
fn difficulty(&self) -> usize;
fn max_difficulty(&self) -> usize {
10
}
fn normalized_difficulty(&self) -> f32 {
self.difficulty() as f32 / self.max_difficulty() as f32
}
}
pub fn rank_by_fitness<'a, T: Evaluate, K: AsRef<Keyword>>(
content: &'a [T],
room_difficulty: f32,
room_theme: &[K])
-> Vec<(f32, &'a T)> {
let mut fitnesses: Vec<(f32, &T)> = content.iter().enumerate()
.map(|(i, ref item)| {
(evaluate(*item, room_difficulty, room_theme), &content[i])
}).collect();
fitnesses.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Less));
fitnesses
}
pub fn rank_by_difficulty<'a, T: Evaluate>(
content: &'a [T],
room_difficulty: f32)
-> Vec<(f32, &'a T)> {
let mut fitnesses: Vec<(f32, &T)> = content.iter().enumerate()
.map(|(i, ref item)| {
(evaluate_difficulty(*item, room_difficulty), &content[i])
}).collect();
fitnesses.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Less));
fitnesses
}
/// Returns the compatibility of content with the given keywords and difficulty. Basically a fitness function.
pub fn evaluate<T: Evaluate, K: AsRef<Keyword>>(content: &T, room_difficulty: f32, room_theme: &[K]) -> f32 {
// Theme suitability, [0..1]
let theme_match_frac = evaluate_theme(content, room_theme);
// Difficulty suitability [0..1]
let difficulty_match_frac = evaluate_difficulty(content, room_difficulty);
let fitness = theme_match_frac.min(difficulty_match_frac);
return fitness;
}
pub fn evaluate_theme<T: Evaluate, K: AsRef<Keyword>>(content: &T, room_theme: &[K]) -> f32 {
// Count number of keywords in content that match with room
let num_matching_keywords = content.theme().iter().filter(|&content_kw| room_theme.iter().any(|room_kw| room_kw.as_ref() == content_kw)).count() as f32;
//let num_content_keywords = content.theme().iter().count() as f32;
let num_room_keywords = room_theme.iter().count() as f32;
// Theme suitability, [0..1]
num_matching_keywords / num_room_keywords
}
pub fn evaluate_difficulty<T: Evaluate>(content: &T, room_difficulty: f32) -> f32 {
let delta = (content.normalized_difficulty() - room_difficulty).abs();
match MAX_DIFFICULTY_DELTA - delta {
distance if distance > 0. => {distance / MAX_DIFFICULTY_DELTA},
_ => 0.,
}
}
|
/// for dan iterator
///
/// for in dapat digunakan untuk berinteraksi dengan `Iterator`
/// dalam beberapa cara.
/// jika tidak disebutkan(not specified) maka loop akan menerapkan fungsi `into_iter`
/// pada koleksi untuk mengubah kedalam iterator
///
/// Ada 3 fungsi yang akan mengembalikan pandangan yg berbeda dari data pada koleksi
/// atau collection.
///
fn main() {
println!("for name in names.iter()");
for_iter();
println!("\n");
println!("for name in names.into_iter()");
for_into_iter();
println!("\n");
println!("for name in names.iter_mut()");
for_iter_mut();
}
// 1. iter
// `iter` akan meminjam setiap elemen dari kumpulan melalui setiap pengulangan.
// dengan demikian membiarkan kumpulan tidak tersentuh dan tersedia untuk digunakan
// kembali setelah pengulangan.
fn for_iter() {
let names = vec!["Agus", "Susilo", "Nurhayati"];
for name in names.iter() {
match name {
&"Nurhayati" => println!("Halo sayangku!"),
_ => println!("Hello {}", name),
}
}
}
// 2. into_iter
// `into_iter` memakai koleksi data pada setiap perulangan pada data yg disediakan.
// setelah data selesai dipakai(consume) data tsb tidak lagi tersedia untuk digunakan
// kembali karena sudah dipindahkan kedalam perulangan
fn for_into_iter() {
let names = vec!["Agus", "Susilo", "Nurhayati"];
for name in names.into_iter() {
match name {
// bandingkan dengan kode diatas, tidak ada tanda & (borrow)
"Nurhayati" => println!("Halo sayangku!"),
_ => println!("Hello {}", name),
}
}
}
// 3. iter_mut
// `iter_mut` meminjam data dan mungkin merubah isinya pada setiap elemen pada koleksi
// mengijinkan koleksi untuk dirubah pada tempatnya.
fn for_iter_mut() {
let mut names = vec!["Agus", "Susilo", "Nurhayati"];
for name in names.iter_mut() {
*name = match name {
// bandingkan dengan kode diatas, tidak ada tanda & (borrow)
&mut "Nurhayati" => "Halo sayangku!",
_ => "Hello",
}
}
println!("names: {:?}", names);
} |
use serde::{Deserialize, Serialize};
use serde::ser::{Serializer, SerializeStruct};
use crate::api::message::amount::{Amount, string_or_struct};
use crate::api::utils::tx_flags::*;
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub enum RelationType {
TRUST = 0,
AUTHORIZE = 1,
FREEZE = 3,
}
impl RelationType {
pub fn get(&self) -> u32 {
match *self {
RelationType::TRUST => { 0 },
RelationType::AUTHORIZE => { 1 },
RelationType::FREEZE => { 3 },
}
}
}
/*
LimitAmount Can't be Native.!!!
*/
#[derive(Deserialize, Debug, Default)]
pub struct RelationTxJson {
#[serde(rename="Flags")]
pub flags: u32,
#[serde(rename="Fee")]
pub fee: u64,
#[serde(rename="TransactionType")]
pub transaction_type: String,
#[serde(rename="Account")]
pub account: String,
#[serde(rename="Target")]
pub target: String,
#[serde(rename="RelationType")]
pub relation_type: u32,
#[serde(rename="LimitAmount")]
#[serde(deserialize_with = "string_or_struct")]
pub limit_amount: Amount,
}
impl RelationTxJson {
pub fn new(account: String, target: String, rtype: u32, amount: Amount) -> Self {
let flag = Flags::Other;
RelationTxJson {
flags: flag.get(),
fee: 10000,
transaction_type: "RelationSet".to_string(),
account: account,
target: target,
relation_type: rtype,
limit_amount: amount,
}
}
}
impl Serialize for RelationTxJson {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// 7 is the number of fields in the struct.
let mut state = serializer.serialize_struct("RelationTxJson", 7)?;
state.serialize_field("Flags", &self.flags)?;
state.serialize_field("Fee", &self.fee)?;
state.serialize_field("TransactionType", &self.transaction_type)?;
state.serialize_field("Account", &self.account)?;
state.serialize_field("Target", &self.target)?;
state.serialize_field("RelationType", &self.relation_type)?;
if self.limit_amount.is_string() {
state.serialize_field("LimitAmount", &Amount::mul_million(&self.limit_amount.value))?;
} else {
state.serialize_field("LimitAmount", &self.limit_amount)?;
}
state.end()
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct RelationTx {
#[serde(rename="id")]
id: u64,
#[serde(rename="command")]
pub command: String,
#[serde(rename="secret")]
pub secret: String,
#[serde(rename="tx_json")]
pub tx_json: RelationTxJson,
}
impl RelationTx {
pub fn new(secret: String, tx_json: RelationTxJson) -> Box<RelationTx> {
Box::new( RelationTx {
id: 1,
command: "submit".to_string(),
secret: secret,
tx_json: tx_json,
})
}
pub fn to_string(&self) -> Result<String, serde_json::error::Error> {
let j = serde_json::to_string(&self)?;
Ok(j)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct RelationTxJsonResponse {
#[serde(rename="Account")]
pub account: String,
#[serde(rename="Fee")]
pub fee: String,
#[serde(rename="Flags")]
pub flags: i32,
#[serde(rename="LimitAmount")]
#[serde(deserialize_with = "string_or_struct")]
pub limit_amount: Amount,
#[serde(rename="RelationType")]
pub relation_type: u64,
#[serde(rename="Sequence")]
pub sequence: u64,
#[serde(rename="SigningPubKey")]
pub signing_pub_key: String,
#[serde(rename="Target")]
pub target: String,
#[serde(rename="Timestamp")]
pub time_stamp: Option<u64>,
#[serde(rename="TransactionType")]
pub transaction_type: String,
#[serde(rename="TxnSignature")]
pub txn_signature: String,
#[serde(rename="hash")]
pub hash: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct RelationTxResponse {
#[serde(rename="engine_result")]
pub engine_result: String,
#[serde(rename="engine_result_code")]
pub engine_result_code: i32,
#[serde(rename="engine_result_message")]
pub engine_result_message: String,
#[serde(rename="tx_blob")]
pub tx_blob: String,
#[serde(rename="tx_json")]
pub tx_json: RelationTxJsonResponse,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RelationSideKick {
pub error : String,
pub error_code : i32,
pub error_message : String,
pub id : u32,
pub request : RelationTx,
pub status : String,
#[serde(rename="type")]
pub rtype : String,
}
impl fmt::Display for RelationSideKick {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RelationSideKick is here!")
}
}
impl Error for RelationSideKick {
fn description(&self) -> &str {
"I'm RelationSideKick side kick"
}
}
|
extern crate seedlink;
use seedlink::SeedLinkClient;
#[test]
#[ignore]
fn streams() {
let mut slc = SeedLinkClient::new("rtserve.iris.washington.edu", 18000);
slc.connect(true).expect("bad hello");
let info = slc.available_streams().expect("bad streams");
let streams = info.streams();
for s in streams {
println!("{}", s);
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::sync::Arc;
use core::ops::Deref;
use spin::RwLock;
use super::super::super::kernel::time::*;
use super::super::super::qlib::common::*;
use super::super::super::qlib::linux::time::*;
//use super::super::super::qlib::perf_tunning::*;
use super::super::vdso::*;
use super::calibratedClock::*;
use super::timer::Clock;
use super::timer::*;
use super::*;
#[derive(Clone, Default)]
pub struct TimeKeeper(Arc<RwLock<TimeKeeperInternal>>);
impl Deref for TimeKeeper {
type Target = Arc<RwLock<TimeKeeperInternal>>;
fn deref(&self) -> &Arc<RwLock<TimeKeeperInternal>> {
&self.0
}
}
impl TimeKeeper {
pub fn Init(&self, vdsoParamPageAddr: u64) {
{
let mut internal = self.write();
internal.Init(vdsoParamPageAddr);
}
let timer = Timer::Period(&MONOTONIC_CLOCK, &Arc::new(TimerUpdater {}), 60 * SECOND);
{
let mut internal = self.write();
internal.timer = Some(timer);
}
}
pub fn NewClock(&self, clockId: ClockID) -> Clock {
let c = TimeKeeperClock {
tk: self.clone(),
c: clockId,
};
return Clock::TimeKeeperClock(Arc::new(c));
}
pub fn Update(&self) {
self.write().Update();
}
pub fn GetTime(&self, c: ClockID) -> Result<i64> {
return self.read().GetTime(c)
}
pub fn BootTime(&self) -> Time {
return self.read().BootTime();
}
}
pub struct TimeKeeperInternal {
// clocks are the clock sources.
pub clocks: CalibratedClocks,
// bootTime is the realtime when the system "booted". i.e., when
// SetClocks was called in the initial (not restored) run.
pub bootTime: Time,
// monotonicOffset is the offset to apply to the monotonic clock output
// from clocks.
//
// It is set only once, by SetClocks.
pub monotonicOffset: i64,
// params manages the parameter page.
pub params: VDSOParamPage,
pub inited: bool,
pub timer: Option<Timer>,
}
impl Default for TimeKeeperInternal {
fn default() -> Self {
let clocks = CalibratedClocks::New();
let res = Self {
clocks: clocks,
bootTime: Time::default(),
monotonicOffset: 0,
params: VDSOParamPage::default(),
inited: false,
timer: None,
};
return res;
}
}
impl TimeKeeperInternal {
pub fn Init(&mut self, vdsoParamPageAddr: u64) {
self.params.SetParamPageAddr(vdsoParamPageAddr);
// Compute the offset of the monotonic clock from the base Clocks.
//
let wantMonotonic = 0;
let nowMonotonic = self.clocks.GetTime(MONOTONIC).expect("Unable to get current monotonic time");
let nowRealtime = self.clocks.GetTime(REALTIME).expect("Unable to get current realtime");
self.monotonicOffset = wantMonotonic - nowMonotonic;
self.bootTime = Time::FromNs(nowRealtime);
self.inited = true;
self.Update();
}
pub fn MonotonicFrequency(&self) -> u64 {
return self.params.vdsoParams.monotonicFrequency;
}
pub fn Update(&mut self) {
//PerfPrint();
//super::super::super::perflog::THREAD_COUNTS.lock().Print(true);
//super::super::super::AllocatorPrint();
assert!(self.inited, "TimeKeeper not inited");
let (monotonicParams, monotonicOk, realtimeParams, realtimeOk) = self.clocks.Update();
let mut p = VdsoParams::default();
if monotonicOk {
p.monotonicReady = 1;
p.monotonicBaseCycles = monotonicParams.BaseCycles;
p.monotonicBaseRef = monotonicParams.BaseRef + self.monotonicOffset;
p.monotonicFrequency = monotonicParams.Frequency;
}
//error!("TimeKeeperInternal::Update monotonicParams is {:?}", &monotonicParams);
if realtimeOk {
p.realtimeReady = 1;
p.realtimeBaseCycles = realtimeParams.BaseCycles;
p.realtimeBaseRef = realtimeParams.BaseRef;
p.realtimeFrequency = realtimeParams.Frequency;
}
match self.params.Write(&p) {
Err(err) => info!("Unable to update VDSO parameter page: {:?}", err),
_ => (),
}
}
// GetTime returns the current time in nanoseconds.
pub fn GetTime(&self, c: ClockID) -> Result<i64> {
assert!(self.inited, "TimeKeeper not inited");
match self.clocks.GetTime(c) {
Err(e) => return Err(e),
Ok(mut now) => {
if c == MONOTONIC {
now += self.monotonicOffset;
}
return Ok(now)
}
}
}
// BootTime returns the system boot real time.
pub fn BootTime(&self) -> Time {
assert!(self.inited, "TimeKeeper not inited");
return self.bootTime;
}
}
#[derive(Clone)]
pub struct TimeKeeperClock {
pub tk: TimeKeeper,
pub c: ClockID,
}
impl TimeKeeperClock {
pub fn Now(&self) -> Time {
let now = self.tk.GetTime(self.c).expect("timekeeperClock Now fail");
return Time::FromNs(now);
}
pub fn WallTimeUntil(&self, t: Time, now: Time) -> Duration {
return t.Sub(now)
}
}
|
use crate::interaction::SurfaceInteraction;
pub trait Texture<T> {
fn evaluate(&self, si: &SurfaceInteraction) -> T;
}
pub mod constant;
pub use constant::*;
|
fn main() {
let s1: String = String::new();
let s2: &str = "hello world";
let s3 = s2.to_string(); // Declare s3: String from s2
let s4 = String::from("like a declaring s3 from s2");
println!("s1: {}", s1);
println!("s2: {}", s2);
println!("s3: {}", s3);
println!("s4: {}", s4);
let mut s5 = String::from("foo");
s5.push_str("bar");
s5.push('1');
let s6 = String::from("hello, ");
let s7 = String::from("world!");
let s8 = s6 + &s7;
let s9 = String::from("tic");
let s10 = String::from("tac");
let s11 = String::from("toe");
let s12 = s9 + "-" + &s10 + "-" + &s11; // It's sucks
let s13 = String::from("tic");
let s14 = format!("{}-{}-{}", s13, s10, s11);
// let s15 = String::from("hello");
// let h = &s15[0]; // String of the rust not support indexing
let korean = String::from("안녕하세요");
let korean_len = korean.len();
println!("5글자일까?? {}", korean_len); // 한글은 글자당 3byte이기 때문에 15로 나옴
let an = &korean[0..3];
println!("an: {}", an);
let hello = "Здравствуйте";
let answer = &hello[0..2];
for i in korean.chars() {
println!("{}", i)
}
for i in korean.bytes() { // 15bytes
println!("{}", i)
}
}
|
//! Python bindings for needletail
use std::io::Cursor;
use pyo3::prelude::*;
use pyo3::{create_exception, wrap_pyfunction};
use crate::sequence::{complement, normalize};
use crate::{
parse_fastx_file as rs_parse_fastx_file, parse_fastx_reader, parser::SequenceRecord,
FastxReader,
};
create_exception!(needletail, NeedletailError, pyo3::exceptions::PyException);
// Avoid some boilerplate with the error handling
macro_rules! py_try {
($call:expr) => {
$call.map_err(|e| PyErr::new::<NeedletailError, _>(format!("{}", e)))?
};
}
#[pyclass]
pub struct PyFastxReader {
reader: Box<dyn FastxReader>,
}
#[pymethods]
impl PyFastxReader {
fn __repr__(&self) -> PyResult<String> {
Ok("<FastxParser>".to_string())
}
fn __iter__(slf: PyRefMut<Self>, py: Python<'_>) -> PyResult<FastxReaderIterator> {
Ok(FastxReaderIterator { t: slf.into_py(py) })
}
}
#[pyclass]
pub struct Record {
#[pyo3(get)]
id: String,
#[pyo3(get)]
seq: String,
#[pyo3(get)]
qual: Option<String>,
}
impl Record {
fn from_sequence_record(rec: &SequenceRecord) -> Self {
Self {
id: String::from_utf8_lossy(rec.id()).to_string(),
seq: String::from_utf8_lossy(&rec.seq()).to_string(),
qual: rec.qual().map(|q| String::from_utf8_lossy(q).to_string()),
}
}
}
#[pymethods]
impl Record {
pub fn is_fasta(&self) -> PyResult<bool> {
Ok(self.qual.is_none())
}
pub fn is_fastq(&self) -> PyResult<bool> {
Ok(self.qual.is_some())
}
pub fn normalize(&mut self, iupac: bool) -> PyResult<()> {
if let Some(s) = normalize(self.seq.as_bytes(), iupac) {
self.seq = String::from_utf8_lossy(&s).to_string();
}
Ok(())
}
}
#[pyclass]
pub struct FastxReaderIterator {
t: PyObject,
}
#[pymethods]
impl FastxReaderIterator {
fn __next__(slf: PyRef<Self>, py: Python<'_>) -> PyResult<Option<Record>> {
let mut parser: PyRefMut<PyFastxReader> = slf.t.extract(py)?;
if let Some(rec) = parser.reader.next() {
let record = py_try!(rec);
Ok(Some(Record::from_sequence_record(&record)))
} else {
Ok(None)
}
}
}
// TODO: what would be really nice is to detect the type of pyobject so it would on file object etc
// not for initial release though
#[pyfunction]
fn parse_fastx_file(path: &str) -> PyResult<PyFastxReader> {
let reader = py_try!(rs_parse_fastx_file(path));
Ok(PyFastxReader { reader })
}
#[pyfunction]
fn parse_fastx_string(content: &str) -> PyResult<PyFastxReader> {
let reader = py_try!(parse_fastx_reader(Cursor::new(content.to_owned())));
Ok(PyFastxReader { reader })
}
#[pyfunction]
pub fn normalize_seq(seq: &str, iupac: bool) -> PyResult<String> {
if let Some(s) = normalize(seq.as_bytes(), iupac) {
Ok(String::from_utf8_lossy(&s).to_string())
} else {
Ok(seq.to_owned())
}
}
#[pyfunction]
pub fn reverse_complement(seq: &str) -> String {
let comp: Vec<u8> = seq
.as_bytes()
.iter()
.rev()
.map(|n| complement(*n))
.collect();
String::from_utf8_lossy(&comp).to_string()
}
#[pymodule]
fn needletail(py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<PyFastxReader>()?;
m.add_wrapped(wrap_pyfunction!(parse_fastx_file))?;
m.add_wrapped(wrap_pyfunction!(parse_fastx_string))?;
m.add_wrapped(wrap_pyfunction!(normalize_seq))?;
m.add_wrapped(wrap_pyfunction!(reverse_complement))?;
m.add("NeedletailError", py.get_type::<NeedletailError>())?;
Ok(())
}
|
use cgmath::Vector3;
use std::marker::PhantomData;
use std::{f32, u32};
use soa_ray::{
SoAHit, SoAHitIter, SoAHitIterMut, SoAHitRef, SoARay, SoARayIter, SoARayIterMut, SoARayRef,
SoARayRefMut,
};
use sys;
pub type Ray4 = sys::RTCRay4;
pub type Hit4 = sys::RTCHit4;
pub type RayHit4 = sys::RTCRayHit4;
impl Ray4 {
pub fn empty() -> Ray4 {
Ray4::segment(
[Vector3::new(0.0, 0.0, 0.0); 4],
[Vector3::new(0.0, 0.0, 0.0); 4],
[0.0; 4],
[f32::INFINITY; 4],
)
}
pub fn new(origin: [Vector3<f32>; 4], dir: [Vector3<f32>; 4]) -> Ray4 {
Ray4::segment(origin, dir, [0.0; 4], [f32::INFINITY; 4])
}
pub fn segment(
origin: [Vector3<f32>; 4],
dir: [Vector3<f32>; 4],
tnear: [f32; 4],
tfar: [f32; 4],
) -> Ray4 {
sys::RTCRay4 {
org_x: [origin[0].x, origin[1].x, origin[2].x, origin[3].x],
org_y: [origin[0].y, origin[1].y, origin[2].y, origin[3].y],
org_z: [origin[0].z, origin[1].z, origin[2].z, origin[3].z],
dir_x: [dir[0].x, dir[1].x, dir[2].x, dir[3].x],
dir_y: [dir[0].y, dir[1].y, dir[2].y, dir[3].y],
dir_z: [dir[0].z, dir[1].z, dir[2].z, dir[3].z],
tnear: tnear,
tfar: tfar,
time: [0.0; 4],
mask: [u32::MAX; 4],
id: [0; 4],
flags: [0; 4],
}
}
pub fn iter(&self) -> SoARayIter<Ray4> {
SoARayIter::new(self, 4)
}
pub fn iter_mut(&mut self) -> SoARayIterMut<Ray4> {
SoARayIterMut::new(self, 4)
}
}
impl SoARay for Ray4 {
fn org(&self, i: usize) -> Vector3<f32> {
Vector3::new(self.org_x[i], self.org_y[i], self.org_z[i])
}
fn set_org(&mut self, i: usize, o: Vector3<f32>) {
self.org_x[i] = o.x;
self.org_y[i] = o.y;
self.org_z[i] = o.z;
}
fn dir(&self, i: usize) -> Vector3<f32> {
Vector3::new(self.dir_x[i], self.dir_y[i], self.dir_z[i])
}
fn set_dir(&mut self, i: usize, d: Vector3<f32>) {
self.dir_x[i] = d.x;
self.dir_y[i] = d.y;
self.dir_z[i] = d.z;
}
fn tnear(&self, i: usize) -> f32 {
self.tnear[i]
}
fn set_tnear(&mut self, i: usize, near: f32) {
self.tnear[i] = near;
}
fn tfar(&self, i: usize) -> f32 {
self.tfar[i]
}
fn set_tfar(&mut self, i: usize, far: f32) {
self.tfar[i] = far;
}
fn time(&self, i: usize) -> f32 {
self.time[i]
}
fn set_time(&mut self, i: usize, time: f32) {
self.time[i] = time;
}
fn mask(&self, i: usize) -> u32 {
self.mask[i]
}
fn set_mask(&mut self, i: usize, mask: u32) {
self.mask[i] = mask;
}
fn id(&self, i: usize) -> u32 {
self.id[i]
}
fn set_id(&mut self, i: usize, id: u32) {
self.id[i] = id;
}
fn flags(&self, i: usize) -> u32 {
self.flags[i]
}
fn set_flags(&mut self, i: usize, flags: u32) {
self.flags[i] = flags;
}
}
impl Hit4 {
pub fn new() -> Hit4 {
sys::RTCHit4 {
Ng_x: [0.0; 4],
Ng_y: [0.0; 4],
Ng_z: [0.0; 4],
u: [0.0; 4],
v: [0.0; 4],
primID: [u32::MAX; 4],
geomID: [u32::MAX; 4],
instID: [[u32::MAX; 4]],
}
}
pub fn any_hit(&self) -> bool {
self.hits().fold(false, |acc, g| acc || g)
}
pub fn hits<'a>(&'a self) -> impl Iterator<Item = bool> + 'a {
self.geomID.iter().map(|g| *g != u32::MAX)
}
pub fn iter(&self) -> SoAHitIter<Hit4> {
SoAHitIter::new(self, 4)
}
pub fn iter_hits<'a>(&'a self) -> impl Iterator<Item = SoAHitRef<Hit4>> + 'a {
SoAHitIter::new(self, 4).filter(|h| h.hit())
}
}
impl SoAHit for Hit4 {
fn normal(&self, i: usize) -> Vector3<f32> {
Vector3::new(self.Ng_x[i], self.Ng_y[i], self.Ng_z[i])
}
fn set_normal(&mut self, i: usize, n: Vector3<f32>) {
self.Ng_x[i] = n.x;
self.Ng_y[i] = n.y;
self.Ng_z[i] = n.z;
}
fn uv(&self, i: usize) -> (f32, f32) {
(self.u[i], self.v[i])
}
fn set_u(&mut self, i: usize, u: f32) {
self.u[i] = u;
}
fn set_v(&mut self, i: usize, v: f32) {
self.v[i] = v;
}
fn prim_id(&self, i: usize) -> u32 {
self.primID[i]
}
fn set_prim_id(&mut self, i: usize, id: u32) {
self.primID[i] = id;
}
fn geom_id(&self, i: usize) -> u32 {
self.geomID[i]
}
fn set_geom_id(&mut self, i: usize, id: u32) {
self.geomID[i] = id;
}
fn inst_id(&self, i: usize) -> u32 {
self.instID[0][i]
}
fn set_inst_id(&mut self, i: usize, id: u32) {
self.instID[0][i] = id;
}
}
impl RayHit4 {
pub fn new(ray: Ray4) -> RayHit4 {
sys::RTCRayHit4 {
ray: ray,
hit: Hit4::new(),
}
}
pub fn iter(&self) -> std::iter::Zip<SoARayIter<Ray4>, SoAHitIter<Hit4>> {
self.ray.iter().zip(self.hit.iter())
}
}
|
//! HAL for the STM32L0X3 family of microcontrollers
#![no_std]
pub use stm32l0x3;
pub mod exti;
pub mod flash;
pub mod gpio;
pub mod i2c;
pub mod lpusart;
pub mod prelude;
pub mod rcc;
pub mod time;
|
fn main() {
let t1 = ("tuple1", 1);
println!("{:?}", t1);
match t1 {
(_, v) => println!("{}", v)
}
let t2 = DataTuple("tuple2", 2);
println!("{:?}", t2);
match t2 {
DataTuple(s, _) => println!("{}", s)
}
}
#[derive(Debug)]
struct DataTuple(&'static str, i32);
|
// Copyright 2020 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::cell::RefCell;
use std::collections::HashMap;
use databend_meta::configs::Config as MetaConfig;
use databend_query::configs::Config as QueryConfig;
use tempfile::tempdir;
use crate::cmds::config::GithubMirror;
use crate::cmds::config::MirrorAsset;
use crate::cmds::status::LocalMetaConfig;
use crate::cmds::status::LocalQueryConfig;
use crate::cmds::Config;
use crate::cmds::Status;
use crate::error::Result;
#[test]
fn test_status() -> Result<()> {
let mut conf = Config {
group: "foo".to_string(),
databend_dir: "/tmp/.databend".to_string(),
mirror: GithubMirror {}.to_mirror(),
clap: RefCell::new(Default::default()),
};
let t = tempdir()?;
conf.databend_dir = t.path().to_str().unwrap().to_string();
// empty profile
{
let mut status = Status::read(conf.clone())?;
status.version = "xx".to_string();
status.write()?;
// should have empty profile with set version
if let Ok(status) = Status::read(conf.clone()) {
assert_eq!(status.version, "xx".to_string());
assert_eq!(status.local_configs, HashMap::new());
}
}
// create basic local profile
{
let mut status = Status::read(conf.clone())?;
status.version = "default".to_string();
status.local_configs = HashMap::new();
status.write()?;
// should have empty profile with set version
if let Ok(status) = Status::read(conf.clone()) {
assert_eq!(status.version, "default".to_string());
assert_eq!(status.local_configs, HashMap::new());
}
}
// update query component on local
{
let mut status = Status::read(conf.clone())?;
let query_config = LocalQueryConfig {
config: QueryConfig::default(),
pid: Some(123),
path: None,
log_dir: Some("./".to_string()),
};
Status::save_local_config(
&mut status,
"query".parse().unwrap(),
"query_1.yaml".to_string(),
&query_config,
)
.unwrap();
status.version = "default".to_string();
status.write()?;
let mut status = Status::read(conf.clone()).unwrap();
assert_eq!(status.version, "default");
assert_eq!(status.get_local_query_configs().len(), 1);
assert_eq!(
status.get_local_query_configs().get(0).unwrap().clone().1,
query_config.clone()
);
assert!(status.has_local_configs());
let meta_config = LocalMetaConfig {
config: MetaConfig::empty(),
pid: Some(123),
path: Some("String".to_string()),
log_dir: Some("dir".to_string()),
};
Status::save_local_config(
&mut status,
"meta".parse().unwrap(),
"meta_1.yaml".to_string(),
&meta_config,
)
.unwrap();
let query_config2 = LocalQueryConfig {
config: QueryConfig::default(),
pid: None,
path: None,
log_dir: None,
};
Status::save_local_config(
&mut status,
"query".parse().unwrap(),
"query_2.yaml".to_string(),
&query_config2,
)
.unwrap();
status.current_profile = Some("local".to_string());
status.write()?;
let status = Status::read(conf.clone()).unwrap();
assert_eq!(status.version, "default");
assert_eq!(status.get_local_query_configs().len(), 2);
assert_eq!(
status.get_local_query_configs().get(0).unwrap().clone().1,
query_config
);
assert_eq!(
status.get_local_query_configs().get(1).unwrap().clone().1,
query_config2
);
assert_eq!(status.get_local_meta_config().unwrap().1, meta_config);
assert_eq!(status.current_profile, Some("local".to_string()));
assert!(status.has_local_configs());
// delete status
let mut status = Status::read(conf.clone()).unwrap();
let (fs, _) = status.clone().get_local_meta_config().unwrap();
Status::delete_local_config(&mut status, "meta".to_string(), fs).unwrap();
for (fs, _) in status.clone().get_local_query_configs() {
Status::delete_local_config(&mut status, "query".to_string(), fs).unwrap();
}
status.current_profile = None;
status.write()?;
let status = Status::read(conf).unwrap();
assert_eq!(status.get_local_query_configs().len(), 0);
assert_eq!(status.get_local_meta_config(), None);
assert_eq!(status.current_profile, None);
assert!(!status.has_local_configs());
}
Ok(())
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::sync::Arc;
use spin::Mutex;
use core::ops::Deref;
use core::cmp::*;
use super::super::uid::NewUID;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::SignalDef::*;
use super::thread_group::*;
use super::session::*;
use super::thread::*;
use super::refcounter::*;
#[derive(Default)]
pub struct ProcessGroupInternal {
// id is the cached identifier in the originator's namespace.
//
// The id is immutable.
pub id: ProcessGroupID,
pub refs: AtomicRefCount,
// originator is the originator of the group.
//
// See note re: leader in Session. The same applies here.
//
// The originator is immutable.
pub originator: ThreadGroup,
// Session is the parent Session.
//
// The session is immutable.
pub session: Session,
// ancestors is the number of thread groups in this process group whose
// parent is in a different process group in the same session.
//
// The name is derived from the fact that process groups where
// ancestors is zero are considered "orphans".
//
// ancestors is protected by TaskSet.mu.
pub ancestors: u32,
}
#[derive(Clone, Default)]
pub struct ProcessGroup {
pub uid: UniqueID,
pub data: Arc<Mutex<ProcessGroupInternal>>
}
impl Deref for ProcessGroup {
type Target = Arc<Mutex<ProcessGroupInternal>>;
fn deref(&self) -> &Arc<Mutex<ProcessGroupInternal>> {
&self.data
}
}
impl Ord for ProcessGroup {
fn cmp(&self, other: &Self) -> Ordering {
let id1 = self.uid;
let id2 = other.uid;
id1.cmp(&id2)
}
}
impl PartialOrd for ProcessGroup {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for ProcessGroup {
fn eq(&self, other: &Self) -> bool {
return self.Uid() == other.Uid()
}
}
impl Eq for ProcessGroup {}
impl ProcessGroup {
pub fn Uid(&self) -> UniqueID {
return self.uid
}
pub fn New(id: ProcessGroupID, orginator: ThreadGroup, session: Session) -> Self {
let pg = ProcessGroupInternal {
id: id,
refs: AtomicRefCount::default(),
originator: orginator,
session: session,
ancestors: 0,
};
return Self {
uid: NewUID(),
data: Arc::new(Mutex::new(pg)),
}
}
pub fn Originator(&self) -> ThreadGroup {
return self.lock().originator.clone();
}
pub fn IsOrphan(&self) -> bool {
let taskSet = self.Originator().TaskSet();
let _r = taskSet.ReadLock();
return self.lock().ancestors == 0;
}
pub fn incRefWithParent(&self, parentPG: Option<ProcessGroup>) {
let add = if Some(self.clone()) != parentPG {
match parentPG {
None => true,
Some(ppg) => {
let sid = self.lock().session.uid;
let psid = ppg.lock().session.uid;
sid == psid
}
}
} else {
false
};
if add {
self.lock().ancestors += 1;
}
self.lock().refs.IncRef();
}
pub fn decRefWithParent(&self, parentPG: Option<ProcessGroup>) {
let ok = if Some(self.clone()) != parentPG {
match parentPG {
None => true,
Some(ppg) => {
let sid = self.lock().session.uid;
let psid = ppg.lock().session.uid;
sid == psid
}
}
} else {
false
};
if ok {
// if this pg was parentPg. But after reparent become non-parentpg. the ancestor will be sub to negtive
// todo: this is bug. fix it.
let ancestors = self.lock().ancestors;
if ancestors > 0 {
self.lock().ancestors = ancestors - 1;
}
}
let mut alive = true;
let originator = self.lock().originator.clone();
let mut needRemove = false;
self.lock().refs.DecRefWithDesctructor(|| {
needRemove = true;
});
if needRemove {
alive = false;
let mut ns = originator.PIDNamespace();
loop {
{
let mut nslock = ns.lock();
let id = match nslock.pgids.get(self) {
None => 0,
Some(id) => {
*id
}
};
nslock.processGroups.remove(&id);
nslock.pgids.remove(self);
}
let tmp = match ns.lock().parent {
None => break,
Some(ref ns) => ns.clone(),
};
ns = tmp;
}
}
if alive {
self.handleOrphan();
};
}
// handleOrphan checks whether the process group is an orphan and has any
// stopped jobs. If yes, then appropriate signals are delivered to each thread
// group within the process group.
//
// Precondition: callers must hold TaskSet.mu for writing.
pub fn handleOrphan(&self) {
if self.lock().ancestors != 0 {
return;
}
let mut hasStopped = false;
let originator = self.lock().originator.clone();
let pidns = originator.PIDNamespace();
let owner = pidns.lock().owner.clone();
owner.forEachThreadGroupLocked(|tg: &ThreadGroup| {
match tg.lock().processGroup.clone() {
None => return,
Some(pg) => {
if pg != self.clone() {
return
}
}
}
{
let lock = tg.lock().signalLock.clone();
let _s = lock.lock();
if tg.lock().groupStopComplete {
hasStopped = true;
}
}
});
if !hasStopped {
return
}
owner.forEachThreadGroupLocked(|tg: &ThreadGroup| {
match tg.lock().processGroup.clone() {
None => return,
Some(pg) => {
if pg != self.clone() {
return
}
}
}
{
let lock = tg.lock().signalLock.clone();
let _s = lock.lock();
let leader = tg.lock().leader.Upgrade().unwrap();
leader.sendSignalLocked(&SignalInfoPriv(Signal::SIGHUP), true).unwrap();
leader.sendSignalLocked(&SignalInfoPriv(Signal::SIGCONT), true).unwrap();
}
});
}
pub fn Session(&self) -> Session {
return self.lock().session.clone();
}
pub fn SendSignal(&self, info: &SignalInfo) -> Result<()> {
let ts = self.lock().originator.TaskSet();
let mut lastError: Result<()> = Ok(());
let rootns = ts.Root();
let _r = ts.ReadLock();
for (tg, _) in &rootns.lock().tgids {
if tg.ProcessGroup() == Some(self.clone()) {
let lock = tg.lock().signalLock.clone();
let _s = lock.lock();
let leader = tg.lock().leader.Upgrade().unwrap();
let infoCopy = *info;
match leader.sendSignalLocked(&infoCopy, true) {
Err(e) => lastError = Err(e),
_ => ()
};
}
}
return lastError
}
}
|
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]
// Due to `schema_introspection` test.
#![cfg_attr(test, recursion_limit = "256")]
#![warn(missing_docs)]
// Required for using `juniper_codegen` macros inside this crate to resolve
// absolute `::juniper` path correctly, without errors.
extern crate core;
extern crate self as juniper;
use std::fmt;
// These are required by the code generated via the `juniper_codegen` macros.
#[doc(hidden)]
pub use {async_trait::async_trait, futures, serde, static_assertions as sa};
#[doc(inline)]
pub use futures::future::{BoxFuture, LocalBoxFuture};
// Depend on juniper_codegen and re-export everything in it.
// This allows users to just depend on juniper and get the derive
// functionality automatically.
pub use juniper_codegen::{
graphql_interface, graphql_object, graphql_scalar, graphql_subscription, graphql_union,
GraphQLEnum, GraphQLInputObject, GraphQLInterface, GraphQLObject, GraphQLScalar, GraphQLUnion,
};
#[doc(hidden)]
#[macro_use]
pub mod macros;
mod ast;
pub mod executor;
mod introspection;
pub mod parser;
pub(crate) mod schema;
mod types;
mod util;
pub mod validation;
mod value;
// This needs to be public until docs have support for private modules:
// https://github.com/rust-lang/cargo/issues/1520
pub mod http;
pub mod integrations;
#[cfg(all(test, not(feature = "expose-test-schema")))]
mod tests;
#[cfg(feature = "expose-test-schema")]
pub mod tests;
#[cfg(test)]
mod executor_tests;
// Needs to be public because macros use it.
pub use crate::util::to_camel_case;
use crate::{
executor::{execute_validated_query, get_operation},
introspection::{INTROSPECTION_QUERY, INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS},
parser::parse_document_source,
validation::{validate_input_values, visit_all_rules, ValidatorContext},
};
pub use crate::{
ast::{
Definition, Document, FromInputValue, InputValue, Operation, OperationType, Selection,
ToInputValue, Type,
},
executor::{
Applies, Context, ExecutionError, ExecutionResult, Executor, FieldError, FieldResult,
FromContext, IntoFieldError, IntoResolvable, LookAheadArgument, LookAheadMethods,
LookAheadSelection, LookAheadValue, OwnedExecutor, Registry, ValuesStream, Variables,
},
introspection::IntrospectionFormat,
macros::helper::subscription::{ExtractTypeFromStream, IntoFieldResult},
parser::{ParseError, ScalarToken, Spanning},
schema::{
meta,
model::{RootNode, SchemaType},
},
types::{
async_await::{GraphQLTypeAsync, GraphQLValueAsync},
base::{Arguments, GraphQLType, GraphQLValue, TypeKind},
marker::{self, GraphQLInterface, GraphQLObject, GraphQLUnion},
nullable::Nullable,
scalars::{EmptyMutation, EmptySubscription, ID},
subscriptions::{
ExecutionOutput, GraphQLSubscriptionType, GraphQLSubscriptionValue,
SubscriptionConnection, SubscriptionCoordinator,
},
},
validation::RuleError,
value::{DefaultScalarValue, Object, ParseScalarResult, ParseScalarValue, ScalarValue, Value},
};
/// An error that prevented query execution
#[allow(missing_docs)]
#[derive(Debug, Eq, PartialEq)]
pub enum GraphQLError {
ParseError(Spanning<ParseError>),
ValidationError(Vec<RuleError>),
NoOperationProvided,
MultipleOperationsProvided,
UnknownOperationName,
IsSubscription,
NotSubscription,
}
impl fmt::Display for GraphQLError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ParseError(e) => write!(f, "{e}"),
Self::ValidationError(errs) => {
for e in errs {
writeln!(f, "{e}")?;
}
Ok(())
}
Self::NoOperationProvided => write!(f, "No operation provided"),
Self::MultipleOperationsProvided => write!(f, "Multiple operations provided"),
Self::UnknownOperationName => write!(f, "Unknown operation name"),
Self::IsSubscription => write!(f, "Operation is a subscription"),
Self::NotSubscription => write!(f, "Operation is not a subscription"),
}
}
}
impl std::error::Error for GraphQLError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::ParseError(e) => Some(e),
Self::ValidationError(errs) => Some(errs.first()?),
Self::NoOperationProvided
| Self::MultipleOperationsProvided
| Self::UnknownOperationName
| Self::IsSubscription
| Self::NotSubscription => None,
}
}
}
/// Execute a query synchronously in a provided schema
pub fn execute_sync<'a, S, QueryT, MutationT, SubscriptionT>(
document_source: &'a str,
operation_name: Option<&str>,
root_node: &'a RootNode<QueryT, MutationT, SubscriptionT, S>,
variables: &Variables<S>,
context: &QueryT::Context,
) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError>
where
S: ScalarValue,
QueryT: GraphQLType<S>,
MutationT: GraphQLType<S, Context = QueryT::Context>,
SubscriptionT: GraphQLType<S, Context = QueryT::Context>,
{
let document = parse_document_source(document_source, &root_node.schema)?;
{
let mut ctx = ValidatorContext::new(&root_node.schema, &document);
visit_all_rules(&mut ctx, &document);
let errors = ctx.into_errors();
if !errors.is_empty() {
return Err(GraphQLError::ValidationError(errors));
}
}
let operation = get_operation(&document, operation_name)?;
{
let errors = validate_input_values(variables, operation, &root_node.schema);
if !errors.is_empty() {
return Err(GraphQLError::ValidationError(errors));
}
}
execute_validated_query(&document, operation, root_node, variables, context)
}
/// Execute a query in a provided schema
pub async fn execute<'a, S, QueryT, MutationT, SubscriptionT>(
document_source: &'a str,
operation_name: Option<&str>,
root_node: &'a RootNode<'a, QueryT, MutationT, SubscriptionT, S>,
variables: &Variables<S>,
context: &QueryT::Context,
) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError>
where
QueryT: GraphQLTypeAsync<S>,
QueryT::TypeInfo: Sync,
QueryT::Context: Sync,
MutationT: GraphQLTypeAsync<S, Context = QueryT::Context>,
MutationT::TypeInfo: Sync,
SubscriptionT: GraphQLType<S, Context = QueryT::Context> + Sync,
SubscriptionT::TypeInfo: Sync,
S: ScalarValue + Send + Sync,
{
let document = parse_document_source(document_source, &root_node.schema)?;
{
let mut ctx = ValidatorContext::new(&root_node.schema, &document);
visit_all_rules(&mut ctx, &document);
let errors = ctx.into_errors();
if !errors.is_empty() {
return Err(GraphQLError::ValidationError(errors));
}
}
let operation = get_operation(&document, operation_name)?;
{
let errors = validate_input_values(variables, operation, &root_node.schema);
if !errors.is_empty() {
return Err(GraphQLError::ValidationError(errors));
}
}
executor::execute_validated_query_async(&document, operation, root_node, variables, context)
.await
}
/// Resolve subscription into `ValuesStream`
pub async fn resolve_into_stream<'a, S, QueryT, MutationT, SubscriptionT>(
document_source: &'a str,
operation_name: Option<&str>,
root_node: &'a RootNode<'a, QueryT, MutationT, SubscriptionT, S>,
variables: &Variables<S>,
context: &'a QueryT::Context,
) -> Result<(Value<ValuesStream<'a, S>>, Vec<ExecutionError<S>>), GraphQLError>
where
QueryT: GraphQLTypeAsync<S>,
QueryT::TypeInfo: Sync,
QueryT::Context: Sync,
MutationT: GraphQLTypeAsync<S, Context = QueryT::Context>,
MutationT::TypeInfo: Sync,
SubscriptionT: GraphQLSubscriptionType<S, Context = QueryT::Context>,
SubscriptionT::TypeInfo: Sync,
S: ScalarValue + Send + Sync,
{
let document: crate::ast::OwnedDocument<'a, S> =
parse_document_source(document_source, &root_node.schema)?;
{
let mut ctx = ValidatorContext::new(&root_node.schema, &document);
visit_all_rules(&mut ctx, &document);
let errors = ctx.into_errors();
if !errors.is_empty() {
return Err(GraphQLError::ValidationError(errors));
}
}
let operation = get_operation(&document, operation_name)?;
{
let errors = validate_input_values(variables, operation, &root_node.schema);
if !errors.is_empty() {
return Err(GraphQLError::ValidationError(errors));
}
}
executor::resolve_validated_subscription(&document, operation, root_node, variables, context)
.await
}
/// Execute the reference introspection query in the provided schema
pub fn introspect<S, QueryT, MutationT, SubscriptionT>(
root_node: &RootNode<QueryT, MutationT, SubscriptionT, S>,
context: &QueryT::Context,
format: IntrospectionFormat,
) -> Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError>
where
S: ScalarValue,
QueryT: GraphQLType<S>,
MutationT: GraphQLType<S, Context = QueryT::Context>,
SubscriptionT: GraphQLType<S, Context = QueryT::Context>,
{
execute_sync(
match format {
IntrospectionFormat::All => INTROSPECTION_QUERY,
IntrospectionFormat::WithoutDescriptions => INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS,
},
None,
root_node,
&Variables::new(),
context,
)
}
impl From<Spanning<ParseError>> for GraphQLError {
fn from(err: Spanning<ParseError>) -> Self {
Self::ParseError(err)
}
}
|
//! Linux [io_uring].
//!
//! This API is very low-level. The main adaptations it makes from the raw
//! Linux io_uring API are the use of appropriately-sized `bitflags`, `enum`,
//! `Result`, `OwnedFd`, `AsFd`, `RawFd`, and `*mut c_void` in place of plain
//! integers.
//!
//! For a higher-level API built on top of this, see the [rustix-uring] crate.
//!
//! # Safety
//!
//! io_uring operates on raw pointers and raw file descriptors. Rustix does not
//! attempt to provide a safe API for these, because the abstraction level is
//! too low for this to be practical. Safety should be introduced in
//! higher-level abstraction layers.
//!
//! # References
//! - [Linux]
//! - [io_uring header]
//!
//! [Linux]: https://man.archlinux.org/man/io_uring.7.en
//! [io_uring]: https://en.wikipedia.org/wiki/Io_uring
//! [io_uring header]: https://github.com/torvalds/linux/blob/master/include/uapi/linux/io_uring.h
//! [rustix-uring]: https://crates.io/crates/rustix-uring
#![allow(unsafe_code)]
use crate::fd::{AsFd, BorrowedFd, OwnedFd, RawFd};
use crate::{backend, io};
use core::ffi::c_void;
use core::mem::{zeroed, MaybeUninit};
use core::ptr::{null_mut, write_bytes};
use linux_raw_sys::net;
mod sys {
pub(super) use linux_raw_sys::io_uring::*;
#[cfg(test)]
pub(super) use {crate::backend::c::iovec, linux_raw_sys::general::open_how};
}
/// `io_uring_setup(entries, params)`—Setup a context for performing
/// asynchronous I/O.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man.archlinux.org/man/io_uring_setup.2.en
#[inline]
pub fn io_uring_setup(entries: u32, params: &mut io_uring_params) -> io::Result<OwnedFd> {
backend::io_uring::syscalls::io_uring_setup(entries, params)
}
/// `io_uring_register(fd, opcode, arg, nr_args)`—Register files or user
/// buffers for asynchronous I/O.
///
/// # Safety
///
/// io_uring operates on raw pointers and raw file descriptors. Users are
/// responsible for ensuring that memory and resources are only accessed in
/// valid ways.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man.archlinux.org/man/io_uring_register.2.en
#[inline]
pub unsafe fn io_uring_register<Fd: AsFd>(
fd: Fd,
opcode: IoringRegisterOp,
arg: *const c_void,
nr_args: u32,
) -> io::Result<u32> {
backend::io_uring::syscalls::io_uring_register(fd.as_fd(), opcode, arg, nr_args)
}
/// `io_uring_enter(fd, to_submit, min_complete, flags, arg, size)`—Initiate
/// and/or complete asynchronous I/O.
///
/// # Safety
///
/// io_uring operates on raw pointers and raw file descriptors. Users are
/// responsible for ensuring that memory and resources are only accessed in
/// valid ways.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man.archlinux.org/man/io_uring_enter.2.en
#[inline]
pub unsafe fn io_uring_enter<Fd: AsFd>(
fd: Fd,
to_submit: u32,
min_complete: u32,
flags: IoringEnterFlags,
arg: *const c_void,
size: usize,
) -> io::Result<u32> {
backend::io_uring::syscalls::io_uring_enter(
fd.as_fd(),
to_submit,
min_complete,
flags,
arg,
size,
)
}
bitflags::bitflags! {
/// `IORING_ENTER_*` flags for use with [`io_uring_enter`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringEnterFlags: u32 {
/// `IORING_ENTER_GETEVENTS`
const GETEVENTS = sys::IORING_ENTER_GETEVENTS;
/// `IORING_ENTER_SQ_WAKEUP`
const SQ_WAKEUP = sys::IORING_ENTER_SQ_WAKEUP;
/// `IORING_ENTER_SQ_WAIT`
const SQ_WAIT = sys::IORING_ENTER_SQ_WAIT;
/// `IORING_ENTER_EXT_ARG`
const EXT_ARG = sys::IORING_ENTER_EXT_ARG;
}
}
/// `IORING_REGISTER_*` and `IORING_UNREGISTER_*` constants for use with
/// [`io_uring_register`].
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum IoringRegisterOp {
/// `IORING_REGISTER_BUFFERS`
RegisterBuffers = sys::IORING_REGISTER_BUFFERS as _,
/// `IORING_UNREGISTER_BUFFERS`
UnregisterBuffers = sys::IORING_UNREGISTER_BUFFERS as _,
/// `IORING_REGISTER_FILES`
RegisterFiles = sys::IORING_REGISTER_FILES as _,
/// `IORING_UNREGISTER_FILES`
UnregisterFiles = sys::IORING_UNREGISTER_FILES as _,
/// `IORING_REGISTER_EVENTFD`
RegisterEventfd = sys::IORING_REGISTER_EVENTFD as _,
/// `IORING_UNREGISTER_EVENTFD`
UnregisterEventfd = sys::IORING_UNREGISTER_EVENTFD as _,
/// `IORING_REGISTER_FILES_UPDATE`
RegisterFilesUpdate = sys::IORING_REGISTER_FILES_UPDATE as _,
/// `IORING_REGISTER_EVENTFD_ASYNC`
RegisterEventfdAsync = sys::IORING_REGISTER_EVENTFD_ASYNC as _,
/// `IORING_REGISTER_PROBE`
RegisterProbe = sys::IORING_REGISTER_PROBE as _,
/// `IORING_REGISTER_PERSONALITY`
RegisterPersonality = sys::IORING_REGISTER_PERSONALITY as _,
/// `IORING_UNREGISTER_PERSONALITY`
UnregisterPersonality = sys::IORING_UNREGISTER_PERSONALITY as _,
/// `IORING_REGISTER_RESTRICTIONS`
RegisterRestrictions = sys::IORING_REGISTER_RESTRICTIONS as _,
/// `IORING_REGISTER_ENABLE_RINGS`
RegisterEnableRings = sys::IORING_REGISTER_ENABLE_RINGS as _,
/// `IORING_REGISTER_BUFFERS2`
RegisterBuffers2 = sys::IORING_REGISTER_BUFFERS2 as _,
/// `IORING_REGISTER_BUFFERS_UPDATE`
RegisterBuffersUpdate = sys::IORING_REGISTER_BUFFERS_UPDATE as _,
/// `IORING_REGISTER_FILES2`
RegisterFiles2 = sys::IORING_REGISTER_FILES2 as _,
/// `IORING_REGISTER_FILES_SKIP`
RegisterFilesSkip = sys::IORING_REGISTER_FILES_SKIP as _,
/// `IORING_REGISTER_FILES_UPDATE2`
RegisterFilesUpdate2 = sys::IORING_REGISTER_FILES_UPDATE2 as _,
/// `IORING_REGISTER_IOWQ_AFF`
RegisterIowqAff = sys::IORING_REGISTER_IOWQ_AFF as _,
/// `IORING_UNREGISTER_IOWQ_AFF`
UnregisterIowqAff = sys::IORING_UNREGISTER_IOWQ_AFF as _,
/// `IORING_REGISTER_IOWQ_MAX_WORKERS`
RegisterIowqMaxWorkers = sys::IORING_REGISTER_IOWQ_MAX_WORKERS as _,
/// `IORING_REGISTER_RING_FDS`
RegisterRingFds = sys::IORING_REGISTER_RING_FDS as _,
/// `IORING_UNREGISTER_RING_FDS`
UnregisterRingFds = sys::IORING_UNREGISTER_RING_FDS as _,
/// `IORING_REGISTER_PBUF_RING`
RegisterPbufRing = sys::IORING_REGISTER_PBUF_RING as _,
/// `IORING_UNREGISTER_PBUF_RING`
UnregisterPbufRing = sys::IORING_UNREGISTER_PBUF_RING as _,
/// `IORING_REGISTER_SYNC_CANCEL`
RegisterSyncCancel = sys::IORING_REGISTER_SYNC_CANCEL as _,
/// `IORING_REGISTER_FILE_ALLOC_RANGE`
RegisterFileAllocRange = sys::IORING_REGISTER_FILE_ALLOC_RANGE as _,
}
/// `IORING_OP_*` constants for use with [`io_uring_sqe`].
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum IoringOp {
/// `IORING_OP_NOP`
Nop = sys::io_uring_op::IORING_OP_NOP as _,
/// `IORING_OP_ACCEPT`
Accept = sys::io_uring_op::IORING_OP_ACCEPT as _,
/// `IORING_OP_ASYNC_CANCEL`
AsyncCancel = sys::io_uring_op::IORING_OP_ASYNC_CANCEL as _,
/// `IORING_OP_CLOSE`
Close = sys::io_uring_op::IORING_OP_CLOSE as _,
/// `IORING_OP_CONNECT`
Connect = sys::io_uring_op::IORING_OP_CONNECT as _,
/// `IORING_OP_EPOLL_CTL`
EpollCtl = sys::io_uring_op::IORING_OP_EPOLL_CTL as _,
/// `IORING_OP_FADVISE`
Fadvise = sys::io_uring_op::IORING_OP_FADVISE as _,
/// `IORING_OP_FALLOCATE`
Fallocate = sys::io_uring_op::IORING_OP_FALLOCATE as _,
/// `IORING_OP_FILES_UPDATE`
FilesUpdate = sys::io_uring_op::IORING_OP_FILES_UPDATE as _,
/// `IORING_OP_FSYNC`
Fsync = sys::io_uring_op::IORING_OP_FSYNC as _,
/// `IORING_OP_LINKAT`
Linkat = sys::io_uring_op::IORING_OP_LINKAT as _,
/// `IORING_OP_LINK_TIMEOUT`
LinkTimeout = sys::io_uring_op::IORING_OP_LINK_TIMEOUT as _,
/// `IORING_OP_MADVISE`
Madvise = sys::io_uring_op::IORING_OP_MADVISE as _,
/// `IORING_OP_MKDIRAT`
Mkdirat = sys::io_uring_op::IORING_OP_MKDIRAT as _,
/// `IORING_OP_OPENAT`
Openat = sys::io_uring_op::IORING_OP_OPENAT as _,
/// `IORING_OP_OPENAT2`
Openat2 = sys::io_uring_op::IORING_OP_OPENAT2 as _,
/// `IORING_OP_POLL_ADD`
PollAdd = sys::io_uring_op::IORING_OP_POLL_ADD as _,
/// `IORING_OP_POLL_REMOVE`
PollRemove = sys::io_uring_op::IORING_OP_POLL_REMOVE as _,
/// `IORING_OP_PROVIDE_BUFFERS`
ProvideBuffers = sys::io_uring_op::IORING_OP_PROVIDE_BUFFERS as _,
/// `IORING_OP_READ`
Read = sys::io_uring_op::IORING_OP_READ as _,
/// `IORING_OP_READV`
Readv = sys::io_uring_op::IORING_OP_READV as _,
/// `IORING_OP_READ_FIXED`
ReadFixed = sys::io_uring_op::IORING_OP_READ_FIXED as _,
/// `IORING_OP_RECV`
Recv = sys::io_uring_op::IORING_OP_RECV as _,
/// `IORING_OP_RECVMSG`
Recvmsg = sys::io_uring_op::IORING_OP_RECVMSG as _,
/// `IORING_OP_REMOVE_BUFFERS`
RemoveBuffers = sys::io_uring_op::IORING_OP_REMOVE_BUFFERS as _,
/// `IORING_OP_RENAMEAT`
Renameat = sys::io_uring_op::IORING_OP_RENAMEAT as _,
/// `IORING_OP_SEND`
Send = sys::io_uring_op::IORING_OP_SEND as _,
/// `IORING_OP_SENDMSG`
Sendmsg = sys::io_uring_op::IORING_OP_SENDMSG as _,
/// `IORING_OP_SHUTDOWN`
Shutdown = sys::io_uring_op::IORING_OP_SHUTDOWN as _,
/// `IORING_OP_SPLICE`
Splice = sys::io_uring_op::IORING_OP_SPLICE as _,
/// `IORING_OP_STATX`
Statx = sys::io_uring_op::IORING_OP_STATX as _,
/// `IORING_OP_SYMLINKAT`
Symlinkat = sys::io_uring_op::IORING_OP_SYMLINKAT as _,
/// `IORING_OP_SYNC_FILE_RANGE`
SyncFileRange = sys::io_uring_op::IORING_OP_SYNC_FILE_RANGE as _,
/// `IORING_OP_TEE`
Tee = sys::io_uring_op::IORING_OP_TEE as _,
/// `IORING_OP_TIMEOUT`
Timeout = sys::io_uring_op::IORING_OP_TIMEOUT as _,
/// `IORING_OP_TIMEOUT_REMOVE`
TimeoutRemove = sys::io_uring_op::IORING_OP_TIMEOUT_REMOVE as _,
/// `IORING_OP_UNLINKAT`
Unlinkat = sys::io_uring_op::IORING_OP_UNLINKAT as _,
/// `IORING_OP_WRITE`
Write = sys::io_uring_op::IORING_OP_WRITE as _,
/// `IORING_OP_WRITEV`
Writev = sys::io_uring_op::IORING_OP_WRITEV as _,
/// `IORING_OP_WRITE_FIXED`
WriteFixed = sys::io_uring_op::IORING_OP_WRITE_FIXED as _,
/// `IORING_OP_MSG_RING`
MsgRing = sys::io_uring_op::IORING_OP_MSG_RING as _,
/// `IORING_OP_FSETXATTR`
Fsetxattr = sys::io_uring_op::IORING_OP_FSETXATTR as _,
/// `IORING_OP_SETXATTR`
Setxattr = sys::io_uring_op::IORING_OP_SETXATTR as _,
/// `IORING_OP_FGETXATTR`
Fgetxattr = sys::io_uring_op::IORING_OP_FGETXATTR as _,
/// `IORING_OP_GETXATTR`
Getxattr = sys::io_uring_op::IORING_OP_GETXATTR as _,
/// `IORING_OP_SOCKET`
Socket = sys::io_uring_op::IORING_OP_SOCKET as _,
/// `IORING_OP_URING_CMD`
UringCmd = sys::io_uring_op::IORING_OP_URING_CMD as _,
/// `IORING_OP_SEND_ZC`
SendZc = sys::io_uring_op::IORING_OP_SEND_ZC as _,
/// `IORING_OP_SENDMSG_ZC`
SendmsgZc = sys::io_uring_op::IORING_OP_SENDMSG_ZC as _,
}
impl Default for IoringOp {
#[inline]
fn default() -> Self {
Self::Nop
}
}
/// `IORING_RESTRICTION_*` constants for use with [`io_uring_restriction`].
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[repr(u16)]
#[non_exhaustive]
pub enum IoringRestrictionOp {
/// `IORING_RESTRICTION_REGISTER_OP`
RegisterOp = sys::IORING_RESTRICTION_REGISTER_OP as _,
/// `IORING_RESTRICTION_SQE_FLAGS_ALLOWED`
SqeFlagsAllowed = sys::IORING_RESTRICTION_SQE_FLAGS_ALLOWED as _,
/// `IORING_RESTRICTION_SQE_FLAGS_REQUIRED`
SqeFlagsRequired = sys::IORING_RESTRICTION_SQE_FLAGS_REQUIRED as _,
/// `IORING_RESTRICTION_SQE_OP`
SqeOp = sys::IORING_RESTRICTION_SQE_OP as _,
}
impl Default for IoringRestrictionOp {
#[inline]
fn default() -> Self {
Self::RegisterOp
}
}
/// `IORING_MSG_*` constants which represent commands for use with
/// [`IoringOp::MsgRing`], (`seq.addr`)
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[repr(u64)]
#[non_exhaustive]
pub enum IoringMsgringCmds {
/// `IORING_MSG_DATA`
Data = sys::IORING_MSG_DATA as _,
/// `IORING_MSG_SEND_FD`
SendFd = sys::IORING_MSG_SEND_FD as _,
}
bitflags::bitflags! {
/// `IORING_SETUP_*` flags for use with [`io_uring_params`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringSetupFlags: u32 {
/// `IORING_SETUP_ATTACH_WQ`
const ATTACH_WQ = sys::IORING_SETUP_ATTACH_WQ;
/// `IORING_SETUP_CLAMP`
const CLAMP = sys::IORING_SETUP_CLAMP;
/// `IORING_SETUP_CQSIZE`
const CQSIZE = sys::IORING_SETUP_CQSIZE;
/// `IORING_SETUP_IOPOLL`
const IOPOLL = sys::IORING_SETUP_IOPOLL;
/// `IORING_SETUP_R_DISABLED`
const R_DISABLED = sys::IORING_SETUP_R_DISABLED;
/// `IORING_SETUP_SQPOLL`
const SQPOLL = sys::IORING_SETUP_SQPOLL;
/// `IORING_SETUP_SQ_AFF`
const SQ_AFF = sys::IORING_SETUP_SQ_AFF;
/// `IORING_SETUP_SQE128`
const SQE128 = sys::IORING_SETUP_SQE128;
/// `IORING_SETUP_CQE32`
const CQE32 = sys::IORING_SETUP_CQE32;
/// `IORING_SETUP_SUBMIT_ALL`
const SUBMIT_ALL = sys::IORING_SETUP_SUBMIT_ALL;
/// `IORING_SETUP_COOP_TRASKRUN`
const COOP_TASKRUN = sys::IORING_SETUP_COOP_TASKRUN;
/// `IORING_SETUP_TASKRUN_FLAG`
const TASKRUN_FLAG = sys::IORING_SETUP_TASKRUN_FLAG;
/// `IORING_SETUP_SINGLE_ISSUER`
const SINGLE_ISSUER = sys::IORING_SETUP_SINGLE_ISSUER;
/// `IORING_SETUP_DEFER_TASKRUN`
const DEFER_TASKRUN = sys::IORING_SETUP_DEFER_TASKRUN;
}
}
bitflags::bitflags! {
/// `IOSQE_*` flags for use with [`io_uring_sqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringSqeFlags: u8 {
/// `1 << IOSQE_ASYNC_BIT`
const ASYNC = 1 << sys::IOSQE_ASYNC_BIT as u8;
/// `1 << IOSQE_BUFFER_SELECT_BIT`
const BUFFER_SELECT = 1 << sys::IOSQE_BUFFER_SELECT_BIT as u8;
/// `1 << IOSQE_FIXED_FILE_BIT`
const FIXED_FILE = 1 << sys::IOSQE_FIXED_FILE_BIT as u8;
/// 1 << `IOSQE_IO_DRAIN_BIT`
const IO_DRAIN = 1 << sys::IOSQE_IO_DRAIN_BIT as u8;
/// `1 << IOSQE_IO_HARDLINK_BIT`
const IO_HARDLINK = 1 << sys::IOSQE_IO_HARDLINK_BIT as u8;
/// `1 << IOSQE_IO_LINK_BIT`
const IO_LINK = 1 << sys::IOSQE_IO_LINK_BIT as u8;
/// `1 << IOSQE_CQE_SKIP_SUCCESS_BIT`
const CQE_SKIP_SUCCESS = 1 << sys::IOSQE_CQE_SKIP_SUCCESS_BIT as u8;
}
}
bitflags::bitflags! {
/// `IORING_CQE_F_*` flags for use with [`io_uring_cqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringCqeFlags: u32 {
/// `IORING_CQE_F_BUFFER`
const BUFFER = bitcast!(sys::IORING_CQE_F_BUFFER);
/// `IORING_CQE_F_MORE`
const MORE = bitcast!(sys::IORING_CQE_F_MORE);
/// `IORING_CQE_F_SOCK_NONEMPTY`
const SOCK_NONEMPTY = bitcast!(sys::IORING_CQE_F_SOCK_NONEMPTY);
/// `IORING_CQE_F_NOTIF`
const NOTIF = bitcast!(sys::IORING_CQE_F_NOTIF);
}
}
bitflags::bitflags! {
/// `IORING_FSYNC_*` flags for use with [`io_uring_sqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringFsyncFlags: u32 {
/// `IORING_FSYNC_DATASYNC`
const DATASYNC = sys::IORING_FSYNC_DATASYNC;
}
}
bitflags::bitflags! {
/// `IORING_TIMEOUT_*` and `IORING_LINK_TIMEOUT_UPDATE` flags for use with
/// [`io_uring_sqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringTimeoutFlags: u32 {
/// `IORING_TIMEOUT_ABS`
const ABS = sys::IORING_TIMEOUT_ABS;
/// `IORING_TIMEOUT_UPDATE`
const UPDATE = sys::IORING_TIMEOUT_UPDATE;
/// `IORING_TIMEOUT_BOOTTIME`
const BOOTTIME = sys::IORING_TIMEOUT_BOOTTIME;
/// `IORING_TIMEOUT_ETIME_SUCCESS`
const ETIME_SUCCESS = sys::IORING_TIMEOUT_ETIME_SUCCESS;
/// `IORING_TIMEOUT_REALTIME`
const REALTIME = sys::IORING_TIMEOUT_REALTIME;
/// `IORING_TIMEOUT_CLOCK_MASK`
const CLOCK_MASK = sys::IORING_TIMEOUT_CLOCK_MASK;
/// `IORING_TIMEOUT_UPDATE_MASK`
const UPDATE_MASK = sys::IORING_TIMEOUT_UPDATE_MASK;
/// `IORING_LINK_TIMEOUT_UPDATE`
const LINK_TIMEOUT_UPDATE = sys::IORING_LINK_TIMEOUT_UPDATE;
}
}
bitflags::bitflags! {
/// `SPLICE_F_*` flags for use with [`io_uring_sqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct SpliceFlags: u32 {
/// `SPLICE_F_FD_IN_FIXED`
const FD_IN_FIXED = sys::SPLICE_F_FD_IN_FIXED;
}
}
bitflags::bitflags! {
/// `IORING_MSG_RING_*` flags for use with [`io_uring_sqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringMsgringFlags: u32 {
/// `IORING_MSG_RING_CQE_SKIP`
const CQE_SKIP = sys::IORING_MSG_RING_CQE_SKIP;
}
}
bitflags::bitflags! {
/// `IORING_ASYNC_CANCEL_*` flags for use with [`io_uring_sqe`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringAsyncCancelFlags: u32 {
/// `IORING_ASYNC_CANCEL_ALL`
const ALL = sys::IORING_ASYNC_CANCEL_ALL;
/// `IORING_ASYNC_CANCEL_FD`
const FD = sys::IORING_ASYNC_CANCEL_FD;
/// `IORING_ASYNC_CANCEL_FD`
const ANY = sys::IORING_ASYNC_CANCEL_ANY;
/// `IORING_ASYNC_CANCEL_FD`
const FD_FIXED = sys::IORING_ASYNC_CANCEL_FD_FIXED;
}
}
bitflags::bitflags! {
/// `IORING_FEAT_*` flags for use with [`io_uring_params`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringFeatureFlags: u32 {
/// `IORING_FEAT_CQE_SKIP`
const CQE_SKIP = sys::IORING_FEAT_CQE_SKIP;
/// `IORING_FEAT_CUR_PERSONALITY`
const CUR_PERSONALITY = sys::IORING_FEAT_CUR_PERSONALITY;
/// `IORING_FEAT_EXT_ARG`
const EXT_ARG = sys::IORING_FEAT_EXT_ARG;
/// `IORING_FEAT_FAST_POLL`
const FAST_POLL = sys::IORING_FEAT_FAST_POLL;
/// `IORING_FEAT_NATIVE_WORKERS`
const NATIVE_WORKERS = sys::IORING_FEAT_NATIVE_WORKERS;
/// `IORING_FEAT_NODROP`
const NODROP = sys::IORING_FEAT_NODROP;
/// `IORING_FEAT_POLL_32BITS`
const POLL_32BITS = sys::IORING_FEAT_POLL_32BITS;
/// `IORING_FEAT_RSRC_TAGS`
const RSRC_TAGS = sys::IORING_FEAT_RSRC_TAGS;
/// `IORING_FEAT_RW_CUR_POS`
const RW_CUR_POS = sys::IORING_FEAT_RW_CUR_POS;
/// `IORING_FEAT_SINGLE_MMAP`
const SINGLE_MMAP = sys::IORING_FEAT_SINGLE_MMAP;
/// `IORING_FEAT_SQPOLL_NONFIXED`
const SQPOLL_NONFIXED = sys::IORING_FEAT_SQPOLL_NONFIXED;
/// `IORING_FEAT_SUBMIT_STABLE`
const SUBMIT_STABLE = sys::IORING_FEAT_SUBMIT_STABLE;
/// `IORING_FEAT_LINKED_FILE`
const LINKED_FILE = sys::IORING_FEAT_LINKED_FILE;
}
}
bitflags::bitflags! {
/// `IO_URING_OP_*` flags for use with [`io_uring_probe_op`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringOpFlags: u16 {
/// `IO_URING_OP_SUPPORTED`
const SUPPORTED = sys::IO_URING_OP_SUPPORTED as _;
}
}
bitflags::bitflags! {
/// `IORING_RSRC_*` flags for use with [`io_uring_rsrc_register`].
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringRsrcFlags: u32 {
/// `IORING_RSRC_REGISTER_SPARSE`
const REGISTER_SPARSE = sys::IORING_RSRC_REGISTER_SPARSE as _;
}
}
bitflags::bitflags! {
/// `IORING_SQ_*` flags.
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringSqFlags: u32 {
/// `IORING_SQ_NEED_WAKEUP`
const NEED_WAKEUP = sys::IORING_SQ_NEED_WAKEUP;
/// `IORING_SQ_CQ_OVERFLOW`
const CQ_OVERFLOW = sys::IORING_SQ_CQ_OVERFLOW;
/// `IORING_SQ_TASKRUN`
const TASKRUN = sys::IORING_SQ_TASKRUN;
}
}
bitflags::bitflags! {
/// `IORING_CQ_*` flags.
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringCqFlags: u32 {
/// `IORING_CQ_EVENTFD_DISABLED`
const EVENTFD_DISABLED = sys::IORING_CQ_EVENTFD_DISABLED;
}
}
bitflags::bitflags! {
/// `IORING_POLL_*` flags.
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringPollFlags: u32 {
/// `IORING_POLL_ADD_MULTI`
const ADD_MULTI = sys::IORING_POLL_ADD_MULTI;
/// `IORING_POLL_UPDATE_EVENTS`
const UPDATE_EVENTS = sys::IORING_POLL_UPDATE_EVENTS;
/// `IORING_POLL_UPDATE_USER_DATA`
const UPDATE_USER_DATA = sys::IORING_POLL_UPDATE_USER_DATA;
/// `IORING_POLL_ADD_LEVEL`
const ADD_LEVEL = sys::IORING_POLL_ADD_LEVEL;
}
}
bitflags::bitflags! {
/// send/sendmsg flags (`sqe.ioprio`)
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringSendFlags: u16 {
/// `IORING_RECVSEND_POLL_FIRST`.
///
/// See also [`IoringRecvFlags::POLL_FIRST`].
const POLL_FIRST = sys::IORING_RECVSEND_POLL_FIRST as _;
/// `IORING_RECVSEND_FIXED_BUF`
///
/// See also [`IoringRecvFlags::FIXED_BUF`].
const FIXED_BUF = sys::IORING_RECVSEND_FIXED_BUF as _;
/// `IORING_SEND_ZC_REPORT_USAGE` (since Linux 6.2)
const ZC_REPORT_USAGE = sys::IORING_SEND_ZC_REPORT_USAGE as _;
}
}
bitflags::bitflags! {
/// recv/recvmsg flags (`sqe.ioprio`)
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringRecvFlags: u16 {
/// `IORING_RECVSEND_POLL_FIRST`
///
/// See also [`IoringSendFlags::POLL_FIRST`].
const POLL_FIRST = sys::IORING_RECVSEND_POLL_FIRST as _;
/// `IORING_RECV_MULTISHOT`
const MULTISHOT = sys::IORING_RECV_MULTISHOT as _;
/// `IORING_RECVSEND_FIXED_BUF`
///
/// See also [`IoringSendFlags::FIXED_BUF`].
const FIXED_BUF = sys::IORING_RECVSEND_FIXED_BUF as _;
}
}
bitflags::bitflags! {
/// accept flags (`sqe.ioprio`)
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct IoringAcceptFlags: u16 {
/// `IORING_ACCEPT_MULTISHOT`
const MULTISHOT = sys::IORING_ACCEPT_MULTISHOT as _;
}
}
bitflags::bitflags! {
/// recvmsg out flags
#[repr(transparent)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct RecvmsgOutFlags: u32 {
/// `MSG_EOR`
const EOR = net::MSG_EOR;
/// `MSG_TRUNC`
const TRUNC = net::MSG_TRUNC;
/// `MSG_CTRUNC`
const CTRUNC = net::MSG_CTRUNC;
/// `MSG_OOB`
const OOB = net::MSG_OOB;
/// `MSG_ERRQUEUE`
const ERRQUEUE = net::MSG_ERRQUEUE;
}
}
#[allow(missing_docs)]
pub const IORING_CQE_BUFFER_SHIFT: u32 = sys::IORING_CQE_BUFFER_SHIFT as _;
#[allow(missing_docs)]
pub const IORING_FILE_INDEX_ALLOC: i32 = sys::IORING_FILE_INDEX_ALLOC as _;
// Re-export these as `u64`, which is the `offset` type in `rustix::io::mmap`.
#[allow(missing_docs)]
pub const IORING_OFF_SQ_RING: u64 = sys::IORING_OFF_SQ_RING as _;
#[allow(missing_docs)]
pub const IORING_OFF_CQ_RING: u64 = sys::IORING_OFF_CQ_RING as _;
#[allow(missing_docs)]
pub const IORING_OFF_SQES: u64 = sys::IORING_OFF_SQES as _;
/// `IORING_REGISTER_FILES_SKIP`
#[inline]
#[doc(alias = "IORING_REGISTER_FILES_SKIP")]
pub const fn io_uring_register_files_skip() -> BorrowedFd<'static> {
let files_skip = sys::IORING_REGISTER_FILES_SKIP as RawFd;
// SAFETY: `IORING_REGISTER_FILES_SKIP` is a reserved value that is never
// dynamically allocated, so it'll remain valid for the duration of
// `'static`.
unsafe { BorrowedFd::<'static>::borrow_raw(files_skip) }
}
/// `IORING_NOTIF_USAGE_ZC_COPIED` (since Linux 6.2)
pub const IORING_NOTIF_USAGE_ZC_COPIED: i32 = sys::IORING_NOTIF_USAGE_ZC_COPIED as _;
/// A pointer in the io_uring API.
///
/// `io_uring`'s native API represents pointers as `u64` values. In order to
/// preserve strict-provenance, use a `*mut c_void`. On platforms where
/// pointers are narrower than 64 bits, this requires additional padding.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct io_uring_ptr {
#[cfg(all(target_pointer_width = "32", target_endian = "big"))]
#[doc(hidden)]
pub __pad32: u32,
#[cfg(all(target_pointer_width = "16", target_endian = "big"))]
#[doc(hidden)]
pub __pad16: u16,
/// The pointer value.
pub ptr: *mut c_void,
#[cfg(all(target_pointer_width = "16", target_endian = "little"))]
#[doc(hidden)]
pub __pad16: u16,
#[cfg(all(target_pointer_width = "32", target_endian = "little"))]
#[doc(hidden)]
pub __pad32: u32,
}
impl From<*mut c_void> for io_uring_ptr {
#[inline]
fn from(ptr: *mut c_void) -> Self {
Self {
ptr,
#[cfg(target_pointer_width = "16")]
__pad16: Default::default(),
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
__pad32: Default::default(),
}
}
}
impl Default for io_uring_ptr {
#[inline]
fn default() -> Self {
Self::from(null_mut())
}
}
/// User data in the io_uring API.
///
/// `io_uring`'s native API represents `user_data` fields as `u64` values. In
/// order to preserve strict-provenance, use a union which allows users to
/// optionally store pointers.
#[repr(C)]
#[derive(Copy, Clone)]
pub union io_uring_user_data {
/// An arbitrary `u64`.
pub u64_: u64,
/// A pointer.
pub ptr: io_uring_ptr,
}
impl io_uring_user_data {
/// Return the `u64` value.
#[inline]
pub fn u64_(self) -> u64 {
// SAFETY: All the fields have the same underlying representation.
unsafe { self.u64_ }
}
/// Create a `Self` from a `u64` value.
#[inline]
pub fn from_u64(u64_: u64) -> Self {
Self { u64_ }
}
/// Return the `ptr` pointer value.
#[inline]
pub fn ptr(self) -> *mut c_void {
// SAFETY: All the fields have the same underlying representation.
unsafe { self.ptr }.ptr
}
/// Create a `Self` from a pointer value.
#[inline]
pub fn from_ptr(ptr: *mut c_void) -> Self {
Self {
ptr: io_uring_ptr::from(ptr),
}
}
}
impl Default for io_uring_user_data {
#[inline]
fn default() -> Self {
let mut s = MaybeUninit::<Self>::uninit();
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe {
write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
impl core::fmt::Debug for io_uring_user_data {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
// SAFETY: Just format as a `u64`, since formatting doesn't preserve
// provenance, and we don't have a discriminant.
unsafe { self.u64_.fmt(fmt) }
}
}
/// An io_uring Submission Queue Entry.
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone, Default)]
pub struct io_uring_sqe {
pub opcode: IoringOp,
pub flags: IoringSqeFlags,
pub ioprio: ioprio_union,
pub fd: RawFd,
pub off_or_addr2: off_or_addr2_union,
pub addr_or_splice_off_in: addr_or_splice_off_in_union,
pub len: len_union,
pub op_flags: op_flags_union,
pub user_data: io_uring_user_data,
pub buf: buf_union,
pub personality: u16,
pub splice_fd_in_or_file_index: splice_fd_in_or_file_index_union,
pub addr3_or_cmd: addr3_or_cmd_union,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union ioprio_union {
pub recv_flags: IoringRecvFlags,
pub send_flags: IoringSendFlags,
pub accept_flags: IoringAcceptFlags,
pub ioprio: u16,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union len_union {
pub poll_flags: IoringPollFlags,
pub len: u32,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union addr3_or_cmd_union {
pub addr3: addr3_struct,
pub cmd: [u8; 0],
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone, Default)]
pub struct addr3_struct {
pub addr3: u64,
pub __pad2: [u64; 1],
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union off_or_addr2_union {
pub off: u64,
pub addr2: io_uring_ptr,
pub cmd_op: cmd_op_struct,
pub user_data: io_uring_user_data,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub struct cmd_op_struct {
pub cmd_op: u32,
pub __pad1: u32,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union addr_or_splice_off_in_union {
pub addr: io_uring_ptr,
pub splice_off_in: u64,
pub msgring_cmd: IoringMsgringCmds,
pub user_data: io_uring_user_data,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union op_flags_union {
pub rw_flags: crate::io::ReadWriteFlags,
pub fsync_flags: IoringFsyncFlags,
pub poll_events: u16,
pub poll32_events: u32,
pub sync_range_flags: u32,
/// `msg_flags` is split into `send_flags` and `recv_flags`.
#[doc(alias = "msg_flags")]
pub send_flags: crate::net::SendFlags,
/// `msg_flags` is split into `send_flags` and `recv_flags`.
#[doc(alias = "msg_flags")]
pub recv_flags: crate::net::RecvFlags,
pub timeout_flags: IoringTimeoutFlags,
pub accept_flags: crate::net::SocketFlags,
pub cancel_flags: IoringAsyncCancelFlags,
pub open_flags: crate::fs::OFlags,
pub statx_flags: crate::fs::AtFlags,
pub fadvise_advice: crate::fs::Advice,
pub splice_flags: SpliceFlags,
pub rename_flags: crate::fs::RenameFlags,
pub unlink_flags: crate::fs::AtFlags,
pub hardlink_flags: crate::fs::AtFlags,
pub msg_ring_flags: IoringMsgringFlags,
}
#[allow(missing_docs)]
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub union buf_union {
pub buf_index: u16,
pub buf_group: u16,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union splice_fd_in_or_file_index_union {
pub splice_fd_in: i32,
pub file_index: u32,
}
/// An io_uring Completion Queue Entry.
///
/// This does not derive `Copy` or `Clone` because the `big_cqe` field is not
/// automatically copyable.
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Default)]
pub struct io_uring_cqe {
pub user_data: io_uring_user_data,
pub res: i32,
pub flags: IoringCqeFlags,
pub big_cqe: sys::__IncompleteArrayField<u64>,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone, Default)]
pub struct io_uring_restriction {
pub opcode: IoringRestrictionOp,
pub register_or_sqe_op_or_sqe_flags: register_or_sqe_op_or_sqe_flags_union,
pub resv: u8,
pub resv2: [u32; 3],
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union register_or_sqe_op_or_sqe_flags_union {
pub register_op: IoringRegisterOp,
pub sqe_op: IoringOp,
pub sqe_flags: IoringSqeFlags,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_params {
pub sq_entries: u32,
pub cq_entries: u32,
pub flags: IoringSetupFlags,
pub sq_thread_cpu: u32,
pub sq_thread_idle: u32,
pub features: IoringFeatureFlags,
pub wq_fd: u32,
pub resv: [u32; 3],
pub sq_off: io_sqring_offsets,
pub cq_off: io_cqring_offsets,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_sqring_offsets {
pub head: u32,
pub tail: u32,
pub ring_mask: u32,
pub ring_entries: u32,
pub flags: u32,
pub dropped: u32,
pub array: u32,
pub resv1: u32,
pub resv2: u64,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_cqring_offsets {
pub head: u32,
pub tail: u32,
pub ring_mask: u32,
pub ring_entries: u32,
pub overflow: u32,
pub cqes: u32,
pub flags: u32,
pub resv1: u32,
pub resv2: u64,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Default)]
pub struct io_uring_probe {
pub last_op: IoringOp,
pub ops_len: u8,
pub resv: u16,
pub resv2: [u32; 3],
pub ops: sys::__IncompleteArrayField<io_uring_probe_op>,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_probe_op {
pub op: IoringOp,
pub resv: u8,
pub flags: IoringOpFlags,
pub resv2: u32,
}
#[allow(missing_docs)]
#[repr(C, align(8))]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_files_update {
pub offset: u32,
pub resv: u32,
pub fds: u64,
}
#[allow(missing_docs)]
#[repr(C, align(8))]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_rsrc_register {
pub nr: u32,
pub flags: IoringRsrcFlags,
pub resv2: u64,
pub data: u64,
pub tags: u64,
}
#[allow(missing_docs)]
#[repr(C, align(8))]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_rsrc_update {
pub offset: u32,
pub resv: u32,
pub data: u64,
}
#[allow(missing_docs)]
#[repr(C, align(8))]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_rsrc_update2 {
pub offset: u32,
pub resv: u32,
pub data: u64,
pub tags: u64,
pub nr: u32,
pub resv2: u32,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_getevents_arg {
pub sigmask: u64,
pub sigmask_sz: u32,
pub pad: u32,
pub ts: u64,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct io_uring_recvmsg_out {
pub namelen: u32,
pub controllen: u32,
pub payloadlen: u32,
pub flags: RecvmsgOutFlags,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iovec {
pub iov_base: *mut c_void,
pub iov_len: usize,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct open_how {
/// An [`OFlags`] value represented as a `u64`.
///
/// [`OFlags`]: crate::fs::OFlags
pub flags: u64,
/// A [`Mode`] value represented as a `u64`.
///
/// [`Mode`]: crate::fs::Mode
pub mode: u64,
pub resolve: crate::fs::ResolveFlags,
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_buf_reg {
pub ring_addr: u64,
pub ring_entries: u32,
pub bgid: u16,
pub pad: u16,
pub resv: [u64; 3_usize],
}
#[allow(missing_docs)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct io_uring_buf {
pub addr: u64,
pub len: u32,
pub bid: u16,
pub resv: u16,
}
impl Default for ioprio_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for len_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for off_or_addr2_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for addr_or_splice_off_in_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for addr3_or_cmd_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for op_flags_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for buf_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for splice_fd_in_or_file_index_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
impl Default for register_or_sqe_op_or_sqe_flags_union {
#[inline]
fn default() -> Self {
// SAFETY: All of Linux's io_uring structs may be zero-initialized.
unsafe { zeroed::<Self>() }
}
}
/// Check that our custom structs and unions have the same layout as the
/// kernel's versions.
#[test]
fn io_uring_layouts() {
use sys as c;
check_renamed_type!(off_or_addr2_union, io_uring_sqe__bindgen_ty_1);
check_renamed_type!(addr_or_splice_off_in_union, io_uring_sqe__bindgen_ty_2);
check_renamed_type!(addr3_or_cmd_union, io_uring_sqe__bindgen_ty_6);
check_renamed_type!(op_flags_union, io_uring_sqe__bindgen_ty_3);
check_renamed_type!(buf_union, io_uring_sqe__bindgen_ty_4);
check_renamed_type!(splice_fd_in_or_file_index_union, io_uring_sqe__bindgen_ty_5);
check_renamed_type!(
register_or_sqe_op_or_sqe_flags_union,
io_uring_restriction__bindgen_ty_1
);
check_renamed_type!(addr3_struct, io_uring_sqe__bindgen_ty_6__bindgen_ty_1);
check_renamed_type!(cmd_op_struct, io_uring_sqe__bindgen_ty_1__bindgen_ty_1);
check_type!(io_uring_sqe);
check_struct_field!(io_uring_sqe, opcode);
check_struct_field!(io_uring_sqe, flags);
check_struct_field!(io_uring_sqe, ioprio);
check_struct_field!(io_uring_sqe, fd);
check_struct_renamed_field!(io_uring_sqe, off_or_addr2, __bindgen_anon_1);
check_struct_renamed_field!(io_uring_sqe, addr_or_splice_off_in, __bindgen_anon_2);
check_struct_field!(io_uring_sqe, len);
check_struct_renamed_field!(io_uring_sqe, op_flags, __bindgen_anon_3);
check_struct_field!(io_uring_sqe, user_data);
check_struct_renamed_field!(io_uring_sqe, buf, __bindgen_anon_4);
check_struct_field!(io_uring_sqe, personality);
check_struct_renamed_field!(io_uring_sqe, splice_fd_in_or_file_index, __bindgen_anon_5);
check_struct_renamed_field!(io_uring_sqe, addr3_or_cmd, __bindgen_anon_6);
check_type!(io_uring_restriction);
check_struct_field!(io_uring_restriction, opcode);
check_struct_renamed_field!(
io_uring_restriction,
register_or_sqe_op_or_sqe_flags,
__bindgen_anon_1
);
check_struct_field!(io_uring_restriction, resv);
check_struct_field!(io_uring_restriction, resv2);
check_struct!(io_uring_cqe, user_data, res, flags, big_cqe);
check_struct!(
io_uring_params,
sq_entries,
cq_entries,
flags,
sq_thread_cpu,
sq_thread_idle,
features,
wq_fd,
resv,
sq_off,
cq_off
);
check_struct!(
io_sqring_offsets,
head,
tail,
ring_mask,
ring_entries,
flags,
dropped,
array,
resv1,
resv2
);
check_struct!(
io_cqring_offsets,
head,
tail,
ring_mask,
ring_entries,
overflow,
cqes,
flags,
resv1,
resv2
);
check_struct!(io_uring_recvmsg_out, namelen, controllen, payloadlen, flags);
check_struct!(io_uring_probe, last_op, ops_len, resv, resv2, ops);
check_struct!(io_uring_probe_op, op, resv, flags, resv2);
check_struct!(io_uring_files_update, offset, resv, fds);
check_struct!(io_uring_rsrc_register, nr, flags, resv2, data, tags);
check_struct!(io_uring_rsrc_update, offset, resv, data);
check_struct!(io_uring_rsrc_update2, offset, resv, data, tags, nr, resv2);
check_struct!(io_uring_getevents_arg, sigmask, sigmask_sz, pad, ts);
check_struct!(iovec, iov_base, iov_len);
check_struct!(open_how, flags, mode, resolve);
check_struct!(io_uring_buf_reg, ring_addr, ring_entries, bgid, pad, resv);
check_struct!(io_uring_buf, addr, len, bid, resv);
}
|
#[doc = "Reader of register CC"]
pub type R = crate::R<u32, super::CC>;
#[doc = "Reader of field `POL`"]
pub type POL_R = crate::R<bool, bool>;
#[doc = "Reader of field `PTPCEN`"]
pub type PTPCEN_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 17 - LED Polarity Control"]
#[inline(always)]
pub fn pol(&self) -> POL_R {
POL_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - PTP Clock Reference Enable"]
#[inline(always)]
pub fn ptpcen(&self) -> PTPCEN_R {
PTPCEN_R::new(((self.bits >> 18) & 0x01) != 0)
}
}
|
//! Generates markdown code for documentation comments
//! of the output Rust crate.
use rust_code_generator::rust_type_to_code;
use rust_type::RustType;
use rust_info::{RustMethodSelfArgKind, RustMethodArgumentsVariant, RustTypeDeclaration,
RustTypeDeclarationKind, RustMethodScope, RustEnumValue, RustMethod,
RustMethodArguments, RustMethodDocItem, RustTypeWrapperKind,
RustQtReceiverDeclaration, RustQtReceiverType};
use cpp_type::{CppType, CppTypeBase, CppTypeClassBase, CppTypeIndirection};
use common::string_utils::JoinWithSeparator;
use common::log;
use common::errors::{Result, unexpected};
/// Generates pseudo-code illustrating argument types for one variant of
/// a Rust method with emulated overloading.
pub fn rust_method_variant(args: &RustMethodArgumentsVariant,
method_name: &str,
self_arg_kind: RustMethodSelfArgKind,
crate_name: &str)
-> String {
let self_arg_doc_text = match self_arg_kind {
RustMethodSelfArgKind::None => "",
RustMethodSelfArgKind::ConstRef => "&self, ",
RustMethodSelfArgKind::MutRef => "&mut self, ",
RustMethodSelfArgKind::Value => "self, ",
};
let return_type_text = rust_type_to_code(&args.return_type.rust_api_type, crate_name);
let arg_texts = args
.arguments
.iter()
.map(|x| rust_type_to_code(&x.argument_type.rust_api_type, crate_name))
.join(", ");
let arg_final_text = if args.arguments.len() == 1 {
arg_texts
} else {
format!("({})", arg_texts)
};
format!("fn {name}({self_arg}{arg_text}) -> {return_type}",
name = method_name,
self_arg = self_arg_doc_text,
arg_text = arg_final_text,
return_type = return_type_text)
}
pub fn wrap_inline_cpp_code(code: &str) -> String {
format!("<span style='color: green;'>```{}```</span>", code)
}
pub fn wrap_cpp_doc_block(html: &str) -> String {
format!("<div style='border: 1px solid #5CFF95; \
background: #D6FFE4; padding: 16px;'>{}</div>",
html)
}
pub fn type_doc(type1: &RustTypeDeclaration) -> String {
let auto_doc = match type1.kind {
RustTypeDeclarationKind::CppTypeWrapper {
ref cpp_type_name,
ref cpp_template_arguments,
ref cpp_doc,
..
} => {
let cpp_type_code = CppType {
base: CppTypeBase::Class(CppTypeClassBase {
name: cpp_type_name.clone(),
template_arguments: cpp_template_arguments.clone(),
}),
indirection: CppTypeIndirection::None,
is_const: false,
is_const2: false,
}
.to_cpp_pseudo_code();
let mut doc = format!("C++ type: {}", wrap_inline_cpp_code(&cpp_type_code));
if let Some(ref cpp_doc) = *cpp_doc {
doc += &format!("\n\n<a href=\"{}\">C++ documentation:</a> {}",
cpp_doc.url,
wrap_cpp_doc_block(&cpp_doc.html));
}
doc
}
RustTypeDeclarationKind::MethodParametersTrait {
ref method_scope,
ref method_name,
..
} => {
let method_name_with_scope = match *method_scope {
RustMethodScope::Impl { ref target_type } => {
format!("{}::{}",
if let RustType::Common { ref base, .. } = *target_type {
base.last_name().unwrap()
} else {
panic!("RustType::Common expected");
},
method_name.last_name().unwrap())
}
RustMethodScope::TraitImpl => {
panic!("TraitImpl is totally not expected here");
}
RustMethodScope::Free => method_name.last_name().unwrap().clone(),
};
let method_link = match *method_scope {
RustMethodScope::Impl { ref target_type } => {
format!("../struct.{}.html#method.{}",
if let RustType::Common { ref base, .. } = *target_type {
base.last_name().unwrap()
} else {
panic!("RustType::Common expected");
},
method_name.last_name().unwrap())
}
RustMethodScope::TraitImpl => {
panic!("TraitImpl is totally not expected here");
}
RustMethodScope::Free => format!("../fn.{}.html", method_name.last_name().unwrap()),
};
format!("This trait represents a set of arguments accepted by [{name}]({link}) \
method.",
name = method_name_with_scope,
link = method_link)
}
};
if let Some(ref doc) = type1.rust_doc {
format!("{}\n\n{}", doc, auto_doc)
} else {
auto_doc
}
}
pub fn enum_value_doc(value: &RustEnumValue) -> String {
if value.is_dummy {
return "This variant is added in Rust because \
enums with one variant and C representation are not supported."
.to_string();
}
if value.cpp_docs.is_empty() {
log::llog(log::DebugGeneral, || "enum_value_doc: cpp_docs is empty");
return String::new();
}
if value.cpp_docs.len() > 1 {
let mut doc = "This variant corresponds to multiple C++ enum variants with the same value:\n\n"
.to_string();
for cpp_doc in &value.cpp_docs {
doc.push_str(&format!("- {}{}\n",
wrap_inline_cpp_code(&format!("{} = {}",
cpp_doc.variant_name,
value.value)),
if let Some(ref text) = cpp_doc.doc {
format!(": {}", text)
} else {
String::new()
}));
}
doc
} else {
let cpp_doc = &value.cpp_docs[0];
let doc_part =
format!("C++ enum variant: {}",
wrap_inline_cpp_code(&format!("{} = {}", cpp_doc.variant_name, value.value)));
match cpp_doc.doc {
Some(ref text) if !text.is_empty() => format!("{} ({})", text, doc_part),
_ => doc_part,
}
}
}
pub fn method_doc(method: &RustMethod) -> String {
let cpp_method_name = match method.arguments {
RustMethodArguments::SingleVariant(ref v) => v.cpp_method.cpp_method.full_name(),
RustMethodArguments::MultipleVariants { ref cpp_method_name, .. } => cpp_method_name.clone(),
};
let overloaded = method.variant_docs.len() > 1 ||
(method.variant_docs.len() == 1 && method.variant_docs[0].rust_fns.len() > 1);
let mut doc = Vec::new();
if overloaded {
doc.push(format!("C++ method: {}\n\n", wrap_inline_cpp_code(&cpp_method_name)));
doc.push("This is an overloaded function. Available variants:\n\n".to_string());
}
let mut shown_docs = Vec::new();
for doc_item in &method.variant_docs {
let ok = if let Some(ref x) = doc_item.doc {
x.mismatched_declaration.is_none()
} else {
true
};
if ok {
shown_docs.push(doc_item.clone())
}
}
for doc_item in &method.variant_docs {
if let Some(ref item_doc) = doc_item.doc {
if item_doc.mismatched_declaration.is_some() {
let anchor = &item_doc.anchor;
if shown_docs
.iter()
.any(|x| if let Some(ref xx) = x.doc {
&xx.anchor == anchor
} else {
false
}) {
shown_docs.push(RustMethodDocItem {
doc: None,
..doc_item.clone()
});
} else {
shown_docs.push(doc_item.clone());
}
}
}
}
let shown_docs_count = shown_docs.len();
for (doc_index, doc_item) in shown_docs.into_iter().enumerate() {
if shown_docs_count > 1 {
doc.push(format!("\n\n## Variant {}\n\n", doc_index + 1));
}
let rust_count = doc_item.rust_fns.len();
if overloaded {
doc.push(format!("Rust arguments: {}{}\n",
if rust_count > 1 { "<br>" } else { "" },
doc_item
.rust_fns
.iter()
.enumerate()
.map(|(i, x)| {
format!("{}```{}```<br>",
if rust_count > 1 {
format!("{}) ", i + 1)
} else {
String::new()
},
x)
})
.join("")));
}
doc.push(format!("C++ method: {}", wrap_inline_cpp_code(&doc_item.cpp_fn)));
doc.push("\n\n".to_string());
// TODO: use inheritance_chain to generate documentation
// if let Some(ref inherited_from) = doc_item.inherited_from {
// doc.push(format!("Inherited from {}. Original C++ method: {}\n\n",
// wrap_inline_cpp_code(&CppTypeBase::Class(inherited_from.class_type
// .clone())
// .to_cpp_pseudo_code()),
// wrap_inline_cpp_code(&inherited_from.short_text)));
// }
if let Some(result) = doc_item.doc {
let prefix = if let Some(ref declaration) = result.mismatched_declaration {
format!("Warning: no exact match found in C++ documentation.\
Below is the <a href=\"{}\">C++ documentation</a> for <code>{}</code>:",
result.url,
declaration)
} else {
format!("<a href=\"{}\">C++ documentation:</a>", result.url)
};
doc.push(format!("{} {}", prefix, wrap_cpp_doc_block(&result.html)));
}
}
let variant_docs = doc.join("");
if let Some(ref common_doc) = method.common_doc {
format!("{}\n\n{}", common_doc, variant_docs)
} else {
variant_docs
}
}
pub fn slots_module_doc() -> String {
"Binding Qt signals to Rust closures or extern functions.\n\n\
Types in this module allow to connect Qt signals with certain argument types \
to a Rust closure. \n\nThere is one slot type for each distinct set of argument types \
present in this crate. However, if argument types were present in a dependency crate, \
the corresponding slot type is located in the dependency's `slots` module."
.into()
}
pub fn slots_raw_module_doc() -> String {
"Binding Qt signals to Rust extern functions.\n\n\
Types in this module to connect Qt signals with certain argument types \
to a Rust extern function with payload. Raw slots expose low level C++ API and are used \
to implement the closure slots located in the parent module. Raw slots are less convenient \
but slightly faster than closure slots.\n\n\
There is one slot type for each distinct set of argument types \
present in this crate. However, if argument types were present in a dependency crate, \
the corresponding slot type is located in the dependency's `slots::raw` module."
.into()
}
pub fn overloading_module_doc() -> String {
"Types for emulating overloading for overloaded functions in this module".into()
}
pub fn doc_for_qt_builtin_receiver(cpp_type_name: &str,
rust_type_name: &str,
receiver: &RustQtReceiverDeclaration)
-> String {
format!("Represents a built-in Qt {signal} `{cpp_type}::{cpp_method}`.\n\n\
An object of this type can be created from `{rust_type}` \
with `object.{signal}s().{rust_method}()` and used for creating Qt connections using \
`qt_core::connection` API. After the connection is made, the object can (should) be dropped. \
The connection will remain active until sender or receiver are destroyed or until a manual \
disconnection is made.\n\n\
An object of this type contains a reference to the original `{rust_type}` object.",
signal = match receiver.receiver_type {
RustQtReceiverType::Signal => "signal",
RustQtReceiverType::Slot => "slot",
},
cpp_type = cpp_type_name,
cpp_method = receiver.original_method_name,
rust_type = rust_type_name,
rust_method = receiver.method_name)
}
pub fn doc_for_qt_builtin_receiver_method(cpp_type_name: &str,
receiver: &RustQtReceiverDeclaration)
-> String {
format!("Returns an object representing a built-in Qt {signal} `{cpp_type}::{cpp_method}`.\n\n\
Return value of this function can be used for creating Qt connections using \
`qt_core::connection` API.",
signal = match receiver.receiver_type {
RustQtReceiverType::Signal => "signal",
RustQtReceiverType::Slot => "slot",
},
cpp_type = cpp_type_name,
cpp_method = receiver.original_method_name)
}
pub fn doc_for_qt_builtin_receivers_struct(rust_type_name: &str, receiver_type: &str) -> String {
format!("Provides access to built-in Qt {} of `{}`.",
receiver_type,
rust_type_name)
}
pub fn add_special_type_docs(data: &mut RustTypeDeclaration) -> Result<()> {
let mut type_doc = None;
if let RustTypeDeclarationKind::CppTypeWrapper {
ref kind,
ref mut methods,
..
} = data.kind {
if let RustTypeWrapperKind::Struct { ref slot_wrapper, .. } = *kind {
if let Some(ref slot_wrapper) = *slot_wrapper {
type_doc = Some(format!("Allows to bind Qt signals with arguments `({cpp_args})` to a \
Rust extern function.\n\n\
Use `{public_type_name}` to bind signals to a Rust closure instead.\n\n\
Create an object using `new()` and bind your function and payload using `set()`. \
The function will receive the payload as its first arguments, and the rest of arguments \
will be values passed through the Qt connection system. Use \
`connect()` method of a `qt_core::connection::Signal` object to connect the signal \
to this slot. The callback function will be executed each time the slot is invoked \
until source signals are disconnected or the slot object is destroyed.\n\n\
If `set()` was not called, slot invokation has no effect.",
public_type_name = slot_wrapper.public_type_name,
cpp_args = slot_wrapper
.arguments
.iter()
.map(|t| t.cpp_type.to_cpp_pseudo_code())
.join(", ")));
for method in methods {
if method.name.parts.len() != 1 {
return Err(unexpected("method name should have one part here").into());
}
if method.variant_docs.len() != 1 {
return Err(unexpected("method.variant_docs should have one item here").into());
}
match method.name.parts[0].as_str() {
"new" => {
method.common_doc = Some("Constructs a new object.".into());
}
"set" => {
method.common_doc = Some("Sets `func` as the callback function \
and `data` as the payload. When the slot is invoked, `func(data)` will be called. \
Note that it may happen at any time and in any thread."
.into());
}
"custom_slot" => {
method.common_doc = Some("Executes the callback function, as if the slot was invoked \
with these arguments. Does nothing if no callback function was set."
.into());
}
_ => {
return Err(unexpected("unknown method for slot wrapper").into());
}
}
}
}
}
}
data.rust_doc = type_doc;
Ok(())
}
|
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use num::{integer::Roots, BigUint, Integer, PrimInt};
use primal::is_prime;
use std::{collections::BTreeMap, rc::Rc};
fn prime_sum_u64(i: u64, j: u64) -> u64 {
// The vast majority are clones of others so sticking them into a rc to avoid the allocations
let mut m: BTreeMap<(u64, u64), Rc<u64>> = BTreeMap::new();
let mut to_do = vec![(i, j)];
while let Some((v, p)) = to_do.pop() {
let result = if v == 1 {
Rc::new(0u64)
}
else if v == 2 {
Rc::new(2u64)
}
else if p == 1 {
Rc::new((2 + v) * (v - 1) / 2)
}
else if m.contains_key(&(v, p)) {
continue;
}
else if p.pow(2) <= v && is_prime(p) {
let a = if let Some(a) = m.get(&(v, p - 1)) {
a.as_ref()
}
else {
to_do.push((v, p));
to_do.push((v, p - 1));
continue;
};
let b = if let Some(b) = m.get(&(v / p, p - 1)) {
b.as_ref()
}
else {
to_do.push((v, p));
to_do.push((v / p, p - 1));
continue;
};
let c = if let Some(c) = m.get(&(p - 1, p - 1)) {
c.as_ref()
}
else {
to_do.push((v, p));
to_do.push((p - 1, p - 1));
continue;
};
Rc::new(a - (b - c) * p)
}
else {
if let Some(a) = m.get(&(v, p - 1)) {
Rc::clone(&a)
}
else {
to_do.push((v, p));
to_do.push((v, p - 1));
continue;
}
};
m.insert((v, p), result);
}
m.get(&(i, j)).unwrap().as_ref().clone()
}
fn sum_of_primes_under(n: u64) -> u64 {
let r = n.sqrt() as u64;
assert!(r * r <= n && (r + 1).pow(2) > n);
let mut v: Vec<_> = (1..r + 1).map(|i| n / i).collect();
v.extend((0..*v.last().unwrap()).rev());
let mut s: BTreeMap<u64, u64> = v.iter().copied().map(|i| (i, i * (i + 1) / 2 - 1)).collect();
for p in 2..r {
if s[&p] > s[&(p - 1)] {
// p is prime
let sp = s[&(p - 1)];
let p2 = p * p;
for &ve in &v {
if ve < p2 {
break;
}
*s.get_mut(&ve).unwrap() -= p * (s[&(ve / p)] - sp);
}
}
}
return s[&n];
}
fn sum_of_primes_u128(n: u128) -> u128 {
let r = n.sqrt();
assert!(r * r <= n && (r + 1).pow(2) > n);
let mut v: Vec<_> = (1..r + 1).map(|i| n / i).collect();
v.extend((0..*v.last().unwrap()).rev());
let mut s: BTreeMap<u128, u128> = v.iter().copied().map(|i| (i, i * (i + 1) / 2 - 1)).collect();
for p in 2..r {
if s[&p] > s[&(p - 1)] {
// p is prime
let sp = s[&(p - 1)];
let p2 = p * p;
for &ve in &v {
if ve < p2 {
break;
}
*s.get_mut(&ve).unwrap() -= p * (s[&(ve / p)] - sp);
}
}
}
return s[&n];
}
fn bench_fibs(c: &mut Criterion) {
let mut group = c.benchmark_group("prime_sum");
for i in [10000].iter() {
group.bench_with_input(BenchmarkId::new("bigint", i), i, |b, i| b.iter(|| prime_sum_bigint(*i, i.sqrt())));
group.bench_with_input(BenchmarkId::new("u64", i), i, |b, i| b.iter(|| sum_of_primes_under(*i)));
group.bench_with_input(BenchmarkId::new("u128", i), i, |b, i| b.iter(|| sum_of_primes_under128(*i as u128)));
}
group.finish();
}
criterion_group!(benches, bench_fibs);
criterion_main!(benches);
|
use std::{
collections::HashMap,
io::{stdin, stdout, Write},
rc::Rc,
vec,
};
use crate::types::{
dot_pair::DotPair,
exception::Exception,
list::{List, ListItem},
struct_declare::Struct,
value::Value,
DynType,
};
fn lang_new(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let struct_type = list.next().to_middle()?.content.to_struct_declare()?;
let rest = list.current_value.clone();
Ok(Value::new(
DynType::Struct(Struct::new(struct_type, rest)?),
None,
))
}
fn lang_apply(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let closure = list.next().to_middle()?.content.to_closure()?;
let args = list.next().to_middle()?;
list.next().to_end()?;
closure(args)
}
fn lang_input(args: Value) -> Result<Value, Exception> {
let mut buffer = String::new();
List::new(args).next().to_end()?;
match stdin().read_line(&mut buffer) {
Ok(_) => Ok(Value::new(
DynType::Str(String::from(buffer.trim_end_matches('\n'))),
None,
)),
Err(err) => Err(Exception {
thrown_object: Value::new(
DynType::Str(format!("Cannot read from stdio, cause: {}", err)),
None,
),
traceback: vec![],
previous_exception: None,
}),
}
}
fn lang_println(arg: Value) -> Result<Value, Exception> {
let mut list = List::new(arg);
while let ListItem::Middle(item) = list.next() {
println!("{}", item.content);
}
list.next().to_end()?;
Ok(Value::new(DynType::Nil, None))
}
fn lang_print(arg: Value) -> Result<Value, Exception> {
let mut list = List::new(arg);
while let ListItem::Middle(item) = list.next() {
print!("{}", item.content);
}
list.next().to_end()?;
stdout()
.flush()
.unwrap_or_else(|error| println!("Print error: {}", &error));
Ok(Value::new(DynType::Nil, None))
}
fn lang_num_add(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut accum = 0.0;
while let ListItem::Middle(value) = list.next() {
accum += value.content.to_number()?;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(accum), None))
}
fn lang_num_mul(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut accum = 1.0;
while let ListItem::Middle(value) = list.next() {
accum *= value.content.to_number()?;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(accum), None))
}
fn lang_num_sub(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut accum = list.next().to_middle()?.content.to_number()?;
let next = list.next();
if let ListItem::End = next {
return Ok(Value::new(DynType::Number(-accum), None));
}
accum -= next.to_middle()?.content.to_number()?;
while let ListItem::Middle(value) = list.next() {
accum -= value.content.to_number()?;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(accum), None))
}
fn lang_num_div(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut accum = list.next().to_middle()?.content.to_number()?;
while let ListItem::Middle(value) = list.next() {
accum /= value.content.to_number()?;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(accum), None))
}
fn lang_num_mod(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let x = list.next().to_middle()?.content.to_number()?;
let y = list.next().to_middle()?.content.to_number()?;
list.next().to_end()?;
Ok(Value::new(DynType::Number(x % y), None))
}
fn lang_equals(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let first = list.next().to_middle()?;
while let ListItem::Middle(current) = list.next() {
if first.content != current.content {
return Ok(Value::new(DynType::Nil, None));
}
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(1.0), None))
}
fn lang_not_equals(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let first = list.next().to_middle()?;
while let ListItem::Middle(current) = list.next() {
if first.content == current.content {
return Ok(Value::new(DynType::Nil, None));
}
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(1.0), None))
}
fn lang_greater_than(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut previous = list.next().to_middle()?;
while let ListItem::Middle(current) = list.next() {
match previous.content.partial_cmp(¤t.content) {
Some(cmp) => match cmp {
std::cmp::Ordering::Less => return Ok(Value::new(DynType::Nil, None)),
std::cmp::Ordering::Equal => return Ok(Value::new(DynType::Nil, None)),
std::cmp::Ordering::Greater => {}
},
None => {
return Err(Exception {
thrown_object: Value::new(
DynType::Str(format!(
"Uncomparable types {:?} and {:?}",
previous.content, current.content
)),
None,
),
traceback: vec![],
previous_exception: None,
})
}
}
previous = current;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(1.0), None))
}
fn lang_greater_than_or_equals(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut previous = list.next().to_middle()?;
while let ListItem::Middle(current) = list.next() {
match previous.content.partial_cmp(¤t.content) {
Some(cmp) => match cmp {
std::cmp::Ordering::Less => return Ok(Value::new(DynType::Nil, None)),
std::cmp::Ordering::Equal => {}
std::cmp::Ordering::Greater => {}
},
None => {
return Err(Exception {
thrown_object: Value::new(
DynType::Str(format!(
"Uncomparable types {:?} and {:?}",
previous.content, current.content
)),
None,
),
traceback: vec![],
previous_exception: None,
})
}
}
previous = current;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(1.0), None))
}
fn lang_less_than(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut previous = list.next().to_middle()?;
while let ListItem::Middle(current) = list.next() {
match previous.content.partial_cmp(¤t.content) {
Some(cmp) => match cmp {
std::cmp::Ordering::Less => {}
std::cmp::Ordering::Equal => return Ok(Value::new(DynType::Nil, None)),
std::cmp::Ordering::Greater => return Ok(Value::new(DynType::Nil, None)),
},
None => {
return Err(Exception {
thrown_object: Value::new(
DynType::Str(format!(
"Uncomparable types {:?} and {:?}",
previous.content, current.content
)),
None,
),
traceback: vec![],
previous_exception: None,
})
}
}
previous = current;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(1.0), None))
}
fn lang_less_than_or_equals(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut previous = list.next().to_middle()?;
while let ListItem::Middle(current) = list.next() {
match previous.content.partial_cmp(¤t.content) {
Some(cmp) => match cmp {
std::cmp::Ordering::Less => {}
std::cmp::Ordering::Equal => {}
std::cmp::Ordering::Greater => return Ok(Value::new(DynType::Nil, None)),
},
None => {
return Err(Exception {
thrown_object: Value::new(
DynType::Str(format!(
"Uncomparable types {:?} and {:?}",
previous.content, current.content
)),
None,
),
traceback: vec![],
previous_exception: None,
})
}
}
previous = current;
}
list.next().to_end()?;
Ok(Value::new(DynType::Number(1.0), None))
}
fn lang_cmp(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let first = list.next().to_middle()?;
let second = list.next().to_middle()?;
list.next().to_end()?;
match first.content.partial_cmp(&second.content) {
Some(cmp) => match cmp {
std::cmp::Ordering::Less => Ok(Value::new(DynType::Number(-1.0), None)),
std::cmp::Ordering::Equal => Ok(Value::new(DynType::Number(0.0), None)),
std::cmp::Ordering::Greater => Ok(Value::new(DynType::Number(1.0), None)),
},
None => Err(Exception {
thrown_object: Value::new(
DynType::Str(format!(
"Uncomparable types {:?} and {:?}",
first.content, second.content
)),
None,
),
traceback: vec![],
previous_exception: None,
}),
}
}
fn lang_pair(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let left = list.next().to_middle()?;
let right = list.next().to_middle()?;
list.next().to_end()?;
Ok(Value::new(DynType::Pair(DotPair { left, right }), None))
}
fn lang_left(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let pair = list.next().to_middle()?;
let pair = pair.content.to_pair()?;
list.next().to_end()?;
let left = pair.left.clone();
Ok(left)
}
fn lang_right(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let pair = list.next().to_middle()?;
let pair = pair.content.to_pair()?;
list.next().to_end()?;
let right = pair.right.clone();
Ok(right)
}
fn lang_concat(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let mut accum = String::new();
while let ListItem::Middle(value) = list.next() {
accum += format!("{}", value.content).as_str();
}
list.next().to_end()?;
Ok(Value::new(DynType::Str(accum), None))
}
fn lang_number(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let parameter = list.next().to_middle()?;
list.next().to_end()?;
let number = match &*parameter.content {
DynType::Nil => Value::new(DynType::Number(0.0), None),
DynType::Number(_) => parameter.clone(),
DynType::Str(s) => Value::new(
DynType::Number(match s.parse::<f64>() {
Ok(num) => num,
Err(_) => {
return Err(Exception {
thrown_object: Value::new(
DynType::Str(format!("Cannot parse '{}' to int", s)),
None,
),
traceback: vec![],
previous_exception: None,
})
}
}),
None,
),
other => {
return Err(Exception {
thrown_object: Value::new(
DynType::Str(format!("Cannot parse '{}' to int", other)),
None,
),
traceback: vec![],
previous_exception: None,
})
}
};
Ok(number)
}
fn lang_str(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let item = list.next().to_middle()?;
list.next().to_end()?;
Ok(Value::new(DynType::Str(format!("{}", item.content)), None))
}
fn lang_split(args: Value) -> Result<Value, Exception> {
let mut list = List::new(args);
let text = list.next().to_middle()?.content.to_string();
let mut splitted: Vec<String> = match list.next() {
ListItem::Middle(s) => text
.split(&(&*s.content).to_string())
.map(str::to_string)
.collect(),
ListItem::End => text.split_whitespace().map(str::to_string).collect(),
ListItem::Last(_) => {
return Err(Exception {
thrown_object: Value::new(DynType::Str(format!("Syntax Error")), None),
traceback: vec![],
previous_exception: None,
})
}
};
list.next().to_end()?;
splitted.reverse();
let mut pair = Value::new(DynType::Nil, None);
for item in splitted {
pair = Value::new(
DynType::Pair(DotPair {
right: pair,
left: Value::new(DynType::Str(item.to_string()), None),
}),
None,
);
}
Ok(pair)
}
pub fn all_base_functions() -> HashMap<String, Value> {
let mut functions = HashMap::new();
functions.insert(
"new".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_new(args))), None),
);
functions.insert(
"apply".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_apply(args))), None),
);
functions.insert(
"input".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_input(args))), None),
);
functions.insert(
"print".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_print(args))), None),
);
functions.insert(
"println".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_println(args))), None),
);
functions.insert(
"+".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_num_add(args))), None),
);
functions.insert(
"-".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_num_sub(args))), None),
);
functions.insert(
"*".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_num_mul(args))), None),
);
functions.insert(
"/".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_num_div(args))), None),
);
functions.insert(
"%".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_num_mod(args))), None),
);
functions.insert(
"=".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_equals(args))), None),
);
functions.insert(
"!=".to_string(),
Value::new(
DynType::Closure(Rc::new(|args| lang_not_equals(args))),
None,
),
);
functions.insert(
">".to_string(),
Value::new(
DynType::Closure(Rc::new(|args| lang_greater_than(args))),
None,
),
);
functions.insert(
">=".to_string(),
Value::new(
DynType::Closure(Rc::new(|args| lang_greater_than_or_equals(args))),
None,
),
);
functions.insert(
"<".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_less_than(args))), None),
);
functions.insert(
"<=".to_string(),
Value::new(
DynType::Closure(Rc::new(|args| lang_less_than_or_equals(args))),
None,
),
);
functions.insert(
"cmp".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_cmp(args))), None),
);
functions.insert(
"pair".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_pair(args))), None),
);
functions.insert(
"left".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_left(args))), None),
);
functions.insert(
"right".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_right(args))), None),
);
functions.insert(
"concat".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_concat(args))), None),
);
functions.insert(
"number".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_number(args))), None),
);
functions.insert(
"str".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_str(args))), None),
);
functions.insert(
"split".to_string(),
Value::new(DynType::Closure(Rc::new(|args| lang_split(args))), None),
);
functions
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qrasterwindow.h
// dst-file: /src/gui/qrasterwindow.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::qpaintdevicewindow::*; // 773
use std::ops::Deref;
use super::qwindow::*; // 773
use super::super::core::qobjectdefs::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QRasterWindow_Class_Size() -> c_int;
// proto: void QRasterWindow::QRasterWindow(QWindow * parent);
fn C_ZN13QRasterWindowC2EP7QWindow(arg0: *mut c_void) -> u64;
// proto: const QMetaObject * QRasterWindow::metaObject();
fn C_ZNK13QRasterWindow10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QRasterWindow)=1
#[derive(Default)]
pub struct QRasterWindow {
qbase: QPaintDeviceWindow,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QRasterWindow {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QRasterWindow {
return QRasterWindow{qbase: QPaintDeviceWindow::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QRasterWindow {
type Target = QPaintDeviceWindow;
fn deref(&self) -> &QPaintDeviceWindow {
return & self.qbase;
}
}
impl AsRef<QPaintDeviceWindow> for QRasterWindow {
fn as_ref(& self) -> & QPaintDeviceWindow {
return & self.qbase;
}
}
// proto: void QRasterWindow::QRasterWindow(QWindow * parent);
impl /*struct*/ QRasterWindow {
pub fn new<T: QRasterWindow_new>(value: T) -> QRasterWindow {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QRasterWindow_new {
fn new(self) -> QRasterWindow;
}
// proto: void QRasterWindow::QRasterWindow(QWindow * parent);
impl<'a> /*trait*/ QRasterWindow_new for (Option<&'a QWindow>) {
fn new(self) -> QRasterWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QRasterWindowC2EP7QWindow()};
let ctysz: c_int = unsafe{QRasterWindow_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN13QRasterWindowC2EP7QWindow(arg0)};
let rsthis = QRasterWindow{qbase: QPaintDeviceWindow::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QRasterWindow::metaObject();
impl /*struct*/ QRasterWindow {
pub fn metaObject<RetType, T: QRasterWindow_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QRasterWindow_metaObject<RetType> {
fn metaObject(self , rsthis: & QRasterWindow) -> RetType;
}
// proto: const QMetaObject * QRasterWindow::metaObject();
impl<'a> /*trait*/ QRasterWindow_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QRasterWindow) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QRasterWindow10metaObjectEv()};
let mut ret = unsafe {C_ZNK13QRasterWindow10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
#![feature(link_args)]
#![feature(libc)]
extern crate libc;
use libc::c_int;
use libc::c_float;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::sync::Arc;
use std::thread;
use std::env;
#[link_args = "-L./ -lbs -lsniper_roi"]
#[link(name = "bs", kind="static")]
#[link(name = "sniper_roi", kind="static")]
extern {
fn BlkSchlsEqEuroNoDiv( sptprice: c_float,
strike: c_float, rate: c_float, volatility: c_float,
time: c_float, otype: c_int, timet: c_float ) -> c_float;
}
extern {
fn SimRoiStart_wrapper();
}
extern {
fn SimRoiEnd_wrapper();
}
extern {
fn SimMarker_wrapper(arg0: c_int, arg1: c_int);
}
// const NTHREADS: usize = 1;
// const testpath: &'static str = "../inputs/in_64K.txt";
const NUM_RUNS : usize = 100;
struct TestParams {
otype: c_int,
sptprice: c_float,
strike: c_float,
rate: c_float,
volatility: c_float,
otime: c_float,
}
fn main(){
let args: Vec<String> = env::args().collect();
let NTHREADS: usize = args[1].parse::<usize>().unwrap();
// println!("Num threads: {}", NTHREADS);
let ref testpath = args[2];
let mut tests: Vec<TestParams> = Vec::with_capacity(100000000);
loadTestData(&mut tests, testpath);
let mut threads = Vec::new();
if NTHREADS>1 {
unsafe{ SimRoiStart_wrapper() };
let tests_arc = Arc::new(tests);
for threadnum in 0..NTHREADS {
let tests_copy = tests_arc.clone();
let num_tests = tests_copy.len();
let start = threadnum*(num_tests / NTHREADS);
let mut end = (threadnum+1)*(num_tests / NTHREADS);
if end > num_tests {
end = num_tests;
}
let handle = thread::spawn(move || {
// println!("Spawned thread");
// println!("start: {} end: {}\n",start,end);
for run in 0..NUM_RUNS {
for testnum in start..end {
let sptprice: c_float = tests_copy[testnum].sptprice;
let strike: c_float = tests_copy[testnum].strike;
let rate: c_float = tests_copy[testnum].rate;
let volatility: c_float = tests_copy[testnum].volatility;
let time: c_float = tests_copy[testnum].otime;
let otype: c_int = tests_copy[testnum].otype;
let timet: c_float = 0.0;
let s = unsafe{ BlkSchlsEqEuroNoDiv(sptprice, strike, rate, volatility, time, otype, timet ) };
// println!("Thread {} running test {}",threadnum,testnum);
}
}
});
threads.push(handle);
}
for t in threads {
t.join();
}
unsafe{ SimRoiEnd_wrapper() };
} else {
unsafe{ SimRoiStart_wrapper() };
let start=0; let end=tests.len();
for run in 0..NUM_RUNS {
for testnum in start..end {
let sptprice: c_float = tests[testnum].sptprice;
let strike: c_float = tests[testnum].strike;
let rate: c_float = tests[testnum].rate;
let volatility: c_float = tests[testnum].volatility;
let time: c_float = tests[testnum].otime;
let otype: c_int = tests[testnum].otype;
let timet: c_float = 0.0;
let s = unsafe{ BlkSchlsEqEuroNoDiv(sptprice, strike, rate, volatility, time, otype, timet ) };
// println!("{}",s);
}
}
unsafe{ SimRoiEnd_wrapper() };
}
}
fn loadTestData(tests: &mut Vec<TestParams>, path_to_test: & String ) {
let testfile = BufReader::new(File::open(path_to_test).unwrap());
for test2 in testfile.lines() {
let test = test2.unwrap();
let params = test.split_whitespace();
let params: Vec<&str> = params.collect();
if params.len()>1 {
let mut otype_val = 0;
if params[6]=="P" {
otype_val = 1;
}
let test_params = TestParams{
otype: otype_val as c_int,
sptprice: params[0].parse::<f32>().unwrap(),
strike: params[1].parse::<f32>().unwrap(),
rate: params[2].parse::<f32>().unwrap(),
volatility: params[4].parse::<f32>().unwrap(),
otime: params[5].parse::<f32>().unwrap(),
};
tests.push(test_params);
}
}
}
|
// NOW_MOUSE_MSG
use num_derive::FromPrimitive;
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum MouseMessageType {
Position = 0x01,
Cursor = 0x02,
Mode = 0x03,
State = 0x04,
}
__flags_struct! {
MousePositionFlags: u8 => {
same = SAME = 0x01,
}
}
__flags_struct! {
MouseCursorFlags: u8 => {
large = LARGE = 0x01,
}
}
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum MouseCursorType {
Mono = 0x00,
Color = 0x01,
Alpha = 0x02,
}
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum MouseMode {
Primary = 0x01,
Secondary = 0x02,
Disabled = 0x03,
}
#[derive(Encode, Decode, FromPrimitive, Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum MouseState {
Primary = 0x01,
Secondary = 0x02,
Disabled = 0x03,
}
|
use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;
use std::time::Duration;
use enet_sys::{
enet_peer_disconnect, enet_peer_disconnect_later, enet_peer_disconnect_now, enet_peer_receive,
enet_peer_reset, enet_peer_send, ENetPeer, _ENetPeerState,
_ENetPeerState_ENET_PEER_STATE_ACKNOWLEDGING_CONNECT,
_ENetPeerState_ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT,
_ENetPeerState_ENET_PEER_STATE_CONNECTED, _ENetPeerState_ENET_PEER_STATE_CONNECTING,
_ENetPeerState_ENET_PEER_STATE_CONNECTION_PENDING,
_ENetPeerState_ENET_PEER_STATE_CONNECTION_SUCCEEDED,
_ENetPeerState_ENET_PEER_STATE_DISCONNECTED, _ENetPeerState_ENET_PEER_STATE_DISCONNECTING,
_ENetPeerState_ENET_PEER_STATE_DISCONNECT_LATER, _ENetPeerState_ENET_PEER_STATE_ZOMBIE,
};
use crate::{Address, Error, Packet};
/// This struct represents an endpoint in an ENet-connection.
///
/// The lifetime of these instances is not really clear from the ENet documentation.
/// Therefore, `Peer`s are always borrowed, and can not really be stored anywhere.
/// For this purpose, use [PeerID](struct.PeerID.html) instead.
///
/// ENet allows the association of arbitrary data with each peer.
/// The type of this associated data is chosen through `T`.
#[repr(transparent)]
pub struct Peer<T> {
inner: ENetPeer,
_data: PhantomData<T>,
}
/// A packet received directly from a `Peer`.
///
/// Contains the received packet as well as the channel on which it was received.
#[derive(Debug)]
pub struct PeerPacket {
/// The packet that was received.
pub packet: Packet,
/// The channel on which the packet was received.
pub channel_id: u8,
}
impl<'a, T> Peer<T>
where
T: 'a,
{
pub(crate) fn new(inner: &'a ENetPeer) -> &'a Peer<T> {
unsafe { &*(inner as *const _ as *const Peer<T>) }
}
pub(crate) fn new_mut(inner: &'a mut ENetPeer) -> &'a mut Peer<T> {
unsafe { &mut *(inner as *mut _ as *mut Peer<T>) }
}
/// Returns the address of this `Peer`.
pub fn address(&self) -> Address {
Address::from_enet_address(&self.inner.address)
}
/// Returns the amout of channels allocated for this `Peer`.
pub fn channel_count(&self) -> usize {
self.inner.channelCount
}
/// Returns a reference to the data associated with this `Peer`, if set.
pub fn data(&self) -> Option<&T> {
unsafe {
let raw_data = self.inner.data as *const T;
if raw_data.is_null() {
None
} else {
Some(&(*raw_data))
}
}
}
/// Returns a mutable reference to the data associated with this `Peer`, if set.
pub fn data_mut(&mut self) -> Option<&mut T> {
unsafe {
let raw_data = self.inner.data as *mut T;
if raw_data.is_null() {
None
} else {
Some(&mut (*raw_data))
}
}
}
/// Sets or clears the data associated with this `Peer`, replacing existing data.
pub fn set_data(&mut self, data: Option<T>) {
unsafe {
let raw_data = self.inner.data as *mut T;
if !raw_data.is_null() {
// free old data
let _: Box<T> = Box::from_raw(raw_data);
}
let new_data = match data {
Some(data) => Box::into_raw(Box::new(data)) as *mut _,
None => std::ptr::null_mut(),
};
self.inner.data = new_data;
}
}
/// Returns the downstream bandwidth of this `Peer` in bytes/second.
pub fn incoming_bandwidth(&self) -> u32 {
self.inner.incomingBandwidth
}
/// Returns the upstream bandwidth of this `Peer` in bytes/second.
pub fn outgoing_bandwidth(&self) -> u32 {
self.inner.outgoingBandwidth
}
/// Returns the mean round trip time between sending a reliable packet and receiving its acknowledgement.
pub fn mean_rtt(&self) -> Duration {
Duration::from_millis(self.inner.roundTripTime as u64)
}
/// Forcefully disconnects this `Peer`.
///
/// The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host.
pub fn reset(&mut self) {
unsafe {
enet_peer_reset(&mut self.inner as *mut _);
}
}
/// Returns the state this `Peer` is in.
pub fn state(&self) -> PeerState {
PeerState::from_sys_state(self.inner.state)
}
/// Queues a packet to be sent.
///
/// Actual sending will happen during `Host::service`.
pub fn send_packet(&mut self, packet: Packet, channel_id: u8) -> Result<(), Error> {
let res =
unsafe { enet_peer_send(&mut self.inner as *mut _, channel_id, packet.into_inner()) };
match res {
r if r > 0 => panic!("unexpected res: {}", r),
0 => Ok(()),
r if r < 0 => Err(Error(r)),
_ => panic!("unreachable"),
}
}
/// Disconnects from this peer.
///
/// A `Disconnect` event will be returned by `Host::service` once the disconnection is complete.
pub fn disconnect(&mut self, data: u32) {
unsafe {
enet_peer_disconnect(&mut self.inner as *mut _, data);
}
}
/// Disconnects from this peer immediately.
///
/// No `Disconnect` event will be created. No disconnect notification for the foreign peer is guaranteed, and this `Peer` is immediately reset on return from this method.
pub fn disconnect_now(&mut self, data: u32) {
self.set_data(None);
unsafe {
enet_peer_disconnect_now(&mut self.inner as *mut _, data);
}
}
/// Disconnects from this peer after all outgoing packets have been sent.
///
/// A `Disconnect` event will be returned by `Host::service` once the disconnection is complete.
pub fn disconnect_later(&mut self, data: u32) {
unsafe {
enet_peer_disconnect_later(&mut self.inner as *mut _, data);
}
}
/// Attempts to dequeue an incoming packet from this `Peer`.
///
/// On success, returns the packet and the channel id of the receiving channel.
pub fn receive<'b>(&mut self) -> Option<PeerPacket> {
let mut channel_id = 0u8;
let res =
unsafe { enet_peer_receive(&mut self.inner as *mut _, &mut channel_id as *mut _) };
if res.is_null() {
None
} else {
Some(PeerPacket {
packet: Packet::from_sys_packet(res),
channel_id,
})
}
}
}
impl<T> Debug for Peer<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Peer").field("data", &self.data()).finish()
}
}
/// The ID of a [Peer](struct.Peer.html).
///
/// Can be used with the [peer](struct.Host.html#method.peer)/[peer_mut](struct.Host.html#method.peer_mut)-methods of Host, to retrieve references to a Peer.
/// As the lifetime semantics of Peers aren't clear in Enet and they cannot be owned, PeerID's are the
/// primary way of storing owned references to Peers.
///
/// When connecting to a host, both a reference to the host, and it's ID are returned.
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct PeerID(pub(crate) usize);
/// Describes the state a `Peer` is in.
///
/// The states should be self-explanatory, ENet doesn't explain them more either.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum PeerState {
Disconnected,
Connected,
Connecting,
AcknowledgingConnect,
ConnectionPending,
ConnectionSucceeded,
DisconnectLater,
Disconnecting,
AcknowledgingDisconnect,
Zombie,
}
impl PeerState {
fn from_sys_state(enet_sys_state: _ENetPeerState) -> PeerState {
#[allow(non_upper_case_globals)]
match enet_sys_state {
_ENetPeerState_ENET_PEER_STATE_DISCONNECTED => PeerState::Disconnected,
_ENetPeerState_ENET_PEER_STATE_CONNECTING => PeerState::Connecting,
_ENetPeerState_ENET_PEER_STATE_ACKNOWLEDGING_CONNECT => PeerState::AcknowledgingConnect,
_ENetPeerState_ENET_PEER_STATE_CONNECTION_PENDING => PeerState::ConnectionPending,
_ENetPeerState_ENET_PEER_STATE_CONNECTION_SUCCEEDED => PeerState::ConnectionSucceeded,
_ENetPeerState_ENET_PEER_STATE_CONNECTED => PeerState::Connected,
_ENetPeerState_ENET_PEER_STATE_DISCONNECT_LATER => PeerState::DisconnectLater,
_ENetPeerState_ENET_PEER_STATE_DISCONNECTING => PeerState::Disconnecting,
_ENetPeerState_ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT => {
PeerState::AcknowledgingDisconnect
}
_ENetPeerState_ENET_PEER_STATE_ZOMBIE => PeerState::Zombie,
val => panic!("unexpected peer state: {}", val),
}
}
}
|
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let a: Vec<u64> = rd.get_vec(n);
// a[0] + max
// a[0] * 2 + a[1] + max * 2
// a[0] * 3 + a[1] * 2 + a[2] + max * 3
let mut max = 0;
let mut prefix_sum = 0;
let mut ans = 0;
for i in 0..n {
max = max.max(a[i]);
prefix_sum += a[i];
ans += prefix_sum;
// println!("max = {}", max);
// println!("prefix = {}", prefix_sum);
println!("{}", ans + max * (i + 1) as u64);
}
}
|
use ffi;
use libc;
use AsLua;
use AsMutLua;
use LuaContext;
use LuaRead;
use Push;
use PushGuard;
use std::marker::PhantomData;
use std::fmt::Debug;
use std::mem;
use std::ptr;
/// Wraps a type that implements `FnMut` so that it can be used by hlua.
///
/// This is only needed because of a limitation in Rust's inferrence system.
pub fn function<F, P>(f: F) -> Function<F, P, <F as FnOnce<P>>::Output> where F: FnMut<P> {
Function {
function: f,
marker: PhantomData,
}
}
/// Opaque type containing a Rust function or closure.
pub struct Function<F, P, R> {
function: F,
marker: PhantomData<(P, R)>,
}
/// Opaque type that represents the Lua context when inside a callback.
///
/// Some types (like `Result`) can only be returned from a callback and not written inside a
/// Lua variable. This type is here to enforce this restriction.
pub struct InsideCallback {
lua: LuaContext,
}
unsafe impl<'a> AsLua for &'a InsideCallback {
fn as_lua(&self) -> LuaContext {
self.lua
}
}
unsafe impl<'a> AsLua for &'a mut InsideCallback {
fn as_lua(&self) -> LuaContext {
self.lua
}
}
unsafe impl<'a> AsMutLua for &'a mut InsideCallback {
fn as_mut_lua(&mut self) -> LuaContext {
self.lua
}
}
impl<L, F, P, R> Push<L> for Function<F, P, R>
where L: AsMutLua, P: 'static,
F: FnMut<P, Output=R>,
P: for<'p> LuaRead<&'p mut InsideCallback>,
R: for<'a> Push<&'a mut InsideCallback> + 'static
{
fn push_to_lua(self, mut lua: L) -> PushGuard<L> {
unsafe {
// pushing the function pointer as a userdata
let lua_data = ffi::lua_newuserdata(lua.as_mut_lua().0,
mem::size_of::<F>() as libc::size_t);
let lua_data: *mut F = mem::transmute(lua_data);
ptr::write(lua_data, self.function);
// pushing wrapper as a closure
let wrapper: extern fn(*mut ffi::lua_State) -> libc::c_int = wrapper::<F, P, R>;
ffi::lua_pushcclosure(lua.as_mut_lua().0, wrapper, 1);
PushGuard { lua: lua, size: 1 }
}
}
}
impl<'a, T, E> Push<&'a mut InsideCallback> for Result<T, E>
where T: Push<&'a mut InsideCallback> +
for<'b> Push<&'b mut &'a mut InsideCallback>,
E: Debug
{
fn push_to_lua(self, mut lua: &'a mut InsideCallback) -> PushGuard<&'a mut InsideCallback> {
match self {
Ok(val) => val.push_to_lua(lua),
Err(val) => {
let msg = format!("{:?}", val);
msg.push_to_lua(&mut lua).forget();
unsafe { ffi::lua_error(lua.as_mut_lua().0); }
unreachable!();
}
}
}
}
// this function is called when Lua wants to call one of our functions
extern fn wrapper<T, P, R>(lua: *mut ffi::lua_State) -> libc::c_int
where T: FnMut<P, Output=R>,
P: for<'p> LuaRead<&'p mut InsideCallback> + 'static,
R: for<'p> Push<&'p mut InsideCallback>
{
// loading the object that we want to call from the Lua context
let data_raw = unsafe { ffi::lua_touserdata(lua, ffi::lua_upvalueindex(1)) };
let data: &mut T = unsafe { mem::transmute(data_raw) };
// creating a temporary Lua context in order to pass it to push & read functions
let mut tmp_lua = InsideCallback { lua: LuaContext(lua) };
// trying to read the arguments
let arguments_count = unsafe { ffi::lua_gettop(lua) } as i32;
let args = match LuaRead::lua_read_at_position(&mut tmp_lua, -arguments_count as libc::c_int) { // TODO: what if the user has the wrong params?
Err(_) => {
let err_msg = format!("wrong parameter types for callback function");
err_msg.push_to_lua(&mut tmp_lua).forget();
unsafe { ffi::lua_error(lua); }
unreachable!()
},
Ok(a) => a
};
let ret_value = data.call_mut(args);
// pushing back the result of the function on the stack
let nb = ret_value.push_to_lua(&mut tmp_lua).forget();
nb as libc::c_int
}
|
// 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 fuchsia_async as fasync;
use futures::{self, task::Poll, FutureExt};
use waitgroup::*;
#[fasync::run_singlethreaded]
#[test]
async fn does_not_terminate_early() {
let mut wg = WaitGroup::new();
{
let _waiter = wg.new_waiter();
}
let _waiter = wg.new_waiter();
let wait_fut = wg.wait().fuse();
fasync::pin_mut!(wait_fut);
assert_eq!(futures::poll!(wait_fut), Poll::Pending);
}
#[fasync::run_singlethreaded]
#[test]
async fn terminates_with_dropped_waiters() {
let mut wg = WaitGroup::new();
{
let _waiter = wg.new_waiter();
let _other_waiter = wg.new_waiter();
}
let wait_fut = wg.wait().fuse();
fasync::pin_mut!(wait_fut);
assert_eq!(futures::poll!(wait_fut), Poll::Ready(()));
}
|
use super::service::Elapsed;
use crate::Error;
use futures01::{try_ready, Async, Future, Poll};
use std::{
cmp,
time::{Duration, Instant},
};
use tokio01::timer::Delay;
use tower::retry::Policy;
pub enum RetryAction {
/// Indicate that this request should be retried with a reason
Retry(String),
/// Indicate that this request should not be retried with a reason
DontRetry(String),
/// Indicate that this request should not be retried but the request was successful
Successful,
}
pub trait RetryLogic: Clone {
type Error: std::error::Error + Send + Sync + 'static;
type Response;
fn is_retriable_error(&self, error: &Self::Error) -> bool;
fn should_retry_response(&self, _response: &Self::Response) -> RetryAction {
// Treat the default as the request is successful
RetryAction::Successful
}
}
#[derive(Debug, Clone)]
pub struct FixedRetryPolicy<L> {
remaining_attempts: usize,
previous_duration: Duration,
current_duration: Duration,
max_duration: Duration,
logic: L,
}
pub struct RetryPolicyFuture<L: RetryLogic> {
delay: Delay,
policy: FixedRetryPolicy<L>,
}
impl<L: RetryLogic> FixedRetryPolicy<L> {
pub fn new(
remaining_attempts: usize,
initial_backoff: Duration,
max_duration: Duration,
logic: L,
) -> Self {
FixedRetryPolicy {
remaining_attempts,
previous_duration: Duration::from_secs(0),
current_duration: initial_backoff,
max_duration,
logic,
}
}
fn advance(&self) -> FixedRetryPolicy<L> {
let next_duration: Duration = self.previous_duration + self.current_duration;
FixedRetryPolicy {
remaining_attempts: self.remaining_attempts - 1,
previous_duration: self.current_duration,
current_duration: cmp::min(next_duration, self.max_duration),
max_duration: self.max_duration,
logic: self.logic.clone(),
}
}
fn backoff(&self) -> Duration {
self.current_duration
}
fn build_retry(&self) -> RetryPolicyFuture<L> {
let policy = self.advance();
let next = Instant::now() + policy.backoff();
let delay = Delay::new(next);
debug!(message = "retrying request.", delay_ms = %self.backoff().as_millis());
RetryPolicyFuture { delay, policy }
}
}
impl<Req, Res, L> Policy<Req, Res, Error> for FixedRetryPolicy<L>
where
Req: Clone,
L: RetryLogic<Response = Res>,
{
type Future = RetryPolicyFuture<L>;
fn retry(&self, _: &Req, result: Result<&Res, &Error>) -> Option<Self::Future> {
match result {
Ok(response) => {
if self.remaining_attempts == 0 {
error!("retries exhausted");
return None;
}
match self.logic.should_retry_response(response) {
RetryAction::Retry(reason) => {
warn!(message = "retrying after response.", %reason);
Some(self.build_retry())
}
RetryAction::DontRetry(reason) => {
warn!(message = "request is not retryable; dropping the request.", %reason);
None
}
RetryAction::Successful => None,
}
}
Err(error) => {
if self.remaining_attempts == 0 {
error!(message = "retries exhausted.", %error);
return None;
}
if let Some(expected) = error.downcast_ref::<L::Error>() {
if self.logic.is_retriable_error(expected) {
warn!("retrying after error: {}", expected);
Some(self.build_retry())
} else {
error!(message = "encountered non-retriable error.", %error);
None
}
} else if error.downcast_ref::<Elapsed>().is_some() {
warn!("request timedout.");
Some(self.build_retry())
} else {
warn!(message = "unexpected error type.", %error);
None
}
}
}
}
fn clone_request(&self, request: &Req) -> Option<Req> {
Some(request.clone())
}
}
impl<L: RetryLogic> Future for RetryPolicyFuture<L> {
type Item = FixedRetryPolicy<L>;
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
try_ready!(self
.delay
.poll()
.map_err(|error| panic!("timer error: {}; this is a bug!", error)));
Ok(Async::Ready(self.policy.clone()))
}
}
impl RetryAction {
pub fn is_retryable(&self) -> bool {
if let RetryAction::Retry(_) = &self {
true
} else {
false
}
}
pub fn is_not_retryable(&self) -> bool {
if let RetryAction::DontRetry(_) = &self {
true
} else {
false
}
}
pub fn is_successful(&self) -> bool {
if let RetryAction::Successful = &self {
true
} else {
false
}
}
}
// Disabling these tests because somehow I triggered a rustc
// bug where we can only have one assert_eq in play.
//
// rustc issue: https://github.com/rust-lang/rust/issues/71259
#[cfg(feature = "disabled")]
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::trace_init;
use futures01::Future;
use std::{fmt, time::Duration};
use tokio01_test::{assert_err, assert_not_ready, assert_ready, clock};
use tower::{retry::Retry, Service};
use tower_test01::{assert_request_eq, mock};
#[test]
fn service_error_retry() {
clock::mock(|clock| {
trace_init();
let policy = FixedRetryPolicy::new(
5,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
let (service, mut handle) = mock::pair();
let mut svc = Retry::new(policy, service);
assert_ready!(svc.poll_ready());
let mut fut = svc.call("hello");
assert_request_eq!(handle, "hello").send_error(Error(true));
assert_not_ready!(fut.poll());
clock.advance(Duration::from_secs(2));
assert_not_ready!(fut.poll());
assert_request_eq!(handle, "hello").send_response("world");
assert_eq!(fut.wait().unwrap(), "world");
});
}
#[test]
fn service_error_no_retry() {
trace_init();
let policy = FixedRetryPolicy::new(
5,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
let (service, mut handle) = mock::pair();
let mut svc = Retry::new(policy, service);
assert_ready!(svc.poll_ready());
let mut fut = svc.call("hello");
assert_request_eq!(handle, "hello").send_error(Error(false));
assert_err!(fut.poll());
}
#[test]
fn timeout_error() {
clock::mock(|clock| {
trace_init();
let policy = FixedRetryPolicy::new(
5,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
let (service, mut handle) = mock::pair();
let mut svc = Retry::new(policy, service);
assert_ready!(svc.poll_ready());
let mut fut = svc.call("hello");
assert_request_eq!(handle, "hello")
.send_error(super::super::service::Elapsed::default());
assert_not_ready!(fut.poll());
clock.advance(Duration::from_secs(2));
assert_not_ready!(fut.poll());
assert_request_eq!(handle, "hello").send_response("world");
assert_eq!(fut.wait().unwrap(), "world");
});
}
#[test]
fn backoff_grows_to_max() {
let mut policy = FixedRetryPolicy::new(
10,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
assert_eq!(Duration::from_secs(1), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(1), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(2), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(3), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(5), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(8), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(10), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(10), policy.backoff());
}
#[derive(Debug, Clone)]
struct SvcRetryLogic;
impl RetryLogic for SvcRetryLogic {
type Error = Error;
type Response = &'static str;
fn is_retriable_error(&self, error: &Self::Error) -> bool {
error.0
}
}
#[derive(Debug)]
struct Error(bool);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "error")
}
}
impl std::error::Error for Error {}
}
|
use huffman::*;
use binary_reader::*;
use std::io::{Read, Write, BufReader};
use std::fs::File;
fn dfs<R: Read>(input: &mut BinaryReader<R>) -> Node {
if input.read_bit() == 1 {
let symbol = input.read_u8();
Node::Leaf(symbol)
} else {
let left = dfs(input);
let right = dfs(input);
Node::Parent {
left: Box::new(left),
right: Box::new(right),
}
}
}
pub fn decompress<R: Read, W: Write>(
input: &mut BinaryReader<R>,
output: &mut W,
) -> ::std::io::Result<()> {
let mut bytes_left = input.read_u64();
if bytes_left == 0 {
return Ok(());
}
let root = dfs(input);
if let Node::Leaf(x) = root {
output.write_all(&vec![x; bytes_left as usize])?;
return Ok(());
}
let mut node = &root;
while bytes_left > 0 {
match *node {
Node::Leaf(x) => {
output.write_all(&[x])?;
bytes_left -= 1;
node = &root;
}
Node::Parent {
ref left,
ref right,
} => node = if input.read_bit() == 0 { left } else { right },
}
}
Ok(())
}
pub fn decompress_file<W: Write>(input_file: &str, output: &mut W) -> ::std::io::Result<()> {
let f = File::open(input_file)?;
let mut input = BinaryReader::new(BufReader::new(f));
decompress(&mut input, output)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.