hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
0ea98b8ff6557bc51c39476638466716d74721c3 | 31 | //! Decode Binary code into ISA | 31 | 31 | 0.741935 |
14e6e6176f0d36eb4b7e7295d49dc0af5c9f8950 | 6,202 | //! Raw FFI functions for host calls.
//!
//! # WASM vs Native
//! `quill-sys` exposes the same API on both WASM and native
//! targets, but there are internal differences in how
//! host functions are called.
//!
//! On WASM, host calls are `extern "C"` functions
//! that the linker adds as an import for the WASM module.
//!
//! On native, host calls are defined in a vtable struct
//! containing a function pointer for each call. The exported
//! functions in this crate defer to the vtable to make their host calls.
//!
//! Additionally, on native, `quill-sys` exports a `HOST_CONTEXT` constant
//! which is passed to every host call. The host expects this to be the
//! value passed to the `quill_setup` method. Failing to set this
//! constant correctly before making host calls
//! will result in undefined behavior.
use std::mem::MaybeUninit;
use quill_common::{
block::BlockGetResult, entity::QueryData, EntityId, HostComponent, Pointer, PointerMut,
};
// The attribute macro transforms the block into either:
// 1. On WASM, an extern "C" block defining functions imported from the host.
// 2. On native targets, the necessary glue code to use the HOST_VTABLE
// to call host functions.
// The resulting public API is the same for both targets.
#[quill_sys_macros::host_functions]
#[link(wasm_import_module = "quill_01")]
extern "C" {
/// Registers a system.
///
/// Each tick, the system is invoked
/// by calling the plugin's exported `quill_run_system` method.
/// `quill_run_system` is given the `system_data` pointer passed
/// to this host call.
pub fn register_system(system_data: PointerMut<u8>, name_ptr: Pointer<u8>, name_len: u32);
/// Initiates a query. Returns the query data.
///
/// The returned query buffers are allocated within
/// the plugin's bump allocator. They will be
/// freed automatically after the plugin finishes
/// executing the current system.
pub fn entity_query(
components_ptr: Pointer<HostComponent>,
components_len: u32,
query_data: PointerMut<MaybeUninit<QueryData>>,
);
/// Determines whether the given entity exists.
pub fn entity_exists(entity: EntityId) -> bool;
/// Gets a component for an entity.
///
/// Sets `bytes_ptr` to a pointer to the serialized
/// component bytes and `bytes_len` to the number of bytes.
///
/// If the entity does not have the component,
/// then `bytes_ptr` is set to null, and `bytes_len`
/// is left untouched.
pub fn entity_get_component(
entity: EntityId,
component: HostComponent,
bytes_ptr: PointerMut<Pointer<u8>>,
bytes_len: PointerMut<u32>,
);
/// Sets or replaces a component for an entity.
///
/// `bytes_ptr` is a pointer to the serialized
/// component.
///
/// This will overwrite any existing component of the same type.
///
/// Does nothing if `entity` does not exist.
pub fn entity_set_component(
entity: EntityId,
component: HostComponent,
bytes_ptr: Pointer<u8>,
bytes_len: u32,
);
/// Sends a message to an entity.
///
/// The given message should be in the JSON format.
///
/// Does nothing if the entity does not exist or it does not have the `Chat` component.
pub fn entity_send_message(entity: EntityId, message_ptr: Pointer<u8>, message_len: u32);
/// Sends a title to an entity.
///
/// The given `Title` should contain at least a `title` or a `sub_title`
///
/// Does nothing if the entity does not exist or if it does not have the `Chat` component.
pub fn entity_send_title(entity: EntityId, title_ptr: Pointer<u8>, title_len: u32);
/// Creates an empty entity builder.
///
/// This builder is used for creating an ecs-entity
///
/// **This is NOT specifically for a minecraft entity!**
///
pub fn entity_builder_new_empty() -> u32;
/// Creates an entity builder.
///
/// The builder is initialized with the default
/// components for the given `EntityInit`.
///
/// `entity_init` is a `bincode`-serialized `EntityInit`.
pub fn entity_builder_new(
position: Pointer<u8>,
entity_init_ptr: Pointer<u8>,
entity_init_len: u32,
) -> u32;
/// Adds a component to an entity builder.
///
/// `bytes` is the serialized component.
pub fn entity_builder_add_component(
builder: u32,
component: HostComponent,
bytes_ptr: Pointer<u8>,
bytes_len: u32,
);
/// Creates an entity from an entity builder.
///
/// Returns the new entity.
///
/// `builder` is consumed after this call.
/// Reusing it is undefined behavior.
pub fn entity_builder_finish(builder: u32) -> EntityId;
/// Gets the block at the given position.
///
/// Returns `None` if the block's chunk is unloaded
/// or if the Y coordinate is out of bounds.
pub fn block_get(x: i32, y: i32, z: i32) -> BlockGetResult;
/// Sets the block at the given position.
///
/// Returns `true` if successful and `false`
/// if the block's chunk is not loaded or
/// the Y coordinate is out of bounds.
///
/// `block` is the vanilla ID of the block.
pub fn block_set(x: i32, y: i32, z: i32, block: u16) -> bool;
/// Fills the given chunk section with `block`.
///
/// Replaces all existing blocks in the section.
///
/// This is an optimized bulk operation that will be significantly
/// faster than calling [`block_set`] on each block in the chunk section.
///
/// Returns `true` if successful and `false` if the
/// block's chunk is not loaded or the section index is out of bounds.
pub fn block_fill_chunk_section(chunk_x: i32, section_y: u32, chunk_z: i32, block: u16)
-> bool;
/// Sends a custom packet to an entity.
///
/// Does nothing if the entity does not have the `ClientId` component.
pub fn plugin_message_send(
entity: EntityId,
channel_ptr: Pointer<u8>,
channel_len: u32,
data_ptr: Pointer<u8>,
data_len: u32,
);
}
| 34.842697 | 94 | 0.649952 |
f4e1a609cb99b2cc2937b67a6b6bdd3b3665186d | 49 | mod common;
mod council;
mod funder;
mod hunter;
| 9.8 | 12 | 0.755102 |
f9a2c589896f4dcbefc6fa52a599cdde1a16ae8b | 2,250 | #[doc = "Register `AC_ADC_DRC_HPFLGAIN` reader"]
pub struct R(crate::R<AC_ADC_DRC_HPFLGAIN_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<AC_ADC_DRC_HPFLGAIN_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<AC_ADC_DRC_HPFLGAIN_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<AC_ADC_DRC_HPFLGAIN_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `AC_ADC_DRC_HPFLGAIN` writer"]
pub struct W(crate::W<AC_ADC_DRC_HPFLGAIN_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<AC_ADC_DRC_HPFLGAIN_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<AC_ADC_DRC_HPFLGAIN_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<AC_ADC_DRC_HPFLGAIN_SPEC>) -> Self {
W(writer)
}
}
impl W {
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "ADC DRC HPF Gain Low Coef Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ac_adc_drc_hpflgain](index.html) module"]
pub struct AC_ADC_DRC_HPFLGAIN_SPEC;
impl crate::RegisterSpec for AC_ADC_DRC_HPFLGAIN_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ac_adc_drc_hpflgain::R](R) reader structure"]
impl crate::Readable for AC_ADC_DRC_HPFLGAIN_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [ac_adc_drc_hpflgain::W](W) writer structure"]
impl crate::Writable for AC_ADC_DRC_HPFLGAIN_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets AC_ADC_DRC_HPFLGAIN to value 0"]
impl crate::Resettable for AC_ADC_DRC_HPFLGAIN_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 34.615385 | 434 | 0.658667 |
0865ee9bafe1549940d831f12761cc2717c17c5d | 11,969 | #[doc = "Register `AUDIO_CODEC_ADC_CLK` reader"]
pub struct R(crate::R<AUDIO_CODEC_ADC_CLK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<AUDIO_CODEC_ADC_CLK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<AUDIO_CODEC_ADC_CLK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<AUDIO_CODEC_ADC_CLK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `AUDIO_CODEC_ADC_CLK` writer"]
pub struct W(crate::W<AUDIO_CODEC_ADC_CLK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<AUDIO_CODEC_ADC_CLK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<AUDIO_CODEC_ADC_CLK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<AUDIO_CODEC_ADC_CLK_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Gating Clock\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLK_GATING_A {
#[doc = "0: `0`"]
OFF = 0,
#[doc = "1: `1`"]
ON = 1,
}
impl From<CLK_GATING_A> for bool {
#[inline(always)]
fn from(variant: CLK_GATING_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `CLK_GATING` reader - Gating Clock"]
pub struct CLK_GATING_R(crate::FieldReader<bool>);
impl CLK_GATING_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CLK_GATING_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CLK_GATING_A {
match self.bits {
false => CLK_GATING_A::OFF,
true => CLK_GATING_A::ON,
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
**self == CLK_GATING_A::OFF
}
#[doc = "Checks if the value of the field is `ON`"]
#[inline(always)]
pub fn is_on(&self) -> bool {
**self == CLK_GATING_A::ON
}
}
impl core::ops::Deref for CLK_GATING_R {
type Target = crate::FieldReader<bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CLK_GATING` writer - Gating Clock"]
pub struct CLK_GATING_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_GATING_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CLK_GATING_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "`0`"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(CLK_GATING_A::OFF)
}
#[doc = "`1`"]
#[inline(always)]
pub fn on(self) -> &'a mut W {
self.variant(CLK_GATING_A::ON)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31);
self.w
}
}
#[doc = "Clock Source Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CLK_SRC_SEL_A {
#[doc = "0: `0`"]
PLL_AUDIO0_1X = 0,
#[doc = "1: `1`"]
PLL_AUDIO1_DIV2 = 1,
#[doc = "2: `10`"]
PLL_AUDIO1_DIV5 = 2,
}
impl From<CLK_SRC_SEL_A> for u8 {
#[inline(always)]
fn from(variant: CLK_SRC_SEL_A) -> Self {
variant as _
}
}
#[doc = "Field `CLK_SRC_SEL` reader - Clock Source Select"]
pub struct CLK_SRC_SEL_R(crate::FieldReader<u8>);
impl CLK_SRC_SEL_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
CLK_SRC_SEL_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<CLK_SRC_SEL_A> {
match self.bits {
0 => Some(CLK_SRC_SEL_A::PLL_AUDIO0_1X),
1 => Some(CLK_SRC_SEL_A::PLL_AUDIO1_DIV2),
2 => Some(CLK_SRC_SEL_A::PLL_AUDIO1_DIV5),
_ => None,
}
}
#[doc = "Checks if the value of the field is `PLL_AUDIO0_1X`"]
#[inline(always)]
pub fn is_pll_audio0_1x(&self) -> bool {
**self == CLK_SRC_SEL_A::PLL_AUDIO0_1X
}
#[doc = "Checks if the value of the field is `PLL_AUDIO1_DIV2`"]
#[inline(always)]
pub fn is_pll_audio1_div2(&self) -> bool {
**self == CLK_SRC_SEL_A::PLL_AUDIO1_DIV2
}
#[doc = "Checks if the value of the field is `PLL_AUDIO1_DIV5`"]
#[inline(always)]
pub fn is_pll_audio1_div5(&self) -> bool {
**self == CLK_SRC_SEL_A::PLL_AUDIO1_DIV5
}
}
impl core::ops::Deref for CLK_SRC_SEL_R {
type Target = crate::FieldReader<u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CLK_SRC_SEL` writer - Clock Source Select"]
pub struct CLK_SRC_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SRC_SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CLK_SRC_SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "`0`"]
#[inline(always)]
pub fn pll_audio0_1x(self) -> &'a mut W {
self.variant(CLK_SRC_SEL_A::PLL_AUDIO0_1X)
}
#[doc = "`1`"]
#[inline(always)]
pub fn pll_audio1_div2(self) -> &'a mut W {
self.variant(CLK_SRC_SEL_A::PLL_AUDIO1_DIV2)
}
#[doc = "`10`"]
#[inline(always)]
pub fn pll_audio1_div5(self) -> &'a mut W {
self.variant(CLK_SRC_SEL_A::PLL_AUDIO1_DIV5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(7 << 24)) | ((value as u32 & 7) << 24);
self.w
}
}
#[doc = "Factor N\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum FACTOR_N_A {
#[doc = "0: `0`"]
N1 = 0,
#[doc = "1: `1`"]
N2 = 1,
#[doc = "2: `10`"]
N4 = 2,
#[doc = "3: `11`"]
N8 = 3,
}
impl From<FACTOR_N_A> for u8 {
#[inline(always)]
fn from(variant: FACTOR_N_A) -> Self {
variant as _
}
}
#[doc = "Field `FACTOR_N` reader - Factor N"]
pub struct FACTOR_N_R(crate::FieldReader<u8>);
impl FACTOR_N_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
FACTOR_N_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FACTOR_N_A {
match self.bits {
0 => FACTOR_N_A::N1,
1 => FACTOR_N_A::N2,
2 => FACTOR_N_A::N4,
3 => FACTOR_N_A::N8,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `N1`"]
#[inline(always)]
pub fn is_n1(&self) -> bool {
**self == FACTOR_N_A::N1
}
#[doc = "Checks if the value of the field is `N2`"]
#[inline(always)]
pub fn is_n2(&self) -> bool {
**self == FACTOR_N_A::N2
}
#[doc = "Checks if the value of the field is `N4`"]
#[inline(always)]
pub fn is_n4(&self) -> bool {
**self == FACTOR_N_A::N4
}
#[doc = "Checks if the value of the field is `N8`"]
#[inline(always)]
pub fn is_n8(&self) -> bool {
**self == FACTOR_N_A::N8
}
}
impl core::ops::Deref for FACTOR_N_R {
type Target = crate::FieldReader<u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FACTOR_N` writer - Factor N"]
pub struct FACTOR_N_W<'a> {
w: &'a mut W,
}
impl<'a> FACTOR_N_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FACTOR_N_A) -> &'a mut W {
self.bits(variant.into())
}
#[doc = "`0`"]
#[inline(always)]
pub fn n1(self) -> &'a mut W {
self.variant(FACTOR_N_A::N1)
}
#[doc = "`1`"]
#[inline(always)]
pub fn n2(self) -> &'a mut W {
self.variant(FACTOR_N_A::N2)
}
#[doc = "`10`"]
#[inline(always)]
pub fn n4(self) -> &'a mut W {
self.variant(FACTOR_N_A::N4)
}
#[doc = "`11`"]
#[inline(always)]
pub fn n8(self) -> &'a mut W {
self.variant(FACTOR_N_A::N8)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u32 & 3) << 8);
self.w
}
}
#[doc = "Field `FACTOR_M` reader - Factor M"]
pub struct FACTOR_M_R(crate::FieldReader<u8>);
impl FACTOR_M_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
FACTOR_M_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FACTOR_M_R {
type Target = crate::FieldReader<u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FACTOR_M` writer - Factor M"]
pub struct FACTOR_M_W<'a> {
w: &'a mut W,
}
impl<'a> FACTOR_M_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | (value as u32 & 0x1f);
self.w
}
}
impl R {
#[doc = "Bit 31 - Gating Clock"]
#[inline(always)]
pub fn clk_gating(&self) -> CLK_GATING_R {
CLK_GATING_R::new(((self.bits >> 31) & 1) != 0)
}
#[doc = "Bits 24:26 - Clock Source Select"]
#[inline(always)]
pub fn clk_src_sel(&self) -> CLK_SRC_SEL_R {
CLK_SRC_SEL_R::new(((self.bits >> 24) & 7) as u8)
}
#[doc = "Bits 8:9 - Factor N"]
#[inline(always)]
pub fn factor_n(&self) -> FACTOR_N_R {
FACTOR_N_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 0:4 - Factor M"]
#[inline(always)]
pub fn factor_m(&self) -> FACTOR_M_R {
FACTOR_M_R::new((self.bits & 0x1f) as u8)
}
}
impl W {
#[doc = "Bit 31 - Gating Clock"]
#[inline(always)]
pub fn clk_gating(&mut self) -> CLK_GATING_W {
CLK_GATING_W { w: self }
}
#[doc = "Bits 24:26 - Clock Source Select"]
#[inline(always)]
pub fn clk_src_sel(&mut self) -> CLK_SRC_SEL_W {
CLK_SRC_SEL_W { w: self }
}
#[doc = "Bits 8:9 - Factor N"]
#[inline(always)]
pub fn factor_n(&mut self) -> FACTOR_N_W {
FACTOR_N_W { w: self }
}
#[doc = "Bits 0:4 - Factor M"]
#[inline(always)]
pub fn factor_m(&mut self) -> FACTOR_M_W {
FACTOR_M_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "AUDIO_CODEC_ADC Clock Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [audio_codec_adc_clk](index.html) module"]
pub struct AUDIO_CODEC_ADC_CLK_SPEC;
impl crate::RegisterSpec for AUDIO_CODEC_ADC_CLK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [audio_codec_adc_clk::R](R) reader structure"]
impl crate::Readable for AUDIO_CODEC_ADC_CLK_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [audio_codec_adc_clk::W](W) writer structure"]
impl crate::Writable for AUDIO_CODEC_ADC_CLK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets AUDIO_CODEC_ADC_CLK to value 0"]
impl crate::Resettable for AUDIO_CODEC_ADC_CLK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.264059 | 430 | 0.569972 |
1853355f5ce20a32f92d553a6edaa06b4320f764 | 575 | use std::env;
use std::process::Command;
use std::str;
fn main() {
if let Some(rustc) = rustc_minor_version() {
if rustc < 38 {
println!("cargo:rustc-cfg=no_intrinsic_type_name");
}
}
}
fn rustc_minor_version() -> Option<u32> {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next() != Some("rustc 1") {
return None;
}
pieces.next()?.parse().ok()
}
| 25 | 69 | 0.575652 |
e4632d9a4377411d53fff4dc4b76dd85c7798039 | 447 | // variables1.rs
// Make me compile! Execute the command `rustlings hint variables1` if you want a hint :)
// About this `I AM NOT DONE` thing:
// We sometimes encourage you to keep trying things on a given exercise,
// even after you already figured it out. If you got everything working and
// feel ready for the next exercise, remove the `I AM NOT DONE` comment below.
fn main() {
let x: u32 = 5;
println!("x has the value {}", x);
}
| 34.384615 | 89 | 0.695749 |
5d7b4fb347df4848d8fdd6953d20c001b150b23c | 7,838 | use rand::{rngs::OsRng, Rng};
use std::f32::consts;
use std::iter;
const TWO_PI: f32 = consts::PI * 2_f32;
const TWO_THIRDS_PI: f32 = consts::FRAC_PI_3 * 2_f32;
const FOUR_THIRDS_PI: f32 = consts::FRAC_PI_3 * 4_f32;
const FIVE_THIRDS_PI: f32 = consts::FRAC_PI_3 * 5_f32;
/// Wrapper of three byte values corresponding to RGB for a single pixel.
pub struct RGB(pub u8, pub u8, pub u8);
/// Value in [0, 2π) corresponding to a hue value (in radians) in the HSL color space.
#[derive(Clone, Copy)]
pub struct Hue(f32);
impl Hue {
/// Constructs a new Hue.
///
/// # Arguments
///
/// * `hue` - the new Hue value.
pub const fn new(hue: f32) -> Self {
Self(hue)
}
/// Returns the internal f32 value corresponding to the Hue.
pub const fn get(self) -> f32 {
self.0
}
/// Increments the internal value by the specificied delta.
///
/// If the new value lies outside the valid Hue range, it is adjusted accordingly by one period.
///
/// # Arguments
///
/// * `dh` - the desired change to the internal value.
fn tick(&mut self, dh: f32) {
self.0 = (self.0 + dh) % TWO_PI;
}
/// Converts the Hue to its corresponding RGB value.
///
/// Sets saturation to 100% and lightness to 50% to get the Hue's truest color value.
///
/// Derived from [`RapidTables` HSL to RGB color conversion](https://www.rapidtables.com/convert/color/hsl-to-rgb.html).
pub fn to_rgb(self) -> RGB {
let hue = self.0;
if hue < consts::PI {
if hue < consts::FRAC_PI_3 {
RGB(u8::MAX, (255_f32 * hue / consts::FRAC_PI_3) as u8, 0)
} else if hue < TWO_THIRDS_PI {
RGB(
(255_f32 * (2_f32 - hue / consts::FRAC_PI_3)) as u8,
u8::MAX,
0,
)
} else {
RGB(
0,
u8::MAX,
(255_f32 * (hue / consts::FRAC_PI_3 - 2_f32)) as u8,
)
}
} else if hue < FOUR_THIRDS_PI {
RGB(
0,
(255_f32 * (4_f32 - hue / consts::FRAC_PI_3)) as u8,
u8::MAX,
)
} else if hue < FIVE_THIRDS_PI {
RGB(
(255_f32 * (hue / consts::FRAC_PI_3 - 4_f32)) as u8,
0,
u8::MAX,
)
} else {
RGB(
u8::MAX,
0,
(255_f32 * (6_f32 - hue / consts::FRAC_PI_3)) as u8,
)
}
}
}
/// A Source in the Spectrum canvas which influences the color of neighboring pixels.
pub struct Source {
/// The x-coordinate of the Source in the Spectrum canvas.
x: f32,
/// The y-coordinate of the Source in the Spectrum canvas.
y: f32,
/// The internal Hue value of the Source.
hue: Hue,
/// The width of the Spectrum canvas.
canvas_width: f32,
/// The height of the spectrum canvas:
canvas_height: f32,
/// The rate of movement in the x direction.
dx: f32,
/// The rate of movement in the y direction.
dy: f32,
/// The rate of change in the Source's Hue.
dh: f32,
/// The cosine of the internal Hue value.
hue_cos: f32,
/// The sine of the internal Hue value.
hue_sin: f32,
}
impl Source {
/// Constructs a new Source.
///
/// Non-specified paramaters are generated at random.
///
/// # Arguments
///
/// * `canvas_width` - the width of the Spectrum canvas.
/// * `canvas_height` - the height of the Spectrum canvas.
/// * `movement_speed` - the range of the Source's movement speed (`dx`, `dy`)
/// * `color_speed` - the range of the Source's color speed (`dh`)
pub fn new(
canvas_width: f32,
canvas_height: f32,
movement_speed: f32,
color_speed: f32,
) -> Self {
let hue = Hue(OsRng.gen_range(0.0_f32, TWO_PI));
let hue_val = hue.get();
let hue_cos = hue_val.cos();
let hue_sin = hue_val.sin();
Self {
x: OsRng.gen_range(0.0_f32, canvas_width),
y: OsRng.gen_range(0.0_f32, canvas_height),
hue,
canvas_width,
canvas_height,
dx: OsRng.gen_range(-movement_speed / 2_f32, movement_speed / 2_f32),
dy: OsRng.gen_range(-movement_speed / 2_f32, movement_speed / 2_f32),
dh: OsRng.gen_range(-color_speed / 2_f32, color_speed / 2_f32),
hue_cos,
hue_sin,
}
}
/// Returns the x-coordinate of the Source.
pub const fn x(&self) -> f32 {
self.x
}
/// Returns the y-coordinate of the Source.
pub const fn y(&self) -> f32 {
self.y
}
/// Returns the cosine of the Source's hue.
pub const fn hue_cos(&self) -> f32 {
self.hue_cos
}
/// Returns the sine of the Source's hue.
pub const fn hue_sin(&self) -> f32 {
self.hue_sin
}
/// Increments the Source by one frame.
///
/// The internal hue is incremented by the Source's `dh` value.
///
/// The Source's position is incremented by `dx` and `dy`, with border collisions behaving as a bounce.
fn tick(&mut self) {
self.hue.tick(self.dh);
let hue_val = self.hue.get();
self.hue_cos = hue_val.cos();
self.hue_sin = hue_val.sin();
self.x += self.dx;
self.y += self.dy;
if self.x <= 0_f32 {
self.x *= -1_f32;
self.dx *= -1_f32;
} else if self.x >= self.canvas_width {
self.x = self.canvas_width - (self.x - self.canvas_width);
self.dx *= -1_f32;
}
if self.y <= 0_f32 {
self.y *= -1_f32;
self.dy *= -1_f32;
} else if self.y >= self.canvas_height {
self.y = self.canvas_height - (self.y - self.canvas_height);
self.dy *= -1_f32;
}
}
}
/// The shared data belonging to both Spectrum implementations.
pub struct BaseSpectrum {
/// The width of the Spectrum canvas.
width: u32,
/// The height of the Spectrum canvas.
height: u32,
/// A vector containing the Spectrum's sources.
sources: Vec<Source>,
}
impl BaseSpectrum {
/// Constructs a new `BaseSpectrum`.
///
/// # Arguments
///
/// * `width` - the width of the `BaseSpectrum`.
/// * `height` - the height of the `BaseSpectrum`.
/// * `num_sources` - the number of Sources to generate.
/// * `movement_speed` - the range of each Source's movement speed (`dx`, `dy`)
/// * `color_speed` - the range of each Source's color speed (`dh`)
pub fn new(
width: u32,
height: u32,
num_sources: u32,
movement_speed: f32,
color_speed: f32,
) -> Self {
let width_float = width as f32;
let height_float = height as f32;
Self {
width,
height,
sources: iter::repeat(())
.map(|()| Source::new(width_float, height_float, movement_speed, color_speed))
.take(num_sources as usize)
.collect(),
}
}
/// Returns the width of the `BaseSpectrum`.
pub const fn width(&self) -> u32 {
self.width
}
/// Returns the height of the `BaseSpectrum`.
pub const fn height(&self) -> u32 {
self.height
}
/// Returns a reference to the vector containing the `BaseSpectrum`'s Sources.
pub const fn sources(&self) -> &Vec<Source> {
&self.sources
}
/// Increments the `BaseSpectrum`'s sources by one frame.
pub fn tick(&mut self) {
for source in &mut self.sources {
source.tick();
}
}
}
| 28.710623 | 124 | 0.540444 |
f7a1b46d277d4650c443e92631f5e09ed5c21b10 | 14 | pub mod grid;
| 7 | 13 | 0.714286 |
acf904a8ab475c31a7ef1684ea82c6bdd19584c2 | 304 | #[doc = "Reader of register TEMP"]
pub type R = crate::R<u32, super::TEMP>;
#[doc = "Reader of field `INT`"]
pub type INT_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 8:16 - INT"]
#[inline(always)]
pub fn int(&self) -> INT_R {
INT_R::new(((self.bits >> 8) & 0x01ff) as u16)
}
}
| 25.333333 | 54 | 0.549342 |
50e1781d2cb511df6bdf4580fa186a84ba182a25 | 3,579 | use crate::utils::{in_macro, snippet, span_lint_and_then};
use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
use rustc::{declare_lint_pass, declare_tool_lint};
use rustc_errors::Applicability;
use syntax::ast::*;
declare_clippy_lint! {
/// **What it does:** Checks for constants with an explicit `'static` lifetime.
///
/// **Why is this bad?** Adding `'static` to every reference can create very
/// complicated types.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```ignore
/// const FOO: &'static [(&'static str, &'static str, fn(&Bar) -> bool)] =
/// &[...]
/// ```
/// This code can be rewritten as
/// ```ignore
/// const FOO: &[(&str, &str, fn(&Bar) -> bool)] = &[...]
/// ```
pub CONST_STATIC_LIFETIME,
style,
"Using explicit `'static` lifetime for constants when elision rules would allow omitting them."
}
declare_lint_pass!(StaticConst => [CONST_STATIC_LIFETIME]);
impl StaticConst {
// Recursively visit types
fn visit_type(&mut self, ty: &Ty, cx: &EarlyContext<'_>) {
match ty.node {
// Be careful of nested structures (arrays and tuples)
TyKind::Array(ref ty, _) => {
self.visit_type(&*ty, cx);
},
TyKind::Tup(ref tup) => {
for tup_ty in tup {
self.visit_type(&*tup_ty, cx);
}
},
// This is what we are looking for !
TyKind::Rptr(ref optional_lifetime, ref borrow_type) => {
// Match the 'static lifetime
if let Some(lifetime) = *optional_lifetime {
match borrow_type.ty.node {
TyKind::Path(..) | TyKind::Slice(..) | TyKind::Array(..) | TyKind::Tup(..) => {
if lifetime.ident.name == "'static" {
let snip = snippet(cx, borrow_type.ty.span, "<type>");
let sugg = format!("&{}", snip);
span_lint_and_then(
cx,
CONST_STATIC_LIFETIME,
lifetime.ident.span,
"Constants have by default a `'static` lifetime",
|db| {
db.span_suggestion(
ty.span,
"consider removing `'static`",
sugg,
Applicability::MachineApplicable, //snippet
);
},
);
}
},
_ => {},
}
}
self.visit_type(&*borrow_type.ty, cx);
},
TyKind::Slice(ref ty) => {
self.visit_type(ty, cx);
},
_ => {},
}
}
}
impl EarlyLintPass for StaticConst {
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
if !in_macro(item.span) {
// Match only constants...
if let ItemKind::Const(ref var_type, _) = item.node {
self.visit_type(var_type, cx);
}
}
}
// Don't check associated consts because `'static` cannot be elided on those (issue #2438)
}
| 38.074468 | 103 | 0.439229 |
033a1a4aa75501b1ae8782c9b4b09dbcfb897e4a | 13,387 | // * This file is part of the uutils coreutils package.
// *
// * (c) Alex Lyon <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) bitor ulong
#[macro_use]
extern crate uucore;
use clap::{App, Arg};
use remove_dir_all::remove_dir_all;
use std::collections::VecDeque;
use std::fs;
use std::io::{stderr, stdin, BufRead, Write};
use std::ops::BitOr;
use std::path::Path;
use walkdir::{DirEntry, WalkDir};
#[derive(Eq, PartialEq, Clone, Copy)]
enum InteractiveMode {
None,
Once,
Always,
}
struct Options {
force: bool,
interactive: InteractiveMode,
#[allow(dead_code)]
one_fs: bool,
preserve_root: bool,
recursive: bool,
dir: bool,
verbose: bool,
}
static ABOUT: &str = "Remove (unlink) the FILE(s)";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static OPT_DIR: &str = "dir";
static OPT_INTERACTIVE: &str = "interactive";
static OPT_FORCE: &str = "force";
static OPT_NO_PRESERVE_ROOT: &str = "no-preserve-root";
static OPT_ONE_FILE_SYSTEM: &str = "one-file-system";
static OPT_PRESERVE_ROOT: &str = "preserve-root";
static OPT_PROMPT: &str = "prompt";
static OPT_PROMPT_MORE: &str = "prompt-more";
static OPT_RECURSIVE: &str = "recursive";
static OPT_RECURSIVE_R: &str = "recursive_R";
static OPT_VERBOSE: &str = "verbose";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... FILE...", executable!())
}
fn get_long_usage() -> String {
String::from(
"By default, rm does not remove directories. Use the --recursive (-r or -R)
option to remove each listed directory, too, along with all of its contents
To remove a file whose name starts with a '-', for example '-foo',
use one of these commands:
rm -- -foo
rm ./-foo
Note that if you use rm to remove a file, it might be possible to recover
some of its contents, given sufficient expertise and/or time. For greater
assurance that the contents are truly unrecoverable, consider using shred.",
)
}
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let long_usage = get_long_usage();
let matches = App::new(executable!())
.version(VERSION)
.about(ABOUT)
.usage(&usage[..])
.after_help(&long_usage[..])
.arg(
Arg::with_name(OPT_FORCE)
.short("f")
.long(OPT_FORCE)
.multiple(true)
.help("ignore nonexistent files and arguments, never prompt")
)
.arg(
Arg::with_name(OPT_PROMPT)
.short("i")
.long("prompt before every removal")
)
.arg(
Arg::with_name(OPT_PROMPT_MORE)
.short("I")
.help("prompt once before removing more than three files, or when removing recursively. Less intrusive than -i, while still giving some protection against most mistakes")
)
.arg(
Arg::with_name(OPT_INTERACTIVE)
.long(OPT_INTERACTIVE)
.help("prompt according to WHEN: never, once (-I), or always (-i). Without WHEN, prompts always")
.value_name("WHEN")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_ONE_FILE_SYSTEM)
.long(OPT_ONE_FILE_SYSTEM)
.help("when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument (NOT IMPLEMENTED)")
)
.arg(
Arg::with_name(OPT_NO_PRESERVE_ROOT)
.long(OPT_NO_PRESERVE_ROOT)
.help("do not treat '/' specially")
)
.arg(
Arg::with_name(OPT_PRESERVE_ROOT)
.long(OPT_PRESERVE_ROOT)
.help("do not remove '/' (default)")
)
.arg(
Arg::with_name(OPT_RECURSIVE).short("r")
.long(OPT_RECURSIVE)
.help("remove directories and their contents recursively")
)
.arg(
// To mimic GNU's behavior we also want the '-R' flag. However, using clap's
// alias method 'visible_alias("R")' would result in a long '--R' flag.
Arg::with_name(OPT_RECURSIVE_R).short("R")
.help("Equivalent to -r")
)
.arg(
Arg::with_name(OPT_DIR)
.short("d")
.long(OPT_DIR)
.help("remove empty directories")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
Arg::with_name(ARG_FILES)
.multiple(true)
.takes_value(true)
.min_values(1)
)
.get_matches_from(args);
let files: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
let force = matches.is_present(OPT_FORCE);
if files.is_empty() && !force {
// Still check by hand and not use clap
// Because "rm -f" is a thing
show_error!("missing an argument");
show_error!("for help, try '{0} --help'", executable!());
return 1;
} else {
let options = Options {
force,
interactive: {
if matches.is_present(OPT_PROMPT) {
InteractiveMode::Always
} else if matches.is_present(OPT_PROMPT_MORE) {
InteractiveMode::Once
} else if matches.is_present(OPT_INTERACTIVE) {
match &matches.value_of(OPT_INTERACTIVE).unwrap()[..] {
"none" => InteractiveMode::None,
"once" => InteractiveMode::Once,
"always" => InteractiveMode::Always,
val => crash!(1, "Invalid argument to interactive ({})", val),
}
} else {
InteractiveMode::None
}
},
one_fs: matches.is_present(OPT_ONE_FILE_SYSTEM),
preserve_root: !matches.is_present(OPT_NO_PRESERVE_ROOT),
recursive: matches.is_present(OPT_RECURSIVE) || matches.is_present(OPT_RECURSIVE_R),
dir: matches.is_present(OPT_DIR),
verbose: matches.is_present(OPT_VERBOSE),
};
if options.interactive == InteractiveMode::Once && (options.recursive || files.len() > 3) {
let msg = if options.recursive {
"Remove all arguments recursively? "
} else {
"Remove all arguments? "
};
if !prompt(msg) {
return 0;
}
}
if remove(files, options) {
return 1;
}
}
0
}
// TODO: implement one-file-system (this may get partially implemented in walkdir)
fn remove(files: Vec<String>, options: Options) -> bool {
let mut had_err = false;
for filename in &files {
let file = Path::new(filename);
had_err = match file.symlink_metadata() {
Ok(metadata) => {
if metadata.is_dir() {
handle_dir(file, &options)
} else if is_symlink_dir(&metadata) {
remove_dir(file, &options)
} else {
remove_file(file, &options)
}
}
Err(_e) => {
// TODO: actually print out the specific error
// TODO: When the error is not about missing files
// (e.g., permission), even rm -f should fail with
// outputting the error, but there's no easy eay.
if !options.force {
show_error!("cannot remove '{}': No such file or directory", filename);
true
} else {
false
}
}
}
.bitor(had_err);
}
had_err
}
fn handle_dir(path: &Path, options: &Options) -> bool {
let mut had_err = false;
let is_root = path.has_root() && path.parent().is_none();
if options.recursive && (!is_root || !options.preserve_root) {
if options.interactive != InteractiveMode::Always {
// we need the extra crate because apparently fs::remove_dir_all() does not function
// correctly on Windows
if let Err(e) = remove_dir_all(path) {
had_err = true;
show_error!("could not remove '{}': {}", path.display(), e);
}
} else {
let mut dirs: VecDeque<DirEntry> = VecDeque::new();
for entry in WalkDir::new(path) {
match entry {
Ok(entry) => {
let file_type = entry.file_type();
if file_type.is_dir() {
dirs.push_back(entry);
} else {
had_err = remove_file(entry.path(), options).bitor(had_err);
}
}
Err(e) => {
had_err = true;
show_error!("recursing in '{}': {}", path.display(), e);
}
}
}
for dir in dirs.iter().rev() {
had_err = remove_dir(dir.path(), options).bitor(had_err);
}
}
} else if options.dir && (!is_root || !options.preserve_root) {
had_err = remove_dir(path, options).bitor(had_err);
} else if options.recursive {
show_error!("could not remove directory '{}'", path.display());
had_err = true;
} else {
show_error!(
"cannot remove '{}': Is a directory", // GNU's rm error message does not include help
path.display()
);
had_err = true;
}
had_err
}
fn remove_dir(path: &Path, options: &Options) -> bool {
let response = if options.interactive == InteractiveMode::Always {
prompt_file(path, true)
} else {
true
};
if response {
if let Ok(mut read_dir) = fs::read_dir(path) {
if options.dir || options.recursive {
if read_dir.next().is_none() {
match fs::remove_dir(path) {
Ok(_) => {
if options.verbose {
println!("removed directory '{}'", path.display());
}
}
Err(e) => {
show_error!("cannot remove '{}': {}", path.display(), e);
return true;
}
}
} else {
// directory can be read but is not empty
show_error!("cannot remove '{}': Directory not empty", path.display());
return true;
}
} else {
// called to remove a symlink_dir (windows) without "-r"/"-R" or "-d"
show_error!("cannot remove '{}': Is a directory", path.display());
return true;
}
} else {
// GNU's rm shows this message if directory is empty but not readable
show_error!("cannot remove '{}': Directory not empty", path.display());
return true;
}
}
false
}
fn remove_file(path: &Path, options: &Options) -> bool {
let response = if options.interactive == InteractiveMode::Always {
prompt_file(path, false)
} else {
true
};
if response {
match fs::remove_file(path) {
Ok(_) => {
if options.verbose {
println!("removed '{}'", path.display());
}
}
Err(e) => {
show_error!("removing '{}': {}", path.display(), e);
return true;
}
}
}
false
}
fn prompt_file(path: &Path, is_dir: bool) -> bool {
if is_dir {
prompt(&(format!("rm: remove directory '{}'? ", path.display())))
} else {
prompt(&(format!("rm: remove file '{}'? ", path.display())))
}
}
fn prompt(msg: &str) -> bool {
let _ = stderr().write_all(msg.as_bytes());
let _ = stderr().flush();
let mut buf = Vec::new();
let stdin = stdin();
let mut stdin = stdin.lock();
#[allow(clippy::match_like_matches_macro)]
// `matches!(...)` macro not stabilized until rust v1.42
match stdin.read_until(b'\n', &mut buf) {
Ok(x) if x > 0 => match buf[0] {
b'y' | b'Y' => true,
_ => false,
},
_ => false,
}
}
#[cfg(not(windows))]
fn is_symlink_dir(_metadata: &fs::Metadata) -> bool {
false
}
#[cfg(windows)]
use std::os::windows::prelude::MetadataExt;
#[cfg(windows)]
fn is_symlink_dir(metadata: &fs::Metadata) -> bool {
use std::os::raw::c_ulong;
pub type DWORD = c_ulong;
pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10;
metadata.file_type().is_symlink()
&& ((metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY) != 0)
}
| 32.731051 | 184 | 0.521924 |
f7a269fdc2fbbce33165a49661705787bb256284 | 15,519 | /*
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
//! Toml-based configuration for use with Capsule applications.
//!
//! # Example
//!
//! A configuration from our [`pktdump`] example:
//! ```
//! app_name = "pktdump"
//! master_core = 0
//! duration = 5
//!
//! [mempool]
//! capacity = 65535
//! cache_size = 256
//!
//! [[ports]]
//! name = "eth1"
//! device = "net_pcap0"
//! args = "rx_pcap=tcp4.pcap,tx_iface=lo"
//! cores = [0]
//!
//! [[ports]]
//! name = "eth2"
//! device = "net_pcap1"
//! args = "rx_pcap=tcp6.pcap,tx_iface=lo"
//! cores = [0]
//! ```
//!
//! [`pktdump`]: https://github.com/capsule-rs/capsule/tree/master/examples/pktdump
use crate::dpdk::CoreId;
use crate::net::{Ipv4Cidr, Ipv6Cidr, MacAddr};
use clap::{clap_app, crate_version};
use failure::Fallible;
use regex::Regex;
use serde::{de, Deserialize, Deserializer};
use std::fmt;
use std::fs;
use std::str::FromStr;
use std::time::Duration;
// make `CoreId` serde deserializable.
impl<'de> Deserialize<'de> for CoreId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let i = usize::deserialize(deserializer)?;
Ok(CoreId::new(i))
}
}
// make `MacAddr` serde deserializable.
impl<'de> Deserialize<'de> for MacAddr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
MacAddr::from_str(&s).map_err(de::Error::custom)
}
}
// make `Ipv4Cidr` serde deserializable.
impl<'de> Deserialize<'de> for Ipv4Cidr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ipv4Cidr::from_str(&s).map_err(de::Error::custom)
}
}
// make `Ipv6Cidr` serde deserializable.
impl<'de> Deserialize<'de> for Ipv6Cidr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ipv6Cidr::from_str(&s).map_err(de::Error::custom)
}
}
/// Deserializes a duration from seconds expressed as `u64`.
pub fn duration_from_secs<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
let secs = u64::deserialize(deserializer)?;
Ok(Duration::from_secs(secs))
}
/// Deserializes an option of duration from seconds expressed as `u64`.
pub fn duration_option_from_secs<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
D: Deserializer<'de>,
{
// for now this is the cleanest way to deserialize an option, till a better
// way is implemented, https://github.com/serde-rs/serde/issues/723
#[derive(Deserialize)]
struct Wrapper(#[serde(deserialize_with = "duration_from_secs")] Duration);
let option = Option::deserialize(deserializer)?.and_then(|Wrapper(dur)| {
if dur.as_secs() > 0 {
Some(dur)
} else {
None
}
});
Ok(option)
}
/// Runtime configuration settings.
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeConfig {
/// Application name. This must be unique if you want to run multiple
/// DPDK applications on the same system.
pub app_name: String,
/// Indicating whether the process is a secondary process. Secondary
/// process cannot initialize shared memory, but can attach to pre-
/// initialized shared memory by the primary process and create objects
/// in it. Defaults to `false`.
#[serde(default)]
pub secondary: bool,
/// Application group name. Use this to group primary and secondary
/// processes together in a multi-process setup; and allow them to share
/// the same memory regions. The default value is the `app_name`. Each
/// process works independently.
#[serde(default)]
pub app_group: Option<String>,
/// The identifier of the master core. This is the core the main thread
/// will run on.
pub master_core: CoreId,
/// Additional cores that are available to the application, and can be
/// used for running general tasks. Packet pipelines cannot be run on
/// these cores unless the core is also assigned to a port separately.
/// Defaults to empty list.
#[serde(default)]
pub cores: Vec<CoreId>,
/// Per mempool settings. On a system with multiple sockets, aka NUMA
/// nodes, one mempool will be allocated for each socket the apllication
/// uses.
#[serde(default)]
pub mempool: MempoolConfig,
/// The ports to use for the application. Must have at least one.
pub ports: Vec<PortConfig>,
/// Additional DPDK [`parameters`] to pass on for EAL initialization. When
/// set, the values are passed through as is without validation.
///
/// [`parameters`]: https://doc.dpdk.org/guides/linux_gsg/linux_eal_parameters.html
#[serde(default)]
pub dpdk_args: Option<String>,
/// If set, the application will stop after the duration expires. Useful
/// for setting a timeout for integration tests.
#[serde(default, deserialize_with = "duration_option_from_secs")]
pub duration: Option<Duration>,
}
impl RuntimeConfig {
/// Returns all the cores assigned to the runtime.
pub(crate) fn all_cores(&self) -> Vec<CoreId> {
let mut cores = vec![];
cores.push(self.master_core);
cores.extend(self.cores.iter());
self.ports.iter().for_each(|port| {
cores.extend(port.cores.iter());
});
cores.sort();
cores.dedup();
cores
}
/// Extracts the EAL arguments from runtime settings.
pub(crate) fn to_eal_args(&self) -> Vec<String> {
let mut eal_args = vec![];
// adds the app name
eal_args.push(self.app_name.clone());
let proc_type = if self.secondary {
"secondary".to_owned()
} else {
"primary".to_owned()
};
// adds the proc type
eal_args.push("--proc-type".to_owned());
eal_args.push(proc_type);
// adds the mem file prefix
let prefix = self.app_group.as_ref().unwrap_or(&self.app_name);
eal_args.push("--file-prefix".to_owned());
eal_args.push(prefix.clone());
// adds all the ports
let pcie = Regex::new(r"^\d{4}:\d{2}:\d{2}\.\d$").unwrap();
self.ports.iter().for_each(|port| {
if pcie.is_match(port.device.as_str()) {
eal_args.push("--pci-whitelist".to_owned());
eal_args.push(port.device.clone());
} else {
let vdev = if let Some(args) = &port.args {
format!("{},{}", port.device, args)
} else {
port.device.clone()
};
eal_args.push("--vdev".to_owned());
eal_args.push(vdev);
}
});
// adds the master core
eal_args.push("--master-lcore".to_owned());
eal_args.push(self.master_core.raw().to_string());
// limits the EAL to only the master core. actual threads are
// managed by the runtime not the EAL.
eal_args.push("-l".to_owned());
eal_args.push(self.master_core.raw().to_string());
// adds additional DPDK args
if let Some(args) = &self.dpdk_args {
eal_args.extend(args.split_ascii_whitespace().map(str::to_owned));
}
eal_args
}
/// Returns the number of KNI enabled ports
pub(crate) fn num_knis(&self) -> usize {
self.ports.iter().filter(|p| p.kni).count()
}
}
impl fmt::Debug for RuntimeConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("runtime");
d.field("app_name", &self.app_name)
.field("secondary", &self.secondary)
.field(
"app_group",
self.app_group.as_ref().unwrap_or(&self.app_name),
)
.field("master_core", &self.master_core)
.field("cores", &self.cores)
.field("mempool", &self.mempool)
.field("ports", &self.ports);
if let Some(dpdk_args) = &self.dpdk_args {
d.field("dpdk_args", dpdk_args);
}
if let Some(duration) = &self.duration {
d.field("duration", duration);
}
d.finish()
}
}
/// Mempool configuration settings.
#[derive(Clone, Deserialize)]
pub struct MempoolConfig {
/// The maximum number of Mbufs the mempool can allocate. The optimum
/// size (in terms of memory usage) is when n is a power of two minus
/// one. Defaults to `65535` or `2 ^ 16 - 1`.
#[serde(default = "default_capacity")]
pub capacity: usize,
/// The size of the per core object cache. If cache_size is non-zero,
/// the library will try to limit the accesses to the common lockless
/// pool. The cache can be disabled if the argument is set to 0. Defaults
/// to `0`.
#[serde(default = "default_cache_size")]
pub cache_size: usize,
}
fn default_capacity() -> usize {
65535
}
fn default_cache_size() -> usize {
0
}
impl Default for MempoolConfig {
fn default() -> Self {
MempoolConfig {
capacity: default_capacity(),
cache_size: default_cache_size(),
}
}
}
impl fmt::Debug for MempoolConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("mempool")
.field("capacity", &self.capacity)
.field("cache_size", &self.cache_size)
.finish()
}
}
/// Port configuration settings.
#[derive(Clone, Deserialize)]
pub struct PortConfig {
/// The application assigned logical name of the port.
///
/// For applications with more than one port, this name can be used to
/// identifer the port.
pub name: String,
/// The device name of the port. It can be the following formats,
///
/// * PCIe address, for example `0000:02:00.0`
/// * DPDK virtual device, for example `net_[pcap0|null0|tap0]`
pub device: String,
/// Additional arguments to configure a virtual device.
#[serde(default)]
pub args: Option<String>,
/// The cores assigned to the port for running the pipelines. The values
/// can overlap with the runtime cores.
pub cores: Vec<CoreId>,
/// The receive queue capacity. Defaults to `128`.
#[serde(default = "default_port_rxd")]
pub rxd: usize,
/// The transmit queue capacity. Defaults to `128`.
#[serde(default = "default_port_txd")]
pub txd: usize,
/// Whether promiscuous mode is enabled for this port. Defaults to `false`.
#[serde(default)]
pub promiscuous: bool,
/// Whether multicast packet reception is enabled for this port. Defaults
/// to `true`.
#[serde(default = "default_multicast_mode")]
pub multicast: bool,
/// Whether kernel NIC interface is enabled for this port. with KNI, this
/// port can exchange packets with the kernel networking stack. Defaults
/// to `false`.
#[serde(default)]
pub kni: bool,
}
fn default_port_rxd() -> usize {
128
}
fn default_port_txd() -> usize {
128
}
fn default_multicast_mode() -> bool {
true
}
impl fmt::Debug for PortConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("port");
d.field("name", &self.name);
d.field("device", &self.device);
if let Some(args) = &self.args {
d.field("args", args);
}
d.field("cores", &self.cores)
.field("rxd", &self.rxd)
.field("txd", &self.txd)
.field("promiscuous", &self.promiscuous)
.field("multicast", &self.multicast)
.field("kni", &self.kni)
.finish()
}
}
/// Loads the app config from a TOML file.
///
/// # Example
///
/// ```
/// home$ ./myapp -f config.toml
/// ```
pub fn load_config() -> Fallible<RuntimeConfig> {
let matches = clap_app!(capsule =>
(version: crate_version!())
(@arg file: -f --file +required +takes_value "configuration file")
)
.get_matches();
let path = matches.value_of("file").unwrap();
let content = fs::read_to_string(path)?;
toml::from_str(&content).map_err(|err| err.into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_defaults() {
const CONFIG: &str = r#"
app_name = "myapp"
master_core = 0
[[ports]]
name = "eth0"
device = "0000:00:01.0"
cores = [2, 3]
"#;
let config: RuntimeConfig = toml::from_str(CONFIG).unwrap();
assert_eq!(false, config.secondary);
assert_eq!(None, config.app_group);
assert!(config.cores.is_empty());
assert_eq!(None, config.dpdk_args);
assert_eq!(default_capacity(), config.mempool.capacity);
assert_eq!(default_cache_size(), config.mempool.cache_size);
assert_eq!(None, config.ports[0].args);
assert_eq!(default_port_rxd(), config.ports[0].rxd);
assert_eq!(default_port_txd(), config.ports[0].txd);
assert_eq!(false, config.ports[0].promiscuous);
assert_eq!(default_multicast_mode(), config.ports[0].multicast);
assert_eq!(false, config.ports[0].kni);
}
#[test]
fn config_to_eal_args() {
const CONFIG: &str = r#"
app_name = "myapp"
secondary = false
app_group = "mygroup"
master_core = 0
cores = [1]
dpdk_args = "-v --log-level eal:8"
[mempool]
capacity = 255
cache_size = 16
[[ports]]
name = "eth0"
device = "0000:00:01.0"
cores = [2, 3]
rxd = 32
txd = 32
[[ports]]
name = "eth1"
device = "net_pcap0"
args = "rx=lo,tx=lo"
cores = [0, 4]
rxd = 32
txd = 32
"#;
let config: RuntimeConfig = toml::from_str(CONFIG).unwrap();
assert_eq!(
&[
"myapp",
"--proc-type",
"primary",
"--file-prefix",
"mygroup",
"--pci-whitelist",
"0000:00:01.0",
"--vdev",
"net_pcap0,rx=lo,tx=lo",
"--master-lcore",
"0",
"-l",
"0",
"-v",
"--log-level",
"eal:8"
],
config.to_eal_args().as_slice(),
)
}
}
| 30.192607 | 95 | 0.584509 |
21f75099bbfb184eb5feb108fc22e8bb47b68c10 | 4,107 | #![no_std]
//! # MiniMQ
//! Provides a minimal MQTTv5 client and message parsing for the MQTT version 5 protocol.
//!
//! This crate provides a minimalistic MQTT 5 client that can be used to publish topics to an MQTT
//! broker and subscribe to receive messages on specific topics.
//!
//! # Limitations
//! This library does not currently support the following elements:
//! * Quality-of-service `ExactlyOnce`
//! * Session timeouts
//! * Server keep alive timeouts (ping)
//! * Bulk subscriptions
//! * Server Authentication
//! * Encryption
//! * Topic aliases
//!
//! # Requirements
//! This library requires that the user provide it an object that implements a basic TcpStack that
//! can be used as the transport layer for MQTT communications.
//!
//! The maximum message size is configured through generic parameters. This allows the maximum
//! message size to be configured by the user. Note that buffers will be allocated on the stack, so it
//! is important to select a size such that the stack does not overflow.
//!
//! # Example
//! Below is a sample snippet showing how this library is used. An example application is provided
//! in `examples/minimq-stm32h7`, which targets the Nucleo-H743 development board with an external
//! temperature sensor installed.
//!
//! ```no_run
//! use minimq::{Minimq, QoS};
//!
//! // Construct an MQTT client with a maximum packet size of 256 bytes.
//! // Connect to a broker at localhost - Use a client ID of "test".
//! let mut mqtt: Minimq<_, _, 256, 16> = Minimq::new(
//! "127.0.0.1".parse().unwrap(),
//! "test",
//! std_embedded_nal::Stack::default(),
//! std_embedded_time::StandardClock::default()).unwrap();
//!
//! let mut subscribed = false;
//!
//! loop {
//! if mqtt.client.is_connected() && !subscribed {
//! mqtt.client.subscribe("topic", &[]).unwrap();
//! subscribed = true;
//! }
//!
//! mqtt.poll(|client, topic, message, properties| {
//! match topic {
//! "topic" => {
//! println!("{:?}", message);
//! client.publish("echo", message, QoS::AtMostOnce, &[]).unwrap();
//! },
//! topic => println!("Unknown topic: {}", topic),
//! };
//! }).unwrap();
//! }
//! ```
pub(crate) mod de;
pub(crate) mod ser;
mod message_types;
mod mqtt_client;
mod network_manager;
mod properties;
mod session_state;
use message_types::MessageType;
pub use properties::Property;
pub use embedded_nal;
pub use embedded_time;
pub use mqtt_client::{Minimq, QoS};
#[cfg(feature = "logging")]
pub(crate) use log::{debug, error, info, warn};
/// Errors that are specific to the MQTT protocol implementation.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ProtocolError {
Bounds,
DataSize,
Invalid,
Failed,
PacketSize,
MalformedPacket,
MalformedInteger,
UnknownProperty,
UnsupportedPacket,
BufferSize,
InvalidProperty,
}
/// Possible errors encountered during an MQTT connection.
#[derive(Debug, PartialEq)]
pub enum Error<E> {
Network(E),
WriteFail,
NotReady,
Unsupported,
ProvidedClientIdTooLong,
Failed(u8),
Protocol(ProtocolError),
SessionReset,
Clock(embedded_time::clock::Error),
}
impl<E> From<embedded_time::clock::Error> for Error<E> {
fn from(clock: embedded_time::clock::Error) -> Self {
Error::Clock(clock)
}
}
impl<E> From<ProtocolError> for Error<E> {
fn from(error: ProtocolError) -> Self {
Error::Protocol(error)
}
}
#[doc(hidden)]
#[cfg(not(feature = "logging"))]
mod mqtt_log {
#[doc(hidden)]
#[macro_export]
macro_rules! debug {
($($arg:tt)+) => {
()
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! info {
($($arg:tt)+) => {
()
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! warn {
($($arg:tt)+) => {
()
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! error {
($($arg:tt)+) => {
()
};
}
}
| 25.993671 | 102 | 0.611882 |
095ed23a27f93c60241fff9391b84612485bf914 | 32,600 | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! The main Materialize server.
//!
//! The name is pronounced "materialize-dee." It listens on port 6875 (MTRL).
//!
//! The design and implementation of materialized is very much in flux. See the
//! draft architecture doc for the most up-to-date plan [0]. Access is limited
//! to those with access to the Material Dropbox Paper folder.
//!
//! [0]: https://paper.dropbox.com/doc/Materialize-architecture-plans--AYSu6vvUu7ZDoOEZl7DNi8UQAg-sZj5rhJmISdZSfK0WBxAl
use std::cmp;
use std::env;
use std::ffi::CStr;
use std::fmt;
use std::fs;
use std::io;
use std::net::SocketAddr;
use std::panic;
use std::panic::PanicInfo;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use anyhow::{bail, Context};
use backtrace::Backtrace;
use chrono::Utc;
use clap::AppSettings;
use coord::{PersistConfig, PersistFileStorage, PersistStorage};
use fail::FailScenario;
use itertools::Itertools;
use lazy_static::lazy_static;
use log::info;
use ore::cgroup::{detect_memory_limit, MemoryLimit};
use ore::metric;
use ore::metrics::ThirdPartyMetric;
use ore::metrics::{raw::IntCounterVec, MetricsRegistry};
use structopt::StructOpt;
use sysinfo::{ProcessorExt, SystemExt};
use self::tracing::MetricsRecorderLayer;
use materialized::TlsMode;
mod sys;
mod tracing;
type OptionalDuration = Option<Duration>;
fn parse_optional_duration(s: &str) -> Result<OptionalDuration, anyhow::Error> {
match s {
"off" => Ok(None),
_ => Ok(Some(repr::util::parse_duration(s)?)),
}
}
/// The streaming SQL materialized view engine.
#[derive(StructOpt)]
#[structopt(settings = &[AppSettings::NextLineHelp, AppSettings::UnifiedHelpMessage], usage = "materialized [OPTION]...")]
struct Args {
// === Special modes. ===
/// Print version information and exit.
///
/// Specify twice to additionally print version information for selected
/// dependencies.
#[structopt(short, long, parse(from_occurrences))]
version: usize,
/// Allow running this dev (unoptimized) build.
#[cfg(debug_assertions)]
#[structopt(long)]
dev: bool,
// TODO(benesch): add an environment variable once we upgrade to clap v3.
// Doesn't presently work in clap v2. See: clap-rs/clap#1476.
/// [DANGEROUS] Enable experimental features.
#[structopt(long)]
experimental: bool,
/// Whether to run in safe mode.
///
/// In safe mode, features that provide access to the underlying machine,
/// like file sources and sinks, are disabled.
///
/// This option is intended for use by the cloud product
/// (cloud.materialize.com), but may be useful in other contexts as well.
#[structopt(long, hidden = true)]
safe: bool,
#[structopt(long)]
disable_user_indexes: bool,
/// The address on which metrics visible to "third parties" get exposed.
///
/// These metrics are structured to allow an infrastructure provider to monitor an installation
/// without needing access to more sensitive data, like names of sources/sinks.
///
/// This address is never served TLS-encrypted or authenticated, and while only "non-sensitive"
/// metrics are served from it, care should be taken to not expose the listen address to the
/// public internet or other unauthorized parties.
#[structopt(
long,
hidden = true,
value_name = "HOST:PORT",
env = "MZ_THIRD_PARTY_METRICS_ADDR"
)]
third_party_metrics_listen_addr: Option<SocketAddr>,
/// Enable persistent user tables. Has to be used with --experimental.
#[structopt(long, hidden = true)]
persistent_user_tables: bool,
/// Disable persistence of all system tables.
///
/// This is a test of the upcoming persistence system. The data is stored on
/// the filesystem in a sub-directory of the Materialize data_directory.
/// This test is enabled by default to allow us to collect data from a
/// variety of deployments, but setting this flag to true to opt out of the
/// test is always safe.
#[structopt(long)]
disable_persistent_system_tables_test: bool,
/// An S3 location used to persist data, specified as s3://<bucket>/<path>.
///
/// The `<path>` is a prefix prepended to all S3 object keys used for
/// persistence and allowed to be empty.
///
/// Ignored if persistence is disabled. If unset, files stored under
/// `--data-directory/-D` are used instead. If set, S3 credentials and
/// region must be available in the process or environment: for details see
/// https://github.com/rusoto/rusoto/blob/rusoto-v0.47.0/AWS-CREDENTIALS.md.
#[structopt(long, hidden = true, default_value)]
persist_storage: String,
/// Enable persistent Kafka UPSERT source. Has to be used with --experimental.
#[structopt(long, hidden = true)]
persistent_kafka_upsert_source: bool,
// === Timely worker configuration. ===
/// Number of dataflow worker threads.
#[structopt(short, long, env = "MZ_WORKERS", value_name = "N", default_value)]
workers: WorkerCount,
/// Log Timely logging itself.
#[structopt(long, hidden = true)]
debug_introspection: bool,
/// Retain prometheus metrics for this amount of time.
#[structopt(short, long, hidden = true, parse(try_from_str = repr::util::parse_duration), default_value = "5min")]
retain_prometheus_metrics: Duration,
// === Performance tuning parameters. ===
/// The frequency at which to update introspection sources.
///
/// The introspection sources are the built-in sources in the mz_catalog
/// schema, like mz_scheduling_elapsed, that reflect the internal state of
/// Materialize's dataflow engine.
///
/// Set to "off" to disable introspection.
#[structopt(long, env = "MZ_INTROSPECTION_FREQUENCY", parse(try_from_str = parse_optional_duration), value_name = "FREQUENCY", default_value = "1s")]
introspection_frequency: OptionalDuration,
/// How much historical detail to maintain in arrangements.
///
/// Set to "off" to disable logical compaction.
#[structopt(long, env = "MZ_LOGICAL_COMPACTION_WINDOW", parse(try_from_str = parse_optional_duration), value_name = "DURATION", default_value = "1ms")]
logical_compaction_window: OptionalDuration,
/// Default frequency with which to advance timestamps
#[structopt(long, env = "MZ_TIMESTAMP_FREQUENCY", hidden = true, parse(try_from_str =repr::util::parse_duration), value_name = "DURATION", default_value = "1s")]
timestamp_frequency: Duration,
/// Default frequency with which to scrape prometheus metrics
#[structopt(long, env = "MZ_METRICS_SCRAPING_INTERVAL", hidden = true, parse(try_from_str = parse_optional_duration), value_name = "DURATION", default_value = "30s")]
metrics_scraping_interval: OptionalDuration,
/// [ADVANCED] Timely progress tracking mode.
#[structopt(long, env = "MZ_TIMELY_PROGRESS_MODE", value_name = "MODE", possible_values = &["eager", "demand"], default_value = "demand")]
timely_progress_mode: timely::worker::ProgressMode,
/// [ADVANCED] Amount of compaction to perform when idle.
#[structopt(long, env = "MZ_DIFFERENTIAL_IDLE_MERGE_EFFORT", value_name = "N")]
differential_idle_merge_effort: Option<isize>,
// === Logging options. ===
/// Where to emit log messages.
///
/// The special value "stderr" will emit messages to the standard error
/// stream. All other values are taken as file paths.
#[structopt(long, env = "MZ_LOG_FILE", value_name = "PATH")]
log_file: Option<String>,
/// Which log messages to emit.
///
/// This value is a comma-separated list of filter directives. Each filter
/// directive has the following format:
///
/// [module::path=]level
///
/// A directive indicates that log messages from the specified module that
/// are at least as severe as the specified level should be emitted. If a
/// directive omits the module, then it implicitly applies to all modules.
/// When directives conflict, the last directive wins. If a log message does
/// not match any directive, it is not emitted.
///
/// The module path of a log message reflects its location in Materialize's
/// source code. Choosing module paths for filter directives requires
/// familiarity with Materialize's codebase and is intended for advanced
/// users. Note that module paths change frequency from release to release.
///
/// The valid levels for a log message are, in increasing order of severity:
/// trace, debug, info, warn, and error. The special level "off" may be used
/// in a directive to suppress all log messages, even errors.
///
/// The default value for this option is "info".
#[structopt(
long,
env = "MZ_LOG_FILTER",
value_name = "FILTER",
default_value = "info"
)]
log_filter: String,
// == Connection options.
/// The address on which to listen for connections.
#[structopt(
long,
env = "MZ_LISTEN_ADDR",
value_name = "HOST:PORT",
default_value = "0.0.0.0:6875"
)]
listen_addr: SocketAddr,
/// How stringently to demand TLS authentication and encryption.
///
/// If set to "disable", then materialized rejects HTTP and PostgreSQL
/// connections that negotiate TLS.
///
/// If set to "require", then materialized requires that all HTTP and
/// PostgreSQL connections negotiate TLS. Unencrypted connections will be
/// rejected.
///
/// If set to "verify-ca", then materialized requires that all HTTP and
/// PostgreSQL connections negotiate TLS and supply a certificate signed by
/// a trusted certificate authority (CA). HTTP connections will operate as
/// the system user in this mode, while PostgreSQL connections will assume
/// the name of whatever user is specified in the handshake.
///
/// The "verify-full" mode is like "verify-ca", except that the Common Name
/// (CN) field of the certificate must match the name of a valid user. HTTP
/// and PostgreSQL connections will operate as this user. PostgreSQL
/// connections must additionally specify the same username in the
/// connection parameters.
///
/// The most secure mode is "verify-full". This is the default mode when
/// the --tls-cert option is specified. Otherwise the default is "disable".
#[structopt(
long, env = "MZ_TLS_MODE",
possible_values = &["disable", "require", "verify-ca", "verify-full"],
default_value = "disable",
default_value_if("tls-cert", None, "verify-full"),
value_name = "MODE",
)]
tls_mode: String,
#[structopt(
long,
env = "MZ_TLS_CA",
required_if("tls-mode", "verify-ca"),
required_if("tls-mode", "verify-full"),
value_name = "PATH"
)]
tls_ca: Option<PathBuf>,
/// Certificate file for TLS connections.
#[structopt(
long,
env = "MZ_TLS_CERT",
requires = "tls-key",
required_ifs(&[("tls-mode", "allow"), ("tls-mode", "require"), ("tls-mode", "verify-ca"), ("tls-mode", "verify-full")]),
value_name = "PATH"
)]
tls_cert: Option<PathBuf>,
/// Private key file for TLS connections.
#[structopt(
long,
env = "MZ_TLS_KEY",
requires = "tls-cert",
required_ifs(&[("tls-mode", "allow"), ("tls-mode", "require"), ("tls-mode", "verify-ca"), ("tls-mode", "verify-full")]),
value_name = "PATH"
)]
tls_key: Option<PathBuf>,
// === Storage options. ===
/// Where to store data.
#[structopt(
short = "D",
long,
env = "MZ_DATA_DIRECTORY",
value_name = "PATH",
default_value = "mzdata"
)]
data_directory: PathBuf,
/// Enable symbioisis with a PostgreSQL server.
#[structopt(long, env = "MZ_SYMBIOSIS", hidden = true)]
symbiosis: Option<String>,
// === Telemetry options. ===
// TODO(benesch): add an environment variable once we upgrade to clap v3.
// Doesn't presently work in clap v2. See: clap-rs/clap#1476.
/// Disable telemetry reporting.
#[structopt(long, conflicts_with_all = &["telemetry-domain", "telemetry-interval"])]
disable_telemetry: bool,
/// The domain hosting the telemetry server.
#[structopt(long, env = "MZ_TELEMETRY_DOMAIN", hidden = true)]
telemetry_domain: Option<String>,
/// The interval at which to report telemetry data.
#[structopt(long, env = "MZ_TELEMETRY_INTERVAL", parse(try_from_str = repr::util::parse_duration), hidden = true)]
telemetry_interval: Option<Duration>,
}
/// This type is a hack to allow a dynamic default for the `--workers` argument,
/// which depends on the number of available CPUs. Ideally structopt would
/// expose a `default_fn` rather than accepting only string literals.
struct WorkerCount(usize);
impl Default for WorkerCount {
fn default() -> Self {
WorkerCount(cmp::max(
1,
// When inside a cgroup with a cpu limit,
// the logical cpus can be lower than the physical cpus.
cmp::min(num_cpus::get(), num_cpus::get_physical()) / 2,
))
}
}
impl FromStr for WorkerCount {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<WorkerCount, anyhow::Error> {
let n = s.parse()?;
if n == 0 {
bail!("must be greater than zero");
}
Ok(WorkerCount(n))
}
}
impl fmt::Display for WorkerCount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
fn main() {
if let Err(err) = run(Args::from_args()) {
eprintln!("materialized: {:#}", err);
process::exit(1);
}
}
fn run(args: Args) -> Result<(), anyhow::Error> {
panic::set_hook(Box::new(handle_panic));
sys::enable_sigbus_sigsegv_backtraces()?;
sys::enable_termination_signal_cleanup()?;
// Initialize fail crate for failpoint support
let _failpoint_scenario = FailScenario::setup();
if args.version > 0 {
println!("materialized {}", materialized::BUILD_INFO.human_version());
if args.version > 1 {
for bi in build_info() {
println!("{}", bi);
}
}
return Ok(());
}
// Prevent accidental usage of development builds.
//
// TODO(benesch): offload environment variable check to clap once we upgrade
// to clap v3. Doesn't presently work in clap v2. See: clap-rs/clap#1476.
#[cfg(debug_assertions)]
if !args.dev && !ore::env::is_var_truthy("MZ_DEV") {
bail!(
"refusing to run dev (unoptimized) binary without explicit opt-in\n\
hint: Pass the '--dev' option or set MZ_DEV=1 in your environment to opt in.\n\
hint: Or perhaps you meant to use a release binary?"
);
}
// Configure Timely and Differential workers.
let log_logging = args.debug_introspection;
let retain_readings_for = args.retain_prometheus_metrics;
let metrics_scraping_interval = args.metrics_scraping_interval;
let logging = args
.introspection_frequency
.map(|granularity| coord::LoggingConfig {
granularity,
log_logging,
retain_readings_for,
metrics_scraping_interval,
});
if log_logging && logging.is_none() {
bail!(
"cannot specify --debug-introspection and --introspection-frequency=off simultaneously"
);
}
// Configure connections.
let tls = if args.tls_mode == "disable" {
if args.tls_ca.is_some() {
bail!("cannot specify --tls-mode=disable and --tls-ca simultaneously");
}
if args.tls_cert.is_some() {
bail!("cannot specify --tls-mode=disable and --tls-cert simultaneously");
}
if args.tls_key.is_some() {
bail!("cannot specify --tls-mode=disable and --tls-key simultaneously");
}
None
} else {
let mode = match args.tls_mode.as_str() {
"require" => {
if args.tls_ca.is_some() {
bail!("cannot specify --tls-mode=require and --tls-ca simultaneously");
}
TlsMode::Require
}
"verify-ca" => TlsMode::VerifyCa {
ca: args.tls_ca.unwrap(),
},
"verify-full" => TlsMode::VerifyFull {
ca: args.tls_ca.unwrap(),
},
_ => unreachable!(),
};
let cert = args.tls_cert.unwrap();
let key = args.tls_key.unwrap();
Some(materialized::TlsConfig { mode, cert, key })
};
// Configure storage.
let data_directory = args.data_directory;
fs::create_dir_all(&data_directory)
.with_context(|| format!("creating data directory: {}", data_directory.display()))?;
// If --disable-telemetry is present, disable telemetry. Otherwise, if a
// custom telemetry domain or interval is provided, enable telemetry as
// specified. Otherwise (the defaults), enable the production server for
// release mode and disable telemetry in debug mode. This should allow for
// good defaults (on in release, off in debug), but also easy development
// during testing of this feature via the command-line flags.
let telemetry = if args.disable_telemetry
|| (cfg!(debug_assertions)
&& args.telemetry_domain.is_none()
&& args.telemetry_interval.is_none())
{
None
} else {
Some(materialized::TelemetryConfig {
domain: args
.telemetry_domain
.unwrap_or_else(|| "cloud.materialize.com".into()),
interval: args
.telemetry_interval
.unwrap_or_else(|| Duration::from_secs(3600)),
})
};
let metrics_registry = MetricsRegistry::new();
// Configure tracing.
{
use tracing_subscriber::filter::{EnvFilter, LevelFilter};
use tracing_subscriber::fmt;
use tracing_subscriber::layer::{Layer, SubscriberExt};
use tracing_subscriber::util::SubscriberInitExt;
let env_filter = EnvFilter::try_new(args.log_filter)
.context("parsing --log-filter option")?
// Ensure panics are logged, even if the user has specified
// otherwise.
.add_directive("panic=error".parse().unwrap());
let log_message_counter: ThirdPartyMetric<IntCounterVec> = metrics_registry
.register_third_party_visible(metric!(
name: "mz_log_message_total",
help: "The number of log messages produced by this materialized instance",
var_labels: ["severity"],
));
match args.log_file.as_deref() {
Some("stderr") => {
// The user explicitly directed logs to stderr. Log only to stderr
// with the user-specified `env_filter`.
tracing_subscriber::registry()
.with(MetricsRecorderLayer::new(log_message_counter))
.with(env_filter)
.with(
fmt::layer()
.with_writer(io::stderr)
.with_ansi(atty::is(atty::Stream::Stderr)),
)
.init()
}
log_file => {
// Logging to a file. If the user did not explicitly specify
// a file, bubble up warnings and errors to stderr.
let stderr_level = match log_file {
Some(_) => LevelFilter::OFF,
None => LevelFilter::WARN,
};
tracing_subscriber::registry()
.with(MetricsRecorderLayer::new(log_message_counter))
.with(env_filter)
.with({
let path = match log_file {
Some(log_file) => PathBuf::from(log_file),
None => data_directory.join("materialized.log"),
};
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).with_context(|| {
format!("creating log file directory: {}", parent.display())
})?;
}
let file = fs::OpenOptions::new()
.append(true)
.create(true)
.open(&path)
.with_context(|| format!("creating log file: {}", path.display()))?;
fmt::layer().with_ansi(false).with_writer(move || {
file.try_clone().expect("failed to clone log file")
})
})
.with(
fmt::layer()
.with_writer(io::stderr)
.with_ansi(atty::is(atty::Stream::Stderr))
.with_filter(stderr_level),
)
.init()
}
}
}
// Configure prometheus process metrics.
mz_process_collector::register_default_process_collector(&metrics_registry);
// When inside a cgroup with a cpu limit,
// the logical cpus can be lower than the physical cpus.
let ncpus_useful = usize::max(1, cmp::min(num_cpus::get(), num_cpus::get_physical()));
let memory_limit = detect_memory_limit().unwrap_or_else(|| MemoryLimit {
max: None,
swap_max: None,
});
let memory_max_str = match memory_limit.max {
Some(max) => format!(", {}KiB limit", max / 1024),
None => "".to_owned(),
};
let swap_max_str = match memory_limit.swap_max {
Some(max) => format!(", {}KiB limit", max / 1024),
None => "".to_owned(),
};
// Print system information as the very first thing in the logs. The goal is
// to increase the probability that we can reproduce a reported bug if all
// we get is the log file.
let mut system = sysinfo::System::new();
system.refresh_system();
info!(
"booting server
materialized {mz_version}
{dep_versions}
invoked as: {invocation}
os: {os}
cpus: {ncpus_logical} logical, {ncpus_physical} physical, {ncpus_useful} useful
cpu0: {cpu0}
memory: {memory_total}KB total, {memory_used}KB used{memory_limit}
swap: {swap_total}KB total, {swap_used}KB used{swap_limit}
dataflow workers: {workers}",
mz_version = materialized::BUILD_INFO.human_version(),
dep_versions = build_info().join("\n"),
invocation = {
use shell_words::quote as escape;
env::vars_os()
.map(|(name, value)| {
(
name.to_string_lossy().into_owned(),
value.to_string_lossy().into_owned(),
)
})
.filter(|(name, _value)| name.starts_with("MZ_"))
.map(|(name, value)| format!("{}={}", escape(&name), escape(&value)))
.chain(env::args().into_iter().map(|arg| escape(&arg).into_owned()))
.join(" ")
},
os = os_info::get(),
ncpus_logical = num_cpus::get(),
ncpus_physical = num_cpus::get_physical(),
ncpus_useful = ncpus_useful,
cpu0 = {
match &system.processors().get(0) {
None => "<unknown>".to_string(),
Some(cpu0) => format!("{} {}MHz", cpu0.brand(), cpu0.frequency()),
}
},
memory_total = system.total_memory(),
memory_used = system.used_memory(),
memory_limit = memory_max_str,
swap_total = system.total_swap(),
swap_used = system.used_swap(),
swap_limit = swap_max_str,
workers = args.workers.0,
);
sys::adjust_rlimits();
// Build Timely worker configuration.
let mut timely_worker =
timely::WorkerConfig::default().progress_mode(args.timely_progress_mode);
differential_dataflow::configure(
&mut timely_worker,
&differential_dataflow::Config {
idle_merge_effort: args.differential_idle_merge_effort,
},
);
// Start Tokio runtime.
let runtime = Arc::new(
tokio::runtime::Builder::new_multi_thread()
.worker_threads(ncpus_useful)
// The default thread name exceeds the Linux limit on thread name
// length, so pick something shorter.
.thread_name_fn(|| {
static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
format!("tokio:work-{}", id)
})
.enable_all()
.build()?,
);
// Configure persistence core.
let persist_config = {
let user_table_enabled = if args.experimental && args.persistent_user_tables {
true
} else if args.persistent_user_tables {
bail!("cannot specify --persistent-user-tables without --experimental");
} else {
false
};
let mut system_table_enabled = !args.disable_persistent_system_tables_test;
if system_table_enabled && args.logical_compaction_window.is_none() {
log::warn!("--logical-compaction-window is off; disabling background persistence test to prevent unbounded disk usage");
system_table_enabled = false;
}
let storage = if args.persist_storage.is_empty() {
PersistStorage::File(PersistFileStorage {
blob_path: data_directory.join("persist").join("blob"),
})
} else if !args.experimental {
bail!("cannot specify --persist-storage without --experimental");
} else {
PersistStorage::try_from(args.persist_storage)?
};
let kafka_upsert_source_enabled =
if args.experimental && args.persistent_kafka_upsert_source {
true
} else if args.persistent_kafka_upsert_source {
bail!("cannot specify --persistent-kafka-upsert-source without --experimental");
} else {
false
};
let lock_info = format!(
"materialized {mz_version}\nos: {os}\nstart time: {start_time}\nnum workers: {num_workers}\n",
mz_version = materialized::BUILD_INFO.human_version(),
os = os_info::get(),
start_time = Utc::now(),
num_workers = args.workers.0,
);
// The min_step_interval knob allows tuning a tradeoff between latency and storage usage.
// As persist gets more sophisticated over time, we'll no longer need this knob,
// but in the meantime we need it to make tests reasonably performant.
// The --timestamp-frequency flag similarly gives testing a control over
// latency vs resource usage, so for simplicity we reuse it here."
let min_step_interval = args.timestamp_frequency;
PersistConfig {
runtime: Some(runtime.clone()),
storage,
user_table_enabled,
system_table_enabled,
kafka_upsert_source_enabled,
lock_info,
min_step_interval,
}
};
let server = runtime.block_on(materialized::serve(materialized::Config {
workers: args.workers.0,
timely_worker,
logging,
logical_compaction_window: args.logical_compaction_window,
timestamp_frequency: args.timestamp_frequency,
listen_addr: args.listen_addr,
third_party_metrics_listen_addr: args.third_party_metrics_listen_addr,
tls,
data_directory,
symbiosis_url: args.symbiosis,
experimental_mode: args.experimental,
disable_user_indexes: args.disable_user_indexes,
safe_mode: args.safe,
telemetry,
introspection_frequency: args
.introspection_frequency
.unwrap_or_else(|| Duration::from_secs(1)),
metrics_registry,
persist: persist_config,
}))?;
eprintln!(
"=======================================================================
Thank you for trying Materialize!
We are interested in any and all feedback you have, which may be able
to improve both our software and your queries! Please reach out at:
Web: https://materialize.com
GitHub issues: https://github.com/MaterializeInc/materialize/issues
Email: [email protected]
Twitter: @MaterializeInc
=======================================================================
"
);
if args.disable_user_indexes {
eprintln!(
"************************************************************************
NOTE!
************************************************************************
Starting Materialize with user indexes disabled.
For more details, see
https://materialize.com/docs/cli#user-indexes-disabled
************************************************************************
"
);
}
if args.experimental {
eprintln!(
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WARNING!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Starting Materialize in experimental mode means:
- This node's catalog of views and sources are unstable.
If you use any version of Materialize besides this one, you might
not be able to start the Materialize node. To fix this, you'll have
to remove all of Materialize's data (e.g. rm -rf mzdata) and start
the node anew.
- You must always start this node in experimental mode; it can no
longer be started in non-experimental/regular mode.
For more details, see https://materialize.com/docs/cli#experimental-mode
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"
);
}
println!(
"materialized {} listening on {}...",
materialized::BUILD_INFO.human_version(),
server.local_addr(),
);
// Block forever.
loop {
thread::park();
}
}
lazy_static! {
static ref PANIC_MUTEX: Mutex<()> = Mutex::new(());
}
fn handle_panic(panic_info: &PanicInfo) {
let _guard = PANIC_MUTEX.lock();
let thr = thread::current();
let thr_name = thr.name().unwrap_or("<unnamed>");
let msg = match panic_info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match panic_info.payload().downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
},
};
let location = if let Some(loc) = panic_info.location() {
loc.to_string()
} else {
"<unknown>".to_string()
};
log::error!(
target: "panic",
"{msg}
thread: {thr_name}
location: {location}
version: {version} ({sha})
backtrace:
{backtrace:?}",
msg = msg,
thr_name = thr_name,
location = location,
version = materialized::BUILD_INFO.version,
sha = materialized::BUILD_INFO.sha,
backtrace = Backtrace::new(),
);
eprintln!(
r#"materialized encountered an internal error and crashed.
We rely on bug reports to diagnose and fix these errors. Please
copy and paste the above details and file a report at:
https://materialize.com/s/bug
"#,
);
process::exit(1);
}
fn build_info() -> Vec<String> {
let openssl_version =
unsafe { CStr::from_ptr(openssl_sys::OpenSSL_version(openssl_sys::OPENSSL_VERSION)) };
let rdkafka_version = unsafe { CStr::from_ptr(rdkafka_sys::bindings::rd_kafka_version_str()) };
vec![
openssl_version.to_string_lossy().into_owned(),
format!("librdkafka v{}", rdkafka_version.to_string_lossy()),
]
}
| 38.443396 | 170 | 0.605061 |
bbaba69ac865e4bf03a9c2956599361a2e5b327a | 147 | // This test checks that #[ockam::node] causes a compile time error
// if the item it is defined on is not a function.
#[ockam::node]
struct A {}
| 24.5 | 67 | 0.693878 |
18f7cc617d41e5615025f469f2e6dedc88f97bbb | 2,622 | use std::io;
use ew::{
tools::{logging, stopchecker},
GoalFromFunction, Optimizer,
particleswarm::{
self,
initializing,
postmove,
velocitycalc,
PostMove,
postvelocitycalc,
PostVelocityCalc,
},
};
use ew_testfunc;
type Coordinate = f32;
fn main() {
// General parameters
let minval: Coordinate = -500.0;
let maxval: Coordinate = 500.0;
let particles_count = 100;
let dimension = 3;
let intervals = vec![(minval, maxval); dimension];
let phi_personal = 3.2;
let phi_global = 1.0;
let k = 0.9;
// Goal function
let goal = GoalFromFunction::new(ew_testfunc::schwefel);
// Particles initializers
let coord_initializer = initializing::RandomCoordinatesInitializer::new(intervals.clone(), particles_count);
let velocity_initializer = initializing::ZeroVelocityInitializer::new(dimension, particles_count);
// PostMove
let post_moves: Vec<Box<dyn PostMove<Coordinate>>> = vec![Box::new(postmove::MoveToBoundary::new(intervals.clone()))];
// Velocity calculator
let velocity_calculator = velocitycalc::CanonicalVelocityCalculator::new(phi_personal, phi_global, k);
let max_velocity = 700.0;
let post_velocity_calc: Vec<Box<dyn PostVelocityCalc<Coordinate>>> =
vec![Box::new(postvelocitycalc::MaxVelocityAbs::new(max_velocity))];
// Stop checker
let change_max_iterations = 150;
let change_delta = 1e-8;
let stop_checker = stopchecker::CompositeAny::new(vec![
Box::new(stopchecker::Threshold::new(1e-6)),
Box::new(stopchecker::GoalNotChange::new(
change_max_iterations,
change_delta,
)),
Box::new(stopchecker::MaxIterations::new(3000)),
]);
// Logger
let mut stdout_verbose = io::stdout();
let mut stdout_result = io::stdout();
let mut stdout_time = io::stdout();
let loggers: Vec<Box<dyn logging::Logger<Vec<Coordinate>>>> = vec![
Box::new(logging::VerboseLogger::new(&mut stdout_verbose, 15)),
Box::new(logging::ResultOnlyLogger::new(&mut stdout_result, 15)),
Box::new(logging::TimeLogger::new(&mut stdout_time)),
];
let mut optimizer = particleswarm::ParticleSwarmOptimizer::new(
Box::new(goal),
Box::new(stop_checker),
Box::new(coord_initializer),
Box::new(velocity_initializer),
Box::new(velocity_calculator),
);
optimizer.set_loggers(loggers);
optimizer.set_post_moves(post_moves);
optimizer.set_post_velocity_calc(post_velocity_calc);
optimizer.find_min();
}
| 30.847059 | 122 | 0.660183 |
794245d13f97cc6816579d280ea6e199329cf273 | 858 | use actix_web::{HttpResponse, Result};
use crate::simulator::SimulatorData;
use crate::server::{GLOBAL_DATA, GAMES};
use std::sync::Mutex;
use serde::{Serialize};
use crate::utils::TimeEstimation;
use chrono::{Utc};
#[derive(Serialize)]
pub struct IndexResponse {
game_id: String,
elapsed: u32
}
pub async fn game_create_action() -> Result<HttpResponse> {
let estimated = TimeEstimation::estimate(SimulatorData::generate);
let simulator_data = estimated.0;
let game_id = simulator_data.id();
GLOBAL_DATA.insert(simulator_data.id(), simulator_data);
let result = IndexResponse{
game_id: game_id.clone(),
elapsed: estimated.1
};
let mut games_list = GAMES.lock().unwrap();
games_list.push((game_id.clone(), Utc::now().naive_utc().to_string()));
Ok(HttpResponse::Ok().json(result))
}
| 24.514286 | 79 | 0.684149 |
1ad0dbfce21e4ba16f1dcaf15fd6f1f9720202cb | 7,509 | // Copyright 2021 Parallel Finance Developer.
// This file is part of Parallel Finance.
// 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.
#![cfg_attr(not(feature = "std"), no_std)]
use crate::{types::Deposits, AssetIdOf, BalanceOf, *};
use frame_support::{
require_transactional,
traits::tokens::{
fungibles::{Inspect, Transfer},
DepositConsequence, WithdrawConsequence,
},
};
impl<T: Config> Inspect<T::AccountId> for Pallet<T> {
type AssetId = AssetIdOf<T>;
type Balance = BalanceOf<T>;
/// The total amount of issuance in the system.
fn total_issuance(ptoken_id: Self::AssetId) -> Self::Balance {
if let Ok(underlying_id) = Self::underlying_id(ptoken_id) {
Self::total_supply(underlying_id)
} else {
Balance::default()
}
}
/// The minimum balance any single account may have.
fn minimum_balance(_ptoken_id: Self::AssetId) -> Self::Balance {
Zero::zero()
}
/// Get the ptoken balance of `who`.
fn balance(ptoken_id: Self::AssetId, who: &T::AccountId) -> Self::Balance {
if let Ok(underlying_id) = Self::underlying_id(ptoken_id) {
Self::account_deposits(underlying_id, who).voucher_balance
} else {
Balance::default()
}
}
/// Get the maximum amount that `who` can withdraw/transfer successfully.
/// For ptoken, We don't care if keep_alive is enabled
fn reducible_balance(
ptoken_id: Self::AssetId,
who: &T::AccountId,
_keep_alive: bool,
) -> Self::Balance {
Self::reducible_asset(ptoken_id, who).unwrap_or_default()
}
/// Returns `true` if the balance of `who` may be increased by `amount`.
fn can_deposit(
ptoken_id: Self::AssetId,
who: &T::AccountId,
amount: Self::Balance,
) -> DepositConsequence {
let underlying_id = match Self::underlying_id(ptoken_id) {
Ok(asset_id) => asset_id,
Err(_) => return DepositConsequence::UnknownAsset,
};
if let Err(res) =
Self::ensure_active_market(underlying_id).map_err(|_| DepositConsequence::UnknownAsset)
{
return res;
}
if Self::total_supply(underlying_id)
.checked_add(amount)
.is_none()
{
return DepositConsequence::Overflow;
}
if Self::balance(ptoken_id, who) + amount < Self::minimum_balance(ptoken_id) {
return DepositConsequence::BelowMinimum;
}
DepositConsequence::Success
}
/// Returns `Failed` if the balance of `who` may not be decreased by `amount`, otherwise
/// the consequence.
fn can_withdraw(
ptoken_id: Self::AssetId,
who: &T::AccountId,
amount: Self::Balance,
) -> WithdrawConsequence<Self::Balance> {
let underlying_id = match Self::underlying_id(ptoken_id) {
Ok(asset_id) => asset_id,
Err(_) => return WithdrawConsequence::UnknownAsset,
};
if let Err(res) =
Self::ensure_active_market(underlying_id).map_err(|_| WithdrawConsequence::UnknownAsset)
{
return res;
}
let sub_result = Self::balance(ptoken_id, who).checked_sub(amount);
if sub_result.is_none() {
return WithdrawConsequence::NoFunds;
}
let rest = sub_result.expect("Cannot be none; qed");
if rest < Self::minimum_balance(ptoken_id) {
return WithdrawConsequence::ReducedToZero(rest);
}
WithdrawConsequence::Success
}
}
impl<T: Config> Transfer<T::AccountId> for Pallet<T> {
/// Returns `Err` if the reducible ptoken of `who` is insufficient
///
/// For ptoken, We don't care if keep_alive is enabled
#[transactional]
fn transfer(
ptoken_id: Self::AssetId,
source: &T::AccountId,
dest: &T::AccountId,
amount: Self::Balance,
_keep_alive: bool,
) -> Result<BalanceOf<T>, DispatchError> {
ensure!(
amount <= Self::reducible_balance(ptoken_id, source, false),
Error::<T>::InsufficientCollateral
);
Self::transfer_ptokens_internal(ptoken_id, source, dest, amount)?;
Ok(amount)
}
}
impl<T: Config> Pallet<T> {
#[require_transactional]
fn transfer_ptokens_internal(
ptoken_id: AssetIdOf<T>,
source: &T::AccountId,
dest: &T::AccountId,
amount: BalanceOf<T>,
) -> Result<(), DispatchError> {
let underlying_id = Self::underlying_id(ptoken_id)?;
AccountDeposits::<T>::try_mutate_exists(
underlying_id,
source,
|deposits| -> DispatchResult {
let mut d = deposits.unwrap_or_default();
d.voucher_balance = d
.voucher_balance
.checked_sub(amount)
.ok_or(ArithmeticError::Underflow)?;
if d.voucher_balance.is_zero() {
// remove deposits storage if zero balance
*deposits = None;
} else {
*deposits = Some(d);
}
Ok(())
},
)?;
AccountDeposits::<T>::try_mutate(underlying_id, &dest, |deposits| -> DispatchResult {
deposits.voucher_balance = deposits
.voucher_balance
.checked_add(amount)
.ok_or(ArithmeticError::Overflow)?;
Ok(())
})?;
Ok(())
}
fn reducible_asset(
ptoken_id: AssetIdOf<T>,
who: &T::AccountId,
) -> Result<BalanceOf<T>, DispatchError> {
let underlying_id = Self::underlying_id(ptoken_id)?;
let Deposits {
is_collateral,
voucher_balance,
} = Self::account_deposits(underlying_id, &who);
if !is_collateral {
return Ok(voucher_balance);
}
let market = Self::ensure_active_market(underlying_id)?;
let collateral_value = Self::collateral_asset_value(who, underlying_id)?;
// liquidity of all assets
let (liquidity, _) = Self::get_account_liquidity(who)?;
if liquidity >= collateral_value {
return Ok(voucher_balance);
}
// Formula
// reducible_underlying_amount = liquidity / collateral_factor / price
let price = Self::get_price(underlying_id)?;
let reducible_supply_value = liquidity
.checked_div(&market.collateral_factor.into())
.ok_or(ArithmeticError::Overflow)?;
let reducible_underlying_amount = reducible_supply_value
.checked_div(&price)
.ok_or(ArithmeticError::Underflow)?
.into_inner();
let exchange_rate = Self::exchange_rate(underlying_id);
let amount = Self::calc_collateral_amount(reducible_underlying_amount, exchange_rate)?;
Ok(amount)
}
}
| 32.790393 | 100 | 0.599281 |
8ff97ab828a735eab873a98857a5ca841661cb74 | 45,441 | //! This module provides constants which are specific to the implementation
//! of the `f64` floating point data type.
//!
//! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
//!
//! Mathematically significant numbers are provided in the `consts` sub-module.
#![stable(feature = "rust1", since = "1.0.0")]
#![allow(missing_docs)]
#[cfg(not(test))]
use crate::intrinsics;
#[cfg(not(test))]
use crate::sys::cmath;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{MIN_EXP, MAX_EXP, MIN_10_EXP};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{MAX_10_EXP, NAN, INFINITY, NEG_INFINITY};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{MIN, MIN_POSITIVE, MAX};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::consts;
#[cfg(not(test))]
#[lang = "f64_runtime"]
impl f64 {
/// Returns the largest integer less than or equal to a number.
///
/// # Examples
///
/// ```
/// let f = 3.99_f64;
/// let g = 3.0_f64;
///
/// assert_eq!(f.floor(), 3.0);
/// assert_eq!(g.floor(), 3.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
}
/// Returns the smallest integer greater than or equal to a number.
///
/// # Examples
///
/// ```
/// let f = 3.01_f64;
/// let g = 4.0_f64;
///
/// assert_eq!(f.ceil(), 4.0);
/// assert_eq!(g.ceil(), 4.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Returns the nearest integer to a number. Round half-way cases away from
/// `0.0`.
///
/// # Examples
///
/// ```
/// let f = 3.3_f64;
/// let g = -3.3_f64;
///
/// assert_eq!(f.round(), 3.0);
/// assert_eq!(g.round(), -3.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the integer part of a number.
///
/// # Examples
///
/// ```
/// let f = 3.3_f64;
/// let g = -3.7_f64;
///
/// assert_eq!(f.trunc(), 3.0);
/// assert_eq!(g.trunc(), -3.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn trunc(self) -> f64 {
unsafe { intrinsics::truncf64(self) }
}
/// Returns the fractional part of a number.
///
/// # Examples
///
/// ```
/// let x = 3.5_f64;
/// let y = -3.5_f64;
/// let abs_difference_x = (x.fract() - 0.5).abs();
/// let abs_difference_y = (y.fract() - (-0.5)).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn fract(self) -> f64 { self - self.trunc() }
/// Computes the absolute value of `self`. Returns `NAN` if the
/// number is `NAN`.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = 3.5_f64;
/// let y = -3.5_f64;
///
/// let abs_difference_x = (x.abs() - x).abs();
/// let abs_difference_y = (y.abs() - (-y)).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
///
/// assert!(f64::NAN.abs().is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn abs(self) -> f64 {
unsafe { intrinsics::fabsf64(self) }
}
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `INFINITY`
/// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// - `NAN` if the number is `NAN`
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let f = 3.5_f64;
///
/// assert_eq!(f.signum(), 1.0);
/// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
///
/// assert!(f64::NAN.signum().is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn signum(self) -> f64 {
if self.is_nan() {
NAN
} else {
unsafe { intrinsics::copysignf64(1.0, self) }
}
}
/// Returns a number composed of the magnitude of `self` and the sign of
/// `y`.
///
/// Equal to `self` if the sign of `self` and `y` are the same, otherwise
/// equal to `-self`. If `self` is a `NAN`, then a `NAN` with the sign of
/// `y` is returned.
///
/// # Examples
///
/// ```
/// #![feature(copysign)]
/// use std::f64;
///
/// let f = 3.5_f64;
///
/// assert_eq!(f.copysign(0.42), 3.5_f64);
/// assert_eq!(f.copysign(-0.42), -3.5_f64);
/// assert_eq!((-f).copysign(0.42), 3.5_f64);
/// assert_eq!((-f).copysign(-0.42), -3.5_f64);
///
/// assert!(f64::NAN.copysign(1.0).is_nan());
/// ```
#[inline]
#[must_use]
#[unstable(feature="copysign", issue="55169")]
pub fn copysign(self, y: f64) -> f64 {
unsafe { intrinsics::copysignf64(self, y) }
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error, yielding a more accurate result than an unfused multiply-add.
///
/// Using `mul_add` can be more performant than an unfused multiply-add if
/// the target architecture has a dedicated `fma` CPU instruction.
///
/// # Examples
///
/// ```
/// let m = 10.0_f64;
/// let x = 4.0_f64;
/// let b = 60.0_f64;
///
/// // 100.0
/// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn mul_add(self, a: f64, b: f64) -> f64 {
unsafe { intrinsics::fmaf64(self, a, b) }
}
/// Calculates Euclidean division, the matching method for `rem_euclid`.
///
/// This computes the integer `n` such that
/// `self = n * rhs + self.rem_euclid(rhs)`.
/// In other words, the result is `self / rhs` rounded to the integer `n`
/// such that `self >= n * rhs`.
///
/// # Examples
///
/// ```
/// #![feature(euclidean_division)]
/// let a: f64 = 7.0;
/// let b = 4.0;
/// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
/// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
/// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
/// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
/// ```
#[inline]
#[unstable(feature = "euclidean_division", issue = "49048")]
pub fn div_euclid(self, rhs: f64) -> f64 {
let q = (self / rhs).trunc();
if self % rhs < 0.0 {
return if rhs > 0.0 { q - 1.0 } else { q + 1.0 }
}
q
}
/// Calculates the least nonnegative remainder of `self (mod rhs)`.
///
/// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
/// most cases. However, due to a floating point round-off error it can
/// result in `r == rhs.abs()`, violating the mathematical definition, if
/// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
/// This result is not an element of the function's codomain, but it is the
/// closest floating point number in the real numbers and thus fulfills the
/// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
/// approximatively.
///
/// # Examples
///
/// ```
/// #![feature(euclidean_division)]
/// let a: f64 = 7.0;
/// let b = 4.0;
/// assert_eq!(a.rem_euclid(b), 3.0);
/// assert_eq!((-a).rem_euclid(b), 1.0);
/// assert_eq!(a.rem_euclid(-b), 3.0);
/// assert_eq!((-a).rem_euclid(-b), 1.0);
/// // limitation due to round-off error
/// assert!((-std::f64::EPSILON).rem_euclid(3.0) != 0.0);
/// ```
#[inline]
#[unstable(feature = "euclidean_division", issue = "49048")]
pub fn rem_euclid(self, rhs: f64) -> f64 {
let r = self % rhs;
if r < 0.0 {
r + rhs.abs()
} else {
r
}
}
/// Raises a number to an integer power.
///
/// Using this function is generally faster than using `powf`
///
/// # Examples
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.powi(2) - x*x).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn powi(self, n: i32) -> f64 {
unsafe { intrinsics::powif64(self, n) }
}
/// Raises a number to a floating point power.
///
/// # Examples
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.powf(2.0) - x*x).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn powf(self, n: f64) -> f64 {
unsafe { intrinsics::powf64(self, n) }
}
/// Takes the square root of a number.
///
/// Returns NaN if `self` is a negative number.
///
/// # Examples
///
/// ```
/// let positive = 4.0_f64;
/// let negative = -4.0_f64;
///
/// let abs_difference = (positive.sqrt() - 2.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// assert!(negative.sqrt().is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sqrt(self) -> f64 {
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}
/// Returns `e^(self)`, (the exponential function).
///
/// # Examples
///
/// ```
/// let one = 1.0_f64;
/// // e^1
/// let e = one.exp();
///
/// // ln(e) - 1 == 0
/// let abs_difference = (e.ln() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Returns `2^(self)`.
///
/// # Examples
///
/// ```
/// let f = 2.0_f64;
///
/// // 2^2 - 4 == 0
/// let abs_difference = (f.exp2() - 4.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn exp2(self) -> f64 {
unsafe { intrinsics::exp2f64(self) }
}
/// Returns the natural logarithm of the number.
///
/// # Examples
///
/// ```
/// let one = 1.0_f64;
/// // e^1
/// let e = one.exp();
///
/// // ln(e) - 1 == 0
/// let abs_difference = (e.ln() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn ln(self) -> f64 {
self.log_wrapper(|n| { unsafe { intrinsics::logf64(n) } })
}
/// Returns the logarithm of the number with respect to an arbitrary base.
///
/// The result may not be correctly rounded owing to implementation details;
/// `self.log2()` can produce more accurate results for base 2, and
/// `self.log10()` can produce more accurate results for base 10.
///
/// # Examples
///
/// ```
/// let five = 5.0_f64;
///
/// // log5(5) - 1 == 0
/// let abs_difference = (five.log(5.0) - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
/// Returns the base 2 logarithm of the number.
///
/// # Examples
///
/// ```
/// let two = 2.0_f64;
///
/// // log2(2) - 1 == 0
/// let abs_difference = (two.log2() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn log2(self) -> f64 {
self.log_wrapper(|n| {
#[cfg(target_os = "android")]
return crate::sys::android::log2f64(n);
#[cfg(not(target_os = "android"))]
return unsafe { intrinsics::log2f64(n) };
})
}
/// Returns the base 10 logarithm of the number.
///
/// # Examples
///
/// ```
/// let ten = 10.0_f64;
///
/// // log10(10) - 1 == 0
/// let abs_difference = (ten.log10() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn log10(self) -> f64 {
self.log_wrapper(|n| { unsafe { intrinsics::log10f64(n) } })
}
/// The positive difference of two numbers.
///
/// * If `self <= other`: `0:0`
/// * Else: `self - other`
///
/// # Examples
///
/// ```
/// let x = 3.0_f64;
/// let y = -3.0_f64;
///
/// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
/// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_deprecated(since = "1.10.0",
reason = "you probably meant `(self - other).abs()`: \
this operation is `(self - other).max(0.0)` \
except that `abs_sub` also propagates NaNs (also \
known as `fdim` in C). If you truly need the positive \
difference, consider using that expression or the C function \
`fdim`, depending on how you wish to handle NaN (please consider \
filing an issue describing your use-case too).")]
pub fn abs_sub(self, other: f64) -> f64 {
unsafe { cmath::fdim(self, other) }
}
/// Takes the cubic root of a number.
///
/// # Examples
///
/// ```
/// let x = 8.0_f64;
///
/// // x^(1/3) - 2 == 0
/// let abs_difference = (x.cbrt() - 2.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn cbrt(self) -> f64 {
unsafe { cmath::cbrt(self) }
}
/// Calculates the length of the hypotenuse of a right-angle triangle given
/// legs of length `x` and `y`.
///
/// # Examples
///
/// ```
/// let x = 2.0_f64;
/// let y = 3.0_f64;
///
/// // sqrt(x^2 + y^2)
/// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn hypot(self, other: f64) -> f64 {
unsafe { cmath::hypot(self, other) }
}
/// Computes the sine of a number (in radians).
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::PI/2.0;
///
/// let abs_difference = (x.sin() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sin(self) -> f64 {
unsafe { intrinsics::sinf64(self) }
}
/// Computes the cosine of a number (in radians).
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = 2.0*f64::consts::PI;
///
/// let abs_difference = (x.cos() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn cos(self) -> f64 {
unsafe { intrinsics::cosf64(self) }
}
/// Computes the tangent of a number (in radians).
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::PI/4.0;
/// let abs_difference = (x.tan() - 1.0).abs();
///
/// assert!(abs_difference < 1e-14);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn tan(self) -> f64 {
unsafe { cmath::tan(self) }
}
/// Computes the arcsine of a number. Return value is in radians in
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
/// [-1, 1].
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let f = f64::consts::PI / 2.0;
///
/// // asin(sin(pi/2))
/// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn asin(self) -> f64 {
unsafe { cmath::asin(self) }
}
/// Computes the arccosine of a number. Return value is in radians in
/// the range [0, pi] or NaN if the number is outside the range
/// [-1, 1].
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let f = f64::consts::PI / 4.0;
///
/// // acos(cos(pi/4))
/// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn acos(self) -> f64 {
unsafe { cmath::acos(self) }
}
/// Computes the arctangent of a number. Return value is in radians in the
/// range [-pi/2, pi/2];
///
/// # Examples
///
/// ```
/// let f = 1.0_f64;
///
/// // atan(tan(1))
/// let abs_difference = (f.tan().atan() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn atan(self) -> f64 {
unsafe { cmath::atan(self) }
}
/// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
///
/// * `x = 0`, `y = 0`: `0`
/// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
/// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let pi = f64::consts::PI;
/// // Positive angles measured counter-clockwise
/// // from positive x axis
/// // -pi/4 radians (45 deg clockwise)
/// let x1 = 3.0_f64;
/// let y1 = -3.0_f64;
///
/// // 3pi/4 radians (135 deg counter-clockwise)
/// let x2 = -3.0_f64;
/// let y2 = 3.0_f64;
///
/// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs();
/// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs();
///
/// assert!(abs_difference_1 < 1e-10);
/// assert!(abs_difference_2 < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn atan2(self, other: f64) -> f64 {
unsafe { cmath::atan2(self, other) }
}
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
/// `(sin(x), cos(x))`.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::PI/4.0;
/// let f = x.sin_cos();
///
/// let abs_difference_0 = (f.0 - x.sin()).abs();
/// let abs_difference_1 = (f.1 - x.cos()).abs();
///
/// assert!(abs_difference_0 < 1e-10);
/// assert!(abs_difference_1 < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sin_cos(self) -> (f64, f64) {
(self.sin(), self.cos())
}
/// Returns `e^(self) - 1` in a way that is accurate even if the
/// number is close to zero.
///
/// # Examples
///
/// ```
/// let x = 7.0_f64;
///
/// // e^(ln(7)) - 1
/// let abs_difference = (x.ln().exp_m1() - 6.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn exp_m1(self) -> f64 {
unsafe { cmath::expm1(self) }
}
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
/// the operations were performed separately.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::E - 1.0;
///
/// // ln(1 + (e - 1)) == ln(e) == 1
/// let abs_difference = (x.ln_1p() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn ln_1p(self) -> f64 {
unsafe { cmath::log1p(self) }
}
/// Hyperbolic sine function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let x = 1.0_f64;
///
/// let f = x.sinh();
/// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
/// let g = (e*e - 1.0)/(2.0*e);
/// let abs_difference = (f - g).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sinh(self) -> f64 {
unsafe { cmath::sinh(self) }
}
/// Hyperbolic cosine function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let x = 1.0_f64;
/// let f = x.cosh();
/// // Solving cosh() at 1 gives this result
/// let g = (e*e + 1.0)/(2.0*e);
/// let abs_difference = (f - g).abs();
///
/// // Same result
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn cosh(self) -> f64 {
unsafe { cmath::cosh(self) }
}
/// Hyperbolic tangent function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let x = 1.0_f64;
///
/// let f = x.tanh();
/// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
/// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2));
/// let abs_difference = (f - g).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn tanh(self) -> f64 {
unsafe { cmath::tanh(self) }
}
/// Inverse hyperbolic sine function.
///
/// # Examples
///
/// ```
/// let x = 1.0_f64;
/// let f = x.sinh().asinh();
///
/// let abs_difference = (f - x).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn asinh(self) -> f64 {
if self == NEG_INFINITY {
NEG_INFINITY
} else {
(self + ((self * self) + 1.0).sqrt()).ln()
}
}
/// Inverse hyperbolic cosine function.
///
/// # Examples
///
/// ```
/// let x = 1.0_f64;
/// let f = x.cosh().acosh();
///
/// let abs_difference = (f - x).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn acosh(self) -> f64 {
match self {
x if x < 1.0 => NAN,
x => (x + ((x * x) - 1.0).sqrt()).ln(),
}
}
/// Inverse hyperbolic tangent function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let f = e.tanh().atanh();
///
/// let abs_difference = (f - e).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn atanh(self) -> f64 {
0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
}
// Solaris/Illumos requires a wrapper around log, log2, and log10 functions
// because of their non-standard behavior (e.g., log(-n) returns -Inf instead
// of expected NaN).
fn log_wrapper<F: Fn(f64) -> f64>(self, log_fn: F) -> f64 {
if !cfg!(target_os = "solaris") {
log_fn(self)
} else {
if self.is_finite() {
if self > 0.0 {
log_fn(self)
} else if self == 0.0 {
NEG_INFINITY // log(0) = -Inf
} else {
NAN // log(-n) = NaN
}
} else if self.is_nan() {
self // log(NaN) = NaN
} else if self > 0.0 {
self // log(Inf) = Inf
} else {
NAN // log(-Inf) = NaN
}
}
}
}
#[cfg(test)]
mod tests {
use crate::f64;
use crate::f64::*;
use crate::num::*;
use crate::num::FpCategory as Fp;
#[test]
fn test_num_f64() {
test_num(10f64, 2f64);
}
#[test]
fn test_min_nan() {
assert_eq!(NAN.min(2.0), 2.0);
assert_eq!(2.0f64.min(NAN), 2.0);
}
#[test]
fn test_max_nan() {
assert_eq!(NAN.max(2.0), 2.0);
assert_eq!(2.0f64.max(NAN), 2.0);
}
#[test]
fn test_nan() {
let nan: f64 = NAN;
assert!(nan.is_nan());
assert!(!nan.is_infinite());
assert!(!nan.is_finite());
assert!(!nan.is_normal());
assert!(nan.is_sign_positive());
assert!(!nan.is_sign_negative());
assert_eq!(Fp::Nan, nan.classify());
}
#[test]
fn test_infinity() {
let inf: f64 = INFINITY;
assert!(inf.is_infinite());
assert!(!inf.is_finite());
assert!(inf.is_sign_positive());
assert!(!inf.is_sign_negative());
assert!(!inf.is_nan());
assert!(!inf.is_normal());
assert_eq!(Fp::Infinite, inf.classify());
}
#[test]
fn test_neg_infinity() {
let neg_inf: f64 = NEG_INFINITY;
assert!(neg_inf.is_infinite());
assert!(!neg_inf.is_finite());
assert!(!neg_inf.is_sign_positive());
assert!(neg_inf.is_sign_negative());
assert!(!neg_inf.is_nan());
assert!(!neg_inf.is_normal());
assert_eq!(Fp::Infinite, neg_inf.classify());
}
#[test]
fn test_zero() {
let zero: f64 = 0.0f64;
assert_eq!(0.0, zero);
assert!(!zero.is_infinite());
assert!(zero.is_finite());
assert!(zero.is_sign_positive());
assert!(!zero.is_sign_negative());
assert!(!zero.is_nan());
assert!(!zero.is_normal());
assert_eq!(Fp::Zero, zero.classify());
}
#[test]
fn test_neg_zero() {
let neg_zero: f64 = -0.0;
assert_eq!(0.0, neg_zero);
assert!(!neg_zero.is_infinite());
assert!(neg_zero.is_finite());
assert!(!neg_zero.is_sign_positive());
assert!(neg_zero.is_sign_negative());
assert!(!neg_zero.is_nan());
assert!(!neg_zero.is_normal());
assert_eq!(Fp::Zero, neg_zero.classify());
}
#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630
#[test]
fn test_one() {
let one: f64 = 1.0f64;
assert_eq!(1.0, one);
assert!(!one.is_infinite());
assert!(one.is_finite());
assert!(one.is_sign_positive());
assert!(!one.is_sign_negative());
assert!(!one.is_nan());
assert!(one.is_normal());
assert_eq!(Fp::Normal, one.classify());
}
#[test]
fn test_is_nan() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert!(nan.is_nan());
assert!(!0.0f64.is_nan());
assert!(!5.3f64.is_nan());
assert!(!(-10.732f64).is_nan());
assert!(!inf.is_nan());
assert!(!neg_inf.is_nan());
}
#[test]
fn test_is_infinite() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert!(!nan.is_infinite());
assert!(inf.is_infinite());
assert!(neg_inf.is_infinite());
assert!(!0.0f64.is_infinite());
assert!(!42.8f64.is_infinite());
assert!(!(-109.2f64).is_infinite());
}
#[test]
fn test_is_finite() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert!(!nan.is_finite());
assert!(!inf.is_finite());
assert!(!neg_inf.is_finite());
assert!(0.0f64.is_finite());
assert!(42.8f64.is_finite());
assert!((-109.2f64).is_finite());
}
#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630
#[test]
fn test_is_normal() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let zero: f64 = 0.0f64;
let neg_zero: f64 = -0.0;
assert!(!nan.is_normal());
assert!(!inf.is_normal());
assert!(!neg_inf.is_normal());
assert!(!zero.is_normal());
assert!(!neg_zero.is_normal());
assert!(1f64.is_normal());
assert!(1e-307f64.is_normal());
assert!(!1e-308f64.is_normal());
}
#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630
#[test]
fn test_classify() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let zero: f64 = 0.0f64;
let neg_zero: f64 = -0.0;
assert_eq!(nan.classify(), Fp::Nan);
assert_eq!(inf.classify(), Fp::Infinite);
assert_eq!(neg_inf.classify(), Fp::Infinite);
assert_eq!(zero.classify(), Fp::Zero);
assert_eq!(neg_zero.classify(), Fp::Zero);
assert_eq!(1e-307f64.classify(), Fp::Normal);
assert_eq!(1e-308f64.classify(), Fp::Subnormal);
}
#[test]
fn test_floor() {
assert_approx_eq!(1.0f64.floor(), 1.0f64);
assert_approx_eq!(1.3f64.floor(), 1.0f64);
assert_approx_eq!(1.5f64.floor(), 1.0f64);
assert_approx_eq!(1.7f64.floor(), 1.0f64);
assert_approx_eq!(0.0f64.floor(), 0.0f64);
assert_approx_eq!((-0.0f64).floor(), -0.0f64);
assert_approx_eq!((-1.0f64).floor(), -1.0f64);
assert_approx_eq!((-1.3f64).floor(), -2.0f64);
assert_approx_eq!((-1.5f64).floor(), -2.0f64);
assert_approx_eq!((-1.7f64).floor(), -2.0f64);
}
#[test]
fn test_ceil() {
assert_approx_eq!(1.0f64.ceil(), 1.0f64);
assert_approx_eq!(1.3f64.ceil(), 2.0f64);
assert_approx_eq!(1.5f64.ceil(), 2.0f64);
assert_approx_eq!(1.7f64.ceil(), 2.0f64);
assert_approx_eq!(0.0f64.ceil(), 0.0f64);
assert_approx_eq!((-0.0f64).ceil(), -0.0f64);
assert_approx_eq!((-1.0f64).ceil(), -1.0f64);
assert_approx_eq!((-1.3f64).ceil(), -1.0f64);
assert_approx_eq!((-1.5f64).ceil(), -1.0f64);
assert_approx_eq!((-1.7f64).ceil(), -1.0f64);
}
#[test]
fn test_round() {
assert_approx_eq!(1.0f64.round(), 1.0f64);
assert_approx_eq!(1.3f64.round(), 1.0f64);
assert_approx_eq!(1.5f64.round(), 2.0f64);
assert_approx_eq!(1.7f64.round(), 2.0f64);
assert_approx_eq!(0.0f64.round(), 0.0f64);
assert_approx_eq!((-0.0f64).round(), -0.0f64);
assert_approx_eq!((-1.0f64).round(), -1.0f64);
assert_approx_eq!((-1.3f64).round(), -1.0f64);
assert_approx_eq!((-1.5f64).round(), -2.0f64);
assert_approx_eq!((-1.7f64).round(), -2.0f64);
}
#[test]
fn test_trunc() {
assert_approx_eq!(1.0f64.trunc(), 1.0f64);
assert_approx_eq!(1.3f64.trunc(), 1.0f64);
assert_approx_eq!(1.5f64.trunc(), 1.0f64);
assert_approx_eq!(1.7f64.trunc(), 1.0f64);
assert_approx_eq!(0.0f64.trunc(), 0.0f64);
assert_approx_eq!((-0.0f64).trunc(), -0.0f64);
assert_approx_eq!((-1.0f64).trunc(), -1.0f64);
assert_approx_eq!((-1.3f64).trunc(), -1.0f64);
assert_approx_eq!((-1.5f64).trunc(), -1.0f64);
assert_approx_eq!((-1.7f64).trunc(), -1.0f64);
}
#[test]
fn test_fract() {
assert_approx_eq!(1.0f64.fract(), 0.0f64);
assert_approx_eq!(1.3f64.fract(), 0.3f64);
assert_approx_eq!(1.5f64.fract(), 0.5f64);
assert_approx_eq!(1.7f64.fract(), 0.7f64);
assert_approx_eq!(0.0f64.fract(), 0.0f64);
assert_approx_eq!((-0.0f64).fract(), -0.0f64);
assert_approx_eq!((-1.0f64).fract(), -0.0f64);
assert_approx_eq!((-1.3f64).fract(), -0.3f64);
assert_approx_eq!((-1.5f64).fract(), -0.5f64);
assert_approx_eq!((-1.7f64).fract(), -0.7f64);
}
#[test]
fn test_abs() {
assert_eq!(INFINITY.abs(), INFINITY);
assert_eq!(1f64.abs(), 1f64);
assert_eq!(0f64.abs(), 0f64);
assert_eq!((-0f64).abs(), 0f64);
assert_eq!((-1f64).abs(), 1f64);
assert_eq!(NEG_INFINITY.abs(), INFINITY);
assert_eq!((1f64/NEG_INFINITY).abs(), 0f64);
assert!(NAN.abs().is_nan());
}
#[test]
fn test_signum() {
assert_eq!(INFINITY.signum(), 1f64);
assert_eq!(1f64.signum(), 1f64);
assert_eq!(0f64.signum(), 1f64);
assert_eq!((-0f64).signum(), -1f64);
assert_eq!((-1f64).signum(), -1f64);
assert_eq!(NEG_INFINITY.signum(), -1f64);
assert_eq!((1f64/NEG_INFINITY).signum(), -1f64);
assert!(NAN.signum().is_nan());
}
#[test]
fn test_is_sign_positive() {
assert!(INFINITY.is_sign_positive());
assert!(1f64.is_sign_positive());
assert!(0f64.is_sign_positive());
assert!(!(-0f64).is_sign_positive());
assert!(!(-1f64).is_sign_positive());
assert!(!NEG_INFINITY.is_sign_positive());
assert!(!(1f64/NEG_INFINITY).is_sign_positive());
assert!(NAN.is_sign_positive());
assert!(!(-NAN).is_sign_positive());
}
#[test]
fn test_is_sign_negative() {
assert!(!INFINITY.is_sign_negative());
assert!(!1f64.is_sign_negative());
assert!(!0f64.is_sign_negative());
assert!((-0f64).is_sign_negative());
assert!((-1f64).is_sign_negative());
assert!(NEG_INFINITY.is_sign_negative());
assert!((1f64/NEG_INFINITY).is_sign_negative());
assert!(!NAN.is_sign_negative());
assert!((-NAN).is_sign_negative());
}
#[test]
fn test_mul_add() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_approx_eq!(12.3f64.mul_add(4.5, 6.7), 62.05);
assert_approx_eq!((-12.3f64).mul_add(-4.5, -6.7), 48.65);
assert_approx_eq!(0.0f64.mul_add(8.9, 1.2), 1.2);
assert_approx_eq!(3.4f64.mul_add(-0.0, 5.6), 5.6);
assert!(nan.mul_add(7.8, 9.0).is_nan());
assert_eq!(inf.mul_add(7.8, 9.0), inf);
assert_eq!(neg_inf.mul_add(7.8, 9.0), neg_inf);
assert_eq!(8.9f64.mul_add(inf, 3.2), inf);
assert_eq!((-3.2f64).mul_add(2.4, neg_inf), neg_inf);
}
#[test]
fn test_recip() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(1.0f64.recip(), 1.0);
assert_eq!(2.0f64.recip(), 0.5);
assert_eq!((-0.4f64).recip(), -2.5);
assert_eq!(0.0f64.recip(), inf);
assert!(nan.recip().is_nan());
assert_eq!(inf.recip(), 0.0);
assert_eq!(neg_inf.recip(), 0.0);
}
#[test]
fn test_powi() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(1.0f64.powi(1), 1.0);
assert_approx_eq!((-3.1f64).powi(2), 9.61);
assert_approx_eq!(5.9f64.powi(-2), 0.028727);
assert_eq!(8.3f64.powi(0), 1.0);
assert!(nan.powi(2).is_nan());
assert_eq!(inf.powi(3), inf);
assert_eq!(neg_inf.powi(2), inf);
}
#[test]
fn test_powf() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(1.0f64.powf(1.0), 1.0);
assert_approx_eq!(3.4f64.powf(4.5), 246.408183);
assert_approx_eq!(2.7f64.powf(-3.2), 0.041652);
assert_approx_eq!((-3.1f64).powf(2.0), 9.61);
assert_approx_eq!(5.9f64.powf(-2.0), 0.028727);
assert_eq!(8.3f64.powf(0.0), 1.0);
assert!(nan.powf(2.0).is_nan());
assert_eq!(inf.powf(2.0), inf);
assert_eq!(neg_inf.powf(3.0), neg_inf);
}
#[test]
fn test_sqrt_domain() {
assert!(NAN.sqrt().is_nan());
assert!(NEG_INFINITY.sqrt().is_nan());
assert!((-1.0f64).sqrt().is_nan());
assert_eq!((-0.0f64).sqrt(), -0.0);
assert_eq!(0.0f64.sqrt(), 0.0);
assert_eq!(1.0f64.sqrt(), 1.0);
assert_eq!(INFINITY.sqrt(), INFINITY);
}
#[test]
fn test_exp() {
assert_eq!(1.0, 0.0f64.exp());
assert_approx_eq!(2.718282, 1.0f64.exp());
assert_approx_eq!(148.413159, 5.0f64.exp());
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf, inf.exp());
assert_eq!(0.0, neg_inf.exp());
assert!(nan.exp().is_nan());
}
#[test]
fn test_exp2() {
assert_eq!(32.0, 5.0f64.exp2());
assert_eq!(1.0, 0.0f64.exp2());
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf, inf.exp2());
assert_eq!(0.0, neg_inf.exp2());
assert!(nan.exp2().is_nan());
}
#[test]
fn test_ln() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_approx_eq!(1.0f64.exp().ln(), 1.0);
assert!(nan.ln().is_nan());
assert_eq!(inf.ln(), inf);
assert!(neg_inf.ln().is_nan());
assert!((-2.3f64).ln().is_nan());
assert_eq!((-0.0f64).ln(), neg_inf);
assert_eq!(0.0f64.ln(), neg_inf);
assert_approx_eq!(4.0f64.ln(), 1.386294);
}
#[test]
fn test_log() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(10.0f64.log(10.0), 1.0);
assert_approx_eq!(2.3f64.log(3.5), 0.664858);
assert_eq!(1.0f64.exp().log(1.0f64.exp()), 1.0);
assert!(1.0f64.log(1.0).is_nan());
assert!(1.0f64.log(-13.9).is_nan());
assert!(nan.log(2.3).is_nan());
assert_eq!(inf.log(10.0), inf);
assert!(neg_inf.log(8.8).is_nan());
assert!((-2.3f64).log(0.1).is_nan());
assert_eq!((-0.0f64).log(2.0), neg_inf);
assert_eq!(0.0f64.log(7.0), neg_inf);
}
#[test]
fn test_log2() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_approx_eq!(10.0f64.log2(), 3.321928);
assert_approx_eq!(2.3f64.log2(), 1.201634);
assert_approx_eq!(1.0f64.exp().log2(), 1.442695);
assert!(nan.log2().is_nan());
assert_eq!(inf.log2(), inf);
assert!(neg_inf.log2().is_nan());
assert!((-2.3f64).log2().is_nan());
assert_eq!((-0.0f64).log2(), neg_inf);
assert_eq!(0.0f64.log2(), neg_inf);
}
#[test]
fn test_log10() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(10.0f64.log10(), 1.0);
assert_approx_eq!(2.3f64.log10(), 0.361728);
assert_approx_eq!(1.0f64.exp().log10(), 0.434294);
assert_eq!(1.0f64.log10(), 0.0);
assert!(nan.log10().is_nan());
assert_eq!(inf.log10(), inf);
assert!(neg_inf.log10().is_nan());
assert!((-2.3f64).log10().is_nan());
assert_eq!((-0.0f64).log10(), neg_inf);
assert_eq!(0.0f64.log10(), neg_inf);
}
#[test]
fn test_to_degrees() {
let pi: f64 = consts::PI;
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(0.0f64.to_degrees(), 0.0);
assert_approx_eq!((-5.8f64).to_degrees(), -332.315521);
assert_eq!(pi.to_degrees(), 180.0);
assert!(nan.to_degrees().is_nan());
assert_eq!(inf.to_degrees(), inf);
assert_eq!(neg_inf.to_degrees(), neg_inf);
}
#[test]
fn test_to_radians() {
let pi: f64 = consts::PI;
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(0.0f64.to_radians(), 0.0);
assert_approx_eq!(154.6f64.to_radians(), 2.698279);
assert_approx_eq!((-332.31f64).to_radians(), -5.799903);
assert_eq!(180.0f64.to_radians(), pi);
assert!(nan.to_radians().is_nan());
assert_eq!(inf.to_radians(), inf);
assert_eq!(neg_inf.to_radians(), neg_inf);
}
#[test]
fn test_asinh() {
assert_eq!(0.0f64.asinh(), 0.0f64);
assert_eq!((-0.0f64).asinh(), -0.0f64);
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf.asinh(), inf);
assert_eq!(neg_inf.asinh(), neg_inf);
assert!(nan.asinh().is_nan());
assert_approx_eq!(2.0f64.asinh(), 1.443635475178810342493276740273105f64);
assert_approx_eq!((-2.0f64).asinh(), -1.443635475178810342493276740273105f64);
}
#[test]
fn test_acosh() {
assert_eq!(1.0f64.acosh(), 0.0f64);
assert!(0.999f64.acosh().is_nan());
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf.acosh(), inf);
assert!(neg_inf.acosh().is_nan());
assert!(nan.acosh().is_nan());
assert_approx_eq!(2.0f64.acosh(), 1.31695789692481670862504634730796844f64);
assert_approx_eq!(3.0f64.acosh(), 1.76274717403908605046521864995958461f64);
}
#[test]
fn test_atanh() {
assert_eq!(0.0f64.atanh(), 0.0f64);
assert_eq!((-0.0f64).atanh(), -0.0f64);
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(1.0f64.atanh(), inf);
assert_eq!((-1.0f64).atanh(), neg_inf);
assert!(2f64.atanh().atanh().is_nan());
assert!((-2f64).atanh().atanh().is_nan());
assert!(inf.atanh().is_nan());
assert!(neg_inf.atanh().is_nan());
assert!(nan.atanh().is_nan());
assert_approx_eq!(0.5f64.atanh(), 0.54930614433405484569762261846126285f64);
assert_approx_eq!((-0.5f64).atanh(), -0.54930614433405484569762261846126285f64);
}
#[test]
fn test_real_consts() {
use super::consts;
let pi: f64 = consts::PI;
let frac_pi_2: f64 = consts::FRAC_PI_2;
let frac_pi_3: f64 = consts::FRAC_PI_3;
let frac_pi_4: f64 = consts::FRAC_PI_4;
let frac_pi_6: f64 = consts::FRAC_PI_6;
let frac_pi_8: f64 = consts::FRAC_PI_8;
let frac_1_pi: f64 = consts::FRAC_1_PI;
let frac_2_pi: f64 = consts::FRAC_2_PI;
let frac_2_sqrtpi: f64 = consts::FRAC_2_SQRT_PI;
let sqrt2: f64 = consts::SQRT_2;
let frac_1_sqrt2: f64 = consts::FRAC_1_SQRT_2;
let e: f64 = consts::E;
let log2_e: f64 = consts::LOG2_E;
let log10_e: f64 = consts::LOG10_E;
let ln_2: f64 = consts::LN_2;
let ln_10: f64 = consts::LN_10;
assert_approx_eq!(frac_pi_2, pi / 2f64);
assert_approx_eq!(frac_pi_3, pi / 3f64);
assert_approx_eq!(frac_pi_4, pi / 4f64);
assert_approx_eq!(frac_pi_6, pi / 6f64);
assert_approx_eq!(frac_pi_8, pi / 8f64);
assert_approx_eq!(frac_1_pi, 1f64 / pi);
assert_approx_eq!(frac_2_pi, 2f64 / pi);
assert_approx_eq!(frac_2_sqrtpi, 2f64 / pi.sqrt());
assert_approx_eq!(sqrt2, 2f64.sqrt());
assert_approx_eq!(frac_1_sqrt2, 1f64 / 2f64.sqrt());
assert_approx_eq!(log2_e, e.log2());
assert_approx_eq!(log10_e, e.log10());
assert_approx_eq!(ln_2, 2f64.ln());
assert_approx_eq!(ln_10, 10f64.ln());
}
#[test]
fn test_float_bits_conv() {
assert_eq!((1f64).to_bits(), 0x3ff0000000000000);
assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
assert_eq!((1337f64).to_bits(), 0x4094e40000000000);
assert_eq!((-14.25f64).to_bits(), 0xc02c800000000000);
assert_approx_eq!(f64::from_bits(0x3ff0000000000000), 1.0);
assert_approx_eq!(f64::from_bits(0x4029000000000000), 12.5);
assert_approx_eq!(f64::from_bits(0x4094e40000000000), 1337.0);
assert_approx_eq!(f64::from_bits(0xc02c800000000000), -14.25);
// Check that NaNs roundtrip their bits regardless of signalingness
// 0xA is 0b1010; 0x5 is 0b0101 -- so these two together clobbers all the mantissa bits
let masked_nan1 = f64::NAN.to_bits() ^ 0x000A_AAAA_AAAA_AAAA;
let masked_nan2 = f64::NAN.to_bits() ^ 0x0005_5555_5555_5555;
assert!(f64::from_bits(masked_nan1).is_nan());
assert!(f64::from_bits(masked_nan2).is_nan());
assert_eq!(f64::from_bits(masked_nan1).to_bits(), masked_nan1);
assert_eq!(f64::from_bits(masked_nan2).to_bits(), masked_nan2);
}
}
| 30.273817 | 99 | 0.510948 |
89bdcf8117d97107b782f66da4799d186f78c565 | 11,968 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::Value;
use glib_sys;
use gobject_sys;
use gst;
use gst_audio_sys;
use gst_base;
use std::boxed::Box as Box_;
use std::mem::transmute;
glib_wrapper! {
pub struct AudioBaseSrc(Object<gst_audio_sys::GstAudioBaseSrc, gst_audio_sys::GstAudioBaseSrcClass, AudioBaseSrcClass>) @extends gst_base::BaseSrc, gst::Element, gst::Object;
match fn {
get_type => || gst_audio_sys::gst_audio_base_src_get_type(),
}
}
unsafe impl Send for AudioBaseSrc {}
unsafe impl Sync for AudioBaseSrc {}
pub const NONE_AUDIO_BASE_SRC: Option<&AudioBaseSrc> = None;
pub trait AudioBaseSrcExt: 'static {
//fn create_ringbuffer(&self) -> /*Ignored*/Option<AudioRingBuffer>;
fn get_provide_clock(&self) -> bool;
//fn get_slave_method(&self) -> /*Ignored*/AudioBaseSrcSlaveMethod;
fn set_provide_clock(&self, provide: bool);
//fn set_slave_method(&self, method: /*Ignored*/AudioBaseSrcSlaveMethod);
fn get_property_actual_buffer_time(&self) -> i64;
fn get_property_actual_latency_time(&self) -> i64;
fn get_property_buffer_time(&self) -> i64;
fn set_property_buffer_time(&self, buffer_time: i64);
fn get_property_latency_time(&self) -> i64;
fn set_property_latency_time(&self, latency_time: i64);
fn connect_property_actual_buffer_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_actual_latency_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_buffer_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_latency_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_provide_clock_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_slave_method_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId;
}
impl<O: IsA<AudioBaseSrc>> AudioBaseSrcExt for O {
//fn create_ringbuffer(&self) -> /*Ignored*/Option<AudioRingBuffer> {
// unsafe { TODO: call gst_audio_sys:gst_audio_base_src_create_ringbuffer() }
//}
fn get_provide_clock(&self) -> bool {
unsafe {
from_glib(gst_audio_sys::gst_audio_base_src_get_provide_clock(
self.as_ref().to_glib_none().0,
))
}
}
//fn get_slave_method(&self) -> /*Ignored*/AudioBaseSrcSlaveMethod {
// unsafe { TODO: call gst_audio_sys:gst_audio_base_src_get_slave_method() }
//}
fn set_provide_clock(&self, provide: bool) {
unsafe {
gst_audio_sys::gst_audio_base_src_set_provide_clock(
self.as_ref().to_glib_none().0,
provide.to_glib(),
);
}
}
//fn set_slave_method(&self, method: /*Ignored*/AudioBaseSrcSlaveMethod) {
// unsafe { TODO: call gst_audio_sys:gst_audio_base_src_set_slave_method() }
//}
fn get_property_actual_buffer_time(&self) -> i64 {
unsafe {
let mut value = Value::from_type(<i64 as StaticType>::static_type());
gobject_sys::g_object_get_property(
self.to_glib_none().0 as *mut gobject_sys::GObject,
b"actual-buffer-time\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `actual-buffer-time` getter")
.unwrap()
}
}
fn get_property_actual_latency_time(&self) -> i64 {
unsafe {
let mut value = Value::from_type(<i64 as StaticType>::static_type());
gobject_sys::g_object_get_property(
self.to_glib_none().0 as *mut gobject_sys::GObject,
b"actual-latency-time\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `actual-latency-time` getter")
.unwrap()
}
}
fn get_property_buffer_time(&self) -> i64 {
unsafe {
let mut value = Value::from_type(<i64 as StaticType>::static_type());
gobject_sys::g_object_get_property(
self.to_glib_none().0 as *mut gobject_sys::GObject,
b"buffer-time\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `buffer-time` getter")
.unwrap()
}
}
fn set_property_buffer_time(&self, buffer_time: i64) {
unsafe {
gobject_sys::g_object_set_property(
self.to_glib_none().0 as *mut gobject_sys::GObject,
b"buffer-time\0".as_ptr() as *const _,
Value::from(&buffer_time).to_glib_none().0,
);
}
}
fn get_property_latency_time(&self) -> i64 {
unsafe {
let mut value = Value::from_type(<i64 as StaticType>::static_type());
gobject_sys::g_object_get_property(
self.to_glib_none().0 as *mut gobject_sys::GObject,
b"latency-time\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `latency-time` getter")
.unwrap()
}
}
fn set_property_latency_time(&self, latency_time: i64) {
unsafe {
gobject_sys::g_object_set_property(
self.to_glib_none().0 as *mut gobject_sys::GObject,
b"latency-time\0".as_ptr() as *const _,
Value::from(&latency_time).to_glib_none().0,
);
}
}
fn connect_property_actual_buffer_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_actual_buffer_time_trampoline<
P,
F: Fn(&P) + Send + Sync + 'static,
>(
this: *mut gst_audio_sys::GstAudioBaseSrc,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<AudioBaseSrc>,
{
let f: &F = &*(f as *const F);
f(&AudioBaseSrc::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::actual-buffer-time\0".as_ptr() as *const _,
Some(transmute(
notify_actual_buffer_time_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
fn connect_property_actual_latency_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_actual_latency_time_trampoline<
P,
F: Fn(&P) + Send + Sync + 'static,
>(
this: *mut gst_audio_sys::GstAudioBaseSrc,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<AudioBaseSrc>,
{
let f: &F = &*(f as *const F);
f(&AudioBaseSrc::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::actual-latency-time\0".as_ptr() as *const _,
Some(transmute(
notify_actual_latency_time_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
fn connect_property_buffer_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_buffer_time_trampoline<P, F: Fn(&P) + Send + Sync + 'static>(
this: *mut gst_audio_sys::GstAudioBaseSrc,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<AudioBaseSrc>,
{
let f: &F = &*(f as *const F);
f(&AudioBaseSrc::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::buffer-time\0".as_ptr() as *const _,
Some(transmute(notify_buffer_time_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_latency_time_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_latency_time_trampoline<P, F: Fn(&P) + Send + Sync + 'static>(
this: *mut gst_audio_sys::GstAudioBaseSrc,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<AudioBaseSrc>,
{
let f: &F = &*(f as *const F);
f(&AudioBaseSrc::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::latency-time\0".as_ptr() as *const _,
Some(transmute(
notify_latency_time_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
fn connect_property_provide_clock_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_provide_clock_trampoline<P, F: Fn(&P) + Send + Sync + 'static>(
this: *mut gst_audio_sys::GstAudioBaseSrc,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<AudioBaseSrc>,
{
let f: &F = &*(f as *const F);
f(&AudioBaseSrc::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::provide-clock\0".as_ptr() as *const _,
Some(transmute(
notify_provide_clock_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
fn connect_property_slave_method_notify<F: Fn(&Self) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_slave_method_trampoline<P, F: Fn(&P) + Send + Sync + 'static>(
this: *mut gst_audio_sys::GstAudioBaseSrc,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<AudioBaseSrc>,
{
let f: &F = &*(f as *const F);
f(&AudioBaseSrc::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::slave-method\0".as_ptr() as *const _,
Some(transmute(
notify_slave_method_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
}
| 32.969697 | 178 | 0.543115 |
4a03088505b93e20c3f4e5a58452cac8b71cca84 | 2,397 | use crate::messages::a2a::A2AMessage;
use crate::messages::error::ProblemReport;
use crate::messages::issuance::credential::Credential;
use crate::messages::issuance::credential_ack::CredentialAck;
use crate::messages::issuance::credential_offer::CredentialOffer;
use crate::messages::issuance::credential_proposal::{CredentialProposal, CredentialProposalData};
use crate::messages::issuance::credential_request::CredentialRequest;
type OptionalComment = Option<String>;
#[derive(Debug, Clone)]
pub enum CredentialIssuanceAction {
CredentialSend(),
CredentialProposalSend(CredentialProposalData),
CredentialProposal(CredentialProposal),
CredentialOffer(CredentialOffer),
CredentialOfferReject(OptionalComment),
CredentialRequestSend(String),
CredentialRequest(CredentialRequest),
Credential(Credential),
CredentialAck(CredentialAck),
ProblemReport(ProblemReport),
Unknown,
}
impl CredentialIssuanceAction {
pub fn thread_id_matches(&self, thread_id: &str) -> bool {
match self {
Self::CredentialOffer(credential_offer) => credential_offer.from_thread(thread_id),
Self::CredentialProposal(credential_proposal) => credential_proposal.from_thread(thread_id),
Self::Credential(credential) => credential.from_thread(thread_id),
_ => true
}
}
}
impl From<A2AMessage> for CredentialIssuanceAction {
fn from(msg: A2AMessage) -> Self {
match msg {
A2AMessage::CredentialProposal(proposal) => {
CredentialIssuanceAction::CredentialProposal(proposal)
}
A2AMessage::CredentialOffer(offer) => {
CredentialIssuanceAction::CredentialOffer(offer)
}
A2AMessage::CredentialRequest(request) => {
CredentialIssuanceAction::CredentialRequest(request)
}
A2AMessage::Credential(credential) => {
CredentialIssuanceAction::Credential(credential)
}
A2AMessage::Ack(ack) | A2AMessage::CredentialAck(ack) => {
CredentialIssuanceAction::CredentialAck(ack)
}
A2AMessage::CommonProblemReport(report) => {
CredentialIssuanceAction::ProblemReport(report)
}
_ => {
CredentialIssuanceAction::Unknown
}
}
}
}
| 37.453125 | 104 | 0.670004 |
2170e3c72d34f44d0a0324b6dad9a4266fe5d22d | 52,697 | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use deno_core::error::custom_error;
use deno_core::error::not_supported;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::include_js_files;
use deno_core::op_async;
use deno_core::op_sync;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde::Deserialize;
use serde::Serialize;
use std::cell::RefCell;
use std::num::NonZeroU32;
use std::rc::Rc;
use block_modes::BlockMode;
use lazy_static::lazy_static;
use num_traits::cast::FromPrimitive;
use rand::rngs::OsRng;
use rand::rngs::StdRng;
use rand::thread_rng;
use rand::Rng;
use rand::SeedableRng;
use ring::digest;
use ring::hkdf;
use ring::hmac::Algorithm as HmacAlgorithm;
use ring::hmac::Key as HmacKey;
use ring::pbkdf2;
use ring::rand as RingRand;
use ring::rand::SecureRandom;
use ring::signature::EcdsaKeyPair;
use ring::signature::EcdsaSigningAlgorithm;
use ring::signature::EcdsaVerificationAlgorithm;
use ring::signature::KeyPair;
use rsa::padding::PaddingScheme;
use rsa::pkcs1::der::Decodable;
use rsa::pkcs1::der::Encodable;
use rsa::pkcs1::FromRsaPrivateKey;
use rsa::pkcs1::ToRsaPrivateKey;
use rsa::pkcs8::der::asn1;
use rsa::pkcs8::FromPrivateKey;
use rsa::BigUint;
use rsa::PublicKey;
use rsa::RsaPrivateKey;
use rsa::RsaPublicKey;
use sha1::Sha1;
use sha2::Digest;
use sha2::Sha256;
use sha2::Sha384;
use sha2::Sha512;
use std::path::PathBuf;
pub use rand; // Re-export rand
mod key;
use crate::key::Algorithm;
use crate::key::CryptoHash;
use crate::key::CryptoNamedCurve;
use crate::key::HkdfOutput;
// Allowlist for RSA public exponents.
lazy_static! {
static ref PUB_EXPONENT_1: BigUint = BigUint::from_u64(3).unwrap();
static ref PUB_EXPONENT_2: BigUint = BigUint::from_u64(65537).unwrap();
}
const RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.1");
const SHA1_RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.5");
const SHA256_RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.11");
const SHA384_RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.12");
const SHA512_RSA_ENCRYPTION_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.13");
const RSASSA_PSS_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.10");
const ID_SHA1_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.3.14.3.2.26");
const ID_SHA256_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("2.16.840.1.101.3.4.2.1");
const ID_SHA384_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("2.16.840.1.101.3.4.2.2");
const ID_SHA512_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("2.16.840.1.101.3.4.2.3");
const ID_MFG1: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.8");
const RSAES_OAEP_OID: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.7");
const ID_P_SPECIFIED: rsa::pkcs8::ObjectIdentifier =
rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.9");
pub fn init(maybe_seed: Option<u64>) -> Extension {
Extension::builder()
.js(include_js_files!(
prefix "deno:ext/crypto",
"00_crypto.js",
"01_webidl.js",
))
.ops(vec![
(
"op_crypto_get_random_values",
op_sync(op_crypto_get_random_values),
),
("op_crypto_generate_key", op_async(op_crypto_generate_key)),
("op_crypto_sign_key", op_async(op_crypto_sign_key)),
("op_crypto_verify_key", op_async(op_crypto_verify_key)),
("op_crypto_derive_bits", op_async(op_crypto_derive_bits)),
("op_crypto_import_key", op_async(op_crypto_import_key)),
("op_crypto_export_key", op_async(op_crypto_export_key)),
("op_crypto_encrypt_key", op_async(op_crypto_encrypt_key)),
("op_crypto_decrypt_key", op_async(op_crypto_decrypt_key)),
("op_crypto_subtle_digest", op_async(op_crypto_subtle_digest)),
("op_crypto_random_uuid", op_sync(op_crypto_random_uuid)),
])
.state(move |state| {
if let Some(seed) = maybe_seed {
state.put(StdRng::seed_from_u64(seed));
}
Ok(())
})
.build()
}
pub fn op_crypto_get_random_values(
state: &mut OpState,
mut zero_copy: ZeroCopyBuf,
_: (),
) -> Result<(), AnyError> {
if zero_copy.len() > 65536 {
return Err(
deno_web::DomExceptionQuotaExceededError::new(&format!("The ArrayBufferView's byte length ({}) exceeds the number of bytes of entropy available via this API (65536)", zero_copy.len()))
.into(),
);
}
let maybe_seeded_rng = state.try_borrow_mut::<StdRng>();
if let Some(seeded_rng) = maybe_seeded_rng {
seeded_rng.fill(&mut *zero_copy);
} else {
let mut rng = thread_rng();
rng.fill(&mut *zero_copy);
}
Ok(())
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlgorithmArg {
name: Algorithm,
modulus_length: Option<u32>,
public_exponent: Option<ZeroCopyBuf>,
named_curve: Option<CryptoNamedCurve>,
hash: Option<CryptoHash>,
length: Option<usize>,
}
pub async fn op_crypto_generate_key(
_state: Rc<RefCell<OpState>>,
args: AlgorithmArg,
_: (),
) -> Result<ZeroCopyBuf, AnyError> {
let algorithm = args.name;
let key = match algorithm {
Algorithm::RsassaPkcs1v15 | Algorithm::RsaPss | Algorithm::RsaOaep => {
let public_exponent = args.public_exponent.ok_or_else(not_supported)?;
let modulus_length = args.modulus_length.ok_or_else(not_supported)?;
let exponent = BigUint::from_bytes_be(&public_exponent);
if exponent != *PUB_EXPONENT_1 && exponent != *PUB_EXPONENT_2 {
return Err(custom_error(
"DOMExceptionOperationError",
"Bad public exponent",
));
}
let mut rng = OsRng;
let private_key: RsaPrivateKey = tokio::task::spawn_blocking(
move || -> Result<RsaPrivateKey, rsa::errors::Error> {
RsaPrivateKey::new_with_exp(
&mut rng,
modulus_length as usize,
&exponent,
)
},
)
.await
.unwrap()
.map_err(|e| custom_error("DOMExceptionOperationError", e.to_string()))?;
private_key.to_pkcs1_der()?.as_ref().to_vec()
}
Algorithm::Ecdsa | Algorithm::Ecdh => {
let curve: &EcdsaSigningAlgorithm =
args.named_curve.ok_or_else(not_supported)?.into();
let rng = RingRand::SystemRandom::new();
let private_key: Vec<u8> = tokio::task::spawn_blocking(
move || -> Result<Vec<u8>, ring::error::Unspecified> {
let pkcs8 = EcdsaKeyPair::generate_pkcs8(curve, &rng)?;
Ok(pkcs8.as_ref().to_vec())
},
)
.await
.unwrap()
.map_err(|_| {
custom_error("DOMExceptionOperationError", "Key generation failed")
})?;
private_key
}
Algorithm::AesCtr
| Algorithm::AesCbc
| Algorithm::AesGcm
| Algorithm::AesKw => {
let length = args.length.ok_or_else(not_supported)?;
// Caller must guarantee divisibility by 8
let mut key_data = vec![0u8; length / 8];
let rng = RingRand::SystemRandom::new();
rng.fill(&mut key_data).map_err(|_| {
custom_error("DOMExceptionOperationError", "Key generation failed")
})?;
key_data
}
Algorithm::Hmac => {
let hash: HmacAlgorithm = args.hash.ok_or_else(not_supported)?.into();
let length = if let Some(length) = args.length {
if (length % 8) != 0 {
return Err(custom_error(
"DOMExceptionOperationError",
"hmac block length must be byte aligned",
));
}
let length = length / 8;
if length > ring::digest::MAX_BLOCK_LEN {
return Err(custom_error(
"DOMExceptionOperationError",
"hmac block length is too large",
));
}
length
} else {
hash.digest_algorithm().block_len
};
let rng = RingRand::SystemRandom::new();
let mut key_bytes = [0; ring::digest::MAX_BLOCK_LEN];
let key_bytes = &mut key_bytes[..length];
rng.fill(key_bytes).map_err(|_| {
custom_error("DOMExceptionOperationError", "Key generation failed")
})?;
key_bytes.to_vec()
}
_ => return Err(not_supported()),
};
Ok(key.into())
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KeyFormat {
Raw,
Pkcs8,
Spki,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub struct KeyData {
// TODO(littledivy): Kept here to be used to importKey() in future.
#[allow(dead_code)]
r#type: KeyFormat,
data: ZeroCopyBuf,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignArg {
key: KeyData,
algorithm: Algorithm,
salt_length: Option<u32>,
hash: Option<CryptoHash>,
named_curve: Option<CryptoNamedCurve>,
}
pub async fn op_crypto_sign_key(
_state: Rc<RefCell<OpState>>,
args: SignArg,
zero_copy: ZeroCopyBuf,
) -> Result<ZeroCopyBuf, AnyError> {
let data = &*zero_copy;
let algorithm = args.algorithm;
let signature = match algorithm {
Algorithm::RsassaPkcs1v15 => {
let private_key = RsaPrivateKey::from_pkcs1_der(&*args.key.data)?;
let (padding, hashed) = match args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?
{
CryptoHash::Sha1 => {
let mut hasher = Sha1::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA1),
},
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha256 => {
let mut hasher = Sha256::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA2_256),
},
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha384 => {
let mut hasher = Sha384::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA2_384),
},
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha512 => {
let mut hasher = Sha512::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA2_512),
},
hasher.finalize()[..].to_vec(),
)
}
};
private_key.sign(padding, &hashed)?
}
Algorithm::RsaPss => {
let private_key = RsaPrivateKey::from_pkcs1_der(&*args.key.data)?;
let salt_len = args
.salt_length
.ok_or_else(|| type_error("Missing argument saltLength".to_string()))?
as usize;
let rng = OsRng;
let (padding, digest_in) = match args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?
{
CryptoHash::Sha1 => {
let mut hasher = Sha1::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha1, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha256 => {
let mut hasher = Sha256::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha256, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha384 => {
let mut hasher = Sha384::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha384, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha512 => {
let mut hasher = Sha512::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha512, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
};
// Sign data based on computed padding and return buffer
private_key.sign(padding, &digest_in)?
}
Algorithm::Ecdsa => {
let curve: &EcdsaSigningAlgorithm =
args.named_curve.ok_or_else(not_supported)?.try_into()?;
let key_pair = EcdsaKeyPair::from_pkcs8(curve, &*args.key.data)?;
// We only support P256-SHA256 & P384-SHA384. These are recommended signature pairs.
// https://briansmith.org/rustdoc/ring/signature/index.html#statics
if let Some(hash) = args.hash {
match hash {
CryptoHash::Sha256 | CryptoHash::Sha384 => (),
_ => return Err(type_error("Unsupported algorithm")),
}
};
let rng = RingRand::SystemRandom::new();
let signature = key_pair.sign(&rng, data)?;
// Signature data as buffer.
signature.as_ref().to_vec()
}
Algorithm::Hmac => {
let hash: HmacAlgorithm = args.hash.ok_or_else(not_supported)?.into();
let key = HmacKey::new(hash, &*args.key.data);
let signature = ring::hmac::sign(&key, data);
signature.as_ref().to_vec()
}
_ => return Err(type_error("Unsupported algorithm".to_string())),
};
Ok(signature.into())
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyArg {
key: KeyData,
algorithm: Algorithm,
salt_length: Option<u32>,
hash: Option<CryptoHash>,
signature: ZeroCopyBuf,
named_curve: Option<CryptoNamedCurve>,
}
pub async fn op_crypto_verify_key(
_state: Rc<RefCell<OpState>>,
args: VerifyArg,
zero_copy: ZeroCopyBuf,
) -> Result<bool, AnyError> {
let data = &*zero_copy;
let algorithm = args.algorithm;
let verification = match algorithm {
Algorithm::RsassaPkcs1v15 => {
let public_key: RsaPublicKey =
RsaPrivateKey::from_pkcs1_der(&*args.key.data)?.to_public_key();
let (padding, hashed) = match args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?
{
CryptoHash::Sha1 => {
let mut hasher = Sha1::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA1),
},
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha256 => {
let mut hasher = Sha256::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA2_256),
},
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha384 => {
let mut hasher = Sha384::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA2_384),
},
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha512 => {
let mut hasher = Sha512::new();
hasher.update(&data);
(
PaddingScheme::PKCS1v15Sign {
hash: Some(rsa::hash::Hash::SHA2_512),
},
hasher.finalize()[..].to_vec(),
)
}
};
public_key
.verify(padding, &hashed, &*args.signature)
.is_ok()
}
Algorithm::RsaPss => {
let salt_len = args
.salt_length
.ok_or_else(|| type_error("Missing argument saltLength".to_string()))?
as usize;
let public_key: RsaPublicKey =
RsaPrivateKey::from_pkcs1_der(&*args.key.data)?.to_public_key();
let rng = OsRng;
let (padding, hashed) = match args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?
{
CryptoHash::Sha1 => {
let mut hasher = Sha1::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha1, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha256 => {
let mut hasher = Sha256::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha256, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha384 => {
let mut hasher = Sha384::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha384, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
CryptoHash::Sha512 => {
let mut hasher = Sha512::new();
hasher.update(&data);
(
PaddingScheme::new_pss_with_salt::<Sha512, _>(rng, salt_len),
hasher.finalize()[..].to_vec(),
)
}
};
public_key
.verify(padding, &hashed, &*args.signature)
.is_ok()
}
Algorithm::Hmac => {
let hash: HmacAlgorithm = args.hash.ok_or_else(not_supported)?.into();
let key = HmacKey::new(hash, &*args.key.data);
ring::hmac::verify(&key, data, &*args.signature).is_ok()
}
Algorithm::Ecdsa => {
let signing_alg: &EcdsaSigningAlgorithm =
args.named_curve.ok_or_else(not_supported)?.try_into()?;
let verify_alg: &EcdsaVerificationAlgorithm =
args.named_curve.ok_or_else(not_supported)?.try_into()?;
let private_key = EcdsaKeyPair::from_pkcs8(signing_alg, &*args.key.data)?;
let public_key_bytes = private_key.public_key().as_ref();
let public_key =
ring::signature::UnparsedPublicKey::new(verify_alg, public_key_bytes);
public_key.verify(data, &*args.signature).is_ok()
}
_ => return Err(type_error("Unsupported algorithm".to_string())),
};
Ok(verification)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportKeyArg {
key: KeyData,
algorithm: Algorithm,
format: KeyFormat,
// RSA-PSS
hash: Option<CryptoHash>,
}
pub async fn op_crypto_export_key(
_state: Rc<RefCell<OpState>>,
args: ExportKeyArg,
_: (),
) -> Result<ZeroCopyBuf, AnyError> {
let algorithm = args.algorithm;
match algorithm {
Algorithm::RsassaPkcs1v15 => {
match args.format {
KeyFormat::Pkcs8 => {
// private_key is a PKCS#1 DER-encoded private key
let private_key = &args.key.data;
// the PKCS#8 v1 structure
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
// version is 0 when publickey is None
let pk_info = rsa::pkcs8::PrivateKeyInfo {
attributes: None,
public_key: None,
algorithm: rsa::pkcs8::AlgorithmIdentifier {
// rsaEncryption(1)
oid: rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.1"),
// parameters field should not be ommited (None).
// It MUST have ASN.1 type NULL as per defined in RFC 3279 Section 2.3.1
parameters: Some(asn1::Any::from(asn1::Null)),
},
private_key,
};
Ok(pk_info.to_der().as_ref().to_vec().into())
}
KeyFormat::Spki => {
// public_key is a PKCS#1 DER-encoded public key
let subject_public_key = &args.key.data;
// the SPKI structure
let key_info = spki::SubjectPublicKeyInfo {
algorithm: spki::AlgorithmIdentifier {
// rsaEncryption(1)
oid: spki::ObjectIdentifier::new("1.2.840.113549.1.1.1"),
// parameters field should not be ommited (None).
// It MUST have ASN.1 type NULL.
parameters: Some(asn1::Any::from(asn1::Null)),
},
subject_public_key,
};
// Infallible based on spec because of the way we import and generate keys.
let spki_der = key_info.to_vec().unwrap();
Ok(spki_der.into())
}
// TODO(@littledivy): jwk
_ => unreachable!(),
}
}
Algorithm::RsaPss => {
match args.format {
KeyFormat::Pkcs8 => {
// Intentionally unused but required. Not encoded into PKCS#8 (see below).
let _hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// private_key is a PKCS#1 DER-encoded private key
let private_key = &args.key.data;
// version is 0 when publickey is None
let pk_info = rsa::pkcs8::PrivateKeyInfo {
attributes: None,
public_key: None,
algorithm: rsa::pkcs8::AlgorithmIdentifier {
// Spec wants the OID to be id-RSASSA-PSS (1.2.840.113549.1.1.10) but ring and RSA do not support it.
// Instead, we use rsaEncryption (1.2.840.113549.1.1.1) as specified in RFC 3447.
// Node, Chromium and Firefox also use rsaEncryption (1.2.840.113549.1.1.1) and do not support id-RSASSA-PSS.
// parameters are set to NULL opposed to what spec wants (see above)
oid: rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.1"),
// parameters field should not be ommited (None).
// It MUST have ASN.1 type NULL as per defined in RFC 3279 Section 2.3.1
parameters: Some(asn1::Any::from(asn1::Null)),
},
private_key,
};
Ok(pk_info.to_der().as_ref().to_vec().into())
}
KeyFormat::Spki => {
// Intentionally unused but required. Not encoded into SPKI (see below).
let _hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// public_key is a PKCS#1 DER-encoded public key
let subject_public_key = &args.key.data;
// the SPKI structure
let key_info = spki::SubjectPublicKeyInfo {
algorithm: spki::AlgorithmIdentifier {
// rsaEncryption(1)
oid: spki::ObjectIdentifier::new("1.2.840.113549.1.1.1"),
// parameters field should not be ommited (None).
// It MUST have ASN.1 type NULL.
parameters: Some(asn1::Any::from(asn1::Null)),
},
subject_public_key,
};
// Infallible based on spec because of the way we import and generate keys.
let spki_der = key_info.to_vec().unwrap();
Ok(spki_der.into())
}
// TODO(@littledivy): jwk
_ => unreachable!(),
}
}
Algorithm::RsaOaep => {
match args.format {
KeyFormat::Pkcs8 => {
// Intentionally unused but required. Not encoded into PKCS#8 (see below).
let _hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// private_key is a PKCS#1 DER-encoded private key
let private_key = &args.key.data;
// version is 0 when publickey is None
let pk_info = rsa::pkcs8::PrivateKeyInfo {
attributes: None,
public_key: None,
algorithm: rsa::pkcs8::AlgorithmIdentifier {
// Spec wants the OID to be id-RSAES-OAEP (1.2.840.113549.1.1.10) but ring and RSA crate do not support it.
// Instead, we use rsaEncryption (1.2.840.113549.1.1.1) as specified in RFC 3447.
// Chromium and Firefox also use rsaEncryption (1.2.840.113549.1.1.1) and do not support id-RSAES-OAEP.
// parameters are set to NULL opposed to what spec wants (see above)
oid: rsa::pkcs8::ObjectIdentifier::new("1.2.840.113549.1.1.1"),
// parameters field should not be ommited (None).
// It MUST have ASN.1 type NULL as per defined in RFC 3279 Section 2.3.1
parameters: Some(asn1::Any::from(asn1::Null)),
},
private_key,
};
Ok(pk_info.to_der().as_ref().to_vec().into())
}
KeyFormat::Spki => {
// Intentionally unused but required. Not encoded into SPKI (see below).
let _hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// public_key is a PKCS#1 DER-encoded public key
let subject_public_key = &args.key.data;
// the SPKI structure
let key_info = spki::SubjectPublicKeyInfo {
algorithm: spki::AlgorithmIdentifier {
// rsaEncryption(1)
oid: spki::ObjectIdentifier::new("1.2.840.113549.1.1.1"),
// parameters field should not be ommited (None).
// It MUST have ASN.1 type NULL.
parameters: Some(asn1::Any::from(asn1::Null)),
},
subject_public_key,
};
// Infallible based on spec because of the way we import and generate keys.
let spki_der = key_info.to_vec().unwrap();
Ok(spki_der.into())
}
// TODO(@littledivy): jwk
_ => unreachable!(),
}
}
_ => Err(type_error("Unsupported algorithm".to_string())),
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeriveKeyArg {
key: KeyData,
algorithm: Algorithm,
hash: Option<CryptoHash>,
length: usize,
iterations: Option<u32>,
// ECDH
public_key: Option<KeyData>,
named_curve: Option<CryptoNamedCurve>,
// HKDF
info: Option<ZeroCopyBuf>,
}
pub async fn op_crypto_derive_bits(
_state: Rc<RefCell<OpState>>,
args: DeriveKeyArg,
zero_copy: Option<ZeroCopyBuf>,
) -> Result<ZeroCopyBuf, AnyError> {
let algorithm = args.algorithm;
match algorithm {
Algorithm::Pbkdf2 => {
let zero_copy = zero_copy.ok_or_else(not_supported)?;
let salt = &*zero_copy;
// The caller must validate these cases.
assert!(args.length > 0);
assert!(args.length % 8 == 0);
let algorithm = match args.hash.ok_or_else(not_supported)? {
CryptoHash::Sha1 => pbkdf2::PBKDF2_HMAC_SHA1,
CryptoHash::Sha256 => pbkdf2::PBKDF2_HMAC_SHA256,
CryptoHash::Sha384 => pbkdf2::PBKDF2_HMAC_SHA384,
CryptoHash::Sha512 => pbkdf2::PBKDF2_HMAC_SHA512,
};
// This will never panic. We have already checked length earlier.
let iterations =
NonZeroU32::new(args.iterations.ok_or_else(not_supported)?).unwrap();
let secret = args.key.data;
let mut out = vec![0; args.length / 8];
pbkdf2::derive(algorithm, iterations, salt, &secret, &mut out);
Ok(out.into())
}
Algorithm::Ecdh => {
let named_curve = args
.named_curve
.ok_or_else(|| type_error("Missing argument namedCurve".to_string()))?;
let public_key = args
.public_key
.ok_or_else(|| type_error("Missing argument publicKey".to_string()))?;
match named_curve {
CryptoNamedCurve::P256 => {
let secret_key = p256::SecretKey::from_pkcs8_der(&args.key.data)?;
let public_key =
p256::SecretKey::from_pkcs8_der(&public_key.data)?.public_key();
let shared_secret = p256::elliptic_curve::ecdh::diffie_hellman(
secret_key.to_secret_scalar(),
public_key.as_affine(),
);
Ok(shared_secret.as_bytes().to_vec().into())
}
// TODO(@littledivy): support for P384
// https://github.com/RustCrypto/elliptic-curves/issues/240
_ => Err(type_error("Unsupported namedCurve".to_string())),
}
}
Algorithm::Hkdf => {
let zero_copy = zero_copy.ok_or_else(not_supported)?;
let salt = &*zero_copy;
let algorithm = match args.hash.ok_or_else(not_supported)? {
CryptoHash::Sha1 => hkdf::HKDF_SHA1_FOR_LEGACY_USE_ONLY,
CryptoHash::Sha256 => hkdf::HKDF_SHA256,
CryptoHash::Sha384 => hkdf::HKDF_SHA384,
CryptoHash::Sha512 => hkdf::HKDF_SHA512,
};
let info = args
.info
.ok_or_else(|| type_error("Missing argument info".to_string()))?;
// IKM
let secret = args.key.data;
// L
let length = args.length / 8;
let salt = hkdf::Salt::new(algorithm, salt);
let prk = salt.extract(&secret);
let info = &[&*info];
let okm = prk.expand(info, HkdfOutput(length))?;
let mut r = vec![0u8; length];
okm.fill(&mut r)?;
Ok(r.into())
}
_ => Err(type_error("Unsupported algorithm".to_string())),
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EncryptArg {
key: KeyData,
algorithm: Algorithm,
// RSA-OAEP
hash: Option<CryptoHash>,
label: Option<ZeroCopyBuf>,
// AES-CBC
iv: Option<ZeroCopyBuf>,
length: Option<usize>,
}
pub async fn op_crypto_encrypt_key(
_state: Rc<RefCell<OpState>>,
args: EncryptArg,
zero_copy: ZeroCopyBuf,
) -> Result<ZeroCopyBuf, AnyError> {
let data = &*zero_copy;
let algorithm = args.algorithm;
match algorithm {
Algorithm::RsaOaep => {
let public_key: RsaPublicKey =
RsaPrivateKey::from_pkcs1_der(&*args.key.data)?.to_public_key();
let label = args.label.map(|l| String::from_utf8_lossy(&*l).to_string());
let mut rng = OsRng;
let padding = match args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?
{
CryptoHash::Sha1 => PaddingScheme::OAEP {
digest: Box::new(Sha1::new()),
mgf_digest: Box::new(Sha1::new()),
label,
},
CryptoHash::Sha256 => PaddingScheme::OAEP {
digest: Box::new(Sha256::new()),
mgf_digest: Box::new(Sha256::new()),
label,
},
CryptoHash::Sha384 => PaddingScheme::OAEP {
digest: Box::new(Sha384::new()),
mgf_digest: Box::new(Sha384::new()),
label,
},
CryptoHash::Sha512 => PaddingScheme::OAEP {
digest: Box::new(Sha512::new()),
mgf_digest: Box::new(Sha512::new()),
label,
},
};
Ok(
public_key
.encrypt(&mut rng, padding, data)
.map_err(|e| {
custom_error("DOMExceptionOperationError", e.to_string())
})?
.into(),
)
}
Algorithm::AesCbc => {
let key = &*args.key.data;
let length = args
.length
.ok_or_else(|| type_error("Missing argument length".to_string()))?;
let iv = args
.iv
.ok_or_else(|| type_error("Missing argument iv".to_string()))?;
// 2-3.
let ciphertext = match length {
128 => {
// Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
type Aes128Cbc =
block_modes::Cbc<aes::Aes128, block_modes::block_padding::Pkcs7>;
let cipher = Aes128Cbc::new_from_slices(key, &iv)?;
cipher.encrypt_vec(data)
}
192 => {
// Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
type Aes192Cbc =
block_modes::Cbc<aes::Aes192, block_modes::block_padding::Pkcs7>;
let cipher = Aes192Cbc::new_from_slices(key, &iv)?;
cipher.encrypt_vec(data)
}
256 => {
// Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
type Aes256Cbc =
block_modes::Cbc<aes::Aes256, block_modes::block_padding::Pkcs7>;
let cipher = Aes256Cbc::new_from_slices(key, &iv)?;
cipher.encrypt_vec(data)
}
_ => unreachable!(),
};
Ok(ciphertext.into())
}
_ => Err(type_error("Unsupported algorithm".to_string())),
}
}
// The parameters field associated with OID id-RSASSA-PSS
// Defined in RFC 3447, section A.2.3
//
// RSASSA-PSS-params ::= SEQUENCE {
// hashAlgorithm [0] HashAlgorithm DEFAULT sha1,
// maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1,
// saltLength [2] INTEGER DEFAULT 20,
// trailerField [3] TrailerField DEFAULT trailerFieldBC
// }
pub struct PssPrivateKeyParameters<'a> {
pub hash_algorithm: rsa::pkcs8::AlgorithmIdentifier<'a>,
pub mask_gen_algorithm: rsa::pkcs8::AlgorithmIdentifier<'a>,
pub salt_length: u32,
}
// Context-specific tag number for hashAlgorithm.
const HASH_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber =
rsa::pkcs8::der::TagNumber::new(0);
// Context-specific tag number for maskGenAlgorithm.
const MASK_GEN_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber =
rsa::pkcs8::der::TagNumber::new(1);
// Context-specific tag number for saltLength.
const SALT_LENGTH_TAG: rsa::pkcs8::der::TagNumber =
rsa::pkcs8::der::TagNumber::new(2);
// Context-specific tag number for pSourceAlgorithm
const P_SOURCE_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber =
rsa::pkcs8::der::TagNumber::new(2);
lazy_static! {
// Default HashAlgorithm for RSASSA-PSS-params (sha1)
//
// sha1 HashAlgorithm ::= {
// algorithm id-sha1,
// parameters SHA1Parameters : NULL
// }
//
// SHA1Parameters ::= NULL
static ref SHA1_HASH_ALGORITHM: rsa::pkcs8::AlgorithmIdentifier<'static> = rsa::pkcs8::AlgorithmIdentifier {
// id-sha1
oid: ID_SHA1_OID,
// NULL
parameters: Some(asn1::Any::from(asn1::Null)),
};
// TODO(@littledivy): `pkcs8` should provide AlgorithmIdentifier to Any conversion.
static ref ENCODED_SHA1_HASH_ALGORITHM: Vec<u8> = SHA1_HASH_ALGORITHM.to_vec().unwrap();
// Default MaskGenAlgrithm for RSASSA-PSS-params (mgf1SHA1)
//
// mgf1SHA1 MaskGenAlgorithm ::= {
// algorithm id-mgf1,
// parameters HashAlgorithm : sha1
// }
static ref MGF1_SHA1_MASK_ALGORITHM: rsa::pkcs8::AlgorithmIdentifier<'static> = rsa::pkcs8::AlgorithmIdentifier {
// id-mgf1
oid: ID_MFG1,
// sha1
parameters: Some(asn1::Any::from_der(&ENCODED_SHA1_HASH_ALGORITHM).unwrap()),
};
// Default PSourceAlgorithm for RSAES-OAEP-params
// The default label is an empty string.
//
// pSpecifiedEmpty PSourceAlgorithm ::= {
// algorithm id-pSpecified,
// parameters EncodingParameters : emptyString
// }
//
// emptyString EncodingParameters ::= ''H
static ref P_SPECIFIED_EMPTY: rsa::pkcs8::AlgorithmIdentifier<'static> = rsa::pkcs8::AlgorithmIdentifier {
// id-pSpecified
oid: ID_P_SPECIFIED,
// EncodingParameters
parameters: Some(asn1::Any::from(asn1::OctetString::new(b"").unwrap())),
};
}
impl<'a> TryFrom<rsa::pkcs8::der::asn1::Any<'a>>
for PssPrivateKeyParameters<'a>
{
type Error = rsa::pkcs8::der::Error;
fn try_from(
any: rsa::pkcs8::der::asn1::Any<'a>,
) -> rsa::pkcs8::der::Result<PssPrivateKeyParameters> {
any.sequence(|decoder| {
let hash_algorithm = decoder
.context_specific(HASH_ALGORITHM_TAG)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or(*SHA1_HASH_ALGORITHM);
let mask_gen_algorithm = decoder
.context_specific(MASK_GEN_ALGORITHM_TAG)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or(*MGF1_SHA1_MASK_ALGORITHM);
let salt_length = decoder
.context_specific(SALT_LENGTH_TAG)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or(20);
Ok(Self {
hash_algorithm,
mask_gen_algorithm,
salt_length,
})
})
}
}
// The parameters field associated with OID id-RSAES-OAEP
// Defined in RFC 3447, section A.2.1
//
// RSAES-OAEP-params ::= SEQUENCE {
// hashAlgorithm [0] HashAlgorithm DEFAULT sha1,
// maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1,
// pSourceAlgorithm [2] PSourceAlgorithm DEFAULT pSpecifiedEmpty
// }
pub struct OaepPrivateKeyParameters<'a> {
pub hash_algorithm: rsa::pkcs8::AlgorithmIdentifier<'a>,
pub mask_gen_algorithm: rsa::pkcs8::AlgorithmIdentifier<'a>,
pub p_source_algorithm: rsa::pkcs8::AlgorithmIdentifier<'a>,
}
impl<'a> TryFrom<rsa::pkcs8::der::asn1::Any<'a>>
for OaepPrivateKeyParameters<'a>
{
type Error = rsa::pkcs8::der::Error;
fn try_from(
any: rsa::pkcs8::der::asn1::Any<'a>,
) -> rsa::pkcs8::der::Result<OaepPrivateKeyParameters> {
any.sequence(|decoder| {
let hash_algorithm = decoder
.context_specific(HASH_ALGORITHM_TAG)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or(*SHA1_HASH_ALGORITHM);
let mask_gen_algorithm = decoder
.context_specific(MASK_GEN_ALGORITHM_TAG)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or(*MGF1_SHA1_MASK_ALGORITHM);
let p_source_algorithm = decoder
.context_specific(P_SOURCE_ALGORITHM_TAG)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or(*P_SPECIFIED_EMPTY);
Ok(Self {
hash_algorithm,
mask_gen_algorithm,
p_source_algorithm,
})
})
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImportKeyArg {
algorithm: Algorithm,
format: KeyFormat,
// RSASSA-PKCS1-v1_5
hash: Option<CryptoHash>,
// ECDSA
named_curve: Option<CryptoNamedCurve>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImportKeyResult {
data: ZeroCopyBuf,
// RSASSA-PKCS1-v1_5
public_exponent: Option<ZeroCopyBuf>,
modulus_length: Option<usize>,
}
pub async fn op_crypto_import_key(
_state: Rc<RefCell<OpState>>,
args: ImportKeyArg,
zero_copy: ZeroCopyBuf,
) -> Result<ImportKeyResult, AnyError> {
let data = &*zero_copy;
let algorithm = args.algorithm;
match algorithm {
Algorithm::Ecdsa => {
let curve = args.named_curve.ok_or_else(|| {
type_error("Missing argument named_curve".to_string())
})?;
match curve {
CryptoNamedCurve::P256 => {
// 1-2.
let point = p256::EncodedPoint::from_bytes(data)?;
// 3.
if point.is_identity() {
return Err(type_error("Invalid key data".to_string()));
}
}
CryptoNamedCurve::P384 => {
// 1-2.
let point = p384::EncodedPoint::from_bytes(data)?;
// 3.
if point.is_identity() {
return Err(type_error("Invalid key data".to_string()));
}
}
};
Ok(ImportKeyResult {
data: zero_copy,
modulus_length: None,
public_exponent: None,
})
}
Algorithm::RsassaPkcs1v15 => {
match args.format {
KeyFormat::Pkcs8 => {
let hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// 2-3.
let pk_info =
rsa::pkcs8::PrivateKeyInfo::from_der(data).map_err(|e| {
custom_error("DOMExceptionOperationError", e.to_string())
})?;
// 4-5.
let alg = pk_info.algorithm.oid;
// 6.
let pk_hash = match alg {
// rsaEncryption
RSA_ENCRYPTION_OID => None,
// sha1WithRSAEncryption
SHA1_RSA_ENCRYPTION_OID => Some(CryptoHash::Sha1),
// sha256WithRSAEncryption
SHA256_RSA_ENCRYPTION_OID => Some(CryptoHash::Sha256),
// sha384WithRSAEncryption
SHA384_RSA_ENCRYPTION_OID => Some(CryptoHash::Sha384),
// sha512WithRSAEncryption
SHA512_RSA_ENCRYPTION_OID => Some(CryptoHash::Sha512),
_ => return Err(type_error("Unsupported algorithm".to_string())),
};
// 7.
if let Some(pk_hash) = pk_hash {
if pk_hash != hash {
return Err(custom_error(
"DOMExceptionDataError",
"Hash mismatch".to_string(),
));
}
}
// 8-9.
let private_key =
rsa::pkcs1::RsaPrivateKey::from_der(pk_info.private_key).map_err(
|e| custom_error("DOMExceptionOperationError", e.to_string()),
)?;
let bytes_consumed = private_key.encoded_len().map_err(|e| {
custom_error("DOMExceptionDataError", e.to_string())
})?;
if bytes_consumed
!= rsa::pkcs1::der::Length::new(pk_info.private_key.len() as u16)
{
return Err(custom_error(
"DOMExceptionDataError",
"Some bytes were not consumed".to_string(),
));
}
Ok(ImportKeyResult {
data: pk_info.private_key.to_vec().into(),
public_exponent: Some(
private_key.public_exponent.as_bytes().to_vec().into(),
),
modulus_length: Some(private_key.modulus.as_bytes().len() * 8),
})
}
// TODO(@littledivy): spki
// TODO(@littledivy): jwk
_ => Err(type_error("Unsupported format".to_string())),
}
}
Algorithm::RsaPss => {
match args.format {
KeyFormat::Pkcs8 => {
let hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// 2-3.
let pk_info =
rsa::pkcs8::PrivateKeyInfo::from_der(data).map_err(|e| {
custom_error("DOMExceptionOperationError", e.to_string())
})?;
// 4-5.
let alg = pk_info.algorithm.oid;
// 6.
let pk_hash = match alg {
// rsaEncryption
RSA_ENCRYPTION_OID => None,
// id-RSASSA-PSS
RSASSA_PSS_OID => {
let params = PssPrivateKeyParameters::try_from(
pk_info.algorithm.parameters.ok_or_else(|| {
custom_error(
"DOMExceptionNotSupportedError",
"Malformed parameters".to_string(),
)
})?,
)
.map_err(|_| {
custom_error(
"DOMExceptionNotSupportedError",
"Malformed parameters".to_string(),
)
})?;
let hash_alg = params.hash_algorithm;
let hash = match hash_alg.oid {
// id-sha1
ID_SHA1_OID => Some(CryptoHash::Sha1),
// id-sha256
ID_SHA256_OID => Some(CryptoHash::Sha256),
// id-sha384
ID_SHA384_OID => Some(CryptoHash::Sha384),
// id-sha256
ID_SHA512_OID => Some(CryptoHash::Sha512),
_ => {
return Err(custom_error(
"DOMExceptionDataError",
"Unsupported hash algorithm".to_string(),
))
}
};
if params.mask_gen_algorithm.oid != ID_MFG1 {
return Err(custom_error(
"DOMExceptionNotSupportedError",
"Unsupported hash algorithm".to_string(),
));
}
hash
}
_ => {
return Err(custom_error(
"DOMExceptionDataError",
"Unsupported algorithm".to_string(),
))
}
};
// 7.
if let Some(pk_hash) = pk_hash {
if pk_hash != hash {
return Err(custom_error(
"DOMExceptionDataError",
"Hash mismatch".to_string(),
));
}
}
// 8-9.
let private_key =
rsa::pkcs1::RsaPrivateKey::from_der(pk_info.private_key).map_err(
|e| custom_error("DOMExceptionOperationError", e.to_string()),
)?;
let bytes_consumed = private_key
.encoded_len()
.map_err(|e| custom_error("DataError", e.to_string()))?;
if bytes_consumed
!= rsa::pkcs1::der::Length::new(pk_info.private_key.len() as u16)
{
return Err(custom_error(
"DOMExceptionDataError",
"Some bytes were not consumed".to_string(),
));
}
Ok(ImportKeyResult {
data: pk_info.private_key.to_vec().into(),
public_exponent: Some(
private_key.public_exponent.as_bytes().to_vec().into(),
),
modulus_length: Some(private_key.modulus.as_bytes().len() * 8),
})
}
// TODO(@littledivy): spki
// TODO(@littledivy): jwk
_ => Err(type_error("Unsupported format".to_string())),
}
}
Algorithm::RsaOaep => {
match args.format {
KeyFormat::Pkcs8 => {
let hash = args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?;
// 2-3.
let pk_info =
rsa::pkcs8::PrivateKeyInfo::from_der(data).map_err(|e| {
custom_error("DOMExceptionOperationError", e.to_string())
})?;
// 4-5.
let alg = pk_info.algorithm.oid;
// 6.
let pk_hash = match alg {
// rsaEncryption
RSA_ENCRYPTION_OID => None,
// id-RSAES-OAEP
RSAES_OAEP_OID => {
let params = OaepPrivateKeyParameters::try_from(
pk_info.algorithm.parameters.ok_or_else(|| {
custom_error(
"DOMExceptionNotSupportedError",
"Malformed parameters".to_string(),
)
})?,
)
.map_err(|_| {
custom_error(
"DOMExceptionNotSupportedError",
"Malformed parameters".to_string(),
)
})?;
let hash_alg = params.hash_algorithm;
let hash = match hash_alg.oid {
// id-sha1
ID_SHA1_OID => Some(CryptoHash::Sha1),
// id-sha256
ID_SHA256_OID => Some(CryptoHash::Sha256),
// id-sha384
ID_SHA384_OID => Some(CryptoHash::Sha384),
// id-sha256
ID_SHA512_OID => Some(CryptoHash::Sha512),
_ => {
return Err(custom_error(
"DOMExceptionDataError",
"Unsupported hash algorithm".to_string(),
))
}
};
if params.mask_gen_algorithm.oid != ID_MFG1 {
return Err(custom_error(
"DOMExceptionNotSupportedError",
"Unsupported hash algorithm".to_string(),
));
}
hash
}
_ => {
return Err(custom_error(
"DOMExceptionDataError",
"Unsupported algorithm".to_string(),
))
}
};
// 7.
if let Some(pk_hash) = pk_hash {
if pk_hash != hash {
return Err(custom_error(
"DOMExceptionDataError",
"Hash mismatch".to_string(),
));
}
}
// 8-9.
let private_key =
rsa::pkcs1::RsaPrivateKey::from_der(pk_info.private_key).map_err(
|e| custom_error("DOMExceptionOperationError", e.to_string()),
)?;
let bytes_consumed = private_key.encoded_len().map_err(|e| {
custom_error("DOMExceptionDataError", e.to_string())
})?;
if bytes_consumed
!= rsa::pkcs1::der::Length::new(pk_info.private_key.len() as u16)
{
return Err(custom_error(
"DOMExceptionDataError",
"Some bytes were not consumed".to_string(),
));
}
Ok(ImportKeyResult {
data: pk_info.private_key.to_vec().into(),
public_exponent: Some(
private_key.public_exponent.as_bytes().to_vec().into(),
),
modulus_length: Some(private_key.modulus.as_bytes().len() * 8),
})
}
// TODO(@littledivy): spki
// TODO(@littledivy): jwk
_ => Err(type_error("Unsupported format".to_string())),
}
}
_ => Err(type_error("Unsupported algorithm".to_string())),
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DecryptArg {
key: KeyData,
algorithm: Algorithm,
// RSA-OAEP
hash: Option<CryptoHash>,
label: Option<ZeroCopyBuf>,
// AES-CBC
iv: Option<ZeroCopyBuf>,
length: Option<usize>,
}
pub async fn op_crypto_decrypt_key(
_state: Rc<RefCell<OpState>>,
args: DecryptArg,
zero_copy: ZeroCopyBuf,
) -> Result<ZeroCopyBuf, AnyError> {
let data = &*zero_copy;
let algorithm = args.algorithm;
match algorithm {
Algorithm::RsaOaep => {
let private_key: RsaPrivateKey =
RsaPrivateKey::from_pkcs1_der(&*args.key.data)?;
let label = args.label.map(|l| String::from_utf8_lossy(&*l).to_string());
let padding = match args
.hash
.ok_or_else(|| type_error("Missing argument hash".to_string()))?
{
CryptoHash::Sha1 => PaddingScheme::OAEP {
digest: Box::new(Sha1::new()),
mgf_digest: Box::new(Sha1::new()),
label,
},
CryptoHash::Sha256 => PaddingScheme::OAEP {
digest: Box::new(Sha256::new()),
mgf_digest: Box::new(Sha256::new()),
label,
},
CryptoHash::Sha384 => PaddingScheme::OAEP {
digest: Box::new(Sha384::new()),
mgf_digest: Box::new(Sha384::new()),
label,
},
CryptoHash::Sha512 => PaddingScheme::OAEP {
digest: Box::new(Sha512::new()),
mgf_digest: Box::new(Sha512::new()),
label,
},
};
Ok(
private_key
.decrypt(padding, data)
.map_err(|e| {
custom_error("DOMExceptionOperationError", e.to_string())
})?
.into(),
)
}
Algorithm::AesCbc => {
let key = &*args.key.data;
let length = args
.length
.ok_or_else(|| type_error("Missing argument length".to_string()))?;
let iv = args
.iv
.ok_or_else(|| type_error("Missing argument iv".to_string()))?;
// 2.
let plaintext = match length {
128 => {
// Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
type Aes128Cbc =
block_modes::Cbc<aes::Aes128, block_modes::block_padding::Pkcs7>;
let cipher = Aes128Cbc::new_from_slices(key, &iv)?;
cipher.decrypt_vec(data)?
}
192 => {
// Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
type Aes192Cbc =
block_modes::Cbc<aes::Aes192, block_modes::block_padding::Pkcs7>;
let cipher = Aes192Cbc::new_from_slices(key, &iv)?;
cipher.decrypt_vec(data)?
}
256 => {
// Section 10.3 Step 2 of RFC 2315 https://www.rfc-editor.org/rfc/rfc2315
type Aes256Cbc =
block_modes::Cbc<aes::Aes256, block_modes::block_padding::Pkcs7>;
let cipher = Aes256Cbc::new_from_slices(key, &iv)?;
cipher.decrypt_vec(data)?
}
_ => unreachable!(),
};
// 6.
Ok(plaintext.into())
}
_ => Err(type_error("Unsupported algorithm".to_string())),
}
}
pub fn op_crypto_random_uuid(
state: &mut OpState,
_: (),
_: (),
) -> Result<String, AnyError> {
let maybe_seeded_rng = state.try_borrow_mut::<StdRng>();
let uuid = if let Some(seeded_rng) = maybe_seeded_rng {
let mut bytes = [0u8; 16];
seeded_rng.fill(&mut bytes);
uuid::Builder::from_bytes(bytes)
.set_version(uuid::Version::Random)
.build()
} else {
uuid::Uuid::new_v4()
};
Ok(uuid.to_string())
}
pub async fn op_crypto_subtle_digest(
_state: Rc<RefCell<OpState>>,
algorithm: CryptoHash,
data: ZeroCopyBuf,
) -> Result<ZeroCopyBuf, AnyError> {
let output = tokio::task::spawn_blocking(move || {
digest::digest(algorithm.into(), &data)
.as_ref()
.to_vec()
.into()
})
.await?;
Ok(output)
}
pub fn get_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_crypto.d.ts")
}
| 31.592926 | 190 | 0.578192 |
038c9e8658fd2eb00433ea1c371f270685dae2b5 | 1,601 | /* Copyright (c) 2021 Jeremy Carter <[email protected]>
All uses of this project in part or in whole are governed
by the terms of the license contained in the file titled
"LICENSE" that's distributed along with the project, which
can be found in the top-level directory of this project.
If you don't agree to follow those terms or you won't
follow them, you are not allowed to use this project or
anything that's made with parts of it at all. The project
is also depending on some third-party technologies, and
some of those are governed by their own separate licenses,
so furthermore, whenever legally possible, all license
terms from all of the different technologies apply, with
this project's license terms taking first priority.
*/
use libnov::{conf, view::*, window::*};
fn main() {
println!(
"Starting Nov...
You can run this with a filename as the first \
argument to specify which image to load, otherwise \
a default image will be loaded.
"
);
let res = libnov::main(Ok(()), |view: &mut View, res| {
let view_name = view.get_name();
println!("[ {} available ]\n", view_name);
#[cfg(feature = "python")]
if view.feature_python.is_some() {
println!(
"[ {} feature available ]: {}",
view_name,
view.feature_python.as_ref().unwrap()
);
}
// This must run last.
Window::new(conf::load(None)?).open_image(res.clone());
res
});
std::process::exit(libnov::exit(res));
}
| 30.788462 | 63 | 0.63148 |
e960826befa05afbcdf4a420bc7b7d387a2bf2c0 | 106 | use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn opt_fn(_a: Option<i32>) -> Option<i32> {
None
}
| 15.142857 | 47 | 0.650943 |
ebcea334524ee1c942eb462f3897a872ac2c8bec | 2,578 | #[doc = "Reader of register CTRL"]
pub type R = crate::R<u32, super::CTRL>;
#[doc = "Writer for register CTRL"]
pub type W = crate::W<u32, super::CTRL>;
#[doc = "Register CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `Reserved31`"]
pub type RESERVED31_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `Reserved31`"]
pub struct RESERVED31_W<'a> {
w: &'a mut W,
}
impl<'a> RESERVED31_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7fff_ffff << 1)) | (((value as u32) & 0x7fff_ffff) << 1);
self.w
}
}
#[doc = "Reader of field `DA`"]
pub type DA_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DA`"]
pub struct DA_W<'a> {
w: &'a mut W,
}
impl<'a> DA_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bits 1:31 - 31:1\\] Software should not rely on the value of a reserved bit. To provide compatibility with future products, the value of a reserved bit should be preserved across a read-modify-write operation."]
#[inline(always)]
pub fn reserved31(&self) -> RESERVED31_R {
RESERVED31_R::new(((self.bits >> 1) & 0x7fff_ffff) as u32)
}
#[doc = "Bit 0 - 0:0\\] Device active 0: Disables the I2C slave operation 1: Enables the I2C slave operation"]
#[inline(always)]
pub fn da(&self) -> DA_R {
DA_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 1:31 - 31:1\\] Software should not rely on the value of a reserved bit. To provide compatibility with future products, the value of a reserved bit should be preserved across a read-modify-write operation."]
#[inline(always)]
pub fn reserved31(&mut self) -> RESERVED31_W {
RESERVED31_W { w: self }
}
#[doc = "Bit 0 - 0:0\\] Device active 0: Disables the I2C slave operation 1: Enables the I2C slave operation"]
#[inline(always)]
pub fn da(&mut self) -> DA_W {
DA_W { w: self }
}
}
| 34.373333 | 224 | 0.595423 |
72ca53c2be9ed2fe2750444de3f037aee806bd9f | 1,224 | use super::SnapshotMap;
#[test]
fn basic() {
let mut map = SnapshotMap::default();
map.insert(22, "twenty-two");
let snapshot = map.snapshot();
map.insert(22, "thirty-three");
assert_eq!(map[&22], "thirty-three");
map.insert(44, "forty-four");
assert_eq!(map[&44], "forty-four");
assert_eq!(map.get(&33), None);
map.rollback_to(snapshot);
assert_eq!(map[&22], "twenty-two");
assert_eq!(map.get(&33), None);
assert_eq!(map.get(&44), None);
}
#[test]
#[should_panic]
fn out_of_order() {
let mut map = SnapshotMap::default();
map.insert(22, "twenty-two");
let snapshot1 = map.snapshot();
map.insert(33, "thirty-three");
let snapshot2 = map.snapshot();
map.insert(44, "forty-four");
map.rollback_to(snapshot1); // bogus, but accepted
map.rollback_to(snapshot2); // asserts
}
#[test]
fn nested_commit_then_rollback() {
let mut map = SnapshotMap::default();
map.insert(22, "twenty-two");
let snapshot1 = map.snapshot();
let snapshot2 = map.snapshot();
map.insert(22, "thirty-three");
map.commit(snapshot2);
assert_eq!(map[&22], "thirty-three");
map.rollback_to(snapshot1);
assert_eq!(map[&22], "twenty-two");
}
| 27.818182 | 54 | 0.627451 |
114a1ae0d9ed2bee3d6b3fdcc3955c397bb5278b | 56,094 | use crate::{AudioBusConfig, Config, DevicesInfo, MidiControllerConfig};
#[derive(Debug, Clone, Default)]
pub struct DisplayState {
pub audio_server_options: Vec<String>,
pub current_audio_server_index: usize,
pub current_audio_server_name: String,
pub midi_server_options: Vec<String>,
pub current_midi_server_index: usize,
pub current_midi_server_name: String,
pub audio_device_options: Vec<String>,
pub current_audio_device_index: usize,
pub current_audio_device_name: String,
pub sample_rate_options: Vec<u32>,
pub current_sample_rate_index: usize,
pub current_sample_rate_str: String,
pub buffer_size_range: BufferSizeRange,
pub current_buffer_size: u32,
pub current_buffer_size_str: String,
pub audio_in_system_port_options: Vec<String>,
pub audio_out_system_port_options: Vec<String>,
pub midi_in_system_port_options: Vec<String>,
pub midi_out_system_port_options: Vec<String>,
pub audio_in_busses: Vec<AudioBusDisplayState>,
pub audio_out_busses: Vec<AudioBusDisplayState>,
pub midi_in_controllers: Vec<MidiControllerDisplayState>,
pub midi_out_controllers: Vec<MidiControllerDisplayState>,
pub current_audio_server_available: bool,
pub current_midi_server_available: bool,
pub playback_only: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SystemPortDisplayState {
pub current_system_port_index: usize,
pub current_system_port_name: String,
pub can_remove: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AudioBusDisplayState {
/// The ID to use for this bus. This ID is for the "internal" bus that appears to the user
/// as list of available sources/sends. This is not necessarily the same as the name of the actual
/// system hardware device that this "internal" bus is connected to.
///
/// This ID *must* be unique for each `AudioBusDisplayState` and `MidiControllerDisplayState`.
///
/// Examples of IDs can include:
///
/// * Realtek Device In
/// * Drums Mic
/// * Headphones Out
/// * Speakers Out
pub id: String,
/// The ports (of the system device) that this bus will be connected to.
pub ports: Vec<SystemPortDisplayState>,
pub can_remove: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MidiControllerDisplayState {
/// The ID to use for this controller. This ID is for the "internal" controller that appears to the user
/// as list of available sources/sends. This is not necessarily the same as the name of the actual
/// system hardware device that this "internal" controller is connected to.
///
/// This ID *must* be unique for each `AudioBusDisplayState` and `MidiControllerDisplayState`.
pub id: String,
/// The name of the system port this controller is connected to.
pub system_port: SystemPortDisplayState,
}
#[derive(Debug, Copy, Clone, Default)]
pub struct BufferSizeRange {
pub min: u32,
pub max: u32,
}
pub struct SystemOptions {
devices_info: DevicesInfo,
display_state: DisplayState,
// For loading the default config
default_audio_server: usize,
default_midi_server: usize,
config_status: ConfigStatus,
do_build_config: bool,
}
impl SystemOptions {
pub fn new() -> Self {
let devices_info = DevicesInfo::new();
let mut default_audio_server = 0;
for (i, server) in devices_info.audio_servers_info().iter().enumerate() {
if &server.name == devices_info.default_audio_server() {
default_audio_server = i;
break;
}
}
let mut default_midi_server = 0;
for (i, server) in devices_info.midi_servers_info().iter().enumerate() {
if &server.name == devices_info.default_midi_server() {
default_midi_server = i;
break;
}
}
let mut new_self = Self {
devices_info,
display_state: DisplayState::default(),
default_audio_server,
default_midi_server,
config_status: ConfigStatus::default(),
do_build_config: false,
};
new_self.display_state.audio_server_options = new_self
.devices_info
.audio_servers_info()
.iter()
.map(|s| s.name.clone())
.collect();
new_self.display_state.midi_server_options = new_self
.devices_info
.midi_servers_info()
.iter()
.map(|s| s.name.clone())
.collect();
new_self.set_audio_defaults();
new_self.set_midi_defaults();
new_self.build_config();
new_self.do_build_config = true;
new_self
}
pub fn devices_info(&self) -> &DevicesInfo {
&self.devices_info
}
pub fn select_audio_server(&mut self, index: usize) {
let index = index.min(self.display_state.audio_server_options.len() - 1);
if self.display_state.current_audio_server_index != index {
self.display_state.current_audio_server_index = index;
self.display_state.current_audio_server_name = self.display_state.audio_server_options
[self.display_state.current_audio_server_index]
.clone();
self.display_state.audio_device_options = self.devices_info.audio_servers_info()
[self.display_state.current_audio_server_index]
.devices
.iter()
.map(|d| d.name.clone())
.collect();
self.display_state.current_audio_server_available = self
.devices_info
.audio_servers_info()[self.display_state.current_audio_server_index]
.available;
self.set_defaults_for_current_audio_server();
if self.do_build_config {
self.build_config();
}
}
}
pub fn select_audio_device(&mut self, index: usize) {
if self.display_state.audio_device_options.len() > 0 {
let index = index.min(self.display_state.audio_device_options.len() - 1);
if self.display_state.current_audio_device_index != index {
self.display_state.current_audio_device_index = index;
self.display_state.current_audio_device_name = self
.display_state
.audio_device_options
.get(self.display_state.current_audio_device_index)
.unwrap_or(&String::from("Unavailable"))
.clone();
self.set_defaults_for_current_audio_device();
if self.do_build_config {
self.build_config();
}
}
} else {
self.display_state.playback_only = false;
}
}
pub fn select_sample_rate(&mut self, index: usize) {
if self.display_state.sample_rate_options.len() > 0 {
let index = index.min(self.display_state.sample_rate_options.len() - 1);
if self.display_state.current_sample_rate_index != index {
self.display_state.current_sample_rate_index = index;
self.display_state.current_sample_rate_str = format!(
"{}",
self.display_state.sample_rate_options
[self.display_state.current_sample_rate_index]
);
if self.do_build_config {
self.build_config();
}
}
} else {
self.display_state.current_sample_rate_str = String::from("Unavailable");
}
}
pub fn select_buffer_size(&mut self, size: u32) {
if self
.display_state
.audio_device_options
.get(self.display_state.current_audio_device_index)
.is_some()
{
let size = size
.min(self.display_state.buffer_size_range.min)
.max(self.display_state.buffer_size_range.max);
if self.display_state.current_buffer_size != size {
self.display_state.current_buffer_size = size;
self.display_state.current_sample_rate_str = format!(
"{}",
self.display_state.sample_rate_options
[self.display_state.current_sample_rate_index]
);
if self.do_build_config {
self.build_config();
}
}
} else {
self.display_state.current_buffer_size_str = String::from("Unavailable");
}
}
pub fn select_auto_buffer_size(&mut self) {
if self
.display_state
.audio_device_options
.get(self.display_state.current_audio_device_index)
.is_some()
{
let size = self.devices_info.audio_servers_info()
[self.display_state.current_audio_server_index]
.devices[self.display_state.current_audio_device_index]
.default_buffer_size
.min(self.display_state.buffer_size_range.min)
.max(self.display_state.buffer_size_range.max);
if self.display_state.current_buffer_size != size {
self.display_state.current_buffer_size = size;
self.display_state.current_sample_rate_str = format!(
"{}",
self.display_state.sample_rate_options
[self.display_state.current_sample_rate_index]
);
if self.do_build_config {
self.build_config();
}
}
} else {
self.display_state.current_buffer_size_str = String::from("Unavailable");
}
}
pub fn remove_audio_in_bus(&mut self, index: usize) {
let mut do_remove = false;
if let Some(bus) = self.display_state.audio_in_busses.get(index) {
do_remove = bus.can_remove;
}
if do_remove {
self.display_state.audio_in_busses.remove(index);
if self.do_build_config {
self.build_config();
}
}
}
pub fn remove_audio_out_bus(&mut self, index: usize) {
let mut do_remove = false;
if let Some(bus) = self.display_state.audio_out_busses.get(index) {
do_remove = bus.can_remove;
}
if do_remove {
self.display_state.audio_out_busses.remove(index);
// If only one audio out bus is left, mark that it cannot be removed.
if self.display_state.audio_out_busses.len() == 1 {
self.display_state.audio_out_busses[0].can_remove = false;
}
if self.do_build_config {
self.build_config();
}
}
}
pub fn add_audio_in_bus(&mut self) {
if self.display_state.audio_in_system_port_options.len() > 0 {
// Find the next available ID.
let mut id = String::from("Mic In");
let mut i = 1;
loop {
let mut is_unique = true;
for bus in self.display_state.audio_in_busses.iter() {
if &id == &bus.id {
is_unique = false;
break;
}
}
if is_unique {
break;
} else {
i += 1;
id = format!("Mic In #{}", i);
}
}
// Find the next available port.
let mut next_port = self
.display_state
.audio_in_busses
.last()
.map(|b| {
b.ports
.last()
.map(|p| p.current_system_port_index + 1)
.unwrap_or(0)
})
.unwrap_or(0);
if next_port >= self.display_state.audio_in_system_port_options.len() {
next_port = 0;
}
self.display_state
.audio_in_busses
.push(AudioBusDisplayState {
id,
ports: vec![SystemPortDisplayState {
current_system_port_index: next_port,
current_system_port_name: self.display_state.audio_in_system_port_options
[next_port]
.clone(),
can_remove: false,
}],
can_remove: true,
});
if self.do_build_config {
self.build_config();
}
}
}
pub fn add_audio_out_bus(&mut self) {
if self.display_state.audio_out_system_port_options.len() > 0 {
// Find the next available ID.
let mut id = String::from("Speakers Out");
let mut i = 1;
loop {
let mut is_unique = true;
for bus in self.display_state.audio_out_busses.iter() {
if &id == &bus.id {
is_unique = false;
break;
}
}
if is_unique {
break;
} else {
i += 1;
id = format!("Speakers Out #{}", i);
}
}
// Find the next available ports.
let mut next_port_left = self
.display_state
.audio_out_busses
.last()
.map(|b| {
b.ports
.last()
.map(|p| p.current_system_port_index + 1)
.unwrap_or(0)
})
.unwrap_or(0);
let mut next_port_right = next_port_left + 1;
if next_port_left >= self.display_state.audio_out_system_port_options.len() {
next_port_left = 0;
}
if next_port_right >= self.display_state.audio_out_system_port_options.len() {
next_port_right = 0;
}
self.display_state
.audio_out_busses
.push(AudioBusDisplayState {
id,
ports: vec![
SystemPortDisplayState {
current_system_port_index: next_port_left,
current_system_port_name: self
.display_state
.audio_out_system_port_options[next_port_left]
.clone(),
can_remove: true,
},
SystemPortDisplayState {
current_system_port_index: next_port_right,
current_system_port_name: self
.display_state
.audio_out_system_port_options[next_port_right]
.clone(),
can_remove: true,
},
],
can_remove: false,
});
// If there is more than one output bus, mark all of them as removeable.
if self.display_state.audio_out_busses.len() > 1 {
for bus in self.display_state.audio_out_busses.iter_mut() {
bus.can_remove = true;
}
}
if self.do_build_config {
self.build_config();
}
}
}
pub fn rename_audio_in_bus<S: Into<String>>(&mut self, bus_index: usize, name: S) {
if let Some(bus) = self.display_state.audio_in_busses.get_mut(bus_index) {
bus.id = name.into();
if self.do_build_config {
self.build_config();
}
}
}
pub fn rename_audio_out_bus<S: Into<String>>(&mut self, bus_index: usize, name: S) {
if let Some(bus) = self.display_state.audio_out_busses.get_mut(bus_index) {
bus.id = name.into();
if self.do_build_config {
self.build_config();
}
}
}
pub fn remove_audio_in_bus_port(&mut self, bus_index: usize, port_index: usize) {
if let Some(bus) = self.display_state.audio_in_busses.get_mut(bus_index) {
let mut do_remove = false;
if let Some(port) = bus.ports.get(port_index) {
do_remove = port.can_remove;
}
if do_remove {
bus.ports.remove(port_index);
// If there is only one port left, mark that it cannot be removed.
if bus.ports.len() == 1 {
bus.ports[0].can_remove = false;
}
if self.do_build_config {
self.build_config();
}
}
}
}
pub fn remove_audio_out_bus_port(&mut self, bus_index: usize, port_index: usize) {
if let Some(bus) = self.display_state.audio_out_busses.get_mut(bus_index) {
let mut do_remove = false;
if let Some(port) = bus.ports.get(port_index) {
do_remove = port.can_remove;
}
if do_remove {
bus.ports.remove(port_index);
// If there is only one port left, mark that it cannot be removed.
if bus.ports.len() == 1 {
bus.ports[0].can_remove = false;
}
if self.do_build_config {
self.build_config();
}
}
}
}
pub fn add_audio_in_bus_port(&mut self, bus_index: usize) {
if self.display_state.audio_in_system_port_options.len() > 0 {
if let Some(bus) = self.display_state.audio_in_busses.get_mut(bus_index) {
// Find the next available port.
let mut next_port = bus
.ports
.last()
.map(|p| p.current_system_port_index + 1)
.unwrap_or(0);
if next_port >= self.display_state.audio_in_system_port_options.len() {
next_port = 0;
}
bus.ports.push(SystemPortDisplayState {
current_system_port_index: next_port,
current_system_port_name: self.display_state.audio_in_system_port_options
[next_port]
.clone(),
can_remove: false,
});
// If there is more than one port, mark all of them as removeable.
if bus.ports.len() > 1 {
for port in bus.ports.iter_mut() {
port.can_remove = true;
}
}
if self.do_build_config {
self.build_config();
}
}
}
}
pub fn add_audio_out_bus_port(&mut self, bus_index: usize) {
if self.display_state.audio_out_system_port_options.len() > 0 {
if let Some(bus) = self.display_state.audio_out_busses.get_mut(bus_index) {
// Find the next available port.
let mut next_port = bus
.ports
.last()
.map(|p| p.current_system_port_index + 1)
.unwrap_or(0);
if next_port >= self.display_state.audio_out_system_port_options.len() {
next_port = 0;
}
bus.ports.push(SystemPortDisplayState {
current_system_port_index: next_port,
current_system_port_name: self.display_state.audio_out_system_port_options
[next_port]
.clone(),
can_remove: false,
});
// If there is more than one port, mark all of them as removeable.
if bus.ports.len() > 1 {
for port in bus.ports.iter_mut() {
port.can_remove = true;
}
}
if self.do_build_config {
self.build_config();
}
}
}
}
pub fn select_audio_in_bus_system_port(
&mut self,
bus_index: usize,
port_index: usize,
system_port_index: usize,
) {
if let Some(bus) = self.display_state.audio_in_busses.get_mut(bus_index) {
if let Some(port) = bus.ports.get_mut(port_index) {
if let Some(system_port) = self
.display_state
.audio_in_system_port_options
.get(system_port_index)
{
port.current_system_port_index = system_port_index;
port.current_system_port_name = system_port.clone();
if self.do_build_config {
self.build_config();
}
}
}
}
}
pub fn select_audio_out_bus_system_port(
&mut self,
bus_index: usize,
port_index: usize,
system_port_index: usize,
) {
if let Some(bus) = self.display_state.audio_out_busses.get_mut(bus_index) {
if let Some(port) = bus.ports.get_mut(port_index) {
if let Some(system_port) = self
.display_state
.audio_out_system_port_options
.get(system_port_index)
{
port.current_system_port_index = system_port_index;
port.current_system_port_name = system_port.clone();
if self.do_build_config {
self.build_config();
}
}
}
}
}
pub fn select_midi_server(&mut self, index: usize) {
let index = index.min(self.display_state.midi_server_options.len() - 1);
if self.display_state.current_midi_server_index != index {
self.display_state.current_midi_server_index = index;
self.display_state.current_midi_server_name = self.display_state.midi_server_options
[self.display_state.current_midi_server_index]
.clone();
self.display_state.midi_in_system_port_options = self.devices_info.midi_servers_info()
[self.display_state.current_midi_server_index]
.in_devices
.iter()
.map(|d| d.name.clone())
.collect();
self.display_state.midi_out_system_port_options = self.devices_info.midi_servers_info()
[self.display_state.current_midi_server_index]
.out_devices
.iter()
.map(|d| d.name.clone())
.collect();
self.display_state.current_midi_server_available =
self.devices_info.midi_servers_info()[self.display_state.current_midi_server_index]
.available;
self.set_defaults_for_current_midi_server();
if self.do_build_config {
self.build_config();
}
}
}
pub fn remove_midi_in_controller(&mut self, index: usize) {
if self.display_state.midi_in_controllers.get(index).is_some() {
self.display_state.midi_in_controllers.remove(index);
if self.do_build_config {
self.build_config();
}
}
}
pub fn remove_midi_out_controller(&mut self, index: usize) {
if self.display_state.midi_out_controllers.get(index).is_some() {
self.display_state.midi_out_controllers.remove(index);
if self.do_build_config {
self.build_config();
}
}
}
pub fn add_midi_in_controller(&mut self) {
if self.display_state.midi_in_system_port_options.len() > 0 {
// Find the next available ID.
let mut id = String::from("Midi In");
let mut i = 1;
loop {
let mut is_unique = true;
for controller in self.display_state.midi_in_controllers.iter() {
if &id == &controller.id {
is_unique = false;
break;
}
}
if is_unique {
break;
} else {
i += 1;
id = format!("Midi In #{}", i);
}
}
// Find the next available port.
let mut next_port = self
.display_state
.midi_in_controllers
.last()
.map(|c| c.system_port.current_system_port_index + 1)
.unwrap_or(0);
if next_port >= self.display_state.midi_in_system_port_options.len() {
next_port = 0;
}
self.display_state
.midi_in_controllers
.push(MidiControllerDisplayState {
id,
system_port: SystemPortDisplayState {
current_system_port_index: next_port,
current_system_port_name: self.display_state.midi_in_system_port_options
[next_port]
.clone(),
can_remove: false,
},
});
if self.do_build_config {
self.build_config();
}
}
}
pub fn add_midi_out_controller(&mut self) {
if self.display_state.midi_out_system_port_options.len() > 0 {
// Find the next available ID.
let mut id = String::from("Midi Out");
let mut i = 1;
loop {
let mut is_unique = true;
for controller in self.display_state.midi_out_controllers.iter() {
if &id == &controller.id {
is_unique = false;
break;
}
}
if is_unique {
break;
} else {
i += 1;
id = format!("Midi Out #{}", i);
}
}
// Find the next available port.
let mut next_port = self
.display_state
.midi_out_controllers
.last()
.map(|c| c.system_port.current_system_port_index + 1)
.unwrap_or(0);
if next_port >= self.display_state.midi_out_system_port_options.len() {
next_port = 0;
}
self.display_state
.midi_out_controllers
.push(MidiControllerDisplayState {
id,
system_port: SystemPortDisplayState {
current_system_port_index: next_port,
current_system_port_name: self.display_state.midi_out_system_port_options
[next_port]
.clone(),
can_remove: false,
},
});
if self.do_build_config {
self.build_config();
}
}
}
pub fn rename_midi_in_controller<S: Into<String>>(&mut self, controller_index: usize, name: S) {
if let Some(controller) = self
.display_state
.midi_in_controllers
.get_mut(controller_index)
{
controller.id = name.into();
if self.do_build_config {
self.build_config();
}
}
}
pub fn rename_midi_out_controller<S: Into<String>>(
&mut self,
controller_index: usize,
name: S,
) {
if let Some(controller) = self
.display_state
.midi_out_controllers
.get_mut(controller_index)
{
controller.id = name.into();
if self.do_build_config {
self.build_config();
}
}
}
pub fn select_midi_in_controller_system_port(
&mut self,
controller_index: usize,
system_port_index: usize,
) {
if let Some(controller) = self
.display_state
.midi_in_controllers
.get_mut(controller_index)
{
if let Some(system_port) = self
.display_state
.midi_in_system_port_options
.get(system_port_index)
{
controller.system_port.current_system_port_index = system_port_index;
controller.system_port.current_system_port_name = system_port.clone();
if self.do_build_config {
self.build_config();
}
}
}
}
pub fn select_midi_out_controller_system_port(
&mut self,
controller_index: usize,
system_port_index: usize,
) {
if let Some(controller) = self
.display_state
.midi_out_controllers
.get_mut(controller_index)
{
if let Some(system_port) = self
.display_state
.midi_out_system_port_options
.get(system_port_index)
{
controller.system_port.current_system_port_index = system_port_index;
controller.system_port.current_system_port_name = system_port.clone();
if self.do_build_config {
self.build_config();
}
}
}
}
pub fn refresh_servers(&mut self) {
let prev_state = self.display_state.clone();
let prev_sample_rate = *self
.display_state
.sample_rate_options
.get(self.display_state.current_sample_rate_index)
.unwrap_or(&0);
self.devices_info.refresh_audio_servers();
self.devices_info.refresh_midi_servers();
// Don't rebuild the config multiple times.
self.do_build_config = false;
// Revert to blank slate.
self.display_state = DisplayState::default();
let mut default_audio_server = 0;
for (i, server) in self.devices_info.audio_servers_info().iter().enumerate() {
if &server.name == self.devices_info.default_audio_server() {
default_audio_server = i;
break;
}
}
let mut default_midi_server = 0;
for (i, server) in self.devices_info.midi_servers_info().iter().enumerate() {
if &server.name == self.devices_info.default_midi_server() {
default_midi_server = i;
break;
}
}
self.default_audio_server = default_audio_server;
self.default_midi_server = default_midi_server;
// Server options are static.
self.display_state.audio_server_options = prev_state.audio_server_options.clone();
self.display_state.midi_server_options = prev_state.midi_server_options.clone();
self.set_audio_defaults();
self.set_midi_defaults();
// Use servers from previous state.
self.select_audio_server(prev_state.current_audio_server_index);
self.select_midi_server(prev_state.current_midi_server_index);
// If previous audio device still exists, use it.
for (device_i, device) in self.display_state.audio_device_options.iter().enumerate() {
if device == &prev_state.current_audio_device_name {
self.select_audio_device(device_i);
// If device is valid, attempt to restore its previous settings.
if !self.display_state.audio_out_system_port_options.is_empty() {
// If previous sample rate still exists, use it.
for (sample_rate_i, sample_rate) in
self.display_state.sample_rate_options.iter().enumerate()
{
if *sample_rate == prev_sample_rate {
self.select_sample_rate(sample_rate_i);
break;
}
}
// If previous buffer size is still valid, use it.
if prev_state.current_buffer_size >= self.display_state.buffer_size_range.min
&& prev_state.current_buffer_size
<= self.display_state.buffer_size_range.max
{
self.select_buffer_size(prev_state.current_buffer_size);
}
// If an input bus was created by default, remove it.
if self.display_state.audio_in_busses.len() == 1 {
self.remove_audio_in_bus(0);
}
let num_default_out_busses = self.display_state.audio_out_busses.len();
// Attempt to restore previous input busses.
for prev_bus in prev_state.audio_in_busses.iter() {
let mut new_ports = Vec::<SystemPortDisplayState>::new();
for port in prev_bus.ports.iter() {
for (system_port_i, system_port) in self
.display_state
.audio_in_system_port_options
.iter()
.enumerate()
{
if &port.current_system_port_name == system_port {
new_ports.push(SystemPortDisplayState {
current_system_port_index: system_port_i,
current_system_port_name: system_port.clone(),
can_remove: false,
});
break;
}
}
}
// If the number of new ports is 0, discard the bus.
if new_ports.len() > 0 {
// If the number of new ports is greater than 0, mark all of them as removeable.
if new_ports.len() > 1 {
for port in new_ports.iter_mut() {
port.can_remove = true;
}
}
self.display_state
.audio_in_busses
.push(AudioBusDisplayState {
id: prev_bus.id.clone(),
ports: new_ports,
can_remove: true,
});
}
}
// Attempt to restore previous output busses.
for prev_bus in prev_state.audio_out_busses.iter() {
let mut new_ports = Vec::<SystemPortDisplayState>::new();
for port in prev_bus.ports.iter() {
for (system_port_i, system_port) in self
.display_state
.audio_out_system_port_options
.iter()
.enumerate()
{
if &port.current_system_port_name == system_port {
new_ports.push(SystemPortDisplayState {
current_system_port_index: system_port_i,
current_system_port_name: system_port.clone(),
can_remove: false,
});
break;
}
}
}
// If the number of new ports is 0, discard the bus.
if new_ports.len() > 0 {
// If the number of new ports is greater than 0, mark all of them as removeable.
if new_ports.len() > 1 {
for port in new_ports.iter_mut() {
port.can_remove = true;
}
}
self.display_state
.audio_out_busses
.push(AudioBusDisplayState {
id: prev_bus.id.clone(),
ports: new_ports,
can_remove: false,
});
}
}
// If any new output busses were created, remove the one that was created by default.
if self.display_state.audio_out_busses.len() > num_default_out_busses
&& num_default_out_busses == 1
{
self.display_state.audio_out_busses.remove(0);
}
// If there is more than one output bus, mark all of them as removeable.
if self.display_state.audio_out_busses.len() > 1 {
for bus in self.display_state.audio_out_busses.iter_mut() {
bus.can_remove = true;
}
}
}
break;
}
}
// If an input bus was created by default, remove it.
if self.display_state.midi_in_controllers.len() == 1 {
self.remove_midi_in_controller(0);
}
// Attempt to restore previous midi input controllers.
for controller in prev_state.midi_in_controllers.iter() {
let mut new_port = None;
for (system_port_i, system_port) in self
.display_state
.midi_in_system_port_options
.iter()
.enumerate()
{
if &controller.system_port.current_system_port_name == system_port {
new_port = Some(SystemPortDisplayState {
current_system_port_index: system_port_i,
current_system_port_name: system_port.clone(),
can_remove: false,
});
break;
}
}
// If the port no longer exists, discard the controller.
if let Some(new_port) = new_port {
self.display_state
.midi_in_controllers
.push(MidiControllerDisplayState {
id: controller.id.clone(),
system_port: new_port,
});
}
}
// Attempt to restore previous midi output controllers.
for controller in prev_state.midi_out_controllers.iter() {
let mut new_port = None;
for (system_port_i, system_port) in self
.display_state
.midi_out_system_port_options
.iter()
.enumerate()
{
if &controller.system_port.current_system_port_name == system_port {
new_port = Some(SystemPortDisplayState {
current_system_port_index: system_port_i,
current_system_port_name: system_port.clone(),
can_remove: false,
});
break;
}
}
// If the port no longer exists, discard the controller.
if let Some(new_port) = new_port {
self.display_state
.midi_out_controllers
.push(MidiControllerDisplayState {
id: controller.id.clone(),
system_port: new_port,
});
}
}
self.build_config();
self.do_build_config = true;
}
pub fn set_audio_defaults(&mut self) {
self.display_state.current_audio_server_index = self.default_audio_server;
self.display_state.current_audio_server_name = self.display_state.audio_server_options
[self.display_state.current_audio_server_index]
.clone();
self.display_state.audio_device_options = self.devices_info.audio_servers_info()
[self.display_state.current_audio_server_index]
.devices
.iter()
.map(|d| d.name.clone())
.collect();
self.display_state.current_audio_server_available = self.devices_info.audio_servers_info()
[self.display_state.current_audio_server_index]
.available;
self.set_defaults_for_current_audio_server();
if self.do_build_config {
self.build_config();
}
}
pub fn set_midi_defaults(&mut self) {
self.display_state.current_midi_server_index = self.default_midi_server;
self.display_state.current_midi_server_name = self.display_state.midi_server_options
[self.display_state.current_midi_server_index]
.clone();
self.display_state.midi_in_system_port_options = self.devices_info.midi_servers_info()
[self.display_state.current_midi_server_index]
.in_devices
.iter()
.map(|d| d.name.clone())
.collect();
self.display_state.midi_out_system_port_options = self.devices_info.midi_servers_info()
[self.display_state.current_midi_server_index]
.out_devices
.iter()
.map(|d| d.name.clone())
.collect();
self.display_state.current_midi_server_available = self.devices_info.midi_servers_info()
[self.display_state.current_midi_server_index]
.available;
self.set_defaults_for_current_midi_server();
if self.do_build_config {
self.build_config();
}
}
pub fn set_defaults_for_current_audio_server(&mut self) {
self.display_state.current_audio_device_index = self.devices_info.audio_servers_info()
[self.display_state.current_audio_server_index]
.default_device;
self.display_state.current_audio_device_name = self
.display_state
.audio_device_options
.get(self.display_state.current_audio_device_index)
.unwrap_or(&String::from("Unavailable"))
.clone();
self.set_defaults_for_current_audio_device();
if self.do_build_config {
self.build_config();
}
}
pub fn set_defaults_for_current_audio_device(&mut self) {
self.display_state.audio_in_busses.clear();
self.display_state.audio_out_busses.clear();
if let Some(device) = self.devices_info.audio_servers_info()
[self.display_state.current_audio_server_index]
.devices
.get(self.display_state.current_audio_device_index)
{
self.display_state.audio_in_system_port_options = device.in_ports.clone();
self.display_state.audio_out_system_port_options = device.out_ports.clone();
self.display_state.sample_rate_options = device.sample_rates.clone();
self.display_state.buffer_size_range = device.buffer_size_range;
self.display_state.current_sample_rate_index = device
.default_sample_rate_index
.min(self.display_state.sample_rate_options.len() - 1);
self.display_state.current_sample_rate_str = format!(
"{}",
self.display_state.sample_rate_options
[self.display_state.current_sample_rate_index]
);
self.display_state.current_buffer_size = device
.default_buffer_size
.min(device.buffer_size_range.min)
.max(device.buffer_size_range.max);
self.display_state.playback_only = device.in_ports.is_empty();
self.display_state.current_buffer_size_str =
format!("{}", self.display_state.current_buffer_size);
if let Some(port) = device.in_ports.get(device.default_in_port) {
self.display_state
.audio_in_busses
.push(AudioBusDisplayState {
id: String::from("Mic In"),
ports: vec![SystemPortDisplayState {
current_system_port_index: device.default_in_port,
current_system_port_name: port.clone(),
can_remove: false,
}],
can_remove: true,
});
}
if let Some(left_port) = device.out_ports.get(device.default_out_port_left) {
if let Some(right_port) = device.out_ports.get(device.default_out_port_right) {
self.display_state
.audio_out_busses
.push(AudioBusDisplayState {
id: String::from("Speakers Out"),
ports: vec![
SystemPortDisplayState {
current_system_port_index: device.default_out_port_left,
current_system_port_name: left_port.clone(),
can_remove: true,
},
SystemPortDisplayState {
current_system_port_index: device.default_out_port_right,
current_system_port_name: right_port.clone(),
can_remove: true,
},
],
can_remove: false,
});
}
}
} else {
self.display_state.audio_in_system_port_options.clear();
self.display_state.audio_out_system_port_options.clear();
self.display_state.sample_rate_options.clear();
self.display_state.current_sample_rate_str = String::from("Unavailable");
self.display_state.buffer_size_range = BufferSizeRange::default();
self.display_state.current_buffer_size_str = String::from("Unavailable");
self.display_state.playback_only = false;
}
if self.do_build_config {
self.build_config();
}
}
pub fn set_defaults_for_current_midi_server(&mut self) {
self.display_state.midi_in_controllers.clear();
self.display_state.midi_out_controllers.clear();
if let Some(midi_in_port) = self.display_state.midi_in_system_port_options.get(
self.devices_info.midi_servers_info()[self.display_state.current_midi_server_index]
.default_in_port,
) {
self.display_state
.midi_in_controllers
.push(MidiControllerDisplayState {
id: String::from("Midi In"),
system_port: SystemPortDisplayState {
current_system_port_index: self.devices_info.midi_servers_info()
[self.display_state.current_midi_server_index]
.default_in_port,
current_system_port_name: midi_in_port.clone(),
can_remove: false,
},
});
}
if self.do_build_config {
self.build_config();
}
}
pub fn display_state(&self) -> &DisplayState {
&self.display_state
}
pub fn config_status(&self) -> &ConfigStatus {
&self.config_status
}
fn build_config(&mut self) {
// Invalid if there are no audio out ports.
if self.display_state.audio_out_system_port_options.is_empty() {
self.config_status = if self.display_state.current_audio_server_available {
ConfigStatus::NoAudioDeviceAvailable
} else {
ConfigStatus::AudioServerUnavailable(
self.display_state.current_audio_server_name.clone(),
)
};
return;
}
// Sanity checks
// Invalid if there are no audio out busses. This shouldn't happen.
if self.display_state.audio_out_busses.is_empty() {
log::error!("Config has no audio out busses. This shouldn't happen.");
self.config_status = ConfigStatus::UnknownError;
return;
}
// Invalid if there are no audio in ports and the config wants an audio in bus. This shouldn't happen.
if self.display_state.audio_in_system_port_options.is_empty()
&& !self.display_state.audio_in_busses.is_empty()
{
log::error!("Config wants to create audio in bus, but device is playback only. This shouldn't happen.");
self.config_status = ConfigStatus::UnknownError;
return;
}
// Invalid if there are no midi in ports and the config wants a midi in controller. This shouldn't happen.
if self.display_state.midi_in_system_port_options.is_empty()
&& !self.display_state.midi_in_controllers.is_empty()
{
log::error!("Config wants to create midi in controller, but no system midi in ports were found. This shouldn't happen.");
self.config_status = ConfigStatus::UnknownError;
return;
}
// Invalid if there are no midi out ports and the config wants a midi out controller. This shouldn't happen.
if self.display_state.midi_out_system_port_options.is_empty()
&& !self.display_state.midi_out_controllers.is_empty()
{
log::error!("Config wants to create midi out controller, but no system midi out ports were found. This shouldn't happen.");
self.config_status = ConfigStatus::UnknownError;
return;
}
let audio_in_busses = self
.display_state
.audio_in_busses
.iter()
.map(|b| AudioBusConfig {
id: b.id.clone(),
system_ports: b
.ports
.iter()
.map(|p| p.current_system_port_name.clone())
.collect(),
})
.collect();
let audio_out_busses = self
.display_state
.audio_out_busses
.iter()
.map(|b| AudioBusConfig {
id: b.id.clone(),
system_ports: b
.ports
.iter()
.map(|p| p.current_system_port_name.clone())
.collect(),
})
.collect();
let (midi_server, midi_in_controllers, midi_out_controllers) =
if !self.display_state.midi_in_controllers.is_empty()
|| !self.display_state.midi_out_controllers.is_empty()
{
(
Some(self.display_state.current_midi_server_name.clone()),
self.display_state
.midi_in_controllers
.iter()
.map(|c| MidiControllerConfig {
id: c.id.clone(),
system_port: c.system_port.current_system_port_name.clone(),
})
.collect(),
self.display_state
.midi_out_controllers
.iter()
.map(|c| MidiControllerConfig {
id: c.id.clone(),
system_port: c.system_port.current_system_port_name.clone(),
})
.collect(),
)
} else {
(None, Vec::new(), Vec::new())
};
let config = Config {
audio_server: self.display_state.current_audio_server_name.clone(),
system_audio_device: self.display_state.current_audio_device_name.clone(),
audio_in_busses,
audio_out_busses,
sample_rate: self
.display_state
.sample_rate_options
.get(self.display_state.current_sample_rate_index)
.map(|s| *s),
buffer_size: Some(self.display_state.current_buffer_size),
midi_server,
midi_in_controllers,
midi_out_controllers,
};
let sample_rate = self.devices_info.sample_rate(&config).unwrap_or(1);
let latency_frames = self.devices_info.estimated_latency(&config).unwrap_or(0);
let latency_ms = 1_000.0 * f64::from(latency_frames) / f64::from(sample_rate);
self.config_status = ConfigStatus::Ok {
config,
sample_rate,
latency_frames,
latency_ms,
};
}
}
#[derive(Debug, Clone)]
pub enum ConfigStatus {
Ok {
config: Config,
sample_rate: u32,
latency_frames: u32,
latency_ms: f64,
},
AudioServerUnavailable(String),
NoAudioDeviceAvailable,
UnknownError,
}
impl Default for ConfigStatus {
fn default() -> Self {
ConfigStatus::UnknownError
}
}
#[derive(Debug, Clone)]
pub struct AudioDeviceInfo {
pub name: String,
pub in_ports: Vec<String>,
pub out_ports: Vec<String>,
pub sample_rates: Vec<u32>,
pub buffer_size_range: BufferSizeRange,
pub default_in_port: usize,
pub default_out_port_left: usize,
pub default_out_port_right: usize,
pub default_sample_rate_index: usize,
pub default_buffer_size: u32,
}
#[derive(Debug, Clone)]
pub struct AudioServerInfo {
pub name: String,
pub version: Option<String>,
pub devices: Vec<AudioDeviceInfo>,
pub available: bool,
pub default_device: usize,
}
impl AudioServerInfo {
pub(crate) fn new(name: String, version: Option<String>) -> Self {
Self {
name,
version,
devices: Vec::new(),
available: false,
default_device: 0,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MidiDeviceInfo {
pub name: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MidiServerInfo {
pub name: String,
pub version: Option<String>,
pub in_devices: Vec<MidiDeviceInfo>,
pub out_devices: Vec<MidiDeviceInfo>,
pub available: bool,
pub default_in_port: usize,
}
impl MidiServerInfo {
pub(crate) fn new(name: String, version: Option<String>) -> Self {
Self {
name,
version,
in_devices: Vec::new(),
out_devices: Vec::new(),
available: false,
default_in_port: 0,
}
}
}
| 36.330311 | 135 | 0.523086 |
fbc5263d82d1018a0d3825953784eea47c077ddb | 755 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo<'a,'b> {
x: &'a isize,
y: &'b isize,
}
impl<'a,'b> Foo<'a,'b> {
fn bar(self: Foo<'b,'a>) {}
//~^ ERROR mismatched types: expected `Foo<'a, 'b>`, found `Foo<'b, 'a>`
//~^^ ERROR mismatched types: expected `Foo<'a, 'b>`, found `Foo<'b, 'a>`
}
fn main() {}
| 31.458333 | 77 | 0.649007 |
cc6a0fb5f8fe7ad38944fea295eb66b3cf3a00f9 | 784 | #GLOBAL
varying vec4 Position_VSPS;
varying vec2 UV_VSPS;
#END
#VS
attribute vec2 Position0;
uniform mat4 Camera;
uniform vec2 Position;
uniform vec2 Size;
uniform vec2 TexelOffset;
void main()
{
vec3 loc = vec3((Position0 * Size) + Position, 0);
gl_Position = Position_VSPS = ( vec4(loc, 1.0) * Camera);
UV_VSPS = vec2(Position0.x, 1.0-Position0.y) + TexelOffset;
}
#END
#PS
uniform vec4 Color;
uniform float Fade;
uniform float Fade2;
uniform sampler2D MainTexture;
uniform sampler2D MainTexture2;
uniform sampler2D MainTexture3;
void main()
{
vec4 outColor = texture2D(MainTexture, UV_VSPS);
outColor += (texture2D(MainTexture2, UV_VSPS) - outColor) * Fade;
outColor += (texture2D(MainTexture3, UV_VSPS) - outColor) * Fade2;
gl_FragData[0] = outColor * Color;
}
#END
| 19.6 | 67 | 0.741071 |
90bbf7ff3b2f5d1b67b84a057ab0debb2912864f | 267 | //! Functions with a common interface that rely on system calls.
#![allow(unsafe_code)] // We're interfacing with system calls.
#[cfg(feature = "local-offset")]
mod local_offset_at;
#[cfg(feature = "local-offset")]
pub(crate) use local_offset_at::local_offset_at;
| 26.7 | 64 | 0.737828 |
1ed6bf50c759af25fca5f040aefa18d6a87698a1 | 218,075 | //! # IBM_DB
//!
//! `ibm_db` is a library for connecting to DB2.
// suppress for the whole module with inner attribute...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, dead_code, improper_ctypes)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
use std::error::Error;
use std::fmt;
pub extern crate odbc_safe;
extern crate encoding_rs;
pub use diagnostics::{DiagnosticRecord, GetDiagRec};
pub use result::Result;
pub use environment::*;
pub use connection::Connection;
pub use statement::*;
pub use ffi::*;
use odbc_object::OdbcObject;
use raii::Raii;
use result::{Return, into_result, try_into_option};
pub use odbc_safe as safe;
mod ffi;
mod odbc_object;
mod raii;
mod diagnostics;
mod result;
mod environment;
mod connection;
mod statement;
/// Reflects the ability of a type to expose a valid handle
pub trait Handle {
type To;
/// Returns a valid handle to the odbc type.
unsafe fn handle(&self) -> *mut Self::To;
}
//Added for connection pooling
#[derive(Debug)]
pub struct ODBCConnectionManager {
connection_string: String
}
#[derive(Debug)]
pub struct ODBCConnectionManagerTx {
connection_string: String
}
pub struct ODBCConnection<'a, AC: safe::AutocommitMode>(Connection<'a, AC>);
unsafe impl Send for ODBCConnection<'static, safe::AutocommitOn> {}
unsafe impl Send for ODBCConnection<'static, safe::AutocommitOff> {}
impl <'a, AC: safe::AutocommitMode> ODBCConnection<'a, AC> {
pub fn raw(&self) -> &Connection<'a, AC> {
&self.0
}
}
pub struct ODBCEnv(Environment<Version3>);
unsafe impl Sync for ODBCEnv {}
unsafe impl Send for ODBCEnv {}
#[derive(Debug)]
pub struct ODBCError(Box<dyn Error>);
lazy_static! {
static ref ENV: ODBCEnv = ODBCEnv(create_environment_v3().unwrap());
}
impl Error for ODBCError {
fn description(&self) -> &str {
"Error connecting DB"
}
}
impl fmt::Display for ODBCError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl From<DiagnosticRecord> for ODBCError {
fn from(err: DiagnosticRecord) -> Self {
println!("ODBC ERROR {}", err);
ODBCError(Box::new(err))
}
}
impl <E: 'static> From<std::sync::PoisonError<E>> for ODBCError {
fn from(err: std::sync::PoisonError<E>) -> Self {
ODBCError(Box::new(err))
}
}
impl ODBCConnectionManager {
/// Creates a new `ODBCConnectionManager`.
pub fn new<S: Into<String>>(connection_string: S) -> ODBCConnectionManager
{
ODBCConnectionManager {
connection_string: connection_string.into()
}
}
}
impl ODBCConnectionManagerTx {
/// Creates a new `ODBCConnectionManagerTx`.
pub fn new<S: Into<String>>(connection_string: S) -> ODBCConnectionManagerTx
{
ODBCConnectionManagerTx {
connection_string: connection_string.into()
}
}
}
impl r2d2::ManageConnection for ODBCConnectionManager {
type Connection = ODBCConnection<'static, safe::AutocommitOn>;
type Error = ODBCError;
fn connect(&self) -> std::result::Result<Self::Connection, Self::Error> {
let env = &ENV.0;
Ok(ODBCConnection(env.connect_with_connection_string(&self.connection_string)?))
}
fn is_valid(&self, _conn: &mut Self::Connection) -> std::result::Result<(), Self::Error> {
//TODO
Ok(())
}
fn has_broken(&self, _conn: &mut Self::Connection) -> bool {
//TODO
false
}
}
impl r2d2::ManageConnection for ODBCConnectionManagerTx {
type Connection = ODBCConnection<'static, safe::AutocommitOff>;
type Error = ODBCError;
fn connect(&self) -> std::result::Result<Self::Connection, Self::Error> {
let env = &ENV.0;
let conn = env.connect_with_connection_string(&self.connection_string)?;
let conn_result = conn.disable_autocommit();
match conn_result {
Ok(conn) => Ok(ODBCConnection(conn)),
_ => Err(ODBCError("Unable to use transactions".into()))
}
}
fn is_valid(&self, _conn: &mut Self::Connection) -> std::result::Result<(), Self::Error> {
//TODO
Ok(())
}
fn has_broken(&self, _conn: &mut Self::Connection) -> bool {
//TODO
false
}
}
//Ends
pub const DB2LINUX : u32 = 1 ;
pub const SQL_CMP_NA_ERRORS : u32 = 1 ;
pub const SQL_CMP_ROWS_AFFECTED : u32 = 2 ;
pub const SQL_CMP_STMTS_COMPLETED : u32 = 3 ;
pub const SQL_CMP_REF_INT_ROWS : u32 = 4 ;
pub const SQL_CONNECT_DB_APP2DB_CONVFACTOR : u32 = 0 ;
pub const SQL_CONNECT_DB_DB2APP_CONVFACTOR : u32 = 1 ;
pub const SQL_CONNECT_DB_UPDATEABILITY_IN_UOW : u32 = 2 ;
pub const SQL_CONNECT_DB_COMMIT_TYPE : u32 = 3 ;
pub const SQL_DB_UPDATEABLE : u32 = 1 ;
pub const SQL_DB_READ_ONLY : u32 = 2 ;
pub const SQL_DB_ONE_PHASE_COMMIT : u32 = 1 ;
pub const SQL_DB_ONE_PHASE_READ_ONLY : u32 = 2 ;
pub const SQL_DB_TWO_PHASE_COMMIT : u32 = 3 ;
pub const SQL_ERRD_NODE_NUM : u32 = 1 ;
pub const DB2CLI_VER : u32 = 784 ;
pub const _FEATURES_H : u32 = 1 ;
pub const _DEFAULT_SOURCE : u32 = 1 ;
pub const __USE_ISOC11 : u32 = 1 ;
pub const __USE_ISOC99 : u32 = 1 ;
pub const __USE_ISOC95 : u32 = 1 ;
pub const __USE_POSIX_IMPLICITLY : u32 = 1 ;
pub const _POSIX_SOURCE : u32 = 1 ;
pub const _POSIX_C_SOURCE : u32 = 200809 ;
pub const __USE_POSIX : u32 = 1 ;
pub const __USE_POSIX2 : u32 = 1 ;
pub const __USE_POSIX199309 : u32 = 1 ;
pub const __USE_POSIX199506 : u32 = 1 ;
pub const __USE_XOPEN2K : u32 = 1 ;
pub const __USE_XOPEN2K8 : u32 = 1 ;
pub const _ATFILE_SOURCE : u32 = 1 ;
pub const __USE_MISC : u32 = 1 ;
pub const __USE_ATFILE : u32 = 1 ;
pub const __USE_FORTIFY_LEVEL : u32 = 0 ;
pub const __GLIBC_USE_DEPRECATED_GETS : u32 = 0 ;
pub const _STDC_PREDEF_H : u32 = 1 ;
pub const __STDC_IEC_559__ : u32 = 1 ;
pub const __STDC_IEC_559_COMPLEX__ : u32 = 1 ;
pub const __STDC_ISO_10646__ : u32 = 201706 ;
pub const __STDC_NO_THREADS__ : u32 = 1 ;
pub const __GNU_LIBRARY__ : u32 = 6 ;
pub const __GLIBC__ : u32 = 2 ;
pub const __GLIBC_MINOR__ : u32 = 27 ;
pub const _SYS_CDEFS_H : u32 = 1 ;
pub const __glibc_c99_flexarr_available : u32 = 1 ;
pub const __WORDSIZE : u32 = 64 ;
pub const __WORDSIZE_TIME64_COMPAT32 : u32 = 1 ;
pub const __SYSCALL_WORDSIZE : u32 = 64 ;
pub const __HAVE_GENERIC_SELECTION : u32 = 1 ;
pub const __GLIBC_USE_LIB_EXT2 : u32 = 0 ;
pub const __GLIBC_USE_IEC_60559_BFP_EXT : u32 = 0 ;
pub const __GLIBC_USE_IEC_60559_FUNCS_EXT : u32 = 0 ;
pub const __GLIBC_USE_IEC_60559_TYPES_EXT : u32 = 0 ;
pub const _STDLIB_H : u32 = 1 ;
pub const WNOHANG : u32 = 1 ;
pub const WUNTRACED : u32 = 2 ;
pub const WSTOPPED : u32 = 2 ;
pub const WEXITED : u32 = 4 ;
pub const WCONTINUED : u32 = 8 ;
pub const WNOWAIT : u32 = 16777216 ;
pub const __WNOTHREAD : u32 = 536870912 ;
pub const __WALL : u32 = 1073741824 ;
pub const __WCLONE : u32 = 2147483648 ;
pub const __ENUM_IDTYPE_T : u32 = 1 ;
pub const __W_CONTINUED : u32 = 65535 ;
pub const __WCOREFLAG : u32 = 128 ;
pub const __HAVE_FLOAT128 : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT128 : u32 = 0 ;
pub const __HAVE_FLOAT64X : u32 = 1 ;
pub const __HAVE_FLOAT64X_LONG_DOUBLE : u32 = 1 ;
pub const __HAVE_FLOAT16 : u32 = 0 ;
pub const __HAVE_FLOAT32 : u32 = 1 ;
pub const __HAVE_FLOAT64 : u32 = 1 ;
pub const __HAVE_FLOAT32X : u32 = 1 ;
pub const __HAVE_FLOAT128X : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT16 : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT32 : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT64 : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT32X : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT64X : u32 = 0 ;
pub const __HAVE_DISTINCT_FLOAT128X : u32 = 0 ;
pub const __HAVE_FLOATN_NOT_TYPEDEF : u32 = 0 ;
pub const __ldiv_t_defined : u32 = 1 ;
pub const __lldiv_t_defined : u32 = 1 ;
pub const RAND_MAX : u32 = 2147483647 ;
pub const EXIT_FAILURE : u32 = 1 ;
pub const EXIT_SUCCESS : u32 = 0 ;
pub const _SYS_TYPES_H : u32 = 1 ;
pub const _BITS_TYPES_H : u32 = 1 ;
pub const _BITS_TYPESIZES_H : u32 = 1 ;
pub const __OFF_T_MATCHES_OFF64_T : u32 = 1 ;
pub const __INO_T_MATCHES_INO64_T : u32 = 1 ;
pub const __RLIM_T_MATCHES_RLIM64_T : u32 = 1 ;
pub const __FD_SETSIZE : u32 = 1024 ;
pub const __clock_t_defined : u32 = 1 ;
pub const __clockid_t_defined : u32 = 1 ;
pub const __time_t_defined : u32 = 1 ;
pub const __timer_t_defined : u32 = 1 ;
pub const _BITS_STDINT_INTN_H : u32 = 1 ;
pub const __BIT_TYPES_DEFINED__ : u32 = 1 ;
pub const _ENDIAN_H : u32 = 1 ;
pub const __LITTLE_ENDIAN : u32 = 1234 ;
pub const __BIG_ENDIAN : u32 = 4321 ;
pub const __PDP_ENDIAN : u32 = 3412 ;
pub const __BYTE_ORDER : u32 = 1234 ;
pub const __FLOAT_WORD_ORDER : u32 = 1234 ;
pub const LITTLE_ENDIAN : u32 = 1234 ;
pub const BIG_ENDIAN : u32 = 4321 ;
pub const PDP_ENDIAN : u32 = 3412 ;
pub const BYTE_ORDER : u32 = 1234 ;
pub const _BITS_BYTESWAP_H : u32 = 1 ;
pub const _BITS_UINTN_IDENTITY_H : u32 = 1 ;
pub const _SYS_SELECT_H : u32 = 1 ;
pub const __FD_ZERO_STOS : & 'static [u8 ;
6usize] = b"stosq\0" ;
pub const __sigset_t_defined : u32 = 1 ;
pub const __timeval_defined : u32 = 1 ;
pub const _STRUCT_TIMESPEC : u32 = 1 ;
pub const FD_SETSIZE : u32 = 1024 ;
pub const _SYS_SYSMACROS_H : u32 = 1 ;
pub const _BITS_SYSMACROS_H : u32 = 1 ;
pub const _BITS_PTHREADTYPES_COMMON_H : u32 = 1 ;
pub const _THREAD_SHARED_TYPES_H : u32 = 1 ;
pub const _BITS_PTHREADTYPES_ARCH_H : u32 = 1 ;
pub const __SIZEOF_PTHREAD_MUTEX_T : u32 = 40 ;
pub const __SIZEOF_PTHREAD_ATTR_T : u32 = 56 ;
pub const __SIZEOF_PTHREAD_RWLOCK_T : u32 = 56 ;
pub const __SIZEOF_PTHREAD_BARRIER_T : u32 = 32 ;
pub const __SIZEOF_PTHREAD_MUTEXATTR_T : u32 = 4 ;
pub const __SIZEOF_PTHREAD_COND_T : u32 = 48 ;
pub const __SIZEOF_PTHREAD_CONDATTR_T : u32 = 4 ;
pub const __SIZEOF_PTHREAD_RWLOCKATTR_T : u32 = 8 ;
pub const __SIZEOF_PTHREAD_BARRIERATTR_T : u32 = 4 ;
pub const __PTHREAD_MUTEX_LOCK_ELISION : u32 = 1 ;
pub const __PTHREAD_MUTEX_NUSERS_AFTER_KIND : u32 = 0 ;
pub const __PTHREAD_MUTEX_USE_UNION : u32 = 0 ;
pub const __PTHREAD_RWLOCK_INT_FLAGS_SHARED : u32 = 1 ;
pub const __PTHREAD_MUTEX_HAVE_PREV : u32 = 1 ;
pub const __have_pthread_attr_t : u32 = 1 ;
pub const _ALLOCA_H : u32 = 1 ;
pub const SQL_MAX_MESSAGE_LENGTH : u32 = 1024 ;
pub const SQL_MAX_ID_LENGTH : u32 = 128 ;
pub const SQL_DATE_LEN : u32 = 10 ;
pub const SQL_TIME_LEN : u32 = 8 ;
pub const SQL_TIMESTAMP_LEN : u32 = 19 ;
pub const SQL_TIMESTAMPTZ_LEN : u32 = 25 ;
pub const SQL_HANDLE_ENV : u32 = 1 ;
pub const SQL_HANDLE_DBC : u32 = 2 ;
pub const SQL_HANDLE_STMT : u32 = 3 ;
pub const SQL_HANDLE_DESC : u32 = 4 ;
pub const SQL_SUCCESS : u32 = 0 ;
pub const SQL_SUCCESS_WITH_INFO : u32 = 1 ;
pub const SQL_NEED_DATA : u32 = 99 ;
pub const SQL_NO_DATA : u32 = 100 ;
pub const SQL_STILL_EXECUTING : u32 = 2 ;
pub const SQL_ERROR : i32 = - 1 ;
pub const SQL_INVALID_HANDLE : i32 = - 2 ;
pub const SQL_CLOSE : u32 = 0 ;
pub const SQL_DROP : u32 = 1 ;
pub const SQL_UNBIND : u32 = 2 ;
pub const SQL_RESET_PARAMS : u32 = 3 ;
pub const SQL_COMMIT : u32 = 0 ;
pub const SQL_ROLLBACK : u32 = 1 ;
pub const SQL_UNKNOWN_TYPE : u32 = 0 ;
pub const SQL_CHAR : u32 = 1 ;
pub const SQL_NUMERIC : u32 = 2 ;
pub const SQL_DECIMAL : u32 = 3 ;
pub const SQL_INTEGER : u32 = 4 ;
pub const SQL_SMALLINT : u32 = 5 ;
pub const SQL_FLOAT : u32 = 6 ;
pub const SQL_REAL : u32 = 7 ;
pub const SQL_DOUBLE : u32 = 8 ;
pub const SQL_DATETIME : u32 = 9 ;
pub const SQL_VARCHAR : u32 = 12 ;
pub const SQL_BOOLEAN : u32 = 16 ;
pub const SQL_ROW : u32 = 19 ;
pub const SQL_WCHAR : i32 = - 8 ;
pub const SQL_WVARCHAR : i32 = - 9 ;
pub const SQL_WLONGVARCHAR : i32 = - 10 ;
pub const SQL_DECFLOAT : i32 = - 360 ;
pub const SQL_TYPE_DATE : u32 = 91 ;
pub const SQL_TYPE_TIME : u32 = 92 ;
pub const SQL_TYPE_TIMESTAMP : u32 = 93 ;
pub const SQL_TYPE_TIMESTAMP_WITH_TIMEZONE : u32 = 95 ;
pub const SQL_UNSPECIFIED : u32 = 0 ;
pub const SQL_INSENSITIVE : u32 = 1 ;
pub const SQL_SENSITIVE : u32 = 2 ;
pub const SQL_DEFAULT : u32 = 99 ;
pub const SQL_ARD_TYPE : i32 = - 99 ;
pub const SQL_CODE_DATE : u32 = 1 ;
pub const SQL_CODE_TIME : u32 = 2 ;
pub const SQL_CODE_TIMESTAMP : u32 = 3 ;
pub const SQL_CODE_TIMESTAMP_WITH_TIMEZONE : u32 = 4 ;
pub const SQL_GRAPHIC : i32 = - 95 ;
pub const SQL_VARGRAPHIC : i32 = - 96 ;
pub const SQL_LONGVARGRAPHIC : i32 = - 97 ;
pub const SQL_BLOB : i32 = - 98 ;
pub const SQL_CLOB : i32 = - 99 ;
pub const SQL_DBCLOB : i32 = - 350 ;
pub const SQL_XML : i32 = - 370 ;
pub const SQL_CURSORHANDLE : i32 = - 380 ;
pub const SQL_DATALINK : i32 = - 400 ;
pub const SQL_USER_DEFINED_TYPE : i32 = - 450 ;
pub const SQL_C_DBCHAR : i32 = - 350 ;
pub const SQL_C_DECIMAL_IBM : u32 = 3 ;
pub const SQL_C_PTR : u32 = 2463 ;
pub const SQL_C_DECIMAL_OLEDB : u32 = 2514 ;
pub const SQL_C_DECIMAL64 : i32 = - 360 ;
pub const SQL_C_DECIMAL128 : i32 = - 361 ;
pub const SQL_C_TIMESTAMP_EXT : i32 = - 362 ;
pub const SQL_C_TYPE_TIMESTAMP_EXT : i32 = - 362 ;
pub const SQL_C_BINARYXML : i32 = - 363 ;
pub const SQL_C_TIMESTAMP_EXT_TZ : i32 = - 364 ;
pub const SQL_C_TYPE_TIMESTAMP_EXT_TZ : i32 = - 364 ;
pub const SQL_C_CURSORHANDLE : i32 = - 365 ;
pub const SQL_BLOB_LOCATOR : u32 = 31 ;
pub const SQL_CLOB_LOCATOR : u32 = 41 ;
pub const SQL_DBCLOB_LOCATOR : i32 = - 351 ;
pub const SQL_C_BLOB_LOCATOR : u32 = 31 ;
pub const SQL_C_CLOB_LOCATOR : u32 = 41 ;
pub const SQL_C_DBCLOB_LOCATOR : i32 = - 351 ;
pub const SQL_NO_NULLS : u32 = 0 ;
pub const SQL_NULLABLE : u32 = 1 ;
pub const SQL_NULLABLE_UNKNOWN : u32 = 2 ;
pub const SQL_NAMED : u32 = 0 ;
pub const SQL_UNNAMED : u32 = 1 ;
pub const SQL_DESC_ALLOC_AUTO : u32 = 1 ;
pub const SQL_DESC_ALLOC_USER : u32 = 2 ;
pub const SQL_TYPE_BASE : u32 = 0 ;
pub const SQL_TYPE_DISTINCT : u32 = 1 ;
pub const SQL_TYPE_STRUCTURED : u32 = 2 ;
pub const SQL_TYPE_REFERENCE : u32 = 3 ;
pub const SQL_NULL_DATA : i32 = - 1 ;
pub const SQL_DATA_AT_EXEC : i32 = - 2 ;
pub const SQL_NTS : i32 = - 3 ;
pub const SQL_NTSL : i32 = - 3 ;
pub const SQL_COLUMN_SCHEMA_NAME : u32 = 16 ;
pub const SQL_COLUMN_CATALOG_NAME : u32 = 17 ;
pub const SQL_COLUMN_DISTINCT_TYPE : u32 = 1250 ;
pub const SQL_DESC_DISTINCT_TYPE : u32 = 1250 ;
pub const SQL_COLUMN_REFERENCE_TYPE : u32 = 1251 ;
pub const SQL_DESC_REFERENCE_TYPE : u32 = 1251 ;
pub const SQL_DESC_STRUCTURED_TYPE : u32 = 1252 ;
pub const SQL_DESC_USER_TYPE : u32 = 1253 ;
pub const SQL_DESC_BASE_TYPE : u32 = 1254 ;
pub const SQL_DESC_KEY_TYPE : u32 = 1255 ;
pub const SQL_DESC_KEY_MEMBER : u32 = 1266 ;
pub const SQL_DESC_IDENTITY_VALUE : u32 = 1267 ;
pub const SQL_DESC_CODEPAGE : u32 = 1268 ;
pub const SQL_DESC_COUNT : u32 = 1001 ;
pub const SQL_DESC_TYPE : u32 = 1002 ;
pub const SQL_DESC_LENGTH : u32 = 1003 ;
pub const SQL_DESC_OCTET_LENGTH_PTR : u32 = 1004 ;
pub const SQL_DESC_PRECISION : u32 = 1005 ;
pub const SQL_DESC_SCALE : u32 = 1006 ;
pub const SQL_DESC_DATETIME_INTERVAL_CODE : u32 = 1007 ;
pub const SQL_DESC_NULLABLE : u32 = 1008 ;
pub const SQL_DESC_INDICATOR_PTR : u32 = 1009 ;
pub const SQL_DESC_DATA_PTR : u32 = 1010 ;
pub const SQL_DESC_NAME : u32 = 1011 ;
pub const SQL_DESC_UNNAMED : u32 = 1012 ;
pub const SQL_DESC_OCTET_LENGTH : u32 = 1013 ;
pub const SQL_DESC_ALLOC_TYPE : u32 = 1099 ;
pub const SQL_DESC_USER_DEFINED_TYPE_CODE : u32 = 1098 ;
pub const SQL_DESC_CARDINALITY : u32 = 1040 ;
pub const SQL_DESC_CARDINALITY_PTR : u32 = 1043 ;
pub const SQL_DESC_ROW_DESC : u32 = 1044 ;
pub const SQL_KEYTYPE_NONE : u32 = 0 ;
pub const SQL_KEYTYPE_PRIMARYKEY : u32 = 1 ;
pub const SQL_KEYTYPE_UNIQUEINDEX : u32 = 2 ;
pub const SQL_UPDT_READONLY : u32 = 0 ;
pub const SQL_UPDT_WRITE : u32 = 1 ;
pub const SQL_UPDT_READWRITE_UNKNOWN : u32 = 2 ;
pub const SQL_PRED_NONE : u32 = 0 ;
pub const SQL_PRED_CHAR : u32 = 1 ;
pub const SQL_PRED_BASIC : u32 = 2 ;
pub const SQL_NULL_HENV : u32 = 0 ;
pub const SQL_NULL_HDBC : u32 = 0 ;
pub const SQL_NULL_HSTMT : u32 = 0 ;
pub const SQL_NULL_HDESC : u32 = 0 ;
pub const SQL_NULL_HANDLE : u32 = 0 ;
pub const SQL_DIAG_RETURNCODE : u32 = 1 ;
pub const SQL_DIAG_NUMBER : u32 = 2 ;
pub const SQL_DIAG_ROW_COUNT : u32 = 3 ;
pub const SQL_DIAG_SQLSTATE : u32 = 4 ;
pub const SQL_DIAG_NATIVE : u32 = 5 ;
pub const SQL_DIAG_MESSAGE_TEXT : u32 = 6 ;
pub const SQL_DIAG_DYNAMIC_FUNCTION : u32 = 7 ;
pub const SQL_DIAG_CLASS_ORIGIN : u32 = 8 ;
pub const SQL_DIAG_SUBCLASS_ORIGIN : u32 = 9 ;
pub const SQL_DIAG_CONNECTION_NAME : u32 = 10 ;
pub const SQL_DIAG_SERVER_NAME : u32 = 11 ;
pub const SQL_DIAG_DYNAMIC_FUNCTION_CODE : u32 = 12 ;
pub const SQL_DIAG_ISAM_ERROR : u32 = 13 ;
pub const SQL_DIAG_SYSPLEX_STATISTICS : u32 = 2528 ;
pub const SQL_DIAG_DB2ZLOAD_RETCODE : u32 = 2529 ;
pub const SQL_DIAG_DB2ZLOAD_LOAD_MSGS : u32 = 2530 ;
pub const SQL_DIAG_LOG_FILENAME : u32 = 2531 ;
pub const SQL_DIAG_BAD_FILENAME : u32 = 2532 ;
pub const SQL_DIAG_ALTER_TABLE : u32 = 4 ;
pub const SQL_DIAG_CALL : u32 = 7 ;
pub const SQL_DIAG_CREATE_INDEX : i32 = - 1 ;
pub const SQL_DIAG_CREATE_TABLE : u32 = 77 ;
pub const SQL_DIAG_CREATE_VIEW : u32 = 84 ;
pub const SQL_DIAG_DELETE_WHERE : u32 = 19 ;
pub const SQL_DIAG_DROP_INDEX : i32 = - 2 ;
pub const SQL_DIAG_DROP_TABLE : u32 = 32 ;
pub const SQL_DIAG_DROP_VIEW : u32 = 36 ;
pub const SQL_DIAG_DYNAMIC_DELETE_CURSOR : u32 = 38 ;
pub const SQL_DIAG_DYNAMIC_UPDATE_CURSOR : u32 = 81 ;
pub const SQL_DIAG_GRANT : u32 = 48 ;
pub const SQL_DIAG_INSERT : u32 = 50 ;
pub const SQL_DIAG_MERGE : u32 = 128 ;
pub const SQL_DIAG_REVOKE : u32 = 59 ;
pub const SQL_DIAG_SELECT_CURSOR : u32 = 85 ;
pub const SQL_DIAG_UNKNOWN_STATEMENT : u32 = 0 ;
pub const SQL_DIAG_UPDATE_WHERE : u32 = 82 ;
pub const SQL_DIAG_DEFERRED_PREPARE_ERROR : u32 = 1279 ;
pub const SQL_ROW_NO_ROW_NUMBER : i32 = - 1 ;
pub const SQL_ROW_NUMBER_UNKNOWN : i32 = - 2 ;
pub const SQL_COLUMN_NO_COLUMN_NUMBER : i32 = - 1 ;
pub const SQL_COLUMN_NUMBER_UNKNOWN : i32 = - 2 ;
pub const SQL_MAX_C_NUMERIC_PRECISION : u32 = 38 ;
pub const SQL_MAX_NUMERIC_LEN : u32 = 16 ;
pub const SQL_DECIMAL64_LEN : u32 = 8 ;
pub const SQL_DECIMAL128_LEN : u32 = 16 ;
pub const ODBCVER : u32 = 896 ;
pub const SQL_SPEC_MAJOR : u32 = 3 ;
pub const SQL_SPEC_MINOR : u32 = 80 ;
pub const SQL_SPEC_STRING : & 'static [u8 ;
6usize] = b"03.80\0" ;
pub const SQL_SQLSTATE_SIZE : u32 = 5 ;
pub const SQL_MAX_DSN_LENGTH : u32 = 32 ;
pub const SQL_MAX_OPTION_STRING_LENGTH : u32 = 256 ;
pub const SQL_NO_DATA_FOUND : u32 = 100 ;
pub const SQL_HANDLE_SENV : u32 = 5 ;
pub const SQL_ATTR_ODBC_VERSION : u32 = 200 ;
pub const SQL_ATTR_CONNECTION_POOLING : u32 = 201 ;
pub const SQL_ATTR_CP_MATCH : u32 = 202 ;
pub const SQL_CP_OFF : u32 = 0 ;
pub const SQL_CP_ONE_PER_DRIVER : u32 = 1 ;
pub const SQL_CP_ONE_PER_HENV : u32 = 2 ;
pub const SQL_CP_DEFAULT : u32 = 0 ;
pub const SQL_CP_STRICT_MATCH : u32 = 0 ;
pub const SQL_CP_RELAXED_MATCH : u32 = 1 ;
pub const SQL_CP_MATCH_DEFAULT : u32 = 0 ;
pub const SQL_OV_ODBC2 : u32 = 2 ;
pub const SQL_OV_ODBC3 : u32 = 3 ;
pub const SQL_OV_ODBC3_80 : u32 = 380 ;
pub const SQL_ACCESS_MODE : u32 = 101 ;
pub const SQL_AUTOCOMMIT : u32 = 102 ;
pub const SQL_LOGIN_TIMEOUT : u32 = 103 ;
pub const SQL_OPT_TRACE : u32 = 104 ;
pub const SQL_OPT_TRACEFILE : u32 = 105 ;
pub const SQL_TRANSLATE_DLL : u32 = 106 ;
pub const SQL_TRANSLATE_OPTION : u32 = 107 ;
pub const SQL_TXN_ISOLATION : u32 = 108 ;
pub const SQL_CURRENT_QUALIFIER : u32 = 109 ;
pub const SQL_ODBC_CURSORS : u32 = 110 ;
pub const SQL_QUIET_MODE : u32 = 111 ;
pub const SQL_PACKET_SIZE : u32 = 112 ;
pub const SQL_ATTR_ACCESS_MODE : u32 = 101 ;
pub const SQL_ATTR_AUTOCOMMIT : u32 = 102 ;
pub const SQL_ATTR_CONNECTION_TIMEOUT : u32 = 113 ;
pub const SQL_ATTR_CURRENT_CATALOG : u32 = 109 ;
pub const SQL_ATTR_DISCONNECT_BEHAVIOR : u32 = 114 ;
pub const SQL_ATTR_ENLIST_IN_DTC : u32 = 1207 ;
pub const SQL_ATTR_ENLIST_IN_XA : u32 = 1208 ;
pub const SQL_ATTR_LOGIN_TIMEOUT : u32 = 103 ;
pub const SQL_ATTR_ODBC_CURSORS : u32 = 110 ;
pub const SQL_ATTR_PACKET_SIZE : u32 = 112 ;
pub const SQL_ATTR_QUIET_MODE : u32 = 111 ;
pub const SQL_ATTR_TRACE : u32 = 104 ;
pub const SQL_ATTR_TRACEFILE : u32 = 105 ;
pub const SQL_ATTR_TRANSLATE_LIB : u32 = 106 ;
pub const SQL_ATTR_TRANSLATE_OPTION : u32 = 107 ;
pub const SQL_ATTR_TXN_ISOLATION : u32 = 108 ;
pub const SQL_ATTR_CONNECTION_DEAD : u32 = 1209 ;
pub const SQL_ATTR_ANSI_APP : u32 = 115 ;
pub const SQL_ATTR_RESET_CONNECTION : u32 = 116 ;
pub const SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE : u32 = 117 ;
pub const SQL_MODE_READ_WRITE : u32 = 0 ;
pub const SQL_MODE_READ_ONLY : u32 = 1 ;
pub const SQL_MODE_DEFAULT : u32 = 0 ;
pub const SQL_AUTOCOMMIT_OFF : u32 = 0 ;
pub const SQL_AUTOCOMMIT_ON : u32 = 1 ;
pub const SQL_AUTOCOMMIT_DEFERRED : u32 = 2 ;
pub const SQL_AUTOCOMMIT_DEFAULT : u32 = 1 ;
pub const SQL_LOGIN_TIMEOUT_DEFAULT : u32 = 15 ;
pub const SQL_OPT_TRACE_OFF : u32 = 0 ;
pub const SQL_OPT_TRACE_ON : u32 = 1 ;
pub const SQL_OPT_TRACE_DEFAULT : u32 = 0 ;
pub const SQL_OPT_TRACE_FILE_DEFAULT : & 'static [u8 ;
9usize] = b"\\SQL.LOG\0" ;
pub const SQL_CUR_USE_IF_NEEDED : u32 = 0 ;
pub const SQL_CUR_USE_ODBC : u32 = 1 ;
pub const SQL_CUR_USE_DRIVER : u32 = 2 ;
pub const SQL_CUR_DEFAULT : u32 = 2 ;
pub const SQL_DB_RETURN_TO_POOL : u32 = 0 ;
pub const SQL_DB_DISCONNECT : u32 = 1 ;
pub const SQL_DB_DEFAULT : u32 = 0 ;
pub const SQL_DTC_DONE : u32 = 0 ;
pub const SQL_CD_TRUE : u32 = 1 ;
pub const SQL_CD_FALSE : u32 = 0 ;
pub const SQL_AA_TRUE : u32 = 1 ;
pub const SQL_AA_FALSE : u32 = 0 ;
pub const SQL_RESET_CONNECTION_YES : u32 = 1 ;
pub const SQL_ASYNC_DBC_ENABLE_ON : u32 = 1 ;
pub const SQL_ASYNC_DBC_ENABLE_OFF : u32 = 0 ;
pub const SQL_ASYNC_DBC_ENABLE_DEFAULT : u32 = 0 ;
pub const SQL_QUERY_TIMEOUT : u32 = 0 ;
pub const SQL_MAX_ROWS : u32 = 1 ;
pub const SQL_NOSCAN : u32 = 2 ;
pub const SQL_MAX_LENGTH : u32 = 3 ;
pub const SQL_ASYNC_ENABLE : u32 = 4 ;
pub const SQL_BIND_TYPE : u32 = 5 ;
pub const SQL_CURSOR_TYPE : u32 = 6 ;
pub const SQL_CONCURRENCY : u32 = 7 ;
pub const SQL_KEYSET_SIZE : u32 = 8 ;
pub const SQL_ROWSET_SIZE : u32 = 9 ;
pub const SQL_SIMULATE_CURSOR : u32 = 10 ;
pub const SQL_RETRIEVE_DATA : u32 = 11 ;
pub const SQL_USE_BOOKMARKS : u32 = 12 ;
pub const SQL_GET_BOOKMARK : u32 = 13 ;
pub const SQL_ROW_NUMBER : u32 = 14 ;
pub const SQL_ATTR_ASYNC_ENABLE : u32 = 4 ;
pub const SQL_ATTR_CONCURRENCY : u32 = 7 ;
pub const SQL_ATTR_CURSOR_TYPE : u32 = 6 ;
pub const SQL_ATTR_ENABLE_AUTO_IPD : u32 = 15 ;
pub const SQL_ATTR_FETCH_BOOKMARK_PTR : u32 = 16 ;
pub const SQL_ATTR_KEYSET_SIZE : u32 = 8 ;
pub const SQL_ATTR_MAX_LENGTH : u32 = 3 ;
pub const SQL_ATTR_MAX_ROWS : u32 = 1 ;
pub const SQL_ATTR_NOSCAN : u32 = 2 ;
pub const SQL_ATTR_PARAM_BIND_OFFSET_PTR : u32 = 17 ;
pub const SQL_ATTR_PARAM_BIND_TYPE : u32 = 18 ;
pub const SQL_ATTR_PARAM_OPERATION_PTR : u32 = 19 ;
pub const SQL_ATTR_PARAM_STATUS_PTR : u32 = 20 ;
pub const SQL_ATTR_PARAMS_PROCESSED_PTR : u32 = 21 ;
pub const SQL_ATTR_PARAMSET_SIZE : u32 = 22 ;
pub const SQL_ATTR_QUERY_TIMEOUT : u32 = 0 ;
pub const SQL_ATTR_RETRIEVE_DATA : u32 = 11 ;
pub const SQL_ATTR_ROW_BIND_OFFSET_PTR : u32 = 23 ;
pub const SQL_ATTR_ROW_BIND_TYPE : u32 = 5 ;
pub const SQL_ATTR_ROW_NUMBER : u32 = 14 ;
pub const SQL_ATTR_ROW_OPERATION_PTR : u32 = 24 ;
pub const SQL_ATTR_ROW_STATUS_PTR : u32 = 25 ;
pub const SQL_ATTR_ROWS_FETCHED_PTR : u32 = 26 ;
pub const SQL_ATTR_ROW_ARRAY_SIZE : u32 = 27 ;
pub const SQL_ATTR_SIMULATE_CURSOR : u32 = 10 ;
pub const SQL_ATTR_USE_BOOKMARKS : u32 = 12 ;
pub const SQL_IS_POINTER : i32 = - 4 ;
pub const SQL_IS_UINTEGER : i32 = - 5 ;
pub const SQL_IS_INTEGER : i32 = - 6 ;
pub const SQL_IS_USMALLINT : i32 = - 7 ;
pub const SQL_IS_SMALLINT : i32 = - 8 ;
pub const SQL_PARAM_BIND_BY_COLUMN : u32 = 0 ;
pub const SQL_PARAM_BIND_TYPE_DEFAULT : u32 = 0 ;
pub const SQL_QUERY_TIMEOUT_DEFAULT : u32 = 0 ;
pub const SQL_MAX_ROWS_DEFAULT : u32 = 0 ;
pub const SQL_NOSCAN_OFF : u32 = 0 ;
pub const SQL_NOSCAN_ON : u32 = 1 ;
pub const SQL_NOSCAN_DEFAULT : u32 = 0 ;
pub const SQL_MAX_LENGTH_DEFAULT : u32 = 0 ;
pub const SQL_ASYNC_ENABLE_OFF : u32 = 0 ;
pub const SQL_ASYNC_ENABLE_ON : u32 = 1 ;
pub const SQL_ASYNC_ENABLE_DEFAULT : u32 = 0 ;
pub const SQL_BIND_BY_COLUMN : u32 = 0 ;
pub const SQL_BIND_TYPE_DEFAULT : u32 = 0 ;
pub const SQL_CONCUR_READ_ONLY : u32 = 1 ;
pub const SQL_CONCUR_LOCK : u32 = 2 ;
pub const SQL_CONCUR_ROWVER : u32 = 3 ;
pub const SQL_CONCUR_VALUES : u32 = 4 ;
pub const SQL_CONCUR_DEFAULT : u32 = 1 ;
pub const SQL_CURSOR_FORWARD_ONLY : u32 = 0 ;
pub const SQL_CURSOR_KEYSET_DRIVEN : u32 = 1 ;
pub const SQL_CURSOR_DYNAMIC : u32 = 2 ;
pub const SQL_CURSOR_STATIC : u32 = 3 ;
pub const SQL_CURSOR_TYPE_DEFAULT : u32 = 0 ;
pub const SQL_ROWSET_SIZE_DEFAULT : u32 = 1 ;
pub const SQL_KEYSET_SIZE_DEFAULT : u32 = 0 ;
pub const SQL_SC_NON_UNIQUE : u32 = 0 ;
pub const SQL_SC_TRY_UNIQUE : u32 = 1 ;
pub const SQL_SC_UNIQUE : u32 = 2 ;
pub const SQL_RD_OFF : u32 = 0 ;
pub const SQL_RD_ON : u32 = 1 ;
pub const SQL_RD_DEFAULT : u32 = 1 ;
pub const SQL_UB_OFF : u32 = 0 ;
pub const SQL_UB_ON : u32 = 1 ;
pub const SQL_UB_DEFAULT : u32 = 0 ;
pub const SQL_UB_FIXED : u32 = 1 ;
pub const SQL_UB_VARIABLE : u32 = 2 ;
pub const SQL_DESC_ARRAY_SIZE : u32 = 20 ;
pub const SQL_DESC_ARRAY_STATUS_PTR : u32 = 21 ;
pub const SQL_DESC_BASE_COLUMN_NAME : u32 = 22 ;
pub const SQL_DESC_BASE_TABLE_NAME : u32 = 23 ;
pub const SQL_DESC_BIND_OFFSET_PTR : u32 = 24 ;
pub const SQL_DESC_BIND_TYPE : u32 = 25 ;
pub const SQL_DESC_DATETIME_INTERVAL_PRECISION : u32 = 26 ;
pub const SQL_DESC_LITERAL_PREFIX : u32 = 27 ;
pub const SQL_DESC_LITERAL_SUFFIX : u32 = 28 ;
pub const SQL_DESC_LOCAL_TYPE_NAME : u32 = 29 ;
pub const SQL_DESC_MAXIMUM_SCALE : u32 = 30 ;
pub const SQL_DESC_MINIMUM_SCALE : u32 = 31 ;
pub const SQL_DESC_NUM_PREC_RADIX : u32 = 32 ;
pub const SQL_DESC_PARAMETER_TYPE : u32 = 33 ;
pub const SQL_DESC_ROWS_PROCESSED_PTR : u32 = 34 ;
pub const SQL_DESC_ROWVER : u32 = 35 ;
pub const SQL_DIAG_CURSOR_ROW_COUNT : i32 = - 1249 ;
pub const SQL_DIAG_ROW_NUMBER : i32 = - 1248 ;
pub const SQL_DIAG_COLUMN_NUMBER : i32 = - 1247 ;
pub const SQL_DATE : u32 = 9 ;
pub const SQL_INTERVAL : u32 = 10 ;
pub const SQL_TIME : u32 = 10 ;
pub const SQL_TIMESTAMP : u32 = 11 ;
pub const SQL_LONGVARCHAR : i32 = - 1 ;
pub const SQL_BINARY : i32 = - 2 ;
pub const SQL_VARBINARY : i32 = - 3 ;
pub const SQL_LONGVARBINARY : i32 = - 4 ;
pub const SQL_BIGINT : i32 = - 5 ;
pub const SQL_TINYINT : i32 = - 6 ;
pub const SQL_BIT : i32 = - 7 ;
pub const SQL_GUID : i32 = - 11 ;
pub const SQL_CODE_YEAR : u32 = 1 ;
pub const SQL_CODE_MONTH : u32 = 2 ;
pub const SQL_CODE_DAY : u32 = 3 ;
pub const SQL_CODE_HOUR : u32 = 4 ;
pub const SQL_CODE_MINUTE : u32 = 5 ;
pub const SQL_CODE_SECOND : u32 = 6 ;
pub const SQL_CODE_YEAR_TO_MONTH : u32 = 7 ;
pub const SQL_CODE_DAY_TO_HOUR : u32 = 8 ;
pub const SQL_CODE_DAY_TO_MINUTE : u32 = 9 ;
pub const SQL_CODE_DAY_TO_SECOND : u32 = 10 ;
pub const SQL_CODE_HOUR_TO_MINUTE : u32 = 11 ;
pub const SQL_CODE_HOUR_TO_SECOND : u32 = 12 ;
pub const SQL_CODE_MINUTE_TO_SECOND : u32 = 13 ;
pub const SQL_INTERVAL_YEAR : u32 = 101 ;
pub const SQL_INTERVAL_MONTH : u32 = 102 ;
pub const SQL_INTERVAL_DAY : u32 = 103 ;
pub const SQL_INTERVAL_HOUR : u32 = 104 ;
pub const SQL_INTERVAL_MINUTE : u32 = 105 ;
pub const SQL_INTERVAL_SECOND : u32 = 106 ;
pub const SQL_INTERVAL_YEAR_TO_MONTH : u32 = 107 ;
pub const SQL_INTERVAL_DAY_TO_HOUR : u32 = 108 ;
pub const SQL_INTERVAL_DAY_TO_MINUTE : u32 = 109 ;
pub const SQL_INTERVAL_DAY_TO_SECOND : u32 = 110 ;
pub const SQL_INTERVAL_HOUR_TO_MINUTE : u32 = 111 ;
pub const SQL_INTERVAL_HOUR_TO_SECOND : u32 = 112 ;
pub const SQL_INTERVAL_MINUTE_TO_SECOND : u32 = 113 ;
pub const SQL_UNICODE : i32 = - 8 ;
pub const SQL_UNICODE_VARCHAR : i32 = - 9 ;
pub const SQL_UNICODE_LONGVARCHAR : i32 = - 10 ;
pub const SQL_UNICODE_CHAR : i32 = - 8 ;
pub const SQL_C_CHAR : u32 = 1 ;
pub const SQL_C_LONG : u32 = 4 ;
pub const SQL_C_SHORT : u32 = 5 ;
pub const SQL_C_FLOAT : u32 = 7 ;
pub const SQL_C_DOUBLE : u32 = 8 ;
pub const SQL_C_NUMERIC : u32 = 2 ;
pub const SQL_C_DEFAULT : u32 = 99 ;
pub const SQL_SIGNED_OFFSET : i32 = - 20 ;
pub const SQL_UNSIGNED_OFFSET : i32 = - 22 ;
pub const SQL_C_DATE : u32 = 9 ;
pub const SQL_C_TIME : u32 = 10 ;
pub const SQL_C_TIMESTAMP : u32 = 11 ;
pub const SQL_C_TYPE_DATE : u32 = 91 ;
pub const SQL_C_TYPE_TIME : u32 = 92 ;
pub const SQL_C_TYPE_TIMESTAMP : u32 = 93 ;
pub const SQL_C_INTERVAL_YEAR : u32 = 101 ;
pub const SQL_C_INTERVAL_MONTH : u32 = 102 ;
pub const SQL_C_INTERVAL_DAY : u32 = 103 ;
pub const SQL_C_INTERVAL_HOUR : u32 = 104 ;
pub const SQL_C_INTERVAL_MINUTE : u32 = 105 ;
pub const SQL_C_INTERVAL_SECOND : u32 = 106 ;
pub const SQL_C_INTERVAL_YEAR_TO_MONTH : u32 = 107 ;
pub const SQL_C_INTERVAL_DAY_TO_HOUR : u32 = 108 ;
pub const SQL_C_INTERVAL_DAY_TO_MINUTE : u32 = 109 ;
pub const SQL_C_INTERVAL_DAY_TO_SECOND : u32 = 110 ;
pub const SQL_C_INTERVAL_HOUR_TO_MINUTE : u32 = 111 ;
pub const SQL_C_INTERVAL_HOUR_TO_SECOND : u32 = 112 ;
pub const SQL_C_INTERVAL_MINUTE_TO_SECOND : u32 = 113 ;
pub const SQL_C_BINARY : i32 = - 2 ;
pub const SQL_C_BIT : i32 = - 7 ;
pub const SQL_C_SBIGINT : i32 = - 25 ;
pub const SQL_C_UBIGINT : i32 = - 27 ;
pub const SQL_C_TINYINT : i32 = - 6 ;
pub const SQL_C_SLONG : i32 = - 16 ;
pub const SQL_C_SSHORT : i32 = - 15 ;
pub const SQL_C_STINYINT : i32 = - 26 ;
pub const SQL_C_ULONG : i32 = - 18 ;
pub const SQL_C_USHORT : i32 = - 17 ;
pub const SQL_C_UTINYINT : i32 = - 28 ;
pub const SQL_C_BOOKMARK : i32 = - 18 ;
pub const SQL_C_GUID : i32 = - 11 ;
pub const SQL_TYPE_NULL : u32 = 0 ;
pub const SQL_DRIVER_C_TYPE_BASE : u32 = 16384 ;
pub const SQL_DRIVER_SQL_TYPE_BASE : u32 = 16384 ;
pub const SQL_DRIVER_DESC_FIELD_BASE : u32 = 16384 ;
pub const SQL_DRIVER_DIAG_FIELD_BASE : u32 = 16384 ;
pub const SQL_DRIVER_INFO_TYPE_BASE : u32 = 16384 ;
pub const SQL_DRIVER_CONN_ATTR_BASE : u32 = 16384 ;
pub const SQL_DRIVER_STMT_ATTR_BASE : u32 = 16384 ;
pub const SQL_C_VARBOOKMARK : i32 = - 2 ;
pub const SQL_NO_ROW_NUMBER : i32 = - 1 ;
pub const SQL_NO_COLUMN_NUMBER : i32 = - 1 ;
pub const SQL_DEFAULT_PARAM : i32 = - 5 ;
pub const SQL_IGNORE : i32 = - 6 ;
pub const SQL_COLUMN_IGNORE : i32 = - 6 ;
pub const SQL_LEN_DATA_AT_EXEC_OFFSET : i32 = - 100 ;
pub const SQL_LEN_BINARY_ATTR_OFFSET : i32 = - 100 ;
pub const SQL_SETPARAM_VALUE_MAX : i32 = - 1 ;
pub const SQL_COLUMN_COUNT : u32 = 0 ;
pub const SQL_COLUMN_NAME : u32 = 1 ;
pub const SQL_COLUMN_TYPE : u32 = 2 ;
pub const SQL_COLUMN_LENGTH : u32 = 3 ;
pub const SQL_COLUMN_PRECISION : u32 = 4 ;
pub const SQL_COLUMN_SCALE : u32 = 5 ;
pub const SQL_COLUMN_DISPLAY_SIZE : u32 = 6 ;
pub const SQL_COLUMN_NULLABLE : u32 = 7 ;
pub const SQL_COLUMN_UNSIGNED : u32 = 8 ;
pub const SQL_COLUMN_MONEY : u32 = 9 ;
pub const SQL_COLUMN_UPDATABLE : u32 = 10 ;
pub const SQL_COLUMN_AUTO_INCREMENT : u32 = 11 ;
pub const SQL_COLUMN_CASE_SENSITIVE : u32 = 12 ;
pub const SQL_COLUMN_SEARCHABLE : u32 = 13 ;
pub const SQL_COLUMN_TYPE_NAME : u32 = 14 ;
pub const SQL_COLUMN_TABLE_NAME : u32 = 15 ;
pub const SQL_COLUMN_OWNER_NAME : u32 = 16 ;
pub const SQL_COLUMN_QUALIFIER_NAME : u32 = 17 ;
pub const SQL_COLUMN_LABEL : u32 = 18 ;
pub const SQL_COLATT_OPT_MAX : u32 = 18 ;
pub const SQL_COLATT_OPT_MIN : u32 = 0 ;
pub const SQL_ATTR_READONLY : u32 = 0 ;
pub const SQL_ATTR_WRITE : u32 = 1 ;
pub const SQL_ATTR_READWRITE_UNKNOWN : u32 = 2 ;
pub const SQL_UNSEARCHABLE : u32 = 0 ;
pub const SQL_LIKE_ONLY : u32 = 1 ;
pub const SQL_ALL_EXCEPT_LIKE : u32 = 2 ;
pub const SQL_SEARCHABLE : u32 = 3 ;
pub const SQL_PRED_SEARCHABLE : u32 = 3 ;
pub const SQL_NO_TOTAL : i32 = - 4 ;
pub const SQL_API_SQLALLOCHANDLESTD : u32 = 73 ;
pub const SQL_API_SQLBULKOPERATIONS : u32 = 24 ;
pub const SQL_API_SQLBINDPARAMETER : u32 = 72 ;
pub const SQL_API_SQLBROWSECONNECT : u32 = 55 ;
pub const SQL_API_SQLCOLATTRIBUTES : u32 = 6 ;
pub const SQL_API_SQLCOLUMNPRIVILEGES : u32 = 56 ;
pub const SQL_API_SQLDESCRIBEPARAM : u32 = 58 ;
pub const SQL_API_SQLDRIVERCONNECT : u32 = 41 ;
pub const SQL_API_SQLDRIVERS : u32 = 71 ;
pub const SQL_API_SQLEXTENDEDFETCH : u32 = 59 ;
pub const SQL_API_SQLFOREIGNKEYS : u32 = 60 ;
pub const SQL_API_SQLMORERESULTS : u32 = 61 ;
pub const SQL_API_SQLNATIVESQL : u32 = 62 ;
pub const SQL_API_SQLNUMPARAMS : u32 = 63 ;
pub const SQL_API_SQLPARAMOPTIONS : u32 = 64 ;
pub const SQL_API_SQLPRIMARYKEYS : u32 = 65 ;
pub const SQL_API_SQLPROCEDURECOLUMNS : u32 = 66 ;
pub const SQL_API_SQLPROCEDURES : u32 = 67 ;
pub const SQL_API_SQLSETPOS : u32 = 68 ;
pub const SQL_API_SQLSETSCROLLOPTIONS : u32 = 69 ;
pub const SQL_API_SQLTABLEPRIVILEGES : u32 = 70 ;
pub const SQL_API_ALL_FUNCTIONS : u32 = 0 ;
pub const SQL_API_LOADBYORDINAL : u32 = 199 ;
pub const SQL_API_ODBC3_ALL_FUNCTIONS : u32 = 999 ;
pub const SQL_API_ODBC3_ALL_FUNCTIONS_SIZE : u32 = 250 ;
pub const SQL_INFO_FIRST : u32 = 0 ;
pub const SQL_ACTIVE_CONNECTIONS : u32 = 0 ;
pub const SQL_ACTIVE_STATEMENTS : u32 = 1 ;
pub const SQL_DRIVER_HDBC : u32 = 3 ;
pub const SQL_DRIVER_HENV : u32 = 4 ;
pub const SQL_DRIVER_HSTMT : u32 = 5 ;
pub const SQL_DRIVER_NAME : u32 = 6 ;
pub const SQL_DRIVER_VER : u32 = 7 ;
pub const SQL_ODBC_API_CONFORMANCE : u32 = 9 ;
pub const SQL_ODBC_VER : u32 = 10 ;
pub const SQL_ROW_UPDATES : u32 = 11 ;
pub const SQL_ODBC_SAG_CLI_CONFORMANCE : u32 = 12 ;
pub const SQL_ODBC_SQL_CONFORMANCE : u32 = 15 ;
pub const SQL_PROCEDURES : u32 = 21 ;
pub const SQL_CONCAT_NULL_BEHAVIOR : u32 = 22 ;
pub const SQL_CURSOR_ROLLBACK_BEHAVIOR : u32 = 24 ;
pub const SQL_EXPRESSIONS_IN_ORDERBY : u32 = 27 ;
pub const SQL_MAX_OWNER_NAME_LEN : u32 = 32 ;
pub const SQL_MAX_PROCEDURE_NAME_LEN : u32 = 33 ;
pub const SQL_MAX_QUALIFIER_NAME_LEN : u32 = 34 ;
pub const SQL_MULT_RESULT_SETS : u32 = 36 ;
pub const SQL_MULTIPLE_ACTIVE_TXN : u32 = 37 ;
pub const SQL_OUTER_JOINS : u32 = 38 ;
pub const SQL_OWNER_TERM : u32 = 39 ;
pub const SQL_PROCEDURE_TERM : u32 = 40 ;
pub const SQL_QUALIFIER_NAME_SEPARATOR : u32 = 41 ;
pub const SQL_QUALIFIER_TERM : u32 = 42 ;
pub const SQL_SCROLL_OPTIONS : u32 = 44 ;
pub const SQL_TABLE_TERM : u32 = 45 ;
pub const SQL_CONVERT_FUNCTIONS : u32 = 48 ;
pub const SQL_NUMERIC_FUNCTIONS : u32 = 49 ;
pub const SQL_STRING_FUNCTIONS : u32 = 50 ;
pub const SQL_SYSTEM_FUNCTIONS : u32 = 51 ;
pub const SQL_TIMEDATE_FUNCTIONS : u32 = 52 ;
pub const SQL_CONVERT_BIGINT : u32 = 53 ;
pub const SQL_CONVERT_BINARY : u32 = 54 ;
pub const SQL_CONVERT_BIT : u32 = 55 ;
pub const SQL_CONVERT_CHAR : u32 = 56 ;
pub const SQL_CONVERT_DATE : u32 = 57 ;
pub const SQL_CONVERT_DECIMAL : u32 = 58 ;
pub const SQL_CONVERT_DOUBLE : u32 = 59 ;
pub const SQL_CONVERT_FLOAT : u32 = 60 ;
pub const SQL_CONVERT_INTEGER : u32 = 61 ;
pub const SQL_CONVERT_LONGVARCHAR : u32 = 62 ;
pub const SQL_CONVERT_NUMERIC : u32 = 63 ;
pub const SQL_CONVERT_REAL : u32 = 64 ;
pub const SQL_CONVERT_SMALLINT : u32 = 65 ;
pub const SQL_CONVERT_TIME : u32 = 66 ;
pub const SQL_CONVERT_TIMESTAMP : u32 = 67 ;
pub const SQL_CONVERT_TINYINT : u32 = 68 ;
pub const SQL_CONVERT_VARBINARY : u32 = 69 ;
pub const SQL_CONVERT_VARCHAR : u32 = 70 ;
pub const SQL_CONVERT_LONGVARBINARY : u32 = 71 ;
pub const SQL_ODBC_SQL_OPT_IEF : u32 = 73 ;
pub const SQL_CORRELATION_NAME : u32 = 74 ;
pub const SQL_NON_NULLABLE_COLUMNS : u32 = 75 ;
pub const SQL_DRIVER_HLIB : u32 = 76 ;
pub const SQL_DRIVER_ODBC_VER : u32 = 77 ;
pub const SQL_LOCK_TYPES : u32 = 78 ;
pub const SQL_POS_OPERATIONS : u32 = 79 ;
pub const SQL_POSITIONED_STATEMENTS : u32 = 80 ;
pub const SQL_BOOKMARK_PERSISTENCE : u32 = 82 ;
pub const SQL_STATIC_SENSITIVITY : u32 = 83 ;
pub const SQL_FILE_USAGE : u32 = 84 ;
pub const SQL_COLUMN_ALIAS : u32 = 87 ;
pub const SQL_GROUP_BY : u32 = 88 ;
pub const SQL_KEYWORDS : u32 = 89 ;
pub const SQL_OWNER_USAGE : u32 = 91 ;
pub const SQL_QUALIFIER_USAGE : u32 = 92 ;
pub const SQL_QUOTED_IDENTIFIER_CASE : u32 = 93 ;
pub const SQL_SUBQUERIES : u32 = 95 ;
pub const SQL_UNION : u32 = 96 ;
pub const SQL_MAX_ROW_SIZE_INCLUDES_LONG : u32 = 103 ;
pub const SQL_MAX_CHAR_LITERAL_LEN : u32 = 108 ;
pub const SQL_TIMEDATE_ADD_INTERVALS : u32 = 109 ;
pub const SQL_TIMEDATE_DIFF_INTERVALS : u32 = 110 ;
pub const SQL_NEED_LONG_DATA_LEN : u32 = 111 ;
pub const SQL_MAX_BINARY_LITERAL_LEN : u32 = 112 ;
pub const SQL_LIKE_ESCAPE_CLAUSE : u32 = 113 ;
pub const SQL_QUALIFIER_LOCATION : u32 = 114 ;
pub const SQL_ACTIVE_ENVIRONMENTS : u32 = 116 ;
pub const SQL_ALTER_DOMAIN : u32 = 117 ;
pub const SQL_SQL_CONFORMANCE : u32 = 118 ;
pub const SQL_DATETIME_LITERALS : u32 = 119 ;
pub const SQL_ASYNC_MODE : u32 = 10021 ;
pub const SQL_BATCH_ROW_COUNT : u32 = 120 ;
pub const SQL_BATCH_SUPPORT : u32 = 121 ;
pub const SQL_CATALOG_LOCATION : u32 = 114 ;
pub const SQL_CATALOG_NAME_SEPARATOR : u32 = 41 ;
pub const SQL_CATALOG_TERM : u32 = 42 ;
pub const SQL_CATALOG_USAGE : u32 = 92 ;
pub const SQL_CONVERT_WCHAR : u32 = 122 ;
pub const SQL_CONVERT_INTERVAL_DAY_TIME : u32 = 123 ;
pub const SQL_CONVERT_INTERVAL_YEAR_MONTH : u32 = 124 ;
pub const SQL_CONVERT_WLONGVARCHAR : u32 = 125 ;
pub const SQL_CONVERT_WVARCHAR : u32 = 126 ;
pub const SQL_CREATE_ASSERTION : u32 = 127 ;
pub const SQL_CREATE_CHARACTER_SET : u32 = 128 ;
pub const SQL_CREATE_COLLATION : u32 = 129 ;
pub const SQL_CREATE_DOMAIN : u32 = 130 ;
pub const SQL_CREATE_SCHEMA : u32 = 131 ;
pub const SQL_CREATE_TABLE : u32 = 132 ;
pub const SQL_CREATE_TRANSLATION : u32 = 133 ;
pub const SQL_CREATE_VIEW : u32 = 134 ;
pub const SQL_DRIVER_HDESC : u32 = 135 ;
pub const SQL_DROP_ASSERTION : u32 = 136 ;
pub const SQL_DROP_CHARACTER_SET : u32 = 137 ;
pub const SQL_DROP_COLLATION : u32 = 138 ;
pub const SQL_DROP_DOMAIN : u32 = 139 ;
pub const SQL_DROP_SCHEMA : u32 = 140 ;
pub const SQL_DROP_TABLE : u32 = 141 ;
pub const SQL_DROP_TRANSLATION : u32 = 142 ;
pub const SQL_DROP_VIEW : u32 = 143 ;
pub const SQL_DYNAMIC_CURSOR_ATTRIBUTES1 : u32 = 144 ;
pub const SQL_DYNAMIC_CURSOR_ATTRIBUTES2 : u32 = 145 ;
pub const SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 : u32 = 146 ;
pub const SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 : u32 = 147 ;
pub const SQL_INDEX_KEYWORDS : u32 = 148 ;
pub const SQL_INFO_SCHEMA_VIEWS : u32 = 149 ;
pub const SQL_KEYSET_CURSOR_ATTRIBUTES1 : u32 = 150 ;
pub const SQL_KEYSET_CURSOR_ATTRIBUTES2 : u32 = 151 ;
pub const SQL_MAX_ASYNC_CONCURRENT_STATEMENTS : u32 = 10022 ;
pub const SQL_ODBC_INTERFACE_CONFORMANCE : u32 = 152 ;
pub const SQL_PARAM_ARRAY_ROW_COUNTS : u32 = 153 ;
pub const SQL_PARAM_ARRAY_SELECTS : u32 = 154 ;
pub const SQL_SCHEMA_TERM : u32 = 39 ;
pub const SQL_SCHEMA_USAGE : u32 = 91 ;
pub const SQL_SQL92_DATETIME_FUNCTIONS : u32 = 155 ;
pub const SQL_SQL92_FOREIGN_KEY_DELETE_RULE : u32 = 156 ;
pub const SQL_SQL92_FOREIGN_KEY_UPDATE_RULE : u32 = 157 ;
pub const SQL_SQL92_GRANT : u32 = 158 ;
pub const SQL_SQL92_NUMERIC_VALUE_FUNCTIONS : u32 = 159 ;
pub const SQL_SQL92_PREDICATES : u32 = 160 ;
pub const SQL_SQL92_RELATIONAL_JOIN_OPERATORS : u32 = 161 ;
pub const SQL_SQL92_REVOKE : u32 = 162 ;
pub const SQL_SQL92_ROW_VALUE_CONSTRUCTOR : u32 = 163 ;
pub const SQL_SQL92_STRING_FUNCTIONS : u32 = 164 ;
pub const SQL_SQL92_VALUE_EXPRESSIONS : u32 = 165 ;
pub const SQL_STANDARD_CLI_CONFORMANCE : u32 = 166 ;
pub const SQL_STATIC_CURSOR_ATTRIBUTES1 : u32 = 167 ;
pub const SQL_STATIC_CURSOR_ATTRIBUTES2 : u32 = 168 ;
pub const SQL_AGGREGATE_FUNCTIONS : u32 = 169 ;
pub const SQL_DDL_INDEX : u32 = 170 ;
pub const SQL_DM_VER : u32 = 171 ;
pub const SQL_INSERT_STATEMENT : u32 = 172 ;
pub const SQL_CONVERT_GUID : u32 = 173 ;
pub const SQL_UNION_STATEMENT : u32 = 96 ;
pub const SQL_ASYNC_DBC_FUNCTIONS : u32 = 10023 ;
pub const SQL_DTC_TRANSITION_COST : u32 = 1750 ;
pub const SQL_AT_ADD_COLUMN_SINGLE : u32 = 32 ;
pub const SQL_AT_ADD_COLUMN_DEFAULT : u32 = 64 ;
pub const SQL_AT_ADD_COLUMN_COLLATION : u32 = 128 ;
pub const SQL_AT_SET_COLUMN_DEFAULT : u32 = 256 ;
pub const SQL_AT_DROP_COLUMN_DEFAULT : u32 = 512 ;
pub const SQL_AT_DROP_COLUMN_CASCADE : u32 = 1024 ;
pub const SQL_AT_DROP_COLUMN_RESTRICT : u32 = 2048 ;
pub const SQL_AT_ADD_TABLE_CONSTRAINT : u32 = 4096 ;
pub const SQL_AT_DROP_TABLE_CONSTRAINT_CASCADE : u32 = 8192 ;
pub const SQL_AT_DROP_TABLE_CONSTRAINT_RESTRICT : u32 = 16384 ;
pub const SQL_AT_CONSTRAINT_NAME_DEFINITION : u32 = 32768 ;
pub const SQL_AT_CONSTRAINT_INITIALLY_DEFERRED : u32 = 65536 ;
pub const SQL_AT_CONSTRAINT_INITIALLY_IMMEDIATE : u32 = 131072 ;
pub const SQL_AT_CONSTRAINT_DEFERRABLE : u32 = 262144 ;
pub const SQL_AT_CONSTRAINT_NON_DEFERRABLE : u32 = 524288 ;
pub const SQL_CVT_CHAR : u32 = 1 ;
pub const SQL_CVT_NUMERIC : u32 = 2 ;
pub const SQL_CVT_DECIMAL : u32 = 4 ;
pub const SQL_CVT_INTEGER : u32 = 8 ;
pub const SQL_CVT_SMALLINT : u32 = 16 ;
pub const SQL_CVT_FLOAT : u32 = 32 ;
pub const SQL_CVT_REAL : u32 = 64 ;
pub const SQL_CVT_DOUBLE : u32 = 128 ;
pub const SQL_CVT_VARCHAR : u32 = 256 ;
pub const SQL_CVT_LONGVARCHAR : u32 = 512 ;
pub const SQL_CVT_BINARY : u32 = 1024 ;
pub const SQL_CVT_VARBINARY : u32 = 2048 ;
pub const SQL_CVT_BIT : u32 = 4096 ;
pub const SQL_CVT_TINYINT : u32 = 8192 ;
pub const SQL_CVT_BIGINT : u32 = 16384 ;
pub const SQL_CVT_DATE : u32 = 32768 ;
pub const SQL_CVT_TIME : u32 = 65536 ;
pub const SQL_CVT_TIMESTAMP : u32 = 131072 ;
pub const SQL_CVT_LONGVARBINARY : u32 = 262144 ;
pub const SQL_CVT_INTERVAL_YEAR_MONTH : u32 = 524288 ;
pub const SQL_CVT_INTERVAL_DAY_TIME : u32 = 1048576 ;
pub const SQL_CVT_WCHAR : u32 = 2097152 ;
pub const SQL_CVT_WLONGVARCHAR : u32 = 4194304 ;
pub const SQL_CVT_WVARCHAR : u32 = 8388608 ;
pub const SQL_CVT_GUID : u32 = 16777216 ;
pub const SQL_FN_CVT_CONVERT : u32 = 1 ;
pub const SQL_FN_CVT_CAST : u32 = 2 ;
pub const SQL_FN_STR_CONCAT : u32 = 1 ;
pub const SQL_FN_STR_INSERT : u32 = 2 ;
pub const SQL_FN_STR_LEFT : u32 = 4 ;
pub const SQL_FN_STR_LTRIM : u32 = 8 ;
pub const SQL_FN_STR_LENGTH : u32 = 16 ;
pub const SQL_FN_STR_LOCATE : u32 = 32 ;
pub const SQL_FN_STR_LCASE : u32 = 64 ;
pub const SQL_FN_STR_REPEAT : u32 = 128 ;
pub const SQL_FN_STR_REPLACE : u32 = 256 ;
pub const SQL_FN_STR_RIGHT : u32 = 512 ;
pub const SQL_FN_STR_RTRIM : u32 = 1024 ;
pub const SQL_FN_STR_SUBSTRING : u32 = 2048 ;
pub const SQL_FN_STR_UCASE : u32 = 4096 ;
pub const SQL_FN_STR_ASCII : u32 = 8192 ;
pub const SQL_FN_STR_CHAR : u32 = 16384 ;
pub const SQL_FN_STR_DIFFERENCE : u32 = 32768 ;
pub const SQL_FN_STR_LOCATE_2 : u32 = 65536 ;
pub const SQL_FN_STR_SOUNDEX : u32 = 131072 ;
pub const SQL_FN_STR_SPACE : u32 = 262144 ;
pub const SQL_FN_STR_BIT_LENGTH : u32 = 524288 ;
pub const SQL_FN_STR_CHAR_LENGTH : u32 = 1048576 ;
pub const SQL_FN_STR_CHARACTER_LENGTH : u32 = 2097152 ;
pub const SQL_FN_STR_OCTET_LENGTH : u32 = 4194304 ;
pub const SQL_FN_STR_POSITION : u32 = 8388608 ;
pub const SQL_SSF_CONVERT : u32 = 1 ;
pub const SQL_SSF_LOWER : u32 = 2 ;
pub const SQL_SSF_UPPER : u32 = 4 ;
pub const SQL_SSF_SUBSTRING : u32 = 8 ;
pub const SQL_SSF_TRANSLATE : u32 = 16 ;
pub const SQL_SSF_TRIM_BOTH : u32 = 32 ;
pub const SQL_SSF_TRIM_LEADING : u32 = 64 ;
pub const SQL_SSF_TRIM_TRAILING : u32 = 128 ;
pub const SQL_FN_NUM_ABS : u32 = 1 ;
pub const SQL_FN_NUM_ACOS : u32 = 2 ;
pub const SQL_FN_NUM_ASIN : u32 = 4 ;
pub const SQL_FN_NUM_ATAN : u32 = 8 ;
pub const SQL_FN_NUM_ATAN2 : u32 = 16 ;
pub const SQL_FN_NUM_CEILING : u32 = 32 ;
pub const SQL_FN_NUM_COS : u32 = 64 ;
pub const SQL_FN_NUM_COT : u32 = 128 ;
pub const SQL_FN_NUM_EXP : u32 = 256 ;
pub const SQL_FN_NUM_FLOOR : u32 = 512 ;
pub const SQL_FN_NUM_LOG : u32 = 1024 ;
pub const SQL_FN_NUM_MOD : u32 = 2048 ;
pub const SQL_FN_NUM_SIGN : u32 = 4096 ;
pub const SQL_FN_NUM_SIN : u32 = 8192 ;
pub const SQL_FN_NUM_SQRT : u32 = 16384 ;
pub const SQL_FN_NUM_TAN : u32 = 32768 ;
pub const SQL_FN_NUM_PI : u32 = 65536 ;
pub const SQL_FN_NUM_RAND : u32 = 131072 ;
pub const SQL_FN_NUM_DEGREES : u32 = 262144 ;
pub const SQL_FN_NUM_LOG10 : u32 = 524288 ;
pub const SQL_FN_NUM_POWER : u32 = 1048576 ;
pub const SQL_FN_NUM_RADIANS : u32 = 2097152 ;
pub const SQL_FN_NUM_ROUND : u32 = 4194304 ;
pub const SQL_FN_NUM_TRUNCATE : u32 = 8388608 ;
pub const SQL_SNVF_BIT_LENGTH : u32 = 1 ;
pub const SQL_SNVF_CHAR_LENGTH : u32 = 2 ;
pub const SQL_SNVF_CHARACTER_LENGTH : u32 = 4 ;
pub const SQL_SNVF_EXTRACT : u32 = 8 ;
pub const SQL_SNVF_OCTET_LENGTH : u32 = 16 ;
pub const SQL_SNVF_POSITION : u32 = 32 ;
pub const SQL_FN_TD_NOW : u32 = 1 ;
pub const SQL_FN_TD_CURDATE : u32 = 2 ;
pub const SQL_FN_TD_DAYOFMONTH : u32 = 4 ;
pub const SQL_FN_TD_DAYOFWEEK : u32 = 8 ;
pub const SQL_FN_TD_DAYOFYEAR : u32 = 16 ;
pub const SQL_FN_TD_MONTH : u32 = 32 ;
pub const SQL_FN_TD_QUARTER : u32 = 64 ;
pub const SQL_FN_TD_WEEK : u32 = 128 ;
pub const SQL_FN_TD_YEAR : u32 = 256 ;
pub const SQL_FN_TD_CURTIME : u32 = 512 ;
pub const SQL_FN_TD_HOUR : u32 = 1024 ;
pub const SQL_FN_TD_MINUTE : u32 = 2048 ;
pub const SQL_FN_TD_SECOND : u32 = 4096 ;
pub const SQL_FN_TD_TIMESTAMPADD : u32 = 8192 ;
pub const SQL_FN_TD_TIMESTAMPDIFF : u32 = 16384 ;
pub const SQL_FN_TD_DAYNAME : u32 = 32768 ;
pub const SQL_FN_TD_MONTHNAME : u32 = 65536 ;
pub const SQL_FN_TD_CURRENT_DATE : u32 = 131072 ;
pub const SQL_FN_TD_CURRENT_TIME : u32 = 262144 ;
pub const SQL_FN_TD_CURRENT_TIMESTAMP : u32 = 524288 ;
pub const SQL_FN_TD_EXTRACT : u32 = 1048576 ;
pub const SQL_SDF_CURRENT_DATE : u32 = 1 ;
pub const SQL_SDF_CURRENT_TIME : u32 = 2 ;
pub const SQL_SDF_CURRENT_TIMESTAMP : u32 = 4 ;
pub const SQL_FN_SYS_USERNAME : u32 = 1 ;
pub const SQL_FN_SYS_DBNAME : u32 = 2 ;
pub const SQL_FN_SYS_IFNULL : u32 = 4 ;
pub const SQL_FN_TSI_FRAC_SECOND : u32 = 1 ;
pub const SQL_FN_TSI_SECOND : u32 = 2 ;
pub const SQL_FN_TSI_MINUTE : u32 = 4 ;
pub const SQL_FN_TSI_HOUR : u32 = 8 ;
pub const SQL_FN_TSI_DAY : u32 = 16 ;
pub const SQL_FN_TSI_WEEK : u32 = 32 ;
pub const SQL_FN_TSI_MONTH : u32 = 64 ;
pub const SQL_FN_TSI_QUARTER : u32 = 128 ;
pub const SQL_FN_TSI_YEAR : u32 = 256 ;
pub const SQL_CA1_NEXT : u32 = 1 ;
pub const SQL_CA1_ABSOLUTE : u32 = 2 ;
pub const SQL_CA1_RELATIVE : u32 = 4 ;
pub const SQL_CA1_BOOKMARK : u32 = 8 ;
pub const SQL_CA1_LOCK_NO_CHANGE : u32 = 64 ;
pub const SQL_CA1_LOCK_EXCLUSIVE : u32 = 128 ;
pub const SQL_CA1_LOCK_UNLOCK : u32 = 256 ;
pub const SQL_CA1_POS_POSITION : u32 = 512 ;
pub const SQL_CA1_POS_UPDATE : u32 = 1024 ;
pub const SQL_CA1_POS_DELETE : u32 = 2048 ;
pub const SQL_CA1_POS_REFRESH : u32 = 4096 ;
pub const SQL_CA1_POSITIONED_UPDATE : u32 = 8192 ;
pub const SQL_CA1_POSITIONED_DELETE : u32 = 16384 ;
pub const SQL_CA1_SELECT_FOR_UPDATE : u32 = 32768 ;
pub const SQL_CA1_BULK_ADD : u32 = 65536 ;
pub const SQL_CA1_BULK_UPDATE_BY_BOOKMARK : u32 = 131072 ;
pub const SQL_CA1_BULK_DELETE_BY_BOOKMARK : u32 = 262144 ;
pub const SQL_CA1_BULK_FETCH_BY_BOOKMARK : u32 = 524288 ;
pub const SQL_CA2_READ_ONLY_CONCURRENCY : u32 = 1 ;
pub const SQL_CA2_LOCK_CONCURRENCY : u32 = 2 ;
pub const SQL_CA2_OPT_ROWVER_CONCURRENCY : u32 = 4 ;
pub const SQL_CA2_OPT_VALUES_CONCURRENCY : u32 = 8 ;
pub const SQL_CA2_SENSITIVITY_ADDITIONS : u32 = 16 ;
pub const SQL_CA2_SENSITIVITY_DELETIONS : u32 = 32 ;
pub const SQL_CA2_SENSITIVITY_UPDATES : u32 = 64 ;
pub const SQL_CA2_MAX_ROWS_SELECT : u32 = 128 ;
pub const SQL_CA2_MAX_ROWS_INSERT : u32 = 256 ;
pub const SQL_CA2_MAX_ROWS_DELETE : u32 = 512 ;
pub const SQL_CA2_MAX_ROWS_UPDATE : u32 = 1024 ;
pub const SQL_CA2_MAX_ROWS_CATALOG : u32 = 2048 ;
pub const SQL_CA2_MAX_ROWS_AFFECTS_ALL : u32 = 3968 ;
pub const SQL_CA2_CRC_EXACT : u32 = 4096 ;
pub const SQL_CA2_CRC_APPROXIMATE : u32 = 8192 ;
pub const SQL_CA2_SIMULATE_NON_UNIQUE : u32 = 16384 ;
pub const SQL_CA2_SIMULATE_TRY_UNIQUE : u32 = 32768 ;
pub const SQL_CA2_SIMULATE_UNIQUE : u32 = 65536 ;
pub const SQL_OAC_NONE : u32 = 0 ;
pub const SQL_OAC_LEVEL1 : u32 = 1 ;
pub const SQL_OAC_LEVEL2 : u32 = 2 ;
pub const SQL_OSCC_NOT_COMPLIANT : u32 = 0 ;
pub const SQL_OSCC_COMPLIANT : u32 = 1 ;
pub const SQL_OSC_MINIMUM : u32 = 0 ;
pub const SQL_OSC_CORE : u32 = 1 ;
pub const SQL_OSC_EXTENDED : u32 = 2 ;
pub const SQL_CB_NULL : u32 = 0 ;
pub const SQL_CB_NON_NULL : u32 = 1 ;
pub const SQL_SO_FORWARD_ONLY : u32 = 1 ;
pub const SQL_SO_KEYSET_DRIVEN : u32 = 2 ;
pub const SQL_SO_DYNAMIC : u32 = 4 ;
pub const SQL_SO_MIXED : u32 = 8 ;
pub const SQL_SO_STATIC : u32 = 16 ;
pub const SQL_FD_FETCH_BOOKMARK : u32 = 128 ;
pub const SQL_CN_NONE : u32 = 0 ;
pub const SQL_CN_DIFFERENT : u32 = 1 ;
pub const SQL_CN_ANY : u32 = 2 ;
pub const SQL_NNC_NULL : u32 = 0 ;
pub const SQL_NNC_NON_NULL : u32 = 1 ;
pub const SQL_NC_START : u32 = 2 ;
pub const SQL_NC_END : u32 = 4 ;
pub const SQL_FILE_NOT_SUPPORTED : u32 = 0 ;
pub const SQL_FILE_TABLE : u32 = 1 ;
pub const SQL_FILE_QUALIFIER : u32 = 2 ;
pub const SQL_FILE_CATALOG : u32 = 2 ;
pub const SQL_GD_BLOCK : u32 = 4 ;
pub const SQL_GD_BOUND : u32 = 8 ;
pub const SQL_GD_OUTPUT_PARAMS : u32 = 16 ;
pub const SQL_PS_POSITIONED_DELETE : u32 = 1 ;
pub const SQL_PS_POSITIONED_UPDATE : u32 = 2 ;
pub const SQL_PS_SELECT_FOR_UPDATE : u32 = 4 ;
pub const SQL_GB_NOT_SUPPORTED : u32 = 0 ;
pub const SQL_GB_GROUP_BY_EQUALS_SELECT : u32 = 1 ;
pub const SQL_GB_GROUP_BY_CONTAINS_SELECT : u32 = 2 ;
pub const SQL_GB_NO_RELATION : u32 = 3 ;
pub const SQL_GB_COLLATE : u32 = 4 ;
pub const SQL_OU_DML_STATEMENTS : u32 = 1 ;
pub const SQL_OU_PROCEDURE_INVOCATION : u32 = 2 ;
pub const SQL_OU_TABLE_DEFINITION : u32 = 4 ;
pub const SQL_OU_INDEX_DEFINITION : u32 = 8 ;
pub const SQL_OU_PRIVILEGE_DEFINITION : u32 = 16 ;
pub const SQL_SU_DML_STATEMENTS : u32 = 1 ;
pub const SQL_SU_PROCEDURE_INVOCATION : u32 = 2 ;
pub const SQL_SU_TABLE_DEFINITION : u32 = 4 ;
pub const SQL_SU_INDEX_DEFINITION : u32 = 8 ;
pub const SQL_SU_PRIVILEGE_DEFINITION : u32 = 16 ;
pub const SQL_QU_DML_STATEMENTS : u32 = 1 ;
pub const SQL_QU_PROCEDURE_INVOCATION : u32 = 2 ;
pub const SQL_QU_TABLE_DEFINITION : u32 = 4 ;
pub const SQL_QU_INDEX_DEFINITION : u32 = 8 ;
pub const SQL_QU_PRIVILEGE_DEFINITION : u32 = 16 ;
pub const SQL_CU_DML_STATEMENTS : u32 = 1 ;
pub const SQL_CU_PROCEDURE_INVOCATION : u32 = 2 ;
pub const SQL_CU_TABLE_DEFINITION : u32 = 4 ;
pub const SQL_CU_INDEX_DEFINITION : u32 = 8 ;
pub const SQL_CU_PRIVILEGE_DEFINITION : u32 = 16 ;
pub const SQL_SQ_COMPARISON : u32 = 1 ;
pub const SQL_SQ_EXISTS : u32 = 2 ;
pub const SQL_SQ_IN : u32 = 4 ;
pub const SQL_SQ_QUANTIFIED : u32 = 8 ;
pub const SQL_SQ_CORRELATED_SUBQUERIES : u32 = 16 ;
pub const SQL_U_UNION : u32 = 1 ;
pub const SQL_U_UNION_ALL : u32 = 2 ;
pub const SQL_BP_CLOSE : u32 = 1 ;
pub const SQL_BP_DELETE : u32 = 2 ;
pub const SQL_BP_DROP : u32 = 4 ;
pub const SQL_BP_TRANSACTION : u32 = 8 ;
pub const SQL_BP_UPDATE : u32 = 16 ;
pub const SQL_BP_OTHER_HSTMT : u32 = 32 ;
pub const SQL_BP_SCROLL : u32 = 64 ;
pub const SQL_SS_ADDITIONS : u32 = 1 ;
pub const SQL_SS_DELETIONS : u32 = 2 ;
pub const SQL_SS_UPDATES : u32 = 4 ;
pub const SQL_CV_CREATE_VIEW : u32 = 1 ;
pub const SQL_CV_CHECK_OPTION : u32 = 2 ;
pub const SQL_CV_CASCADED : u32 = 4 ;
pub const SQL_CV_LOCAL : u32 = 8 ;
pub const SQL_LCK_NO_CHANGE : u32 = 1 ;
pub const SQL_LCK_EXCLUSIVE : u32 = 2 ;
pub const SQL_LCK_UNLOCK : u32 = 4 ;
pub const SQL_POS_POSITION : u32 = 1 ;
pub const SQL_POS_REFRESH : u32 = 2 ;
pub const SQL_POS_UPDATE : u32 = 4 ;
pub const SQL_POS_DELETE : u32 = 8 ;
pub const SQL_POS_ADD : u32 = 16 ;
pub const SQL_QL_START : u32 = 1 ;
pub const SQL_QL_END : u32 = 2 ;
pub const SQL_AF_AVG : u32 = 1 ;
pub const SQL_AF_COUNT : u32 = 2 ;
pub const SQL_AF_MAX : u32 = 4 ;
pub const SQL_AF_MIN : u32 = 8 ;
pub const SQL_AF_SUM : u32 = 16 ;
pub const SQL_AF_DISTINCT : u32 = 32 ;
pub const SQL_AF_ALL : u32 = 64 ;
pub const SQL_SC_SQL92_ENTRY : u32 = 1 ;
pub const SQL_SC_FIPS127_2_TRANSITIONAL : u32 = 2 ;
pub const SQL_SC_SQL92_INTERMEDIATE : u32 = 4 ;
pub const SQL_SC_SQL92_FULL : u32 = 8 ;
pub const SQL_DL_SQL92_DATE : u32 = 1 ;
pub const SQL_DL_SQL92_TIME : u32 = 2 ;
pub const SQL_DL_SQL92_TIMESTAMP : u32 = 4 ;
pub const SQL_DL_SQL92_INTERVAL_YEAR : u32 = 8 ;
pub const SQL_DL_SQL92_INTERVAL_MONTH : u32 = 16 ;
pub const SQL_DL_SQL92_INTERVAL_DAY : u32 = 32 ;
pub const SQL_DL_SQL92_INTERVAL_HOUR : u32 = 64 ;
pub const SQL_DL_SQL92_INTERVAL_MINUTE : u32 = 128 ;
pub const SQL_DL_SQL92_INTERVAL_SECOND : u32 = 256 ;
pub const SQL_DL_SQL92_INTERVAL_YEAR_TO_MONTH : u32 = 512 ;
pub const SQL_DL_SQL92_INTERVAL_DAY_TO_HOUR : u32 = 1024 ;
pub const SQL_DL_SQL92_INTERVAL_DAY_TO_MINUTE : u32 = 2048 ;
pub const SQL_DL_SQL92_INTERVAL_DAY_TO_SECOND : u32 = 4096 ;
pub const SQL_DL_SQL92_INTERVAL_HOUR_TO_MINUTE : u32 = 8192 ;
pub const SQL_DL_SQL92_INTERVAL_HOUR_TO_SECOND : u32 = 16384 ;
pub const SQL_DL_SQL92_INTERVAL_MINUTE_TO_SECOND : u32 = 32768 ;
pub const SQL_CL_START : u32 = 1 ;
pub const SQL_CL_END : u32 = 2 ;
pub const SQL_BRC_PROCEDURES : u32 = 1 ;
pub const SQL_BRC_EXPLICIT : u32 = 2 ;
pub const SQL_BRC_ROLLED_UP : u32 = 4 ;
pub const SQL_BS_SELECT_EXPLICIT : u32 = 1 ;
pub const SQL_BS_ROW_COUNT_EXPLICIT : u32 = 2 ;
pub const SQL_BS_SELECT_PROC : u32 = 4 ;
pub const SQL_BS_ROW_COUNT_PROC : u32 = 8 ;
pub const SQL_PARC_BATCH : u32 = 1 ;
pub const SQL_PARC_NO_BATCH : u32 = 2 ;
pub const SQL_PAS_BATCH : u32 = 1 ;
pub const SQL_PAS_NO_BATCH : u32 = 2 ;
pub const SQL_PAS_NO_SELECT : u32 = 3 ;
pub const SQL_IK_NONE : u32 = 0 ;
pub const SQL_IK_ASC : u32 = 1 ;
pub const SQL_IK_DESC : u32 = 2 ;
pub const SQL_IK_ALL : u32 = 3 ;
pub const SQL_ISV_ASSERTIONS : u32 = 1 ;
pub const SQL_ISV_CHARACTER_SETS : u32 = 2 ;
pub const SQL_ISV_CHECK_CONSTRAINTS : u32 = 4 ;
pub const SQL_ISV_COLLATIONS : u32 = 8 ;
pub const SQL_ISV_COLUMN_DOMAIN_USAGE : u32 = 16 ;
pub const SQL_ISV_COLUMN_PRIVILEGES : u32 = 32 ;
pub const SQL_ISV_COLUMNS : u32 = 64 ;
pub const SQL_ISV_CONSTRAINT_COLUMN_USAGE : u32 = 128 ;
pub const SQL_ISV_CONSTRAINT_TABLE_USAGE : u32 = 256 ;
pub const SQL_ISV_DOMAIN_CONSTRAINTS : u32 = 512 ;
pub const SQL_ISV_DOMAINS : u32 = 1024 ;
pub const SQL_ISV_KEY_COLUMN_USAGE : u32 = 2048 ;
pub const SQL_ISV_REFERENTIAL_CONSTRAINTS : u32 = 4096 ;
pub const SQL_ISV_SCHEMATA : u32 = 8192 ;
pub const SQL_ISV_SQL_LANGUAGES : u32 = 16384 ;
pub const SQL_ISV_TABLE_CONSTRAINTS : u32 = 32768 ;
pub const SQL_ISV_TABLE_PRIVILEGES : u32 = 65536 ;
pub const SQL_ISV_TABLES : u32 = 131072 ;
pub const SQL_ISV_TRANSLATIONS : u32 = 262144 ;
pub const SQL_ISV_USAGE_PRIVILEGES : u32 = 524288 ;
pub const SQL_ISV_VIEW_COLUMN_USAGE : u32 = 1048576 ;
pub const SQL_ISV_VIEW_TABLE_USAGE : u32 = 2097152 ;
pub const SQL_ISV_VIEWS : u32 = 4194304 ;
pub const SQL_AM_NONE : u32 = 0 ;
pub const SQL_AM_CONNECTION : u32 = 1 ;
pub const SQL_AM_STATEMENT : u32 = 2 ;
pub const SQL_AD_CONSTRAINT_NAME_DEFINITION : u32 = 1 ;
pub const SQL_AD_ADD_DOMAIN_CONSTRAINT : u32 = 2 ;
pub const SQL_AD_DROP_DOMAIN_CONSTRAINT : u32 = 4 ;
pub const SQL_AD_ADD_DOMAIN_DEFAULT : u32 = 8 ;
pub const SQL_AD_DROP_DOMAIN_DEFAULT : u32 = 16 ;
pub const SQL_AD_ADD_CONSTRAINT_INITIALLY_DEFERRED : u32 = 32 ;
pub const SQL_AD_ADD_CONSTRAINT_INITIALLY_IMMEDIATE : u32 = 64 ;
pub const SQL_AD_ADD_CONSTRAINT_DEFERRABLE : u32 = 128 ;
pub const SQL_AD_ADD_CONSTRAINT_NON_DEFERRABLE : u32 = 256 ;
pub const SQL_CS_CREATE_SCHEMA : u32 = 1 ;
pub const SQL_CS_AUTHORIZATION : u32 = 2 ;
pub const SQL_CS_DEFAULT_CHARACTER_SET : u32 = 4 ;
pub const SQL_CTR_CREATE_TRANSLATION : u32 = 1 ;
pub const SQL_CA_CREATE_ASSERTION : u32 = 1 ;
pub const SQL_CA_CONSTRAINT_INITIALLY_DEFERRED : u32 = 16 ;
pub const SQL_CA_CONSTRAINT_INITIALLY_IMMEDIATE : u32 = 32 ;
pub const SQL_CA_CONSTRAINT_DEFERRABLE : u32 = 64 ;
pub const SQL_CA_CONSTRAINT_NON_DEFERRABLE : u32 = 128 ;
pub const SQL_CCS_CREATE_CHARACTER_SET : u32 = 1 ;
pub const SQL_CCS_COLLATE_CLAUSE : u32 = 2 ;
pub const SQL_CCS_LIMITED_COLLATION : u32 = 4 ;
pub const SQL_CCOL_CREATE_COLLATION : u32 = 1 ;
pub const SQL_CDO_CREATE_DOMAIN : u32 = 1 ;
pub const SQL_CDO_DEFAULT : u32 = 2 ;
pub const SQL_CDO_CONSTRAINT : u32 = 4 ;
pub const SQL_CDO_COLLATION : u32 = 8 ;
pub const SQL_CDO_CONSTRAINT_NAME_DEFINITION : u32 = 16 ;
pub const SQL_CDO_CONSTRAINT_INITIALLY_DEFERRED : u32 = 32 ;
pub const SQL_CDO_CONSTRAINT_INITIALLY_IMMEDIATE : u32 = 64 ;
pub const SQL_CDO_CONSTRAINT_DEFERRABLE : u32 = 128 ;
pub const SQL_CDO_CONSTRAINT_NON_DEFERRABLE : u32 = 256 ;
pub const SQL_CT_CREATE_TABLE : u32 = 1 ;
pub const SQL_CT_COMMIT_PRESERVE : u32 = 2 ;
pub const SQL_CT_COMMIT_DELETE : u32 = 4 ;
pub const SQL_CT_GLOBAL_TEMPORARY : u32 = 8 ;
pub const SQL_CT_LOCAL_TEMPORARY : u32 = 16 ;
pub const SQL_CT_CONSTRAINT_INITIALLY_DEFERRED : u32 = 32 ;
pub const SQL_CT_CONSTRAINT_INITIALLY_IMMEDIATE : u32 = 64 ;
pub const SQL_CT_CONSTRAINT_DEFERRABLE : u32 = 128 ;
pub const SQL_CT_CONSTRAINT_NON_DEFERRABLE : u32 = 256 ;
pub const SQL_CT_COLUMN_CONSTRAINT : u32 = 512 ;
pub const SQL_CT_COLUMN_DEFAULT : u32 = 1024 ;
pub const SQL_CT_COLUMN_COLLATION : u32 = 2048 ;
pub const SQL_CT_TABLE_CONSTRAINT : u32 = 4096 ;
pub const SQL_CT_CONSTRAINT_NAME_DEFINITION : u32 = 8192 ;
pub const SQL_DI_CREATE_INDEX : u32 = 1 ;
pub const SQL_DI_DROP_INDEX : u32 = 2 ;
pub const SQL_DC_DROP_COLLATION : u32 = 1 ;
pub const SQL_DD_DROP_DOMAIN : u32 = 1 ;
pub const SQL_DD_RESTRICT : u32 = 2 ;
pub const SQL_DD_CASCADE : u32 = 4 ;
pub const SQL_DS_DROP_SCHEMA : u32 = 1 ;
pub const SQL_DS_RESTRICT : u32 = 2 ;
pub const SQL_DS_CASCADE : u32 = 4 ;
pub const SQL_DCS_DROP_CHARACTER_SET : u32 = 1 ;
pub const SQL_DA_DROP_ASSERTION : u32 = 1 ;
pub const SQL_DT_DROP_TABLE : u32 = 1 ;
pub const SQL_DT_RESTRICT : u32 = 2 ;
pub const SQL_DT_CASCADE : u32 = 4 ;
pub const SQL_DTR_DROP_TRANSLATION : u32 = 1 ;
pub const SQL_DV_DROP_VIEW : u32 = 1 ;
pub const SQL_DV_RESTRICT : u32 = 2 ;
pub const SQL_DV_CASCADE : u32 = 4 ;
pub const SQL_IS_INSERT_LITERALS : u32 = 1 ;
pub const SQL_IS_INSERT_SEARCHED : u32 = 2 ;
pub const SQL_IS_SELECT_INTO : u32 = 4 ;
pub const SQL_OIC_CORE : u32 = 1 ;
pub const SQL_OIC_LEVEL1 : u32 = 2 ;
pub const SQL_OIC_LEVEL2 : u32 = 3 ;
pub const SQL_SFKD_CASCADE : u32 = 1 ;
pub const SQL_SFKD_NO_ACTION : u32 = 2 ;
pub const SQL_SFKD_SET_DEFAULT : u32 = 4 ;
pub const SQL_SFKD_SET_NULL : u32 = 8 ;
pub const SQL_SFKU_CASCADE : u32 = 1 ;
pub const SQL_SFKU_NO_ACTION : u32 = 2 ;
pub const SQL_SFKU_SET_DEFAULT : u32 = 4 ;
pub const SQL_SFKU_SET_NULL : u32 = 8 ;
pub const SQL_SG_USAGE_ON_DOMAIN : u32 = 1 ;
pub const SQL_SG_USAGE_ON_CHARACTER_SET : u32 = 2 ;
pub const SQL_SG_USAGE_ON_COLLATION : u32 = 4 ;
pub const SQL_SG_USAGE_ON_TRANSLATION : u32 = 8 ;
pub const SQL_SG_WITH_GRANT_OPTION : u32 = 16 ;
pub const SQL_SG_DELETE_TABLE : u32 = 32 ;
pub const SQL_SG_INSERT_TABLE : u32 = 64 ;
pub const SQL_SG_INSERT_COLUMN : u32 = 128 ;
pub const SQL_SG_REFERENCES_TABLE : u32 = 256 ;
pub const SQL_SG_REFERENCES_COLUMN : u32 = 512 ;
pub const SQL_SG_SELECT_TABLE : u32 = 1024 ;
pub const SQL_SG_UPDATE_TABLE : u32 = 2048 ;
pub const SQL_SG_UPDATE_COLUMN : u32 = 4096 ;
pub const SQL_SP_EXISTS : u32 = 1 ;
pub const SQL_SP_ISNOTNULL : u32 = 2 ;
pub const SQL_SP_ISNULL : u32 = 4 ;
pub const SQL_SP_MATCH_FULL : u32 = 8 ;
pub const SQL_SP_MATCH_PARTIAL : u32 = 16 ;
pub const SQL_SP_MATCH_UNIQUE_FULL : u32 = 32 ;
pub const SQL_SP_MATCH_UNIQUE_PARTIAL : u32 = 64 ;
pub const SQL_SP_OVERLAPS : u32 = 128 ;
pub const SQL_SP_UNIQUE : u32 = 256 ;
pub const SQL_SP_LIKE : u32 = 512 ;
pub const SQL_SP_IN : u32 = 1024 ;
pub const SQL_SP_BETWEEN : u32 = 2048 ;
pub const SQL_SP_COMPARISON : u32 = 4096 ;
pub const SQL_SP_QUANTIFIED_COMPARISON : u32 = 8192 ;
pub const SQL_SRJO_CORRESPONDING_CLAUSE : u32 = 1 ;
pub const SQL_SRJO_CROSS_JOIN : u32 = 2 ;
pub const SQL_SRJO_EXCEPT_JOIN : u32 = 4 ;
pub const SQL_SRJO_FULL_OUTER_JOIN : u32 = 8 ;
pub const SQL_SRJO_INNER_JOIN : u32 = 16 ;
pub const SQL_SRJO_INTERSECT_JOIN : u32 = 32 ;
pub const SQL_SRJO_LEFT_OUTER_JOIN : u32 = 64 ;
pub const SQL_SRJO_NATURAL_JOIN : u32 = 128 ;
pub const SQL_SRJO_RIGHT_OUTER_JOIN : u32 = 256 ;
pub const SQL_SRJO_UNION_JOIN : u32 = 512 ;
pub const SQL_SR_USAGE_ON_DOMAIN : u32 = 1 ;
pub const SQL_SR_USAGE_ON_CHARACTER_SET : u32 = 2 ;
pub const SQL_SR_USAGE_ON_COLLATION : u32 = 4 ;
pub const SQL_SR_USAGE_ON_TRANSLATION : u32 = 8 ;
pub const SQL_SR_GRANT_OPTION_FOR : u32 = 16 ;
pub const SQL_SR_CASCADE : u32 = 32 ;
pub const SQL_SR_RESTRICT : u32 = 64 ;
pub const SQL_SR_DELETE_TABLE : u32 = 128 ;
pub const SQL_SR_INSERT_TABLE : u32 = 256 ;
pub const SQL_SR_INSERT_COLUMN : u32 = 512 ;
pub const SQL_SR_REFERENCES_TABLE : u32 = 1024 ;
pub const SQL_SR_REFERENCES_COLUMN : u32 = 2048 ;
pub const SQL_SR_SELECT_TABLE : u32 = 4096 ;
pub const SQL_SR_UPDATE_TABLE : u32 = 8192 ;
pub const SQL_SR_UPDATE_COLUMN : u32 = 16384 ;
pub const SQL_SRVC_VALUE_EXPRESSION : u32 = 1 ;
pub const SQL_SRVC_NULL : u32 = 2 ;
pub const SQL_SRVC_DEFAULT : u32 = 4 ;
pub const SQL_SRVC_ROW_SUBQUERY : u32 = 8 ;
pub const SQL_SVE_CASE : u32 = 1 ;
pub const SQL_SVE_CAST : u32 = 2 ;
pub const SQL_SVE_COALESCE : u32 = 4 ;
pub const SQL_SVE_NULLIF : u32 = 8 ;
pub const SQL_SCC_XOPEN_CLI_VERSION1 : u32 = 1 ;
pub const SQL_SCC_ISO92_CLI : u32 = 2 ;
pub const SQL_US_UNION : u32 = 1 ;
pub const SQL_US_UNION_ALL : u32 = 2 ;
pub const SQL_DTC_ENLIST_EXPENSIVE : u32 = 1 ;
pub const SQL_DTC_UNENLIST_EXPENSIVE : u32 = 2 ;
pub const SQL_ASYNC_DBC_NOT_CAPABLE : u32 = 0 ;
pub const SQL_ASYNC_DBC_CAPABLE : u32 = 1 ;
pub const SQL_FETCH_FIRST_USER : u32 = 31 ;
pub const SQL_FETCH_FIRST_SYSTEM : u32 = 32 ;
pub const SQL_ENTIRE_ROWSET : u32 = 0 ;
pub const SQL_POSITION : u32 = 0 ;
pub const SQL_REFRESH : u32 = 1 ;
pub const SQL_UPDATE : u32 = 2 ;
pub const SQL_DELETE : u32 = 3 ;
pub const SQL_ADD : u32 = 4 ;
pub const SQL_SETPOS_MAX_OPTION_VALUE : u32 = 4 ;
pub const SQL_UPDATE_BY_BOOKMARK : u32 = 5 ;
pub const SQL_DELETE_BY_BOOKMARK : u32 = 6 ;
pub const SQL_FETCH_BY_BOOKMARK : u32 = 7 ;
pub const SQL_LOCK_NO_CHANGE : u32 = 0 ;
pub const SQL_LOCK_EXCLUSIVE : u32 = 1 ;
pub const SQL_LOCK_UNLOCK : u32 = 2 ;
pub const SQL_SETPOS_MAX_LOCK_VALUE : u32 = 2 ;
pub const SQL_BEST_ROWID : u32 = 1 ;
pub const SQL_ROWVER : u32 = 2 ;
pub const SQL_PC_NOT_PSEUDO : u32 = 1 ;
pub const SQL_QUICK : u32 = 0 ;
pub const SQL_ENSURE : u32 = 1 ;
pub const SQL_TABLE_STAT : u32 = 0 ;
pub const SQL_ALL_CATALOGS : & 'static [u8 ;
2usize] = b"%\0" ;
pub const SQL_ALL_SCHEMAS : & 'static [u8 ;
2usize] = b"%\0" ;
pub const SQL_ALL_TABLE_TYPES : & 'static [u8 ;
2usize] = b"%\0" ;
pub const SQL_DRIVER_NOPROMPT : u32 = 0 ;
pub const SQL_DRIVER_COMPLETE : u32 = 1 ;
pub const SQL_DRIVER_PROMPT : u32 = 2 ;
pub const SQL_DRIVER_COMPLETE_REQUIRED : u32 = 3 ;
pub const SQL_FETCH_BOOKMARK : u32 = 8 ;
pub const SQL_ROW_SUCCESS : u32 = 0 ;
pub const SQL_ROW_DELETED : u32 = 1 ;
pub const SQL_ROW_UPDATED : u32 = 2 ;
pub const SQL_ROW_NOROW : u32 = 3 ;
pub const SQL_ROW_ADDED : u32 = 4 ;
pub const SQL_ROW_ERROR : u32 = 5 ;
pub const SQL_ROW_SUCCESS_WITH_INFO : u32 = 6 ;
pub const SQL_ROW_PROCEED : u32 = 0 ;
pub const SQL_ROW_IGNORE : u32 = 1 ;
pub const SQL_PARAM_SUCCESS : u32 = 0 ;
pub const SQL_PARAM_SUCCESS_WITH_INFO : u32 = 6 ;
pub const SQL_PARAM_ERROR : u32 = 5 ;
pub const SQL_PARAM_UNUSED : u32 = 7 ;
pub const SQL_PARAM_DIAG_UNAVAILABLE : u32 = 1 ;
pub const SQL_PARAM_PROCEED : u32 = 0 ;
pub const SQL_PARAM_IGNORE : u32 = 1 ;
pub const SQL_CASCADE : u32 = 0 ;
pub const SQL_RESTRICT : u32 = 1 ;
pub const SQL_SET_NULL : u32 = 2 ;
pub const SQL_NO_ACTION : u32 = 3 ;
pub const SQL_SET_DEFAULT : u32 = 4 ;
pub const SQL_INITIALLY_DEFERRED : u32 = 5 ;
pub const SQL_INITIALLY_IMMEDIATE : u32 = 6 ;
pub const SQL_NOT_DEFERRABLE : u32 = 7 ;
pub const SQL_PARAM_TYPE_UNKNOWN : u32 = 0 ;
pub const SQL_PARAM_INPUT : u32 = 1 ;
pub const SQL_PARAM_INPUT_OUTPUT : u32 = 2 ;
pub const SQL_RESULT_COL : u32 = 3 ;
pub const SQL_PARAM_OUTPUT : u32 = 4 ;
pub const SQL_RETURN_VALUE : u32 = 5 ;
pub const SQL_PARAM_INPUT_OUTPUT_STREAM : u32 = 8 ;
pub const SQL_PARAM_OUTPUT_STREAM : u32 = 16 ;
pub const SQL_PT_UNKNOWN : u32 = 0 ;
pub const SQL_PT_PROCEDURE : u32 = 1 ;
pub const SQL_PT_FUNCTION : u32 = 2 ;
pub const SQL_DATABASE_NAME : u32 = 16 ;
pub const SQL_CONCUR_TIMESTAMP : u32 = 3 ;
pub const SQL_SCROLL_FORWARD_ONLY : u32 = 0 ;
pub const SQL_SCROLL_KEYSET_DRIVEN : i32 = - 1 ;
pub const SQL_SCROLL_DYNAMIC : i32 = - 2 ;
pub const SQL_SCROLL_STATIC : i32 = - 3 ;
pub const TRACE_VERSION : u32 = 1000 ;
pub const TRACE_ON : u32 = 1 ;
pub const TRACE_VS_EVENT_ON : u32 = 2 ;
pub const ODBC_VS_FLAG_UNICODE_ARG : u32 = 1 ;
pub const ODBC_VS_FLAG_UNICODE_COR : u32 = 2 ;
pub const ODBC_VS_FLAG_RETCODE : u32 = 4 ;
pub const ODBC_VS_FLAG_STOP : u32 = 8 ;
pub const SQL_API_SQLALLOCCONNECT : u32 = 1 ;
pub const SQL_API_SQLALLOCENV : u32 = 2 ;
pub const SQL_API_SQLALLOCSTMT : u32 = 3 ;
pub const SQL_API_SQLBINDCOL : u32 = 4 ;
pub const SQL_API_SQLBINDPARAM : u32 = 1002 ;
pub const SQL_API_SQLCANCEL : u32 = 5 ;
pub const SQL_API_SQLCONNECT : u32 = 7 ;
pub const SQL_API_SQLCOPYDESC : u32 = 1004 ;
pub const SQL_API_SQLDESCRIBECOL : u32 = 8 ;
pub const SQL_API_SQLDISCONNECT : u32 = 9 ;
pub const SQL_API_SQLERROR : u32 = 10 ;
pub const SQL_API_SQLEXECDIRECT : u32 = 11 ;
pub const SQL_API_SQLEXECUTE : u32 = 12 ;
pub const SQL_API_SQLFETCH : u32 = 13 ;
pub const SQL_API_SQLFREECONNECT : u32 = 14 ;
pub const SQL_API_SQLFREEENV : u32 = 15 ;
pub const SQL_API_SQLFREESTMT : u32 = 16 ;
pub const SQL_API_SQLGETCURSORNAME : u32 = 17 ;
pub const SQL_API_SQLNUMRESULTCOLS : u32 = 18 ;
pub const SQL_API_SQLPREPARE : u32 = 19 ;
pub const SQL_API_SQLROWCOUNT : u32 = 20 ;
pub const SQL_API_SQLSETCURSORNAME : u32 = 21 ;
pub const SQL_API_SQLSETDESCFIELD : u32 = 1017 ;
pub const SQL_API_SQLSETDESCREC : u32 = 1018 ;
pub const SQL_API_SQLSETENVATTR : u32 = 1019 ;
pub const SQL_API_SQLSETPARAM : u32 = 22 ;
pub const SQL_API_SQLTRANSACT : u32 = 23 ;
pub const SQL_API_SQLCOLUMNS : u32 = 40 ;
pub const SQL_API_SQLGETCONNECTOPTION : u32 = 42 ;
pub const SQL_API_SQLGETDATA : u32 = 43 ;
pub const SQL_API_SQLGETDATAINTERNAL : u32 = 174 ;
pub const SQL_API_SQLGETDESCFIELD : u32 = 1008 ;
pub const SQL_API_SQLGETDESCREC : u32 = 1009 ;
pub const SQL_API_SQLGETDIAGFIELD : u32 = 1010 ;
pub const SQL_API_SQLGETDIAGREC : u32 = 1011 ;
pub const SQL_API_SQLGETENVATTR : u32 = 1012 ;
pub const SQL_API_SQLGETFUNCTIONS : u32 = 44 ;
pub const SQL_API_SQLGETINFO : u32 = 45 ;
pub const SQL_API_SQLGETSTMTOPTION : u32 = 46 ;
pub const SQL_API_SQLGETTYPEINFO : u32 = 47 ;
pub const SQL_API_SQLPARAMDATA : u32 = 48 ;
pub const SQL_API_SQLPUTDATA : u32 = 49 ;
pub const SQL_API_SQLSETCONNECTOPTION : u32 = 50 ;
pub const SQL_API_SQLSETSTMTOPTION : u32 = 51 ;
pub const SQL_API_SQLSPECIALCOLUMNS : u32 = 52 ;
pub const SQL_API_SQLSTATISTICS : u32 = 53 ;
pub const SQL_API_SQLTABLES : u32 = 54 ;
pub const SQL_API_SQLDATASOURCES : u32 = 57 ;
pub const SQL_API_SQLSETCONNECTATTR : u32 = 1016 ;
pub const SQL_API_SQLSETSTMTATTR : u32 = 1020 ;
pub const SQL_API_SQLBINDFILETOCOL : u32 = 1250 ;
pub const SQL_API_SQLBINDFILETOPARAM : u32 = 1251 ;
pub const SQL_API_SQLSETCOLATTRIBUTES : u32 = 1252 ;
pub const SQL_API_SQLGETSQLCA : u32 = 1253 ;
pub const SQL_API_SQLSETCONNECTION : u32 = 1254 ;
pub const SQL_API_SQLGETDATALINKATTR : u32 = 1255 ;
pub const SQL_API_SQLBUILDDATALINK : u32 = 1256 ;
pub const SQL_API_SQLNEXTRESULT : u32 = 1257 ;
pub const SQL_API_SQLCREATEDB : u32 = 1258 ;
pub const SQL_API_SQLDROPDB : u32 = 1259 ;
pub const SQL_API_SQLCREATEPKG : u32 = 1260 ;
pub const SQL_API_SQLDROPPKG : u32 = 1261 ;
pub const SQL_API_SQLEXTENDEDPREPARE : u32 = 1296 ;
pub const SQL_API_SQLEXTENDEDBIND : u32 = 1297 ;
pub const SQL_API_SQLEXTENDEDDESCRIBE : u32 = 1298 ;
pub const SQL_API_SQLRELOADCONFIG : u32 = 1299 ;
pub const SQL_API_SQLFETCHSCROLL : u32 = 1021 ;
pub const SQL_API_SQLGETLENGTH : u32 = 1022 ;
pub const SQL_API_SQLGETPOSITION : u32 = 1023 ;
pub const SQL_API_SQLGETSUBSTRING : u32 = 1024 ;
pub const SQL_API_SQLEXTENDEDPROCEDURES : u32 = 1025 ;
pub const SQL_API_SQLEXTENDEDPROCEDURECOLUMNS : u32 = 1026 ;
pub const SQL_API_SQLALLOCHANDLE : u32 = 1001 ;
pub const SQL_API_SQLFREEHANDLE : u32 = 1006 ;
pub const SQL_API_SQLCLOSECURSOR : u32 = 1003 ;
pub const SQL_API_SQLENDTRAN : u32 = 1005 ;
pub const SQL_API_SQLCOLATTRIBUTE : u32 = 6 ;
pub const SQL_API_SQLGETSTMTATTR : u32 = 1014 ;
pub const SQL_API_SQLGETCONNECTATTR : u32 = 1007 ;
pub const SQL_EXT_API_LAST : u32 = 72 ;
pub const SQL_MAX_DRIVER_CONNECTIONS : u32 = 0 ;
pub const SQL_MAXIMUM_DRIVER_CONNECTIONS : u32 = 0 ;
pub const SQL_MAX_CONCURRENT_ACTIVITIES : u32 = 1 ;
pub const SQL_MAXIMUM_CONCURRENT_ACTIVITIES : u32 = 1 ;
pub const SQL_DROP_MODULE : u32 = 2600 ;
pub const SQL_MODULE_USAGE : u32 = 2601 ;
pub const SQL_CREATE_MODULE : u32 = 2602 ;
pub const SQL_MAX_MODULE_NAME_LEN : u32 = 2603 ;
pub const SQL_DRIVER_BLDLEVEL : u32 = 2604 ;
pub const SQL_DATALINK_URL : & 'static [u8 ;
4usize] = b"URL\0" ;
pub const SQL_ATTR_DATALINK_COMMENT : u32 = 1 ;
pub const SQL_ATTR_DATALINK_LINKTYPE : u32 = 2 ;
pub const SQL_ATTR_DATALINK_URLCOMPLETE : u32 = 3 ;
pub const SQL_ATTR_DATALINK_URLPATH : u32 = 4 ;
pub const SQL_ATTR_DATALINK_URLPATHONLY : u32 = 5 ;
pub const SQL_ATTR_DATALINK_URLSCHEME : u32 = 6 ;
pub const SQL_ATTR_DATALINK_URLSERVER : u32 = 7 ;
pub const SQL_DATA_SOURCE_NAME : u32 = 2 ;
pub const SQL_FETCH_DIRECTION : u32 = 8 ;
pub const SQL_SERVER_NAME : u32 = 13 ;
pub const SQL_SEARCH_PATTERN_ESCAPE : u32 = 14 ;
pub const SQL_DBMS_NAME : u32 = 17 ;
pub const SQL_DBMS_VER : u32 = 18 ;
pub const SQL_ACCESSIBLE_TABLES : u32 = 19 ;
pub const SQL_ACCESSIBLE_PROCEDURES : u32 = 20 ;
pub const SQL_CURSOR_COMMIT_BEHAVIOR : u32 = 23 ;
pub const SQL_DATA_SOURCE_READ_ONLY : u32 = 25 ;
pub const SQL_DEFAULT_TXN_ISOLATION : u32 = 26 ;
pub const SQL_IDENTIFIER_CASE : u32 = 28 ;
pub const SQL_IDENTIFIER_QUOTE_CHAR : u32 = 29 ;
pub const SQL_MAX_COLUMN_NAME_LEN : u32 = 30 ;
pub const SQL_MAXIMUM_COLUMN_NAME_LENGTH : u32 = 30 ;
pub const SQL_MAX_CURSOR_NAME_LEN : u32 = 31 ;
pub const SQL_MAXIMUM_CURSOR_NAME_LENGTH : u32 = 31 ;
pub const SQL_MAX_TABLE_NAME_LEN : u32 = 35 ;
pub const SQL_SCROLL_CONCURRENCY : u32 = 43 ;
pub const SQL_TXN_CAPABLE : u32 = 46 ;
pub const SQL_TRANSACTION_CAPABLE : u32 = 46 ;
pub const SQL_USER_NAME : u32 = 47 ;
pub const SQL_TXN_ISOLATION_OPTION : u32 = 72 ;
pub const SQL_TRANSACTION_ISOLATION_OPTION : u32 = 72 ;
pub const SQL_GETDATA_EXTENSIONS : u32 = 81 ;
pub const SQL_NULL_COLLATION : u32 = 85 ;
pub const SQL_ALTER_TABLE : u32 = 86 ;
pub const SQL_ORDER_BY_COLUMNS_IN_SELECT : u32 = 90 ;
pub const SQL_SPECIAL_CHARACTERS : u32 = 94 ;
pub const SQL_MAX_COLUMNS_IN_GROUP_BY : u32 = 97 ;
pub const SQL_MAXIMUM_COLUMNS_IN_GROUP_BY : u32 = 97 ;
pub const SQL_MAX_COLUMNS_IN_INDEX : u32 = 98 ;
pub const SQL_MAXIMUM_COLUMNS_IN_INDEX : u32 = 98 ;
pub const SQL_MAX_COLUMNS_IN_ORDER_BY : u32 = 99 ;
pub const SQL_MAXIMUM_COLUMNS_IN_ORDER_BY : u32 = 99 ;
pub const SQL_MAX_COLUMNS_IN_SELECT : u32 = 100 ;
pub const SQL_MAXIMUM_COLUMNS_IN_SELECT : u32 = 100 ;
pub const SQL_MAX_COLUMNS_IN_TABLE : u32 = 101 ;
pub const SQL_MAX_INDEX_SIZE : u32 = 102 ;
pub const SQL_MAXIMUM_INDEX_SIZE : u32 = 102 ;
pub const SQL_MAX_ROW_SIZE : u32 = 104 ;
pub const SQL_MAXIMUM_ROW_SIZE : u32 = 104 ;
pub const SQL_MAX_STATEMENT_LEN : u32 = 105 ;
pub const SQL_MAXIMUM_STATEMENT_LENGTH : u32 = 105 ;
pub const SQL_MAX_TABLES_IN_SELECT : u32 = 106 ;
pub const SQL_MAXIMUM_TABLES_IN_SELECT : u32 = 106 ;
pub const SQL_MAX_USER_NAME_LEN : u32 = 107 ;
pub const SQL_MAXIMUM_USER_NAME_LENGTH : u32 = 107 ;
pub const SQL_MAX_SCHEMA_NAME_LEN : u32 = 32 ;
pub const SQL_MAXIMUM_SCHEMA_NAME_LENGTH : u32 = 32 ;
pub const SQL_MAX_CATALOG_NAME_LEN : u32 = 34 ;
pub const SQL_MAXIMUM_CATALOG_NAME_LENGTH : u32 = 34 ;
pub const SQL_OJ_CAPABILITIES : u32 = 115 ;
pub const SQL_CONFIG_KEYWORDS : u32 = 174 ;
pub const SQL_OUTER_JOIN_CAPABILITIES : u32 = 115 ;
pub const SQL_XOPEN_CLI_YEAR : u32 = 10000 ;
pub const SQL_CURSOR_SENSITIVITY : u32 = 10001 ;
pub const SQL_DESCRIBE_PARAMETER : u32 = 10002 ;
pub const SQL_CATALOG_NAME : u32 = 10003 ;
pub const SQL_COLLATION_SEQ : u32 = 10004 ;
pub const SQL_MAX_IDENTIFIER_LEN : u32 = 10005 ;
pub const SQL_MAXIMUM_IDENTIFIER_LENGTH : u32 = 10005 ;
pub const SQL_INTEGRITY : u32 = 73 ;
pub const SQL_DATABASE_CODEPAGE : u32 = 2519 ;
pub const SQL_APPLICATION_CODEPAGE : u32 = 2520 ;
pub const SQL_CONNECT_CODEPAGE : u32 = 2521 ;
pub const SQL_ATTR_DB2_APPLICATION_ID : u32 = 2532 ;
pub const SQL_ATTR_DB2_APPLICATION_HANDLE : u32 = 2533 ;
pub const SQL_ATTR_HANDLE_XA_ASSOCIATED : u32 = 2535 ;
pub const SQL_DB2_DRIVER_VER : u32 = 2550 ;
pub const SQL_ATTR_XML_DECLARATION : u32 = 2552 ;
pub const SQL_ATTR_CURRENT_IMPLICIT_XMLPARSE_OPTION : u32 = 2553 ;
pub const SQL_ATTR_XQUERY_STATEMENT : u32 = 2557 ;
pub const SQL_DB2_DRIVER_TYPE : u32 = 2567 ;
pub const SQL_INPUT_CHAR_CONVFACTOR : u32 = 2581 ;
pub const SQL_OUTPUT_CHAR_CONVFACTOR : u32 = 2582 ;
pub const SQL_ATTR_REPLACE_QUOTED_LITERALS : u32 = 2586 ;
pub const SQL_ATTR_REPORT_TIMESTAMP_TRUNC_AS_WARN : u32 = 2587 ;
pub const SQL_ATTR_CLIENT_ENCALG : u32 = 2589 ;
pub const SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION : u32 = 2595 ;
pub const SQL_ATTR_REPORT_SEAMLESSFAILOVER_WARNING : u32 = 2605 ;
pub const SQL_CONCURRENT_ACCESS_RESOLUTION_UNSET : u32 = 0 ;
pub const SQL_USE_CURRENTLY_COMMITTED : u32 = 1 ;
pub const SQL_WAIT_FOR_OUTCOME : u32 = 2 ;
pub const SQL_SKIP_LOCKED_DATA : u32 = 3 ;
pub const SQL_DBMS_FUNCTIONLVL : u32 = 203 ;
pub const SQL_CLI_STMT_UNDEFINED : u32 = 0 ;
pub const SQL_CLI_STMT_ALTER_TABLE : u32 = 1 ;
pub const SQL_CLI_STMT_CREATE_INDEX : u32 = 5 ;
pub const SQL_CLI_STMT_CREATE_TABLE : u32 = 6 ;
pub const SQL_CLI_STMT_CREATE_VIEW : u32 = 7 ;
pub const SQL_CLI_STMT_DELETE_SEARCHED : u32 = 8 ;
pub const SQL_CLI_STMT_DELETE_POSITIONED : u32 = 9 ;
pub const SQL_CLI_STMT_DROP_PACKAGE : u32 = 10 ;
pub const SQL_CLI_STMT_DROP_INDEX : u32 = 11 ;
pub const SQL_CLI_STMT_DROP_TABLE : u32 = 12 ;
pub const SQL_CLI_STMT_DROP_VIEW : u32 = 13 ;
pub const SQL_CLI_STMT_GRANT : u32 = 14 ;
pub const SQL_CLI_STMT_INSERT : u32 = 15 ;
pub const SQL_CLI_STMT_REVOKE : u32 = 16 ;
pub const SQL_CLI_STMT_SELECT : u32 = 18 ;
pub const SQL_CLI_STMT_UPDATE_SEARCHED : u32 = 19 ;
pub const SQL_CLI_STMT_UPDATE_POSITIONED : u32 = 20 ;
pub const SQL_CLI_STMT_CALL : u32 = 24 ;
pub const SQL_CLI_STMT_SELECT_FOR_UPDATE : u32 = 29 ;
pub const SQL_CLI_STMT_WITH : u32 = 30 ;
pub const SQL_CLI_STMT_SELECT_FOR_FETCH : u32 = 31 ;
pub const SQL_CLI_STMT_VALUES : u32 = 32 ;
pub const SQL_CLI_STMT_CREATE_TRIGGER : u32 = 34 ;
pub const SQL_CLI_STMT_SELECT_OPTIMIZE_FOR_NROWS : u32 = 39 ;
pub const SQL_CLI_STMT_SELECT_INTO : u32 = 40 ;
pub const SQL_CLI_STMT_CREATE_PROCEDURE : u32 = 41 ;
pub const SQL_CLI_STMT_CREATE_FUNCTION : u32 = 42 ;
pub const SQL_CLI_STMT_INSERT_VALUES : u32 = 45 ;
pub const SQL_CLI_STMT_SET_CURRENT_QUERY_OPT : u32 = 46 ;
pub const SQL_CLI_STMT_MERGE : u32 = 56 ;
pub const SQL_CLI_STMT_XQUERY : u32 = 59 ;
pub const SQL_CLI_STMT_SET : u32 = 62 ;
pub const SQL_CLI_STMT_ALTER_PROCEDURE : u32 = 63 ;
pub const SQL_CLI_STMT_CLOSE_DATABASE : u32 = 64 ;
pub const SQL_CLI_STMT_CREATE_DATABASE : u32 = 65 ;
pub const SQL_CLI_STMT_DROP_DATABASE : u32 = 66 ;
pub const SQL_CLI_STMT_ANONYMOUS_BLOCK : u32 = 72 ;
pub const SQL_IBM_ALTERTABLEVARCHAR : u32 = 1000 ;
pub const SQL_AT_ADD_COLUMN : u32 = 1 ;
pub const SQL_AT_DROP_COLUMN : u32 = 2 ;
pub const SQL_AT_ADD_CONSTRAINT : u32 = 8 ;
pub const SQL_CB_DELETE : u32 = 0 ;
pub const SQL_CB_CLOSE : u32 = 1 ;
pub const SQL_CB_PRESERVE : u32 = 2 ;
pub const SQL_IC_UPPER : u32 = 1 ;
pub const SQL_IC_LOWER : u32 = 2 ;
pub const SQL_IC_SENSITIVE : u32 = 3 ;
pub const SQL_IC_MIXED : u32 = 4 ;
pub const SQL_TC_NONE : u32 = 0 ;
pub const SQL_TC_DML : u32 = 1 ;
pub const SQL_TC_ALL : u32 = 2 ;
pub const SQL_TC_DDL_COMMIT : u32 = 3 ;
pub const SQL_TC_DDL_IGNORE : u32 = 4 ;
pub const SQL_SCCO_READ_ONLY : u32 = 1 ;
pub const SQL_SCCO_LOCK : u32 = 2 ;
pub const SQL_SCCO_OPT_ROWVER : u32 = 4 ;
pub const SQL_SCCO_OPT_VALUES : u32 = 8 ;
pub const SQL_FD_FETCH_NEXT : u32 = 1 ;
pub const SQL_FD_FETCH_FIRST : u32 = 2 ;
pub const SQL_FD_FETCH_LAST : u32 = 4 ;
pub const SQL_FD_FETCH_PRIOR : u32 = 8 ;
pub const SQL_FD_FETCH_ABSOLUTE : u32 = 16 ;
pub const SQL_FD_FETCH_RELATIVE : u32 = 32 ;
pub const SQL_FD_FETCH_RESUME : u32 = 64 ;
pub const SQL_TXN_READ_UNCOMMITTED : u32 = 1 ;
pub const SQL_TRANSACTION_READ_UNCOMMITTED : u32 = 1 ;
pub const SQL_TXN_READ_COMMITTED : u32 = 2 ;
pub const SQL_TRANSACTION_READ_COMMITTED : u32 = 2 ;
pub const SQL_TXN_REPEATABLE_READ : u32 = 4 ;
pub const SQL_TRANSACTION_REPEATABLE_READ : u32 = 4 ;
pub const SQL_TXN_SERIALIZABLE : u32 = 8 ;
pub const SQL_TRANSACTION_SERIALIZABLE : u32 = 8 ;
pub const SQL_TXN_NOCOMMIT : u32 = 32 ;
pub const SQL_TRANSACTION_NOCOMMIT : u32 = 32 ;
pub const SQL_TXN_IDS_CURSOR_STABILITY : u32 = 64 ;
pub const SQL_TRANSACTION_IDS_CURSOR_STABILITY : u32 = 64 ;
pub const SQL_TXN_IDS_LAST_COMMITTED : u32 = 128 ;
pub const SQL_TRANSACTION_IDS_LAST_COMMITTED : u32 = 128 ;
pub const SQL_GD_ANY_COLUMN : u32 = 1 ;
pub const SQL_GD_ANY_ORDER : u32 = 2 ;
pub const SQL_OJ_LEFT : u32 = 1 ;
pub const SQL_OJ_RIGHT : u32 = 2 ;
pub const SQL_OJ_FULL : u32 = 4 ;
pub const SQL_OJ_NESTED : u32 = 8 ;
pub const SQL_OJ_NOT_ORDERED : u32 = 16 ;
pub const SQL_OJ_INNER : u32 = 32 ;
pub const SQL_OJ_ALL_COMPARISON_OPS : u32 = 64 ;
pub const SQL_CLI_DRIVER_TYPE_UNDEFINED : u32 = 0 ;
pub const SQL_CLI_DRIVER_RUNTIME_CLIENT : u32 = 1 ;
pub const SQL_CLI_DRIVER_CLI_DRIVER : u32 = 2 ;
pub const SQL_ALL_TYPES : u32 = 0 ;
pub const SQL_ATTR_AUTO_IPD : u32 = 10001 ;
pub const SQL_ATTR_APP_ROW_DESC : u32 = 10010 ;
pub const SQL_ATTR_APP_PARAM_DESC : u32 = 10011 ;
pub const SQL_ATTR_IMP_ROW_DESC : u32 = 10012 ;
pub const SQL_ATTR_IMP_PARAM_DESC : u32 = 10013 ;
pub const SQL_ATTR_METADATA_ID : u32 = 10014 ;
pub const SQL_ATTR_CURSOR_SCROLLABLE : i32 = - 1 ;
pub const SQL_ATTR_CURSOR_SENSITIVITY : i32 = - 2 ;
pub const SQL_NONSCROLLABLE : u32 = 0 ;
pub const SQL_SCROLLABLE : u32 = 1 ;
pub const SQL_CURSOR_HOLD : u32 = 1250 ;
pub const SQL_ATTR_CURSOR_HOLD : u32 = 1250 ;
pub const SQL_NODESCRIBE_OUTPUT : u32 = 1251 ;
pub const SQL_ATTR_NODESCRIBE_OUTPUT : u32 = 1251 ;
pub const SQL_NODESCRIBE_INPUT : u32 = 1264 ;
pub const SQL_ATTR_NODESCRIBE_INPUT : u32 = 1264 ;
pub const SQL_NODESCRIBE : u32 = 1251 ;
pub const SQL_ATTR_NODESCRIBE : u32 = 1251 ;
pub const SQL_CLOSE_BEHAVIOR : u32 = 1257 ;
pub const SQL_ATTR_CLOSE_BEHAVIOR : u32 = 1257 ;
pub const SQL_ATTR_CLOSEOPEN : u32 = 1265 ;
pub const SQL_ATTR_CURRENT_PACKAGE_SET : u32 = 1276 ;
pub const SQL_ATTR_DEFERRED_PREPARE : u32 = 1277 ;
pub const SQL_ATTR_EARLYCLOSE : u32 = 1268 ;
pub const SQL_ATTR_PROCESSCTL : u32 = 1278 ;
pub const SQL_ATTR_PREFETCH : u32 = 1285 ;
pub const SQL_ATTR_ENABLE_IPD_SETTING : u32 = 1286 ;
pub const SQL_ATTR_RETRYONERROR : u32 = 121 ;
pub const SQL_DESC_DESCRIPTOR_TYPE : u32 = 1287 ;
pub const SQL_ATTR_OPTIMIZE_SQLCOLUMNS : u32 = 1288 ;
pub const SQL_ATTR_MEM_DEBUG_DUMP : u32 = 1289 ;
pub const SQL_ATTR_CONNECT_NODE : u32 = 1290 ;
pub const SQL_ATTR_CONNECT_WITH_XA : u32 = 1291 ;
pub const SQL_ATTR_GET_XA_RESOURCE : u32 = 1292 ;
pub const SQL_ATTR_DB2_SQLERRP : u32 = 2451 ;
pub const SQL_ATTR_SERVER_MSGTXT_SP : u32 = 2452 ;
pub const SQL_ATTR_OPTIMIZE_FOR_NROWS : u32 = 2450 ;
pub const SQL_ATTR_QUERY_OPTIMIZATION_LEVEL : u32 = 1293 ;
pub const SQL_ATTR_USE_LIGHT_OUTPUT_SQLDA : u32 = 1298 ;
pub const SQL_ATTR_CURSOR_BLOCK_NUM_ROWS : u32 = 2453 ;
pub const SQL_ATTR_CURSOR_BLOCK_EARLY_CLOSE : u32 = 2454 ;
pub const SQL_ATTR_SERVER_MSGTXT_MASK : u32 = 2455 ;
pub const SQL_ATTR_USE_LIGHT_INPUT_SQLDA : u32 = 2458 ;
pub const SQL_ATTR_BLOCK_FOR_NROWS : u32 = 2459 ;
pub const SQL_ATTR_OPTIMIZE_ROWS_FOR_BLOCKING : u32 = 2460 ;
pub const SQL_ATTR_STATICMODE : u32 = 2467 ;
pub const SQL_ATTR_DB2_MESSAGE_PREFIX : u32 = 2468 ;
pub const SQL_ATTR_CALL_RETVAL_AS_PARM : u32 = 2469 ;
pub const SQL_ATTR_CALL_RETURN : u32 = 2470 ;
pub const SQL_ATTR_RETURN_USER_DEFINED_TYPES : u32 = 2471 ;
pub const SQL_ATTR_ENABLE_EXTENDED_PARAMDATA : u32 = 2472 ;
pub const SQL_ATTR_APP_TYPE : u32 = 2473 ;
pub const SQL_ATTR_TRANSFORM_GROUP : u32 = 2474 ;
pub const SQL_ATTR_DESCRIBE_CALL : u32 = 2476 ;
pub const SQL_ATTR_AUTOCOMMCLEANUP : u32 = 2477 ;
pub const SQL_ATTR_USEMALLOC : u32 = 2478 ;
pub const SQL_ATTR_PRESERVE_LOCALE : u32 = 2479 ;
pub const SQL_ATTR_MAPGRAPHIC : u32 = 2480 ;
pub const SQL_ATTR_INSERT_BUFFERING : u32 = 2481 ;
pub const SQL_ATTR_USE_LOAD_API : u32 = 2482 ;
pub const SQL_ATTR_LOAD_RECOVERABLE : u32 = 2483 ;
pub const SQL_ATTR_LOAD_COPY_LOCATION : u32 = 2484 ;
pub const SQL_ATTR_LOAD_MESSAGE_FILE : u32 = 2485 ;
pub const SQL_ATTR_LOAD_SAVECOUNT : u32 = 2486 ;
pub const SQL_ATTR_LOAD_CPU_PARALLELISM : u32 = 2487 ;
pub const SQL_ATTR_LOAD_DISK_PARALLELISM : u32 = 2488 ;
pub const SQL_ATTR_LOAD_INDEXING_MODE : u32 = 2489 ;
pub const SQL_ATTR_LOAD_STATS_MODE : u32 = 2490 ;
pub const SQL_ATTR_LOAD_TEMP_FILES_PATH : u32 = 2491 ;
pub const SQL_ATTR_LOAD_DATA_BUFFER_SIZE : u32 = 2492 ;
pub const SQL_ATTR_LOAD_MODIFIED_BY : u32 = 2493 ;
pub const SQL_ATTR_DB2_RESERVED_2494 : u32 = 2494 ;
pub const SQL_ATTR_DESCRIBE_BEHAVIOR : u32 = 2495 ;
pub const SQL_ATTR_FETCH_SENSITIVITY : u32 = 2496 ;
pub const SQL_ATTR_DB2_RESERVED_2497 : u32 = 2497 ;
pub const SQL_ATTR_CLIENT_LOB_BUFFERING : u32 = 2498 ;
pub const SQL_ATTR_SKIP_TRACE : u32 = 2499 ;
pub const SQL_ATTR_LOAD_INFO : u32 = 2501 ;
pub const SQL_ATTR_DESCRIBE_INPUT_ON_PREPARE : u32 = 2505 ;
pub const SQL_ATTR_DESCRIBE_OUTPUT_LEVEL : u32 = 2506 ;
pub const SQL_ATTR_CURRENT_PACKAGE_PATH : u32 = 2509 ;
pub const SQL_ATTR_INFO_PROGRAMID : u32 = 2511 ;
pub const SQL_ATTR_INFO_PROGRAMNAME : u32 = 2516 ;
pub const SQL_ATTR_FREE_LOCATORS_ON_FETCH : u32 = 2518 ;
pub const SQL_ATTR_KEEP_DYNAMIC : u32 = 2522 ;
pub const SQL_ATTR_LOAD_ROWS_READ_PTR : u32 = 2524 ;
pub const SQL_ATTR_LOAD_ROWS_SKIPPED_PTR : u32 = 2525 ;
pub const SQL_ATTR_LOAD_ROWS_COMMITTED_PTR : u32 = 2526 ;
pub const SQL_ATTR_LOAD_ROWS_LOADED_PTR : u32 = 2527 ;
pub const SQL_ATTR_LOAD_ROWS_REJECTED_PTR : u32 = 2528 ;
pub const SQL_ATTR_LOAD_ROWS_DELETED_PTR : u32 = 2529 ;
pub const SQL_ATTR_LOAD_INFO_VER : u32 = 2530 ;
pub const SQL_ATTR_SET_SSA : u32 = 2531 ;
pub const SQL_ATTR_BLOCK_LOBS : u32 = 2534 ;
pub const SQL_ATTR_LOAD_ACCESS_LEVEL : u32 = 2536 ;
pub const SQL_ATTR_MAPCHAR : u32 = 2546 ;
pub const SQL_ATTR_ARM_CORRELATOR : u32 = 2554 ;
pub const SQL_ATTR_CLIENT_DEBUGINFO : u32 = 2556 ;
pub const SQL_ATTR_GET_GENERATED_VALUE : u32 = 2583 ;
pub const SQL_ATTR_GET_SERIAL_VALUE : u32 = 2584 ;
pub const SQL_ATTR_INTERLEAVED_PUTDATA : u32 = 2591 ;
pub const SQL_ATTR_FORCE_ROLLBACK : u32 = 2596 ;
pub const SQL_ATTR_STMT_CONCENTRATOR : u32 = 2597 ;
pub const SQL_ATTR_LOAD_REPLACE_OPTION : u32 = 3036 ;
pub const SQL_ATTR_SESSION_GLOBAL_VAR : u32 = 3044 ;
pub const SQL_ATTR_SPECIAL_REGISTER : u32 = 3049 ;
pub const SQL_STMT_CONCENTRATOR_OFF : u32 = 1 ;
pub const SQL_STMT_CONCENTRATOR_WITH_LITERALS : u32 = 2 ;
pub const SQL_INFO_LAST : u32 = 174 ;
pub const SQL_INFO_DRIVER_START : u32 = 1000 ;
pub const SQL_FORCE_ROLLBACK_ON : u32 = 1 ;
pub const SQL_FORCE_ROLLBACK_OFF : u32 = 0 ;
pub const SQL_FORCE_ROLLBACK_DEFAULT : u32 = 0 ;
pub const SQL_DESCRIBE_NONE : u32 = 0 ;
pub const SQL_DESCRIBE_LIGHT : u32 = 1 ;
pub const SQL_DESCRIBE_REGULAR : u32 = 2 ;
pub const SQL_DESCRIBE_EXTENDED : u32 = 3 ;
pub const SQL_USE_LOAD_OFF : u32 = 0 ;
pub const SQL_USE_LOAD_INSERT : u32 = 1 ;
pub const SQL_USE_LOAD_REPLACE : u32 = 2 ;
pub const SQL_USE_LOAD_RESTART : u32 = 3 ;
pub const SQL_USE_LOAD_TERMINATE : u32 = 4 ;
pub const SQL_USE_LOAD_WITH_ET : u32 = 5 ;
pub const SQL_LOAD_REPLACE_DEFAULT : u32 = 0 ;
pub const SQL_LOAD_KEEPDICTIONARY : u32 = 1 ;
pub const SQL_LOAD_RESETDICTIONARY : u32 = 2 ;
pub const SQL_LOAD_RESETDICTIONARYONLY : u32 = 3 ;
pub const SQL_PREFETCH_ON : u32 = 1 ;
pub const SQL_PREFETCH_OFF : u32 = 0 ;
pub const SQL_PREFETCH_DEFAULT : u32 = 0 ;
pub const SQL_CC_NO_RELEASE : u32 = 0 ;
pub const SQL_CC_RELEASE : u32 = 1 ;
pub const SQL_CC_DEFAULT : u32 = 0 ;
pub const SQL_RETRYONERROR_OFF : u32 = 0 ;
pub const SQL_RETRYONERROR_ON : u32 = 1 ;
pub const SQL_RETRYONERROR_DEFAULT : u32 = 1 ;
pub const SQL_RETRYBINDONERROR_OFF : u32 = 0 ;
pub const SQL_RETRYBINDONERROR_ON : u32 = 1 ;
pub const SQL_RETRYBINDONERROR_DEFAULT : u32 = 1 ;
pub const SQL_ALLOW_INTERLEAVED_GETDATA_OFF : u32 = 0 ;
pub const SQL_ALLOW_INTERLEAVED_GETDATA_ON : u32 = 1 ;
pub const SQL_ALLOW_INTERLEAVED_GETDATA_DEFAULT : u32 = 0 ;
pub const SQL_INTERLEAVED_STREAM_PUTDATA_OFF : u32 = 0 ;
pub const SQL_INTERLEAVED_STREAM_PUTDATA_ON : u32 = 1 ;
pub const SQL_OVERRIDE_CODEPAGE_ON : u32 = 1 ;
pub const SQL_OVERRIDE_CODEPAGE_OFF : u32 = 0 ;
pub const SQL_DEFERRED_PREPARE_ON : u32 = 1 ;
pub const SQL_DEFERRED_PREPARE_OFF : u32 = 0 ;
pub const SQL_DEFERRED_PREPARE_DEFAULT : u32 = 1 ;
pub const SQL_EARLYCLOSE_ON : u32 = 1 ;
pub const SQL_EARLYCLOSE_OFF : u32 = 0 ;
pub const SQL_EARLYCLOSE_SERVER : u32 = 2 ;
pub const SQL_EARLYCLOSE_DEFAULT : u32 = 1 ;
pub const SQL_APP_TYPE_ODBC : u32 = 1 ;
pub const SQL_APP_TYPE_OLEDB : u32 = 2 ;
pub const SQL_APP_TYPE_JDBC : u32 = 3 ;
pub const SQL_APP_TYPE_ADONET : u32 = 4 ;
pub const SQL_APP_TYPE_DRDAWRAPPER : u32 = 5 ;
pub const SQL_APP_TYPE_OCI : u32 = 6 ;
pub const SQL_APP_TYPE_DEFAULT : u32 = 1 ;
pub const SQL_PROCESSCTL_NOTHREAD : u32 = 1 ;
pub const SQL_PROCESSCTL_NOFORK : u32 = 2 ;
pub const SQL_PROCESSCTL_SHARESTMTDESC : u32 = 4 ;
pub const SQL_PROCESSCTL_MULTICONNECT3 : u32 = 8 ;
pub const SQL_FALSE : u32 = 0 ;
pub const SQL_TRUE : u32 = 1 ;
pub const SQL_CURSOR_HOLD_ON : u32 = 1 ;
pub const SQL_CURSOR_HOLD_OFF : u32 = 0 ;
pub const SQL_CURSOR_HOLD_DEFAULT : u32 = 1 ;
pub const SQL_NODESCRIBE_ON : u32 = 1 ;
pub const SQL_NODESCRIBE_OFF : u32 = 0 ;
pub const SQL_NODESCRIBE_DEFAULT : u32 = 0 ;
pub const SQL_DESCRIBE_CALL_NEVER : u32 = 0 ;
pub const SQL_DESCRIBE_CALL_BEFORE : u32 = 1 ;
pub const SQL_DESCRIBE_CALL_ON_ERROR : u32 = 2 ;
pub const SQL_DESCRIBE_CALL_DEFAULT : i32 = - 1 ;
pub const SQL_CLIENTLOB_USE_LOCATORS : u32 = 0 ;
pub const SQL_CLIENTLOB_BUFFER_UNBOUND_LOBS : u32 = 1 ;
pub const SQL_CLIENTLOB_DEFAULT : u32 = 0 ;
pub const SQL_CLIENT_ENCALG_NOT_SET : u32 = 0 ;
pub const SQL_CLIENT_ENCALG_ANY : u32 = 1 ;
pub const SQL_CLIENT_ENCALG_AES_ONLY : u32 = 2 ;
pub const SQL_COMMITONEOF_OFF : u32 = 0 ;
pub const SQL_COMMITONEOF_ON : u32 = 1 ;
pub const SQL_WCHARTYPE : u32 = 1252 ;
pub const SQL_LONGDATA_COMPAT : u32 = 1253 ;
pub const SQL_CURRENT_SCHEMA : u32 = 1254 ;
pub const SQL_DB2EXPLAIN : u32 = 1258 ;
pub const SQL_DB2ESTIMATE : u32 = 1259 ;
pub const SQL_PARAMOPT_ATOMIC : u32 = 1260 ;
pub const SQL_STMTTXN_ISOLATION : u32 = 1261 ;
pub const SQL_MAXCONN : u32 = 1262 ;
pub const SQL_ATTR_CLISCHEMA : u32 = 1280 ;
pub const SQL_ATTR_INFO_USERID : u32 = 1281 ;
pub const SQL_ATTR_INFO_WRKSTNNAME : u32 = 1282 ;
pub const SQL_ATTR_INFO_APPLNAME : u32 = 1283 ;
pub const SQL_ATTR_INFO_ACCTSTR : u32 = 1284 ;
pub const SQL_ATTR_AUTOCOMMIT_NOCOMMIT : u32 = 2462 ;
pub const SQL_ATTR_QUERY_PATROLLER : u32 = 2466 ;
pub const SQL_ATTR_CHAINING_BEGIN : u32 = 2464 ;
pub const SQL_ATTR_CHAINING_END : u32 = 2465 ;
pub const SQL_ATTR_EXTENDEDBIND : u32 = 2475 ;
pub const SQL_ATTR_GRAPHIC_UNICODESERVER : u32 = 2503 ;
pub const SQL_ATTR_RETURN_CHAR_AS_WCHAR_OLEDB : u32 = 2517 ;
pub const SQL_ATTR_GATEWAY_CONNECTED : u32 = 2537 ;
pub const SQL_ATTR_SQLCOLUMNS_SORT_BY_ORDINAL_OLEDB : u32 = 2542 ;
pub const SQL_ATTR_REPORT_ISLONG_FOR_LONGTYPES_OLEDB : u32 = 2543 ;
pub const SQL_ATTR_PING_DB : u32 = 2545 ;
pub const SQL_ATTR_RECEIVE_TIMEOUT : u32 = 2547 ;
pub const SQL_ATTR_REOPT : u32 = 2548 ;
pub const SQL_ATTR_LOB_CACHE_SIZE : u32 = 2555 ;
pub const SQL_ATTR_STREAM_GETDATA : u32 = 2558 ;
pub const SQL_ATTR_APP_USES_LOB_LOCATOR : u32 = 2559 ;
pub const SQL_ATTR_MAX_LOB_BLOCK_SIZE : u32 = 2560 ;
pub const SQL_ATTR_USE_TRUSTED_CONTEXT : u32 = 2561 ;
pub const SQL_ATTR_TRUSTED_CONTEXT_USERID : u32 = 2562 ;
pub const SQL_ATTR_TRUSTED_CONTEXT_PASSWORD : u32 = 2563 ;
pub const SQL_ATTR_USER_REGISTRY_NAME : u32 = 2564 ;
pub const SQL_ATTR_DECFLOAT_ROUNDING_MODE : u32 = 2565 ;
pub const SQL_ATTR_APPEND_FOR_FETCH_ONLY : u32 = 2573 ;
pub const SQL_ATTR_ONLY_USE_BIG_PACKAGES : u32 = 2577 ;
pub const SQL_ATTR_NONATMOIC_BUFFER_INSERT : u32 = 2588 ;
pub const SQL_ATTR_ROWCOUNT_PREFETCH : u32 = 2592 ;
pub const SQL_ATTR_PING_REQUEST_PACKET_SIZE : u32 = 2593 ;
pub const SQL_ATTR_PING_NTIMES : u32 = 2594 ;
pub const SQL_ATTR_ALLOW_INTERLEAVED_GETDATA : u32 = 2599 ;
pub const SQL_ATTR_INTERLEAVED_STREAM_PUTDATA : u32 = 3000 ;
pub const SQL_ATTR_FET_BUF_SIZE : u32 = 3001 ;
pub const SQL_ATTR_CLIENT_CODEPAGE : u32 = 3002 ;
pub const SQL_ATTR_EXTENDED_INDICATORS : u32 = 3003 ;
pub const SQL_ATTR_SESSION_TIME_ZONE : u32 = 3004 ;
pub const SQL_ATTR_CLIENT_TIME_ZONE : u32 = 3005 ;
pub const SQL_ATTR_NETWORK_STATISTICS : u32 = 3006 ;
pub const SQL_ATTR_OVERRIDE_CHARACTER_CODEPAGE : u32 = 3007 ;
pub const SQL_ATTR_GET_LATEST_MEMBER : u32 = 3008 ;
pub const SQL_ATTR_CO_CAPTUREONPREPARE : u32 = 3009 ;
pub const SQL_ATTR_RETRYBINDONERROR : u32 = 3010 ;
pub const SQL_ATTR_COMMITONEOF : u32 = 3011 ;
pub const SQL_ATTR_PARC_BATCH : u32 = 3012 ;
pub const SQL_ATTR_COLUMNWISE_MRI : u32 = 3013 ;
pub const SQL_ATTR_OVERRIDE_CODEPAGE : u32 = 3014 ;
pub const SQL_ATTR_SQLCODEMAP : u32 = 3015 ;
pub const SQL_ATTR_ISREADONLYSQL : u32 = 3016 ;
pub const SQL_ATTR_DBC_SYS_NAMING : u32 = 3017 ;
pub const SQL_ATTR_FREE_MEMORY_ON_STMTCLOSE : u32 = 3018 ;
pub const SQL_ATTR_OVERRIDE_PRIMARY_AFFINITY : u32 = 3020 ;
pub const SQL_ATTR_STREAM_OUTPUTLOB_ON_CALL : u32 = 3021 ;
pub const SQL_ATTR_CACHE_USRLIBL : u32 = 3022 ;
pub const SQL_ATTR_GET_LATEST_MEMBER_NAME : u32 = 3023 ;
pub const SQL_ATTR_INFO_CRRTKN : u32 = 3024 ;
pub const SQL_ATTR_DATE_FMT : u32 = 3025 ;
pub const SQL_ATTR_DATE_SEP : u32 = 3026 ;
pub const SQL_ATTR_TIME_FMT : u32 = 3027 ;
pub const SQL_ATTR_TIME_SEP : u32 = 3028 ;
pub const SQL_ATTR_DECIMAL_SEP : u32 = 3029 ;
pub const SQL_ATTR_READ_ONLY_CONNECTION : u32 = 3030 ;
pub const SQL_ATTR_CONFIG_KEYWORDS_ARRAY_SIZE : u32 = 3031 ;
pub const SQL_ATTR_CONFIG_KEYWORDS_MAXLEN : u32 = 3032 ;
pub const SQL_ATTR_RETRY_ON_MERGE : u32 = 3033 ;
pub const SQL_ATTR_DETECT_READ_ONLY_TXN : u32 = 3034 ;
pub const SQL_ATTR_IGNORE_SERVER_LIST : u32 = 3035 ;
pub const SQL_ATTR_DB2ZLOAD_LOADSTMT : u32 = 3037 ;
pub const SQL_ATTR_DB2ZLOAD_RECDELIM : u32 = 3038 ;
pub const SQL_ATTR_DB2ZLOAD_BEGIN : u32 = 3039 ;
pub const SQL_ATTR_DB2ZLOAD_END : u32 = 3040 ;
pub const SQL_ATTR_DB2ZLOAD_FILETYPE : u32 = 3041 ;
pub const SQL_ATTR_DB2ZLOAD_MSGFILE : u32 = 3042 ;
pub const SQL_ATTR_DB2ZLOAD_UTILITYID : u32 = 3043 ;
pub const SQL_ATTR_CONNECT_PASSIVE : u32 = 3045 ;
pub const SQL_ATTR_CLIENT_APPLCOMPAT : u32 = 3046 ;
pub const SQL_ATTR_DB2ZLOAD_LOADFILE : u32 = 3047 ;
pub const SQL_ATTR_PREFETCH_NROWS : u32 = 3048 ;
pub const SQL_ATTR_LOB_FILE_THRESHOLD : u32 = 3050 ;
pub const SQL_ATTR_TRUSTED_CONTEXT_ACCESSTOKEN : u32 = 3051 ;
pub const SQL_ATTR_CLIENT_USERID : u32 = 1281 ;
pub const SQL_ATTR_CLIENT_WRKSTNNAME : u32 = 1282 ;
pub const SQL_ATTR_CLIENT_APPLNAME : u32 = 1283 ;
pub const SQL_ATTR_CLIENT_ACCTSTR : u32 = 1284 ;
pub const SQL_ATTR_CLIENT_PROGINFO : u32 = 2516 ;
pub const SQL_DM_DROP_MODULE : u32 = 1 ;
pub const SQL_DM_RESTRICT : u32 = 2 ;
pub const SQL_MU_PROCEDURE_INVOCATION : u32 = 1 ;
pub const SQL_CM_CREATE_MODULE : u32 = 1 ;
pub const SQL_CM_AUTHORIZATION : u32 = 2 ;
pub const SQL_ATTR_WCHARTYPE : u32 = 1252 ;
pub const SQL_ATTR_LONGDATA_COMPAT : u32 = 1253 ;
pub const SQL_ATTR_CURRENT_SCHEMA : u32 = 1254 ;
pub const SQL_ATTR_DB2EXPLAIN : u32 = 1258 ;
pub const SQL_ATTR_DB2ESTIMATE : u32 = 1259 ;
pub const SQL_ATTR_PARAMOPT_ATOMIC : u32 = 1260 ;
pub const SQL_ATTR_STMTTXN_ISOLATION : u32 = 1261 ;
pub const SQL_ATTR_MAXCONN : u32 = 1262 ;
pub const SQL_CONNECTTYPE : u32 = 1255 ;
pub const SQL_SYNC_POINT : u32 = 1256 ;
pub const SQL_MINMEMORY_USAGE : u32 = 1263 ;
pub const SQL_CONN_CONTEXT : u32 = 1269 ;
pub const SQL_ATTR_INHERIT_NULL_CONNECT : u32 = 1270 ;
pub const SQL_ATTR_FORCE_CONVERSION_ON_CLIENT : u32 = 1275 ;
pub const SQL_ATTR_INFO_KEYWORDLIST : u32 = 2500 ;
pub const SQL_ATTR_DISABLE_SYSPLEX : u32 = 2590 ;
pub const SQL_ATTR_CONNECTTYPE : u32 = 1255 ;
pub const SQL_ATTR_SYNC_POINT : u32 = 1256 ;
pub const SQL_ATTR_MINMEMORY_USAGE : u32 = 1263 ;
pub const SQL_ATTR_CONN_CONTEXT : u32 = 1269 ;
pub const SQL_LD_COMPAT_YES : u32 = 1 ;
pub const SQL_LD_COMPAT_NO : u32 = 0 ;
pub const SQL_LD_COMPAT_DEFAULT : u32 = 0 ;
pub const SQL_ATTR_EXTENDEDBIND_COPY : u32 = 1 ;
pub const SQL_ATTR_EXTENDEDBIND_NOCOPY : u32 = 0 ;
pub const SQL_ATTR_EXTENDEDBIND_DEFAULT : u32 = 0 ;
pub const SQL_NC_HIGH : u32 = 0 ;
pub const SQL_NC_LOW : u32 = 1 ;
pub const SQL_PARC_BATCH_ENABLE : u32 = 1 ;
pub const SQL_PARC_BATCH_DISABLE : u32 = 0 ;
pub const SQL_SQLCODEMAP_NOMAP : u32 = 1 ;
pub const SQL_SQLCODEMAP_MAP : u32 = 2 ;
pub const SQL_CONNECT_PASSIVE_YES : u32 = 1 ;
pub const SQL_CONNECT_PASSIVE_NO : u32 = 0 ;
pub const SQL_CONNECT_PASSIVE_DEFAULT : u32 = 0 ;
pub const CLI_MAX_LONGVARCHAR : u32 = 1250 ;
pub const CLI_MAX_VARCHAR : u32 = 1251 ;
pub const CLI_MAX_CHAR : u32 = 1252 ;
pub const CLI_MAX_LONGVARGRAPHIC : u32 = 1253 ;
pub const CLI_MAX_VARGRAPHIC : u32 = 1254 ;
pub const CLI_MAX_GRAPHIC : u32 = 1255 ;
pub const SQL_DIAG_MESSAGE_TEXT_PTR : u32 = 2456 ;
pub const SQL_DIAG_LINE_NUMBER : u32 = 2461 ;
pub const SQL_DIAG_ERRMC : u32 = 2467 ;
pub const SQL_DIAG_SQLCA : u32 = 3037 ;
pub const SQL_DIAG_BYTES_PROCESSED : u32 = 2477 ;
pub const SQL_DIAG_RELATIVE_COST_ESTIMATE : u32 = 2504 ;
pub const SQL_DIAG_ROW_COUNT_ESTIMATE : u32 = 2507 ;
pub const SQL_DIAG_ELAPSED_SERVER_TIME : u32 = 2538 ;
pub const SQL_DIAG_ELAPSED_NETWORK_TIME : u32 = 2539 ;
pub const SQL_DIAG_ACCUMULATED_SERVER_TIME : u32 = 2540 ;
pub const SQL_DIAG_ACCUMULATED_NETWORK_TIME : u32 = 2541 ;
pub const SQL_DIAG_QUIESCE : u32 = 2549 ;
pub const SQL_DIAG_TOLERATED_ERROR : u32 = 2559 ;
pub const SQL_DIAG_NETWORK_STATISTICS : u32 = 2560 ;
pub const SQL_DIAG_QUIESCE_NO : u32 = 0 ;
pub const SQL_DIAG_QUIESCE_DATABASE : u32 = 1 ;
pub const SQL_DIAG_QUIESCE_INSTANCE : u32 = 2 ;
pub const SQL_ATTR_LITTLE_ENDIAN_UNICODE : u32 = 2457 ;
pub const SQL_ATTR_DIAGLEVEL : u32 = 2574 ;
pub const SQL_ATTR_NOTIFYLEVEL : u32 = 2575 ;
pub const SQL_ATTR_DIAGPATH : u32 = 2576 ;
pub const SQL_ATTR_MESSAGE_LINE_LENGTH : u32 = 2580 ;
pub const SQL_ATTR_ENABLE_IFXENV : u32 = 2585 ;
pub const SQL_ATTR_TRACENOHEADER : u32 = 2598 ;
pub const SQL_ATTR_DB2TRC_STARTUP_SIZE : u32 = 3019 ;
pub const SQL_ATOMIC_YES : u32 = 1 ;
pub const SQL_ATOMIC_NO : u32 = 0 ;
pub const SQL_ATOMIC_DEFAULT : u32 = 1 ;
pub const SQL_CONCURRENT_TRANS : u32 = 1 ;
pub const SQL_COORDINATED_TRANS : u32 = 2 ;
pub const SQL_CONNECTTYPE_DEFAULT : u32 = 1 ;
pub const SQL_ONEPHASE : u32 = 1 ;
pub const SQL_TWOPHASE : u32 = 2 ;
pub const SQL_SYNCPOINT_DEFAULT : u32 = 1 ;
pub const SQL_DB2ESTIMATE_ON : u32 = 1 ;
pub const SQL_DB2ESTIMATE_OFF : u32 = 0 ;
pub const SQL_DB2ESTIMATE_DEFAULT : u32 = 0 ;
pub const SQL_DB2EXPLAIN_OFF : u32 = 0 ;
pub const SQL_DB2EXPLAIN_SNAPSHOT_ON : u32 = 1 ;
pub const SQL_DB2EXPLAIN_MODE_ON : u32 = 2 ;
pub const SQL_DB2EXPLAIN_SNAPSHOT_MODE_ON : u32 = 3 ;
pub const SQL_DB2EXPLAIN_ON : u32 = 1 ;
pub const SQL_DB2EXPLAIN_DEFAULT : u32 = 0 ;
pub const SQL_WCHARTYPE_NOCONVERT : u32 = 0 ;
pub const SQL_WCHARTYPE_DEFAULT : u32 = 0 ;
pub const SQL_OPTIMIZE_SQLCOLUMNS_OFF : u32 = 0 ;
pub const SQL_OPTIMIZE_SQLCOLUMNS_ON : u32 = 1 ;
pub const SQL_OPTIMIZE_SQLCOLUMNS_DEFAULT : u32 = 0 ;
pub const SQL_CONNECT_WITH_XA_OFF : u32 = 0 ;
pub const SQL_CONNECT_WITH_XA_ON : u32 = 1 ;
pub const SQL_CONNECT_WITH_XA_DEFAULT : u32 = 0 ;
pub const SQL_ATTR_SERVER_MSGTXT_MASK_LOCAL_FIRST : u32 = 0 ;
pub const SQL_ATTR_SERVER_MSGTXT_MASK_WARNINGS : u32 = 1 ;
pub const SQL_ATTR_SERVER_MSGTXT_MASK_ERRORS : u32 = 4294967294 ;
pub const SQL_ATTR_SERVER_MSGTXT_MASK_ALL : u32 = 4294967295 ;
pub const SQL_ATTR_SERVER_MSGTXT_MASK_DEFAULT : u32 = 0 ;
pub const SQL_ATTR_QUERY_PATROLLER_DISABLE : u32 = 1 ;
pub const SQL_ATTR_QUERY_PATROLLER_ENABLE : u32 = 2 ;
pub const SQL_ATTR_QUERY_PATROLLER_BYPASS : u32 = 3 ;
pub const SQL_STATICMODE_DISABLED : u32 = 0 ;
pub const SQL_STATICMODE_CAPTURE : u32 = 1 ;
pub const SQL_STATICMODE_MATCH : u32 = 2 ;
pub const SQL_ATTR_DB2_MESSAGE_PREFIX_OFF : u32 = 0 ;
pub const SQL_ATTR_DB2_MESSAGE_PREFIX_ON : u32 = 1 ;
pub const SQL_ATTR_DB2_MESSAGE_PREFIX_DEFAULT : u32 = 1 ;
pub const SQL_ATTR_INSERT_BUFFERING_OFF : u32 = 0 ;
pub const SQL_ATTR_INSERT_BUFFERING_ON : u32 = 1 ;
pub const SQL_ATTR_INSERT_BUFFERING_IGD : u32 = 2 ;
pub const SQL_ROWCOUNT_PREFETCH_OFF : u32 = 0 ;
pub const SQL_ROWCOUNT_PREFETCH_ON : u32 = 1 ;
pub const SQL_SCOPE_CURROW : u32 = 0 ;
pub const SQL_SCOPE_TRANSACTION : u32 = 1 ;
pub const SQL_SCOPE_SESSION : u32 = 2 ;
pub const SQL_INDEX_UNIQUE : u32 = 0 ;
pub const SQL_INDEX_ALL : u32 = 1 ;
pub const SQL_INDEX_CLUSTERED : u32 = 1 ;
pub const SQL_INDEX_HASHED : u32 = 2 ;
pub const SQL_INDEX_OTHER : u32 = 3 ;
pub const SQL_PC_UNKNOWN : u32 = 0 ;
pub const SQL_PC_NON_PSEUDO : u32 = 1 ;
pub const SQL_PC_PSEUDO : u32 = 2 ;
pub const SQL_ROW_IDENTIFIER : u32 = 1 ;
pub const SQL_MAPGRAPHIC_DEFAULT : i32 = - 1 ;
pub const SQL_MAPGRAPHIC_GRAPHIC : u32 = 0 ;
pub const SQL_MAPGRAPHIC_WCHAR : u32 = 1 ;
pub const SQL_MAPCHAR_DEFAULT : u32 = 0 ;
pub const SQL_MAPCHAR_WCHAR : u32 = 1 ;
pub const SQL_FETCH_NEXT : u32 = 1 ;
pub const SQL_FETCH_FIRST : u32 = 2 ;
pub const SQL_FETCH_LAST : u32 = 3 ;
pub const SQL_FETCH_PRIOR : u32 = 4 ;
pub const SQL_FETCH_ABSOLUTE : u32 = 5 ;
pub const SQL_FETCH_RELATIVE : u32 = 6 ;
pub const SQL_EXTENDED_INDICATOR_NOT_SET : u32 = 0 ;
pub const SQL_EXTENDED_INDICATOR_ENABLE : u32 = 1 ;
pub const SQL_EXTENDED_INDICATOR_DISABLE : u32 = 2 ;
pub const SQL_COLUMNWISE_MRI_ON : u32 = 1 ;
pub const SQL_COLUMNWISE_MRI_OFF : u32 = 0 ;
pub const SQL_ISREADONLYSQL_YES : u32 = 1 ;
pub const SQL_ISREADONLYSQL_NO : u32 = 0 ;
pub const SQL_FREE_MEMORY_ON_STMTCLOSE_YES : u32 = 1 ;
pub const SQL_FREE_MEMORY_ON_STMTCLOSE_NO : u32 = 0 ;
pub const SQL_ATTR_CACHE_USRLIBL_YES : u32 = 0 ;
pub const SQL_ATTR_CACHE_USRLIBL_NO : u32 = 1 ;
pub const SQL_ATTR_CACHE_USRLIBL_REFRESH : u32 = 2 ;
pub const SQL_IBMi_FMT_ISO : u32 = 1 ;
pub const SQL_IBMi_FMT_USA : u32 = 2 ;
pub const SQL_IBMi_FMT_EUR : u32 = 3 ;
pub const SQL_IBMi_FMT_JIS : u32 = 4 ;
pub const SQL_IBMi_FMT_MDY : u32 = 5 ;
pub const SQL_IBMi_FMT_DMY : u32 = 6 ;
pub const SQL_IBMi_FMT_YMD : u32 = 7 ;
pub const SQL_IBMi_FMT_JUL : u32 = 8 ;
pub const SQL_IBMi_FMT_HMS : u32 = 9 ;
pub const SQL_IBMi_FMT_JOB : u32 = 10 ;
pub const SQL_SEP_SLASH : u32 = 1 ;
pub const SQL_SEP_DASH : u32 = 2 ;
pub const SQL_SEP_PERIOD : u32 = 3 ;
pub const SQL_SEP_COMMA : u32 = 4 ;
pub const SQL_SEP_BLANK : u32 = 5 ;
pub const SQL_SEP_COLON : u32 = 6 ;
pub const SQL_SEP_JOB : u32 = 7 ;
pub const SQL_XML_DECLARATION_NONE : u32 = 0 ;
pub const SQL_XML_DECLARATION_BOM : u32 = 1 ;
pub const SQL_XML_DECLARATION_BASE : u32 = 2 ;
pub const SQL_XML_DECLARATION_ENCATTR : u32 = 4 ;
pub const SQL_DB2ZLOAD_RECDELIM_NONE : u32 = 0 ;
pub const SQL_DB2ZLOAD_RECDELIM_ALF : u32 = 1 ;
pub const SQL_DB2ZLOAD_RECDELIM_ENL : u32 = 2 ;
pub const SQL_DB2ZLOAD_RECDELIM_CRLF : u32 = 3 ;
pub const SQL_DB2ZLOAD_FILETYPE_DEL : u32 = 1 ;
pub const SQL_DB2ZLOAD_FILETYPE_INT : u32 = 2 ;
pub const SQL_DB2ZLOAD_FILETYPE_SPANNED : u32 = 3 ;
pub const DSD_ACR_AFFINITY : u32 = 1 ;
pub const SQL_ATTR_OUTPUT_NTS : u32 = 10001 ;
pub const SQL_FILE_READ : u32 = 2 ;
pub const SQL_FILE_CREATE : u32 = 8 ;
pub const SQL_FILE_OVERWRITE : u32 = 16 ;
pub const SQL_FILE_APPEND : u32 = 32 ;
pub const SQL_FROM_LOCATOR : u32 = 2 ;
pub const SQL_FROM_LITERAL : u32 = 3 ;
pub const SQL_ROUND_HALF_EVEN : u32 = 0 ;
pub const SQL_ROUND_HALF_UP : u32 = 1 ;
pub const SQL_ROUND_DOWN : u32 = 2 ;
pub const SQL_ROUND_CEILING : u32 = 3 ;
pub const SQL_ROUND_FLOOR : u32 = 4 ;
pub const SQL_NETWORK_STATISTICS_ON_SKIP_NOSERVER : u32 = 2 ;
pub const SQL_NETWORK_STATISTICS_ON : u32 = 1 ;
pub const SQL_NETWORK_STATISTICS_OFF : u32 = 0 ;
pub const SQL_NETWORK_STATISTICS_DEFAULT : u32 = 0 ;
pub const SQL_READ_ONLY_CONNECTION_ON : u32 = 1 ;
pub const SQL_READ_ONLY_CONNECTION_OFF : u32 = 0 ;
pub const SQL_READ_ONLY_CONNECTION_DEFAULT : u32 = 0 ;
pub const SQL_UNASSIGNED : i32 = - 7 ;
pub const SQL_DETECT_READ_ONLY_TXN_ENABLE : u32 = 1 ;
pub const SQL_DETECT_READ_ONLY_TXN_DISABLE : u32 = 0 ;
pub const SQL_C_WCHAR : i32 = - 8 ;
pub const SQL_C_TCHAR : u32 = 1 ;
# [doc = " Define fixed size integer types."] pub type sqlint8 = :: std :: os :: raw :: c_char ;
pub type sqluint8 = :: std :: os :: raw :: c_uchar ;
pub type sqlint16 = :: std :: os :: raw :: c_short ;
pub type sqluint16 = :: std :: os :: raw :: c_ushort ;
pub type sqlint32 = :: std :: os :: raw :: c_int ;
pub type sqluint32 = :: std :: os :: raw :: c_uint ;
pub type sqlint64 = :: std :: os :: raw :: c_long ;
pub type sqluint64 = :: std :: os :: raw :: c_ulong ;
pub type sqlintptr = sqlint64 ;
pub type sqluintptr = sqluint64 ;
# [repr (C)]
# [derive (Copy , Clone)] pub struct sqlca { pub sqlcaid : [:: std :: os :: raw :: c_char ;
8usize] , pub sqlcabc : sqlint32 , pub sqlcode : sqlint32 , pub sqlerrml : :: std :: os :: raw :: c_short , pub sqlerrmc : [:: std :: os :: raw :: c_char ;
70usize] , pub sqlerrp : [:: std :: os :: raw :: c_char ;
8usize] , pub sqlerrd : [sqlint32 ;
6usize] , pub sqlwarn : [:: std :: os :: raw :: c_char ;
11usize] , pub sqlstate : [:: std :: os :: raw :: c_char ;
5usize] , }
# [test] fn bindgen_test_layout_sqlca () { assert_eq ! (:: std :: mem :: size_of :: < sqlca > () , 136usize , concat ! ("Size of: " , stringify ! (sqlca))) ;
assert_eq ! (:: std :: mem :: align_of :: < sqlca > () , 4usize , concat ! ("Alignment of " , stringify ! (sqlca))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlcaid as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlcaid))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlcabc as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlcabc))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlcode as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlcode))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlerrml as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlerrml))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlerrmc as * const _ as usize } , 18usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlerrmc))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlerrp as * const _ as usize } , 88usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlerrp))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlerrd as * const _ as usize } , 96usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlerrd))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlwarn as * const _ as usize } , 120usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlwarn))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < sqlca > ())) . sqlstate as * const _ as usize } , 131usize , concat ! ("Offset of field: " , stringify ! (sqlca) , "::" , stringify ! (sqlstate))) ;
} pub type size_t = :: std :: os :: raw :: c_ulong ;
pub type wchar_t = :: std :: os :: raw :: c_int ;
pub const idtype_t_P_ALL : idtype_t = 0 ;
pub const idtype_t_P_PID : idtype_t = 1 ;
pub const idtype_t_P_PGID : idtype_t = 2 ;
pub type idtype_t = :: std :: os :: raw :: c_uint ;
pub type _Float32 = f32 ;
pub type _Float64 = f64 ;
pub type _Float32x = f64 ;
pub type _Float64x = u128 ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct div_t { pub quot : :: std :: os :: raw :: c_int , pub rem : :: std :: os :: raw :: c_int , }
# [test] fn bindgen_test_layout_div_t () { assert_eq ! (:: std :: mem :: size_of :: < div_t > () , 8usize , concat ! ("Size of: " , stringify ! (div_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < div_t > () , 4usize , concat ! ("Alignment of " , stringify ! (div_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < div_t > ())) . quot as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (div_t) , "::" , stringify ! (quot))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < div_t > ())) . rem as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (div_t) , "::" , stringify ! (rem))) ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct ldiv_t { pub quot : :: std :: os :: raw :: c_long , pub rem : :: std :: os :: raw :: c_long , }
# [test] fn bindgen_test_layout_ldiv_t () { assert_eq ! (:: std :: mem :: size_of :: < ldiv_t > () , 16usize , concat ! ("Size of: " , stringify ! (ldiv_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < ldiv_t > () , 8usize , concat ! ("Alignment of " , stringify ! (ldiv_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < ldiv_t > ())) . quot as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (ldiv_t) , "::" , stringify ! (quot))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < ldiv_t > ())) . rem as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (ldiv_t) , "::" , stringify ! (rem))) ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct lldiv_t { pub quot : :: std :: os :: raw :: c_longlong , pub rem : :: std :: os :: raw :: c_longlong , }
# [test] fn bindgen_test_layout_lldiv_t () { assert_eq ! (:: std :: mem :: size_of :: < lldiv_t > () , 16usize , concat ! ("Size of: " , stringify ! (lldiv_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < lldiv_t > () , 8usize , concat ! ("Alignment of " , stringify ! (lldiv_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < lldiv_t > ())) . quot as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (lldiv_t) , "::" , stringify ! (quot))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < lldiv_t > ())) . rem as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (lldiv_t) , "::" , stringify ! (rem))) ;
} extern "C" { pub fn __ctype_get_mb_cur_max () -> size_t ;
} extern "C" { pub fn atof (__nptr : * const :: std :: os :: raw :: c_char) -> f64 ;
} extern "C" { pub fn atoi (__nptr : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn atol (__nptr : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn atoll (__nptr : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_longlong ;
} extern "C" { pub fn strtod (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char) -> f64 ;
} extern "C" { pub fn strtof (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char) -> f32 ;
} extern "C" { pub fn strtold (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char) -> u128 ;
} extern "C" { pub fn strtol (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char , __base : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn strtoul (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char , __base : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_ulong ;
} extern "C" { pub fn strtoq (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char , __base : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_longlong ;
} extern "C" { pub fn strtouq (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char , __base : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_ulonglong ;
} extern "C" { pub fn strtoll (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char , __base : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_longlong ;
} extern "C" { pub fn strtoull (__nptr : * const :: std :: os :: raw :: c_char , __endptr : * mut * mut :: std :: os :: raw :: c_char , __base : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_ulonglong ;
} extern "C" { pub fn l64a (__n : :: std :: os :: raw :: c_long) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn a64l (__s : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_long ;
} pub type __u_char = :: std :: os :: raw :: c_uchar ;
pub type __u_short = :: std :: os :: raw :: c_ushort ;
pub type __u_int = :: std :: os :: raw :: c_uint ;
pub type __u_long = :: std :: os :: raw :: c_ulong ;
pub type __int8_t = :: std :: os :: raw :: c_schar ;
pub type __uint8_t = :: std :: os :: raw :: c_uchar ;
pub type __int16_t = :: std :: os :: raw :: c_short ;
pub type __uint16_t = :: std :: os :: raw :: c_ushort ;
pub type __int32_t = :: std :: os :: raw :: c_int ;
pub type __uint32_t = :: std :: os :: raw :: c_uint ;
pub type __int64_t = :: std :: os :: raw :: c_long ;
pub type __uint64_t = :: std :: os :: raw :: c_ulong ;
pub type __quad_t = :: std :: os :: raw :: c_long ;
pub type __u_quad_t = :: std :: os :: raw :: c_ulong ;
pub type __intmax_t = :: std :: os :: raw :: c_long ;
pub type __uintmax_t = :: std :: os :: raw :: c_ulong ;
pub type __dev_t = :: std :: os :: raw :: c_ulong ;
pub type __uid_t = :: std :: os :: raw :: c_uint ;
pub type __gid_t = :: std :: os :: raw :: c_uint ;
pub type __ino_t = :: std :: os :: raw :: c_ulong ;
pub type __ino64_t = :: std :: os :: raw :: c_ulong ;
pub type __mode_t = :: std :: os :: raw :: c_uint ;
pub type __nlink_t = :: std :: os :: raw :: c_ulong ;
pub type __off_t = :: std :: os :: raw :: c_long ;
pub type __off64_t = :: std :: os :: raw :: c_long ;
pub type __pid_t = :: std :: os :: raw :: c_int ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __fsid_t { pub __val : [:: std :: os :: raw :: c_int ;
2usize] , }
# [test] fn bindgen_test_layout___fsid_t () { assert_eq ! (:: std :: mem :: size_of :: < __fsid_t > () , 8usize , concat ! ("Size of: " , stringify ! (__fsid_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < __fsid_t > () , 4usize , concat ! ("Alignment of " , stringify ! (__fsid_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __fsid_t > ())) . __val as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__fsid_t) , "::" , stringify ! (__val))) ;
} pub type __clock_t = :: std :: os :: raw :: c_long ;
pub type __rlim_t = :: std :: os :: raw :: c_ulong ;
pub type __rlim64_t = :: std :: os :: raw :: c_ulong ;
pub type __id_t = :: std :: os :: raw :: c_uint ;
pub type __time_t = :: std :: os :: raw :: c_long ;
pub type __useconds_t = :: std :: os :: raw :: c_uint ;
pub type __suseconds_t = :: std :: os :: raw :: c_long ;
pub type __daddr_t = :: std :: os :: raw :: c_int ;
pub type __key_t = :: std :: os :: raw :: c_int ;
pub type __clockid_t = :: std :: os :: raw :: c_int ;
pub type __timer_t = * mut :: std :: os :: raw :: c_void ;
pub type __blksize_t = :: std :: os :: raw :: c_long ;
pub type __blkcnt_t = :: std :: os :: raw :: c_long ;
pub type __blkcnt64_t = :: std :: os :: raw :: c_long ;
pub type __fsblkcnt_t = :: std :: os :: raw :: c_ulong ;
pub type __fsblkcnt64_t = :: std :: os :: raw :: c_ulong ;
pub type __fsfilcnt_t = :: std :: os :: raw :: c_ulong ;
pub type __fsfilcnt64_t = :: std :: os :: raw :: c_ulong ;
pub type __fsword_t = :: std :: os :: raw :: c_long ;
pub type __ssize_t = :: std :: os :: raw :: c_long ;
pub type __syscall_slong_t = :: std :: os :: raw :: c_long ;
pub type __syscall_ulong_t = :: std :: os :: raw :: c_ulong ;
pub type __loff_t = __off64_t ;
pub type __caddr_t = * mut :: std :: os :: raw :: c_char ;
pub type __intptr_t = :: std :: os :: raw :: c_long ;
pub type __socklen_t = :: std :: os :: raw :: c_uint ;
pub type __sig_atomic_t = :: std :: os :: raw :: c_int ;
pub type u_char = __u_char ;
pub type u_short = __u_short ;
pub type u_int = __u_int ;
pub type u_long = __u_long ;
pub type quad_t = __quad_t ;
pub type u_quad_t = __u_quad_t ;
pub type fsid_t = __fsid_t ;
pub type loff_t = __loff_t ;
pub type ino_t = __ino_t ;
pub type dev_t = __dev_t ;
pub type gid_t = __gid_t ;
pub type mode_t = __mode_t ;
pub type nlink_t = __nlink_t ;
pub type uid_t = __uid_t ;
pub type off_t = __off_t ;
pub type pid_t = __pid_t ;
pub type id_t = __id_t ;
pub type ssize_t = __ssize_t ;
pub type daddr_t = __daddr_t ;
pub type caddr_t = __caddr_t ;
pub type key_t = __key_t ;
pub type clock_t = __clock_t ;
pub type clockid_t = __clockid_t ;
pub type time_t = __time_t ;
pub type timer_t = __timer_t ;
pub type ulong = :: std :: os :: raw :: c_ulong ;
pub type ushort = :: std :: os :: raw :: c_ushort ;
pub type uint = :: std :: os :: raw :: c_uint ;
pub type u_int8_t = :: std :: os :: raw :: c_uchar ;
pub type u_int16_t = :: std :: os :: raw :: c_ushort ;
pub type u_int32_t = :: std :: os :: raw :: c_uint ;
pub type u_int64_t = :: std :: os :: raw :: c_ulong ;
pub type register_t = :: std :: os :: raw :: c_long ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __sigset_t { pub __val : [:: std :: os :: raw :: c_ulong ;
16usize] , }
# [test] fn bindgen_test_layout___sigset_t () { assert_eq ! (:: std :: mem :: size_of :: < __sigset_t > () , 128usize , concat ! ("Size of: " , stringify ! (__sigset_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < __sigset_t > () , 8usize , concat ! ("Alignment of " , stringify ! (__sigset_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __sigset_t > ())) . __val as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__sigset_t) , "::" , stringify ! (__val))) ;
} pub type sigset_t = __sigset_t ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct timeval { pub tv_sec : __time_t , pub tv_usec : __suseconds_t , }
# [test] fn bindgen_test_layout_timeval () { assert_eq ! (:: std :: mem :: size_of :: < timeval > () , 16usize , concat ! ("Size of: " , stringify ! (timeval))) ;
assert_eq ! (:: std :: mem :: align_of :: < timeval > () , 8usize , concat ! ("Alignment of " , stringify ! (timeval))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < timeval > ())) . tv_sec as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (timeval) , "::" , stringify ! (tv_sec))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < timeval > ())) . tv_usec as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (timeval) , "::" , stringify ! (tv_usec))) ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct timespec { pub tv_sec : __time_t , pub tv_nsec : __syscall_slong_t , }
# [test] fn bindgen_test_layout_timespec () { assert_eq ! (:: std :: mem :: size_of :: < timespec > () , 16usize , concat ! ("Size of: " , stringify ! (timespec))) ;
assert_eq ! (:: std :: mem :: align_of :: < timespec > () , 8usize , concat ! ("Alignment of " , stringify ! (timespec))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < timespec > ())) . tv_sec as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (timespec) , "::" , stringify ! (tv_sec))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < timespec > ())) . tv_nsec as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (timespec) , "::" , stringify ! (tv_nsec))) ;
} pub type suseconds_t = __suseconds_t ;
pub type __fd_mask = :: std :: os :: raw :: c_long ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct fd_set { pub __fds_bits : [__fd_mask ;
16usize] , }
# [test] fn bindgen_test_layout_fd_set () { assert_eq ! (:: std :: mem :: size_of :: < fd_set > () , 128usize , concat ! ("Size of: " , stringify ! (fd_set))) ;
assert_eq ! (:: std :: mem :: align_of :: < fd_set > () , 8usize , concat ! ("Alignment of " , stringify ! (fd_set))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < fd_set > ())) . __fds_bits as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (fd_set) , "::" , stringify ! (__fds_bits))) ;
} pub type fd_mask = __fd_mask ;
extern "C" { pub fn select (__nfds : :: std :: os :: raw :: c_int , __readfds : * mut fd_set , __writefds : * mut fd_set , __exceptfds : * mut fd_set , __timeout : * mut timeval) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn pselect (__nfds : :: std :: os :: raw :: c_int , __readfds : * mut fd_set , __writefds : * mut fd_set , __exceptfds : * mut fd_set , __timeout : * const timespec , __sigmask : * const __sigset_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn gnu_dev_major (__dev : __dev_t) -> :: std :: os :: raw :: c_uint ;
} extern "C" { pub fn gnu_dev_minor (__dev : __dev_t) -> :: std :: os :: raw :: c_uint ;
} extern "C" { pub fn gnu_dev_makedev (__major : :: std :: os :: raw :: c_uint , __minor : :: std :: os :: raw :: c_uint) -> __dev_t ;
} pub type blksize_t = __blksize_t ;
pub type blkcnt_t = __blkcnt_t ;
pub type fsblkcnt_t = __fsblkcnt_t ;
pub type fsfilcnt_t = __fsfilcnt_t ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __pthread_rwlock_arch_t { pub __readers : :: std :: os :: raw :: c_uint , pub __writers : :: std :: os :: raw :: c_uint , pub __wrphase_futex : :: std :: os :: raw :: c_uint , pub __writers_futex : :: std :: os :: raw :: c_uint , pub __pad3 : :: std :: os :: raw :: c_uint , pub __pad4 : :: std :: os :: raw :: c_uint , pub __cur_writer : :: std :: os :: raw :: c_int , pub __shared : :: std :: os :: raw :: c_int , pub __rwelision : :: std :: os :: raw :: c_schar , pub __pad1 : [:: std :: os :: raw :: c_uchar ;
7usize] , pub __pad2 : :: std :: os :: raw :: c_ulong , pub __flags : :: std :: os :: raw :: c_uint , }
# [test] fn bindgen_test_layout___pthread_rwlock_arch_t () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_rwlock_arch_t > () , 56usize , concat ! ("Size of: " , stringify ! (__pthread_rwlock_arch_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_rwlock_arch_t > () , 8usize , concat ! ("Alignment of " , stringify ! (__pthread_rwlock_arch_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __readers as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__readers))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __writers as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__writers))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __wrphase_futex as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__wrphase_futex))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __writers_futex as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__writers_futex))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __pad3 as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__pad3))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __pad4 as * const _ as usize } , 20usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__pad4))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __cur_writer as * const _ as usize } , 24usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__cur_writer))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __shared as * const _ as usize } , 28usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__shared))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __rwelision as * const _ as usize } , 32usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__rwelision))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __pad1 as * const _ as usize } , 33usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__pad1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __pad2 as * const _ as usize } , 40usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__pad2))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_rwlock_arch_t > ())) . __flags as * const _ as usize } , 48usize , concat ! ("Offset of field: " , stringify ! (__pthread_rwlock_arch_t) , "::" , stringify ! (__flags))) ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __pthread_internal_list { pub __prev : * mut __pthread_internal_list , pub __next : * mut __pthread_internal_list , }
# [test] fn bindgen_test_layout___pthread_internal_list () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_internal_list > () , 16usize , concat ! ("Size of: " , stringify ! (__pthread_internal_list))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_internal_list > () , 8usize , concat ! ("Alignment of " , stringify ! (__pthread_internal_list))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_internal_list > ())) . __prev as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_internal_list) , "::" , stringify ! (__prev))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_internal_list > ())) . __next as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (__pthread_internal_list) , "::" , stringify ! (__next))) ;
} pub type __pthread_list_t = __pthread_internal_list ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __pthread_mutex_s { pub __lock : :: std :: os :: raw :: c_int , pub __count : :: std :: os :: raw :: c_uint , pub __owner : :: std :: os :: raw :: c_int , pub __nusers : :: std :: os :: raw :: c_uint , pub __kind : :: std :: os :: raw :: c_int , pub __spins : :: std :: os :: raw :: c_short , pub __elision : :: std :: os :: raw :: c_short , pub __list : __pthread_list_t , }
# [test] fn bindgen_test_layout___pthread_mutex_s () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_mutex_s > () , 40usize , concat ! ("Size of: " , stringify ! (__pthread_mutex_s))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_mutex_s > () , 8usize , concat ! ("Alignment of " , stringify ! (__pthread_mutex_s))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __lock as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__lock))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __count as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__count))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __owner as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__owner))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __nusers as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__nusers))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __kind as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__kind))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __spins as * const _ as usize } , 20usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__spins))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __elision as * const _ as usize } , 22usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__elision))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_mutex_s > ())) . __list as * const _ as usize } , 24usize , concat ! ("Offset of field: " , stringify ! (__pthread_mutex_s) , "::" , stringify ! (__list))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub struct __pthread_cond_s { pub __bindgen_anon_1 : __pthread_cond_s__bindgen_ty_1 , pub __bindgen_anon_2 : __pthread_cond_s__bindgen_ty_2 , pub __g_refs : [:: std :: os :: raw :: c_uint ;
2usize] , pub __g_size : [:: std :: os :: raw :: c_uint ;
2usize] , pub __g1_orig_size : :: std :: os :: raw :: c_uint , pub __wrefs : :: std :: os :: raw :: c_uint , pub __g_signals : [:: std :: os :: raw :: c_uint ;
2usize] , }
# [repr (C)]
# [derive (Copy , Clone)] pub union __pthread_cond_s__bindgen_ty_1 { pub __wseq : :: std :: os :: raw :: c_ulonglong , pub __wseq32 : __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 , _bindgen_union_align : u64 , }
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 { pub __low : :: std :: os :: raw :: c_uint , pub __high : :: std :: os :: raw :: c_uint , }
# [test] fn bindgen_test_layout___pthread_cond_s__bindgen_ty_1__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 > () , 8usize , concat ! ("Size of: " , stringify ! (__pthread_cond_s__bindgen_ty_1__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 > () , 4usize , concat ! ("Alignment of " , stringify ! (__pthread_cond_s__bindgen_ty_1__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 > ())) . __low as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_1__bindgen_ty_1) , "::" , stringify ! (__low))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 > ())) . __high as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_1__bindgen_ty_1) , "::" , stringify ! (__high))) ;
}
# [test] fn bindgen_test_layout___pthread_cond_s__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_cond_s__bindgen_ty_1 > () , 8usize , concat ! ("Size of: " , stringify ! (__pthread_cond_s__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_cond_s__bindgen_ty_1 > () , 8usize , concat ! ("Alignment of " , stringify ! (__pthread_cond_s__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_1 > ())) . __wseq as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_1) , "::" , stringify ! (__wseq))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_1 > ())) . __wseq32 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_1) , "::" , stringify ! (__wseq32))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union __pthread_cond_s__bindgen_ty_2 { pub __g1_start : :: std :: os :: raw :: c_ulonglong , pub __g1_start32 : __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 , _bindgen_union_align : u64 , }
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 { pub __low : :: std :: os :: raw :: c_uint , pub __high : :: std :: os :: raw :: c_uint , }
# [test] fn bindgen_test_layout___pthread_cond_s__bindgen_ty_2__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 > () , 8usize , concat ! ("Size of: " , stringify ! (__pthread_cond_s__bindgen_ty_2__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 > () , 4usize , concat ! ("Alignment of " , stringify ! (__pthread_cond_s__bindgen_ty_2__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 > ())) . __low as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_2__bindgen_ty_1) , "::" , stringify ! (__low))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 > ())) . __high as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_2__bindgen_ty_1) , "::" , stringify ! (__high))) ;
}
# [test] fn bindgen_test_layout___pthread_cond_s__bindgen_ty_2 () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_cond_s__bindgen_ty_2 > () , 8usize , concat ! ("Size of: " , stringify ! (__pthread_cond_s__bindgen_ty_2))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_cond_s__bindgen_ty_2 > () , 8usize , concat ! ("Alignment of " , stringify ! (__pthread_cond_s__bindgen_ty_2))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_2 > ())) . __g1_start as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_2) , "::" , stringify ! (__g1_start))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s__bindgen_ty_2 > ())) . __g1_start32 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s__bindgen_ty_2) , "::" , stringify ! (__g1_start32))) ;
}
# [test] fn bindgen_test_layout___pthread_cond_s () { assert_eq ! (:: std :: mem :: size_of :: < __pthread_cond_s > () , 48usize , concat ! ("Size of: " , stringify ! (__pthread_cond_s))) ;
assert_eq ! (:: std :: mem :: align_of :: < __pthread_cond_s > () , 8usize , concat ! ("Alignment of " , stringify ! (__pthread_cond_s))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s > ())) . __g_refs as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s) , "::" , stringify ! (__g_refs))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s > ())) . __g_size as * const _ as usize } , 24usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s) , "::" , stringify ! (__g_size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s > ())) . __g1_orig_size as * const _ as usize } , 32usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s) , "::" , stringify ! (__g1_orig_size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s > ())) . __wrefs as * const _ as usize } , 36usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s) , "::" , stringify ! (__wrefs))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < __pthread_cond_s > ())) . __g_signals as * const _ as usize } , 40usize , concat ! ("Offset of field: " , stringify ! (__pthread_cond_s) , "::" , stringify ! (__g_signals))) ;
} pub type pthread_t = :: std :: os :: raw :: c_ulong ;
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_mutexattr_t { pub __size : [:: std :: os :: raw :: c_char ;
4usize] , pub __align : :: std :: os :: raw :: c_int , _bindgen_union_align : u32 , }
# [test] fn bindgen_test_layout_pthread_mutexattr_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_mutexattr_t > () , 4usize , concat ! ("Size of: " , stringify ! (pthread_mutexattr_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_mutexattr_t > () , 4usize , concat ! ("Alignment of " , stringify ! (pthread_mutexattr_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_mutexattr_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_mutexattr_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_mutexattr_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_mutexattr_t) , "::" , stringify ! (__align))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_condattr_t { pub __size : [:: std :: os :: raw :: c_char ;
4usize] , pub __align : :: std :: os :: raw :: c_int , _bindgen_union_align : u32 , }
# [test] fn bindgen_test_layout_pthread_condattr_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_condattr_t > () , 4usize , concat ! ("Size of: " , stringify ! (pthread_condattr_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_condattr_t > () , 4usize , concat ! ("Alignment of " , stringify ! (pthread_condattr_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_condattr_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_condattr_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_condattr_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_condattr_t) , "::" , stringify ! (__align))) ;
} pub type pthread_key_t = :: std :: os :: raw :: c_uint ;
pub type pthread_once_t = :: std :: os :: raw :: c_int ;
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_attr_t { pub __size : [:: std :: os :: raw :: c_char ;
56usize] , pub __align : :: std :: os :: raw :: c_long , _bindgen_union_align : [u64 ;
7usize] , }
# [test] fn bindgen_test_layout_pthread_attr_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_attr_t > () , 56usize , concat ! ("Size of: " , stringify ! (pthread_attr_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_attr_t > () , 8usize , concat ! ("Alignment of " , stringify ! (pthread_attr_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_attr_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_attr_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_attr_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_attr_t) , "::" , stringify ! (__align))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_mutex_t { pub __data : __pthread_mutex_s , pub __size : [:: std :: os :: raw :: c_char ;
40usize] , pub __align : :: std :: os :: raw :: c_long , _bindgen_union_align : [u64 ;
5usize] , }
# [test] fn bindgen_test_layout_pthread_mutex_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_mutex_t > () , 40usize , concat ! ("Size of: " , stringify ! (pthread_mutex_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_mutex_t > () , 8usize , concat ! ("Alignment of " , stringify ! (pthread_mutex_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_mutex_t > ())) . __data as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_mutex_t) , "::" , stringify ! (__data))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_mutex_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_mutex_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_mutex_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_mutex_t) , "::" , stringify ! (__align))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_cond_t { pub __data : __pthread_cond_s , pub __size : [:: std :: os :: raw :: c_char ;
48usize] , pub __align : :: std :: os :: raw :: c_longlong , _bindgen_union_align : [u64 ;
6usize] , }
# [test] fn bindgen_test_layout_pthread_cond_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_cond_t > () , 48usize , concat ! ("Size of: " , stringify ! (pthread_cond_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_cond_t > () , 8usize , concat ! ("Alignment of " , stringify ! (pthread_cond_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_cond_t > ())) . __data as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_cond_t) , "::" , stringify ! (__data))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_cond_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_cond_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_cond_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_cond_t) , "::" , stringify ! (__align))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_rwlock_t { pub __data : __pthread_rwlock_arch_t , pub __size : [:: std :: os :: raw :: c_char ;
56usize] , pub __align : :: std :: os :: raw :: c_long , _bindgen_union_align : [u64 ;
7usize] , }
# [test] fn bindgen_test_layout_pthread_rwlock_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_rwlock_t > () , 56usize , concat ! ("Size of: " , stringify ! (pthread_rwlock_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_rwlock_t > () , 8usize , concat ! ("Alignment of " , stringify ! (pthread_rwlock_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_rwlock_t > ())) . __data as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_rwlock_t) , "::" , stringify ! (__data))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_rwlock_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_rwlock_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_rwlock_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_rwlock_t) , "::" , stringify ! (__align))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_rwlockattr_t { pub __size : [:: std :: os :: raw :: c_char ;
8usize] , pub __align : :: std :: os :: raw :: c_long , _bindgen_union_align : u64 , }
# [test] fn bindgen_test_layout_pthread_rwlockattr_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_rwlockattr_t > () , 8usize , concat ! ("Size of: " , stringify ! (pthread_rwlockattr_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_rwlockattr_t > () , 8usize , concat ! ("Alignment of " , stringify ! (pthread_rwlockattr_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_rwlockattr_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_rwlockattr_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_rwlockattr_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_rwlockattr_t) , "::" , stringify ! (__align))) ;
} pub type pthread_spinlock_t = :: std :: os :: raw :: c_int ;
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_barrier_t { pub __size : [:: std :: os :: raw :: c_char ;
32usize] , pub __align : :: std :: os :: raw :: c_long , _bindgen_union_align : [u64 ;
4usize] , }
# [test] fn bindgen_test_layout_pthread_barrier_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_barrier_t > () , 32usize , concat ! ("Size of: " , stringify ! (pthread_barrier_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_barrier_t > () , 8usize , concat ! ("Alignment of " , stringify ! (pthread_barrier_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_barrier_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_barrier_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_barrier_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_barrier_t) , "::" , stringify ! (__align))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union pthread_barrierattr_t { pub __size : [:: std :: os :: raw :: c_char ;
4usize] , pub __align : :: std :: os :: raw :: c_int , _bindgen_union_align : u32 , }
# [test] fn bindgen_test_layout_pthread_barrierattr_t () { assert_eq ! (:: std :: mem :: size_of :: < pthread_barrierattr_t > () , 4usize , concat ! ("Size of: " , stringify ! (pthread_barrierattr_t))) ;
assert_eq ! (:: std :: mem :: align_of :: < pthread_barrierattr_t > () , 4usize , concat ! ("Alignment of " , stringify ! (pthread_barrierattr_t))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_barrierattr_t > ())) . __size as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_barrierattr_t) , "::" , stringify ! (__size))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < pthread_barrierattr_t > ())) . __align as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (pthread_barrierattr_t) , "::" , stringify ! (__align))) ;
} extern "C" { pub fn random () -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn srandom (__seed : :: std :: os :: raw :: c_uint) ;
} extern "C" { pub fn initstate (__seed : :: std :: os :: raw :: c_uint , __statebuf : * mut :: std :: os :: raw :: c_char , __statelen : size_t) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn setstate (__statebuf : * mut :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct random_data { pub fptr : * mut i32 , pub rptr : * mut i32 , pub state : * mut i32 , pub rand_type : :: std :: os :: raw :: c_int , pub rand_deg : :: std :: os :: raw :: c_int , pub rand_sep : :: std :: os :: raw :: c_int , pub end_ptr : * mut i32 , }
# [test] fn bindgen_test_layout_random_data () { assert_eq ! (:: std :: mem :: size_of :: < random_data > () , 48usize , concat ! ("Size of: " , stringify ! (random_data))) ;
assert_eq ! (:: std :: mem :: align_of :: < random_data > () , 8usize , concat ! ("Alignment of " , stringify ! (random_data))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . fptr as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (fptr))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . rptr as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (rptr))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . state as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (state))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . rand_type as * const _ as usize } , 24usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (rand_type))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . rand_deg as * const _ as usize } , 28usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (rand_deg))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . rand_sep as * const _ as usize } , 32usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (rand_sep))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < random_data > ())) . end_ptr as * const _ as usize } , 40usize , concat ! ("Offset of field: " , stringify ! (random_data) , "::" , stringify ! (end_ptr))) ;
} extern "C" { pub fn random_r (__buf : * mut random_data , __result : * mut i32) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn srandom_r (__seed : :: std :: os :: raw :: c_uint , __buf : * mut random_data) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn initstate_r (__seed : :: std :: os :: raw :: c_uint , __statebuf : * mut :: std :: os :: raw :: c_char , __statelen : size_t , __buf : * mut random_data) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn setstate_r (__statebuf : * mut :: std :: os :: raw :: c_char , __buf : * mut random_data) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn rand () -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn srand (__seed : :: std :: os :: raw :: c_uint) ;
} extern "C" { pub fn rand_r (__seed : * mut :: std :: os :: raw :: c_uint) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn drand48 () -> f64 ;
} extern "C" { pub fn erand48 (__xsubi : * mut :: std :: os :: raw :: c_ushort) -> f64 ;
} extern "C" { pub fn lrand48 () -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn nrand48 (__xsubi : * mut :: std :: os :: raw :: c_ushort) -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn mrand48 () -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn jrand48 (__xsubi : * mut :: std :: os :: raw :: c_ushort) -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn srand48 (__seedval : :: std :: os :: raw :: c_long) ;
} extern "C" { pub fn seed48 (__seed16v : * mut :: std :: os :: raw :: c_ushort) -> * mut :: std :: os :: raw :: c_ushort ;
} extern "C" { pub fn lcong48 (__param : * mut :: std :: os :: raw :: c_ushort) ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct drand48_data { pub __x : [:: std :: os :: raw :: c_ushort ;
3usize] , pub __old_x : [:: std :: os :: raw :: c_ushort ;
3usize] , pub __c : :: std :: os :: raw :: c_ushort , pub __init : :: std :: os :: raw :: c_ushort , pub __a : :: std :: os :: raw :: c_ulonglong , }
# [test] fn bindgen_test_layout_drand48_data () { assert_eq ! (:: std :: mem :: size_of :: < drand48_data > () , 24usize , concat ! ("Size of: " , stringify ! (drand48_data))) ;
assert_eq ! (:: std :: mem :: align_of :: < drand48_data > () , 8usize , concat ! ("Alignment of " , stringify ! (drand48_data))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < drand48_data > ())) . __x as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (drand48_data) , "::" , stringify ! (__x))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < drand48_data > ())) . __old_x as * const _ as usize } , 6usize , concat ! ("Offset of field: " , stringify ! (drand48_data) , "::" , stringify ! (__old_x))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < drand48_data > ())) . __c as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (drand48_data) , "::" , stringify ! (__c))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < drand48_data > ())) . __init as * const _ as usize } , 14usize , concat ! ("Offset of field: " , stringify ! (drand48_data) , "::" , stringify ! (__init))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < drand48_data > ())) . __a as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (drand48_data) , "::" , stringify ! (__a))) ;
} extern "C" { pub fn drand48_r (__buffer : * mut drand48_data , __result : * mut f64) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn erand48_r (__xsubi : * mut :: std :: os :: raw :: c_ushort , __buffer : * mut drand48_data , __result : * mut f64) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn lrand48_r (__buffer : * mut drand48_data , __result : * mut :: std :: os :: raw :: c_long) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn nrand48_r (__xsubi : * mut :: std :: os :: raw :: c_ushort , __buffer : * mut drand48_data , __result : * mut :: std :: os :: raw :: c_long) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mrand48_r (__buffer : * mut drand48_data , __result : * mut :: std :: os :: raw :: c_long) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn jrand48_r (__xsubi : * mut :: std :: os :: raw :: c_ushort , __buffer : * mut drand48_data , __result : * mut :: std :: os :: raw :: c_long) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn srand48_r (__seedval : :: std :: os :: raw :: c_long , __buffer : * mut drand48_data) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn seed48_r (__seed16v : * mut :: std :: os :: raw :: c_ushort , __buffer : * mut drand48_data) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn lcong48_r (__param : * mut :: std :: os :: raw :: c_ushort , __buffer : * mut drand48_data) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn malloc (__size : :: std :: os :: raw :: c_ulong) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn calloc (__nmemb : :: std :: os :: raw :: c_ulong , __size : :: std :: os :: raw :: c_ulong) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn realloc (__ptr : * mut :: std :: os :: raw :: c_void , __size : :: std :: os :: raw :: c_ulong) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn free (__ptr : * mut :: std :: os :: raw :: c_void) ;
} extern "C" { pub fn alloca (__size : :: std :: os :: raw :: c_ulong) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn valloc (__size : size_t) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn posix_memalign (__memptr : * mut * mut :: std :: os :: raw :: c_void , __alignment : size_t , __size : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn aligned_alloc (__alignment : size_t , __size : size_t) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn abort () ;
} extern "C" { pub fn atexit (__func : :: std :: option :: Option < unsafe extern "C" fn () >) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn at_quick_exit (__func : :: std :: option :: Option < unsafe extern "C" fn () >) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn on_exit (__func : :: std :: option :: Option < unsafe extern "C" fn (__status : :: std :: os :: raw :: c_int , __arg : * mut :: std :: os :: raw :: c_void) > , __arg : * mut :: std :: os :: raw :: c_void) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn exit (__status : :: std :: os :: raw :: c_int) ;
} extern "C" { pub fn quick_exit (__status : :: std :: os :: raw :: c_int) ;
} extern "C" { pub fn _Exit (__status : :: std :: os :: raw :: c_int) ;
} extern "C" { pub fn getenv (__name : * const :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn putenv (__string : * mut :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn setenv (__name : * const :: std :: os :: raw :: c_char , __value : * const :: std :: os :: raw :: c_char , __replace : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn unsetenv (__name : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn clearenv () -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mktemp (__template : * mut :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn mkstemp (__template : * mut :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mkstemps (__template : * mut :: std :: os :: raw :: c_char , __suffixlen : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mkdtemp (__template : * mut :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn system (__command : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn realpath (__name : * const :: std :: os :: raw :: c_char , __resolved : * mut :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
} pub type __compar_fn_t = :: std :: option :: Option < unsafe extern "C" fn (arg1 : * const :: std :: os :: raw :: c_void , arg2 : * const :: std :: os :: raw :: c_void) -> :: std :: os :: raw :: c_int > ;
extern "C" { pub fn bsearch (__key : * const :: std :: os :: raw :: c_void , __base : * const :: std :: os :: raw :: c_void , __nmemb : size_t , __size : size_t , __compar : __compar_fn_t) -> * mut :: std :: os :: raw :: c_void ;
} extern "C" { pub fn qsort (__base : * mut :: std :: os :: raw :: c_void , __nmemb : size_t , __size : size_t , __compar : __compar_fn_t) ;
} extern "C" { pub fn abs (__x : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn labs (__x : :: std :: os :: raw :: c_long) -> :: std :: os :: raw :: c_long ;
} extern "C" { pub fn llabs (__x : :: std :: os :: raw :: c_longlong) -> :: std :: os :: raw :: c_longlong ;
} extern "C" { pub fn div (__numer : :: std :: os :: raw :: c_int , __denom : :: std :: os :: raw :: c_int) -> div_t ;
} extern "C" { pub fn ldiv (__numer : :: std :: os :: raw :: c_long , __denom : :: std :: os :: raw :: c_long) -> ldiv_t ;
} extern "C" { pub fn lldiv (__numer : :: std :: os :: raw :: c_longlong , __denom : :: std :: os :: raw :: c_longlong) -> lldiv_t ;
} extern "C" { pub fn ecvt (__value : f64 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn fcvt (__value : f64 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn gcvt (__value : f64 , __ndigit : :: std :: os :: raw :: c_int , __buf : * mut :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn qecvt (__value : u128 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn qfcvt (__value : u128 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn qgcvt (__value : u128 , __ndigit : :: std :: os :: raw :: c_int , __buf : * mut :: std :: os :: raw :: c_char) -> * mut :: std :: os :: raw :: c_char ;
} extern "C" { pub fn ecvt_r (__value : f64 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int , __buf : * mut :: std :: os :: raw :: c_char , __len : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn fcvt_r (__value : f64 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int , __buf : * mut :: std :: os :: raw :: c_char , __len : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn qecvt_r (__value : u128 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int , __buf : * mut :: std :: os :: raw :: c_char , __len : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn qfcvt_r (__value : u128 , __ndigit : :: std :: os :: raw :: c_int , __decpt : * mut :: std :: os :: raw :: c_int , __sign : * mut :: std :: os :: raw :: c_int , __buf : * mut :: std :: os :: raw :: c_char , __len : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mblen (__s : * const :: std :: os :: raw :: c_char , __n : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mbtowc (__pwc : * mut wchar_t , __s : * const :: std :: os :: raw :: c_char , __n : size_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn wctomb (__s : * mut :: std :: os :: raw :: c_char , __wchar : wchar_t) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn mbstowcs (__pwcs : * mut wchar_t , __s : * const :: std :: os :: raw :: c_char , __n : size_t) -> size_t ;
} extern "C" { pub fn wcstombs (__s : * mut :: std :: os :: raw :: c_char , __pwcs : * const wchar_t , __n : size_t) -> size_t ;
} extern "C" { pub fn rpmatch (__response : * const :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn getsubopt (__optionp : * mut * mut :: std :: os :: raw :: c_char , __tokens : * const * mut :: std :: os :: raw :: c_char , __valuep : * mut * mut :: std :: os :: raw :: c_char) -> :: std :: os :: raw :: c_int ;
} extern "C" { pub fn getloadavg (__loadavg : * mut f64 , __nelem : :: std :: os :: raw :: c_int) -> :: std :: os :: raw :: c_int ;
} pub type SCHAR = :: std :: os :: raw :: c_schar ;
pub type UCHAR = :: std :: os :: raw :: c_uchar ;
pub type SWORD = :: std :: os :: raw :: c_short ;
pub type USHORT = :: std :: os :: raw :: c_ushort ;
pub type SSHORT = :: std :: os :: raw :: c_short ;
pub type UWORD = :: std :: os :: raw :: c_ushort ;
pub type SDWORD = sqlint32 ;
pub type ULONG = sqluint32 ;
pub type UDWORD = sqluint32 ;
pub type SLONG = sqlint32 ;
pub type SDOUBLE = f64 ;
pub type SFLOAT = f32 ;
pub type SQLDATE = :: std :: os :: raw :: c_uchar ;
pub type SQLTIME = :: std :: os :: raw :: c_uchar ;
pub type SQLTIMESTAMP = :: std :: os :: raw :: c_uchar ;
pub type SQLDECIMAL = :: std :: os :: raw :: c_uchar ;
pub type SQLNUMERIC = :: std :: os :: raw :: c_uchar ;
pub type LDOUBLE = f64 ;
pub type PTR = * mut :: std :: os :: raw :: c_void ;
pub type HENV = * mut :: std :: os :: raw :: c_void ;
pub type HDBC = * mut :: std :: os :: raw :: c_void ;
pub type HSTMT = * mut :: std :: os :: raw :: c_void ;
pub type RETCODE = :: std :: os :: raw :: c_short ;
pub type SQLCHAR = UCHAR ;
pub type SQLVARCHAR = UCHAR ;
pub type SQLSCHAR = SCHAR ;
pub type SQLINTEGER = SDWORD ;
pub type SQLSMALLINT = SWORD ;
pub type SQLDOUBLE = SDOUBLE ;
pub type SQLFLOAT = SDOUBLE ;
pub type SQLREAL = SFLOAT ;
pub type SQLRETURN = SQLSMALLINT ;
pub type SQLUINTEGER = UDWORD ;
pub type SQLUSMALLINT = UWORD ;
pub type SQLPOINTER = PTR ;
pub type SQLDBCHAR = :: std :: os :: raw :: c_ushort ;
pub type SQLWCHAR = :: std :: os :: raw :: c_ushort ;
pub type SQLTCHAR = SQLCHAR ;
pub type SQLHANDLE = SQLINTEGER ;
pub type SQLHENV = SQLINTEGER ;
pub type SQLHDBC = SQLINTEGER ;
pub type SQLHSTMT = SQLINTEGER ;
pub type SQLHWND = SQLPOINTER ;
pub type SQLHDESC = SQLHANDLE ;
pub type SQLBIGINT = :: std :: os :: raw :: c_long ;
pub type SQLUBIGINT = :: std :: os :: raw :: c_ulong ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct DATE_STRUCT { pub year : SQLSMALLINT , pub month : SQLUSMALLINT , pub day : SQLUSMALLINT , }
# [test] fn bindgen_test_layout_DATE_STRUCT () { assert_eq ! (:: std :: mem :: size_of :: < DATE_STRUCT > () , 6usize , concat ! ("Size of: " , stringify ! (DATE_STRUCT))) ;
assert_eq ! (:: std :: mem :: align_of :: < DATE_STRUCT > () , 2usize , concat ! ("Alignment of " , stringify ! (DATE_STRUCT))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < DATE_STRUCT > ())) . year as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (DATE_STRUCT) , "::" , stringify ! (year))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < DATE_STRUCT > ())) . month as * const _ as usize } , 2usize , concat ! ("Offset of field: " , stringify ! (DATE_STRUCT) , "::" , stringify ! (month))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < DATE_STRUCT > ())) . day as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (DATE_STRUCT) , "::" , stringify ! (day))) ;
} pub type SQL_DATE_STRUCT = DATE_STRUCT ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct TIME_STRUCT { pub hour : SQLUSMALLINT , pub minute : SQLUSMALLINT , pub second : SQLUSMALLINT , }
# [test] fn bindgen_test_layout_TIME_STRUCT () { assert_eq ! (:: std :: mem :: size_of :: < TIME_STRUCT > () , 6usize , concat ! ("Size of: " , stringify ! (TIME_STRUCT))) ;
assert_eq ! (:: std :: mem :: align_of :: < TIME_STRUCT > () , 2usize , concat ! ("Alignment of " , stringify ! (TIME_STRUCT))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIME_STRUCT > ())) . hour as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (TIME_STRUCT) , "::" , stringify ! (hour))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIME_STRUCT > ())) . minute as * const _ as usize } , 2usize , concat ! ("Offset of field: " , stringify ! (TIME_STRUCT) , "::" , stringify ! (minute))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIME_STRUCT > ())) . second as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (TIME_STRUCT) , "::" , stringify ! (second))) ;
} pub type SQL_TIME_STRUCT = TIME_STRUCT ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct TIMESTAMP_STRUCT { pub year : SQLSMALLINT , pub month : SQLUSMALLINT , pub day : SQLUSMALLINT , pub hour : SQLUSMALLINT , pub minute : SQLUSMALLINT , pub second : SQLUSMALLINT , pub fraction : SQLUINTEGER , }
# [test] fn bindgen_test_layout_TIMESTAMP_STRUCT () { assert_eq ! (:: std :: mem :: size_of :: < TIMESTAMP_STRUCT > () , 16usize , concat ! ("Size of: " , stringify ! (TIMESTAMP_STRUCT))) ;
assert_eq ! (:: std :: mem :: align_of :: < TIMESTAMP_STRUCT > () , 4usize , concat ! ("Alignment of " , stringify ! (TIMESTAMP_STRUCT))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . year as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (year))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . month as * const _ as usize } , 2usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (month))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . day as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (day))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . hour as * const _ as usize } , 6usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (hour))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . minute as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (minute))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . second as * const _ as usize } , 10usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (second))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT > ())) . fraction as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT) , "::" , stringify ! (fraction))) ;
} pub type SQL_TIMESTAMP_STRUCT = TIMESTAMP_STRUCT ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct TIMESTAMP_STRUCT_EXT { pub year : SQLSMALLINT , pub month : SQLUSMALLINT , pub day : SQLUSMALLINT , pub hour : SQLUSMALLINT , pub minute : SQLUSMALLINT , pub second : SQLUSMALLINT , pub fraction : SQLUINTEGER , pub fraction2 : SQLUINTEGER , }
# [test] fn bindgen_test_layout_TIMESTAMP_STRUCT_EXT () { assert_eq ! (:: std :: mem :: size_of :: < TIMESTAMP_STRUCT_EXT > () , 20usize , concat ! ("Size of: " , stringify ! (TIMESTAMP_STRUCT_EXT))) ;
assert_eq ! (:: std :: mem :: align_of :: < TIMESTAMP_STRUCT_EXT > () , 4usize , concat ! ("Alignment of " , stringify ! (TIMESTAMP_STRUCT_EXT))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . year as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (year))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . month as * const _ as usize } , 2usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (month))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . day as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (day))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . hour as * const _ as usize } , 6usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (hour))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . minute as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (minute))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . second as * const _ as usize } , 10usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (second))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . fraction as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (fraction))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT > ())) . fraction2 as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT) , "::" , stringify ! (fraction2))) ;
} pub type SQL_TIMESTAMP_STRUCT_EXT = TIMESTAMP_STRUCT_EXT ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct TIMESTAMP_STRUCT_EXT_TZ { pub year : SQLSMALLINT , pub month : SQLUSMALLINT , pub day : SQLUSMALLINT , pub hour : SQLUSMALLINT , pub minute : SQLUSMALLINT , pub second : SQLUSMALLINT , pub fraction : SQLUINTEGER , pub fraction2 : SQLUINTEGER , pub timezone_hour : SQLSMALLINT , pub timezone_minute : SQLSMALLINT , }
# [test] fn bindgen_test_layout_TIMESTAMP_STRUCT_EXT_TZ () { assert_eq ! (:: std :: mem :: size_of :: < TIMESTAMP_STRUCT_EXT_TZ > () , 24usize , concat ! ("Size of: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ))) ;
assert_eq ! (:: std :: mem :: align_of :: < TIMESTAMP_STRUCT_EXT_TZ > () , 4usize , concat ! ("Alignment of " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . year as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (year))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . month as * const _ as usize } , 2usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (month))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . day as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (day))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . hour as * const _ as usize } , 6usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (hour))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . minute as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (minute))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . second as * const _ as usize } , 10usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (second))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . fraction as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (fraction))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . fraction2 as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (fraction2))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . timezone_hour as * const _ as usize } , 20usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (timezone_hour))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < TIMESTAMP_STRUCT_EXT_TZ > ())) . timezone_minute as * const _ as usize } , 22usize , concat ! ("Offset of field: " , stringify ! (TIMESTAMP_STRUCT_EXT_TZ) , "::" , stringify ! (timezone_minute))) ;
} pub type SQL_TIMESTAMP_STRUCT_EXT_TZ = TIMESTAMP_STRUCT_EXT_TZ ;
pub const SQLINTERVAL_SQL_IS_YEAR : SQLINTERVAL = 1 ;
pub const SQLINTERVAL_SQL_IS_MONTH : SQLINTERVAL = 2 ;
pub const SQLINTERVAL_SQL_IS_DAY : SQLINTERVAL = 3 ;
pub const SQLINTERVAL_SQL_IS_HOUR : SQLINTERVAL = 4 ;
pub const SQLINTERVAL_SQL_IS_MINUTE : SQLINTERVAL = 5 ;
pub const SQLINTERVAL_SQL_IS_SECOND : SQLINTERVAL = 6 ;
pub const SQLINTERVAL_SQL_IS_YEAR_TO_MONTH : SQLINTERVAL = 7 ;
pub const SQLINTERVAL_SQL_IS_DAY_TO_HOUR : SQLINTERVAL = 8 ;
pub const SQLINTERVAL_SQL_IS_DAY_TO_MINUTE : SQLINTERVAL = 9 ;
pub const SQLINTERVAL_SQL_IS_DAY_TO_SECOND : SQLINTERVAL = 10 ;
pub const SQLINTERVAL_SQL_IS_HOUR_TO_MINUTE : SQLINTERVAL = 11 ;
pub const SQLINTERVAL_SQL_IS_HOUR_TO_SECOND : SQLINTERVAL = 12 ;
pub const SQLINTERVAL_SQL_IS_MINUTE_TO_SECOND : SQLINTERVAL = 13 ;
pub type SQLINTERVAL = :: std :: os :: raw :: c_uint ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct tagSQL_YEAR_MONTH { pub year : SQLUINTEGER , pub month : SQLUINTEGER , }
# [test] fn bindgen_test_layout_tagSQL_YEAR_MONTH () { assert_eq ! (:: std :: mem :: size_of :: < tagSQL_YEAR_MONTH > () , 8usize , concat ! ("Size of: " , stringify ! (tagSQL_YEAR_MONTH))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagSQL_YEAR_MONTH > () , 4usize , concat ! ("Alignment of " , stringify ! (tagSQL_YEAR_MONTH))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_YEAR_MONTH > ())) . year as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagSQL_YEAR_MONTH) , "::" , stringify ! (year))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_YEAR_MONTH > ())) . month as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (tagSQL_YEAR_MONTH) , "::" , stringify ! (month))) ;
} pub type SQL_YEAR_MONTH_STRUCT = tagSQL_YEAR_MONTH ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct tagSQL_DAY_SECOND { pub day : SQLUINTEGER , pub hour : SQLUINTEGER , pub minute : SQLUINTEGER , pub second : SQLUINTEGER , pub fraction : SQLUINTEGER , }
# [test] fn bindgen_test_layout_tagSQL_DAY_SECOND () { assert_eq ! (:: std :: mem :: size_of :: < tagSQL_DAY_SECOND > () , 20usize , concat ! ("Size of: " , stringify ! (tagSQL_DAY_SECOND))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagSQL_DAY_SECOND > () , 4usize , concat ! ("Alignment of " , stringify ! (tagSQL_DAY_SECOND))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_DAY_SECOND > ())) . day as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagSQL_DAY_SECOND) , "::" , stringify ! (day))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_DAY_SECOND > ())) . hour as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (tagSQL_DAY_SECOND) , "::" , stringify ! (hour))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_DAY_SECOND > ())) . minute as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (tagSQL_DAY_SECOND) , "::" , stringify ! (minute))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_DAY_SECOND > ())) . second as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (tagSQL_DAY_SECOND) , "::" , stringify ! (second))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_DAY_SECOND > ())) . fraction as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (tagSQL_DAY_SECOND) , "::" , stringify ! (fraction))) ;
} pub type SQL_DAY_SECOND_STRUCT = tagSQL_DAY_SECOND ;
# [repr (C)]
# [derive (Copy , Clone)] pub struct tagSQL_INTERVAL_STRUCT { pub interval_type : SQLINTERVAL , pub interval_sign : SQLSMALLINT , pub intval : tagSQL_INTERVAL_STRUCT__bindgen_ty_1 , }
# [repr (C)]
# [derive (Copy , Clone)] pub union tagSQL_INTERVAL_STRUCT__bindgen_ty_1 { pub year_month : SQL_YEAR_MONTH_STRUCT , pub day_second : SQL_DAY_SECOND_STRUCT , _bindgen_union_align : [u32 ;
5usize] , }
# [test] fn bindgen_test_layout_tagSQL_INTERVAL_STRUCT__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < tagSQL_INTERVAL_STRUCT__bindgen_ty_1 > () , 20usize , concat ! ("Size of: " , stringify ! (tagSQL_INTERVAL_STRUCT__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagSQL_INTERVAL_STRUCT__bindgen_ty_1 > () , 4usize , concat ! ("Alignment of " , stringify ! (tagSQL_INTERVAL_STRUCT__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_INTERVAL_STRUCT__bindgen_ty_1 > ())) . year_month as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagSQL_INTERVAL_STRUCT__bindgen_ty_1) , "::" , stringify ! (year_month))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_INTERVAL_STRUCT__bindgen_ty_1 > ())) . day_second as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagSQL_INTERVAL_STRUCT__bindgen_ty_1) , "::" , stringify ! (day_second))) ;
}
# [test] fn bindgen_test_layout_tagSQL_INTERVAL_STRUCT () { assert_eq ! (:: std :: mem :: size_of :: < tagSQL_INTERVAL_STRUCT > () , 28usize , concat ! ("Size of: " , stringify ! (tagSQL_INTERVAL_STRUCT))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagSQL_INTERVAL_STRUCT > () , 4usize , concat ! ("Alignment of " , stringify ! (tagSQL_INTERVAL_STRUCT))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_INTERVAL_STRUCT > ())) . interval_type as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagSQL_INTERVAL_STRUCT) , "::" , stringify ! (interval_type))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_INTERVAL_STRUCT > ())) . interval_sign as * const _ as usize } , 4usize , concat ! ("Offset of field: " , stringify ! (tagSQL_INTERVAL_STRUCT) , "::" , stringify ! (interval_sign))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_INTERVAL_STRUCT > ())) . intval as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (tagSQL_INTERVAL_STRUCT) , "::" , stringify ! (intval))) ;
} pub type SQL_INTERVAL_STRUCT = tagSQL_INTERVAL_STRUCT ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct tagSQL_NUMERIC_STRUCT { pub precision : SQLCHAR , pub scale : SQLSCHAR , pub sign : SQLCHAR , pub val : [SQLCHAR ;
16usize] , }
# [test] fn bindgen_test_layout_tagSQL_NUMERIC_STRUCT () { assert_eq ! (:: std :: mem :: size_of :: < tagSQL_NUMERIC_STRUCT > () , 19usize , concat ! ("Size of: " , stringify ! (tagSQL_NUMERIC_STRUCT))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagSQL_NUMERIC_STRUCT > () , 1usize , concat ! ("Alignment of " , stringify ! (tagSQL_NUMERIC_STRUCT))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_NUMERIC_STRUCT > ())) . precision as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagSQL_NUMERIC_STRUCT) , "::" , stringify ! (precision))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_NUMERIC_STRUCT > ())) . scale as * const _ as usize } , 1usize , concat ! ("Offset of field: " , stringify ! (tagSQL_NUMERIC_STRUCT) , "::" , stringify ! (scale))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_NUMERIC_STRUCT > ())) . sign as * const _ as usize } , 2usize , concat ! ("Offset of field: " , stringify ! (tagSQL_NUMERIC_STRUCT) , "::" , stringify ! (sign))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagSQL_NUMERIC_STRUCT > ())) . val as * const _ as usize } , 3usize , concat ! ("Offset of field: " , stringify ! (tagSQL_NUMERIC_STRUCT) , "::" , stringify ! (val))) ;
} pub type SQL_NUMERIC_STRUCT = tagSQL_NUMERIC_STRUCT ;
# [repr (C)]
# [derive (Copy , Clone)] pub struct SQLDECIMAL64 { pub udec64 : SQLDECIMAL64__bindgen_ty_1 , }
# [repr (C)]
# [derive (Copy , Clone)] pub union SQLDECIMAL64__bindgen_ty_1 { pub dummy : SQLDOUBLE , pub dec64 : [SQLCHAR ;
8usize] , _bindgen_union_align : u64 , }
# [test] fn bindgen_test_layout_SQLDECIMAL64__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < SQLDECIMAL64__bindgen_ty_1 > () , 8usize , concat ! ("Size of: " , stringify ! (SQLDECIMAL64__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < SQLDECIMAL64__bindgen_ty_1 > () , 8usize , concat ! ("Alignment of " , stringify ! (SQLDECIMAL64__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQLDECIMAL64__bindgen_ty_1 > ())) . dummy as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQLDECIMAL64__bindgen_ty_1) , "::" , stringify ! (dummy))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQLDECIMAL64__bindgen_ty_1 > ())) . dec64 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQLDECIMAL64__bindgen_ty_1) , "::" , stringify ! (dec64))) ;
}
# [test] fn bindgen_test_layout_SQLDECIMAL64 () { assert_eq ! (:: std :: mem :: size_of :: < SQLDECIMAL64 > () , 8usize , concat ! ("Size of: " , stringify ! (SQLDECIMAL64))) ;
assert_eq ! (:: std :: mem :: align_of :: < SQLDECIMAL64 > () , 8usize , concat ! ("Alignment of " , stringify ! (SQLDECIMAL64))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQLDECIMAL64 > ())) . udec64 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQLDECIMAL64) , "::" , stringify ! (udec64))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub struct SQLDECIMAL128 { pub udec128 : SQLDECIMAL128__bindgen_ty_1 , }
# [repr (C)]
# [derive (Copy , Clone)] pub union SQLDECIMAL128__bindgen_ty_1 { pub dummy : SQLDOUBLE , pub dec128 : [SQLCHAR ;
16usize] , _bindgen_union_align : [u64 ;
2usize] , }
# [test] fn bindgen_test_layout_SQLDECIMAL128__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < SQLDECIMAL128__bindgen_ty_1 > () , 16usize , concat ! ("Size of: " , stringify ! (SQLDECIMAL128__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < SQLDECIMAL128__bindgen_ty_1 > () , 8usize , concat ! ("Alignment of " , stringify ! (SQLDECIMAL128__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQLDECIMAL128__bindgen_ty_1 > ())) . dummy as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQLDECIMAL128__bindgen_ty_1) , "::" , stringify ! (dummy))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQLDECIMAL128__bindgen_ty_1 > ())) . dec128 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQLDECIMAL128__bindgen_ty_1) , "::" , stringify ! (dec128))) ;
}
# [test] fn bindgen_test_layout_SQLDECIMAL128 () { assert_eq ! (:: std :: mem :: size_of :: < SQLDECIMAL128 > () , 16usize , concat ! ("Size of: " , stringify ! (SQLDECIMAL128))) ;
assert_eq ! (:: std :: mem :: align_of :: < SQLDECIMAL128 > () , 8usize , concat ! ("Alignment of " , stringify ! (SQLDECIMAL128))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQLDECIMAL128 > ())) . udec128 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQLDECIMAL128) , "::" , stringify ! (udec128))) ;
} extern "C" { pub fn SQLAllocConnect (henv : SQLHENV , phdbc : * mut SQLHDBC) -> SQLRETURN ;
} extern "C" { pub fn SQLAllocEnv (phenv : * mut SQLHENV) -> SQLRETURN ;
} extern "C" { pub fn SQLAllocStmt (hdbc : SQLHDBC , phstmt : * mut SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLAllocHandle (fHandleType : SQLSMALLINT , hInput : SQLHANDLE , phOutput : * mut SQLHANDLE) -> SQLRETURN ;
} extern "C" { pub fn SQLBindCol (hstmt : SQLHSTMT , icol : SQLUSMALLINT , fCType : SQLSMALLINT , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLCancel (hstmt : SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLColAttribute (hstmt : SQLHSTMT , icol : SQLUSMALLINT , fDescType : SQLUSMALLINT , rgbDesc : SQLPOINTER , cbDescMax : SQLSMALLINT , pcbDesc : * mut SQLSMALLINT , pfDesc : SQLPOINTER) -> SQLRETURN ;
} extern "C" { pub fn SQLConnect (hdbc : SQLHDBC , szDSN : * mut SQLCHAR , cbDSN : SQLSMALLINT , szUID : * mut SQLCHAR , cbUID : SQLSMALLINT , szAuthStr : * mut SQLCHAR , cbAuthStr : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDescribeCol (hstmt : SQLHSTMT , icol : SQLUSMALLINT , szColName : * mut SQLCHAR , cbColNameMax : SQLSMALLINT , pcbColName : * mut SQLSMALLINT , pfSqlType : * mut SQLSMALLINT , pcbColDef : * mut SQLUINTEGER , pibScale : * mut SQLSMALLINT , pfNullable : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDisconnect (hdbc : SQLHDBC) -> SQLRETURN ;
} extern "C" { pub fn SQLError (henv : SQLHENV , hdbc : SQLHDBC , hstmt : SQLHSTMT , szSqlState : * mut SQLCHAR , pfNativeError : * mut SQLINTEGER , szErrorMsg : * mut SQLCHAR , cbErrorMsgMax : SQLSMALLINT , pcbErrorMsg : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExecDirect (hstmt : SQLHSTMT , szSqlStr : * mut SQLCHAR , cbSqlStr : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLExecute (hstmt : SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLFetch (hstmt : SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLFreeConnect (hdbc : SQLHDBC) -> SQLRETURN ;
} extern "C" { pub fn SQLFreeEnv (henv : SQLHENV) -> SQLRETURN ;
} extern "C" { pub fn SQLFreeStmt (hstmt : SQLHSTMT , fOption : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLCloseCursor (hStmt : SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetCursorName (hstmt : SQLHSTMT , szCursor : * mut SQLCHAR , cbCursorMax : SQLSMALLINT , pcbCursor : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetData (hstmt : SQLHSTMT , icol : SQLUSMALLINT , fCType : SQLSMALLINT , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLNumResultCols (hstmt : SQLHSTMT , pccol : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLPrepare (hstmt : SQLHSTMT , szSqlStr : * mut SQLCHAR , cbSqlStr : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLRowCount (hstmt : SQLHSTMT , pcrow : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetCursorName (hstmt : SQLHSTMT , szCursor : * mut SQLCHAR , cbCursor : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLSetParam (hstmt : SQLHSTMT , ipar : SQLUSMALLINT , fCType : SQLSMALLINT , fSqlType : SQLSMALLINT , cbParamDef : SQLUINTEGER , ibScale : SQLSMALLINT , rgbValue : SQLPOINTER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLTransact (henv : SQLHENV , hdbc : SQLHDBC , fType : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLEndTran (fHandleType : SQLSMALLINT , hHandle : SQLHANDLE , fType : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLFreeHandle (fHandleType : SQLSMALLINT , hHandle : SQLHANDLE) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDiagRec (fHandleType : SQLSMALLINT , hHandle : SQLHANDLE , iRecNumber : SQLSMALLINT , pszSqlState : * mut SQLCHAR , pfNativeError : * mut SQLINTEGER , pszErrorMsg : * mut SQLCHAR , cbErrorMsgMax : SQLSMALLINT , pcbErrorMsg : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDiagField (fHandleType : SQLSMALLINT , hHandle : SQLHANDLE , iRecNumber : SQLSMALLINT , fDiagIdentifier : SQLSMALLINT , pDiagInfo : SQLPOINTER , cbDiagInfoMax : SQLSMALLINT , pcbDiagInfo : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLCopyDesc (hDescSource : SQLHDESC , hDescTarget : SQLHDESC) -> SQLRETURN ;
} extern "C" { pub fn SQLCreateDb (hDbc : SQLHDBC , szDB : * mut SQLCHAR , cbDB : SQLINTEGER , szCodeset : * mut SQLCHAR , cbCodeset : SQLINTEGER , szMode : * mut SQLCHAR , cbMode : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLDropDb (hDbc : SQLHDBC , szDB : * mut SQLCHAR , cbDB : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLCreatePkg (hDbc : SQLHDBC , szBindFileName : * mut SQLCHAR , cbBindFileName : SQLINTEGER , szBindOpts : * mut SQLCHAR , cbBindOpts : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDescField (DescriptorHandle : SQLHDESC , RecNumber : SQLSMALLINT , FieldIdentifier : SQLSMALLINT , Value : SQLPOINTER , BufferLength : SQLINTEGER , StringLength : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDescRec (DescriptorHandle : SQLHDESC , RecNumber : SQLSMALLINT , Name : * mut SQLCHAR , BufferLength : SQLSMALLINT , StringLength : * mut SQLSMALLINT , Type : * mut SQLSMALLINT , SubType : * mut SQLSMALLINT , Length : * mut SQLINTEGER , Precision : * mut SQLSMALLINT , Scale : * mut SQLSMALLINT , Nullable : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLSetDescField (DescriptorHandle : SQLHDESC , RecNumber : SQLSMALLINT , FieldIdentifier : SQLSMALLINT , Value : SQLPOINTER , BufferLength : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetDescRec (DescriptorHandle : SQLHDESC , RecNumber : SQLSMALLINT , Type : SQLSMALLINT , SubType : SQLSMALLINT , Length : SQLINTEGER , Precision : SQLSMALLINT , Scale : SQLSMALLINT , Data : SQLPOINTER , StringLength : * mut SQLINTEGER , Indicator : * mut SQLINTEGER) -> SQLRETURN ;
} pub type LPWSTR = * mut SQLWCHAR ;
pub type DWORD = sqluint32 ;
pub type BOOL = :: std :: os :: raw :: c_uint ;
pub type WCHAR = wchar_t ;
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct _TAGGUID { pub Data1 : :: std :: os :: raw :: c_ulong , pub Data2 : :: std :: os :: raw :: c_ushort , pub Data3 : :: std :: os :: raw :: c_ushort , pub Data4 : [:: std :: os :: raw :: c_uchar ;
8usize] , }
# [test] fn bindgen_test_layout__TAGGUID () { assert_eq ! (:: std :: mem :: size_of :: < _TAGGUID > () , 24usize , concat ! ("Size of: " , stringify ! (_TAGGUID))) ;
assert_eq ! (:: std :: mem :: align_of :: < _TAGGUID > () , 8usize , concat ! ("Alignment of " , stringify ! (_TAGGUID))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < _TAGGUID > ())) . Data1 as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (_TAGGUID) , "::" , stringify ! (Data1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < _TAGGUID > ())) . Data2 as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (_TAGGUID) , "::" , stringify ! (Data2))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < _TAGGUID > ())) . Data3 as * const _ as usize } , 10usize , concat ! ("Offset of field: " , stringify ! (_TAGGUID) , "::" , stringify ! (Data3))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < _TAGGUID > ())) . Data4 as * const _ as usize } , 12usize , concat ! ("Offset of field: " , stringify ! (_TAGGUID) , "::" , stringify ! (Data4))) ;
} pub type TAGGUID = _TAGGUID ;
pub type SQLSTATE = [SQLTCHAR ;
6usize] ;
extern "C" { pub fn SQLDriverConnect (hdbc : SQLHDBC , hwnd : SQLHWND , szConnStrIn : * mut SQLCHAR , cchConnStrIn : SQLSMALLINT , szConnStrOut : * mut SQLCHAR , cchConnStrOutMax : SQLSMALLINT , pcchConnStrOut : * mut SQLSMALLINT , fDriverCompletion : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLBrowseConnect (hdbc : SQLHDBC , szConnStrIn : * mut SQLCHAR , cchConnStrIn : SQLSMALLINT , szConnStrOut : * mut SQLCHAR , cchConnStrOutMax : SQLSMALLINT , pcchConnStrOut : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLBulkOperations (StatementHandle : SQLHSTMT , Operation : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLColAttributes (hstmt : SQLHSTMT , icol : SQLUSMALLINT , fDescType : SQLUSMALLINT , rgbDesc : SQLPOINTER , cbDescMax : SQLSMALLINT , pcbDesc : * mut SQLSMALLINT , pfDesc : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLColumnPrivileges (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cchCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cchSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cchTableName : SQLSMALLINT , szColumnName : * mut SQLCHAR , cchColumnName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDescribeParam (hstmt : SQLHSTMT , ipar : SQLUSMALLINT , pfSqlType : * mut SQLSMALLINT , pcbParamDef : * mut SQLUINTEGER , pibScale : * mut SQLSMALLINT , pfNullable : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedFetch (hstmt : SQLHSTMT , fFetchType : SQLUSMALLINT , irow : SQLINTEGER , pcrow : * mut SQLUINTEGER , rgfRowStatus : * mut SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLForeignKeys (hstmt : SQLHSTMT , szPkCatalogName : * mut SQLCHAR , cchPkCatalogName : SQLSMALLINT , szPkSchemaName : * mut SQLCHAR , cchPkSchemaName : SQLSMALLINT , szPkTableName : * mut SQLCHAR , cchPkTableName : SQLSMALLINT , szFkCatalogName : * mut SQLCHAR , cchFkCatalogName : SQLSMALLINT , szFkSchemaName : * mut SQLCHAR , cchFkSchemaName : SQLSMALLINT , szFkTableName : * mut SQLCHAR , cchFkTableName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLMoreResults (hstmt : SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLNativeSql (hdbc : SQLHDBC , szSqlStrIn : * mut SQLCHAR , cchSqlStrIn : SQLINTEGER , szSqlStr : * mut SQLCHAR , cchSqlStrMax : SQLINTEGER , pcbSqlStr : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLNumParams (hstmt : SQLHSTMT , pcpar : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLParamOptions (hstmt : SQLHSTMT , crow : SQLUINTEGER , pirow : * mut SQLUINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLPrimaryKeys (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cchCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cchSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cchTableName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLProcedureColumns (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cchCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cchSchemaName : SQLSMALLINT , szProcName : * mut SQLCHAR , cchProcName : SQLSMALLINT , szColumnName : * mut SQLCHAR , cchColumnName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLProcedures (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cchCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cchSchemaName : SQLSMALLINT , szProcName : * mut SQLCHAR , cchProcName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLSetPos (hstmt : SQLHSTMT , irow : SQLUSMALLINT , fOption : SQLUSMALLINT , fLock : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLTablePrivileges (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cchCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cchSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cchTableName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDrivers (henv : SQLHENV , fDirection : SQLUSMALLINT , szDriverDesc : * mut SQLCHAR , cchDriverDescMax : SQLSMALLINT , pcchDriverDesc : * mut SQLSMALLINT , szDriverAttributes : * mut SQLCHAR , cchDrvrAttrMax : SQLSMALLINT , pcchDrvrAttr : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLBindParameter (hstmt : SQLHSTMT , ipar : SQLUSMALLINT , fParamType : SQLSMALLINT , fCType : SQLSMALLINT , fSqlType : SQLSMALLINT , cbColDef : SQLUINTEGER , ibScale : SQLSMALLINT , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLAllocHandleStd (fHandleType : SQLSMALLINT , hInput : SQLHANDLE , phOutput : * mut SQLHANDLE) -> SQLRETURN ;
} extern "C" { pub fn SQLSetScrollOptions (hstmt : SQLHSTMT , fConcurrency : SQLUSMALLINT , crowKeyset : SQLINTEGER , crowRowset : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn TraceOpenLogFile (szFileName : LPWSTR , lpwszOutputMsg : LPWSTR , cbOutputMsg : DWORD) -> RETCODE ;
} extern "C" { pub fn TraceCloseLogFile () -> RETCODE ;
} extern "C" { pub fn TraceReturn (arg1 : RETCODE , arg2 : RETCODE) ;
} extern "C" { pub fn TraceVersion () -> DWORD ;
} extern "C" { pub fn TraceVSControl (arg1 : DWORD) -> RETCODE ;
} extern "C" { pub fn ODBCSetTryWaitValue (dwValue : DWORD) -> BOOL ;
} extern "C" { pub fn ODBCGetTryWaitValue () -> DWORD ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub struct tagODBC_VS_ARGS { pub pguidEvent : * const TAGGUID , pub dwFlags : DWORD , pub __bindgen_anon_1 : tagODBC_VS_ARGS__bindgen_ty_1 , pub __bindgen_anon_2 : tagODBC_VS_ARGS__bindgen_ty_2 , pub RetCode : RETCODE , }
# [repr (C)]
# [derive (Copy , Clone)] pub union tagODBC_VS_ARGS__bindgen_ty_1 { pub wszArg : * mut WCHAR , pub szArg : * mut :: std :: os :: raw :: c_char , _bindgen_union_align : u64 , }
# [test] fn bindgen_test_layout_tagODBC_VS_ARGS__bindgen_ty_1 () { assert_eq ! (:: std :: mem :: size_of :: < tagODBC_VS_ARGS__bindgen_ty_1 > () , 8usize , concat ! ("Size of: " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_1))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagODBC_VS_ARGS__bindgen_ty_1 > () , 8usize , concat ! ("Alignment of " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_1))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS__bindgen_ty_1 > ())) . wszArg as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_1) , "::" , stringify ! (wszArg))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS__bindgen_ty_1 > ())) . szArg as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_1) , "::" , stringify ! (szArg))) ;
}
# [repr (C)]
# [derive (Copy , Clone)] pub union tagODBC_VS_ARGS__bindgen_ty_2 { pub wszCorrelation : * mut WCHAR , pub szCorrelation : * mut :: std :: os :: raw :: c_char , _bindgen_union_align : u64 , }
# [test] fn bindgen_test_layout_tagODBC_VS_ARGS__bindgen_ty_2 () { assert_eq ! (:: std :: mem :: size_of :: < tagODBC_VS_ARGS__bindgen_ty_2 > () , 8usize , concat ! ("Size of: " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_2))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagODBC_VS_ARGS__bindgen_ty_2 > () , 8usize , concat ! ("Alignment of " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_2))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS__bindgen_ty_2 > ())) . wszCorrelation as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_2) , "::" , stringify ! (wszCorrelation))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS__bindgen_ty_2 > ())) . szCorrelation as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS__bindgen_ty_2) , "::" , stringify ! (szCorrelation))) ;
}
# [test] fn bindgen_test_layout_tagODBC_VS_ARGS () { assert_eq ! (:: std :: mem :: size_of :: < tagODBC_VS_ARGS > () , 40usize , concat ! ("Size of: " , stringify ! (tagODBC_VS_ARGS))) ;
assert_eq ! (:: std :: mem :: align_of :: < tagODBC_VS_ARGS > () , 8usize , concat ! ("Alignment of " , stringify ! (tagODBC_VS_ARGS))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS > ())) . pguidEvent as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS) , "::" , stringify ! (pguidEvent))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS > ())) . dwFlags as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS) , "::" , stringify ! (dwFlags))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < tagODBC_VS_ARGS > ())) . RetCode as * const _ as usize } , 32usize , concat ! ("Offset of field: " , stringify ! (tagODBC_VS_ARGS) , "::" , stringify ! (RetCode))) ;
} pub type ODBC_VS_ARGS = tagODBC_VS_ARGS ;
pub type PODBC_VS_ARGS = * mut tagODBC_VS_ARGS ;
extern "C" { pub fn FireVSDebugEvent (arg1 : PODBC_VS_ARGS) ;
}
# [repr (C)]
# [derive (Debug , Copy , Clone)] pub struct SQL_NET_STATS { pub iNetStatsLength : SQLINTEGER , pub uiNetStatsServerTime : SQLUBIGINT , pub uiNetStatsNetworkTime : SQLUBIGINT , pub uiNetStatsBytesSent : SQLUBIGINT , pub uiNetStatsBytesReceived : SQLUBIGINT , pub uiNetStatsRoundTrips : SQLUBIGINT , }
# [test] fn bindgen_test_layout_SQL_NET_STATS () { assert_eq ! (:: std :: mem :: size_of :: < SQL_NET_STATS > () , 48usize , concat ! ("Size of: " , stringify ! (SQL_NET_STATS))) ;
assert_eq ! (:: std :: mem :: align_of :: < SQL_NET_STATS > () , 8usize , concat ! ("Alignment of " , stringify ! (SQL_NET_STATS))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQL_NET_STATS > ())) . iNetStatsLength as * const _ as usize } , 0usize , concat ! ("Offset of field: " , stringify ! (SQL_NET_STATS) , "::" , stringify ! (iNetStatsLength))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQL_NET_STATS > ())) . uiNetStatsServerTime as * const _ as usize } , 8usize , concat ! ("Offset of field: " , stringify ! (SQL_NET_STATS) , "::" , stringify ! (uiNetStatsServerTime))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQL_NET_STATS > ())) . uiNetStatsNetworkTime as * const _ as usize } , 16usize , concat ! ("Offset of field: " , stringify ! (SQL_NET_STATS) , "::" , stringify ! (uiNetStatsNetworkTime))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQL_NET_STATS > ())) . uiNetStatsBytesSent as * const _ as usize } , 24usize , concat ! ("Offset of field: " , stringify ! (SQL_NET_STATS) , "::" , stringify ! (uiNetStatsBytesSent))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQL_NET_STATS > ())) . uiNetStatsBytesReceived as * const _ as usize } , 32usize , concat ! ("Offset of field: " , stringify ! (SQL_NET_STATS) , "::" , stringify ! (uiNetStatsBytesReceived))) ;
assert_eq ! (unsafe { & (* (:: std :: ptr :: null :: < SQL_NET_STATS > ())) . uiNetStatsRoundTrips as * const _ as usize } , 40usize , concat ! ("Offset of field: " , stringify ! (SQL_NET_STATS) , "::" , stringify ! (uiNetStatsRoundTrips))) ;
} extern "C" { pub fn SQLColumns (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cbTableName : SQLSMALLINT , szColumnName : * mut SQLCHAR , cbColumnName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDataSources (henv : SQLHENV , fDirection : SQLUSMALLINT , szDSN : * mut SQLCHAR , cbDSNMax : SQLSMALLINT , pcbDSN : * mut SQLSMALLINT , szDescription : * mut SQLCHAR , cbDescriptionMax : SQLSMALLINT , pcbDescription : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLFetchScroll (StatementHandle : SQLHSTMT , FetchOrientation : SQLSMALLINT , FetchOffset : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetConnectAttr (ConnectionHandle : SQLHDBC , Attribute : SQLINTEGER , Value : SQLPOINTER , BufferLength : SQLINTEGER , StringLength : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetConnectOption (hdbc : SQLHDBC , fOption : SQLUSMALLINT , pvParam : SQLPOINTER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetFunctions (hdbc : SQLHDBC , fFunction : SQLUSMALLINT , pfExists : * mut SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetInfo (hdbc : SQLHDBC , fInfoType : SQLUSMALLINT , rgbInfoValue : SQLPOINTER , cbInfoValueMax : SQLSMALLINT , pcbInfoValue : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetStmtAttr (StatementHandle : SQLHSTMT , Attribute : SQLINTEGER , Value : SQLPOINTER , BufferLength : SQLINTEGER , StringLength : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetStmtOption (hstmt : SQLHSTMT , fOption : SQLUSMALLINT , pvParam : SQLPOINTER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetTypeInfo (hstmt : SQLHSTMT , fSqlType : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLParamData (hstmt : SQLHSTMT , prgbValue : * mut SQLPOINTER) -> SQLRETURN ;
} extern "C" { pub fn SQLPutData (hstmt : SQLHSTMT , rgbValue : SQLPOINTER , cbValue : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetConnectAttr (hdbc : SQLHDBC , fOption : SQLINTEGER , pvParam : SQLPOINTER , fStrLen : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetConnectOption (hdbc : SQLHDBC , fOption : SQLUSMALLINT , vParam : SQLUINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetStmtAttr (hstmt : SQLHSTMT , fOption : SQLINTEGER , pvParam : SQLPOINTER , fStrLen : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetStmtOption (hstmt : SQLHSTMT , fOption : SQLUSMALLINT , vParam : SQLUINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSpecialColumns (hstmt : SQLHSTMT , fColType : SQLUSMALLINT , szCatalogName : * mut SQLCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cbTableName : SQLSMALLINT , fScope : SQLUSMALLINT , fNullable : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLStatistics (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cbTableName : SQLSMALLINT , fUnique : SQLUSMALLINT , fAccuracy : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLTables (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLCHAR , cbTableName : SQLSMALLINT , szTableType : * mut SQLCHAR , cbTableType : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLNextResult (hstmtSource : SQLHSTMT , hstmtTarget : SQLHSTMT) -> SQLRETURN ;
} extern "C" { pub fn SQLColAttributeW (hstmt : SQLHSTMT , iCol : SQLUSMALLINT , iField : SQLUSMALLINT , pCharAttr : SQLPOINTER , cbCharAttrMax : SQLSMALLINT , pcbCharAttr : * mut SQLSMALLINT , pNumAttr : SQLPOINTER) -> SQLRETURN ;
} extern "C" { pub fn SQLColAttributesW (hstmt : SQLHSTMT , icol : SQLUSMALLINT , fDescType : SQLUSMALLINT , rgbDesc : SQLPOINTER , cbDescMax : SQLSMALLINT , pcbDesc : * mut SQLSMALLINT , pfDesc : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLConnectW (hdbc : SQLHDBC , szDSN : * mut SQLWCHAR , cbDSN : SQLSMALLINT , szUID : * mut SQLWCHAR , cbUID : SQLSMALLINT , szAuthStr : * mut SQLWCHAR , cbAuthStr : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLConnectWInt (hdbc : SQLHDBC , szDSN : * mut SQLWCHAR , cbDSN : SQLSMALLINT , szUID : * mut SQLWCHAR , cbUID : SQLSMALLINT , szAuthStr : * mut SQLWCHAR , cbAuthStr : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDescribeColW (hstmt : SQLHSTMT , icol : SQLUSMALLINT , szColName : * mut SQLWCHAR , cbColNameMax : SQLSMALLINT , pcbColName : * mut SQLSMALLINT , pfSqlType : * mut SQLSMALLINT , pcbColDef : * mut SQLUINTEGER , pibScale : * mut SQLSMALLINT , pfNullable : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLErrorW (henv : SQLHENV , hdbc : SQLHDBC , hstmt : SQLHSTMT , szSqlState : * mut SQLWCHAR , pfNativeError : * mut SQLINTEGER , szErrorMsg : * mut SQLWCHAR , cbErrorMsgMax : SQLSMALLINT , pcbErrorMsg : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExecDirectW (hstmt : SQLHSTMT , szSqlStr : * mut SQLWCHAR , cbSqlStr : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetConnectAttrW (hdbc : SQLHDBC , fAttribute : SQLINTEGER , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetCursorNameW (hstmt : SQLHSTMT , szCursor : * mut SQLWCHAR , cbCursorMax : SQLSMALLINT , pcbCursor : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLSetDescFieldW (DescriptorHandle : SQLHDESC , RecNumber : SQLSMALLINT , FieldIdentifier : SQLSMALLINT , Value : SQLPOINTER , BufferLength : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDescFieldW (hdesc : SQLHDESC , iRecord : SQLSMALLINT , iField : SQLSMALLINT , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDescRecW (hdesc : SQLHDESC , iRecord : SQLSMALLINT , szName : * mut SQLWCHAR , cbNameMax : SQLSMALLINT , pcbName : * mut SQLSMALLINT , pfType : * mut SQLSMALLINT , pfSubType : * mut SQLSMALLINT , pLength : * mut SQLINTEGER , pPrecision : * mut SQLSMALLINT , pScale : * mut SQLSMALLINT , pNullable : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDiagFieldW (fHandleType : SQLSMALLINT , handle : SQLHANDLE , iRecord : SQLSMALLINT , fDiagField : SQLSMALLINT , rgbDiagInfo : SQLPOINTER , cbDiagInfoMax : SQLSMALLINT , pcbDiagInfo : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDiagRecW (fHandleType : SQLSMALLINT , handle : SQLHANDLE , iRecord : SQLSMALLINT , szSqlState : * mut SQLWCHAR , pfNativeError : * mut SQLINTEGER , szErrorMsg : * mut SQLWCHAR , cbErrorMsgMax : SQLSMALLINT , pcbErrorMsg : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetEnvAttrW (hEnv : SQLHENV , fAttribute : SQLINTEGER , pParam : SQLPOINTER , cbParamMax : SQLINTEGER , pcbParam : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLPrepareW (hstmt : SQLHSTMT , szSqlStr : * mut SQLWCHAR , cbSqlStr : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedPrepareW (hStmt : SQLHSTMT , pszSqlStrIn : * mut SQLWCHAR , cbSqlStr : SQLINTEGER , cPars : SQLINTEGER , sStmtType : SQLSMALLINT , cStmtAttrs : SQLINTEGER , piStmtAttr : * mut SQLINTEGER , pvParams : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetConnectAttrW (hdbc : SQLHDBC , fAttribute : SQLINTEGER , rgbValue : SQLPOINTER , cbValue : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetCursorNameW (hstmt : SQLHSTMT , szCursor : * mut SQLWCHAR , cbCursor : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLSetEnvAttrW (hEnv : SQLHENV , fAttribute : SQLINTEGER , pParam : SQLPOINTER , cbParam : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLColumnsW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT , szColumnName : * mut SQLWCHAR , cbColumnName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetInfoW (hdbc : SQLHDBC , fInfoType : SQLUSMALLINT , rgbInfoValue : SQLPOINTER , cbInfoValueMax : SQLSMALLINT , pcbInfoValue : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetConnectOptionW (hDbc : SQLHDBC , fOptionIn : SQLUSMALLINT , pvParam : SQLPOINTER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetConnectOptionW (hDbc : SQLHDBC , fOptionIn : SQLUSMALLINT , vParam : SQLUINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetTypeInfoW (hstmt : SQLHSTMT , fSqlType : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLSpecialColumnsW (hstmt : SQLHSTMT , fColType : SQLUSMALLINT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT , fScope : SQLUSMALLINT , fNullable : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLStatisticsW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT , fUnique : SQLUSMALLINT , fAccuracy : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLTablesW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT , szTableType : * mut SQLWCHAR , cbTableType : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDataSourcesW (henv : SQLHENV , fDirection : SQLUSMALLINT , szDSN : * mut SQLWCHAR , cbDSNMax : SQLSMALLINT , pcbDSN : * mut SQLSMALLINT , szDescription : * mut SQLWCHAR , cbDescriptionMax : SQLSMALLINT , pcbDescription : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLDriverConnectW (hdbc : SQLHDBC , hwnd : SQLHWND , szConnStrIn : * mut SQLWCHAR , cbConnStrIn : SQLSMALLINT , szConnStrOut : * mut SQLWCHAR , cbConnStrOutMax : SQLSMALLINT , pcbConnStrOut : * mut SQLSMALLINT , fDriverCompletion : SQLUSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLBrowseConnectW (hdbc : SQLHDBC , szConnStrIn : * mut SQLWCHAR , cbConnStrIn : SQLSMALLINT , szConnStrOut : * mut SQLWCHAR , cbConnStrOutMax : SQLSMALLINT , pcbConnStrOut : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLColumnPrivilegesW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT , szColumnName : * mut SQLWCHAR , cbColumnName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetStmtAttrW (hstmt : SQLHSTMT , fAttribute : SQLINTEGER , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , pcbValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetStmtAttrW (hstmt : SQLHSTMT , fAttribute : SQLINTEGER , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLForeignKeysW (hstmt : SQLHSTMT , szPkCatalogName : * mut SQLWCHAR , cbPkCatalogName : SQLSMALLINT , szPkSchemaName : * mut SQLWCHAR , cbPkSchemaName : SQLSMALLINT , szPkTableName : * mut SQLWCHAR , cbPkTableName : SQLSMALLINT , szFkCatalogName : * mut SQLWCHAR , cbFkCatalogName : SQLSMALLINT , szFkSchemaName : * mut SQLWCHAR , cbFkSchemaName : SQLSMALLINT , szFkTableName : * mut SQLWCHAR , cbFkTableName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLNativeSqlW (hdbc : SQLHDBC , szSqlStrIn : * mut SQLWCHAR , cbSqlStrIn : SQLINTEGER , szSqlStr : * mut SQLWCHAR , cbSqlStrMax : SQLINTEGER , pcbSqlStr : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLPrimaryKeysW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLProcedureColumnsW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szProcName : * mut SQLWCHAR , cbProcName : SQLSMALLINT , szColumnName : * mut SQLWCHAR , cbColumnName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLProceduresW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szProcName : * mut SQLWCHAR , cbProcName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedProcedureColumnsW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szProcName : * mut SQLWCHAR , cbProcName : SQLSMALLINT , szColumnName : * mut SQLWCHAR , cbColumnName : SQLSMALLINT , szModuleName : * mut SQLWCHAR , cbModuleName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedProceduresW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szProcName : * mut SQLWCHAR , cbProcName : SQLSMALLINT , szModuleName : * mut SQLWCHAR , cbModuleName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLTablePrivilegesW (hstmt : SQLHSTMT , szCatalogName : * mut SQLWCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLWCHAR , cbSchemaName : SQLSMALLINT , szTableName : * mut SQLWCHAR , cbTableName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLCreateDbW (hDbc : SQLHDBC , pszDBW : * mut SQLWCHAR , cbDB : SQLINTEGER , pszCodeSetW : * mut SQLWCHAR , cbCodeSet : SQLINTEGER , pszModeW : * mut SQLWCHAR , cbMode : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLDropDbW (hDbc : SQLHDBC , pszDBW : * mut SQLWCHAR , cbDB : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLCreatePkgW (hDbc : SQLHDBC , szBindFileNameIn : * mut SQLWCHAR , cbBindFileNameIn : SQLINTEGER , szBindOpts : * mut SQLWCHAR , cbBindOpts : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLDropPkgW (hDbc : SQLHDBC , szCollection : * mut SQLWCHAR , cbCollection : SQLINTEGER , szPackage : * mut SQLWCHAR , cbPackage : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLBindFileToCol (hstmt : SQLHSTMT , icol : SQLUSMALLINT , FileName : * mut SQLCHAR , FileNameLength : * mut SQLSMALLINT , FileOptions : * mut SQLUINTEGER , MaxFileNameLength : SQLSMALLINT , StringLength : * mut SQLINTEGER , IndicatorValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLBindFileToParam (hstmt : SQLHSTMT , ipar : SQLUSMALLINT , fSqlType : SQLSMALLINT , FileName : * mut SQLCHAR , FileNameLength : * mut SQLSMALLINT , FileOptions : * mut SQLUINTEGER , MaxFileNameLength : SQLSMALLINT , IndicatorValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetLength (hstmt : SQLHSTMT , LocatorCType : SQLSMALLINT , Locator : SQLINTEGER , StringLength : * mut SQLINTEGER , IndicatorValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetPosition (hstmt : SQLHSTMT , LocatorCType : SQLSMALLINT , SourceLocator : SQLINTEGER , SearchLocator : SQLINTEGER , SearchLiteral : * mut SQLCHAR , SearchLiteralLength : SQLINTEGER , FromPosition : SQLUINTEGER , LocatedAt : * mut SQLUINTEGER , IndicatorValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetSQLCA (henv : SQLHENV , hdbc : SQLHDBC , hstmt : SQLHSTMT , pSqlca : * mut sqlca) -> SQLRETURN ;
} extern "C" { pub fn SQLGetSubString (hstmt : SQLHSTMT , LocatorCType : SQLSMALLINT , SourceLocator : SQLINTEGER , FromPosition : SQLUINTEGER , ForLength : SQLUINTEGER , TargetCType : SQLSMALLINT , rgbValue : SQLPOINTER , cbValueMax : SQLINTEGER , StringLength : * mut SQLINTEGER , IndicatorValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetColAttributes (hstmt : SQLHSTMT , icol : SQLUSMALLINT , pszColName : * mut SQLCHAR , cbColName : SQLSMALLINT , fSQLType : SQLSMALLINT , cbColDef : SQLUINTEGER , ibScale : SQLSMALLINT , fNullable : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedProcedures (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cbSchemaName : SQLSMALLINT , szProcName : * mut SQLCHAR , cbProcName : SQLSMALLINT , szModuleName : * mut SQLCHAR , cbModuleName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedProcedureColumns (hstmt : SQLHSTMT , szCatalogName : * mut SQLCHAR , cbCatalogName : SQLSMALLINT , szSchemaName : * mut SQLCHAR , cbSchemaName : SQLSMALLINT , szProcName : * mut SQLCHAR , cbProcName : SQLSMALLINT , szColumnName : * mut SQLCHAR , cbColumnName : SQLSMALLINT , szModuleName : * mut SQLCHAR , cbModuleName : SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLReloadConfig (config_property : SQLINTEGER , DiagInfoString : * mut SQLCHAR , BufferLength : SQLSMALLINT , StringLengthPtr : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLReloadConfigW (config_property : SQLINTEGER , DiagInfoString : * mut SQLWCHAR , BufferLength : SQLSMALLINT , StringLengthPtr : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLGetPositionW (hStmt : SQLHSTMT , fCType : SQLSMALLINT , iLocatorIn : SQLINTEGER , iPatternLocator : SQLINTEGER , pszPatternLiteral : * mut SQLWCHAR , cbPatternLiteral : SQLINTEGER , iStartSearchAtIn : SQLUINTEGER , piLocatedAtIn : * mut SQLUINTEGER , piIndicatorValue : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetConnection (hdbc : SQLHDBC) -> SQLRETURN ;
} extern "C" { pub fn SQLGetEnvAttr (henv : SQLHENV , Attribute : SQLINTEGER , Value : SQLPOINTER , BufferLength : SQLINTEGER , StringLength : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLSetEnvAttr (henv : SQLHENV , Attribute : SQLINTEGER , Value : SQLPOINTER , StringLength : SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLBindParam (StatementHandle : SQLHSTMT , ParameterNumber : SQLUSMALLINT , ValueType : SQLSMALLINT , ParameterType : SQLSMALLINT , LengthPrecision : SQLUINTEGER , ParameterScale : SQLSMALLINT , ParameterValue : SQLPOINTER , StrLen_or_Ind : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLBuildDataLink (hStmt : SQLHSTMT , pszLinkType : * mut SQLCHAR , cbLinkType : SQLINTEGER , pszDataLocation : * mut SQLCHAR , cbDataLocation : SQLINTEGER , pszComment : * mut SQLCHAR , cbComment : SQLINTEGER , pDataLink : * mut SQLCHAR , cbDataLinkMax : SQLINTEGER , pcbDataLink : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLGetDataLinkAttr (hStmt : SQLHSTMT , fAttrType : SQLSMALLINT , pDataLink : * mut SQLCHAR , cbDataLink : SQLINTEGER , pAttribute : SQLPOINTER , cbAttributeMax : SQLINTEGER , pcbAttribute : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedPrepare (hstmt : SQLHSTMT , pszSqlStmt : * mut SQLCHAR , cbSqlStmt : SQLINTEGER , cPars : SQLINTEGER , sStmtType : SQLSMALLINT , cStmtAttrs : SQLINTEGER , piStmtAttr : * mut SQLINTEGER , pvParams : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedBind (hstmt : SQLHSTMT , fBindCol : SQLSMALLINT , cRecords : SQLSMALLINT , pfCType : * mut SQLSMALLINT , rgbValue : * mut SQLPOINTER , cbValueMax : * mut SQLINTEGER , puiPrecisionCType : * mut SQLUINTEGER , psScaleCType : * mut SQLSMALLINT , pcbValue : * mut * mut SQLINTEGER , piIndicatorPtr : * mut * mut SQLINTEGER , pfParamType : * mut SQLSMALLINT , pfSQLType : * mut SQLSMALLINT , pcbColDef : * mut SQLUINTEGER , pibScale : * mut SQLSMALLINT) -> SQLRETURN ;
} extern "C" { pub fn SQLExtendedDescribe (hStmt : SQLHANDLE , fDescribeCol : SQLSMALLINT , iNumRecordsAllocated : SQLUSMALLINT , pusNumRecords : * mut SQLUSMALLINT , pNames : * mut SQLCHAR , sNameMaxByteLen : SQLSMALLINT , psNameCharLen : * mut SQLSMALLINT , psSQLType : * mut SQLSMALLINT , pcbColDef : * mut SQLUINTEGER , pcbDisplaySize : * mut SQLUINTEGER , psScale : * mut SQLSMALLINT , psNullable : * mut SQLSMALLINT , psParamType : * mut SQLSMALLINT , piCardinality : * mut SQLINTEGER) -> SQLRETURN ;
} extern "C" { pub fn SQLDropPkg (hDbc : SQLHDBC , szCollection : * mut SQLCHAR , cbCollection : SQLINTEGER , szPackage : * mut SQLCHAR , cbPackage : SQLINTEGER) -> SQLRETURN ;
}
| 68.23373 | 558 | 0.682114 |
e9345a52013002d649dcef90118c3e8c294d30e8 | 978 | use crate::nors::ResultsByCountType;
use std::str::FromStr;
#[derive(Debug)]
pub enum OutputType {
PlainText,
JSON,
}
impl FromStr for OutputType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"plaintext" => Ok(Self::PlainText),
"json" => Ok(Self::JSON),
_ => Err(()),
}
}
}
impl Default for OutputType {
fn default() -> Self {
Self::PlainText
}
}
impl OutputType {
pub fn print(&self, results: &ResultsByCountType) {
match self {
Self::PlainText => {
for (result_type, result) in results.results.iter() {
println!("{:?}: {}", result_type, result);
}
}
Self::JSON => {
println!(
"{}",
serde_json::to_string(&results).expect("json serialize error.")
);
}
}
}
}
| 22.227273 | 83 | 0.461145 |
c1e667a0eff0020dab9dcbe6ede22a083d465597 | 5,618 | #![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_parens)]
#![allow(unused_variables)]
#![no_main]
#![no_std]
use cortex_m_rt::entry;
use cortex_m;
use nucleo_h7xx as nucleo;
use nucleo::loggit;
use nucleo::hal as hal;
use hal::prelude::*;
use hal::gpio::Speed::*;
use hal::hal::digital::v2::OutputPin;
use hal::hal::digital::v2::ToggleableOutputPin;
use hal::rcc::CoreClocks;
use hal::{ethernet, ethernet::PHY};
use hal::pac;
use pac::interrupt;
use smoltcp;
use smoltcp::iface::{
EthernetInterface, EthernetInterfaceBuilder, Neighbor, NeighborCache,
Route, Routes,
};
use smoltcp::socket::{SocketSet, SocketSetItem};
use smoltcp::socket::{UdpSocket, UdpSocketBuffer, UdpPacketMetadata};
use smoltcp::storage::PacketMetadata;
use smoltcp::time::Instant;
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv6Cidr, IpEndpoint, Ipv4Address};
use log::{debug, error, info};
/// Simple ethernet example that will respond to icmp pings on
/// `IP_LOCAL` and periodically send a udp packet to
/// `IP_REMOTE:IP_REMOTE_PORT`
///
/// You can start a simple listening server with netcat:
///
/// nc -u -l 34254
const MAC_LOCAL: [u8; 6] = [0x02, 0x00, 0x11, 0x22, 0x33, 0x44];
const IP_LOCAL: [u8; 4] = [ 192, 168, 20, 99 ];
const IP_REMOTE: [u8; 4] = [ 192, 168, 20, 114 ];
const IP_REMOTE_PORT: u16 = 34254;
mod utilities;
#[entry]
fn main() -> ! {
// - endpoints ------------------------------------------------------------
let local_endpoint = IpEndpoint::new(Ipv4Address::from_bytes(&IP_LOCAL).into(), 1234);
let remote_endpoint = IpEndpoint::new(Ipv4Address::from_bytes(&IP_REMOTE).into(),
IP_REMOTE_PORT);
// - board setup ----------------------------------------------------------
info!("Setting up board");
let board = nucleo::Board::take().unwrap();
let dp = pac::Peripherals::take().unwrap();
let ccdr = board.freeze_clocks(dp.PWR.constrain(),
dp.RCC.constrain(),
&dp.SYSCFG);
let pins = board.split_gpios(dp.GPIOA.split(ccdr.peripheral.GPIOA),
dp.GPIOB.split(ccdr.peripheral.GPIOB),
dp.GPIOC.split(ccdr.peripheral.GPIOC),
dp.GPIOD.split(ccdr.peripheral.GPIOD),
dp.GPIOE.split(ccdr.peripheral.GPIOE),
dp.GPIOF.split(ccdr.peripheral.GPIOF),
dp.GPIOG.split(ccdr.peripheral.GPIOG));
utilities::logger::init();
// - ethernet interface ---------------------------------------------------
info!("Bringing up ethernet interface");
let timeout_timer = dp.TIM17.timer(100.hz(), ccdr.peripheral.TIM17, &ccdr.clocks);
let timeout_timer = nucleo::timer::CountDownTimer::new(timeout_timer);
let timeout_timer = match nucleo::ethernet::Interface::start(pins.ethernet,
&MAC_LOCAL,
&IP_LOCAL,
ccdr.peripheral.ETH1MAC,
&ccdr.clocks,
timeout_timer) {
Ok(tim17) => tim17,
Err(e) => {
error!("Failed to start ethernet interface: {:?}", e);
loop { }
}
};
// wait for link to come up
info!("Waiting for link to come up");
nucleo::ethernet::Interface::interrupt_free(|ethernet_interface| {
while !ethernet_interface.poll_link() { }
});
// create and bind socket
let socket_handle = nucleo::ethernet::Interface::interrupt_free(|ethernet_interface| {
let socket_handle = ethernet_interface.new_udp_socket();
let mut socket = ethernet_interface.sockets.as_mut().unwrap().get::<UdpSocket>(socket_handle);
match socket.bind(local_endpoint) {
Ok(()) => return socket_handle,
Err(e) => {
error!("Failed to bind socket to endpoint: {:?}", local_endpoint);
loop { }
}
}
});
// - main loop ------------------------------------------------------------
info!("Entering main loop");
let mut last = 0;
loop {
cortex_m::asm::wfi();
// poll ethernet interface
let now = nucleo::ethernet::Interface::interrupt_free(|ethernet_interface| {
match ethernet_interface.poll() {
Ok(result) => {}, // packets were processed or emitted
Err(smoltcp::Error::Exhausted) => (),
Err(smoltcp::Error::Unrecognized) => (),
Err(e) => debug!("ethernet::Interface.poll() -> {:?}", e)
}
ethernet_interface.now()
});
// check if it has been 5 seconds since we last sent something
if (now - last) < 5000 {
continue;
} else {
last = now;
}
// send something
nucleo::ethernet::Interface::interrupt_free(|ethernet_interface| {
let mut socket = ethernet_interface.sockets.as_mut().unwrap().get::<UdpSocket>(socket_handle);
match socket.send_slice("nucleo says hello!\n".as_bytes(), remote_endpoint) {
Ok(()) => (),
Err(smoltcp::Error::Exhausted) => (),
Err(e) => error!("UdpSocket::send error: {:?}", e),
};
});
}
}
| 33.843373 | 106 | 0.529014 |
c1bdec211206c35b8d06df5d79929d1e7963704e | 6,050 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use crate::common::protocol::negotiation::{NegotiationClient, NegotiationError};
use futures::future::{BoxFuture, FutureExt, TryFutureExt};
use std::{backtrace::Backtrace, sync::Arc};
use crate::common::protocol::{
traits::{ServiceRegistry, TunnelRegistry},
Client, Request, Response, RouteAddress, Router, RoutingError,
};
use crate::{
common::protocol::ClientError,
util::tunnel_stream::{TunnelStream, WrappedStream},
};
pub struct RequestClientHandler {
tunnel_registry: Arc<dyn TunnelRegistry + Send + Sync + 'static>,
service_registry: Arc<dyn ServiceRegistry + Send + Sync + 'static>,
router: Arc<dyn Router + Send + Sync + 'static>,
}
#[derive(thiserror::Error, Debug)]
pub enum RequestHandlingError {
#[error("Route not found for request {0:?}")]
RouteNotFound(Request),
#[error("Route found but unavailable for request")]
RouteUnavailable(Request),
#[error("The Protocol Client failed when handling the request")]
ProtocolClientError(#[from] ClientError),
#[error("Protocol negotiation failed")]
NegotiationError(#[from] NegotiationError, Backtrace),
}
impl RequestClientHandler {
pub fn new(
tunnel_registry: Arc<dyn TunnelRegistry + Send + Sync + 'static>,
service_registry: Arc<dyn ServiceRegistry + Send + Sync + 'static>,
router: Arc<dyn Router + Send + Sync + 'static>,
) -> Self {
Self {
tunnel_registry,
service_registry,
router,
}
}
/// Routes a request and returns its ProtocolClient::Response-typed response.
pub fn handle<TProtocolClient: Client + Send + Sync + 'static>(
self: Arc<Self>,
address: RouteAddress,
client: TProtocolClient,
) -> BoxFuture<'static, Result<TProtocolClient::Response, RequestHandlingError>> {
// TODO: if Router no longer requires a full Request object, this can avoid boxing
let request = Request {
address,
protocol_client: Box::new(client),
};
self
.handle_dynamic(request)
.map_ok(|response: Response| {
*response
.into_inner()
.downcast::<TProtocolClient::Response>()
.expect("Contained response type must match that of the protocol client that produced it")
})
.boxed()
}
/// Handles making a request through a provided link, skipping the routing phase
pub fn handle_direct<TProtocolClient: Client + Send + Sync + 'static>(
self: Arc<Self>,
direct_address: RouteAddress,
client: TProtocolClient,
link: Box<dyn TunnelStream + Send + 'static>,
) -> BoxFuture<'static, Result<TProtocolClient::Response, RequestHandlingError>> {
// TODO: if Router no longer requires a full Request object, this can avoid boxing
let request = Request {
address: direct_address.clone(),
protocol_client: Box::new(client),
};
self
.handle_dynamic_direct(request, direct_address, link)
.map_ok(|response: Response| {
*response
.into_inner()
.downcast::<TProtocolClient::Response>()
.expect("Contained response type must match that of the protocol client that produced it")
})
.boxed()
}
/// Handles making a request through a provided link, skipping the routing phase,
/// but with the possibility of returning a type that may not match the one expected.
pub fn handle_dynamic_direct(
self: Arc<Self>,
request: Request,
direct_address: RouteAddress,
link: Box<dyn TunnelStream + Send + 'static>,
) -> BoxFuture<'static, Result<Response, RequestHandlingError>> {
async move {
tracing::trace!("Running protocol negotiation");
let link = self.negotiate_link(&direct_address, link).await?;
tracing::trace!("Running protocol client");
use tracing_futures::Instrument;
let protocol_client_span = tracing::debug_span!("protocol_client", addr=?direct_address);
let result = request
.protocol_client
.handle_dynamic(direct_address, link)
.instrument(protocol_client_span)
.await;
let response: Response = match result {
Ok(response) => response,
Err(e) => {
tracing::debug!(error=?e, "Protocol client failure");
return Err(e)?;
}
};
Result::<Response, RequestHandlingError>::Ok(response)
}
.boxed()
}
/// Routes a request and returns its response with dynamic/"Any" typing.
pub fn handle_dynamic(
self: Arc<Self>,
request: Request,
) -> BoxFuture<'static, Result<Response, RequestHandlingError>> {
let router = Arc::clone(&self.router);
let tunnel_registry: Arc<dyn TunnelRegistry + Send + Sync + 'static> =
Arc::clone(&self.tunnel_registry);
async move {
// Note: Type-annotated because rust-analyzer fails to resolve typings here on its own
let (resolved_address, link): (RouteAddress, Box<dyn TunnelStream + Send + 'static>) =
match router.route(&request, tunnel_registry).await {
Err(RoutingError::NoMatchingTunnel) => {
return Err(RequestHandlingError::RouteNotFound(request));
}
Err(RoutingError::LinkOpenFailure(_e)) => {
return Err(RequestHandlingError::RouteUnavailable(request));
}
Ok((resolved_address, tunnel)) => (resolved_address, tunnel),
};
self
.handle_dynamic_direct(request, resolved_address, link)
.await
}
.boxed()
}
pub fn negotiate_link(
self: Arc<Self>,
addr: &RouteAddress,
link: Box<dyn TunnelStream + Send + 'static>,
) -> BoxFuture<'static, Result<Box<dyn TunnelStream + Send + 'static>, NegotiationError>> {
use tracing_futures::Instrument;
let addr = addr.clone();
let negotiation_client = NegotiationClient;
let negotiation_span = tracing::debug_span!("negotiation", addr=?addr);
async move {
let link = negotiation_client.handle(addr, link).await?;
Ok(link)
}
.instrument(negotiation_span)
.boxed()
}
}
| 35.588235 | 100 | 0.668595 |
fc429dd543dcc12543e9df6830d207117b511d43 | 17,674 | use std::collections::HashMap;
use std::convert::TryFrom;
use std::iter::{FromIterator, Peekable};
use std::option::Option::Some;
use std::result::Result::Ok;
use std::str::Chars;
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
NULL,
FALSE,
TRUE,
NUMBER(f64),
STRING(String),
ARRAY(Vec<Value>),
OBJECT(HashMap<String, Value>),
}
#[derive(Debug, PartialEq)]
pub enum DecodingError {
ExpectValue,
InvalidValue,
RootNotSingular,
}
pub struct Parser<'a> {
chars: Peekable<Chars<'a>>,
}
impl Parser<'_> {
pub fn new(text: &str) -> Parser {
Parser {
chars: text.chars().peekable(),
}
}
pub fn parse(&mut self) -> Result<Value, DecodingError> {
let result = self.parse_value();
if result.is_ok() && self.chars.next() != None {
return Err(DecodingError::RootNotSingular);
}
return result;
}
fn parse_value(&mut self) -> Result<Value, DecodingError> {
self.skip_white_space();
let result = match self.chars.peek() {
None => Err(DecodingError::ExpectValue),
Some('n') => self.parse_null(),
Some('t') => self.parse_true(),
Some('f') => self.parse_false(),
Some('\"') => self.parse_string(),
Some('[') => self.parse_array(),
Some('{') => self.parse_object(),
_ => self.parse_number(),
};
self.skip_white_space();
return result;
}
fn skip_white_space(&mut self) {
while let Some(c) = self.chars.peek() {
if *c == '\r' || *c == '\t' || *c == '\n' || *c == ' ' {
self.chars.next();
} else {
break;
}
}
}
fn parse_null(&mut self) -> Result<Value, DecodingError> {
if self.next_if_match_str("null") {
return Ok(Value::NULL);
}
return Err(DecodingError::InvalidValue);
}
fn parse_true(&mut self) -> Result<Value, DecodingError> {
if self.next_if_match_str("true") {
return Ok(Value::TRUE);
}
return Err(DecodingError::InvalidValue);
}
fn parse_false(&mut self) -> Result<Value, DecodingError> {
if self.next_if_match_str("false") {
return Ok(Value::FALSE);
}
return Err(DecodingError::InvalidValue);
}
fn parse_number(&mut self) -> Result<Value, DecodingError> {
// number = [ "-" ] int [ fraction ] [ exponent ]
// int = "0" / digit1-9 *digit
// fraction = "." 1*digit
// exp = ("e" / "E") ["-" / "+"] 1*digit
let mut number_chars = vec![];
// 解析 "-"
if self.next_if_match('-') {
number_chars.push('-');
}
// 解析整数部分
// int = "0" / digit1-9 *digit
if self.next_if_match('0') {
number_chars.push('0');
} else if let Some(ch) = self.next_if_digit() {
number_chars.push(ch);
while let Some(ch) = self.next_if_digit() {
number_chars.push(ch);
}
} else {
// 整数部分必须存在
return Err(DecodingError::InvalidValue);
}
// 解析小数部分
// fraction = "." 1*digit
if self.next_if_match('.') {
number_chars.push('.');
// 解析小数点后的数字
let mut has_number = false;
while let Some(ch) = self.next_if_digit() {
number_chars.push(ch);
has_number = true;
}
// 小数点后面至少要有一个数字
if !has_number {
return Err(DecodingError::InvalidValue);
}
}
// 解析指数部分
// exp = ("e" / "E") ["-" / "+"] 1*digit
if self.next_if_match_ignore_case('e') {
number_chars.push('e');
if self.next_if_match('-') {
number_chars.push('-');
} else if self.next_if_match('+') {
number_chars.push('+');
}
// 解析指数的数字部分
let mut has_number = false;
while let Some(ch) = self.next_if_digit() {
number_chars.push(ch);
has_number = true;
}
// 指数后面必须有个数字
if !has_number {
return Err(DecodingError::InvalidValue);
}
}
// 将字符串形式的数字,转换为 double 来存储
if let Ok(number) = String::from_iter(number_chars).parse::<f64>() {
return Ok(Value::NUMBER(number));
}
return Err(DecodingError::InvalidValue);
}
fn parse_string(&mut self) -> Result<Value, DecodingError> {
if !self.next_if_match('\"') {
return Err(DecodingError::InvalidValue);
}
let mut chars: Vec<char> = Vec::new();
while let Some(&char) = self.chars.peek() {
if char == '\"' {
break;
}
if self.next_if_match('\\') {
// 转义字符
match self.chars.peek() {
Some('\"') => chars.push('\"'),
Some('\\') => chars.push('\\'),
Some('/') => chars.push('/'),
Some('n') => chars.push('\n'),
Some('r') => chars.push('\r'),
Some('t') => chars.push('\t'),
// rust 不支持 \b, \f 转义字符,因此这两个转义字符被忽略
Some('b') => {}
Some('f') => {}
// Escaped Unicode
Some('u') => {
self.chars.next();
let mut numbers = [char; 4];
for i in 0..4 {
if let Some(number) = self.next_if_hex_digit() {
numbers[i] = number;
} else {
return Err(DecodingError::InvalidValue);
}
}
let numbers: String = numbers.iter().collect();
if let Ok(number) = u32::from_str_radix(numbers.as_str(), 16) {
if let Some(char) = Parser::from_u32(number) {
chars.push(char);
continue;
} else {
return Err(DecodingError::InvalidValue);
}
} else {
return Err(DecodingError::InvalidValue);
}
}
_ => return Err(DecodingError::InvalidValue),
}
} else {
// 其它字符
chars.push(char);
}
self.chars.next();
}
// 必须以 '\"' 结尾
if !self.next_if_match('\"') {
return Err(DecodingError::InvalidValue);
}
return Ok(Value::STRING(chars.into_iter().collect()));
}
fn parse_array(&mut self) -> Result<Value, DecodingError> {
if !self.next_if_match('[') {
return Err(DecodingError::InvalidValue);
}
self.skip_white_space();
if self.next_if_match(']') {
return Ok(Value::ARRAY(Vec::new()));
}
let mut array = Vec::new();
while let Ok(value) = self.parse_value() {
array.push(value);
if self.next_if_match(']') {
break;
} else if self.next_if_match(',') {
continue;
} else {
return Err(DecodingError::InvalidValue);
}
}
return Ok(Value::ARRAY(array));
}
fn parse_object(&mut self) -> Result<Value, DecodingError> {
if !self.next_if_match('{') {
return Err(DecodingError::InvalidValue);
}
self.skip_white_space();
if self.next_if_match('}') {
return Ok(Value::OBJECT(HashMap::new()));
}
let mut object = HashMap::new();
loop {
self.skip_white_space();
if let Ok(Value::STRING(key)) = self.parse_string() {
self.skip_white_space();
if !self.next_if_match(':') {
return Err(DecodingError::InvalidValue);
}
if let Ok(value) = self.parse_value() {
object.insert(key, value);
if self.next_if_match('}') {
break;
} else if self.next_if_match(',') {
continue;
} else {
return Err(DecodingError::InvalidValue);
}
} else {
return Err(DecodingError::InvalidValue);
}
} else {
return Err(DecodingError::InvalidValue);
}
}
return Ok(Value::OBJECT(object));
}
fn next_if_match(&mut self, expect_char: char) -> bool {
if let Some(char) = self.chars.peek() {
if *char == expect_char {
self.chars.next();
return true;
}
}
return false;
}
fn next_if_match_ignore_case(&mut self, expect_char: char) -> bool {
if let Some(char) = self.chars.peek() {
if char.eq_ignore_ascii_case(&expect_char) {
self.chars.next();
return true;
}
}
return false;
}
fn next_if_match_str(&mut self, chars: &str) -> bool {
for char in chars.chars() {
if !self.next_if_match(char) {
return false;
}
}
return true;
}
fn next_if_digit(&mut self) -> Option<char> {
if let Some(&char) = self.chars.peek() {
if char >= '0' && char <= '9' {
self.chars.next();
return Some(char);
}
}
return None;
}
fn next_if_hex_digit(&mut self) -> Option<char> {
if let Some(&char) = self.chars.peek() {
if (char >= '0' && char <= '9')
|| (char >= 'a' && char <= 'f')
|| (char >= 'A' && char <= 'F')
{
self.chars.next();
return Some(char);
}
}
return None;
}
fn from_u32(i: u32) -> Option<char> {
return if let Ok(char) = char::try_from(i) {
Some(char)
} else {
None
};
}
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_result(expect_result: Result<Value, DecodingError>, text: &str) {
let mut parser = Parser::new(text);
let actual_result = parser.parse();
assert_eq!(expect_result, actual_result);
}
#[test]
fn basic_tests() {
assert_result(Err(DecodingError::ExpectValue), "");
// null
assert_result(Ok(Value::NULL), "null");
assert_result(Ok(Value::NULL), "\r\n\t null");
assert_result(Err(DecodingError::InvalidValue), "nil");
assert_result(Err(DecodingError::InvalidValue), "n");
// true, false
assert_result(Ok(Value::TRUE), "true");
assert_result(Ok(Value::FALSE), "false");
assert_result(Err(DecodingError::RootNotSingular), "true_");
assert_result(Err(DecodingError::InvalidValue), "False_");
}
fn assert_number(expect_number: f64, text: &str) {
let mut parser = Parser::new(text);
let actual_result = parser.parse();
assert!(actual_result.is_ok());
assert_eq!(Value::NUMBER(expect_number), actual_result.unwrap());
}
#[test]
fn number_tests() {
assert_number(0.0, "0");
assert_number(0.0, "-0");
assert_number(0.0, "-0.0");
assert_number(1.0, "1");
assert_number(-1.0, "-1");
assert_number(1.5, "1.5");
assert_number(-1.5, "-1.5");
assert_number(3.1416, "3.1416");
assert_number(1E10, "1E10");
assert_number(1e10, "1e10");
assert_number(1E+10, "1E+10");
assert_number(1E-10, "1E-10");
assert_number(-1E10, "-1E10");
assert_number(-1e10, "-1e10");
assert_number(-1E+10, "-1E+10");
assert_number(-1E-10, "-1E-10");
assert_number(1.234E+10, "1.234E+10");
assert_number(1.234E-10, "1.234E-10");
assert_number(0.0, "1e-10000");
/* the smallest number > 1 */
assert_number(1.0000000000000002, "1.0000000000000002");
/* minimum denormal */
assert_number(4.9406564584124654e-324, "4.9406564584124654e-324");
assert_number(-4.9406564584124654e-324, "-4.9406564584124654e-324");
/* Max subnormal double */
assert_number(2.2250738585072009e-308, "2.2250738585072009e-308");
assert_number(-2.2250738585072009e-308, "-2.2250738585072009e-308");
/* Min normal positive double */
assert_number(2.2250738585072014e-308, "2.2250738585072014e-308");
assert_number(-2.2250738585072014e-308, "-2.2250738585072014e-308");
/* Max double */
assert_number(1.7976931348623157e+308, "1.7976931348623157e+308");
assert_number(-1.7976931348623157e+308, "-1.7976931348623157e+308");
assert_result(Err(DecodingError::InvalidValue), "+0");
assert_result(Err(DecodingError::InvalidValue), "+1");
assert_result(Err(DecodingError::InvalidValue), ".123");
assert_result(Err(DecodingError::InvalidValue), "1.");
assert_result(Err(DecodingError::InvalidValue), "INF");
assert_result(Err(DecodingError::InvalidValue), "inf");
assert_result(Err(DecodingError::InvalidValue), "NAN");
assert_result(Err(DecodingError::InvalidValue), "nan");
}
fn assert_string(expect_string: &str, text: &str) {
let mut parser = Parser::new(text);
let result = parser.parse();
assert_eq!(Ok(Value::STRING(expect_string.to_string())), result);
}
#[test]
fn string_tests() {
assert_string("", r#" "" "#);
assert_string("hello world", r#" "hello world" "#);
// 转义字符
assert_string("hello\n world", r#" "hello\n world" "#);
assert_string("hello\t world", r#" "hello\t world" "#);
assert_string("hello\r world", r#" "hello\r world" "#);
assert_string("hello\\ world", r#" "hello\\ world" "#);
assert_string("hello\" world", r#" "hello\" world" "#);
assert_string("hello/ world", r#" "hello\/ world" "#);
// 不支持的转移字符
assert_string("hello world", r#" "hello\b world" "#);
assert_string("hello world", r#" "hello\f world" "#);
// escaped unicode
assert_string("❤", r#" "\u2764" "#);
assert_result(Err(DecodingError::InvalidValue), r#" "hello "#);
assert_result(Err(DecodingError::InvalidValue), r#" hello" "#);
assert_result(Err(DecodingError::RootNotSingular), r#" "hello"hello" "#);
}
fn assert_array(ok_value: Vec<Value>, text: &str) {
let mut parser = Parser::new(text);
let result = parser.parse();
assert_eq!(Ok(Value::ARRAY(ok_value)), result);
}
#[test]
fn array_tests() {
assert_array(Vec::new(), r#" [] "#);
assert_array(
vec![
Value::STRING("hello".to_string()),
Value::STRING("world".to_string()),
Value::NUMBER(1.0),
Value::NUMBER(2.0),
Value::ARRAY(vec![
Value::STRING("colorful".to_string()),
Value::STRING("json".to_string()),
Value::TRUE,
Value::NULL,
]),
],
r#" ["hello", "world", 1.0, 2.0, ["colorful", "json", true, null]] "#,
);
assert_array(vec![
Value::ARRAY(vec![]),
Value::ARRAY(vec![])
], r#" [[],[]] "#);
assert_result(Err(DecodingError::InvalidValue), r#" ["abc", ["123", [1.0]] "#);
}
fn assert_object(expect_object: HashMap<String, Value>, text: &str) {
let mut parser = Parser::new(text);
let result = parser.parse();
assert_eq!(Ok(Value::OBJECT(expect_object)), result);
}
#[test]
fn object_tests() {
assert_object(HashMap::new(), r#" {} "#);
assert_object(
hashmap! {
"name".to_string() => Value::STRING("董哒哒".to_string()),
"age".to_string() => Value::NUMBER(42.0),
"color".to_string() => Value::ARRAY(vec![
Value::STRING("blue".to_string()),
Value::STRING("yellow".to_string()),
]),
"project".to_string() => Value::OBJECT(hashmap! {
"name".to_string() => Value::STRING("colorful-json".to_string()),
"done".to_string() => Value::TRUE,
})
},
r#" {
"name": "董哒哒",
"age": 42,
"color": [
"blue",
"yellow"
],
"project": {
"name": "colorful-json",
"done": true
}
} "#,
);
assert_object(hashmap! {
"".to_string() => Value::OBJECT(hashmap! {})
}, r#" {"": {}} "#);
assert_result(Err(DecodingError::InvalidValue), r#" {"name": { "age": 19 } "#);
assert_result(Err(DecodingError::RootNotSingular), r#" "name": "董哒哒" "#);
}
}
| 31.673835 | 89 | 0.481329 |
4b31f39330932e2b84dc6ef2845f7009430345a8 | 813 | // Copyright 2013 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.
extern crate collections;
use std::collections::HashMap;
trait Graph<Node, Edge> {
fn f(&self, Edge);
}
impl<E> Graph<int, E> for HashMap<int, int> {
fn f(&self, _e: E) {
panic!();
}
}
pub fn main() {
let g : Box<HashMap<int,int>> = box HashMap::new();
let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>;
}
| 27.1 | 68 | 0.672817 |
5b8a00d66571ad2164f13b18a340ad8edf8545b5 | 650 | // 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.
pub mod epsocket;
| 40.625 | 75 | 0.746154 |
ffe5fb2a147a2e2be50179f746658cb33fecbb07 | 1,341 | #[doc = "Reader of register ETMCLAIMCLR"]
pub type R = crate::R<u32, super::ETMCLAIMCLR>;
#[doc = "Writer for register ETMCLAIMCLR"]
pub type W = crate::W<u32, super::ETMCLAIMCLR>;
#[doc = "Register ETMCLAIMCLR `reset()`'s with value 0"]
impl crate::ResetValue for super::ETMCLAIMCLR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `CLRTAG`"]
pub type CLRTAG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CLRTAG`"]
pub struct CLRTAG_W<'a> {
w: &'a mut W,
}
impl<'a> CLRTAG_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Tag Bits"]
#[inline(always)]
pub fn clrtag(&self) -> CLRTAG_R {
CLRTAG_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Tag Bits"]
#[inline(always)]
pub fn clrtag(&mut self) -> CLRTAG_W {
CLRTAG_W { w: self }
}
}
| 26.294118 | 70 | 0.558538 |
d9fd201b909a7bc2390d2a180b23202039af67a8 | 15,927 | use anyhow::{
anyhow,
Result,
};
use iota_streams_app::message::{
HasLink as _,
LinkGenerator,
};
use iota_streams_core::{
prelude::Vec,
prng,
};
use super::*;
use crate::{
api,
message,
};
type UserImp = api::user::User<DefaultF, Address, LinkGen, LinkStore, PkStore, PskStore>;
/// Baseline User api object. Contains the api user implementation as well as the transport object
pub struct User<Trans> {
pub user: UserImp,
pub transport: Trans,
}
#[cfg(not(feature = "async"))]
impl<Trans> User<Trans>
where
Trans: Transport,
{
/// Create a new User instance.
///
/// # Arguments
/// * `seed` - A string slice representing the seed of the user [Characters: A-Z, 9]
/// * `encoding` - A string slice representing the encoding type for the message [supported: utf-8]
/// * `payload_length` - Maximum size in bytes of payload per message chunk [1-1024],
/// * `multi_branching` - Boolean representing use of multi-branch or single-branch sequencing
/// * `transport` - Transport object used for sending and receiving
///
pub fn new(seed: &str, encoding: &str, payload_length: usize, multi_branching: bool, transport: Trans) -> Self {
let nonce = "TANGLEUSERNONCE".as_bytes().to_vec();
let user = UserImp::gen(
prng::from_seed("IOTA Streams Channels user sig keypair", seed),
nonce,
if multi_branching { 1 } else { 0 },
encoding.as_bytes().to_vec(),
payload_length,
);
Self { user, transport }
}
// Attributes
/// Fetch the Address (application instance) of the channel.
pub fn channel_address(&self) -> Option<&ChannelAddress> {
self.user.appinst.as_ref().map(|x| &x.appinst)
}
/// Return boolean representing the sequencing nature of the channel
pub fn is_multi_branching(&self) -> bool {
self.user.is_multi_branching()
}
/// Fetch the user ed25519 public key
pub fn get_pk(&self) -> &PublicKey {
&self.user.sig_kp.public
}
pub fn is_registered(&self) -> bool {
self.user.appinst.is_some()
}
pub fn unregister(&mut self) {
self.user.appinst = None;
self.user.author_sig_pk = None;
}
// Send
/// Send a message with sequencing logic. If channel is single-branched, then no secondary
/// sequence message is sent and None is returned for the address.
///
/// # Arguments
/// * `wrapped` - A wrapped sequence object containing the sequence message and state
///
fn send_sequence(&mut self, wrapped: WrappedSequence) -> Result<Option<Address>> {
if let Some(seq_msg) = wrapped.0 {
self.transport.send_message(&Message::new(seq_msg))?;
}
if let Some(wrap_state) = wrapped.1 {
self.user.commit_sequence(wrap_state, MsgInfo::Sequence)
} else {
Ok(None)
}
}
/// Send a message without using sequencing logic. Reserved for Announce and Subscribe messages
fn send_message(&mut self, msg: WrappedMessage, info: MsgInfo) -> Result<Address> {
self.transport.send_message(&Message::new(msg.message))?;
self.user.commit_wrapped(msg.wrapped, info)
}
/// Send a message using sequencing logic.
///
/// # Arguments
/// * `msg` - Wrapped Message ready for sending
/// * `ref_link` - Reference link to be included in sequence message
/// * `info` - Enum denominating the type of message being sent and committed
///
fn send_message_sequenced(
&mut self,
msg: WrappedMessage,
ref_link: &MsgId,
info: MsgInfo,
) -> Result<(Address, Option<Address>)> {
let seq = self.user.wrap_sequence(ref_link)?;
self.transport.send_message(&Message::new(msg.message))?;
let seq_link = self.send_sequence(seq)?;
let msg_link = self.user.commit_wrapped(msg.wrapped, info)?;
Ok((msg_link, seq_link))
}
/// Send an announcement message, generating a channel [Author].
pub fn send_announce(&mut self) -> Result<Address> {
let msg = self.user.announce()?;
self.send_message(msg, MsgInfo::Announce)
}
/// Create and send a signed packet [Author, Subscriber].
///
/// # Arguments
/// * `link_to` - Address of the message the keyload will be attached to
/// * `public_payload` - Wrapped vector of Bytes to have public access
/// * `masked_payload` - Wrapped vector of Bytes to have masked access
///
pub fn send_signed_packet(
&mut self,
link_to: &Address,
public_payload: &Bytes,
masked_payload: &Bytes,
) -> Result<(Address, Option<Address>)> {
let msg = self.user.sign_packet(&link_to.msgid, public_payload, masked_payload)?;
self.send_message_sequenced(msg, link_to.rel(), MsgInfo::SignedPacket)
}
/// Create and send a tagged packet [Author, Subscriber].
///
/// # Arguments
/// * `link_to` - Address of the message the keyload will be attached to
/// * `public_payload` - Wrapped vector of Bytes to have public access
/// * `masked_payload` - Wrapped vector of Bytes to have masked access
///
pub fn send_tagged_packet(
&mut self,
link_to: &Address,
public_payload: &Bytes,
masked_payload: &Bytes,
) -> Result<(Address, Option<Address>)> {
let msg = self.user.tag_packet(&link_to.msgid, public_payload, masked_payload)?;
self.send_message_sequenced(msg, link_to.rel(), MsgInfo::TaggedPacket)
}
/// Create and send a new keyload for a list of subscribers [Author].
///
/// # Arguments
/// * `link_to` - Address of the message the keyload will be attached to
/// * `psk_ids` - Vector of Pre-shared key ids to be included in message
/// * `ke_pks` - Vector of Public Keys to be included in message
///
pub fn send_keyload(
&mut self,
link_to: &Address,
psk_ids: &PskIds,
ke_pks: &Vec<PublicKey>,
) -> Result<(Address, Option<Address>)> {
let msg = self.user.share_keyload(&link_to.msgid, psk_ids, ke_pks)?;
self.send_message_sequenced(msg, link_to.rel(), MsgInfo::Keyload)
}
/// Create and send keyload for all subscribed subscribers [Author].
///
/// # Arguments
/// * `link_to` - Address of the message the keyload will be attached to
///
pub fn send_keyload_for_everyone(&mut self, link_to: &Address) -> Result<(Address, Option<Address>)> {
let msg = self.user.share_keyload_for_everyone(&link_to.msgid)?;
self.send_message_sequenced(msg, link_to.rel(), MsgInfo::Keyload)
}
/// Create and Send a Subscribe message to a Channel app instance [Subscriber].
///
/// # Arguments
/// * `link_to` - Address of the Channel Announcement message
///
pub fn send_subscribe(&mut self, link_to: &Address) -> Result<Address> {
let msg = self.user.subscribe(&link_to.msgid)?;
self.send_message(msg, MsgInfo::Subscribe)
}
// Receive
/// Receive and process a sequence message [Author, Subscriber].
///
/// # Arguments
/// * `link` - Address of the message to be processed
///
pub fn receive_sequence(&mut self, link: &Address) -> Result<Address> {
let msg = self.transport.recv_message(link)?;
if let Some(_addr) = &self.user.appinst {
let seq_link = msg.binary.link.clone();
let seq_msg = self.user.handle_sequence(msg.binary, MsgInfo::Sequence)?.body;
let msg_id = self.user.link_gen.link_from(
&seq_msg.pk,
Cursor::new_at(&seq_msg.ref_link, 0, seq_msg.seq_num.0 as u32),
);
if self.is_multi_branching() {
self.store_state(seq_msg.pk, &seq_link)
} else {
self.store_state_for_all(&seq_link, seq_msg.seq_num.0 as u32)
}
Ok(msg_id)
} else {
Err(anyhow!("No channel registered"))
}
}
/// Receive and process a signed packet message [Author, Subscriber].
///
/// # Arguments
/// * `link` - Address of the message to be processed
///
pub fn receive_signed_packet(&mut self, link: &Address) -> Result<(PublicKey, Bytes, Bytes)> {
let msg = self.transport.recv_message(link)?;
// TODO: msg.timestamp is lost
let m = self.user.handle_signed_packet(msg.binary, MsgInfo::SignedPacket)?;
Ok(m.body)
}
/// Receive and process a tagged packet message [Author, Subscriber].
///
/// # Arguments
/// * `link` - Address of the message to be processed
///
pub fn receive_tagged_packet(&mut self, link: &Address) -> Result<(Bytes, Bytes)> {
let msg = self.transport.recv_message(link)?;
let m = self.user.handle_tagged_packet(msg.binary, MsgInfo::TaggedPacket)?;
Ok(m.body)
}
/// Receive and process a subscribe message [Author].
///
/// # Arguments
/// * `link` - Address of the message to be processed
///
pub fn receive_subscribe(&mut self, link: &Address) -> Result<()> {
let msg = self.transport.recv_message(link)?;
// TODO: Timestamp is lost.
self.user.handle_subscribe(msg.binary, MsgInfo::Subscribe)
}
/// Receive and Process an announcement message [Subscriber].
///
/// # Arguments
/// * `link_to` - Address of the Channel Announcement message
///
pub fn receive_announcement(&mut self, link: &Address) -> Result<()> {
let msg = self.transport.recv_message(link)?;
self.user.handle_announcement(msg.binary, MsgInfo::Announce)
}
/// Receive and process a keyload message [Subscriber].
///
/// # Arguments
/// * `link` - Address of the message to be processed
///
pub fn receive_keyload(&mut self, link: &Address) -> Result<bool> {
let msg = self.transport.recv_message(link)?;
let m = self.user.handle_keyload(msg.binary, MsgInfo::Keyload)?;
Ok(m.body)
}
/// Receive and process a message of unknown type. Message will be handled appropriately and
/// the unwrapped contents returned [Author, Subscriber].
///
/// # Arguments
/// * `link` - Address of the message to be processed
/// * `pk` - Optional ed25519 Public Key of the sending participant. None if unknown
///
pub fn receive_message(&mut self, link: &Address, pk: Option<PublicKey>) -> Result<UnwrappedMessage> {
let msg = self.transport.recv_message(link)?;
self.handle_message(msg, pk)
}
// Utility
/// Stores the provided link to the internal sequencing state for the provided participant
/// [Used for multi-branching sequence state updates]
/// [Author, Subscriber]
///
/// # Arguments
/// * `pk` - ed25519 Public Key of the sender of the message
/// * `link` - Address link to be stored in internal sequence state mapping
///
pub fn store_state(&mut self, pk: PublicKey, link: &Address) {
// TODO: assert!(link.appinst == self.appinst.unwrap());
self.user.store_state(pk, link.msgid.clone())
}
/// Stores the provided link and sequence number to the internal sequencing state for all participants
/// [Used for single-branching sequence state updates]
/// [Author, Subscriber]
///
/// # Arguments
/// * `link` - Address link to be stored in internal sequence state mapping
/// * `seq_num` - New sequence state to be stored in internal sequence state mapping
///
pub fn store_state_for_all(&mut self, link: &Address, seq_num: u32) {
// TODO: assert!(link.appinst == self.appinst.unwrap());
self.user.store_state_for_all(link.msgid.clone(), seq_num)
}
/// Generate a vector containing the next sequenced message identifier for each publishing
/// participant in the channel
/// [Author, Subscriber]
///
/// # Arguments
/// * `branching` - Boolean representing the sequencing nature of the channel
///
pub fn gen_next_msg_ids(&mut self, branching: bool) -> Vec<(PublicKey, Cursor<Address>)> {
self.user.gen_next_msg_ids(branching)
}
/// Retrieves the next message for each user (if present in transport layer) and returns them [Author, Subscriber]
pub fn fetch_next_msgs(&mut self) -> Vec<UnwrappedMessage> {
let ids = self.user.gen_next_msg_ids(self.user.is_multi_branching());
let mut msgs = Vec::new();
for (
pk,
Cursor {
link,
branch_no: _,
seq_no,
},
) in ids
{
let msg = self.transport.recv_message(&link);
if msg.is_ok() {
let msg = self.handle_message(msg.unwrap(), Some(pk));
if let Ok(msg) = msg {
if !self.user.is_multi_branching() {
self.user.store_state_for_all(link.msgid, seq_no);
}
msgs.push(msg);
}
}
}
msgs
}
/// Handle message of unknown type. Ingests a message and unwraps it according to it's determined
/// content type [Author, Subscriber].
///
/// # Arguments
/// * `msg` - Binary message of unknown type
/// * `pk` - Optional ed25519 Public Key of the sending participant. None if unknown
///
pub fn handle_message(&mut self, msg: Message, pk: Option<PublicKey>) -> Result<UnwrappedMessage> {
// Forget TangleMessage and timestamp
let msg = msg.binary;
let preparsed = msg.parse_header()?;
match preparsed.header.content_type {
message::SIGNED_PACKET => {
let m = self.user.handle_signed_packet(msg, MsgInfo::SignedPacket)?;
let u = m.map(|(pk, public, masked)| MessageContent::new_signed_packet(pk, public, masked));
Ok(u)
}
message::TAGGED_PACKET => {
let m = self.user.handle_tagged_packet(msg, MsgInfo::TaggedPacket)?;
let u = m.map(|(public, masked)| MessageContent::new_tagged_packet(public, masked));
Ok(u)
}
message::KEYLOAD => {
// So long as the unwrap has not failed, we will return a blank object to
// inform the user that a message was present, even if the use wasn't part of
// the keyload itself. This is to prevent sequencing failures
let m = self.user.handle_keyload(msg, MsgInfo::Keyload)?;
// TODO: Verify content, whether user is allowed or not!
let u = m.map(|_allowed| MessageContent::new_keyload());
Ok(u)
}
message::SEQUENCE => {
let store_link = msg.link.rel().clone();
let unwrapped = self.user.handle_sequence(msg, MsgInfo::Sequence)?;
let msg_link = self.user.link_gen.link_from(
&unwrapped.body.pk,
Cursor::new_at(&unwrapped.body.ref_link, 0, unwrapped.body.seq_num.0 as u32),
);
let msg = self.transport.recv_message(&msg_link)?;
self.user.store_state(pk.unwrap().clone(), store_link);
self.handle_message(msg, pk)
}
unknown_content => Err(anyhow!("Not a recognised message type: {}", unknown_content)),
}
}
pub fn export(&self, flag: u8, pwd: &str) -> Result<Vec<u8>> {
self.user.export(flag, pwd)
}
pub fn import(bytes: &[u8], flag: u8, pwd: &str, tsp: Trans) -> Result<Self> {
UserImp::import(bytes, flag, pwd).map(|u| Self { user: u, transport: tsp, })
}
}
| 37.475294 | 118 | 0.603441 |
8a59c89afa2dc29612fc4fb4fd35f22e13f3cd7d | 10,166 | //! Utilities for high level parsing of js code.
use crate::*;
use rome_js_syntax::{AstNode, JsAnyRoot, JsExpressionSnipped, JsModule, JsScript, SyntaxNode};
use rslint_errors::Severity;
use std::marker::PhantomData;
/// A utility struct for managing the result of a parser job
#[derive(Debug, Clone)]
pub struct Parse<T> {
root: SyntaxNode,
errors: Vec<ParserError>,
_ty: PhantomData<T>,
}
impl<T> Parse<T> {
pub fn new_module(root: SyntaxNode, errors: Vec<ParserError>) -> Parse<T> {
Self::new(root, errors)
}
pub fn new_script(root: SyntaxNode, errors: Vec<ParserError>) -> Parse<T> {
Self::new(root, errors)
}
pub fn new(root: SyntaxNode, errors: Vec<ParserError>) -> Parse<T> {
Parse {
root,
errors,
_ty: PhantomData,
}
}
pub fn cast<N: AstNode>(self) -> Option<Parse<N>> {
if N::can_cast(self.syntax().kind()) {
Some(Parse::new(self.root, self.errors))
} else {
None
}
}
/// The syntax node represented by this Parse result
///
/// ```
/// use rslint_parser::parse_script;
/// use rome_js_syntax::{JsIfStatement, SyntaxNodeExt, JsSyntaxKind, AstNode, AstNodeList};
///
/// let parse = parse_script(
/// "
/// if (a > 5) {
/// /* something */
/// }
/// ", 0);
///
/// // The first stmt in the root syntax node (Script) is the if statement.
/// let if_stmt = parse.tree().statements().first().unwrap();
///
/// assert_eq!(if_stmt.syntax().kind(), JsSyntaxKind::JS_IF_STATEMENT);
/// ```
pub fn syntax(&self) -> SyntaxNode {
self.root.clone()
}
/// Get the diagnostics which occurred when parsing
pub fn diagnostics(&self) -> &[Diagnostic] {
self.errors.as_slice()
}
/// Get the diagnostics which occurred when parsing
pub fn into_diagnostics(self) -> Vec<Diagnostic> {
self.errors
}
/// Returns [true] if the parser encountered some errors during the parsing.
pub fn has_errors(&self) -> bool {
self.errors.iter().any(|diagnostic| diagnostic.is_error())
}
}
impl<T: AstNode> Parse<T> {
/// Convert this parse result into a typed AST node.
///
/// # Panics
/// Panics if the node represented by this parse result mismatches.
pub fn tree(&self) -> T {
self.try_tree().unwrap_or_else(|| {
panic!(
"Expected tree to be a {} but root is:\n{:#?}",
std::any::type_name::<T>(),
self.syntax()
)
})
}
/// Try to convert this parse's untyped syntax node into an AST node.
pub fn try_tree(&self) -> Option<T> {
T::cast(self.syntax())
}
/// Convert this parse into a result
pub fn ok(self) -> Result<T, Vec<ParserError>> {
if !self.errors.iter().any(|d| d.severity == Severity::Error) {
Ok(self.tree())
} else {
Err(self.errors)
}
}
}
/// Run the rslint_lexer lexer to turn source code into tokens and errors produced by the lexer
pub fn tokenize(text: &str, file_id: usize) -> (Vec<rslint_lexer::Token>, Vec<ParserError>) {
let mut tokens = Vec::new();
let mut errors = Vec::new();
for (tok, error) in rslint_lexer::Lexer::from_str(text, file_id) {
tokens.push(tok);
if let Some(err) = error {
// waiting for https://github.com/rust-lang/rust/issues/80437
errors.push(*err)
}
}
(tokens, errors)
}
fn parse_common(
text: &str,
file_id: usize,
source_type: SourceType,
) -> (Vec<Event>, Vec<ParserError>, Vec<rslint_lexer::Token>) {
let (tokens, mut errors) = tokenize(text, file_id);
let tok_source = TokenSource::new(text, &tokens);
let mut parser = crate::Parser::new(tok_source, file_id, source_type);
crate::syntax::program::parse(&mut parser);
let (events, p_errs) = parser.finish();
errors.extend(p_errs);
(events, errors, tokens)
}
/// Parse text into a [`Parse`](Parse) which can then be turned into an untyped root [`SyntaxNode`](SyntaxNode).
/// Or turned into a typed [`Script`](Script) with [`tree`](Parse::tree).
///
/// ```
/// use rslint_parser::parse_script;
/// use rome_js_syntax::{AstNode, SyntaxToken, SyntaxNodeExt, SyntaxList, util, JsComputedMemberExpression};
///
/// let parse = parse_script("foo.bar[2]", 0);
/// // Parse returns a JS Root which contains two lists, the directives and the statements, let's get the statements
/// let stmt = parse.syntax().children().nth(1).unwrap();
/// // The untyped syntax node of `foo.bar[2]`, the root node is `Script`.
/// let untyped_expr_node = stmt.first_child().unwrap();
///
/// // SyntaxNodes can be turned into a nice string representation.
/// println!("{:#?}", untyped_expr_node);
///
/// // You can then cast syntax nodes into a typed AST node.
/// let typed_ast_node = JsComputedMemberExpression::cast(untyped_expr_node.first_child().unwrap()).unwrap();
///
/// // Everything on every ast node is optional because of error recovery.
/// let prop = dbg!(typed_ast_node.member()).unwrap();
///
/// // You can then go back to an untyped SyntaxNode and get its range, text, parents, children, etc.
/// assert_eq!(prop.syntax().text(), "2");
///
/// // Util has a function for yielding all tokens of a node.
/// let tokens = untyped_expr_node.tokens();
///
/// assert_eq!(&util::concat_tokens(&tokens), "foo.bar[2]")
/// ```
pub fn parse_script(text: &str, file_id: usize) -> Parse<JsScript> {
parse(
text,
file_id,
SourceType::js_module().with_module_kind(ModuleKind::Script),
)
.cast::<JsScript>()
.unwrap()
}
/// Lossly parse text into a [`Parse`](Parse) which can then be turned into an untyped root [`SyntaxNode`](SyntaxNode).
/// Or turned into a typed [`Script`](Script) with [`tree`](Parse::tree).
///
/// Unlike [`parse_text`], the final parse result includes no whitespace, it does however include errors.
///
/// Note however that the ranges and text of nodes still includes whitespace! Therefore you should trim text before rendering it.
/// The [`util`](crate::util) module has utility functions for dealing with this easily.
///
/// ```
/// use rslint_parser::parse_script_lossy;
/// use rome_js_syntax::{JsComputedMemberExpression, AstNode, SyntaxToken, SyntaxNodeExt, util, SyntaxList};
///
/// let parse = parse_script_lossy("foo.bar[2]", 0);
/// // Parse returns a JS Root with two children, an empty list of directives and the list of statements, let's get the statements
/// let stmt = parse.syntax().children().nth(1).unwrap();
/// // The untyped syntax node of `foo.bar[2]`, the root node is `Script`.
/// let untyped_expr_node = stmt.first_child().unwrap();
///
/// // SyntaxNodes can be turned into a nice string representation.
/// println!("{:#?}", untyped_expr_node);
///
/// // You can then cast syntax nodes into a typed AST node.
/// let typed_ast_node = JsComputedMemberExpression::cast(untyped_expr_node.first_child().unwrap()).unwrap();
///
/// // Everything on every ast node is optional because of error recovery.
/// let prop = typed_ast_node.member().unwrap();
///
/// // You can then go back to an untyped SyntaxNode and get its range, text, parents, children, etc.
/// assert_eq!(prop.syntax().text(), "2");
///
/// // Util has a function for yielding all tokens of a node.
/// let tokens = untyped_expr_node.tokens();
///
/// // End result does not include whitespace because the parsing is lossy in this case
/// assert_eq!(&util::concat_tokens(&tokens), "foo.bar[2]")
/// ```
pub fn parse_script_lossy(text: &str, file_id: usize) -> Parse<JsScript> {
let (events, errors, tokens) = parse_common(
text,
file_id,
SourceType::js_module().with_module_kind(ModuleKind::Script),
);
let mut tree_sink = LossyTreeSink::new(text, &tokens);
crate::process(&mut tree_sink, events, errors);
let (green, parse_errors) = tree_sink.finish();
Parse::new_script(green, parse_errors)
}
/// Same as [`parse_text_lossy`] but configures the parser to parse an ECMAScript module instead of a Script
pub fn parse_module_lossy(text: &str, file_id: usize) -> Parse<JsModule> {
let (events, errors, tokens) = parse_common(text, file_id, SourceType::js_module());
let mut tree_sink = LossyTreeSink::new(text, &tokens);
crate::process(&mut tree_sink, events, errors);
let (green, parse_errors) = tree_sink.finish();
Parse::new_module(green, parse_errors)
}
/// Same as [`parse_text`] but configures the parser to parse an ECMAScript module instead of a script
pub fn parse_module(text: &str, file_id: usize) -> Parse<JsModule> {
parse(text, file_id, SourceType::js_module())
.cast::<JsModule>()
.unwrap()
}
/// Parses the provided string as a EcmaScript program using the provided syntax features.
pub fn parse(text: &str, file_id: usize, source_type: SourceType) -> Parse<JsAnyRoot> {
let (events, errors, tokens) = parse_common(text, file_id, source_type);
let mut tree_sink = LosslessTreeSink::new(text, &tokens);
crate::process(&mut tree_sink, events, errors);
let (green, parse_errors) = tree_sink.finish();
Parse::new(green, parse_errors)
}
/// Losslessly Parse text into an expression [`Parse`](Parse) which can then be turned into an untyped root [`SyntaxNode`](SyntaxNode).
/// Or turned into a typed [`Expr`](Expr) with [`tree`](Parse::tree).
pub fn parse_expression(text: &str, file_id: usize) -> Parse<JsExpressionSnipped> {
let (tokens, mut errors) = tokenize(text, file_id);
let tok_source = TokenSource::new(text, &tokens);
let mut parser = crate::Parser::new(tok_source, file_id, SourceType::js_module());
crate::syntax::expr::parse_expression_snipped(&mut parser).unwrap();
let (events, p_diags) = parser.finish();
errors.extend(p_diags);
let mut tree_sink = LosslessTreeSink::new(text, &tokens);
crate::process(&mut tree_sink, events, errors);
let (green, parse_errors) = tree_sink.finish();
Parse::new_script(green, parse_errors)
}
| 37.932836 | 135 | 0.647059 |
e6adfdc13aa2bb1d550e67c36b4ae19ec654453d | 2,207 | use std::sync::mpsc;
use std::sync::{atomic::AtomicBool, Arc};
use std::thread;
use std::time::Duration;
use crossterm::event::{self, Event as CEvent, KeyEvent};
pub enum Event<I> {
Input(I),
Tick,
}
/// A small event handler that wrap termion input and tick events. Each event
/// type is handled in its own thread and returned to a common `Receiver`
pub struct Events {
rx: mpsc::Receiver<Event<KeyEvent>>,
_input_handle: thread::JoinHandle<()>,
_ignore_exit_key: Arc<AtomicBool>,
_tick_handle: thread::JoinHandle<()>,
}
#[derive(Debug, Clone, Copy)]
pub struct Config {
pub tick_rate: Duration,
}
impl Default for Config {
fn default() -> Config {
Config {
tick_rate: Duration::from_millis(250),
}
}
}
impl Events {
pub fn new() -> Events {
Events::with_config(Config::default())
}
pub fn with_config(config: Config) -> Events {
let (tx, rx) = mpsc::channel();
let ignore_exit_key = Arc::new(AtomicBool::new(false));
let input_handle = {
let tx = tx.clone();
thread::spawn(move || {
loop {
// poll for tick rate duration, if no events, sent tick event.
if event::poll(std::time::Duration::from_millis(10)).unwrap() {
if let CEvent::Key(key) = event::read().unwrap() {
if let Err(_) = tx.send(Event::Input(key)) {
return;
}
}
}
}
})
};
let tick_handle = {
let tx = tx.clone();
thread::spawn(move || {
let tx = tx.clone();
loop {
tx.send(Event::Tick).unwrap();
thread::sleep(config.tick_rate);
}
})
};
Events {
rx,
_ignore_exit_key: ignore_exit_key,
_input_handle: input_handle,
_tick_handle: tick_handle,
}
}
pub fn next(&self) -> Result<Event<KeyEvent>, mpsc::RecvError> {
self.rx.recv()
}
}
| 27.5875 | 83 | 0.50068 |
ef46a12b27728e97f783586989f9852b0bae0778 | 585 | // This powerful wrapper provides the ability to store a positive integer value.
// Rewrite it using generics so that it supports wrapping ANY type.
// Execute `rustlings hint generics2` for hints!
struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
pub fn new(value: T) -> Self {
return Wrapper { value };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn store_u32_in_wrapper() {
assert_eq!(Wrapper::new(42).value, 42);
}
#[test]
fn store_str_in_wrapper() {
assert_eq!(Wrapper::new("Foo").value, "Foo");
}
}
| 19.5 | 80 | 0.610256 |
082ca639f8849dc065322aafa350622f28b2c5ac | 10,916 | use cumulus_primitives_core::ParaId;
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup, Properties};
use sc_service::ChainType;
use serde::{Deserialize, Serialize};
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};
use sp_core::crypto::Ss58Codec;
use kpron_runtime::constants::currency::{EXISTENTIAL_DEPOSIT, SYMBOL, DECIMALS};
use kpron_runtime::constants::address::{SS58_PREFIX};
use statemint_common::{
Signature, AccountId, AuraId,
};
/// Specialized `ChainSpec` for the normal Kpron runtime.
pub type ChainSpec = sc_service::GenericChainSpec<kpron_runtime::GenesisConfig, Extensions>;
/// Helper function to generate a crypto pair from seed
pub fn get_from_dev_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(seed, None)
.expect("static values are valid; qed")
.public()
}
/// The extensions for the [`ChainSpec`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
#[serde(deny_unknown_fields)]
pub struct Extensions {
/// The relay chain of the Parachain.
pub relay_chain: String,
/// The id of the Parachain.
pub para_id: u32,
}
impl Extensions {
/// Try to get the extension from the given `ChainSpec`.
pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {
sc_chain_spec::get_extension(chain_spec.extensions())
}
}
type AccountPublic = <Signature as Verify>::Signer;
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_dev_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_dev_seed::<TPublic>(seed)).into_account()
}
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
pub fn get_account_id_from_str<TPublic: Public>(s: &str) -> AccountId
where AccountId: From<TPublic>
{
let public = TPublic::from_string(s).unwrap();
AccountId::from(public)
}
/// Generate collator keys from seed.
///
/// This function's return type must always match the session keys of the chain in tuple format.
pub fn get_collator_keys_from_dev_seed(seed: &str) -> AuraId {
get_from_dev_seed::<AuraId>(seed)
}
/// Generate the session keys from individual elements.
///
/// The input must be a tuple of individual keys (a single arg for now since we have just one key).
pub fn kpron_session_keys(keys: AuraId) -> kpron_runtime::opaque::SessionKeys {
kpron_runtime::opaque::SessionKeys { aura: keys }
}
pub fn kpron_config(id: ParaId) -> ChainSpec {
ChainSpec::from_genesis(
// Name
"Kpron",
// ID
"kpron",
ChainType::Live,
move || {
generate_genesis(
vec![
(
AccountId::from_string("5Dh7s4b8rs2emsq7hvvpTJTtJwNXoGxHbbrxwBGeNd9VuXo1").unwrap(),
AuraId::from_string("5Dh7s4b8rs2emsq7hvvpTJTtJwNXoGxHbbrxwBGeNd9VuXo1").unwrap()
),
(
AccountId::from_string("5GYqdDCfzTExVaUbZ3neycG6mR8iFrYFK6HPJhJictBuksRj").unwrap(),
AuraId::from_string("5GYqdDCfzTExVaUbZ3neycG6mR8iFrYFK6HPJhJictBuksRj").unwrap()
),
],
vec![
(get_account_id_from_str::<sr25519::Public>("5DoJDZNU84uLQz19kj4KhpFDxdnaQv9mNw8QTDSGDaPWdxfE"), 1_000_000_000_000_000_000_000),
],
id,
)
},
Vec::new(),
None,
Some("kpron"),
chain_properties(),
Extensions {
relay_chain: "kusama".into(),
para_id: id.into(),
},
)
}
pub fn kpron_testnet_config(id: ParaId) -> ChainSpec {
ChainSpec::from_genesis(
// Name
"Kpron testnet",
// ID
"kpron_testnet",
ChainType::Custom(String::from("Test")),
move || {
generate_genesis(
vec![
(
AccountId::from_string("5Dh7s4b8rs2emsq7hvvpTJTtJwNXoGxHbbrxwBGeNd9VuXo1").unwrap(),
AuraId::from_string("5Dh7s4b8rs2emsq7hvvpTJTtJwNXoGxHbbrxwBGeNd9VuXo1").unwrap()
),
(
AccountId::from_string("5GYqdDCfzTExVaUbZ3neycG6mR8iFrYFK6HPJhJictBuksRj").unwrap(),
AuraId::from_string("5GYqdDCfzTExVaUbZ3neycG6mR8iFrYFK6HPJhJictBuksRj").unwrap()
),
],
vec![
(get_account_id_from_str::<sr25519::Public>("5DoJDZNU84uLQz19kj4KhpFDxdnaQv9mNw8QTDSGDaPWdxfE"), 1_000_000_000_000_000_000_000),
],
id,
)
},
Vec::new(),
None,
Some("kpron"),
chain_properties(),
Extensions {
relay_chain: "westend".into(),
para_id: id.into(),
},
)
}
pub fn kpron_dev_config(id: ParaId) -> ChainSpec {
ChainSpec::from_genesis(
// Name
"Kpron Development",
// ID
"kpron_dev",
ChainType::Development,
move || {
test_generate_genesis(
get_account_id_from_dev_seed::<sr25519::Public>("Alice"),
vec![
(
get_account_id_from_dev_seed::<sr25519::Public>("Alice"),
get_collator_keys_from_dev_seed("Alice"),
),
(
get_account_id_from_dev_seed::<sr25519::Public>("Bob"),
get_collator_keys_from_dev_seed("Bob"),
)
],
vec![
(get_account_id_from_dev_seed::<sr25519::Public>("Alice"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Bob"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Alice//stash"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Bob//stash"), 1 << 60),
],
id,
)
},
Vec::new(),
None,
Some("kpron"),
chain_properties(),
Extensions {
relay_chain: "kusama-dev".into(),
para_id: id.into(),
},
)
}
pub fn kpron_local_config(id: ParaId) -> ChainSpec {
ChainSpec::from_genesis(
// Name
"Kpron Local",
// ID
"kpron_local",
ChainType::Local,
move || {
test_generate_genesis(
get_account_id_from_dev_seed::<sr25519::Public>("Alice"),
vec![
(
get_account_id_from_dev_seed::<sr25519::Public>("Alice"),
get_collator_keys_from_dev_seed("Alice"),
),
(
get_account_id_from_dev_seed::<sr25519::Public>("Bob"),
get_collator_keys_from_dev_seed("Bob"),
)
],
vec![
(get_account_id_from_dev_seed::<sr25519::Public>("Alice"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Bob"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Charlie"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Dave"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Eve"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Ferdie"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Alice//stash"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Bob//stash"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Charlie//stash"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Dave//stash"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Eve//stash"), 1 << 60),
(get_account_id_from_dev_seed::<sr25519::Public>("Ferdie//stash"), 1 << 60),
],
id,
)
},
Vec::new(),
None,
Some("kpron"),
chain_properties(),
Extensions {
relay_chain: "kusama-local".into(),
para_id: id.into(),
},
)
}
fn generate_genesis(
invulnerables: Vec<(AccountId, AuraId)>,
endowed_accounts: Vec<(AccountId, u128)>,
id: ParaId,
) -> kpron_runtime::GenesisConfig {
// TODO check invulnerables balance > STATEMINE_ED * 16
kpron_runtime::GenesisConfig {
system: kpron_runtime::SystemConfig {
code: kpron_runtime::WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
changes_trie_config: Default::default(),
},
balances: kpron_runtime::BalancesConfig {
balances: endowed_accounts,
},
parachain_info: kpron_runtime::ParachainInfoConfig { parachain_id: id },
collator_selection: kpron_runtime::CollatorSelectionConfig {
invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(),
candidacy_bond: EXISTENTIAL_DEPOSIT * 16, //16KPN
..Default::default()
},
session: kpron_runtime::SessionConfig {
keys: invulnerables.iter().cloned().map(|(acc, aura)| (
acc.clone(), // account id
acc.clone(), // validator id
kpron_session_keys(aura), // session keys
)).collect()
},
aura: Default::default(),
aura_ext: Default::default(),
parachain_system: Default::default(),
}
}
fn test_generate_genesis(
root_key: AccountId,
invulnerables: Vec<(AccountId, AuraId)>,
endowed_accounts: Vec<(AccountId, u128)>,
id: ParaId,
) -> kpron_runtime::GenesisConfig {
// TODO check invulnerables balance > EXISTENTIAL_DEPOSIT * 16
kpron_runtime::GenesisConfig {
system: kpron_runtime::SystemConfig {
code: kpron_runtime::WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
changes_trie_config: Default::default(),
},
balances: kpron_runtime::BalancesConfig {
balances: endowed_accounts,
},
parachain_info: kpron_runtime::ParachainInfoConfig { parachain_id: id },
collator_selection: kpron_runtime::CollatorSelectionConfig {
invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(),
candidacy_bond: EXISTENTIAL_DEPOSIT * 16, // 16KPN
..Default::default()
},
session: kpron_runtime::SessionConfig {
keys: invulnerables.iter().cloned().map(|(acc, aura)| (
acc.clone(), // account id
acc.clone(), // validator id
kpron_session_keys(aura), // session keys
)).collect()
},
aura: Default::default(),
aura_ext: Default::default(),
parachain_system: Default::default(),
}
}
fn chain_properties() -> Option<Properties> {
let mut p = Properties::new();
p.insert("tokenSymbol".into(), SYMBOL.into());
p.insert("tokenDecimals".into(), DECIMALS.into());
p.insert("ss58Format".into(), SS58_PREFIX.into());
Some(p)
}
#[cfg(test)]
mod spec_tests {
use super::*;
use std::str::FromStr;
use sp_core::crypto::Ss58Codec;
use sp_core::ed25519;
#[test]
fn test_get_account() {
let addr_str = "xx";
let public_str = "xx";
let seed_str = "xx";
let result = AccountId::from_str(addr_str);
println!("from str: {}", result.unwrap());
let result = AccountId::from_str(public_str);
let account = result.unwrap();
println!("from str: {}", account);
let result1 = AuraId::from_string(addr_str);
let public = result1.unwrap();
println!("AuraId, {}", public.to_ss58check());
let result1 = sr25519::Public::from_string(public_str);
let public = result1.unwrap();
println!("sr25519::Public, {}", public.to_ss58check());
let addr1 = get_from_seed::<AuraId>(seed_str);
let addr2 = get_from_seed::<sr25519::Public>(seed_str);
let addr3 = get_from_seed::<ed25519::Public>(seed_str);
println!("addr1: {} \naddr2: {}\naddr3: {}", addr1, addr2, addr3);
}
}
| 30.322222 | 133 | 0.69018 |
ded0f316a150e9905db8eba8e1066210fc67c623 | 42,658 | // Copyright 2012 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.
/*!
* High-level text containers.
*
* Ropes are a high-level representation of text that offers
* much better performance than strings for common operations,
* and generally reduce memory allocations and copies, while only
* entailing a small degradation of less common operations.
*
* More precisely, where a string is represented as a memory buffer,
* a rope is a tree structure whose leaves are slices of immutable
* strings. Therefore, concatenation, appending, prepending, substrings,
* etc. are operations that require only trivial tree manipulation,
* generally without having to copy memory. In addition, the tree
* structure of ropes makes them suitable as a form of index to speed-up
* access to Unicode characters by index in long chunks of text.
*
* The following operations are algorithmically faster in ropes:
*
* * extracting a subrope is logarithmic (linear in strings);
* * appending/prepending is near-constant time (linear in strings);
* * concatenation is near-constant time (linear in strings);
* * char length is constant-time (linear in strings);
* * access to a character by index is logarithmic (linear in strings);
*/
#[forbid(deprecated_mode)];
use core::cast;
use core::char;
use core::option;
use core::prelude::*;
use core::str;
use core::uint;
use core::vec;
/// The type of ropes.
pub type Rope = node::Root;
/*
Section: Creating a rope
*/
/// Create an empty rope
pub pure fn empty() -> Rope {
return node::Empty;
}
/**
* Adopt a string as a rope.
*
* # Arguments
*
* * str - A valid string.
*
* # Return value
*
* A rope representing the same string as `str`. Depending of the length
* of `str`, this rope may be empty, flat or complex.
*
* # Performance notes
*
* * this operation does not copy the string;
* * the function runs in linear time.
*/
pub fn of_str(str: @~str) -> Rope {
return of_substr(str, 0u, str::len(*str));
}
/**
* As `of_str` but for a substring.
*
* # Arguments
* * byte_offset - The offset of `str` at which the rope starts.
* * byte_len - The number of bytes of `str` to use.
*
* # Return value
*
* A rope representing the same string as `str::substr(str, byte_offset,
* byte_len)`. Depending on `byte_len`, this rope may be empty, flat or
* complex.
*
* # Performance note
*
* This operation does not copy the substring.
*
* # Safety notes
*
* * this function does _not_ check the validity of the substring;
* * this function fails if `byte_offset` or `byte_len` do not match `str`.
*/
pub fn of_substr(str: @~str, byte_offset: uint, byte_len: uint) -> Rope {
if byte_len == 0u { return node::Empty; }
if byte_offset + byte_len > str::len(*str) { fail; }
return node::Content(node::of_substr(str, byte_offset, byte_len));
}
/*
Section: Adding things to a rope
*/
/**
* Add one char to the end of the rope
*
* # Performance note
*
* * this function executes in near-constant time
*/
pub fn append_char(rope: Rope, char: char) -> Rope {
return append_str(rope, @str::from_chars(~[char]));
}
/**
* Add one string to the end of the rope
*
* # Performance note
*
* * this function executes in near-linear time
*/
pub fn append_str(rope: Rope, str: @~str) -> Rope {
return append_rope(rope, of_str(str))
}
/**
* Add one char to the beginning of the rope
*
* # Performance note
* * this function executes in near-constant time
*/
pub fn prepend_char(rope: Rope, char: char) -> Rope {
return prepend_str(rope, @str::from_chars(~[char]));
}
/**
* Add one string to the beginning of the rope
*
* # Performance note
* * this function executes in near-linear time
*/
pub fn prepend_str(rope: Rope, str: @~str) -> Rope {
return append_rope(of_str(str), rope)
}
/// Concatenate two ropes
pub fn append_rope(left: Rope, right: Rope) -> Rope {
match (left) {
node::Empty => return right,
node::Content(left_content) => {
match (right) {
node::Empty => return left,
node::Content(right_content) => {
return node::Content(node::concat2(left_content, right_content));
}
}
}
}
}
/**
* Concatenate many ropes.
*
* If the ropes are balanced initially and have the same height, the resulting
* rope remains balanced. However, this function does not take any further
* measure to ensure that the result is balanced.
*/
pub fn concat(v: ~[Rope]) -> Rope {
//Copy `v` into a mut vector
let mut len = vec::len(v);
if len == 0u { return node::Empty; }
let ropes = vec::cast_to_mut(vec::from_elem(len, v[0]));
for uint::range(1u, len) |i| {
ropes[i] = v[i];
}
//Merge progresively
while len > 1u {
for uint::range(0u, len/2u) |i| {
ropes[i] = append_rope(ropes[2u*i], ropes[2u*i+1u]);
}
if len%2u != 0u {
ropes[len/2u] = ropes[len - 1u];
len = len/2u + 1u;
} else {
len = len/2u;
}
}
//Return final rope
return ropes[0];
}
/*
Section: Keeping ropes healthy
*/
/**
* Balance a rope.
*
* # Return value
*
* A copy of the rope in which small nodes have been grouped in memory,
* and with a reduced height.
*
* If you perform numerous rope concatenations, it is generally a good idea
* to rebalance your rope at some point, before using it for other purposes.
*/
pub fn bal(rope:Rope) -> Rope {
match (rope) {
node::Empty => return rope,
node::Content(x) => match (node::bal(x)) {
option::None => rope,
option::Some(y) => node::Content(y)
}
}
}
/*
Section: Transforming ropes
*/
/**
* Extract a subrope from a rope.
*
* # Performance note
*
* * on a balanced rope, this operation takes algorithmic time;
* * this operation does not involve any copying
*
* # Safety note
*
* * this function fails if char_offset/char_len do not represent
* valid positions in rope
*/
pub fn sub_chars(rope: Rope, char_offset: uint, char_len: uint) -> Rope {
if char_len == 0u { return node::Empty; }
match (rope) {
node::Empty => fail,
node::Content(node) => if char_len > node::char_len(node) {
fail
} else {
return node::Content(node::sub_chars(node, char_offset, char_len))
}
}
}
/**
* Extract a subrope from a rope.
*
* # Performance note
*
* * on a balanced rope, this operation takes algorithmic time;
* * this operation does not involve any copying
*
* # Safety note
*
* * this function fails if byte_offset/byte_len do not represent
* valid positions in rope
*/
pub fn sub_bytes(rope: Rope, byte_offset: uint, byte_len: uint) -> Rope {
if byte_len == 0u { return node::Empty; }
match (rope) {
node::Empty => fail,
node::Content(node) =>if byte_len > node::byte_len(node) {
fail
} else {
return node::Content(node::sub_bytes(node, byte_offset, byte_len))
}
}
}
/*
Section: Comparing ropes
*/
/**
* Compare two ropes by Unicode lexicographical order.
*
* This function compares only the contents of the rope, not their structure.
*
* # Return value
*
* A negative value if `left < right`, 0 if eq(left, right) or a positive
* value if `left > right`
*/
pub fn cmp(left: Rope, right: Rope) -> int {
match ((left, right)) {
(node::Empty, node::Empty) => return 0,
(node::Empty, _) => return -1,
(_, node::Empty) => return 1,
(node::Content(a), node::Content(b)) => {
return node::cmp(a, b);
}
}
}
/**
* Returns `true` if both ropes have the same content (regardless of
* their structure), `false` otherwise
*/
pub fn eq(left: Rope, right: Rope) -> bool {
return cmp(left, right) == 0;
}
/**
* # Arguments
*
* * left - an arbitrary rope
* * right - an arbitrary rope
*
* # Return value
*
* `true` if `left <= right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
pub fn le(left: Rope, right: Rope) -> bool {
return cmp(left, right) <= 0;
}
/**
* # Arguments
*
* * left - an arbitrary rope
* * right - an arbitrary rope
*
* # Return value
*
* `true` if `left < right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
pub fn lt(left: Rope, right: Rope) -> bool {
return cmp(left, right) < 0;
}
/**
* # Arguments
*
* * left - an arbitrary rope
* * right - an arbitrary rope
*
* # Return value
*
* `true` if `left >= right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
pub fn ge(left: Rope, right: Rope) -> bool {
return cmp(left, right) >= 0;
}
/**
* # Arguments
*
* * left - an arbitrary rope
* * right - an arbitrary rope
*
* # Return value
*
* `true` if `left > right` in lexicographical order (regardless of their
* structure), `false` otherwise
*/
pub fn gt(left: Rope, right: Rope) -> bool {
return cmp(left, right) > 0;
}
/*
Section: Iterating
*/
/**
* Loop through a rope, char by char
*
* While other mechanisms are available, this is generally the best manner
* of looping through the contents of a rope char by char. If you prefer a
* loop that iterates through the contents string by string (e.g. to print
* the contents of the rope or output it to the system), however,
* you should rather use `traverse_components`.
*
* # Arguments
*
* * rope - A rope to traverse. It may be empty.
* * it - A block to execute with each consecutive character of the rope.
* Return `true` to continue, `false` to stop.
*
* # Return value
*
* `true` If execution proceeded correctly, `false` if it was interrupted,
* that is if `it` returned `false` at any point.
*/
pub fn loop_chars(rope: Rope, it: fn(c: char) -> bool) -> bool {
match (rope) {
node::Empty => return true,
node::Content(x) => return node::loop_chars(x, it)
}
}
/**
* Loop through a rope, char by char, until the end.
*
* # Arguments
* * rope - A rope to traverse. It may be empty
* * it - A block to execute with each consecutive character of the rope.
*/
pub fn iter_chars(rope: Rope, it: fn(char)) {
do loop_chars(rope) |x| {
it(x);
true
};
}
/**
* Loop through a rope, string by string
*
* While other mechanisms are available, this is generally the best manner of
* looping through the contents of a rope string by string, which may be
* useful e.g. to print strings as you see them (without having to copy their
* contents into a new string), to send them to then network, to write them to
* a file, etc.. If you prefer a loop that iterates through the contents
* char by char (e.g. to search for a char), however, you should rather
* use `traverse`.
*
* # Arguments
*
* * rope - A rope to traverse. It may be empty
* * it - A block to execute with each consecutive string component of the
* rope. Return `true` to continue, `false` to stop
*
* # Return value
*
* `true` If execution proceeded correctly, `false` if it was interrupted,
* that is if `it` returned `false` at any point.
*/
pub fn loop_leaves(rope: Rope, it: fn(node::Leaf) -> bool) -> bool{
match (rope) {
node::Empty => return true,
node::Content(x) => return node::loop_leaves(x, it)
}
}
pub mod iterator {
pub mod leaf {
use rope::{Rope, node};
use core::prelude::*;
pub fn start(rope: Rope) -> node::leaf_iterator::T {
match (rope) {
node::Empty => return node::leaf_iterator::empty(),
node::Content(x) => return node::leaf_iterator::start(x)
}
}
pub fn next(it: &node::leaf_iterator::T) -> Option<node::Leaf> {
return node::leaf_iterator::next(it);
}
}
pub mod char {
use rope::{Rope, node};
use core::prelude::*;
pub fn start(rope: Rope) -> node::char_iterator::T {
match (rope) {
node::Empty => return node::char_iterator::empty(),
node::Content(x) => return node::char_iterator::start(x)
}
}
pub fn next(it: &node::char_iterator::T) -> Option<char> {
return node::char_iterator::next(it)
}
}
}
/*
Section: Rope properties
*/
/**
* Returns the height of the rope.
*
* The height of the rope is a bound on the number of operations which
* must be performed during a character access before finding the leaf in
* which a character is contained.
*
* # Performance note
*
* Constant time.
*/
pub pure fn height(rope: Rope) -> uint {
match (rope) {
node::Empty => return 0u,
node::Content(x) => return node::height(x)
}
}
/**
* The number of character in the rope
*
* # Performance note
*
* Constant time.
*/
pub pure fn char_len(rope: Rope) -> uint {
match (rope) {
node::Empty => return 0u,
node::Content(x) => return node::char_len(x)
}
}
/**
* The number of bytes in the rope
*
* # Performance note
*
* Constant time.
*/
pub pure fn byte_len(rope: Rope) -> uint {
match (rope) {
node::Empty => return 0u,
node::Content(x) => return node::byte_len(x)
}
}
/**
* The character at position `pos`
*
* # Arguments
*
* * pos - A position in the rope
*
* # Safety notes
*
* The function will fail if `pos` is not a valid position in the rope.
*
* # Performance note
*
* This function executes in a time proportional to the height of the
* rope + the (bounded) length of the largest leaf.
*/
pub fn char_at(rope: Rope, pos: uint) -> char {
match (rope) {
node::Empty => fail,
node::Content(x) => return node::char_at(x, pos)
}
}
/*
Section: Implementation
*/
pub mod node {
use rope::node;
use core::cast;
use core::char;
use core::option;
use core::prelude::*;
use core::str;
use core::uint;
use core::vec;
/// Implementation of type `rope`
pub enum Root {
/// An empty rope
Empty,
/// A non-empty rope
Content(@Node),
}
/**
* A text component in a rope.
*
* This is actually a slice in a rope, so as to ensure maximal sharing.
*
* # Fields
*
* * byte_offset = The number of bytes skippen in `content`
* * byte_len - The number of bytes of `content` to use
* * char_len - The number of chars in the leaf.
* * content - Contents of the leaf.
*
* Note that we can have `char_len < str::char_len(content)`, if
* this leaf is only a subset of the string. Also note that the
* string can be shared between several ropes, e.g. for indexing
* purposes.
*/
pub struct Leaf {
byte_offset: uint,
byte_len: uint,
char_len: uint,
content: @~str,
}
/**
* A node obtained from the concatenation of two other nodes
*
* # Fields
*
* * left - The node containing the beginning of the text.
* * right - The node containing the end of the text.
* * char_len - The number of chars contained in all leaves of this node.
* * byte_len - The number of bytes in the subrope.
*
* Used to pre-allocate the correct amount of storage for
* serialization.
*
* * height - Height of the subrope.
*
* Used for rebalancing and to allocate stacks for traversals.
*/
pub struct Concat {
//FIXME (#2744): Perhaps a `vec` instead of `left`/`right`
left: @Node,
right: @Node,
char_len: uint,
byte_len: uint,
height: uint,
}
pub enum Node {
/// A leaf consisting in a `str`
Leaf(Leaf),
/// The concatenation of two ropes
Concat(Concat),
}
/**
* The maximal number of chars that _should_ be permitted in a single node
*
* This is not a strict value
*/
pub const hint_max_leaf_char_len: uint = 256u;
/**
* The maximal height that _should_ be permitted in a tree.
*
* This is not a strict value
*/
pub const hint_max_node_height: uint = 16u;
/**
* Adopt a string as a node.
*
* If the string is longer than `max_leaf_char_len`, it is
* logically split between as many leaves as necessary. Regardless,
* the string itself is not copied.
*
* Performance note: The complexity of this function is linear in
* the length of `str`.
*/
pub fn of_str(str: @~str) -> @Node {
return of_substr(str, 0u, str::len(*str));
}
/**
* Adopt a slice of a string as a node.
*
* If the slice is longer than `max_leaf_char_len`, it is logically split
* between as many leaves as necessary. Regardless, the string itself
* is not copied
*
* # Arguments
*
* * byte_start - The byte offset where the slice of `str` starts.
* * byte_len - The number of bytes from `str` to use.
*
* # Safety note
*
* Behavior is undefined if `byte_start` or `byte_len` do not represent
* valid positions in `str`
*/
pub fn of_substr(str: @~str, byte_start: uint, byte_len: uint) -> @Node {
return of_substr_unsafer(str, byte_start, byte_len,
str::count_chars(*str, byte_start, byte_len));
}
/**
* Adopt a slice of a string as a node.
*
* If the slice is longer than `max_leaf_char_len`, it is logically split
* between as many leaves as necessary. Regardless, the string itself
* is not copied
*
* # Arguments
*
* * byte_start - The byte offset where the slice of `str` starts.
* * byte_len - The number of bytes from `str` to use.
* * char_len - The number of chars in `str` in the interval
* [byte_start, byte_start+byte_len)
*
* # Safety notes
*
* * Behavior is undefined if `byte_start` or `byte_len` do not represent
* valid positions in `str`
* * Behavior is undefined if `char_len` does not accurately represent the
* number of chars between byte_start and byte_start+byte_len
*/
pub fn of_substr_unsafer(str: @~str, byte_start: uint, byte_len: uint,
char_len: uint) -> @Node {
assert(byte_start + byte_len <= str::len(*str));
let candidate = @Leaf(Leaf {
byte_offset: byte_start,
byte_len: byte_len,
char_len: char_len,
content: str,
});
if char_len <= hint_max_leaf_char_len {
return candidate;
} else {
//Firstly, split `str` in slices of hint_max_leaf_char_len
let mut leaves = uint::div_ceil(char_len, hint_max_leaf_char_len);
//Number of leaves
let nodes = vec::cast_to_mut(vec::from_elem(leaves, candidate));
let mut i = 0u;
let mut offset = byte_start;
let first_leaf_char_len =
if char_len%hint_max_leaf_char_len == 0u {
hint_max_leaf_char_len
} else {
char_len%hint_max_leaf_char_len
};
while i < leaves {
let chunk_char_len: uint =
if i == 0u { first_leaf_char_len }
else { hint_max_leaf_char_len };
let chunk_byte_len =
str::count_bytes(*str, offset, chunk_char_len);
nodes[i] = @Leaf(Leaf {
byte_offset: offset,
byte_len: chunk_byte_len,
char_len: chunk_char_len,
content: str,
});
offset += chunk_byte_len;
i += 1u;
}
//Then, build a tree from these slices by collapsing them
while leaves > 1u {
i = 0u;
while i < leaves - 1u {//Concat nodes 0 with 1, 2 with 3 etc.
nodes[i/2u] = concat2(nodes[i], nodes[i + 1u]);
i += 2u;
}
if i == leaves - 1u {
//And don't forget the last node if it is in even position
nodes[i/2u] = nodes[i];
}
leaves = uint::div_ceil(leaves, 2u);
}
return nodes[0u];
}
}
pub pure fn byte_len(node: @Node) -> uint {
//FIXME (#2744): Could we do this without the pattern-matching?
match (*node) {
Leaf(y) => y.byte_len,
Concat(ref y) => y.byte_len
}
}
pub pure fn char_len(node: @Node) -> uint {
match (*node) {
Leaf(y) => y.char_len,
Concat(ref y) => y.char_len
}
}
/**
* Concatenate a forest of nodes into one tree.
*
* # Arguments
*
* * forest - The forest. This vector is progressively rewritten during
* execution and should be discarded as meaningless afterwards.
*/
pub fn tree_from_forest_destructive(forest: &[mut @Node]) -> @Node {
let mut i;
let mut len = vec::len(forest);
while len > 1u {
i = 0u;
while i < len - 1u {//Concat nodes 0 with 1, 2 with 3 etc.
let mut left = forest[i];
let mut right = forest[i+1u];
let left_len = char_len(left);
let right_len= char_len(right);
let mut left_height= height(left);
let mut right_height=height(right);
if left_len + right_len > hint_max_leaf_char_len {
if left_len <= hint_max_leaf_char_len {
left = flatten(left);
left_height = height(left);
}
if right_len <= hint_max_leaf_char_len {
right = flatten(right);
right_height = height(right);
}
}
if left_height >= hint_max_node_height {
left = of_substr_unsafer(@serialize_node(left),
0u,byte_len(left),
left_len);
}
if right_height >= hint_max_node_height {
right = of_substr_unsafer(@serialize_node(right),
0u,byte_len(right),
right_len);
}
forest[i/2u] = concat2(left, right);
i += 2u;
}
if i == len - 1u {
//And don't forget the last node if it is in even position
forest[i/2u] = forest[i];
}
len = uint::div_ceil(len, 2u);
}
return forest[0];
}
pub fn serialize_node(node: @Node) -> ~str {
unsafe {
let mut buf = vec::cast_to_mut(vec::from_elem(byte_len(node), 0));
let mut offset = 0u;//Current position in the buffer
let it = leaf_iterator::start(node);
loop {
match (leaf_iterator::next(&it)) {
option::None => break,
option::Some(x) => {
//FIXME (#2744): Replace with memcpy or something similar
let mut local_buf: ~[u8] =
cast::reinterpret_cast(&*x.content);
let mut i = x.byte_offset;
while i < x.byte_len {
buf[offset] = local_buf[i];
offset += 1u;
i += 1u;
}
cast::forget(move local_buf);
}
}
}
return cast::transmute(move buf);
}
}
/**
* Replace a subtree by a single leaf with the same contents.
*
* * Performance note
*
* This function executes in linear time.
*/
pub fn flatten(node: @Node) -> @Node {
unsafe {
match (*node) {
Leaf(_) => node,
Concat(ref x) => {
@Leaf(Leaf {
byte_offset: 0u,
byte_len: x.byte_len,
char_len: x.char_len,
content: @serialize_node(node),
})
}
}
}
}
/**
* Balance a node.
*
* # Algorithm
*
* * if the node height is smaller than `hint_max_node_height`, do nothing
* * otherwise, gather all leaves as a forest, rebuild a balanced node,
* concatenating small leaves along the way
*
* # Return value
*
* * `option::None` if no transformation happened
* * `option::Some(x)` otherwise, in which case `x` has the same contents
* as `node` bot lower height and/or fragmentation.
*/
pub fn bal(node: @Node) -> Option<@Node> {
if height(node) < hint_max_node_height { return option::None; }
//1. Gather all leaves as a forest
let mut forest = ~[];
let it = leaf_iterator::start(node);
loop {
match (leaf_iterator::next(&it)) {
option::None => break,
option::Some(x) => forest.push(@Leaf(x))
}
}
//2. Rebuild tree from forest
let root = @*tree_from_forest_destructive(forest);
return option::Some(root);
}
/**
* Compute the subnode of a node.
*
* # Arguments
*
* * node - A node
* * byte_offset - A byte offset in `node`
* * byte_len - The number of bytes to return
*
* # Performance notes
*
* * this function performs no copying;
* * this function executes in a time proportional to the height of `node`
*
* # Safety notes
*
* This function fails if `byte_offset` or `byte_len` do not represent
* valid positions in `node`.
*/
pub fn sub_bytes(node: @Node, byte_offset: uint,
byte_len: uint) -> @Node {
let mut node = node;
let mut byte_offset = byte_offset;
loop {
if byte_offset == 0u && byte_len == node::byte_len(node) {
return node;
}
match (*node) {
node::Leaf(x) => {
let char_len =
str::count_chars(*x.content, byte_offset, byte_len);
return @Leaf(Leaf {
byte_offset: byte_offset,
byte_len: byte_len,
char_len: char_len,
content: x.content,
});
}
node::Concat(ref x) => {
let left_len: uint = node::byte_len(x.left);
if byte_offset <= left_len {
if byte_offset + byte_len <= left_len {
//Case 1: Everything fits in x.left, tail-call
node = x.left;
} else {
//Case 2: A (non-empty, possibly full) suffix
//of x.left and a (non-empty, possibly full) prefix
//of x.right
let left_result =
sub_bytes(x.left, byte_offset, left_len);
let right_result =
sub_bytes(x.right, 0u, left_len - byte_offset);
return concat2(left_result, right_result);
}
} else {
//Case 3: Everything fits in x.right
byte_offset -= left_len;
node = x.right;
}
}
}
};
}
/**
* Compute the subnode of a node.
*
* # Arguments
*
* * node - A node
* * char_offset - A char offset in `node`
* * char_len - The number of chars to return
*
* # Performance notes
*
* * this function performs no copying;
* * this function executes in a time proportional to the height of `node`
*
* # Safety notes
*
* This function fails if `char_offset` or `char_len` do not represent
* valid positions in `node`.
*/
pub fn sub_chars(node: @Node, char_offset: uint,
char_len: uint) -> @Node {
let mut node = node;
let mut char_offset = char_offset;
loop {
match (*node) {
node::Leaf(x) => {
if char_offset == 0u && char_len == x.char_len {
return node;
}
let byte_offset =
str::count_bytes(*x.content, 0u, char_offset);
let byte_len =
str::count_bytes(*x.content, byte_offset, char_len);
return @Leaf(Leaf {
byte_offset: byte_offset,
byte_len: byte_len,
char_len: char_len,
content: x.content,
});
}
node::Concat(ref x) => {
if char_offset == 0u && char_len == x.char_len {return node;}
let left_len : uint = node::char_len(x.left);
if char_offset <= left_len {
if char_offset + char_len <= left_len {
//Case 1: Everything fits in x.left, tail call
node = x.left;
} else {
//Case 2: A (non-empty, possibly full) suffix
//of x.left and a (non-empty, possibly full) prefix
//of x.right
let left_result =
sub_chars(x.left, char_offset, left_len);
let right_result =
sub_chars(x.right, 0u, left_len - char_offset);
return concat2(left_result, right_result);
}
} else {
//Case 3: Everything fits in x.right, tail call
node = x.right;
char_offset -= left_len;
}
}
}
};
}
pub fn concat2(left: @Node, right: @Node) -> @Node {
@Concat(Concat {
left: left,
right: right,
char_len: char_len(left) + char_len(right),
byte_len: byte_len(left) + byte_len(right),
height: uint::max(height(left), height(right)) + 1u,
})
}
pub pure fn height(node: @Node) -> uint {
match (*node) {
Leaf(_) => 0u,
Concat(ref x) => x.height,
}
}
pub fn cmp(a: @Node, b: @Node) -> int {
let ita = char_iterator::start(a);
let itb = char_iterator::start(b);
let mut result = 0;
while result == 0 {
match ((char_iterator::next(&ita), char_iterator::next(&itb))) {
(option::None, option::None) => break,
(option::Some(chara), option::Some(charb)) => {
result = char::cmp(chara, charb);
}
(option::Some(_), _) => {
result = 1;
}
(_, option::Some(_)) => {
result = -1;
}
}
}
return result;
}
pub fn loop_chars(node: @Node, it: fn(c: char) -> bool) -> bool {
return loop_leaves(node,|leaf| {
str::all_between(*leaf.content,
leaf.byte_offset,
leaf.byte_len, it)
});
}
/**
* Loop through a node, leaf by leaf
*
* # Arguments
*
* * rope - A node to traverse.
* * it - A block to execute with each consecutive leaf of the node.
* Return `true` to continue, `false` to stop
*
* # Arguments
*
* `true` If execution proceeded correctly, `false` if it was interrupted,
* that is if `it` returned `false` at any point.
*/
pub fn loop_leaves(node: @Node, it: fn(Leaf) -> bool) -> bool{
let mut current = node;
loop {
match (*current) {
Leaf(x) => return it(x),
Concat(ref x) => if loop_leaves(x.left, it) { //non tail call
current = x.right; //tail call
} else {
return false;
}
}
};
}
/**
* # Arguments
*
* * pos - A position in the rope
*
* # Return value
*
* The character at position `pos`
*
* # Safety notes
*
* The function will fail if `pos` is not a valid position in the rope.
*
* Performance note: This function executes in a time
* proportional to the height of the rope + the (bounded)
* length of the largest leaf.
*/
pub pure fn char_at(node: @Node, pos: uint) -> char {
let mut node = node;
let mut pos = pos;
loop {
match *node {
Leaf(x) => return str::char_at(*x.content, pos),
Concat(Concat {left, right, _}) => {
let left_len = char_len(left);
node = if left_len > pos { left }
else { pos -= left_len; right };
}
}
};
}
pub mod leaf_iterator {
use rope::node::{Concat, Leaf, Node, height};
use core::option;
use core::prelude::*;
use core::vec;
pub struct T {
stack: ~[mut @Node],
mut stackpos: int,
}
pub fn empty() -> T {
let stack : ~[mut @Node] = ~[mut];
T { stack: stack, stackpos: -1 }
}
pub fn start(node: @Node) -> T {
let stack = vec::cast_to_mut(
vec::from_elem(height(node)+1u, node));
T {
stack: stack,
stackpos: 0,
}
}
pub fn next(it: &T) -> Option<Leaf> {
if it.stackpos < 0 { return option::None; }
loop {
let current = it.stack[it.stackpos];
it.stackpos -= 1;
match (*current) {
Concat(ref x) => {
it.stackpos += 1;
it.stack[it.stackpos] = x.right;
it.stackpos += 1;
it.stack[it.stackpos] = x.left;
}
Leaf(x) => return option::Some(x)
}
};
}
}
pub mod char_iterator {
use rope::node::{Leaf, Node};
use rope::node::leaf_iterator;
use core::option;
use core::prelude::*;
use core::str;
pub struct T {
leaf_iterator: leaf_iterator::T,
mut leaf: Option<Leaf>,
mut leaf_byte_pos: uint,
}
pub fn start(node: @Node) -> T {
T {
leaf_iterator: leaf_iterator::start(node),
leaf: option::None,
leaf_byte_pos: 0u,
}
}
pub fn empty() -> T {
T {
leaf_iterator: leaf_iterator::empty(),
leaf: option::None,
leaf_byte_pos: 0u,
}
}
pub fn next(it: &T) -> Option<char> {
loop {
match (get_current_or_next_leaf(it)) {
option::None => return option::None,
option::Some(_) => {
let next_char = get_next_char_in_leaf(it);
match (next_char) {
option::None => loop,
option::Some(_) => return next_char
}
}
}
};
}
pub fn get_current_or_next_leaf(it: &T) -> Option<Leaf> {
match ((*it).leaf) {
option::Some(_) => return (*it).leaf,
option::None => {
let next = leaf_iterator::next(&((*it).leaf_iterator));
match (next) {
option::None => return option::None,
option::Some(_) => {
(*it).leaf = next;
(*it).leaf_byte_pos = 0u;
return next;
}
}
}
}
}
pub fn get_next_char_in_leaf(it: &T) -> Option<char> {
match copy (*it).leaf {
option::None => return option::None,
option::Some(aleaf) => {
if (*it).leaf_byte_pos >= aleaf.byte_len {
//We are actually past the end of the leaf
(*it).leaf = option::None;
return option::None
} else {
let range =
str::char_range_at(*aleaf.content,
(*it).leaf_byte_pos + aleaf.byte_offset);
let ch = range.ch;
let next = range.next;
(*it).leaf_byte_pos = next - aleaf.byte_offset;
return option::Some(ch)
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use rope::*;
use core::option;
use core::str;
use core::uint;
use core::vec;
//Utility function, used for sanity check
fn rope_to_string(r: Rope) -> ~str {
match (r) {
node::Empty => return ~"",
node::Content(x) => {
let str = @mut ~"";
fn aux(str: @mut ~str, node: @node::Node) {
unsafe {
match (*node) {
node::Leaf(x) => {
*str += str::slice(
*x.content, x.byte_offset,
x.byte_offset + x.byte_len);
}
node::Concat(ref x) => {
aux(str, x.left);
aux(str, x.right);
}
}
}
}
aux(str, x);
return *str
}
}
}
#[test]
fn trivial() {
assert char_len(empty()) == 0u;
assert byte_len(empty()) == 0u;
}
#[test]
fn of_string1() {
let sample = @~"0123456789ABCDE";
let r = of_str(sample);
assert char_len(r) == str::char_len(*sample);
assert rope_to_string(r) == *sample;
}
#[test]
fn of_string2() {
let buf = @ mut ~"1234567890";
let mut i = 0;
while i < 10 {
let a = *buf;
let b = *buf;
*buf = a + b;
i+=1;
}
let sample = @*buf;
let r = of_str(sample);
assert char_len(r) == str::char_len(*sample);
assert rope_to_string(r) == *sample;
let mut string_iter = 0u;
let string_len = str::len(*sample);
let rope_iter = iterator::char::start(r);
let mut equal = true;
while equal {
match (node::char_iterator::next(&rope_iter)) {
option::None => {
if string_iter < string_len {
equal = false;
} break; }
option::Some(c) => {
let range = str::char_range_at(*sample, string_iter);
string_iter = range.next;
if range.ch != c { equal = false; break; }
}
}
}
assert equal;
}
#[test]
fn iter1() {
let buf = @ mut ~"1234567890";
let mut i = 0;
while i < 10 {
let a = *buf;
let b = *buf;
*buf = a + b;
i+=1;
}
let sample = @*buf;
let r = of_str(sample);
let mut len = 0u;
let it = iterator::char::start(r);
loop {
match (node::char_iterator::next(&it)) {
option::None => break,
option::Some(_) => len += 1u
}
}
assert len == str::char_len(*sample);
}
#[test]
fn bal1() {
let init = @~"1234567890";
let buf = @mut * init;
let mut i = 0;
while i < 8 {
let a = *buf;
let b = *buf;
*buf = a + b;
i+=1;
}
let sample = @*buf;
let r1 = of_str(sample);
let mut r2 = of_str(init);
i = 0;
while i < 8 { r2 = append_rope(r2, r2); i+= 1;}
assert eq(r1, r2);
let r3 = bal(r2);
assert char_len(r1) == char_len(r3);
assert eq(r1, r3);
}
#[test]
#[ignore]
fn char_at1() {
//Generate a large rope
let mut r = of_str(@~"123456789");
for uint::range(0u, 10u) |_i| {
r = append_rope(r, r);
}
//Copy it in the slowest possible way
let mut r2 = empty();
for uint::range(0u, char_len(r)) |i| {
r2 = append_char(r2, char_at(r, i));
}
assert eq(r, r2);
let mut r3 = empty();
for uint::range(0u, char_len(r)) |i| {
r3 = prepend_char(r3, char_at(r, char_len(r) - i - 1u));
}
assert eq(r, r3);
//Additional sanity checks
let balr = bal(r);
let bal2 = bal(r2);
let bal3 = bal(r3);
assert eq(r, balr);
assert eq(r, bal2);
assert eq(r, bal3);
assert eq(r2, r3);
assert eq(bal2, bal3);
}
#[test]
fn concat1() {
//Generate a reasonable rope
let chunk = of_str(@~"123456789");
let mut r = empty();
for uint::range(0u, 10u) |_i| {
r = append_rope(r, chunk);
}
//Same rope, obtained with rope::concat
let r2 = concat(vec::from_elem(10u, chunk));
assert eq(r, r2);
}
}
| 29.058583 | 78 | 0.512987 |
1d871be08c4ae4600b98c23be89ddbb84814f661 | 10,684 | use rand::{seq::SliceRandom, thread_rng};
use std::io::{stdin, BufRead};
const SHUFFLE_SIZE: usize = 62;
const RESHUFFLE: usize = 10;
const NUM_DECKS: usize = 4;
const BUST_KWD: &str = &"bust";
const STARTING_MONEY: usize = 1_000;
// --- CARDS ---
#[derive(Copy, Clone)]
enum Card {
Def(u8),
Maybe(u8, u8),
}
impl std::fmt::Debug for Card {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Card::Def(n) => format!("{}", n).fmt(f),
Card::Maybe(x, y) => format!("{} or {}", x, y).fmt(f),
}
}
}
impl std::fmt::Display for Card {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Card::Def(n) => format!("{}", n).fmt(f),
Card::Maybe(x, y) => format!("{} or {}", x, y).fmt(f),
}
}
}
impl std::ops::Add for Card {
type Output = Self;
fn add(self, other: Self) -> Self {
match (self, other) {
(Self::Def(a), Self::Def(b)) => Self::Def(a + b),
(Self::Def(a), Self::Maybe(b, c)) | (Self::Maybe(b, c), Self::Def(a)) => {
if a + c > 21 {
Self::Def(a + b)
} else {
Self::Maybe(a + b, a + c)
}
}
(Self::Maybe(a, b), _) => Self::Maybe(a + 1, b + 1),
}
}
}
impl std::ops::AddAssign for Card {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl PartialEq for Card {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Def(a), Self::Def(b)) => a == b,
(Self::Maybe(a, b), Self::Maybe(c, d)) => (a == c) && (b == d),
_ => false,
}
}
}
macro_rules! real_sum {
( $e:expr ) => {
match $e.sum {
Card::Def(n) | Card::Maybe(_, n) => n,
}
};
}
#[derive(Clone)]
struct Cards {
cards: Vec<Card>,
}
impl Cards {
fn sum(&self) -> Card {
let mut total = Card::Def(0);
for card in self.cards.iter() {
total += *card;
}
total
}
}
// --- DECK ---
#[derive(Debug)]
struct Deck {
cards: Vec<Card>,
drawables: Vec<Card>,
}
impl Deck {
// TODO: add counting mechanism to deck.draw()
fn new() -> Self {
let mut deck: Vec<Card> = (0..52 * NUM_DECKS as u8).map(|_| Card::Def(1)).collect();
const VALS: [Card; 13] = [
Card::Maybe(1, 11),
Card::Def(2),
Card::Def(3),
Card::Def(4),
Card::Def(5),
Card::Def(6),
Card::Def(7),
Card::Def(8),
Card::Def(9),
Card::Def(10),
Card::Def(10),
Card::Def(10),
Card::Def(10),
];
for i in 0..52 * NUM_DECKS {
deck[i] = VALS[i % 13];
}
Deck {
cards: deck,
drawables: Vec::new(),
}
}
fn shuffle(&mut self) {
self.drawables = self
.cards
.choose_multiple(&mut thread_rng(), SHUFFLE_SIZE)
.map(|&c| c)
.collect();
}
fn draw(&mut self) -> Card {
match self.drawables.pop() {
Some(n) => n,
None => panic!("Not enough cards!"),
}
}
}
// --- HAND ---
struct Hand {
cards: Cards,
sum: Card,
busted: bool,
}
impl Hand {
fn new(deck: &mut Deck) -> Self {
let cards: Cards = Cards {
cards: (0..2).map(|_| deck.draw()).collect(),
};
Hand {
sum: cards.sum(),
busted: false,
cards,
}
}
fn show(&self) {
println!("{:?} = {}", self.cards.cards, self.sum);
}
fn hit(&mut self, deck: &mut Deck) {
let card = deck.draw();
self.cards.cards.push(card);
self.sum += card;
}
}
// --- MONEY ---
struct Wallet {
balance: usize,
bet: usize,
}
impl Wallet {
fn new() -> Self {
Wallet {
balance: STARTING_MONEY,
bet: 0,
}
}
fn place_bet(&mut self, amount: usize) -> Result<(), ()> {
if self.balance >= amount {
self.balance -= amount;
self.bet += amount;
Ok(())
} else {
Err(())
}
}
fn double(&mut self) -> Result<(), ()> {
self.place_bet(self.bet)
}
fn pay_out(&mut self, multiplier: usize) {
self.balance += multiplier * self.bet;
self.bet = 0;
}
fn lose(&mut self) {
self.bet = 0;
}
}
// --- PROGRAM ---
fn choice(input: &str, deck: &mut Deck, hand: &mut Hand, wallet: &mut Wallet) -> bool {
match input {
"s" => return false,
"h" => hand.hit(deck),
"d" => {
match wallet.double() {
Ok(_) => {
hand.hit(deck);
hand.show();
return false;
}
Err(_) => {
println!("Balance too low (${})", wallet.balance);
return true;
}
};
}
BUST_KWD => return false,
_ => (),
}
true
// True means keep playing the round
}
#[allow(unused_assignments)]
fn play() {
let mut wallet = Wallet::new();
let mut deck = Deck::new();
'play: loop {
deck.shuffle();
'main: loop {
if deck.drawables.len() < RESHUFFLE {
break 'main;
}
println!("***********");
println!("Balance: ${}", wallet.balance);
println!("Place Bet:");
if let Err(_) = wallet.place_bet(loop {
if let Ok(n) = stdin()
.lock()
.lines()
.next()
.unwrap()
.unwrap()
.parse::<usize>()
{
break n;
}
}) {
println!("Balance too low (${})", wallet.balance);
continue 'main;
}
let mut hand = Hand::new(&mut deck);
if hand.sum == Card::Maybe(11, 21) {
hand.show();
println!("Blackjack!");
wallet.pay_out(3);
continue 'main;
}
let mut dealer = Hand::new(&mut deck);
println!("Dealer: {}", dealer.cards.cards[0]);
// --- Inputs ---
let mut split = false;
let mut bet = 0usize;
let mut hand2 = Hand {
cards: Cards { cards: vec![] },
busted: false,
sum: Card::Def(0),
};
macro_rules! player_input {
( $e:expr ) => {{
$e.show();
if match $e.sum {
Card::Def(n) => n > 21,
_ => false,
} {
println!("Busted!");
$e.busted = true;
BUST_KWD
} else {
match &stdin().lock().lines().next().unwrap().unwrap()[..] {
"s" => "s",
"h" => "h",
"d" => "d",
"sp" => {
if $e.cards.cards[0] == $e.cards.cards[1]
&& wallet.balance >= wallet.bet
&& bet == 0
{
split = true;
$e.cards.cards.remove(1);
$e.sum = $e.cards.cards[0];
"h"
} else {
"tortoise"
}
}
"q" => break 'play,
_ => "tortoise",
}
}
}};
}
macro_rules! dealer_input {
() => {{
if real_sum!(dealer) < 17 {
"h"
} else {
if match dealer.sum {
Card::Def(n) => n > 21,
_ => false,
} {
dealer.busted = true;
BUST_KWD
} else {
"s"
}
}
}};
}
// --- Success Validation ---
macro_rules! win_lose {
( $e:expr ) => {
let hand_final = real_sum!($e);
let dealer_final = real_sum!(dealer);
if !$e.busted && (hand_final >= dealer_final || dealer.busted) {
if hand_final == dealer_final {
println!("Push!");
wallet.pay_out(1);
} else {
println!("You Win!");
wallet.pay_out(2);
}
} else {
println!("You Lose!");
wallet.lose();
}
};
}
// --- Play ---
while choice(dealer_input!(), &mut deck, &mut dealer, &mut wallet) {}
while choice(player_input!(hand), &mut deck, &mut hand, &mut wallet) {
if split {
bet = wallet.bet;
let val = hand.cards.cards[0] + Card::Def(0);
hand2 = Hand {
cards: Cards { cards: vec![val] },
busted: false,
sum: val,
};
hand2.hit(&mut deck);
println!("--- HAND 1 ---");
while choice(player_input!(hand2), &mut deck, &mut hand2, &mut wallet) {}
println!("--- HAND 2 ---");
split = false;
}
}
println!("--- DEALER ---");
dealer.show();
if bet != 0 {
win_lose!(hand2);
wallet.place_bet(bet).unwrap();
}
win_lose!(hand);
}
println!("Reshuffling cards...");
}
}
fn main() {
play();
}
| 26.122249 | 93 | 0.360352 |
87cd1bcfabe18aa0ce13d4aed9d734365a07304b | 1,007 | /**
给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
题目数据保证答案符合 32 位整数范围。
示例 1:
输入:nums = [1,2,3], target = 4
输出:7
解释:
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
示例 2:
输入:nums = [9], target = 3
输出:0
提示:
1 <= nums.length <= 200
1 <= nums[i] <= 1000
nums 中的所有元素 互不相同
1 <= target <= 1000
进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
pub fn combination_sum4(nums: Vec<i32>, target: i32) -> i32 {
if nums.is_empty() { return 0 }
let mut dp = vec![0; target as usize + 1];
dp[0] = 1;
for i in 1..=target as usize {
for &num in &nums {
if i >= num as usize {
dp[i] += dp[i - num as usize]
}
}
}
dp[target as usize] as i32
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| 15.734375 | 74 | 0.567031 |
62e4b1a287c62cd197f59cd93b974ce25d409a92 | 160 |
struct A{i:i32}
struct B{a:A}
fn main(){
let a = A{a:1};
let b = B{a:a};
unsafe{ #intrinsicDeallocate(b) };
unsafe{ #intrinsicDeallocate(b) };
} | 13.333333 | 37 | 0.575 |
0122e6ee6c24af54b0b7c661bde1e0685248a999 | 8,572 | use crate::app::{App, PerMap};
use ezgui::{hotkey, Btn, Checkbox, Color, EventCtx, Key, Line, Text, TextExt, TextSpan, Widget};
use geom::{Duration, Pt2D};
use map_model::{AreaID, BuildingID, BusStopID, IntersectionID, LaneID, Map, ParkingLotID, RoadID};
use sim::{AgentID, AgentType, CarID, PedestrianID, TripMode, TripPhaseType};
use std::collections::BTreeSet;
// Aside from Road and Trip, everything here can actually be selected.
#[derive(Clone, Hash, PartialEq, Eq, Debug, PartialOrd, Ord)]
pub enum ID {
Road(RoadID),
Lane(LaneID),
Intersection(IntersectionID),
Building(BuildingID),
ParkingLot(ParkingLotID),
Car(CarID),
Pedestrian(PedestrianID),
PedCrowd(Vec<PedestrianID>),
BusStop(BusStopID),
Area(AreaID),
}
impl abstutil::Cloneable for ID {}
impl ID {
pub fn from_agent(id: AgentID) -> ID {
match id {
AgentID::Car(id) => ID::Car(id),
AgentID::Pedestrian(id) => ID::Pedestrian(id),
AgentID::BusPassenger(_, bus) => ID::Car(bus),
}
}
pub fn agent_id(&self) -> Option<AgentID> {
match *self {
ID::Car(id) => Some(AgentID::Car(id)),
ID::Pedestrian(id) => Some(AgentID::Pedestrian(id)),
// PedCrowd doesn't map to a single agent.
_ => None,
}
}
pub fn canonical_point(&self, primary: &PerMap) -> Option<Pt2D> {
match *self {
ID::Road(id) => primary.map.maybe_get_r(id).map(|r| r.center_pts.first_pt()),
ID::Lane(id) => primary.map.maybe_get_l(id).map(|l| l.first_pt()),
ID::Intersection(id) => primary.map.maybe_get_i(id).map(|i| i.polygon.center()),
ID::Building(id) => primary.map.maybe_get_b(id).map(|b| b.polygon.center()),
ID::ParkingLot(id) => primary.map.maybe_get_pl(id).map(|pl| pl.polygon.center()),
ID::Car(id) => primary
.sim
.canonical_pt_for_agent(AgentID::Car(id), &primary.map),
ID::Pedestrian(id) => primary
.sim
.canonical_pt_for_agent(AgentID::Pedestrian(id), &primary.map),
ID::PedCrowd(ref members) => primary
.sim
.canonical_pt_for_agent(AgentID::Pedestrian(members[0]), &primary.map),
ID::BusStop(id) => primary
.map
.maybe_get_bs(id)
.map(|bs| bs.sidewalk_pos.pt(&primary.map)),
ID::Area(id) => primary.map.maybe_get_a(id).map(|a| a.polygon.center()),
}
}
}
pub fn list_names<F: Fn(TextSpan) -> TextSpan>(txt: &mut Text, styler: F, names: BTreeSet<String>) {
let len = names.len();
for (idx, n) in names.into_iter().enumerate() {
if idx != 0 {
if idx == len - 1 {
if len == 2 {
txt.append(Line(" and "));
} else {
txt.append(Line(", and "));
}
} else {
txt.append(Line(", "));
}
}
txt.append(styler(Line(n)));
}
}
// TODO Associate this with maps, but somehow avoid reading the entire file when listing them.
pub fn nice_map_name(name: &str) -> &str {
match name {
"ballard" => "Ballard",
"downtown" => "Downtown Seattle",
"huge_seattle" => "Seattle (entire area)",
"lakeslice" => "Lake Washington corridor",
"montlake" => "Montlake and Eastlake",
"south_seattle" => "South Seattle",
"udistrict" => "University District",
"west_seattle" => "West Seattle",
// Outside Seattle
"huge_krakow" => "Kraków (city center)",
"berlin_center" => "Berlin (city center)",
_ => name,
}
}
// Shorter is better
pub fn cmp_duration_shorter(after: Duration, before: Duration) -> Vec<TextSpan> {
if after.epsilon_eq(before) {
vec![Line("same")]
} else if after < before {
vec![
Line((before - after).to_string()).fg(Color::GREEN),
Line(" faster"),
]
} else if after > before {
vec![
Line((after - before).to_string()).fg(Color::RED),
Line(" slower"),
]
} else {
unreachable!()
}
}
pub fn color_for_mode(app: &App, m: TripMode) -> Color {
match m {
TripMode::Walk => app.cs.unzoomed_pedestrian,
TripMode::Bike => app.cs.unzoomed_bike,
TripMode::Transit => app.cs.unzoomed_bus,
TripMode::Drive => app.cs.unzoomed_car,
}
}
pub fn color_for_agent_type(app: &App, a: AgentType) -> Color {
match a {
AgentType::Pedestrian => app.cs.unzoomed_pedestrian,
AgentType::Bike => app.cs.unzoomed_bike,
AgentType::Bus | AgentType::Train => app.cs.unzoomed_bus,
AgentType::TransitRider => app.cs.bus_lane,
AgentType::Car => app.cs.unzoomed_car,
}
}
pub fn color_for_trip_phase(app: &App, tpt: TripPhaseType) -> Color {
match tpt {
TripPhaseType::Driving => app.cs.unzoomed_car,
TripPhaseType::Walking => app.cs.unzoomed_pedestrian,
TripPhaseType::Biking => app.cs.bike_lane,
TripPhaseType::Parking => app.cs.parking_trip,
TripPhaseType::WaitingForBus(_, _) => app.cs.bus_layer,
TripPhaseType::RidingBus(_, _, _) => app.cs.bus_lane,
TripPhaseType::Aborted | TripPhaseType::Finished => unreachable!(),
TripPhaseType::DelayedStart => Color::YELLOW,
TripPhaseType::Remote => Color::PINK,
}
}
pub fn amenity_type(a: &str) -> Option<&'static str> {
if a == "supermarket" || a == "convenience" {
Some("groceries")
} else if a == "restaurant"
|| a == "cafe"
|| a == "fast_food"
|| a == "food_court"
|| a == "ice_cream"
|| a == "pastry"
|| a == "deli"
{
Some("food")
} else if a == "pub" || a == "bar" || a == "nightclub" || a == "lounge" {
Some("bar")
} else if a == "doctors"
|| a == "dentist"
|| a == "clinic"
|| a == "pharmacy"
|| a == "chiropractor"
{
Some("medical")
} else if a == "place_of_worship" {
Some("church / temple")
} else if a == "college" || a == "school" || a == "kindergarten" || a == "university" {
Some("education")
} else if a == "bank" || a == "post_office" || a == "atm" {
Some("bank / post office")
} else if a == "theatre"
|| a == "arts_centre"
|| a == "library"
|| a == "cinema"
|| a == "art_gallery"
{
Some("media")
} else if a == "childcare" {
Some("childcare")
} else if a == "second_hand"
|| a == "clothes"
|| a == "furniture"
|| a == "shoes"
|| a == "department_store"
{
Some("shopping")
} else {
None
}
}
// TODO Well, there goes the nice consolidation of stuff in BtnBuilder. :\
pub fn hotkey_btn<I: Into<String>>(ctx: &EventCtx, app: &App, label: I, key: Key) -> Widget {
let label = label.into();
let mut txt = Text::new();
txt.append(Line(key.describe()).fg(ctx.style().hotkey_color));
txt.append(Line(format!(" - {}", label)));
Btn::text_bg(label, txt, app.cs.section_bg, app.cs.hovering).build_def(ctx, hotkey(key))
}
pub fn intersections_from_roads(roads: &BTreeSet<RoadID>, map: &Map) -> BTreeSet<IntersectionID> {
let mut results = BTreeSet::new();
for r in roads {
let r = map.get_r(*r);
for i in vec![r.src_i, r.dst_i] {
if results.contains(&i) {
continue;
}
if map.get_i(i).roads.iter().all(|r| roads.contains(r)) {
results.insert(i);
}
}
}
results
}
pub fn checkbox_per_mode(
ctx: &mut EventCtx,
app: &App,
current_state: &BTreeSet<TripMode>,
) -> Widget {
let mut filters = Vec::new();
for m in TripMode::all() {
filters.push(
Checkbox::colored(
ctx,
m.ongoing_verb(),
color_for_mode(app, m),
current_state.contains(&m),
)
.margin_right(5),
);
filters.push(m.ongoing_verb().draw_text(ctx).margin_right(10));
}
Widget::custom_row(filters)
}
pub fn copy_to_clipboard(x: String) {
#[cfg(not(target_arch = "wasm32"))]
{
use clipboard::{ClipboardContext, ClipboardProvider};
let mut cb: ClipboardContext = ClipboardProvider::new().unwrap();
cb.set_contents(x).unwrap();
}
}
| 33.096525 | 100 | 0.545847 |
db38ecfe27c2e234cc79679e776c1ee7ccf6afd9 | 933 | //! Cryptographic random number generation.
use ffi;
#[cfg(not(feature = "std"))]
use prelude::*;
use std::iter::repeat;
/// `randombytes()` randomly generates size bytes of data.
///
/// THREAD SAFETY: `randombytes()` is thread-safe provided that you have
/// called `sodiumoxide::init()` once before using any other function
/// from sodiumoxide.
pub fn randombytes(size: usize) -> Vec<u8> {
unsafe {
let mut buf: Vec<u8> = repeat(0u8).take(size).collect();
let pbuf = buf.as_mut_ptr();
ffi::randombytes_buf(pbuf, size);
buf
}
}
/// `randombytes_into()` fills a buffer `buf` with random data.
///
/// THREAD SAFETY: `randombytes_into()` is thread-safe provided that you have
/// called `sodiumoxide::init()` once before using any other function
/// from sodiumoxide.
pub fn randombytes_into(buf: &mut [u8]) {
unsafe {
ffi::randombytes_buf(buf.as_mut_ptr(), buf.len());
}
}
| 30.096774 | 77 | 0.65702 |
b921e10f65e3f274cc151e28293c3e488845f52f | 991 | #![cfg_attr(not(feature = "std"), no_std)]
#![feature(external_doc)]
//#![deny(missing_docs)]
#![doc(include = "../README.md")]
#![doc(html_logo_url = "https://doc.dalek.rs/assets/dalek-logo-clear.png")]
#![doc(html_root_url = "https://docs.rs/bulletproofs/2.0.0")]
#[macro_use]
extern crate alloc;
mod util;
#[doc(include = "../docs/notes-intro.md")]
mod notes {
#[doc(include = "../docs/notes-ipp.md")]
mod inner_product_proof {}
#[doc(include = "../docs/notes-rp.md")]
mod range_proof {}
#[doc(include = "../docs/notes-r1cs.md")]
mod r1cs_proof {}
}
mod errors;
mod generators;
mod inner_product_proof;
mod range_proof;
mod transcript;
pub use crate::{
errors::ProofError,
generators::{BulletproofGens, BulletproofGensShare, PedersenGens},
range_proof::RangeProof,
};
#[doc(include = "../docs/aggregation-api.md")]
pub mod range_proof_mpc {
pub use crate::{
errors::MPCError,
range_proof::{dealer, messages, party},
};
}
#[cfg(feature = "yoloproofs")]
pub mod r1cs;
| 22.022222 | 75 | 0.68113 |
56c609a93b6123bc9e71d8947ae22cfc39d1b991 | 2,630 | // Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{fmt, marker::PhantomData};
/// `ContextKey` provides strongly typed access to data inside `Context`.
/// See `exonum::fabric::keys` for keys used by the exonum itself.
pub struct ContextKey<T> {
// These fields are public so that `context_key`
// macro works outside of this crate. It should be
// replaced with `const fn`, once it is stable.
#[doc(hidden)]
pub __name: &'static str,
#[doc(hidden)]
pub __phantom: PhantomData<T>,
}
// We need explicit `impl Copy` because derive won't work if `T: !Copy`.
impl<T> Copy for ContextKey<T> {}
// Bug in clippy, fixed on master branch.
// spell-checker:ignore expl
#[cfg_attr(feature = "cargo-clippy", allow(expl_impl_clone_on_copy))]
impl<T> Clone for ContextKey<T> {
fn clone(&self) -> Self {
ContextKey {
__name: self.__name,
__phantom: self.__phantom,
}
}
}
impl<T> fmt::Debug for ContextKey<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "ContextKey({:?})", self.__name)
}
}
impl<T> ContextKey<T> {
/// Name of this key.
pub fn name(&self) -> &str {
self.__name
}
}
/// Constructs a `ContextKey` from a given name.
///
/// For additional information refer to
/// [`exonum:helpers:fabric:ContextKey`].
///
/// [`exonum:helpers:fabric:ContextKey`]: ./helpers/fabric/struct.ContextKey.html
///
/// # Examples
///
/// The example below creates a constant using the `ContextKey` macro.
///
/// ```
/// #[macro_use]
/// extern crate exonum;
/// use exonum::helpers::fabric::ContextKey;
///
/// const NAME: ContextKey<String> = context_key!("name");
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! context_key {
($name:expr) => {{
$crate::helpers::fabric::ContextKey {
__name: $name,
__phantom: ::std::marker::PhantomData,
}
}};
}
#[test]
fn key_is_copy() {
const K: ContextKey<Vec<String>> = context_key!("k");
let x = K;
let y = x;
assert_eq!(x.name(), y.name());
}
| 28.27957 | 81 | 0.641065 |
899042e287dfead279d3e1697968c359f1402887 | 17,927 | //
// GLSL Mathematics for Rust.
//
// Copyright (c) 2015 The glm-rs authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use super::traits::{GenBVec, GenFloatVec, GenNumVec, GenVec};
use basenum::*;
use num::{Float, One, Zero};
use quickcheck::{Arbitrary, Gen};
use rand::{Rand, Rng};
use serde_derive::*;
use std::cmp::Eq;
use std::mem;
use std::ops::{
Add, BitAnd, BitOr, BitXor, Div, Index, IndexMut, Mul, Neg, Not, Rem, Shl, Shr, Sub,
};
use traits::*;
// copied from `cgmath-rs/src/vector.rs`.
macro_rules! fold(
($m: ident, { $x: expr, $y: expr }) => {
$x.$m($y)
};
($m: ident, { $x: expr, $y: expr, $z: expr }) => {
$x.$m($y).$m($z)
};
($m: ident, { $x: expr, $y: expr, $z: expr, $w: expr }) => {
$x.$m($y).$m($z).$m($w)
};
);
macro_rules! def_genvec(
(
$t: ident, // name of the type to be defined,
$n: expr, // dimension (2, 3, or 4),
$($field: ident),+ // list of field names (e.g., "x, y, z").
) => {
#[repr(C)]
#[derive(Copy, Clone, PartialEq, Debug,Serialize,Deserialize)]
pub struct $t<T: Primitive> {
$(pub $field: T),+
}
impl<T: Primitive> $t<T> {
#[inline(always)]
pub fn new($($field: T),+) -> $t<T> {
$t { $($field: $field),+ }
}
#[inline(always)]
pub fn from_array(ary: &[T; $n]) -> &$t<T> {
let r: &$t<T> = unsafe { mem::transmute(ary) };
r
}
#[inline(always)]
pub fn from_array_mut(ary: &mut [T; $n]) -> &mut $t<T> {
let r: &mut $t<T> = unsafe { mem::transmute(ary) };
r
}
#[inline(always)]
pub fn as_array(&self) -> &[T; $n] {
let ary: &[T; $n] = unsafe { mem::transmute(self) };
ary
}
#[inline(always)]
pub fn as_array_mut(&mut self) -> &mut [T; $n] {
let ary: &mut [T; $n] = unsafe { mem::transmute(self) };
ary
}
}
impl<T: Primitive> GenVec<T> for $t<T> {
#[inline(always)]
fn dim() -> usize { $n }
}
impl<T: Primitive> Index<usize> for $t<T> {
type Output = T;
#[inline(always)]
fn index<'a>(&'a self, i: usize) -> &'a T {
self.as_array().index(i)
}
}
impl<T: Primitive> IndexMut<usize> for $t<T> {
#[inline(always)]
fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut T {
self.as_array_mut().index_mut(i)
}
}
impl<T: Primitive> Rand for $t<T> {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> $t<T> {
$t {$($field: rng.gen()),+}
}
}
impl<T: Primitive + Arbitrary> Arbitrary for $t<T> {
fn arbitrary<G: Gen>(g: &mut G) -> $t<T> {
// do not use `g.size()`.
g.gen()
}
}
impl Eq for $t<bool> {}
impl GenBType for $t<bool> {}
impl GenBVec for $t<bool> {
#[inline(always)]
fn all(&self) -> bool {
$(self.$field) && +
}
#[inline(always)]
fn any(&self) -> bool {
$(self.$field) || +
}
#[inline(always)]
fn not(&self) -> $t<bool> {
$t::new($(!self.$field),+)
}
}
impl<T: BaseNum> Add<$t<T>> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn add(self, rhs: $t<T>) -> $t<T> {
$t::new($(self.$field + rhs.$field),+)
}
}
impl<T: BaseNum> Add<T> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn add(self, rhs: T) -> $t<T> {
$t::new($(self.$field + rhs),+)
}
}
impl<T: BaseNum> Mul<$t<T>> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn mul(self, rhs: $t<T>) -> $t<T> {
$t::new($(self.$field * rhs.$field),+)
}
}
impl<T: BaseNum> Mul<T> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn mul(self, rhs: T) -> $t<T> {
$t::new($(self.$field * rhs),+)
}
}
impl<T: BaseNum> Div<$t<T>> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn div(self, rhs: $t<T>) -> $t<T> {
$t::new($(self.$field / rhs.$field),+)
}
}
impl<T: BaseNum> Div<T> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn div(self, rhs: T) -> $t<T> {
$t::new($(self.$field / rhs),+)
}
}
impl<T: BaseNum> Rem<$t<T>> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn rem(self, rhs: $t<T>) -> $t<T> {
$t::new($(self.$field % rhs.$field),+)
}
}
impl<T: BaseNum> Rem<T> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn rem(self, rhs: T) -> $t<T> {
$t::new($(self.$field % rhs),+)
}
}
impl<T: BaseNum> One for $t<T> {
#[inline(always)]
fn one() -> $t<T> {
let y = T::one();
$t { $($field: y),+ }
}
}
impl<T: BaseNum> Zero for $t<T> {
#[inline(always)]
fn zero() -> $t<T> {
let l = T::zero();
$t { $($field: l),+ }
}
#[inline]
fn is_zero(&self) -> bool {
let l = T::zero();
$(self.$field == l) && +
}
}
impl<T: BaseNum> GenNum<T> for $t<T> {
#[inline(always)]
fn from_s(x: T) -> Self {
$t { $($field: x),+ }
}
#[inline(always)]
fn map<F: Fn(T) -> T>(self, f: F) -> $t<T> {
$t::new($(f(self.$field)),+)
}
#[inline(always)]
fn zip<F: Fn(T, T) -> T>(self, y: $t<T>, f: F) -> $t<T> {
$t::new($(f(self.$field, y.$field)),+)
}
#[inline]
fn split<F: Fn(T) -> (T, T)>(self, f: F) -> ($t<T>, $t<T>) {
let ling = $t::<T>::zero();
let mut a = ling;
let mut b = ling;
let dim = $t::<T>::dim();
for i in 0..dim {
let (c, d) = f(self[i]);
a[i] = c;
b[i] = d;
}
(a, b)
}
#[inline]
fn map2<F: Fn(T, T) -> (T, T)>(self, y: Self, f: F) -> (Self, Self) {
let ling = Self::zero();
let mut a = ling;
let mut b = ling;
let dim = Self::dim();
for i in 0..dim {
let (c, d) = f(self[i], y[i]);
a[i] = c;
b[i] = d;
}
(a, b)
}
}
impl<T: BaseNum> GenNumVec<T> for $t<T> {
#[inline(always)]
fn sum(&self) -> T {
fold!(add, { $(self.$field),+ })
}
#[inline(always)]
fn product(&self) -> T {
fold!(mul, { $(self.$field),+ })
}
#[inline(always)]
fn min(&self) -> T {
fold!(min, { $(self.$field),+ })
}
#[inline(always)]
fn max(&self) -> T {
fold!(max, { $(self.$field),+ })
}
}
impl<T: SignedNum + BaseNum> Neg for $t<T> {
type Output = $t<T>;
#[inline]
fn neg(self) -> $t<T> {
$t::new($(-(self.$field)),+)
}
}
impl<T: SignedNum + BaseNum> Sub<$t<T>> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn sub(self, rhs: $t<T>) -> $t<T> {
$t::new($(self.$field - rhs.$field),+)
}
}
impl<T: SignedNum + BaseNum> Sub<T> for $t<T> {
type Output = $t<T>;
#[inline(always)]
fn sub(self, rhs: T) -> $t<T> {
$t::new($(self.$field - rhs),+)
}
}
impl<T: SignedNum + BaseNum> SignedNum for $t<T> {
#[inline]
fn abs(&self) -> $t<T> {
$t::new($(self.$field.abs()),+)
}
#[inline]
fn sign(&self) -> $t<T> {
$t::new($(self.$field.sign()),+)
}
}
impl<T: BaseInt> Eq for $t<T> {}
impl<T: BaseInt> Not for $t<T> {
type Output = Self;
#[inline]
fn not(self) -> Self {
$t::new($(!self.$field),+)
}
}
impl<T: BaseInt> BitAnd<T> for $t<T> {
type Output = Self;
#[inline]
fn bitand(self, rhs: T) -> Self {
$t::new($(self.$field & rhs),+)
}
}
impl<T: BaseInt> BitAnd<$t<T>> for $t<T> {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
$t::new($(self.$field & rhs.$field),+)
}
}
impl<T: BaseInt> BitOr<T> for $t<T> {
type Output = Self;
#[inline]
fn bitor(self, rhs: T) -> Self {
$t::new($(self.$field | rhs),+)
}
}
impl<T: BaseInt> BitOr<$t<T>> for $t<T> {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
$t::new($(self.$field | rhs.$field),+)
}
}
impl<T: BaseInt> BitXor<T> for $t<T> {
type Output = Self;
#[inline]
fn bitxor(self, rhs: T) -> Self {
$t::new($(self.$field ^ rhs),+)
}
}
impl<T: BaseInt> BitXor<$t<T>> for $t<T> {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
$t::new($(self.$field ^ rhs.$field),+)
}
}
impl<T: BaseInt> Shl<usize> for $t<T> {
type Output = Self;
#[inline]
fn shl(self, rhs: usize) -> Self {
$t::new($(self.$field << rhs),+)
}
}
impl<T: BaseInt> Shr<usize> for $t<T> {
type Output = Self;
#[inline]
fn shr(self, rhs: usize) -> Self {
$t::new($(self.$field >> rhs),+)
}
}
impl<T: BaseInt> GenInt<T> for $t<T> {}
impl GenIType for $t<i32> {}
impl GenUType for $t<u32> {}
impl<T: BaseFloat> ApproxEq for $t<T> {
type BaseType = T;
#[inline]
fn is_close_to(&self, rhs: &$t<T>, max_diff: T) -> bool {
$(self.$field.is_close_to(&rhs.$field, max_diff)) && +
}
}
impl<T: BaseFloat> GenFloat<T> for $t<T> {
fn fma(&self, b: &$t<T>, c: &$t<T>) -> $t<T> {
$t::new($(Float::mul_add(self.$field, b.$field, c.$field)),+)
}
}
impl<T: BaseFloat> GenFloatVec<T> for $t<T> {}
impl GenType for $t<f32> {}
impl GenDType for $t<f64> {}
}
);
def_genvec! { Vector2, 2, x, y }
def_genvec! { Vector3, 3, x, y, z }
def_genvec! { Vector4, 4, x, y, z, w }
impl<T: Primitive> Vector2<T> {
/// Extends _self_ to a `Vector3` by appending `z`.
///
/// # Example
///
/// ```rust
/// use glm::*;
///
/// let v2 = vec2(1., 2.);
/// let v3 = vec3(1., 2., 3.);
/// assert_eq!(v2.extend(3.), v3);
/// ```
#[inline]
pub fn extend(&self, z: T) -> Vector3<T> {
Vector3 {
x: self.x,
y: self.y,
z: z,
}
}
}
impl<T: Primitive> Vector3<T> {
/// Extends _self_ to a `Vector4` by appending `w`.
///
/// # Example
///
/// ```rust
/// use glm::*;
///
/// let v3 = vec3(1., 2., 3.);
/// let v4 = vec4(1., 2., 3., 4.);
/// assert_eq!(v3.extend(4.), v4);
/// ```
#[inline]
pub fn extend(&self, w: T) -> Vector4<T> {
Vector4 {
x: self.x,
y: self.y,
z: self.z,
w: w,
}
}
/// Truncates _self_ to a `Vector2` by remove the `i`<sub>th</sub> element.
///
/// Parameter `i` is `0` based index.
///
/// # Panic
///
/// It is a panic if i is larger than `2`.
///
/// # Example
///
/// ```rust
/// use glm::*;
///
/// let v3 = vec3(1., 2., 3.);
/// let v2 = vec2(1., 3.);
/// assert_eq!(v3.truncate(1), v2);
/// ```
#[inline]
pub fn truncate(&self, i: usize) -> Vector2<T> {
match i {
0 => Vector2::new(self.y, self.z),
1 => Vector2::new(self.x, self.z),
2 => Vector2::new(self.x, self.y),
_ => panic!("parameter i is out of range [{:?} > 2].", i),
}
}
}
impl<T: Primitive> Vector4<T> {
/// Truncates _self_ to a `Vector3` by remove the `i`<sub>th</sub> element.
///
/// Parameter `i` is `0` based index.
///
/// # Panic
///
/// It is a panic if i is larger than `3`.
#[inline]
pub fn truncate(&self, i: usize) -> Vector3<T> {
match i {
0 => Vector3::new(self.y, self.z, self.w),
1 => Vector3::new(self.x, self.z, self.w),
2 => Vector3::new(self.x, self.y, self.w),
3 => Vector3::new(self.x, self.y, self.z),
_ => panic!("parameter i is out of range [{:?} > 3].", i),
}
}
}
macro_rules! def_alias(
(
$({
$a: ident, // type alias (e.g., Vec2 for Vector2<f32>),
$t: ident, // type to be aliased,
$et: ty, // element type,
$ctor: ident, // constructor name (e.g., vec3),
$($field: ident),+ // fields,
}),+
) => {
$(
pub type $a = $t<$et>;
#[inline(always)]
pub fn $ctor($($field: $et),+) -> $t<$et> {
$t::new($($field),+)
}
)+
}
);
def_alias! {
{ BVec2, Vector2, bool, bvec2, x, y },
{ BVec3, Vector3, bool, bvec3, x, y, z },
{ BVec4, Vector4, bool, bvec4, x, y, z, w },
{ Vec2, Vector2, f32, vec2, x, y },
{ Vec3, Vector3, f32, vec3, x, y, z },
{ Vec4, Vector4, f32, vec4, x, y, z, w },
{ DVec2, Vector2, f64, dvec2, x, y },
{ DVec3, Vector3, f64, dvec3, x, y, z },
{ DVec4, Vector4, f64, dvec4, x, y, z, w },
{ IVec2, Vector2, i32, ivec2, x, y },
{ IVec3, Vector3, i32, ivec3, x, y, z },
{ IVec4, Vector4, i32, ivec4, x, y, z, w },
{ UVec2, Vector2, u32, uvec2, x, y },
{ UVec3, Vector3, u32, uvec3, x, y, z },
{ UVec4, Vector4, u32, uvec4, x, y, z, w }
}
/*
use serde::ser::SerializeStruct;
impl Serialize for Vec2 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("Vector2", 2)?;
s.serialize_field("x", &self.x)?;
s.serialize_field("y", &self.y)?;
s.end()
}
}
*/
#[cfg(test)]
mod test {
use super::*;
use num::One;
use quickcheck::*;
#[test]
fn test_as_array() {
fn prop(v3: Vec3) -> bool {
let ary: &[f32; 3] = v3.as_array();
ary[0] == v3.x && ary[1] == v3.y && ary[2] == v3.z
}
quickcheck(prop as fn(Vec3) -> bool);
}
#[test]
fn test_as_array_mut() {
fn prop(v2: DVec2) -> bool {
let DVec2 { x, y } = v2;
let mut v = v2;
let ary: &mut [f64; 2] = v.as_array_mut();
ary[0] = x + 1.;
ary[1] = y * 2.;
(x + 1.) == ary[0] && (y * 2.) == ary[1]
}
quickcheck(prop as fn(DVec2) -> bool)
}
#[test]
fn test_index() {
fn prop(v3: Vec3) -> bool {
v3[0] == v3.x && v3[1] == v3.y && v3[2] == v3.z
}
quickcheck(prop as fn(Vec3) -> bool);
}
#[test]
fn test_index_mut() {
fn prop(iv: IVec3) -> bool {
let mut miv = iv;
miv[0] = iv.x + 1;
miv[1] = iv.y + 1;
miv[2] = iv.z + 1;
miv == iv + IVec3::one()
}
quickcheck(prop as fn(IVec3) -> bool);
}
}
| 30.855422 | 88 | 0.406091 |
6180f750ba814c6917bdd92836fd0d902855686a | 4,534 | use getrandom::register_custom_getrandom;
use proptest::test_runner::{
Config,
TestRunner
};
use sudograph::graphql_database;
use test_utilities::{
arbitraries::{
order::{
order_create::get_order_create_arbitrary,
order_read::get_order_read_arbitrary
},
queries::queries::QueriesArbitrary
}
};
fn custom_getrandom(buf: &mut [u8]) -> Result<(), getrandom::Error> {
// TODO get some randomness
return Ok(());
}
register_custom_getrandom!(custom_getrandom);
graphql_database!("canisters/order/src/schema.graphql");
// TODO also add in some counter to at least know what iteration you're on
#[ic_cdk_macros::update]
fn test_order(
cases: u32,
logging: String
) -> bool {
let graphql_ast = Box::leak(Box::new(graphql_parser::schema::parse_schema::<String>(static_schema).unwrap()));
let object_types = Box::leak(Box::new(get_object_types(graphql_ast)));
futures::executor::block_on(async {
graphql_mutation(
"
mutation {
clear
}
".to_string(),
"{}".to_string()
).await;
});
for object_type in object_types.iter() {
if object_type.name == "SudographSettings" {
continue;
}
let mut runner = TestRunner::new(Config {
cases,
max_shrink_iters: 0,
.. Config::default()
});
let order_create_arbitrary = get_order_create_arbitrary(
graphql_ast,
object_types,
object_type,
None,
2,
&graphql_mutation,
&graphql_mutation
);
runner.run(&order_create_arbitrary, |order_create_concrete| {
let order_read_arbitrary = get_order_read_arbitrary(
graphql_ast,
object_type,
true,
Some(object_type.name.clone()),
None,
order_create_concrete.objects,
order_create_concrete.order_info_map
);
let mut runner = TestRunner::new(Config {
cases: 10,
max_shrink_iters: 0,
.. Config::default()
});
runner.run(&order_read_arbitrary, |order_read_concrete| {
if logging == "verbose" {
ic_cdk::println!("order_read_concrete.selection\n");
ic_cdk::println!("{:#?}", order_read_concrete.selection);
}
let result_string = futures::executor::block_on(async {
return graphql_query(
format!(
"query {{
{selection}
}}",
selection = order_read_concrete.selection
),
"{}".to_string()
).await;
});
let result_json: serde_json::value::Value = serde_json::from_str(&result_string).unwrap();
let query_name = format!(
"read{object_type_name}",
object_type_name = object_type.name
);
let expected_value = serde_json::json!({
"data": {
query_name: order_read_concrete.expected_value
}
});
if logging == "verbose" {
// ic_cdk::println!("result_json\n");
// ic_cdk::println!("{:#?}", result_json);
// ic_cdk::println!("expected_value\n");
// ic_cdk::println!("{:#?}", expected_value);
}
assert_eq!(
result_json,
expected_value
);
return Ok(());
}).unwrap();
futures::executor::block_on(async {
graphql_mutation(
"
mutation {
clear
}
".to_string(),
"{}".to_string()
).await;
});
if logging == "verbose" {
ic_cdk::println!("Test complete");
ic_cdk::println!("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
return Ok(());
}).unwrap();
}
return true;
} | 29.828947 | 114 | 0.468461 |
91071eb3df5a266338d4f6ca30dad8c774618309 | 2,494 | // Copyright 2018 The Grin Developers
//
// 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.
//! libtx specific errors
use failure::{Backtrace, Context, Fail};
use std::fmt::{self, Display};
use crate::core::transaction;
use crate::keychain;
use crate::util::secp;
/// Lib tx error definition
#[derive(Debug)]
pub struct Error {
inner: Context<ErrorKind>,
}
#[derive(Clone, Debug, Eq, Fail, PartialEq, Serialize, Deserialize)]
/// Libwallet error types
pub enum ErrorKind {
/// SECP error
#[fail(display = "Secp Error")]
Secp(secp::Error),
/// Keychain error
#[fail(display = "Keychain Error")]
Keychain(keychain::Error),
/// Transaction error
#[fail(display = "Transaction Error")]
Transaction(transaction::Error),
/// Signature error
#[fail(display = "Signature Error")]
Signature(String),
/// Rangeproof error
#[fail(display = "Rangeproof Error")]
RangeProof(String),
}
impl Fail for Error {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl Error {
/// Return errorkind
pub fn kind(&self) -> ErrorKind {
self.inner.get_context().clone()
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
inner: Context::new(kind),
}
}
}
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner: inner }
}
}
impl From<secp::Error> for Error {
fn from(error: secp::Error) -> Error {
Error {
inner: Context::new(ErrorKind::Secp(error)),
}
}
}
impl From<keychain::Error> for Error {
fn from(error: keychain::Error) -> Error {
Error {
inner: Context::new(ErrorKind::Keychain(error)),
}
}
}
impl From<transaction::Error> for Error {
fn from(error: transaction::Error) -> Error {
Error {
inner: Context::new(ErrorKind::Transaction(error)),
}
}
}
| 22.880734 | 75 | 0.681235 |
ac05a9dbe3b91dd240ab8caad4795132e7bf078e | 5,383 | use crate::api::*;
use crate::constants::*;
use crate::services::cookie::CookieService;
use crate::services::router;
use serde::{Deserialize, Serialize};
use serde_json::to_string;
use wasm_bindgen::prelude::*;
use yew::{
format::{Json, Nothing},
prelude::*,
};
use yew_material::list::*;
use yew_material::text_inputs::*;
use yew_material::{
MatButton, MatFormfield, MatList, MatSnackbar, MatTextField, WeakComponentLink,
};
use yew_router::agent::RouteRequest;
use yew_router::prelude::*;
pub struct ListPostsPage {
link: ComponentLink<Self>,
fetch: FetchState<ResponseBlock<PostsResponse>>,
fetch_counts: FetchState<ResponseBlock<CountPostsResponse>>,
list_link: WeakComponentLink<MatList>,
page: i64,
count: i64,
}
pub enum Msg {
GetPostHeaders,
GetCounts,
ReceivePostHeadersResponse(FetchState<ResponseBlock<PostsResponse>>),
ReceiveCountsResponse(FetchState<ResponseBlock<CountPostsResponse>>),
NextPage,
PreviousPage,
}
#[derive(Properties, Clone)]
pub struct Props {}
impl Component for ListPostsPage {
type Message = Msg;
type Properties = Props;
fn create(_props: Props, link: ComponentLink<Self>) -> Self {
Self {
link,
fetch: FetchState::NotFetching,
fetch_counts: FetchState::NotFetching,
list_link: WeakComponentLink::default(),
page: 0,
count: 0,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::GetCounts => {
let future = async move {
match get_post_counts().await {
Ok(info) => Msg::ReceiveCountsResponse(FetchState::Success(info)),
Err(_) => Msg::ReceiveCountsResponse(FetchState::Failed(FetchError::from(
JsValue::FALSE,
))),
}
};
send_future(self.link.clone(), future);
false
}
Msg::GetPostHeaders => {
let page = self.page;
let future = async move {
match posts(page * MAX_LIST_POSTS, MAX_LIST_POSTS).await {
Ok(info) => Msg::ReceivePostHeadersResponse(FetchState::Success(info)),
Err(_) => Msg::ReceivePostHeadersResponse(FetchState::Failed(
FetchError::from(JsValue::FALSE),
)), // TODO
}
};
send_future(self.link.clone(), future);
false
}
Msg::ReceiveCountsResponse(data) => {
self.fetch_counts = data;
if let FetchState::Success(r) = self.fetch_counts.clone() {
if let Some(body) = r.body {
self.count = body.count;
}
}
true
}
Msg::ReceivePostHeadersResponse(data) => {
self.fetch = data;
true
}
Msg::NextPage => {
if (self.page + 1) * MAX_LIST_POSTS < self.count {
self.page += 1;
self.fetch = FetchState::NotFetching;
true
} else {
false
}
}
Msg::PreviousPage => {
if self.page > 0 {
self.page -= 1;
self.fetch = FetchState::NotFetching;
true
} else {
false
}
}
_ => false,
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
if let FetchState::NotFetching = self.fetch_counts.clone() {
self.link.send_message(Msg::GetCounts);
}
let list = if let FetchState::Success(r) = self.fetch.clone() {
if let Some(body) = r.body {
body.posts
} else {
vec![]
}
} else if let FetchState::NotFetching = self.fetch.clone() {
self.link.send_message(Msg::GetPostHeaders);
vec![]
} else {
vec![]
};
html! {
<div class="container">
<div class="block">
<h3>{"Posts"}</h3>
<MatList list_link=self.list_link.clone()>
{
for list.iter().map(|post_header| {
html! {
<router::MainRouterAnchor route=router::MainRoute::ViewPost(post_header.id as i64)><MatListItem>{&post_header.title}</MatListItem></router::MainRouterAnchor>
}
})
}
</MatList>
<div class="button-grid">
<span onclick=self.link.callback(|_| Msg::PreviousPage)><MatButton disabled=(self.page == 0) label="Previous"/></span>
<span onclick=self.link.callback(|_| Msg::NextPage)><MatButton disabled=((self.page+1)*MAX_LIST_POSTS >= self.count) label="Next"/></span>
</div>
</div>
</div>
}
}
}
| 33.64375 | 189 | 0.490061 |
d98d460c8db0c9795331a2f2290df8b89b969d81 | 2,169 | use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
impl Config {
pub fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("Not enough arguments");
}
let query = args[1].clone();
let filename = args[2].clone();
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
Ok(Config { query, filename, case_sensitive })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
// Read file contents
let contents = fs::read_to_string(config.filename)?;
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
};
for line in results {
println!("{}", line);
}
Ok(())
}
// Data returned by the function will live as long as the data passed into
// the `search` function in the `contents` argument.
fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(
vec!["safe, fast, productive."],
search(query, contents)
);
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
| 21.264706 | 80 | 0.559244 |
09c6691c730d8a956320a837ab539a091638c52c | 5,757 | use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use log::debug;
use super::LibSource;
pub struct RPathConfig<'a> {
pub used_libs: &'a [(String, LibSource)],
pub output_file: PathBuf,
pub is_like_osx: bool,
pub has_rpath: bool,
pub linker_is_gnu: bool,
pub get_install_prefix_lib_path: &'a mut dyn FnMut() -> PathBuf,
}
pub fn get_rpath_flags(config: &mut RPathConfig<'_>) -> Vec<String> {
// No rpath on windows
if !config.has_rpath {
return Vec::new();
}
debug!("preparing the RPATH!");
let libs = config.used_libs.clone();
let libs = libs
.iter()
.filter_map(|&(_, ref l)| l.option())
.collect::<Vec<_>>();
let rpaths = get_rpaths(config, &libs);
let mut flags = rpaths_to_flags(&rpaths);
// Use DT_RUNPATH instead of DT_RPATH if available
if config.linker_is_gnu {
flags.push("-Wl,--enable-new-dtags".to_owned());
}
flags
}
fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
let mut ret = Vec::with_capacity(rpaths.len()); // the minimum needed capacity
for rpath in rpaths {
if rpath.contains(',') {
ret.push("-Wl,-rpath".into());
ret.push("-Xlinker".into());
ret.push(rpath.clone());
} else {
ret.push(format!("-Wl,-rpath,{}", &(*rpath)));
}
}
ret
}
fn get_rpaths(config: &mut RPathConfig<'_>, libs: &[PathBuf]) -> Vec<String> {
debug!("output: {:?}", config.output_file.display());
debug!("libs:");
for libpath in libs {
debug!(" {:?}", libpath.display());
}
// Use relative paths to the libraries. Binaries can be moved
// as long as they maintain the relative relationship to the
// crates they depend on.
let rel_rpaths = get_rpaths_relative_to_output(config, libs);
// And a final backup rpath to the global library location.
let fallback_rpaths = vec![get_install_prefix_rpath(config)];
fn log_rpaths(desc: &str, rpaths: &[String]) {
debug!("{} rpaths:", desc);
for rpath in rpaths {
debug!(" {}", *rpath);
}
}
log_rpaths("relative", &rel_rpaths);
log_rpaths("fallback", &fallback_rpaths);
let mut rpaths = rel_rpaths;
rpaths.extend_from_slice(&fallback_rpaths);
// Remove duplicates
let rpaths = minimize_rpaths(&rpaths);
rpaths
}
fn get_rpaths_relative_to_output(config: &mut RPathConfig<'_>, libs: &[PathBuf]) -> Vec<String> {
libs.iter()
.map(|a| get_rpath_relative_to_output(config, a))
.collect()
}
fn get_rpath_relative_to_output(config: &mut RPathConfig<'_>, lib: &Path) -> String {
// Mac doesn't appear to support $ORIGIN
let prefix = if config.is_like_osx {
"@loader_path"
} else {
"$ORIGIN"
};
let cwd = env::current_dir().unwrap();
let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or_else(|_| cwd.join(lib));
lib.pop(); // strip filename
let mut output = cwd.join(&config.output_file);
output.pop(); // strip filename
let output = fs::canonicalize(&output).unwrap_or(output);
let relative = path_relative_from(&lib, &output).unwrap_or_else(|| {
panic!(
"couldn't create relative path from {:?} to {:?}",
output, lib
)
});
// FIXME (#9639): This needs to handle non-utf8 paths
format!(
"{}/{}",
prefix,
relative.to_str().expect("non-utf8 component in path")
)
}
// This routine is adapted from the *old* Path's `path_relative_from`
// function, which works differently from the new `relative_from` function.
// In particular, this handles the case on unix where both paths are
// absolute but with only the root as the common directory.
fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
use std::path::Component;
if path.is_absolute() != base.is_absolute() {
if path.is_absolute() {
Some(PathBuf::from(path))
} else {
None
}
} else {
let mut ita = path.components();
let mut itb = base.components();
let mut comps: Vec<Component<'_>> = vec![];
loop {
match (ita.next(), itb.next()) {
(None, None) => break,
(Some(a), None) => {
comps.push(a);
comps.extend(ita.by_ref());
break;
}
(None, _) => comps.push(Component::ParentDir),
(Some(a), Some(b)) if comps.is_empty() && a == b => (),
(Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
(Some(_), Some(b)) if b == Component::ParentDir => return None,
(Some(a), Some(_)) => {
comps.push(Component::ParentDir);
comps.extend(itb.map(|_| Component::ParentDir));
comps.push(a);
comps.extend(ita.by_ref());
break;
}
}
}
Some(comps.iter().map(|c| c.as_os_str()).collect())
}
}
fn get_install_prefix_rpath(config: &mut RPathConfig<'_>) -> String {
let path = (config.get_install_prefix_lib_path)();
let path = env::current_dir().unwrap().join(&path);
// FIXME (#9639): This needs to handle non-utf8 paths
path.to_str()
.expect("non-utf8 component in rpath")
.to_owned()
}
fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
let mut set = HashSet::new();
let mut minimized = Vec::new();
for rpath in rpaths {
if set.insert(rpath) {
minimized.push(rpath.clone());
}
}
minimized
}
| 30.62234 | 97 | 0.569567 |
874eb83f1d64cc5799394e379bbb8f872ae8ba83 | 2,264 | //! Unit test for PrivateTree
#[cfg(test)]
use super::{index::NodeIndex, private_tree::*, test_util::*};
#[cfg(test)]
use crate::{ciphersuite::*, credentials::*, key_packages::*, utils::*};
#[cfg(test)]
// Common setup for tests.
fn setup(ciphersuite: &Ciphersuite, len: usize) -> (KeyPackageBundle, NodeIndex, Vec<NodeIndex>) {
let credential_bundle =
CredentialBundle::new("username".into(), CredentialType::Basic, ciphersuite.name())
.unwrap();
let key_package_bundle =
KeyPackageBundle::new(&[ciphersuite.name()], &credential_bundle, vec![]).unwrap();
let own_index = NodeIndex::from(0u32);
let direct_path = generate_path_u8(len);
(key_package_bundle, own_index, direct_path)
}
#[cfg(test)]
// Common tests after setup.
fn test_private_tree(
private_tree: &PrivateTree,
direct_path: &[NodeIndex],
public_keys: &[HPKEPublicKey],
ciphersuite: &Ciphersuite,
) {
// Check that we can encrypt to a public key.
let path_index = 15;
let index = direct_path[path_index];
let public_key = &public_keys[path_index];
let private_key = private_tree.path_keys().get(index).unwrap();
let data = randombytes(55);
let info = b"PrivateTree Test Info";
let aad = b"PrivateTree Test AAD";
let c = ciphersuite.hpke_seal(public_key, info, aad, &data);
let m = ciphersuite
.hpke_open(&c, &private_key, info, aad)
.expect("Error decrypting valid Secret in PrivateTree test.");
assert_eq!(m, data);
}
#[test]
fn create_private_tree_from_secret() {
use crate::config::*;
const PATH_LENGTH: usize = 33;
for ciphersuite in Config::supported_ciphersuites() {
let (key_package_bundle, own_index, direct_path) = setup(ciphersuite, PATH_LENGTH);
let mut private_tree = PrivateTree::from_key_package_bundle(own_index, &key_package_bundle);
// Compute path secrets from the leaf and generate keypairs
let public_keys = private_tree.generate_path_secrets(
&ciphersuite,
key_package_bundle.leaf_secret(),
&direct_path,
);
assert_eq!(public_keys.len(), direct_path.len());
test_private_tree(&private_tree, &direct_path, &public_keys, &ciphersuite);
}
}
| 33.791045 | 100 | 0.67447 |
87db5ccfad046fc93d972d3544144d9f21e0d065 | 725 | use {
crate::duplicate_shred,
crossbeam_channel::{RecvTimeoutError, SendError},
std::io,
thiserror::Error,
};
#[derive(Error, Debug)]
pub enum GossipError {
#[error("duplicate node instance")]
DuplicateNodeInstance,
#[error(transparent)]
DuplicateShredError(#[from] duplicate_shred::Error),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
RecvTimeoutError(#[from] RecvTimeoutError),
#[error("send error")]
SendError,
#[error("serialization error")]
Serialize(#[from] Box<bincode::ErrorKind>),
}
impl<T> std::convert::From<SendError<T>> for GossipError {
fn from(_e: SendError<T>) -> GossipError {
GossipError::SendError
}
}
| 25 | 58 | 0.655172 |
6ac5eb17335e5c57c7d4501453fc73eaf1599130 | 1,256 | use serde::Serialize;
use crate::{
net,
requests::{RequestOld, ResponseResult},
types::{Chat, ChatId},
Bot,
};
/// Use this method to get up to date information about the chat (current name
/// of the user for one-on-one conversations, current username of a user, group
/// or channel, etc.).
///
/// [The official docs](https://core.telegram.org/bots/api#getchat).
#[serde_with_macros::skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
pub struct GetChat {
#[serde(skip_serializing)]
bot: Bot,
pub chat_id: ChatId,
}
#[async_trait::async_trait]
impl RequestOld for GetChat {
type Output = Chat;
async fn send(&self) -> ResponseResult<Chat> {
net::request_json(self.bot.client(), self.bot.token(), "getChat", &self).await
}
}
impl GetChat {
pub(crate) fn new<C>(bot: Bot, chat_id: C) -> Self
where
C: Into<ChatId>,
{
let chat_id = chat_id.into();
Self { bot, chat_id }
}
/// Unique identifier for the target chat or username of the target
/// supergroup or channel (in the format `@channelusername`).
pub fn chat_id<T>(mut self, val: T) -> Self
where
T: Into<ChatId>,
{
self.chat_id = val.into();
self
}
}
| 24.627451 | 86 | 0.627389 |
fc54d5098ffd20f13709f325580d6496921c6841 | 5,358 | // Generated from definition io.k8s.api.policy.v1beta1.PodDisruptionBudgetSpec
/// PodDisruptionBudgetSpec is a description of a PodDisruptionBudget.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PodDisruptionBudgetSpec {
/// An eviction is allowed if at most "maxUnavailable" pods selected by "selector" are unavailable after the eviction, i.e. even in absence of the evicted pod. For example, one can prevent all voluntary evictions by specifying 0. This is a mutually exclusive setting with "minAvailable".
pub max_unavailable: Option<crate::v1_14::apimachinery::pkg::util::intstr::IntOrString>,
/// An eviction is allowed if at least "minAvailable" pods selected by "selector" will still be available after the eviction, i.e. even in the absence of the evicted pod. So for example you can prevent all voluntary evictions by specifying "100%".
pub min_available: Option<crate::v1_14::apimachinery::pkg::util::intstr::IntOrString>,
/// Label query over pods whose evictions are managed by the disruption budget.
pub selector: Option<crate::v1_14::apimachinery::pkg::apis::meta::v1::LabelSelector>,
}
impl<'de> serde::Deserialize<'de> for PodDisruptionBudgetSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_max_unavailable,
Key_min_available,
Key_selector,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"maxUnavailable" => Field::Key_max_unavailable,
"minAvailable" => Field::Key_min_available,
"selector" => Field::Key_selector,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = PodDisruptionBudgetSpec;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "struct PodDisruptionBudgetSpec")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_max_unavailable: Option<crate::v1_14::apimachinery::pkg::util::intstr::IntOrString> = None;
let mut value_min_available: Option<crate::v1_14::apimachinery::pkg::util::intstr::IntOrString> = None;
let mut value_selector: Option<crate::v1_14::apimachinery::pkg::apis::meta::v1::LabelSelector> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_max_unavailable => value_max_unavailable = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_min_available => value_min_available = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_selector => value_selector = serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(PodDisruptionBudgetSpec {
max_unavailable: value_max_unavailable,
min_available: value_min_available,
selector: value_selector,
})
}
}
deserializer.deserialize_struct(
"PodDisruptionBudgetSpec",
&[
"maxUnavailable",
"minAvailable",
"selector",
],
Visitor,
)
}
}
impl serde::Serialize for PodDisruptionBudgetSpec {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"PodDisruptionBudgetSpec",
self.max_unavailable.as_ref().map_or(0, |_| 1) +
self.min_available.as_ref().map_or(0, |_| 1) +
self.selector.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.max_unavailable {
serde::ser::SerializeStruct::serialize_field(&mut state, "maxUnavailable", value)?;
}
if let Some(value) = &self.min_available {
serde::ser::SerializeStruct::serialize_field(&mut state, "minAvailable", value)?;
}
if let Some(value) = &self.selector {
serde::ser::SerializeStruct::serialize_field(&mut state, "selector", value)?;
}
serde::ser::SerializeStruct::end(state)
}
}
| 47 | 291 | 0.578201 |
fce3167dbfb5f60b1384f7b052b9f6ae6a1586b6 | 2,271 | use gdal::{
vector::{Defn, Feature, FieldDefn, OGRFieldType, ToGdal},
Dataset, Driver,
};
use h3ron::{Index, ToPolygon};
use h3ron_ndarray::{AxisOrder, H3Converter, ResolutionSearchMode::SmallerThanPixel, Transform};
fn main() {
env_logger::init(); // run with the environment variable RUST_LOG set to "debug" for log output
let filename = format!("{}/../data/r.tiff", env!("CARGO_MANIFEST_DIR"));
let dataset = Dataset::open((&filename).as_ref()).unwrap();
let transform = Transform::from_gdal(&dataset.geo_transform().unwrap());
let band = dataset.rasterband(1).unwrap();
let band_array = band
.read_as_array::<u8>((0, 0), band.size(), band.size(), None)
.unwrap();
let view = band_array.view();
let conv = H3Converter::new(&view, &Some(0_u8), &transform, AxisOrder::YX);
let h3_resolution = conv.nearest_h3_resolution(SmallerThanPixel).unwrap();
println!("selected H3 resolution: {}", h3_resolution);
let results = conv.to_h3(h3_resolution, true).unwrap();
results.iter().for_each(|(value, index_stack)| {
println!("{} -> {}", value, index_stack.len());
});
// write to vector file
let out_drv = Driver::get("GPKG").unwrap();
let mut out_dataset = out_drv
.create_vector_only("h3ify_r_tiff_results.gpkg")
.unwrap();
let out_lyr = out_dataset.create_layer(Default::default()).unwrap();
let h3index_field_defn = FieldDefn::new("h3index", OGRFieldType::OFTString).unwrap();
h3index_field_defn.set_width(20);
h3index_field_defn.add_to_layer(&out_lyr).unwrap();
let h3res_field_defn = FieldDefn::new("h3res", OGRFieldType::OFTInteger).unwrap();
h3res_field_defn.add_to_layer(&out_lyr).unwrap();
let defn = Defn::from_layer(&out_lyr);
results.iter().for_each(|(_value, index_stack)| {
for cell in index_stack.iter_compacted_cells() {
let mut ft = Feature::new(&defn).unwrap();
ft.set_geometry(cell.to_polygon().to_gdal().unwrap())
.unwrap();
ft.set_field_string("h3index", &cell.to_string()).unwrap();
ft.set_field_integer("h3res", cell.resolution() as i32)
.unwrap();
ft.create(&out_lyr).unwrap();
}
});
}
| 38.491525 | 99 | 0.646852 |
21a18662ca61fbe12cccd45414107be6fcf2985f | 749 | use {
super::{error::ValueError, Value},
crate::result::{Error, Result},
sqlparser::ast::Value as AstValue,
std::convert::TryFrom,
};
impl<'a> TryFrom<&'a AstValue> for Value {
type Error = Error;
fn try_from(ast_value: &'a AstValue) -> Result<Self> {
match ast_value {
AstValue::Boolean(value) => Ok(Value::Bool(value.clone())),
AstValue::Number(value, false) => value
.parse::<i64>()
.map_or_else(
|_| value.parse::<f64>().map(Value::F64),
|value| Ok(Value::I64(value)),
)
.map_err(|_| ValueError::FailedToParseNumber.into()),
AstValue::SingleQuotedString(value) => Ok(Value::Str(value.clone())),
AstValue::Null => Ok(Value::Null),
_ => Err(ValueError::UnimplementedLiteralType.into()),
}
}
}
| 27.740741 | 72 | 0.640854 |
0914994d1df6902c9852c63e9f37ac241b5d1770 | 6,150 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use crate::Converter;
use glib::object::Cast;
use glib::object::ObjectType as ObjectType_;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use std::ptr;
glib::wrapper! {
pub struct CharsetConverter(Object<ffi::GCharsetConverter, ffi::GCharsetConverterClass>) @implements Converter;
match fn {
type_ => || ffi::g_charset_converter_get_type(),
}
}
impl CharsetConverter {
#[doc(alias = "g_charset_converter_new")]
pub fn new(to_charset: &str, from_charset: &str) -> Result<CharsetConverter, glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_charset_converter_new(
to_charset.to_glib_none().0,
from_charset.to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(from_glib_full(ret))
} else {
Err(from_glib_full(error))
}
}
}
// rustdoc-stripper-ignore-next
/// Creates a new builder-style object to construct a [`CharsetConverter`]
/// This method returns an instance of [`CharsetConverterBuilder`] which can be used to create a [`CharsetConverter`].
pub fn builder() -> CharsetConverterBuilder {
CharsetConverterBuilder::default()
}
#[doc(alias = "g_charset_converter_get_num_fallbacks")]
#[doc(alias = "get_num_fallbacks")]
pub fn num_fallbacks(&self) -> u32 {
unsafe { ffi::g_charset_converter_get_num_fallbacks(self.to_glib_none().0) }
}
#[doc(alias = "g_charset_converter_get_use_fallback")]
#[doc(alias = "get_use_fallback")]
pub fn uses_fallback(&self) -> bool {
unsafe {
from_glib(ffi::g_charset_converter_get_use_fallback(
self.to_glib_none().0,
))
}
}
#[doc(alias = "g_charset_converter_set_use_fallback")]
pub fn set_use_fallback(&self, use_fallback: bool) {
unsafe {
ffi::g_charset_converter_set_use_fallback(
self.to_glib_none().0,
use_fallback.into_glib(),
);
}
}
#[doc(alias = "from-charset")]
pub fn from_charset(&self) -> Option<glib::GString> {
unsafe {
let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type());
glib::gobject_ffi::g_object_get_property(
self.as_ptr() as *mut glib::gobject_ffi::GObject,
b"from-charset\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `from-charset` getter")
}
}
#[doc(alias = "to-charset")]
pub fn to_charset(&self) -> Option<glib::GString> {
unsafe {
let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type());
glib::gobject_ffi::g_object_get_property(
self.as_ptr() as *mut glib::gobject_ffi::GObject,
b"to-charset\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `to-charset` getter")
}
}
#[doc(alias = "use-fallback")]
pub fn connect_use_fallback_notify<F: Fn(&CharsetConverter) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_use_fallback_trampoline<F: Fn(&CharsetConverter) + 'static>(
this: *mut ffi::GCharsetConverter,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::use-fallback\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_use_fallback_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
#[derive(Clone, Default)]
// rustdoc-stripper-ignore-next
/// A builder for generating a [`CharsetConverter`].
pub struct CharsetConverterBuilder {
from_charset: Option<String>,
to_charset: Option<String>,
use_fallback: Option<bool>,
}
impl CharsetConverterBuilder {
// rustdoc-stripper-ignore-next
/// Create a new [`CharsetConverterBuilder`].
pub fn new() -> Self {
Self::default()
}
// rustdoc-stripper-ignore-next
/// Build the [`CharsetConverter`].
pub fn build(self) -> CharsetConverter {
let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
if let Some(ref from_charset) = self.from_charset {
properties.push(("from-charset", from_charset));
}
if let Some(ref to_charset) = self.to_charset {
properties.push(("to-charset", to_charset));
}
if let Some(ref use_fallback) = self.use_fallback {
properties.push(("use-fallback", use_fallback));
}
glib::Object::new::<CharsetConverter>(&properties)
.expect("Failed to create an instance of CharsetConverter")
}
pub fn from_charset(mut self, from_charset: &str) -> Self {
self.from_charset = Some(from_charset.to_string());
self
}
pub fn to_charset(mut self, to_charset: &str) -> Self {
self.to_charset = Some(to_charset.to_string());
self
}
pub fn use_fallback(mut self, use_fallback: bool) -> Self {
self.use_fallback = Some(use_fallback);
self
}
}
impl fmt::Display for CharsetConverter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("CharsetConverter")
}
}
| 32.712766 | 122 | 0.580976 |
fc64d600825076b46f76880f43a3bc8a77430715 | 21,839 | // Copyright (c) 2017-present PyO3 Project and Contributors
use crate::panic::PanicException;
use crate::type_object::PyTypeObject;
use crate::types::PyType;
use crate::{
exceptions::{self, PyBaseException},
ffi,
};
use crate::{
AsPyPointer, FromPyPointer, IntoPy, Py, PyAny, PyNativeType, PyObject, Python,
ToBorrowedObject, ToPyObject,
};
use std::borrow::Cow;
use std::cell::UnsafeCell;
use std::ffi::CString;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::ptr::NonNull;
mod err_state;
mod impls;
pub use err_state::PyErrArguments;
use err_state::{boxed_args, PyErrState, PyErrStateNormalized};
/// Represents a Python exception that was raised.
pub struct PyErr {
// Safety: can only hand out references when in the "normalized" state. Will never change
// after normalization.
//
// The state is temporarily removed from the PyErr during normalization, to avoid
// concurrent modifications.
state: UnsafeCell<Option<PyErrState>>,
}
unsafe impl Send for PyErr {}
unsafe impl Sync for PyErr {}
/// Represents the result of a Python call.
pub type PyResult<T> = Result<T, PyErr>;
/// Error that indicates a failure to convert a PyAny to a more specific Python type.
#[derive(Debug)]
pub struct PyDowncastError<'a> {
from: &'a PyAny,
to: Cow<'static, str>,
}
impl<'a> PyDowncastError<'a> {
pub fn new(from: &'a PyAny, to: impl Into<Cow<'static, str>>) -> Self {
PyDowncastError {
from,
to: to.into(),
}
}
}
impl PyErr {
/// Creates a new PyErr of type `T`.
///
/// `value` can be:
/// * a tuple: the exception instance will be created using Python `T(*tuple)`
/// * any other value: the exception instance will be created using Python `T(value)`
///
/// Note: if `value` is not `Send` or `Sync`, consider using `PyErr::from_instance` instead.
///
/// Panics if `T` is not a Python class derived from `BaseException`.
///
/// Example:
/// ```ignore
/// return Err(PyErr::new::<exceptions::PyTypeError, _>("Error message"));
/// ```
///
/// In most cases, you can use a concrete exception's constructor instead, which is equivalent:
/// ```ignore
/// return Err(exceptions::PyTypeError::new_err("Error message"));
/// ```
pub fn new<T, A>(args: A) -> PyErr
where
T: PyTypeObject,
A: PyErrArguments + Send + Sync + 'static,
{
Python::with_gil(|py| PyErr::from_type(T::type_object(py), args))
}
/// Constructs a new error, with the usual lazy initialization of Python exceptions.
///
/// `exc` is the exception type; usually one of the standard exceptions
/// like `exceptions::PyRuntimeError`.
/// `args` is the a tuple of arguments to pass to the exception constructor.
pub fn from_type<A>(ty: &PyType, args: A) -> PyErr
where
A: PyErrArguments + Send + Sync + 'static,
{
if unsafe { ffi::PyExceptionClass_Check(ty.as_ptr()) } == 0 {
return exceptions_must_derive_from_base_exception(ty.py());
}
PyErr::from_state(PyErrState::Lazy {
ptype: ty.into(),
pvalue: boxed_args(args),
})
}
/// Creates a new PyErr.
///
/// `obj` must be an Python exception instance, the PyErr will use that instance.
/// If `obj` is a Python exception type object, the PyErr will (lazily) create a new
/// instance of that type.
/// Otherwise, a `TypeError` is created instead.
///
/// # Example
/// ```rust
/// use pyo3::{Python, PyErr, IntoPy, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// // Case #1: Exception instance
/// let err = PyErr::from_instance(PyTypeError::new_err("some type error",).instance(py));
/// assert_eq!(err.to_string(), "TypeError: some type error");
///
/// // Case #2: Exception type
/// let err = PyErr::from_instance(PyType::new::<PyTypeError>(py));
/// assert_eq!(err.to_string(), "TypeError: ");
///
/// // Case #3: Invalid exception value
/// let err = PyErr::from_instance("foo".into_py(py).as_ref(py));
/// assert_eq!(err.to_string(), "TypeError: exceptions must derive from BaseException");
/// });
/// ```
pub fn from_instance(obj: &PyAny) -> PyErr {
let ptr = obj.as_ptr();
let state = if unsafe { ffi::PyExceptionInstance_Check(ptr) } != 0 {
PyErrState::Normalized(PyErrStateNormalized {
ptype: unsafe {
Py::from_borrowed_ptr(obj.py(), ffi::PyExceptionInstance_Class(ptr))
},
pvalue: unsafe { Py::from_borrowed_ptr(obj.py(), obj.as_ptr()) },
ptraceback: None,
})
} else if unsafe { ffi::PyExceptionClass_Check(obj.as_ptr()) } != 0 {
PyErrState::FfiTuple {
ptype: unsafe { Some(Py::from_borrowed_ptr(obj.py(), ptr)) },
pvalue: None,
ptraceback: None,
}
} else {
return exceptions_must_derive_from_base_exception(obj.py());
};
PyErr::from_state(state)
}
/// Get the type of this exception object.
///
/// The object will be normalized first if needed.
///
/// # Example
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::new_err(("some type error",));
/// assert_eq!(err.ptype(py), PyType::new::<PyTypeError>(py));
/// });
/// ```
pub fn ptype<'py>(&'py self, py: Python<'py>) -> &'py PyType {
self.normalized(py).ptype.as_ref(py)
}
/// Get the value of this exception object.
///
/// The object will be normalized first if needed.
///
/// # Example
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::new_err(("some type error",));
/// assert!(err.is_instance::<PyTypeError>(py));
/// assert_eq!(err.pvalue(py).to_string(), "some type error");
/// });
/// ```
pub fn pvalue<'py>(&'py self, py: Python<'py>) -> &'py PyBaseException {
self.normalized(py).pvalue.as_ref(py)
}
/// Get the value of this exception object.
///
/// The object will be normalized first if needed.
///
/// # Example
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::new_err(("some type error",));
/// assert_eq!(err.ptraceback(py), None);
/// });
/// ```
pub fn ptraceback<'py>(&'py self, py: Python<'py>) -> Option<&'py PyAny> {
self.normalized(py)
.ptraceback
.as_ref()
.map(|obj| obj.as_ref(py))
}
/// Gets whether an error is present in the Python interpreter's global state.
#[inline]
pub fn occurred(_: Python) -> bool {
unsafe { !ffi::PyErr_Occurred().is_null() }
}
/// Retrieves the current error from the Python interpreter's global state.
///
/// The error is cleared from the Python interpreter.
/// If no error is set, returns a `SystemError`.
///
/// If the error fetched is a `PanicException` (which would have originated from a panic in a
/// pyo3 callback) then this function will resume the panic.
pub fn fetch(py: Python) -> PyErr {
unsafe {
let mut ptype: *mut ffi::PyObject = std::ptr::null_mut();
let mut pvalue: *mut ffi::PyObject = std::ptr::null_mut();
let mut ptraceback: *mut ffi::PyObject = std::ptr::null_mut();
ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback);
let err = PyErr::new_from_ffi_tuple(py, ptype, pvalue, ptraceback);
if ptype == PanicException::type_object(py).as_ptr() {
let msg: String = PyAny::from_borrowed_ptr_or_opt(py, pvalue)
.and_then(|obj| obj.extract().ok())
.unwrap_or_else(|| String::from("Unwrapped panic from Python code"));
eprintln!(
"--- PyO3 is resuming a panic after fetching a PanicException from Python. ---"
);
eprintln!("Python stack trace below:");
err.print(py);
std::panic::resume_unwind(Box::new(msg))
}
err
}
}
/// Creates a new exception type with the given name, which must be of the form
/// `<module>.<ExceptionName>`, as required by `PyErr_NewException`.
///
/// `base` can be an existing exception type to subclass, or a tuple of classes
/// `dict` specifies an optional dictionary of class variables and methods
pub fn new_type<'p>(
_: Python<'p>,
name: &str,
base: Option<&PyType>,
dict: Option<PyObject>,
) -> NonNull<ffi::PyTypeObject> {
let base: *mut ffi::PyObject = match base {
None => std::ptr::null_mut(),
Some(obj) => obj.as_ptr(),
};
let dict: *mut ffi::PyObject = match dict {
None => std::ptr::null_mut(),
Some(obj) => obj.as_ptr(),
};
unsafe {
let null_terminated_name =
CString::new(name).expect("Failed to initialize nul terminated exception name");
NonNull::new_unchecked(ffi::PyErr_NewException(
null_terminated_name.as_ptr() as *mut c_char,
base,
dict,
) as *mut ffi::PyTypeObject)
}
}
/// Create a PyErr from an ffi tuple
///
/// # Safety
/// - `ptype` must be a pointer to valid Python exception type object.
/// - `pvalue` must be a pointer to a valid Python object, or NULL.
/// - `ptraceback` must be a pointer to a valid Python traceback object, or NULL.
unsafe fn new_from_ffi_tuple(
py: Python,
ptype: *mut ffi::PyObject,
pvalue: *mut ffi::PyObject,
ptraceback: *mut ffi::PyObject,
) -> PyErr {
// Note: must not panic to ensure all owned pointers get acquired correctly,
// and because we mustn't panic in normalize().
PyErr::from_state(PyErrState::FfiTuple {
ptype: Py::from_owned_ptr_or_opt(py, ptype),
pvalue: Py::from_owned_ptr_or_opt(py, pvalue),
ptraceback: Py::from_owned_ptr_or_opt(py, ptraceback),
})
}
/// Prints a standard traceback to `sys.stderr`.
pub fn print(&self, py: Python) {
self.clone_ref(py).restore(py);
unsafe { ffi::PyErr_PrintEx(0) }
}
/// Prints a standard traceback to `sys.stderr`, and sets
/// `sys.last_{type,value,traceback}` attributes to this exception's data.
pub fn print_and_set_sys_last_vars(&self, py: Python) {
self.clone_ref(py).restore(py);
unsafe { ffi::PyErr_PrintEx(1) }
}
/// Returns true if the current exception matches the exception in `exc`.
///
/// If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass.
/// If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match.
pub fn matches<T>(&self, py: Python, exc: T) -> bool
where
T: ToBorrowedObject,
{
exc.with_borrowed_ptr(py, |exc| unsafe {
ffi::PyErr_GivenExceptionMatches(self.ptype_ptr(), exc) != 0
})
}
/// Returns true if the current exception is instance of `T`.
pub fn is_instance<T>(&self, py: Python) -> bool
where
T: PyTypeObject,
{
unsafe {
ffi::PyErr_GivenExceptionMatches(self.ptype_ptr(), T::type_object(py).as_ptr()) != 0
}
}
/// Retrieves the exception instance for this error.
pub fn instance<'py>(&'py self, py: Python<'py>) -> &'py PyBaseException {
self.normalized(py).pvalue.as_ref(py)
}
/// Consumes self to take ownership of the exception instance for this error.
pub fn into_instance(self, py: Python) -> Py<PyBaseException> {
let out = self.normalized(py).pvalue.as_ref(py).into();
std::mem::forget(self);
out
}
/// Writes the error back to the Python interpreter's global state.
/// This is the opposite of `PyErr::fetch()`.
#[inline]
pub fn restore(self, py: Python) {
let (ptype, pvalue, ptraceback) = self
.state
.into_inner()
.expect("Cannot restore a PyErr while normalizing it")
.into_ffi_tuple(py);
unsafe { ffi::PyErr_Restore(ptype, pvalue, ptraceback) }
}
/// Issues a warning message.
/// May return a `PyErr` if warnings-as-errors is enabled.
pub fn warn(py: Python, category: &PyAny, message: &str, stacklevel: i32) -> PyResult<()> {
let message = CString::new(message)?;
unsafe {
error_on_minusone(
py,
ffi::PyErr_WarnEx(
category.as_ptr(),
message.as_ptr(),
stacklevel as ffi::Py_ssize_t,
),
)
}
}
/// Clone the PyErr. This requires the GIL, which is why PyErr does not implement Clone.
///
/// # Example
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::new_err(("some type error",));
/// let err_clone = err.clone_ref(py);
/// assert_eq!(err.ptype(py), err_clone.ptype(py));
/// assert_eq!(err.pvalue(py), err_clone.pvalue(py));
/// assert_eq!(err.ptraceback(py), err_clone.ptraceback(py));
/// });
/// ```
pub fn clone_ref(&self, py: Python) -> PyErr {
PyErr::from_state(PyErrState::Normalized(self.normalized(py).clone()))
}
fn from_state(state: PyErrState) -> PyErr {
PyErr {
state: UnsafeCell::new(Some(state)),
}
}
/// Returns borrowed reference to this Err's type
fn ptype_ptr(&self) -> *mut ffi::PyObject {
match unsafe { &*self.state.get() } {
Some(PyErrState::Lazy { ptype, .. }) => ptype.as_ptr(),
Some(PyErrState::FfiTuple { ptype, .. }) => ptype.as_ptr(),
Some(PyErrState::Normalized(n)) => n.ptype.as_ptr(),
None => panic!("Cannot access exception type while normalizing"),
}
}
fn normalized(&self, py: Python) -> &PyErrStateNormalized {
// This process is safe because:
// - Access is guaranteed not to be concurrent thanks to `Python` GIL token
// - Write happens only once, and then never will change again.
// - State is set to None during the normalization process, so that a second
// concurrent normalization attempt will panic before changing anything.
if let Some(PyErrState::Normalized(n)) = unsafe { &*self.state.get() } {
return n;
}
let state = unsafe {
(*self.state.get())
.take()
.expect("Cannot normalize a PyErr while already normalizing it.")
};
let (mut ptype, mut pvalue, mut ptraceback) = state.into_ffi_tuple(py);
unsafe {
ffi::PyErr_NormalizeException(&mut ptype, &mut pvalue, &mut ptraceback);
let self_state = &mut *self.state.get();
*self_state = Some(PyErrState::Normalized(PyErrStateNormalized {
ptype: Py::from_owned_ptr_or_opt(py, ptype)
.unwrap_or_else(|| exceptions::PySystemError::type_object(py).into()),
pvalue: Py::from_owned_ptr_or_opt(py, pvalue).unwrap_or_else(|| {
exceptions::PySystemError::new_err("Exception value missing")
.instance(py)
.into_py(py)
}),
ptraceback: PyObject::from_owned_ptr_or_opt(py, ptraceback),
}));
match self_state {
Some(PyErrState::Normalized(n)) => n,
_ => unreachable!(),
}
}
}
}
impl std::fmt::Debug for PyErr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
Python::with_gil(|py| {
f.debug_struct("PyErr")
.field("type", self.ptype(py))
.field("value", self.pvalue(py))
.field("traceback", &self.ptraceback(py))
.finish()
})
}
}
impl std::fmt::Display for PyErr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
Python::with_gil(|py| {
let instance = self.instance(py);
let type_name = instance.get_type().name().map_err(|_| std::fmt::Error)?;
write!(f, "{}", type_name)?;
if let Ok(s) = instance.str() {
write!(f, ": {}", &s.to_string_lossy())
} else {
write!(f, ": <exception str() failed>")
}
})
}
}
impl std::error::Error for PyErr {}
impl IntoPy<PyObject> for PyErr {
fn into_py(self, py: Python) -> PyObject {
self.into_instance(py).into()
}
}
impl ToPyObject for PyErr {
fn to_object(&self, py: Python) -> PyObject {
self.clone_ref(py).into_py(py)
}
}
impl<'a> IntoPy<PyObject> for &'a PyErr {
fn into_py(self, py: Python) -> PyObject {
self.clone_ref(py).into_py(py)
}
}
/// Convert `PyDowncastError` to Python `TypeError`.
impl<'a> std::convert::From<PyDowncastError<'a>> for PyErr {
fn from(err: PyDowncastError) -> PyErr {
exceptions::PyTypeError::new_err(err.to_string())
}
}
impl<'a> std::error::Error for PyDowncastError<'a> {}
impl<'a> std::fmt::Display for PyDowncastError<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"'{}' object cannot be converted to '{}'",
self.from.get_type().name().map_err(|_| std::fmt::Error)?,
self.to
)
}
}
pub fn panic_after_error(_py: Python) -> ! {
unsafe {
ffi::PyErr_Print();
}
panic!("Python API call failed");
}
/// Returns Ok if the error code is not -1.
#[inline]
pub fn error_on_minusone(py: Python, result: c_int) -> PyResult<()> {
if result != -1 {
Ok(())
} else {
Err(PyErr::fetch(py))
}
}
#[inline]
fn exceptions_must_derive_from_base_exception(py: Python) -> PyErr {
PyErr::from_state(PyErrState::Lazy {
ptype: exceptions::PyTypeError::type_object(py).into(),
pvalue: boxed_args("exceptions must derive from BaseException"),
})
}
#[cfg(test)]
mod tests {
use super::PyErrState;
use crate::exceptions;
use crate::{PyErr, Python};
#[test]
fn set_typeerror() {
let gil = Python::acquire_gil();
let py = gil.python();
let err: PyErr = exceptions::PyTypeError::new_err(());
err.restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
}
#[test]
#[should_panic(expected = "new panic")]
fn fetching_panic_exception_resumes_unwind() {
// TODO replace with #[cfg(panic = "unwind")] once stable
if !crate::cfg_panic_unwind() {
// panic to meet the expected abort in panic=abort :-/
panic!("new panic");
}
use crate::panic::PanicException;
let gil = Python::acquire_gil();
let py = gil.python();
let err: PyErr = PanicException::new_err("new panic");
err.restore(py);
assert!(PyErr::occurred(py));
// should resume unwind
let _ = PyErr::fetch(py);
}
#[test]
fn err_debug() {
// Debug representation should be like the following (without the newlines):
// PyErr {
// type: <class 'Exception'>,
// value: Exception('banana'),
// traceback: Some(<traceback object at 0x..)"
// }
let gil = Python::acquire_gil();
let py = gil.python();
let err = py
.run("raise Exception('banana')", None, None)
.expect_err("raising should have given us an error");
let debug_str = format!("{:?}", err);
assert!(debug_str.starts_with("PyErr { "));
assert!(debug_str.ends_with(" }"));
// strip "PyErr { " and " }"
let mut fields = debug_str["PyErr { ".len()..debug_str.len() - 2].split(", ");
assert_eq!(fields.next().unwrap(), "type: <class 'Exception'>");
if py.version_info() >= (3, 7) {
assert_eq!(fields.next().unwrap(), "value: Exception('banana')");
} else {
// Python 3.6 and below formats the repr differently
assert_eq!(fields.next().unwrap(), ("value: Exception('banana',)"));
}
let traceback = fields.next().unwrap();
assert!(traceback.starts_with("traceback: Some(<traceback object at 0x"));
assert!(traceback.ends_with(">)"));
assert!(fields.next().is_none());
}
#[test]
fn err_display() {
let gil = Python::acquire_gil();
let py = gil.python();
let err = py
.run("raise Exception('banana')", None, None)
.expect_err("raising should have given us an error");
assert_eq!(err.to_string(), "Exception: banana");
}
#[test]
fn test_pyerr_send_sync() {
fn is_send<T: Send>() {}
fn is_sync<T: Sync>() {}
is_send::<PyErr>();
is_sync::<PyErr>();
is_send::<PyErrState>();
is_sync::<PyErrState>();
}
}
| 34.284144 | 113 | 0.568799 |
d79f20f600e2cfea10f766c9f9d6d9263ad2288d | 6,605 | use std::fmt;
use std::str::FromStr;
use header::{Header, Raw};
use header::parsing::{from_comma_delimited, fmt_comma_delimited};
/// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2)
///
/// The `Cache-Control` header field is used to specify directives for
/// caches along the request/response chain. Such cache directives are
/// unidirectional in that the presence of a directive in a request does
/// not imply that the same directive is to be given in the response.
///
/// # ABNF
/// ```plain
/// Cache-Control = 1#cache-directive
/// cache-directive = token [ "=" ( token / quoted-string ) ]
/// ```
///
/// # Example values
/// * `no-cache`
/// * `private, community="UCI"`
/// * `max-age=30`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, CacheControl, CacheDirective};
///
/// let mut headers = Headers::new();
/// headers.set(
/// CacheControl(vec![CacheDirective::MaxAge(86400u32)])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, CacheControl, CacheDirective};
///
/// let mut headers = Headers::new();
/// headers.set(
/// CacheControl(vec![
/// CacheDirective::NoCache,
/// CacheDirective::Private,
/// CacheDirective::MaxAge(360u32),
/// CacheDirective::Extension("foo".to_owned(),
/// Some("bar".to_owned())),
/// ])
/// );
/// ```
#[derive(PartialEq, Clone, Debug)]
pub struct CacheControl(pub Vec<CacheDirective>);
__hyper__deref!(CacheControl => Vec<CacheDirective>);
impl Header for CacheControl {
fn header_name() -> &'static str {
static NAME: &'static str = "Cache-Control";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<CacheControl> {
let directives = try!(from_comma_delimited(raw));
if !directives.is_empty() {
Ok(CacheControl(directives))
} else {
Err(::Error::Header)
}
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_comma_delimited(f, &self[..])
}
}
/// `CacheControl` contains a list of these directives.
#[derive(PartialEq, Clone, Debug)]
pub enum CacheDirective {
/// "no-cache"
NoCache,
/// "no-store"
NoStore,
/// "no-transform"
NoTransform,
/// "only-if-cached"
OnlyIfCached,
// request directives
/// "max-age=delta"
MaxAge(u32),
/// "max-stale=delta"
MaxStale(u32),
/// "min-fresh=delta"
MinFresh(u32),
// response directives
/// "must-revalidate"
MustRevalidate,
/// "public"
Public,
/// "private"
Private,
/// "proxy-revalidate"
ProxyRevalidate,
/// "s-maxage=delta"
SMaxAge(u32),
/// Extension directives. Optionally include an argument.
Extension(String, Option<String>)
}
impl fmt::Display for CacheDirective {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::CacheDirective::*;
fmt::Display::fmt(match *self {
NoCache => "no-cache",
NoStore => "no-store",
NoTransform => "no-transform",
OnlyIfCached => "only-if-cached",
MaxAge(secs) => return write!(f, "max-age={}", secs),
MaxStale(secs) => return write!(f, "max-stale={}", secs),
MinFresh(secs) => return write!(f, "min-fresh={}", secs),
MustRevalidate => "must-revalidate",
Public => "public",
Private => "private",
ProxyRevalidate => "proxy-revalidate",
SMaxAge(secs) => return write!(f, "s-maxage={}", secs),
Extension(ref name, None) => &name[..],
Extension(ref name, Some(ref arg)) => return write!(f, "{}={}", name, arg),
}, f)
}
}
impl FromStr for CacheDirective {
type Err = Option<<u32 as FromStr>::Err>;
fn from_str(s: &str) -> Result<CacheDirective, Option<<u32 as FromStr>::Err>> {
use self::CacheDirective::*;
match s {
"no-cache" => Ok(NoCache),
"no-store" => Ok(NoStore),
"no-transform" => Ok(NoTransform),
"only-if-cached" => Ok(OnlyIfCached),
"must-revalidate" => Ok(MustRevalidate),
"public" => Ok(Public),
"private" => Ok(Private),
"proxy-revalidate" => Ok(ProxyRevalidate),
"" => Err(None),
_ => match s.find('=') {
Some(idx) if idx+1 < s.len() => match (&s[..idx], (&s[idx+1..]).trim_matches('"')) {
("max-age" , secs) => secs.parse().map(MaxAge).map_err(Some),
("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
(left, right) => Ok(Extension(left.to_owned(), Some(right.to_owned())))
},
Some(_) => Err(None),
None => Ok(Extension(s.to_owned(), None))
}
}
}
}
#[cfg(test)]
mod tests {
use header::Header;
use super::*;
#[test]
fn test_parse_multiple_headers() {
let cache = Header::parse_header(&vec![b"no-cache".to_vec(), b"private".to_vec()].into());
assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::NoCache,
CacheDirective::Private])))
}
#[test]
fn test_parse_argument() {
let cache = Header::parse_header(&vec![b"max-age=100, private".to_vec()].into());
assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(100),
CacheDirective::Private])))
}
#[test]
fn test_parse_quote_form() {
let cache = Header::parse_header(&vec![b"max-age=\"200\"".to_vec()].into());
assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(200)])))
}
#[test]
fn test_parse_extension() {
let cache = Header::parse_header(&vec![b"foo, bar=baz".to_vec()].into());
assert_eq!(cache.ok(), Some(CacheControl(vec![
CacheDirective::Extension("foo".to_owned(), None),
CacheDirective::Extension("bar".to_owned(), Some("baz".to_owned()))])))
}
#[test]
fn test_parse_bad_syntax() {
let cache: ::Result<CacheControl> = Header::parse_header(&vec![b"foo=".to_vec()].into());
assert_eq!(cache.ok(), None)
}
}
bench_header!(normal,
CacheControl, { vec![b"no-cache, private".to_vec(), b"max-age=100".to_vec()] });
| 32.219512 | 100 | 0.555488 |
1a5174e06016e49c95be52be5512c2a798417cd8 | 16,070 | //! Randomised property tests for MetaAddr.
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
env,
net::SocketAddr,
str::FromStr,
sync::Arc,
time::Duration,
};
use chrono::Utc;
use proptest::{collection::vec, prelude::*};
use tokio::time::Instant;
use tower::service_fn;
use tracing::Span;
use zebra_chain::serialization::DateTime32;
use crate::{
constants::{MAX_ADDRS_IN_ADDRESS_BOOK, MAX_RECENT_PEER_AGE, MIN_PEER_RECONNECTION_DELAY},
meta_addr::{
arbitrary::{MAX_ADDR_CHANGE, MAX_META_ADDR},
MetaAddr, MetaAddrChange,
PeerAddrState::*,
},
peer_set::candidate_set::CandidateSet,
protocol::{external::canonical_socket_addr, types::PeerServices},
AddressBook,
};
use super::check;
/// The number of test cases to use for proptest that have verbose failures.
///
/// Set this to the default number of proptest cases, unless you're debugging a
/// failure.
const DEFAULT_VERBOSE_TEST_PROPTEST_CASES: u32 = 256;
proptest! {
/// Make sure that the sanitize function reduces time and state metadata
/// leaks for valid addresses.
///
/// Make sure that the sanitize function skips invalid IP addresses, ports,
/// and client services.
#[test]
fn sanitize_avoids_leaks(addr in MetaAddr::arbitrary()) {
zebra_test::init();
if let Some(sanitized) = addr.sanitize() {
// check that all sanitized addresses are valid for outbound
prop_assert!(addr.last_known_info_is_valid_for_outbound());
// also check the address, port, and services individually
prop_assert!(!addr.addr.ip().is_unspecified());
prop_assert_ne!(addr.addr.port(), 0);
if let Some(services) = addr.services {
prop_assert!(services.contains(PeerServices::NODE_NETWORK));
}
check::sanitize_avoids_leaks(&addr, &sanitized);
}
}
/// Make sure that [`MetaAddrChange`]s:
/// - do not modify the last seen time, unless it was None, and
/// - only modify the services after a response or failure.
#[test]
fn preserve_initial_untrusted_values(
(mut addr, changes) in MetaAddrChange::addr_changes_strategy(MAX_ADDR_CHANGE),
) {
zebra_test::init();
for change in changes {
if let Some(changed_addr) = change.apply_to_meta_addr(addr) {
// untrusted last seen times:
// check that we replace None with Some, but leave Some unchanged
if addr.untrusted_last_seen.is_some() {
prop_assert_eq!(changed_addr.untrusted_last_seen, addr.untrusted_last_seen);
} else {
prop_assert_eq!(
changed_addr.untrusted_last_seen,
change.untrusted_last_seen()
);
}
// services:
// check that we only change if there was a handshake
if addr.services.is_some()
&& (changed_addr.last_connection_state.is_never_attempted()
|| changed_addr.last_connection_state == AttemptPending
|| change.untrusted_services().is_none())
{
prop_assert_eq!(changed_addr.services, addr.services);
}
addr = changed_addr;
}
}
}
/// Make sure that [`MetaAddr`]s do not get retried more than once per
/// [`MIN_PEER_RECONNECTION_DELAY`], regardless of the [`MetaAddrChange`]s that are
/// applied to them.
///
/// This is the simple version of the test, which checks [`MetaAddr`]s by
/// themselves. It detects bugs in [`MetaAddr`]s, even if there are
/// compensating bugs in the [`CandidateSet`] or [`AddressBook`].
#[test]
fn individual_peer_retry_limit_meta_addr(
(mut addr, changes) in MetaAddrChange::addr_changes_strategy(MAX_ADDR_CHANGE)
) {
zebra_test::init();
let instant_now = std::time::Instant::now();
let chrono_now = Utc::now();
let mut attempt_count: usize = 0;
for change in changes {
while addr.is_ready_for_connection_attempt(instant_now, chrono_now) {
attempt_count += 1;
// Assume that this test doesn't last longer than MIN_PEER_RECONNECTION_DELAY
prop_assert!(attempt_count <= 1);
// Simulate an attempt
addr = MetaAddr::new_reconnect(&addr.addr)
.apply_to_meta_addr(addr)
.expect("unexpected invalid attempt");
}
// If `change` is invalid for the current MetaAddr state, skip it.
if let Some(changed_addr) = change.apply_to_meta_addr(addr) {
prop_assert_eq!(changed_addr.addr, addr.addr);
addr = changed_addr;
}
}
}
/// Make sure that a sanitized [`AddressBook`] contains the local listener
/// [`MetaAddr`], regardless of the previous contents of the address book.
///
/// If Zebra gossips its own listener address to peers, and gets it back,
/// its address book will contain its local listener address. This address
/// will likely be in [`PeerAddrState::Failed`], due to failed
/// self-connection attempts.
#[test]
fn sanitized_address_book_contains_local_listener(
local_listener in any::<SocketAddr>(),
address_book_addrs in vec(any::<MetaAddr>(), 0..MAX_META_ADDR),
) {
zebra_test::init();
let chrono_now = Utc::now();
let address_book = AddressBook::new_with_addrs(
local_listener,
MAX_ADDRS_IN_ADDRESS_BOOK,
Span::none(),
address_book_addrs
);
let sanitized_addrs = address_book.sanitized(chrono_now);
let expected_local_listener = address_book.local_listener_meta_addr();
let canonical_local_listener = canonical_socket_addr(local_listener);
let book_sanitized_local_listener = sanitized_addrs
.iter()
.find(|meta_addr| meta_addr.addr == canonical_local_listener);
// invalid addresses should be removed by sanitization,
// regardless of where they have come from
prop_assert_eq!(
book_sanitized_local_listener.cloned(),
expected_local_listener.sanitize(),
"address book: {:?}, sanitized_addrs: {:?}, canonical_local_listener: {:?}",
address_book,
sanitized_addrs,
canonical_local_listener,
);
}
}
proptest! {
// These tests can produce a lot of debug output, so we use a smaller number of cases by default.
// Set the PROPTEST_CASES env var to override this default.
#![proptest_config(proptest::test_runner::Config::with_cases(env::var("PROPTEST_CASES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(DEFAULT_VERBOSE_TEST_PROPTEST_CASES)))]
/// Make sure that [`MetaAddr`]s do not get retried more than once per
/// [`MIN_PEER_RECONNECTION_DELAY`], regardless of the [`MetaAddrChange`]s that are
/// applied to a single peer's entries in the [`AddressBook`].
///
/// This is the complex version of the test, which checks [`MetaAddr`],
/// [`CandidateSet`] and [`AddressBook`] together.
#[test]
fn individual_peer_retry_limit_candidate_set(
(addr, changes) in MetaAddrChange::addr_changes_strategy(MAX_ADDR_CHANGE)
) {
let runtime = zebra_test::init_async();
let _guard = runtime.enter();
// Run the test for this many simulated live peer durations
const LIVE_PEER_INTERVALS: u32 = 3;
// Run the test for this much simulated time
let overall_test_time: Duration = MIN_PEER_RECONNECTION_DELAY * LIVE_PEER_INTERVALS;
// Advance the clock by this much for every peer change
let peer_change_interval: Duration =
overall_test_time / MAX_ADDR_CHANGE.try_into().unwrap();
prop_assert!(
u32::try_from(MAX_ADDR_CHANGE).unwrap() >= 3 * LIVE_PEER_INTERVALS,
"there are enough changes for good test coverage",
);
// Only put valid addresses in the address book.
// This means some tests will start with an empty address book.
let addrs = if addr.last_known_info_is_valid_for_outbound() {
Some(addr)
} else {
None
};
let address_book = Arc::new(std::sync::Mutex::new(AddressBook::new_with_addrs(
SocketAddr::from_str("0.0.0.0:0").unwrap(),
MAX_ADDRS_IN_ADDRESS_BOOK,
Span::none(),
addrs,
)));
let peer_service = service_fn(|_| async { unreachable!("Service should not be called") });
let mut candidate_set = CandidateSet::new(address_book.clone(), peer_service);
runtime.block_on(async move {
tokio::time::pause();
// The earliest time we can have a valid next attempt for this peer
let earliest_next_attempt = Instant::now() + MIN_PEER_RECONNECTION_DELAY;
// The number of attempts for this peer in the last MIN_PEER_RECONNECTION_DELAY
let mut attempt_count: usize = 0;
for (i, change) in changes.into_iter().enumerate() {
while let Some(candidate_addr) = candidate_set.next().await {
prop_assert_eq!(candidate_addr.addr, addr.addr);
attempt_count += 1;
prop_assert!(
attempt_count <= 1,
"candidate: {:?},\n \
change: {},\n \
now: {:?},\n \
earliest next attempt: {:?},\n \
attempts: {}, live peer interval limit: {},\n \
test time limit: {:?}, peer change interval: {:?},\n \
original addr was in address book: {}\n",
candidate_addr,
i,
Instant::now(),
earliest_next_attempt,
attempt_count,
LIVE_PEER_INTERVALS,
overall_test_time,
peer_change_interval,
addr.last_known_info_is_valid_for_outbound(),
);
}
// If `change` is invalid for the current MetaAddr state,
// multiple intervals will elapse between actual changes to
// the MetaAddr in the AddressBook.
address_book.clone().lock().unwrap().update(change);
tokio::time::advance(peer_change_interval).await;
if Instant::now() >= earliest_next_attempt {
attempt_count = 0;
}
}
Ok(())
})?;
}
/// Make sure that all disconnected [`MetaAddr`]s are retried once, before
/// any are retried twice.
///
/// This is the simple version of the test, which checks [`MetaAddr`]s by
/// themselves. It detects bugs in [`MetaAddr`]s, even if there are
/// compensating bugs in the [`CandidateSet`] or [`AddressBook`].
//
// TODO: write a similar test using the AddressBook and CandidateSet
#[test]
fn multiple_peer_retry_order_meta_addr(
addr_changes_lists in vec(
MetaAddrChange::addr_changes_strategy(MAX_ADDR_CHANGE),
2..MAX_ADDR_CHANGE
),
) {
let runtime = zebra_test::init_async();
let _guard = runtime.enter();
let instant_now = std::time::Instant::now();
let chrono_now = Utc::now();
// Run the test for this many simulated live peer durations
const LIVE_PEER_INTERVALS: u32 = 3;
// Run the test for this much simulated time
let overall_test_time: Duration = MIN_PEER_RECONNECTION_DELAY * LIVE_PEER_INTERVALS;
// Advance the clock by this much for every peer change
let peer_change_interval: Duration =
overall_test_time / MAX_ADDR_CHANGE.try_into().unwrap();
prop_assert!(
u32::try_from(MAX_ADDR_CHANGE).unwrap() >= 3 * LIVE_PEER_INTERVALS,
"there are enough changes for good test coverage",
);
let attempt_counts = runtime.block_on(async move {
tokio::time::pause();
// The current attempt counts for each peer in this interval
let mut attempt_counts: HashMap<SocketAddr, u32> = HashMap::new();
// The most recent address info for each peer
let mut addrs: HashMap<SocketAddr, MetaAddr> = HashMap::new();
for change_index in 0..MAX_ADDR_CHANGE {
for (addr, changes) in addr_changes_lists.iter() {
let addr = addrs.entry(addr.addr).or_insert(*addr);
let change = changes.get(change_index);
while addr.is_ready_for_connection_attempt(instant_now, chrono_now) {
*attempt_counts.entry(addr.addr).or_default() += 1;
prop_assert!(
*attempt_counts.get(&addr.addr).unwrap() <= LIVE_PEER_INTERVALS + 1
);
// Simulate an attempt
*addr = MetaAddr::new_reconnect(&addr.addr)
.apply_to_meta_addr(*addr)
.expect("unexpected invalid attempt");
}
// If `change` is invalid for the current MetaAddr state, skip it.
// If we've run out of changes for this addr, do nothing.
if let Some(changed_addr) = change.and_then(|change| change.apply_to_meta_addr(*addr))
{
prop_assert_eq!(changed_addr.addr, addr.addr);
*addr = changed_addr;
}
}
tokio::time::advance(peer_change_interval).await;
}
Ok(attempt_counts)
})?;
let min_attempts = attempt_counts.values().min();
let max_attempts = attempt_counts.values().max();
if let (Some(&min_attempts), Some(&max_attempts)) = (min_attempts, max_attempts) {
prop_assert!(max_attempts >= min_attempts);
prop_assert!(max_attempts - min_attempts <= 1);
}
}
/// Make sure check if a peer was recently seen is correct.
#[test]
fn last_seen_is_recent_is_correct(peer in any::<MetaAddr>()) {
let chrono_now = Utc::now();
let time_since_last_seen = peer
.last_seen()
.map(|last_seen| last_seen.saturating_elapsed(chrono_now));
let recently_seen = time_since_last_seen
.map(|elapsed| elapsed <= MAX_RECENT_PEER_AGE)
.unwrap_or(false);
prop_assert_eq!(
peer.last_seen_is_recent(chrono_now),
recently_seen,
"last seen: {:?}, now: {:?}",
peer.last_seen(),
DateTime32::now(),
);
}
/// Make sure a peer is correctly determined to be probably reachable.
#[test]
fn probably_rechable_is_determined_correctly(peer in any::<MetaAddr>()) {
let chrono_now = Utc::now();
let last_attempt_failed = peer.last_connection_state == Failed;
let not_recently_seen = !peer.last_seen_is_recent(chrono_now);
let probably_unreachable = last_attempt_failed && not_recently_seen;
prop_assert_eq!(
peer.is_probably_reachable(chrono_now),
!probably_unreachable,
"last_connection_state: {:?}, last_seen: {:?}",
peer.last_connection_state,
peer.last_seen()
);
}
}
| 39.195122 | 106 | 0.583821 |
e87083d00080aeaa76b6879bbe96ec6d75531612 | 12,166 | use crate::Day;
#[derive(Debug, PartialOrd, PartialEq)]
pub struct Container {
row_len: u8,
seats: Vec<SeatRow>,
}
impl Container {
pub fn new() -> Self {
Self {
row_len: 0,
seats: Vec::new(),
}
}
fn adjacent(&self, row: usize, col: u8) -> usize {
let mut adjacent = 0;
if row > 0 {
let seat_row = &self.seats[row - 1];
if col > 0 && seat_row.is_occupied(col - 1) {
adjacent += 1;
}
if seat_row.is_occupied(col) {
adjacent += 1;
}
if col < self.row_len - 1 && seat_row.is_occupied(col + 1) {
adjacent += 1;
}
}
let seat_row = &self.seats[row];
if col > 0 && seat_row.is_occupied(col - 1) {
adjacent += 1;
}
if col < self.row_len - 1 && seat_row.is_occupied(col + 1) {
adjacent += 1;
}
if row < self.seats.len() - 1 {
let seat_row = &self.seats[row + 1];
if col > 0 && seat_row.is_occupied(col - 1) {
adjacent += 1;
}
if seat_row.is_occupied(col) {
adjacent += 1;
}
if col < self.row_len - 1 && seat_row.is_occupied(col + 1) {
adjacent += 1;
}
}
adjacent
}
fn visibly_adjacent(&self, row: usize, col: usize) -> usize {
let mut adjacent = 0;
if row > 0 {
// TL
for diff in 1..=row {
if diff > col {
break;
}
let col_idx = (col - diff) as u8;
let row_idx = row - diff;
if !self.seats[row_idx].is_floor(col_idx) {
if self.seats[row_idx].is_occupied(col_idx) {
adjacent += 1;
}
break;
}
}
// TC
for diff in 1..=row {
let row_idx = row - diff;
if !self.seats[row_idx].is_floor(col as u8) {
if self.seats[row_idx].is_occupied(col as u8) {
adjacent += 1;
}
break;
}
}
// TR
for diff in 1..=row {
if self.row_len as usize - diff <= col {
break;
}
let col_idx = (col + diff) as u8;
let row_idx = row - diff;
if !self.seats[row_idx].is_floor(col_idx) {
if self.seats[row_idx].is_occupied(col_idx) {
adjacent += 1;
}
break;
}
}
}
// ML
for diff in 1..=col {
let col_idx = (col - diff) as u8;
if !self.seats[row].is_floor(col_idx) {
if self.seats[row].is_occupied(col_idx) {
adjacent += 1;
}
break;
}
}
// MR
for diff in 1..=(self.row_len as usize - col) {
let col_idx = (col + diff) as u8;
if !self.seats[row].is_floor(col_idx) {
if self.seats[row].is_occupied(col_idx) {
adjacent += 1;
}
break;
}
}
// BL
for diff in 1..(self.seats.len() - row) {
if diff > col {
break;
}
let col_idx = (col - diff) as u8;
let row_idx = row + diff;
if !self.seats[row_idx].is_floor(col_idx) {
if self.seats[row_idx].is_occupied(col_idx) {
adjacent += 1;
}
break;
}
}
// BM
for diff in 1..(self.seats.len() - row) {
let row_idx = row + diff;
if !self.seats[row_idx].is_floor(col as u8) {
if self.seats[row_idx].is_occupied(col as u8) {
adjacent += 1;
}
break;
}
}
// BR
for diff in 1..(self.seats.len() - row) {
if self.row_len as usize - diff <= col {
break;
}
let col_idx = (col + diff) as u8;
let row_idx = row + diff;
if !self.seats[row_idx].is_floor(col_idx) {
if self.seats[row_idx].is_occupied(col_idx) {
adjacent += 1;
}
break;
}
}
adjacent
}
}
// u128 is sufficient as input data has len < 100
#[derive(Clone, Debug, PartialOrd, PartialEq)]
struct SeatRow {
floor: u128,
occupied: u128,
}
impl SeatRow {
fn is_floor(&self, idx: u8) -> bool {
self.floor & 1 << idx > 0
}
fn is_occupied(&self, idx: u8) -> bool {
self.occupied & 1 << idx > 0
}
// fn is_empty(&self, idx: u8) -> bool {
// (self.floor | self.occupied) & 1 << idx == 0
// }
}
impl Day for Container {
fn parse_input(&mut self, input: &str) -> Result<(), String> {
input.trim().lines().try_for_each(|line| {
self.row_len = line.len() as u8;
let row = line.trim().char_indices().try_fold(
SeatRow {
floor: 0,
occupied: 0,
},
|mut acc, (idx, chr)| {
match chr {
'L' => {}
'#' => {
acc.occupied |= 1 << idx;
}
'.' => {
acc.floor |= 1 << idx;
}
_ => {
return Err(format!("unsupported character: '{}'", chr));
}
};
Ok(acc)
},
);
match row {
Ok(r) => {
self.seats.push(r);
Ok(())
}
Err(e) => Err(e),
}
})
}
fn part_1(&self) -> Result<String, String> {
let mut seat_container = Container {
row_len: self.row_len,
seats: self.seats.clone(),
};
for _ in 0..100_000 {
let mut change_set = Vec::<(usize, bool, u128)>::with_capacity(self.row_len as usize);
seat_container
.seats
.iter()
.enumerate()
.for_each(|(idx, seat_row)| {
for i in 0..self.row_len {
if seat_row.is_floor(i as u8) {
continue;
}
let adjacent = seat_container.adjacent(idx, i);
let occupied = seat_row.is_occupied(i as u8);
if occupied && adjacent >= 4 {
change_set.push((idx, true, !(1u128 << i)));
} else if !occupied && adjacent == 0 {
change_set.push((idx, false, 1 << i));
}
}
});
if change_set.is_empty() {
return Ok(seat_container
.seats
.iter()
.fold(0u32, |mut acc, seat_row| {
acc += seat_row.occupied.count_ones();
acc
})
.to_string());
}
change_set.iter().for_each(|(idx, unset, change)| {
if *unset {
seat_container.seats[*idx].occupied &= change;
} else {
seat_container.seats[*idx].occupied |= change;
}
});
}
Err("failed to find stable state after 100,000 iterations".to_owned())
}
fn part_2(&self) -> Result<String, String> {
let mut seat_container = Container {
row_len: self.row_len,
seats: self.seats.clone(),
};
for _ in 0..100_000 {
let mut change_set = Vec::<(usize, bool, u128)>::with_capacity(self.row_len as usize);
seat_container
.seats
.iter()
.enumerate()
.for_each(|(idx, seat_row)| {
for i in 0..self.row_len {
if seat_row.is_floor(i as u8) {
continue;
}
let adjacent = seat_container.visibly_adjacent(idx, i as usize);
let occupied = seat_row.is_occupied(i as u8);
if occupied && adjacent >= 5 {
change_set.push((idx, true, !(1u128 << i)));
} else if !occupied && adjacent == 0 {
change_set.push((idx, false, 1 << i));
}
}
});
if change_set.is_empty() {
return Ok(seat_container
.seats
.iter()
.fold(0u32, |mut acc, seat_row| {
acc += seat_row.occupied.count_ones();
acc
})
.to_string());
}
change_set.iter().for_each(|(idx, unset, change)| {
if *unset {
seat_container.seats[*idx].occupied &= change;
} else {
seat_container.seats[*idx].occupied |= change;
}
});
}
Err("failed to find stable state after 100,000 iterations".to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_input() {
let input = "L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL";
let expected = make_expected();
let mut cont = Container::new();
assert_eq!(Ok(()), cont.parse_input(input));
assert_eq!(expected, cont);
}
#[test]
fn test_part_1_example() {
let input = make_expected();
let expected = 37.to_string();
assert_eq!(Ok(expected), input.part_1());
}
#[test]
fn test_part_2_example() {
let input = make_expected();
let expected = 26.to_string();
assert_eq!(Ok(expected), input.part_2());
}
fn make_expected() -> Container {
Container {
row_len: 10,
seats: vec![
SeatRow {
floor: 1 << 1 | 1 << 4 | 1 << 7,
occupied: 0,
},
SeatRow {
floor: 1 << 7,
occupied: 0,
},
SeatRow {
floor: 1 << 1 | 1 << 3 | 1 << 5 | 1 << 6 | 1 << 8 | 1 << 9,
occupied: 0,
},
SeatRow {
floor: 1 << 4 | 1 << 7,
occupied: 0,
},
SeatRow {
floor: 1 << 1 | 1 << 4 | 1 << 7,
occupied: 0,
},
SeatRow {
floor: 1 << 1 | 1 << 7,
occupied: 0,
},
SeatRow {
floor: 1 << 0 | 1 << 1 | 1 << 3 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9,
occupied: 0,
},
SeatRow {
floor: 0,
occupied: 0,
},
SeatRow {
floor: 1 << 1 | 1 << 8,
occupied: 0,
},
SeatRow {
floor: 1 << 1 | 1 << 7,
occupied: 0,
},
],
}
}
}
| 27.967816 | 98 | 0.375226 |
e507c4197dc43db9b8e45a6d545d163006ebbcdd | 7,041 | use hashbrown::{HashMap, HashSet};
use log::*;
use morgan_interface::bvm_address::BvmAddr;
pub type Fork = u64;
#[derive(Default)]
pub struct AccountsIndex<T> {
account_maps: HashMap<BvmAddr, Vec<(Fork, T)>>,
roots: HashSet<Fork>,
pub last_root: Fork,
}
impl<T: Clone> AccountsIndex<T> {
pub fn get(&self, address: &BvmAddr, ancestors: &HashMap<Fork, usize>) -> Option<(&T, Fork)> {
let list = self.account_maps.get(address)?;
let mut max = 0;
let mut rv = None;
for e in list.iter().rev() {
if e.0 >= max && (ancestors.get(&e.0).is_some() || self.is_genesis(e.0)) {
trace!("GET {} {:?}", e.0, ancestors);
rv = Some((&e.1, e.0));
max = e.0;
}
}
rv
}
pub fn insert(&mut self, fork: Fork, address: &BvmAddr, account_info: T) -> Vec<(Fork, T)> {
let mut rv = vec![];
let mut fork_vec: Vec<(Fork, T)> = vec![];
{
let entry = self.account_maps.entry(*address).or_insert(vec![]);
std::mem::swap(entry, &mut fork_vec);
};
rv.extend(fork_vec.iter().filter(|(f, _)| *f == fork).cloned());
fork_vec.retain(|(f, _)| *f != fork);
fork_vec.push((fork, account_info));
rv.extend(
fork_vec
.iter()
.filter(|(fork, _)| self.is_purged(*fork))
.cloned(),
);
fork_vec.retain(|(fork, _)| !self.is_purged(*fork));
{
let entry = self.account_maps.entry(*address).or_insert(vec![]);
std::mem::swap(entry, &mut fork_vec);
};
rv
}
pub fn is_purged(&self, fork: Fork) -> bool {
fork < self.last_root
}
pub fn is_genesis(&self, fork: Fork) -> bool {
self.roots.contains(&fork)
}
pub fn add_root(&mut self, fork: Fork) {
assert!(
(self.last_root == 0 && fork == 0) || (fork > self.last_root),
"new roots must be increasing"
);
self.last_root = fork;
self.roots.insert(fork);
}
pub fn cleanup_dead_fork(&mut self, fork: Fork) {
self.roots.remove(&fork);
}
}
#[cfg(test)]
mod tests {
use super::*;
use morgan_interface::signature::{Keypair, KeypairUtil};
#[test]
fn test_get_empty() {
let key = Keypair::new();
let index = AccountsIndex::<bool>::default();
let ancestors = HashMap::new();
assert_eq!(index.get(&key.address(), &ancestors), None);
}
#[test]
fn test_insert_no_ancestors() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
let ancestors = HashMap::new();
assert_eq!(index.get(&key.address(), &ancestors), None);
}
#[test]
fn test_insert_wrong_ancestors() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
let ancestors = vec![(1, 1)].into_iter().collect();
assert_eq!(index.get(&key.address(), &ancestors), None);
}
#[test]
fn test_insert_with_ancestors() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
let ancestors = vec![(0, 0)].into_iter().collect();
assert_eq!(index.get(&key.address(), &ancestors), Some((&true, 0)));
}
#[test]
fn test_is_root() {
let mut index = AccountsIndex::<bool>::default();
assert!(!index.is_genesis(0));
index.add_root(0);
assert!(index.is_genesis(0));
}
#[test]
fn test_insert_with_root() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
let ancestors = vec![].into_iter().collect();
index.add_root(0);
assert_eq!(index.get(&key.address(), &ancestors), Some((&true, 0)));
}
#[test]
fn test_is_purged() {
let mut index = AccountsIndex::<bool>::default();
assert!(!index.is_purged(0));
index.add_root(1);
assert!(index.is_purged(0));
index.add_root(2);
assert!(index.is_purged(1));
}
#[test]
fn test_max_last_root() {
let mut index = AccountsIndex::<bool>::default();
index.add_root(1);
assert_eq!(index.last_root, 1);
}
#[test]
#[should_panic]
fn test_max_last_root_old() {
let mut index = AccountsIndex::<bool>::default();
index.add_root(1);
index.add_root(0);
}
#[test]
fn test_cleanup_first() {
let mut index = AccountsIndex::<bool>::default();
index.add_root(0);
index.add_root(1);
index.cleanup_dead_fork(0);
assert!(index.is_genesis(1));
assert!(!index.is_genesis(0));
}
#[test]
fn test_cleanup_last() {
let mut index = AccountsIndex::<bool>::default();
index.add_root(0);
index.add_root(1);
index.cleanup_dead_fork(1);
assert!(!index.is_genesis(1));
assert!(index.is_genesis(0));
}
#[test]
fn test_update_last_wins() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let ancestors = vec![(0, 0)].into_iter().collect();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
assert_eq!(index.get(&key.address(), &ancestors), Some((&true, 0)));
let gc = index.insert(0, &key.address(), false);
assert_eq!(gc, vec![(0, true)]);
assert_eq!(index.get(&key.address(), &ancestors), Some((&false, 0)));
}
#[test]
fn test_update_new_fork() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let ancestors = vec![(0, 0)].into_iter().collect();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
let gc = index.insert(1, &key.address(), false);
assert!(gc.is_empty());
assert_eq!(index.get(&key.address(), &ancestors), Some((&true, 0)));
let ancestors = vec![(1, 0)].into_iter().collect();
assert_eq!(index.get(&key.address(), &ancestors), Some((&false, 1)));
}
#[test]
fn test_update_gc_purged_fork() {
let key = Keypair::new();
let mut index = AccountsIndex::<bool>::default();
let gc = index.insert(0, &key.address(), true);
assert!(gc.is_empty());
index.add_root(1);
let gc = index.insert(1, &key.address(), false);
assert_eq!(gc, vec![(0, true)]);
let ancestors = vec![].into_iter().collect();
assert_eq!(index.get(&key.address(), &ancestors), Some((&false, 1)));
}
}
| 30.881579 | 98 | 0.541684 |
ed0e91da36178c9a176139be56cce14cef2301cf | 15,998 | //! Client-side types.
use super::*;
macro_rules! define_handles {
(
'owned: $($oty:ident,)*
'interned: $($ity:ident,)*
) => {
#[repr(C)]
#[allow(non_snake_case)]
pub struct HandleCounters {
$($oty: AtomicUsize,)*
$($ity: AtomicUsize,)*
}
impl HandleCounters {
// FIXME(eddyb) use a reference to the `static COUNTERS`, instead of
// a wrapper `fn` pointer, once `const fn` can reference `static`s.
extern "C" fn get() -> &'static Self {
static COUNTERS: HandleCounters = HandleCounters {
$($oty: AtomicUsize::new(1),)*
$($ity: AtomicUsize::new(1),)*
};
&COUNTERS
}
}
// FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
#[repr(C)]
#[allow(non_snake_case)]
pub(super) struct HandleStore<S: server::Types> {
$($oty: handle::OwnedStore<S::$oty>,)*
$($ity: handle::InternedStore<S::$ity>,)*
}
impl<S: server::Types> HandleStore<S> {
pub(super) fn new(handle_counters: &'static HandleCounters) -> Self {
HandleStore {
$($oty: handle::OwnedStore::new(&handle_counters.$oty),)*
$($ity: handle::InternedStore::new(&handle_counters.$ity),)*
}
}
}
$(
#[repr(C)]
pub(crate) struct $oty(handle::Handle);
// Forward `Drop::drop` to the inherent `drop` method.
impl Drop for $oty {
fn drop(&mut self) {
$oty(self.0).drop();
}
}
impl<S> Encode<S> for $oty {
fn encode(self, w: &mut Writer, s: &mut S) {
let handle = self.0;
mem::forget(self);
handle.encode(w, s);
}
}
impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
for Marked<S::$oty, $oty>
{
fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
s.$oty.take(handle::Handle::decode(r, &mut ()))
}
}
impl<S> Encode<S> for &$oty {
fn encode(self, w: &mut Writer, s: &mut S) {
self.0.encode(w, s);
}
}
impl<'s, S: server::Types> Decode<'_, 's, HandleStore<server::MarkedTypes<S>>>
for &'s Marked<S::$oty, $oty>
{
fn decode(r: &mut Reader<'_>, s: &'s HandleStore<server::MarkedTypes<S>>) -> Self {
&s.$oty[handle::Handle::decode(r, &mut ())]
}
}
impl<S> Encode<S> for &mut $oty {
fn encode(self, w: &mut Writer, s: &mut S) {
self.0.encode(w, s);
}
}
impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore<server::MarkedTypes<S>>>
for &'s mut Marked<S::$oty, $oty>
{
fn decode(
r: &mut Reader<'_>,
s: &'s mut HandleStore<server::MarkedTypes<S>>
) -> Self {
&mut s.$oty[handle::Handle::decode(r, &mut ())]
}
}
impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
for Marked<S::$oty, $oty>
{
fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
s.$oty.alloc(self).encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for $oty {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
$oty(handle::Handle::decode(r, s))
}
}
)*
$(
#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct $ity(handle::Handle);
impl<S> Encode<S> for $ity {
fn encode(self, w: &mut Writer, s: &mut S) {
self.0.encode(w, s);
}
}
impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
for Marked<S::$ity, $ity>
{
fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
s.$ity.copy(handle::Handle::decode(r, &mut ()))
}
}
impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
for Marked<S::$ity, $ity>
{
fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
s.$ity.alloc(self).encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for $ity {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
$ity(handle::Handle::decode(r, s))
}
}
)*
}
}
define_handles! {
'owned:
FreeFunctions,
TokenStream,
TokenStreamBuilder,
TokenStreamIter,
Group,
Literal,
SourceFile,
MultiSpan,
Diagnostic,
'interned:
Punct,
Ident,
Span,
}
// FIXME(eddyb) generate these impls by pattern-matching on the
// names of methods - also could use the presence of `fn drop`
// to distinguish between 'owned and 'interned, above.
// Alternatively, special 'modes" could be listed of types in with_api
// instead of pattern matching on methods, here and in server decl.
impl Clone for TokenStream {
fn clone(&self) -> Self {
self.clone()
}
}
impl Clone for TokenStreamIter {
fn clone(&self) -> Self {
self.clone()
}
}
impl Clone for Group {
fn clone(&self) -> Self {
self.clone()
}
}
impl Clone for Literal {
fn clone(&self) -> Self {
self.clone()
}
}
impl fmt::Debug for Literal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Literal")
// format the kind without quotes, as in `kind: Float`
.field("kind", &format_args!("{}", &self.debug_kind()))
.field("symbol", &self.symbol())
// format `Some("...")` on one line even in {:#?} mode
.field("suffix", &format_args!("{:?}", &self.suffix()))
.field("span", &self.span())
.finish()
}
}
impl Clone for SourceFile {
fn clone(&self) -> Self {
self.clone()
}
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.debug())
}
}
macro_rules! define_client_side {
($($name:ident {
$(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
}),* $(,)?) => {
$(impl $name {
$(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* {
Bridge::with(|bridge| {
let mut b = bridge.cached_buffer.take();
b.clear();
api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ());
reverse_encode!(b; $($arg),*);
b = bridge.dispatch.call(b);
let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ());
bridge.cached_buffer = b;
r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
})
})*
})*
}
}
with_api!(self, self, define_client_side);
enum BridgeState<'a> {
/// No server is currently connected to this client.
NotConnected,
/// A server is connected and available for requests.
Connected(Bridge<'a>),
/// Access to the bridge is being exclusively acquired
/// (e.g., during `BridgeState::with`).
InUse,
}
enum BridgeStateL {}
impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL {
type Out = BridgeState<'a>;
}
thread_local! {
static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> =
scoped_cell::ScopedCell::new(BridgeState::NotConnected);
}
impl BridgeState<'_> {
/// Take exclusive control of the thread-local
/// `BridgeState`, and pass it to `f`, mutably.
/// The state will be restored after `f` exits, even
/// by panic, including modifications made to it by `f`.
///
/// N.B., while `f` is running, the thread-local state
/// is `BridgeState::InUse`.
fn with<R>(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R {
BRIDGE_STATE.with(|state| {
state.replace(BridgeState::InUse, |mut state| {
// FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone
f(&mut *state)
})
})
}
}
impl Bridge<'_> {
pub(crate) fn is_available() -> bool {
BridgeState::with(|state| match state {
BridgeState::Connected(_) | BridgeState::InUse => true,
BridgeState::NotConnected => false,
})
}
fn enter<R>(self, f: impl FnOnce() -> R) -> R {
let force_show_panics = self.force_show_panics;
// Hide the default panic output within `proc_macro` expansions.
// NB. the server can't do this because it may use a different libstd.
static HIDE_PANICS_DURING_EXPANSION: Once = Once::new();
HIDE_PANICS_DURING_EXPANSION.call_once(|| {
let prev = panic::take_hook();
panic::set_hook(Box::new(move |info| {
let show = BridgeState::with(|state| match state {
BridgeState::NotConnected => true,
BridgeState::Connected(_) | BridgeState::InUse => force_show_panics,
});
if show {
prev(info)
}
}));
});
BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f))
}
fn with<R>(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R {
BridgeState::with(|state| match state {
BridgeState::NotConnected => {
panic!("procedural macro API is used outside of a procedural macro");
}
BridgeState::InUse => {
panic!("procedural macro API is used while it's already in use");
}
BridgeState::Connected(bridge) => f(bridge),
})
}
}
/// A client-side "global object" (usually a function pointer),
/// which may be using a different `proc_macro` from the one
/// used by the server, but can be interacted with compatibly.
///
/// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer).
/// The call ABI of function pointers used for `F` doesn't
/// need to match between server and client, since it's only
/// passed between them and (eventually) called by the client.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Client<F> {
// FIXME(eddyb) use a reference to the `static COUNTERS`, instead of
// a wrapper `fn` pointer, once `const fn` can reference `static`s.
pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,
pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer<u8>,
pub(super) f: F,
}
/// Client-side helper for handling client panics, entering the bridge,
/// deserializing input and serializing output.
// FIXME(eddyb) maybe replace `Bridge::enter` with this?
fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
mut bridge: Bridge<'_>,
f: impl FnOnce(A) -> R,
) -> Buffer<u8> {
// The initial `cached_buffer` contains the input.
let mut b = bridge.cached_buffer.take();
panic::catch_unwind(panic::AssertUnwindSafe(|| {
bridge.enter(|| {
let reader = &mut &b[..];
let input = A::decode(reader, &mut ());
// Put the `cached_buffer` back in the `Bridge`, for requests.
Bridge::with(|bridge| bridge.cached_buffer = b.take());
let output = f(input);
// Take the `cached_buffer` back out, for the output value.
b = Bridge::with(|bridge| bridge.cached_buffer.take());
// HACK(eddyb) Separate encoding a success value (`Ok(output)`)
// from encoding a panic (`Err(e: PanicMessage)`) to avoid
// having handles outside the `bridge.enter(|| ...)` scope, and
// to catch panics that could happen while encoding the success.
//
// Note that panics should be impossible beyond this point, but
// this is defensively trying to avoid any accidental panicking
// reaching the `extern "C"` (which should `abort` but might not
// at the moment, so this is also potentially preventing UB).
b.clear();
Ok::<_, ()>(output).encode(&mut b, &mut ());
})
}))
.map_err(PanicMessage::from)
.unwrap_or_else(|e| {
b.clear();
Err::<(), _>(e).encode(&mut b, &mut ());
});
b
}
impl Client<fn(super::super::TokenStream) -> super::super::TokenStream> {
pub fn expand1(f: fn(super::super::TokenStream) -> super::super::TokenStream) -> Self {
extern "C" fn run(
bridge: Bridge<'_>,
f: impl FnOnce(super::super::TokenStream) -> super::super::TokenStream,
) -> Buffer<u8> {
run_client(bridge, |input| f(super::super::TokenStream(input)).0)
}
Client { get_handle_counters: HandleCounters::get, run, f }
}
}
impl Client<fn(super::super::TokenStream, super::super::TokenStream) -> super::super::TokenStream> {
pub fn expand2(
f: fn(super::super::TokenStream, super::super::TokenStream) -> super::super::TokenStream,
) -> Self {
extern "C" fn run(
bridge: Bridge<'_>,
f: impl FnOnce(
super::super::TokenStream,
super::super::TokenStream,
) -> super::super::TokenStream,
) -> Buffer<u8> {
run_client(bridge, |(input, input2)| {
f(super::super::TokenStream(input), super::super::TokenStream(input2)).0
})
}
Client { get_handle_counters: HandleCounters::get, run, f }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub enum ProcMacro {
CustomDerive {
trait_name: &'static str,
attributes: &'static [&'static str],
client: Client<fn(super::super::TokenStream) -> super::super::TokenStream>,
},
Attr {
name: &'static str,
client: Client<
fn(super::super::TokenStream, super::super::TokenStream) -> super::super::TokenStream,
>,
},
Bang {
name: &'static str,
client: Client<fn(super::super::TokenStream) -> super::super::TokenStream>,
},
}
impl ProcMacro {
pub fn name(&self) -> &'static str {
match self {
ProcMacro::CustomDerive { trait_name, .. } => trait_name,
ProcMacro::Attr { name, .. } => name,
ProcMacro::Bang { name, .. } => name,
}
}
pub fn custom_derive(
trait_name: &'static str,
attributes: &'static [&'static str],
expand: fn(super::super::TokenStream) -> super::super::TokenStream,
) -> Self {
ProcMacro::CustomDerive { trait_name, attributes, client: Client::expand1(expand) }
}
pub fn attr(
name: &'static str,
expand: fn(
super::super::TokenStream,
super::super::TokenStream,
) -> super::super::TokenStream,
) -> Self {
ProcMacro::Attr { name, client: Client::expand2(expand) }
}
pub fn bang(
name: &'static str,
expand: fn(super::super::TokenStream) -> super::super::TokenStream,
) -> Self {
ProcMacro::Bang { name, client: Client::expand1(expand) }
}
}
| 32.917695 | 100 | 0.51669 |
382429db70ed91bc4a8cae80a3bd14750f844d53 | 7,467 | use crate::parse::ast::{Expr, ExprKind, Item, ItemKind, LetVar};
use lasso::ThreadedRodeo;
use pretty::{DocAllocator, DocBuilder};
/// Trait representing anything that can be turned into a `Doc`.
pub trait Pretty {
/// Turns `&self` into a `DocBuilder`.
fn pretty<'alloc, D>(
&'alloc self,
alloc: &'alloc D,
rodeo: &ThreadedRodeo,
) -> DocBuilder<'alloc, D>
where
D: DocAllocator<'alloc>,
D::Doc: Clone;
}
impl Pretty for Expr {
fn pretty<'alloc, D>(
&'alloc self,
alloc: &'alloc D,
rodeo: &ThreadedRodeo,
) -> DocBuilder<'alloc, D>
where
D: DocAllocator<'alloc>,
D::Doc: Clone,
{
self.kind.pretty(alloc, rodeo)
}
}
impl Pretty for ExprKind {
fn pretty<'alloc, D>(
&'alloc self,
alloc: &'alloc D,
rodeo: &ThreadedRodeo,
) -> DocBuilder<'alloc, D>
where
D: DocAllocator<'alloc>,
D::Doc: Clone,
{
match self {
ExprKind::Number(x) => alloc.as_string(x),
ExprKind::Var(name) => alloc.as_string(rodeo.resolve(&name.spur)),
ExprKind::Unary { op, val } => {
alloc.as_string(op).append(val.pretty(alloc, rodeo)).group()
}
ExprKind::Binary { left, op, right } => left
.pretty(alloc, rodeo)
.append(alloc.space())
.append(alloc.as_string(op))
.append(alloc.space())
.append(right.pretty(alloc, rodeo))
.group(),
ExprKind::Call { callee, args } => {
let separator = alloc.text(",").append(alloc.space());
alloc
.as_string(rodeo.resolve(&callee.spur))
.append(alloc.text("("))
.append(alloc.intersperse(
args.into_iter().map(|expr| expr.pretty(alloc, rodeo)),
separator,
))
.append(alloc.text(")"))
.group()
}
ExprKind::If { cond, then, else_ } => alloc
.text("if")
.append(alloc.space())
.append(cond.pretty(alloc, rodeo))
.append(alloc.space())
.append(alloc.text("then"))
.append(alloc.hardline().append(then.pretty(alloc, rodeo)).nest(2))
.append(alloc.hardline().append(alloc.text("else")))
.append(alloc.hardline().append(else_.pretty(alloc, rodeo)).nest(2))
.group(),
ExprKind::For { .. } => todo!(),
ExprKind::Let { vars, body } => {
let vars = vars.into_iter().map(|LetVar { name, val }| {
let doc = alloc.as_string(rodeo.resolve(&name.spur));
if let Some(val) = val {
doc.append(alloc.space())
.append(alloc.text("="))
.append(alloc.space())
.append(val.pretty(alloc, rodeo))
.group()
} else {
doc.group()
}
});
let separator = alloc.text(",").append(alloc.space());
alloc
.text("var")
.append(alloc.space())
.append(alloc.intersperse(vars, separator))
.append(alloc.space())
.append(alloc.text("in"))
.append(alloc.hardline())
.append(body.pretty(alloc, rodeo).nest(2))
.group()
}
}
}
}
impl Pretty for Item {
fn pretty<'alloc, D>(
&'alloc self,
alloc: &'alloc D,
rodeo: &ThreadedRodeo,
) -> DocBuilder<'alloc, D>
where
D: DocAllocator<'alloc>,
D::Doc: Clone,
{
self.kind.pretty(alloc, rodeo)
}
}
impl Pretty for ItemKind {
fn pretty<'alloc, D>(
&'alloc self,
alloc: &'alloc D,
rodeo: &ThreadedRodeo,
) -> DocBuilder<'alloc, D>
where
D: DocAllocator<'alloc>,
D::Doc: Clone,
{
match self {
ItemKind::Function { name, args, body } => {
let separator = alloc.space();
alloc
.text("def")
.append(alloc.space())
.append(alloc.as_string(rodeo.resolve(&name.spur)))
.append(alloc.text("("))
.append(
alloc.intersperse(
args.into_iter()
.map(|name| alloc.as_string(rodeo.resolve(&name.spur))),
separator,
),
)
.append(alloc.text(")"))
.group()
.append(
alloc
.hardline()
.append(body.pretty(alloc, rodeo))
.append(alloc.text(";"))
.nest(2),
)
}
ItemKind::Extern { name, args } => {
let separator = alloc.space();
alloc
.text("extern")
.append(alloc.space())
.append(alloc.as_string(rodeo.resolve(&name.spur)))
.append(alloc.text("("))
.append(
alloc.intersperse(
args.into_iter()
.map(|name| alloc.as_string(rodeo.resolve(&name.spur))),
separator,
),
)
.append(alloc.text(")"))
.append(alloc.text(";"))
.group()
}
ItemKind::Operator {
op,
prec,
is_binary,
body,
args,
} => {
let separator = alloc.space();
alloc
.text("def")
.append(alloc.space())
.append(alloc.text(if *is_binary { "binary" } else { "unary" }))
.append(alloc.as_string(op))
.append(if *is_binary {
alloc
.space()
.append(alloc.as_string(prec))
.append(alloc.space())
} else {
alloc.nil()
})
.append(alloc.text("("))
.append(
alloc.intersperse(
args.into_iter()
.map(|name| alloc.as_string(rodeo.resolve(&name.spur))),
separator,
),
)
.append(alloc.text(")"))
.group()
.append(
alloc
.hardline()
.append(body.pretty(alloc, rodeo))
.append(alloc.text(";"))
.nest(2),
)
}
}
}
}
| 34.730233 | 88 | 0.392393 |
1e92fb8cf41fd41b1861b33fd858449f79b6b247 | 4,741 | mod test {
use crate::search::{binary_search, linear_search};
fn test_empty<F: Fn(&u8, &[u8]) -> Option<usize>>(f: F) {
let index = f(&1, &vec![]);
assert_eq!(index, None);
}
fn test_string_search_sorted<F: Fn(&String, &[String]) -> Option<usize>>(f: F) {
let arr = vec![String::from("a"), String::from("aa"), String::from("abc")];
let index = f(&String::from("a"), &arr);
assert_eq!(index, Some(0));
let index = f(&String::from("aa"), &arr);
assert_eq!(index, Some(1));
let index = f(&String::from("abc"), &arr);
assert_eq!(index, Some(2));
let index = f(&String::from("z"), &arr);
assert_eq!(index, None);
}
fn test_int_search_sorted<F: Fn(&i32, &[i32]) -> Option<usize>>(f: F) {
let arr = vec![-1, 1, 3, 6, 9];
let index = f(&-1, &arr);
assert_eq!(index, Some(0));
let index = f(&1, &arr);
assert_eq!(index, Some(1));
let index = f(&3, &arr);
assert_eq!(index, Some(2));
let index = f(&6, &arr);
assert_eq!(index, Some(3));
let index = f(&9, &arr);
assert_eq!(index, Some(4));
let index = f(&10, &arr);
assert_eq!(index, None);
}
fn test_float_search_sorted<F: Fn(&f32, &[f32]) -> Option<usize>>(f: F) {
let arr = vec![-1.1, -1.0, 2.1, 3.9102, 4.6];
let index = f(&-1.1, &arr);
assert_eq!(index, Some(0));
let index = f(&-1.0, &arr);
assert_eq!(index, Some(1));
let index = f(&2.1, &arr);
assert_eq!(index, Some(2));
let index = f(&3.9102, &arr);
assert_eq!(index, Some(3));
let index = f(&4.6, &arr);
assert_eq!(index, Some(4));
let index = f(&-1.2, &arr);
assert_eq!(index, None);
let index = f(&10.2, &arr);
assert_eq!(index, None);
}
fn test_string_search_unsorted<F: Fn(&String, &[String]) -> Option<usize>>(f: F) {
let arr = vec![String::from("ab"), String::from("az"), String::from("a")];
let index = f(&String::from("ab"), &arr);
assert_eq!(index, Some(0));
let index = f(&String::from("az"), &arr);
assert_eq!(index, Some(1));
let index = f(&String::from("a"), &arr);
assert_eq!(index, Some(2));
let index = f(&String::from("z"), &arr);
assert_eq!(index, None);
}
fn test_int_search_unsorted<F: Fn(&i32, &[i32]) -> Option<usize>>(f: F) {
let arr = vec![1, 4, 3, 46, -9];
let index = f(&1, &arr);
assert_eq!(index, Some(0));
let index = f(&4, &arr);
assert_eq!(index, Some(1));
let index = f(&3, &arr);
assert_eq!(index, Some(2));
let index = f(&46, &arr);
assert_eq!(index, Some(3));
let index = f(&-9, &arr);
assert_eq!(index, Some(4));
let index = f(&10, &arr);
assert_eq!(index, None);
}
fn test_float_search_unsorted<F: Fn(&f32, &[f32]) -> Option<usize>>(f: F) {
let arr = vec![1.1, 1.01, -2.1, -3.2, 4.6];
let index = f(&1.1, &arr);
assert_eq!(index, Some(0));
let index = f(&1.01, &arr);
assert_eq!(index, Some(1));
let index = f(&-2.1, &arr);
assert_eq!(index, Some(2));
let index = f(&-3.2, &arr);
assert_eq!(index, Some(3));
let index = f(&4.6, &arr);
assert_eq!(index, Some(4));
let index = f(&-1.2, &arr);
assert_eq!(index, None);
}
#[test]
fn linear_search_empty() {
test_empty(linear_search);
}
#[test]
fn linear_search_int_search_sorted() {
test_int_search_sorted(linear_search);
}
#[test]
fn linear_search_float_search_sorted() {
test_float_search_sorted(linear_search);
}
#[test]
fn linear_search_string_search_sorted() {
test_string_search_sorted(linear_search);
}
#[test]
fn linear_search_int_search_unsorted() {
test_int_search_unsorted(linear_search);
}
#[test]
fn linear_search_float_search_unsorted() {
test_float_search_unsorted(linear_search);
}
#[test]
fn linear_search_string_search_unsorted() {
test_string_search_unsorted(linear_search);
}
#[test]
fn binary_search_empty() {
test_empty(binary_search);
}
#[test]
fn binary_search_int_search_sorted() {
test_int_search_sorted(binary_search);
}
#[test]
fn binary_search_float_search_sorted() {
test_float_search_sorted(binary_search);
}
#[test]
fn binary_search_string_search_sorted() {
test_string_search_sorted(binary_search);
}
}
| 25.627027 | 86 | 0.530479 |
8a91b86d6b3bf6d851e3083515a14e01a7397a4a | 12,928 | // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::serde_json::Value;
use serde::Serialize;
use std::collections::HashMap;
use std::convert::From;
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use std::time::SystemTime;
mod http;
mod lsp;
mod throughput;
fn read_json(filename: &str) -> Result<Value> {
let f = fs::File::open(filename)?;
Ok(serde_json::from_reader(f)?)
}
fn write_json(filename: &str, value: &Value) -> Result<()> {
let f = fs::File::create(filename)?;
serde_json::to_writer(f, value)?;
Ok(())
}
/// The list of the tuples of the benchmark name, arguments and return code
const EXEC_TIME_BENCHMARKS: &[(&str, &[&str], Option<i32>)] = &[
// we need to run the cold_* benchmarks before the _warm_ ones as they ensure
// the cache is properly populated, instead of other tests possibly
// invalidating that cache.
(
"cold_hello",
&["run", "--reload", "cli/tests/002_hello.ts"],
None,
),
(
"cold_relative_import",
&["run", "--reload", "cli/tests/003_relative_import.ts"],
None,
),
("hello", &["run", "cli/tests/002_hello.ts"], None),
(
"relative_import",
&["run", "cli/tests/003_relative_import.ts"],
None,
),
("error_001", &["run", "cli/tests/error_001.ts"], Some(1)),
(
"no_check_hello",
&["run", "--reload", "--no-check", "cli/tests/002_hello.ts"],
None,
),
(
"workers_startup",
&["run", "--allow-read", "cli/tests/workers/bench_startup.ts"],
None,
),
(
"workers_round_robin",
&[
"run",
"--allow-read",
"cli/tests/workers/bench_round_robin.ts",
],
None,
),
(
"workers_large_message",
&[
"run",
"--allow-read",
"cli/tests/workers_large_message_bench.ts",
],
None,
),
(
"text_decoder",
&["run", "cli/tests/text_decoder_perf.js"],
None,
),
(
"text_encoder",
&["run", "cli/tests/text_encoder_perf.js"],
None,
),
(
"check",
&[
"cache",
"--reload",
"test_util/std/examples/chat/server_test.ts",
],
None,
),
(
"no_check",
&[
"cache",
"--reload",
"--no-check",
"test_util/std/examples/chat/server_test.ts",
],
None,
),
(
"bundle",
&["bundle", "test_util/std/examples/chat/server_test.ts"],
None,
),
(
"bundle_no_check",
&[
"bundle",
"--no-check",
"test_util/std/examples/chat/server_test.ts",
],
None,
),
];
const RESULT_KEYS: &[&str] =
&["mean", "stddev", "user", "system", "min", "max"];
fn run_exec_time(
deno_exe: &PathBuf,
target_dir: &PathBuf,
) -> Result<HashMap<String, HashMap<String, f64>>> {
let hyperfine_exe = test_util::prebuilt_tool_path("hyperfine");
let benchmark_file = target_dir.join("hyperfine_results.json");
let benchmark_file = benchmark_file.to_str().unwrap();
let mut command = [
hyperfine_exe.to_str().unwrap(),
"--export-json",
benchmark_file,
"--warmup",
"3",
]
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>();
for (_, args, return_code) in EXEC_TIME_BENCHMARKS {
let ret_code_test = if let Some(code) = return_code {
// Bash test which asserts the return code value of the previous command
// $? contains the return code of the previous command
format!("; test $? -eq {}", code)
} else {
"".to_string()
};
command.push(format!(
"{} {} {}",
deno_exe.to_str().unwrap(),
args.join(" "),
ret_code_test
));
}
test_util::run(
&command.iter().map(|s| s.as_ref()).collect::<Vec<_>>(),
None,
None,
None,
true,
);
let mut results = HashMap::<String, HashMap<String, f64>>::new();
let hyperfine_results = read_json(benchmark_file)?;
for ((name, _, _), data) in EXEC_TIME_BENCHMARKS.iter().zip(
hyperfine_results
.as_object()
.unwrap()
.get("results")
.unwrap()
.as_array()
.unwrap(),
) {
let data = data.as_object().unwrap().clone();
results.insert(
name.to_string(),
data
.into_iter()
.filter(|(key, _)| RESULT_KEYS.contains(&key.as_str()))
.map(|(key, val)| (key, val.as_f64().unwrap()))
.collect(),
);
}
Ok(results)
}
fn rlib_size(target_dir: &std::path::Path, prefix: &str) -> u64 {
let mut size = 0;
let mut seen = std::collections::HashSet::new();
for entry in std::fs::read_dir(target_dir.join("deps")).unwrap() {
let entry = entry.unwrap();
let os_str = entry.file_name();
let name = os_str.to_str().unwrap();
if name.starts_with(prefix) && name.ends_with(".rlib") {
let start = name.split('-').next().unwrap().to_string();
if seen.contains(&start) {
println!("skip {}", name);
} else {
seen.insert(start);
size += entry.metadata().unwrap().len();
println!("check size {} {}", name, size);
}
}
}
assert!(size > 0);
size
}
const BINARY_TARGET_FILES: &[&str] =
&["CLI_SNAPSHOT.bin", "COMPILER_SNAPSHOT.bin"];
fn get_binary_sizes(target_dir: &PathBuf) -> Result<HashMap<String, u64>> {
let mut sizes = HashMap::<String, u64>::new();
let mut mtimes = HashMap::<String, SystemTime>::new();
sizes.insert(
"deno".to_string(),
test_util::deno_exe_path().metadata()?.len(),
);
// add up size for denort
sizes.insert(
"denort".to_string(),
test_util::denort_exe_path().metadata()?.len(),
);
// add up size for everything in target/release/deps/libswc*
let swc_size = rlib_size(&target_dir, "libswc");
println!("swc {} bytes", swc_size);
sizes.insert("swc_rlib".to_string(), swc_size);
let rusty_v8_size = rlib_size(&target_dir, "librusty_v8");
println!("rusty_v8 {} bytes", rusty_v8_size);
sizes.insert("rusty_v8_rlib".to_string(), rusty_v8_size);
// Because cargo's OUT_DIR is not predictable, search the build tree for
// snapshot related files.
for file in walkdir::WalkDir::new(target_dir) {
let file = match file {
Ok(file) => file,
Err(_) => continue,
};
let filename = file.file_name().to_str().unwrap().to_string();
if !BINARY_TARGET_FILES.contains(&filename.as_str()) {
continue;
}
let meta = file.metadata()?;
let file_mtime = meta.modified()?;
// If multiple copies of a file are found, use the most recent one.
if let Some(stored_mtime) = mtimes.get(&filename) {
if *stored_mtime > file_mtime {
continue;
}
}
mtimes.insert(filename.clone(), file_mtime);
sizes.insert(filename, meta.len());
}
Ok(sizes)
}
const BUNDLES: &[(&str, &str)] = &[
("file_server", "./test_util/std/http/file_server.ts"),
("gist", "./test_util/std/examples/gist.ts"),
];
fn bundle_benchmark(deno_exe: &PathBuf) -> Result<HashMap<String, u64>> {
let mut sizes = HashMap::<String, u64>::new();
for (name, url) in BUNDLES {
let path = format!("{}.bundle.js", name);
test_util::run(
&[
deno_exe.to_str().unwrap(),
"bundle",
"--unstable",
url,
&path,
],
None,
None,
None,
true,
);
let file = PathBuf::from(path);
assert!(file.is_file());
sizes.insert(name.to_string(), file.metadata()?.len());
let _ = fs::remove_file(file);
}
Ok(sizes)
}
fn run_throughput(deno_exe: &PathBuf) -> Result<HashMap<String, f64>> {
let mut m = HashMap::<String, f64>::new();
m.insert("100M_tcp".to_string(), throughput::tcp(deno_exe, 100)?);
m.insert("100M_cat".to_string(), throughput::cat(deno_exe, 100));
m.insert("10M_tcp".to_string(), throughput::tcp(deno_exe, 10)?);
m.insert("10M_cat".to_string(), throughput::cat(deno_exe, 10));
Ok(m)
}
fn run_http(target_dir: &PathBuf, new_data: &mut BenchResult) -> Result<()> {
let stats = http::benchmark(target_dir)?;
new_data.req_per_sec = stats
.iter()
.map(|(name, result)| (name.clone(), result.requests))
.collect();
new_data.max_latency = stats
.iter()
.map(|(name, result)| (name.clone(), result.latency))
.collect();
Ok(())
}
fn run_strace_benchmarks(
deno_exe: &PathBuf,
new_data: &mut BenchResult,
) -> Result<()> {
use std::io::Read;
let mut thread_count = HashMap::<String, u64>::new();
let mut syscall_count = HashMap::<String, u64>::new();
for (name, args, _) in EXEC_TIME_BENCHMARKS {
let mut file = tempfile::NamedTempFile::new()?;
Command::new("strace")
.args(&[
"-c",
"-f",
"-o",
file.path().to_str().unwrap(),
deno_exe.to_str().unwrap(),
])
.args(args.iter())
.stdout(Stdio::inherit())
.spawn()?
.wait()?;
let mut output = String::new();
file.as_file_mut().read_to_string(&mut output)?;
let strace_result = test_util::parse_strace_output(&output);
let clone = strace_result.get("clone").map(|d| d.calls).unwrap_or(0) + 1;
let total = strace_result.get("total").unwrap().calls;
thread_count.insert(name.to_string(), clone);
syscall_count.insert(name.to_string(), total);
}
new_data.thread_count = thread_count;
new_data.syscall_count = syscall_count;
Ok(())
}
fn run_max_mem_benchmark(deno_exe: &PathBuf) -> Result<HashMap<String, u64>> {
let mut results = HashMap::<String, u64>::new();
for (name, args, return_code) in EXEC_TIME_BENCHMARKS {
let proc = Command::new("time")
.args(&["-v", deno_exe.to_str().unwrap()])
.args(args.iter())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()?;
let proc_result = proc.wait_with_output()?;
if let Some(code) = return_code {
assert_eq!(proc_result.status.code().unwrap(), *code);
}
let out = String::from_utf8(proc_result.stderr)?;
results.insert(name.to_string(), test_util::parse_max_mem(&out).unwrap());
}
Ok(results)
}
fn cargo_deps() -> usize {
let cargo_lock = test_util::root_path().join("Cargo.lock");
let mut count = 0;
let file = std::fs::File::open(cargo_lock).unwrap();
use std::io::BufRead;
for line in std::io::BufReader::new(file).lines() {
if line.unwrap().starts_with("[[package]]") {
count += 1
}
}
println!("cargo_deps {}", count);
assert!(count > 10); // Sanity check.
count
}
#[derive(Default, Serialize)]
struct BenchResult {
created_at: String,
sha1: String,
// TODO(ry) The "benchmark" benchmark should actually be called "exec_time".
// When this is changed, the historical data in gh-pages branch needs to be
// changed too.
benchmark: HashMap<String, HashMap<String, f64>>,
binary_size: HashMap<String, u64>,
bundle_size: HashMap<String, u64>,
cargo_deps: usize,
max_latency: HashMap<String, f64>,
max_memory: HashMap<String, u64>,
lsp_exec_time: HashMap<String, u64>,
req_per_sec: HashMap<String, u64>,
syscall_count: HashMap<String, u64>,
thread_count: HashMap<String, u64>,
throughput: HashMap<String, f64>,
}
/*
TODO(SyrupThinker)
Switch to the #[bench] attribute once
it is stabilized.
Before that the #[test] tests won't be run because
we replace the harness with our own runner here.
*/
fn main() -> Result<()> {
if env::args().find(|s| s == "--bench").is_none() {
return Ok(());
}
println!("Starting Deno benchmark");
let target_dir = test_util::target_dir();
let deno_exe = test_util::deno_exe_path();
env::set_current_dir(&test_util::root_path())?;
let mut new_data = BenchResult {
created_at: chrono::Utc::now()
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
sha1: test_util::run_collect(
&["git", "rev-parse", "HEAD"],
None,
None,
None,
true,
)
.0
.trim()
.to_string(),
benchmark: run_exec_time(&deno_exe, &target_dir)?,
binary_size: get_binary_sizes(&target_dir)?,
bundle_size: bundle_benchmark(&deno_exe)?,
cargo_deps: cargo_deps(),
lsp_exec_time: lsp::benchmarks(&deno_exe)?,
..Default::default()
};
// Cannot run throughput benchmark on windows because they don't have nc or
// pipe.
if cfg!(not(target_os = "windows")) {
new_data.throughput = run_throughput(&deno_exe)?;
run_http(&target_dir, &mut new_data)?;
}
if cfg!(target_os = "linux") {
run_strace_benchmarks(&deno_exe, &mut new_data)?;
new_data.max_memory = run_max_mem_benchmark(&deno_exe)?;
}
println!("===== <BENCHMARK RESULTS>");
serde_json::to_writer_pretty(std::io::stdout(), &new_data)?;
println!("\n===== </BENCHMARK RESULTS>");
if let Some(filename) = target_dir.join("bench.json").to_str() {
write_json(filename, &serde_json::to_value(&new_data)?)?;
} else {
eprintln!("Cannot write bench.json, path is invalid");
}
Ok(())
}
pub(crate) type Result<T> = std::result::Result<T, AnyError>;
| 25.856 | 79 | 0.614403 |
22491a55053970c2a03307a38bf58f3bc628be8c | 1,134 | use clap::Parser;
use git_mob::{get_available_coauthors, write_coauthors_file, Author};
use std::process;
#[derive(Parser, Debug)]
#[clap(name = "git-edit-coauthor", version)]
/// Edit a co-author in your .git-coauthors template
struct Opt {
/// Co-author initials
initials: String,
/// The name of the co-author, in quotes, e.g. "Foo Bar"
#[clap(long, required_unless_present("email"))]
name: Option<String>,
/// The email of the co-author
#[clap(long, required_unless_present("name"))]
email: Option<String>,
}
fn main() {
let opt = Opt::parse();
let mut authors = get_available_coauthors();
let mut updated_author: Author;
if let Some(author) = authors.get(&opt.initials) {
updated_author = author.clone();
} else {
eprintln!("No author found with initials {}", &opt.initials);
process::exit(1);
}
if let Some(name) = opt.name {
updated_author.name = name;
}
if let Some(email) = opt.email {
updated_author.email = email;
}
authors.insert(opt.initials, updated_author);
write_coauthors_file(authors);
}
| 25.772727 | 69 | 0.641093 |
fb558b47337cff216aaa2e2e9a6da9d9b2c3b192 | 369 | fn part1() -> u64 {
todo!()
}
fn part2() -> u64 {
todo!()
}
#[allow(clippy::unnecessary_wraps)]
pub fn run() -> Result<String, String> {
let _input = include_str!("input/d16.txt");
let out1 = part1();
let out2 = part2();
Ok(format!("{} {}", out1, out2))
}
#[cfg(test)]
mod tests {
// use super::*;
// #[test]
// fn test01() {}
}
| 15.375 | 47 | 0.509485 |
75360ec8a72a221f685d98f3ad485840287e6e02 | 1,180 | #![deny(rust_2018_idioms, unsafe_code)]
mod mssql_datamodel_connector;
mod mysql_datamodel_connector;
mod postgres_datamodel_connector;
mod sqlite_datamodel_connector;
pub use mssql_datamodel_connector::MsSqlDatamodelConnector;
pub use mysql_datamodel_connector::MySqlDatamodelConnector;
pub use postgres_datamodel_connector::PostgresDatamodelConnector;
pub use sqlite_datamodel_connector::SqliteDatamodelConnector;
use datamodel_connector::ReferentialIntegrity;
pub struct SqlDatamodelConnectors {}
impl SqlDatamodelConnectors {
pub fn postgres(referential_integrity: ReferentialIntegrity) -> PostgresDatamodelConnector {
PostgresDatamodelConnector::new(referential_integrity)
}
pub fn mysql(referential_integrity: ReferentialIntegrity) -> MySqlDatamodelConnector {
MySqlDatamodelConnector::new(referential_integrity)
}
pub fn sqlite(referential_integrity: ReferentialIntegrity) -> SqliteDatamodelConnector {
SqliteDatamodelConnector::new(referential_integrity)
}
pub fn mssql(referential_integrity: ReferentialIntegrity) -> MsSqlDatamodelConnector {
MsSqlDatamodelConnector::new(referential_integrity)
}
}
| 34.705882 | 96 | 0.818644 |
086bae276effd0f11f9a34a6ecee918e1086ea45 | 420 | #[test]
fn union_find_test() {
use crate::data_structures::disjoint_set::UnionFind;
let mut uf = UnionFind::new(10);
uf.unite(0, 2);
uf.unite(0, 3);
uf.unite(2, 5);
uf.unite(5, 7);
assert_eq!(uf.same(0, 5), true);
assert_eq!(uf.same(0, 7), true);
assert_eq!(uf.same(0, 1), false);
assert_eq!(uf.len(0), 5);
assert_eq!(uf.len(3), 5);
assert_eq!(uf.represent(6), 6);
}
| 20 | 56 | 0.57381 |
8a250b71bf70e415af76b460821222c34e32ba1c | 2,027 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{format_err, Result};
use aptos_rest_client::Client as RestClient;
use reqwest::{Client, Url};
use std::{
fmt,
str::FromStr,
time::{Duration, Instant},
};
use tokio::time;
#[derive(Clone)]
pub struct Instance {
peer_name: String,
ip: String,
ac_port: u32,
debug_interface_port: Option<u32>,
// todo: remove this, no where is using it
http_client: Client,
}
impl Instance {
pub fn new(
peer_name: String,
ip: String,
ac_port: u32,
debug_interface_port: Option<u32>,
http_client: Client,
) -> Instance {
Instance {
peer_name,
ip,
ac_port,
debug_interface_port,
http_client,
}
}
pub async fn wait_server_ready(&self, deadline: Instant) -> Result<()> {
while self.rest_client().get_ledger_information().await.is_err() {
if Instant::now() > deadline {
return Err(format_err!("wait_server_ready for {} timed out", self));
}
time::sleep(Duration::from_secs(3)).await;
}
Ok(())
}
pub fn peer_name(&self) -> &String {
&self.peer_name
}
pub fn ip(&self) -> &String {
&self.ip
}
pub fn ac_port(&self) -> u32 {
self.ac_port
}
pub fn api_url(&self) -> Url {
Url::from_str(&format!("http://{}:{}", self.ip(), self.ac_port())).expect("Invalid URL.")
}
pub fn debug_interface_port(&self) -> Option<u32> {
self.debug_interface_port
}
pub fn rest_client(&self) -> RestClient {
RestClient::new(self.api_url())
}
}
impl fmt::Display for Instance {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self.peer_name, self.ip)
}
}
impl fmt::Debug for Instance {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
| 23.298851 | 97 | 0.559941 |
760836b33911d24f20e16a187bbb57f7a2b7ea03 | 1,399 | mod function;
mod record;
use self::function::parse_function;
use self::record::parse_record;
use crate::parser::{CompletedMarker, Parser};
use crate::token_set::TokenSet;
use syntax::{NodeKind, TokenKind};
pub(super) const DEF_FIRST: TokenSet =
TokenSet::new([TokenKind::FncKw, TokenKind::RecKw, TokenKind::DocCommentLeader]);
pub(super) fn parse_def(p: &mut Parser<'_>) -> Option<CompletedMarker> {
let docs_cm = if p.at(TokenKind::DocCommentLeader) { Some(parse_docs(p)) } else { None };
let _guard = p.expected_syntax_name("definition");
if p.at(TokenKind::FncKw) {
let m = match docs_cm {
Some(cm) => cm.precede(p),
None => p.start(),
};
return Some(parse_function(p, m));
} else if p.at(TokenKind::RecKw) {
let m = match docs_cm {
Some(cm) => cm.precede(p),
None => p.start(),
};
return Some(parse_record(p, m));
}
p.error_with_recovery_set_no_default(TokenSet::default())
}
fn parse_docs(p: &mut Parser<'_>) -> CompletedMarker {
assert!(p.at(TokenKind::DocCommentLeader));
let m = p.start();
while p.at(TokenKind::DocCommentLeader) {
let m = p.start();
p.bump();
if p.at(TokenKind::DocCommentContents) {
p.bump();
}
m.complete(p, NodeKind::DocComment);
}
m.complete(p, NodeKind::Docs)
}
| 27.98 | 93 | 0.608292 |
332f61340aabb0bdd6ea5ce8281dfd2208489393 | 34,553 | use std::env;
use std::fmt;
use std::fs::{self, File};
use std::mem;
use std::path::{Path, PathBuf};
use std::process::Command;
use curl::easy::{Easy, List};
use git2::{self, ObjectType};
use log::{debug, info};
use serde::ser;
use serde::Serialize;
use url::Url;
use crate::core::GitReference;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::process_builder::process;
use crate::util::{internal, network, Config, Progress, ToUrl};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
impl ser::Serialize for GitRevision {
fn serialize<S: ser::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
serialize_str(self, s)
}
}
fn serialize_str<T, S>(t: &T, s: S) -> Result<S::Ok, S::Error>
where
T: fmt::Display,
S: ser::Serializer,
{
s.collect_str(t)
}
impl fmt::Display for GitRevision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
pub struct GitShortID(git2::Buf);
impl GitShortID {
pub fn as_str(&self) -> &str {
self.0.as_str().unwrap()
}
}
/// `GitRemote` represents a remote repository. It gets cloned into a local
/// `GitDatabase`.
#[derive(PartialEq, Clone, Debug, Serialize)]
pub struct GitRemote {
#[serde(serialize_with = "serialize_str")]
url: Url,
}
/// `GitDatabase` is a local clone of a remote repository's database. Multiple
/// `GitCheckouts` can be cloned from this `GitDatabase`.
#[derive(Serialize)]
pub struct GitDatabase {
remote: GitRemote,
path: PathBuf,
#[serde(skip_serializing)]
repo: git2::Repository,
}
/// `GitCheckout` is a local checkout of a particular revision. Calling
/// `clone_into` with a reference will resolve the reference into a revision,
/// and return a `failure::Error` if no revision for that reference was found.
#[derive(Serialize)]
pub struct GitCheckout<'a> {
database: &'a GitDatabase,
location: PathBuf,
revision: GitRevision,
#[serde(skip_serializing)]
repo: git2::Repository,
}
// Implementations
impl GitRemote {
pub fn new(url: &Url) -> GitRemote {
GitRemote { url: url.clone() }
}
pub fn url(&self) -> &Url {
&self.url
}
pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> {
reference.resolve(&self.db_at(path)?.repo)
}
pub fn checkout(
&self,
into: &Path,
reference: &GitReference,
cargo_config: &Config,
) -> CargoResult<(GitDatabase, GitRevision)> {
let mut repo_and_rev = None;
if let Ok(mut repo) = git2::Repository::open(into) {
self.fetch_into(&mut repo, cargo_config)
.chain_err(|| format!("failed to fetch into {}", into.display()))?;
if let Ok(rev) = reference.resolve(&repo) {
repo_and_rev = Some((repo, rev));
}
}
let (repo, rev) = match repo_and_rev {
Some(pair) => pair,
None => {
let repo = self
.clone_into(into, cargo_config)
.chain_err(|| format!("failed to clone into: {}", into.display()))?;
let rev = reference.resolve(&repo)?;
(repo, rev)
}
};
Ok((
GitDatabase {
remote: self.clone(),
path: into.to_path_buf(),
repo,
},
rev,
))
}
pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> {
let repo = git2::Repository::open(db_path)?;
Ok(GitDatabase {
remote: self.clone(),
path: db_path.to_path_buf(),
repo,
})
}
fn fetch_into(&self, dst: &mut git2::Repository, cargo_config: &Config) -> CargoResult<()> {
// Create a local anonymous remote in the repository to fetch the url
let refspec = "refs/heads/*:refs/heads/*";
fetch(dst, &self.url, refspec, cargo_config)
}
fn clone_into(&self, dst: &Path, cargo_config: &Config) -> CargoResult<git2::Repository> {
if fs::metadata(&dst).is_ok() {
paths::remove_dir_all(dst)?;
}
fs::create_dir_all(dst)?;
let mut repo = init(dst, true)?;
fetch(
&mut repo,
&self.url,
"refs/heads/*:refs/heads/*",
cargo_config,
)?;
Ok(repo)
}
}
impl GitDatabase {
pub fn copy_to(
&self,
rev: GitRevision,
dest: &Path,
cargo_config: &Config,
) -> CargoResult<GitCheckout<'_>> {
let mut checkout = None;
if let Ok(repo) = git2::Repository::open(dest) {
let mut co = GitCheckout::new(dest, self, rev.clone(), repo);
if !co.is_fresh() {
// After a successful fetch operation do a sanity check to
// ensure we've got the object in our database to reset to. This
// can fail sometimes for corrupt repositories where the fetch
// operation succeeds but the object isn't actually there.
co.fetch(cargo_config)?;
if co.has_object() {
co.reset(cargo_config)?;
assert!(co.is_fresh());
checkout = Some(co);
}
} else {
checkout = Some(co);
}
};
let checkout = match checkout {
Some(c) => c,
None => GitCheckout::clone_into(dest, self, rev, cargo_config)?,
};
checkout.update_submodules(cargo_config)?;
Ok(checkout)
}
pub fn to_short_id(&self, revision: &GitRevision) -> CargoResult<GitShortID> {
let obj = self.repo.find_object(revision.0, None)?;
Ok(GitShortID(obj.short_id()?))
}
pub fn has_ref(&self, reference: &str) -> CargoResult<()> {
self.repo.revparse_single(reference)?;
Ok(())
}
}
impl GitReference {
fn resolve(&self, repo: &git2::Repository) -> CargoResult<GitRevision> {
let id = match *self {
GitReference::Tag(ref s) => (|| -> CargoResult<git2::Oid> {
let refname = format!("refs/tags/{}", s);
let id = repo.refname_to_id(&refname)?;
let obj = repo.find_object(id, None)?;
let obj = obj.peel(ObjectType::Commit)?;
Ok(obj.id())
})()
.chain_err(|| format!("failed to find tag `{}`", s))?,
GitReference::Branch(ref s) => {
let b = repo
.find_branch(s, git2::BranchType::Local)
.chain_err(|| format!("failed to find branch `{}`", s))?;
b.get()
.target()
.ok_or_else(|| failure::format_err!("branch `{}` did not have a target", s))?
}
GitReference::Rev(ref s) => {
let obj = repo.revparse_single(s)?;
match obj.as_tag() {
Some(tag) => tag.target_id(),
None => obj.id(),
}
}
};
Ok(GitRevision(id))
}
}
impl<'a> GitCheckout<'a> {
fn new(
path: &Path,
database: &'a GitDatabase,
revision: GitRevision,
repo: git2::Repository,
) -> GitCheckout<'a> {
GitCheckout {
location: path.to_path_buf(),
database,
revision,
repo,
}
}
fn clone_into(
into: &Path,
database: &'a GitDatabase,
revision: GitRevision,
config: &Config,
) -> CargoResult<GitCheckout<'a>> {
let dirname = into.parent().unwrap();
fs::create_dir_all(&dirname)
.chain_err(|| format!("Couldn't mkdir {}", dirname.display()))?;
if into.exists() {
paths::remove_dir_all(into)?;
}
// we're doing a local filesystem-to-filesystem clone so there should
// be no need to respect global configuration options, so pass in
// an empty instance of `git2::Config` below.
let git_config = git2::Config::new()?;
// Clone the repository, but make sure we use the "local" option in
// libgit2 which will attempt to use hardlinks to set up the database.
// This should speed up the clone operation quite a bit if it works.
//
// Note that we still use the same fetch options because while we don't
// need authentication information we may want progress bars and such.
let url = database.path.to_url()?;
let mut repo = None;
with_fetch_options(&git_config, &url, config, &mut |fopts| {
let mut checkout = git2::build::CheckoutBuilder::new();
checkout.dry_run(); // we'll do this below during a `reset`
let r = git2::build::RepoBuilder::new()
// use hard links and/or copy the database, we're doing a
// filesystem clone so this'll speed things up quite a bit.
.clone_local(git2::build::CloneLocal::Local)
.with_checkout(checkout)
.fetch_options(fopts)
// .remote_create(|repo, _name, url| repo.remote_anonymous(url))
.clone(url.as_str(), into)?;
repo = Some(r);
Ok(())
})?;
let repo = repo.unwrap();
let checkout = GitCheckout::new(into, database, revision, repo);
checkout.reset(config)?;
Ok(checkout)
}
fn is_fresh(&self) -> bool {
match self.repo.revparse_single("HEAD") {
Ok(ref head) if head.id() == self.revision.0 => {
// See comments in reset() for why we check this
self.location.join(".cargo-ok").exists()
}
_ => false,
}
}
fn fetch(&mut self, cargo_config: &Config) -> CargoResult<()> {
info!("fetch {}", self.repo.path().display());
let url = self.database.path.to_url()?;
let refspec = "refs/heads/*:refs/heads/*";
fetch(&mut self.repo, &url, refspec, cargo_config)?;
Ok(())
}
fn has_object(&self) -> bool {
self.repo.find_object(self.revision.0, None).is_ok()
}
fn reset(&self, config: &Config) -> CargoResult<()> {
// If we're interrupted while performing this reset (e.g. we die because
// of a signal) Cargo needs to be sure to try to check out this repo
// again on the next go-round.
//
// To enable this we have a dummy file in our checkout, .cargo-ok, which
// if present means that the repo has been successfully reset and is
// ready to go. Hence if we start to do a reset, we make sure this file
// *doesn't* exist, and then once we're done we create the file.
let ok_file = self.location.join(".cargo-ok");
let _ = paths::remove_file(&ok_file);
info!("reset {} to {}", self.repo.path().display(), self.revision);
let object = self.repo.find_object(self.revision.0, None)?;
reset(&self.repo, &object, config)?;
File::create(ok_file)?;
Ok(())
}
fn update_submodules(&self, cargo_config: &Config) -> CargoResult<()> {
return update_submodules(&self.repo, cargo_config);
fn update_submodules(repo: &git2::Repository, cargo_config: &Config) -> CargoResult<()> {
info!("update submodules for: {:?}", repo.workdir().unwrap());
for mut child in repo.submodules()? {
update_submodule(repo, &mut child, cargo_config).chain_err(|| {
format!(
"failed to update submodule `{}`",
child.name().unwrap_or("")
)
})?;
}
Ok(())
}
fn update_submodule(
parent: &git2::Repository,
child: &mut git2::Submodule<'_>,
cargo_config: &Config,
) -> CargoResult<()> {
child.init(false)?;
let url = child
.url()
.ok_or_else(|| internal("non-utf8 url for submodule"))?;
// A submodule which is listed in .gitmodules but not actually
// checked out will not have a head id, so we should ignore it.
let head = match child.head_id() {
Some(head) => head,
None => return Ok(()),
};
// If the submodule hasn't been checked out yet, we need to
// clone it. If it has been checked out and the head is the same
// as the submodule's head, then we can skip an update and keep
// recursing.
let head_and_repo = child.open().and_then(|repo| {
let target = repo.head()?.target();
Ok((target, repo))
});
let mut repo = match head_and_repo {
Ok((head, repo)) => {
if child.head_id() == head {
return update_submodules(&repo, cargo_config);
}
repo
}
Err(..) => {
let path = parent.workdir().unwrap().join(child.path());
let _ = paths::remove_dir_all(&path);
init(&path, false)?
}
};
// Fetch data from origin and reset to the head commit
let refspec = "refs/heads/*:refs/heads/*";
let url = url.to_url()?;
fetch(&mut repo, &url, refspec, cargo_config).chain_err(|| {
internal(format!(
"failed to fetch submodule `{}` from {}",
child.name().unwrap_or(""),
url
))
})?;
let obj = repo.find_object(head, None)?;
reset(&repo, &obj, cargo_config)?;
update_submodules(&repo, cargo_config)
}
}
}
/// Prepare the authentication callbacks for cloning a git repository.
///
/// The main purpose of this function is to construct the "authentication
/// callback" which is used to clone a repository. This callback will attempt to
/// find the right authentication on the system (without user input) and will
/// guide libgit2 in doing so.
///
/// The callback is provided `allowed` types of credentials, and we try to do as
/// much as possible based on that:
///
/// * Prioritize SSH keys from the local ssh agent as they're likely the most
/// reliable. The username here is prioritized from the credential
/// callback, then from whatever is configured in git itself, and finally
/// we fall back to the generic user of `git`.
///
/// * If a username/password is allowed, then we fallback to git2-rs's
/// implementation of the credential helper. This is what is configured
/// with `credential.helper` in git, and is the interface for the OSX
/// keychain, for example.
///
/// * After the above two have failed, we just kinda grapple attempting to
/// return *something*.
///
/// If any form of authentication fails, libgit2 will repeatedly ask us for
/// credentials until we give it a reason to not do so. To ensure we don't
/// just sit here looping forever we keep track of authentications we've
/// attempted and we don't try the same ones again.
fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T>
where
F: FnMut(&mut git2::Credentials<'_>) -> CargoResult<T>,
{
let mut cred_helper = git2::CredentialHelper::new(url);
cred_helper.config(cfg);
let mut ssh_username_requested = false;
let mut cred_helper_bad = None;
let mut ssh_agent_attempts = Vec::new();
let mut any_attempts = false;
let mut tried_sshkey = false;
let mut res = f(&mut |url, username, allowed| {
any_attempts = true;
// libgit2's "USERNAME" authentication actually means that it's just
// asking us for a username to keep going. This is currently only really
// used for SSH authentication and isn't really an authentication type.
// The logic currently looks like:
//
// let user = ...;
// if (user.is_null())
// user = callback(USERNAME, null, ...);
//
// callback(SSH_KEY, user, ...)
//
// So if we're being called here then we know that (a) we're using ssh
// authentication and (b) no username was specified in the URL that
// we're trying to clone. We need to guess an appropriate username here,
// but that may involve a few attempts. Unfortunately we can't switch
// usernames during one authentication session with libgit2, so to
// handle this we bail out of this authentication session after setting
// the flag `ssh_username_requested`, and then we handle this below.
if allowed.contains(git2::CredentialType::USERNAME) {
debug_assert!(username.is_none());
ssh_username_requested = true;
return Err(git2::Error::from_str("gonna try usernames later"));
}
// An "SSH_KEY" authentication indicates that we need some sort of SSH
// authentication. This can currently either come from the ssh-agent
// process or from a raw in-memory SSH key. Cargo only supports using
// ssh-agent currently.
//
// If we get called with this then the only way that should be possible
// is if a username is specified in the URL itself (e.g. `username` is
// Some), hence the unwrap() here. We try custom usernames down below.
if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_sshkey {
// If ssh-agent authentication fails, libgit2 will keep
// calling this callback asking for other authentication
// methods to try. Make sure we only try ssh-agent once,
// to avoid looping forever.
tried_sshkey = true;
let username = username.unwrap();
debug_assert!(!ssh_username_requested);
ssh_agent_attempts.push(username.to_string());
return git2::Cred::ssh_key_from_agent(username);
}
// Sometimes libgit2 will ask for a username/password in plaintext. This
// is where Cargo would have an interactive prompt if we supported it,
// but we currently don't! Right now the only way we support fetching a
// plaintext password is through the `credential.helper` support, so
// fetch that here.
if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
let r = git2::Cred::credential_helper(cfg, url, username);
cred_helper_bad = Some(r.is_err());
return r;
}
// I'm... not sure what the DEFAULT kind of authentication is, but seems
// easy to support?
if allowed.contains(git2::CredentialType::DEFAULT) {
return git2::Cred::default();
}
// Whelp, we tried our best
Err(git2::Error::from_str("no authentication available"))
});
// Ok, so if it looks like we're going to be doing ssh authentication, we
// want to try a few different usernames as one wasn't specified in the URL
// for us to use. In order, we'll try:
//
// * A credential helper's username for this URL, if available.
// * This account's username.
// * "git"
//
// We have to restart the authentication session each time (due to
// constraints in libssh2 I guess? maybe this is inherent to ssh?), so we
// call our callback, `f`, in a loop here.
if ssh_username_requested {
debug_assert!(res.is_err());
let mut attempts = Vec::new();
attempts.push("git".to_string());
if let Ok(s) = env::var("USER").or_else(|_| env::var("USERNAME")) {
attempts.push(s);
}
if let Some(ref s) = cred_helper.username {
attempts.push(s.clone());
}
while let Some(s) = attempts.pop() {
// We should get `USERNAME` first, where we just return our attempt,
// and then after that we should get `SSH_KEY`. If the first attempt
// fails we'll get called again, but we don't have another option so
// we bail out.
let mut attempts = 0;
res = f(&mut |_url, username, allowed| {
if allowed.contains(git2::CredentialType::USERNAME) {
return git2::Cred::username(&s);
}
if allowed.contains(git2::CredentialType::SSH_KEY) {
debug_assert_eq!(Some(&s[..]), username);
attempts += 1;
if attempts == 1 {
ssh_agent_attempts.push(s.to_string());
return git2::Cred::ssh_key_from_agent(&s);
}
}
Err(git2::Error::from_str("no authentication available"))
});
// If we made two attempts then that means:
//
// 1. A username was requested, we returned `s`.
// 2. An ssh key was requested, we returned to look up `s` in the
// ssh agent.
// 3. For whatever reason that lookup failed, so we were asked again
// for another mode of authentication.
//
// Essentially, if `attempts == 2` then in theory the only error was
// that this username failed to authenticate (e.g. no other network
// errors happened). Otherwise something else is funny so we bail
// out.
if attempts != 2 {
break;
}
}
}
if res.is_ok() || !any_attempts {
return res.map_err(From::from);
}
// In the case of an authentication failure (where we tried something) then
// we try to give a more helpful error message about precisely what we
// tried.
let res = res.map_err(failure::Error::from).chain_err(|| {
let mut msg = "failed to authenticate when downloading \
repository"
.to_string();
if !ssh_agent_attempts.is_empty() {
let names = ssh_agent_attempts
.iter()
.map(|s| format!("`{}`", s))
.collect::<Vec<_>>()
.join(", ");
msg.push_str(&format!(
"\nattempted ssh-agent authentication, but \
none of the usernames {} succeeded",
names
));
}
if let Some(failed_cred_helper) = cred_helper_bad {
if failed_cred_helper {
msg.push_str(
"\nattempted to find username/password via \
git's `credential.helper` support, but failed",
);
} else {
msg.push_str(
"\nattempted to find username/password via \
`credential.helper`, but maybe the found \
credentials were incorrect",
);
}
}
msg
})?;
Ok(res)
}
fn reset(repo: &git2::Repository, obj: &git2::Object<'_>, config: &Config) -> CargoResult<()> {
let mut pb = Progress::new("Checkout", config);
let mut opts = git2::build::CheckoutBuilder::new();
opts.progress(|_, cur, max| {
drop(pb.tick(cur, max));
});
repo.reset(obj, git2::ResetType::Hard, Some(&mut opts))?;
Ok(())
}
pub fn with_fetch_options(
git_config: &git2::Config,
url: &Url,
config: &Config,
cb: &mut dyn FnMut(git2::FetchOptions<'_>) -> CargoResult<()>,
) -> CargoResult<()> {
let mut progress = Progress::new("Fetch", config);
network::with_retry(config, || {
with_authentication(url.as_str(), git_config, |f| {
let mut rcb = git2::RemoteCallbacks::new();
rcb.credentials(f);
rcb.transfer_progress(|stats| {
progress
.tick(stats.indexed_objects(), stats.total_objects())
.is_ok()
});
// Create a local anonymous remote in the repository to fetch the
// url
let mut opts = git2::FetchOptions::new();
opts.remote_callbacks(rcb)
.download_tags(git2::AutotagOption::All);
cb(opts)
})?;
Ok(())
})
}
pub fn fetch(
repo: &mut git2::Repository,
url: &Url,
refspec: &str,
config: &Config,
) -> CargoResult<()> {
if config.frozen() {
failure::bail!(
"attempting to update a git repository, but --frozen \
was specified"
)
}
if !config.network_allowed() {
failure::bail!("can't update a git repository in the offline mode")
}
// If we're fetching from GitHub, attempt GitHub's special fast path for
// testing if we've already got an up-to-date copy of the repository
if url.host_str() == Some("github.com") {
if let Ok(oid) = repo.refname_to_id("refs/remotes/origin/master") {
let mut handle = config.http()?.borrow_mut();
debug!("attempting GitHub fast path for {}", url);
if github_up_to_date(&mut handle, url, &oid) {
return Ok(());
} else {
debug!("fast path failed, falling back to a git fetch");
}
}
}
// We reuse repositories quite a lot, so before we go through and update the
// repo check to see if it's a little too old and could benefit from a gc.
// In theory this shouldn't be too too expensive compared to the network
// request we're about to issue.
maybe_gc_repo(repo)?;
// Unfortuantely `libgit2` is notably lacking in the realm of authentication
// when compared to the `git` command line. As a result, allow an escape
// hatch for users that would prefer to use `git`-the-CLI for fetching
// repositories instead of `libgit2`-the-library. This should make more
// flavors of authentication possible while also still giving us all the
// speed and portability of using `libgit2`.
if let Some(val) = config.get_bool("net.git-fetch-with-cli")? {
if val.val {
return fetch_with_cli(repo, url, refspec, config);
}
}
debug!("doing a fetch for {}", url);
let git_config = git2::Config::open_default()?;
with_fetch_options(&git_config, url, config, &mut |mut opts| {
// The `fetch` operation here may fail spuriously due to a corrupt
// repository. It could also fail, however, for a whole slew of other
// reasons (aka network related reasons). We want Cargo to automatically
// recover from corrupt repositories, but we don't want Cargo to stomp
// over other legitimate errors.o
//
// Consequently we save off the error of the `fetch` operation and if it
// looks like a "corrupt repo" error then we blow away the repo and try
// again. If it looks like any other kind of error, or if we've already
// blown away the repository, then we want to return the error as-is.
let mut repo_reinitialized = false;
loop {
debug!("initiating fetch of {} from {}", refspec, url);
let res = repo
.remote_anonymous(url.as_str())?
.fetch(&[refspec], Some(&mut opts), None);
let err = match res {
Ok(()) => break,
Err(e) => e,
};
debug!("fetch failed: {}", err);
if !repo_reinitialized && err.class() == git2::ErrorClass::Reference {
repo_reinitialized = true;
debug!(
"looks like this is a corrupt repository, reinitializing \
and trying again"
);
if reinitialize(repo).is_ok() {
continue;
}
}
return Err(err.into());
}
Ok(())
})
}
fn fetch_with_cli(
repo: &mut git2::Repository,
url: &Url,
refspec: &str,
config: &Config,
) -> CargoResult<()> {
let mut cmd = process("git");
cmd.arg("fetch")
.arg("--tags") // fetch all tags
.arg("--quiet")
.arg("--update-head-ok") // see discussion in #2078
.arg(url.to_string())
.arg(refspec)
.cwd(repo.path());
config
.shell()
.verbose(|s| s.status("Running", &cmd.to_string()))?;
cmd.exec()?;
Ok(())
}
/// Cargo has a bunch of long-lived git repositories in its global cache and
/// some, like the index, are updated very frequently. Right now each update
/// creates a new "pack file" inside the git database, and over time this can
/// cause bad performance and bad current behavior in libgit2.
///
/// One pathological use case today is where libgit2 opens hundreds of file
/// descriptors, getting us dangerously close to blowing out the OS limits of
/// how many fds we can have open. This is detailed in #4403.
///
/// To try to combat this problem we attempt a `git gc` here. Note, though, that
/// we may not even have `git` installed on the system! As a result we
/// opportunistically try a `git gc` when the pack directory looks too big, and
/// failing that we just blow away the repository and start over.
fn maybe_gc_repo(repo: &mut git2::Repository) -> CargoResult<()> {
// Here we arbitrarily declare that if you have more than 100 files in your
// `pack` folder that we need to do a gc.
let entries = match repo.path().join("objects/pack").read_dir() {
Ok(e) => e.count(),
Err(_) => {
debug!("skipping gc as pack dir appears gone");
return Ok(());
}
};
let max = env::var("__CARGO_PACKFILE_LIMIT")
.ok()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(100);
if entries < max {
debug!("skipping gc as there's only {} pack files", entries);
return Ok(());
}
// First up, try a literal `git gc` by shelling out to git. This is pretty
// likely to fail though as we may not have `git` installed. Note that
// libgit2 doesn't currently implement the gc operation, so there's no
// equivalent there.
match Command::new("git")
.arg("gc")
.current_dir(repo.path())
.output()
{
Ok(out) => {
debug!(
"git-gc status: {}\n\nstdout ---\n{}\nstderr ---\n{}",
out.status,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
if out.status.success() {
let new = git2::Repository::open(repo.path())?;
mem::replace(repo, new);
return Ok(());
}
}
Err(e) => debug!("git-gc failed to spawn: {}", e),
}
// Alright all else failed, let's start over.
reinitialize(repo)
}
fn reinitialize(repo: &mut git2::Repository) -> CargoResult<()> {
// Here we want to drop the current repository object pointed to by `repo`,
// so we initialize temporary repository in a sub-folder, blow away the
// existing git folder, and then recreate the git repo. Finally we blow away
// the `tmp` folder we allocated.
let path = repo.path().to_path_buf();
debug!("reinitializing git repo at {:?}", path);
let tmp = path.join("tmp");
let bare = !repo.path().ends_with(".git");
*repo = init(&tmp, false)?;
for entry in path.read_dir()? {
let entry = entry?;
if entry.file_name().to_str() == Some("tmp") {
continue;
}
let path = entry.path();
drop(paths::remove_file(&path).or_else(|_| paths::remove_dir_all(&path)));
}
*repo = init(&path, bare)?;
paths::remove_dir_all(&tmp)?;
Ok(())
}
fn init(path: &Path, bare: bool) -> CargoResult<git2::Repository> {
let mut opts = git2::RepositoryInitOptions::new();
// Skip anyting related to templates, they just call all sorts of issues as
// we really don't want to use them yet they insist on being used. See #6240
// for an example issue that comes up.
opts.external_template(false);
opts.bare(bare);
Ok(git2::Repository::init_opts(&path, &opts)?)
}
/// Updating the index is done pretty regularly so we want it to be as fast as
/// possible. For registries hosted on GitHub (like the crates.io index) there's
/// a fast path available to use [1] to tell us that there's no updates to be
/// made.
///
/// This function will attempt to hit that fast path and verify that the `oid`
/// is actually the current `master` branch of the repository. If `true` is
/// returned then no update needs to be performed, but if `false` is returned
/// then the standard update logic still needs to happen.
///
/// [1]: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference
///
/// Note that this function should never cause an actual failure because it's
/// just a fast path. As a result all errors are ignored in this function and we
/// just return a `bool`. Any real errors will be reported through the normal
/// update path above.
fn github_up_to_date(handle: &mut Easy, url: &Url, oid: &git2::Oid) -> bool {
macro_rules! r#try {
($e:expr) => {
match $e {
Some(e) => e,
None => return false,
}
};
}
// This expects GitHub urls in the form `github.com/user/repo` and nothing
// else
let mut pieces = r#try!(url.path_segments());
let username = r#try!(pieces.next());
let repo = r#try!(pieces.next());
if pieces.next().is_some() {
return false;
}
let url = format!(
"https://api.github.com/repos/{}/{}/commits/master",
username, repo
);
r#try!(handle.get(true).ok());
r#try!(handle.url(&url).ok());
r#try!(handle.useragent("cargo").ok());
let mut headers = List::new();
r#try!(headers.append("Accept: application/vnd.github.3.sha").ok());
r#try!(headers.append(&format!("If-None-Match: \"{}\"", oid)).ok());
r#try!(handle.http_headers(headers).ok());
r#try!(handle.perform().ok());
r#try!(handle.response_code().ok()) == 304
}
| 37.598477 | 97 | 0.565132 |
56f36c793494d61979f2d61f6b25abf43d833a75 | 1,600 | // slug string A human-readable string that is used as a unique
// identifier for each region.
// name string The display name of the region. This will be a full
// name that is used in the control panel and other interfaces.
// sizes array This attribute is set to an array which contains
// the identifying slugs for the sizes available in this region.
// available boolean This is a boolean value that represents whether new
// Droplets can be created in this region.
// features array This attribute is set to an array which contains
// features available in this region
use std::fmt;
use std::borrow::Cow;
use response::NamedResponse;
use response;
#[derive(Deserialize, Debug)]
pub struct Region {
pub name: String,
pub slug: String,
pub sizes: Vec<String>,
pub features: Vec<String>,
pub available: bool,
}
impl response::NotArray for Region {}
impl fmt::Display for Region {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"Name: {}\n\
Slug: {}\n\
Sizes:{}\n\
Features:{}\n\
Available: {}",
self.name,
self.slug,
self.sizes.iter().fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.features.iter().fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.available)
}
}
impl NamedResponse for Region {
fn name<'a>() -> Cow<'a, str> { "region".into() }
}
pub type Regions = Vec<Region>;
| 32 | 96 | 0.581875 |
bb7215dd8210026f6977ab040f469dfc391a72cf | 855 | // Copyright 2018 Guillaume Pinot (@TeXitoi) <[email protected]>
//
// 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.
use clap::Parser;
#[derive(Parser, Debug)]
struct MakeCookie {
#[clap(short, value_parser)]
s: String,
#[clap(subcommand, long)]
cmd: Command,
}
#[derive(Parser, Debug)]
enum Command {
/// Pound acorns into flour for cookie dough.
Pound {
#[clap(value_parser)]
acorns: u32,
},
Sparkle {
#[clap(short, value_parser)]
color: String,
},
}
fn main() {
let opt = MakeCookie::parse();
println!("{:?}", opt);
}
| 22.5 | 68 | 0.635088 |
fbf8cd563d550d5fd522e8c40ebd47d9cb912737 | 5,471 | use crate::db::db_client_connection;
use mongodb::{
bson::{self, doc, oid::ObjectId},
error::Error as MongodbError,
results::InsertOneResult,
Database,
};
pub async fn setup() -> Database {
let db = db_client_connection().await.unwrap();
drop_collections(&db).await;
insert_mocked_data(&db).await.unwrap();
db
}
fn random_id() -> ObjectId {
ObjectId::new()
}
async fn insert_mocked_data(db: &Database) -> Result<(), MongodbError> {
let organization_foo_id = random_id();
let organization_acme_id = random_id();
let user_foo_id = random_id();
let user_bar_id = random_id();
let user_dee_id = random_id();
let repository_tux_id = random_id();
let repository_mar_id = random_id();
let repository_bar_id = random_id();
let repository_dee_id = random_id();
let organization_foo = doc! {
"__typename": "Organization",
"_id": organization_foo_id,
"avatarUrl": "https://foo.com/avatar.jpg",
"login": "organization_foo",
"people": vec![doc!{ "_id": user_foo_id, "ref": "users" }],
"url": "https://github.com/foo",
};
let organization_acme = doc! {
"__typename": "Organization",
"_id": organization_acme_id,
"avatarUrl": "https://acme.com/avatar.jpg",
"login": "organization_acme",
"people": vec![
doc!{ "_id": user_foo_id, "ref": "users" },
doc!{ "_id": user_dee_id, "ref": "users" },
],
"url": "https://github.com/acme",
};
let organization_empty_org = doc! {
"__typename": "Organization",
"_id": random_id(),
"avatarUrl": "https://empty_org.com/avatar.jpg",
"login": "empty_org",
"people": vec![] as Vec<bson::Document>,
"url": "https://github.com/empty_org",
};
let user_foo = doc! {
"__typename": "User",
"_id": user_foo_id,
"avatarUrl": "https://foo.com/avatar.jpg",
"email": "[email protected]",
"followers": vec![
doc! { "_id": user_bar_id },
doc! { "_id": user_dee_id },
],
"login": "user_foo",
"organizations": vec![
doc! { "_id": organization_foo_id },
doc! { "_id": organization_acme_id },
],
"url":"https://github.com/foo",
};
let user_bar = doc! {
"__typename": "User",
"_id": user_bar_id,
"avatarUrl": "https://bar.com/avatar.jpg",
"email": "[email protected]",
"following": vec![
doc! { "_id": user_foo_id }
],
"followers": vec![
doc! { "_id": user_dee_id },
],
"login": "user_bar",
"starredRepositories": vec![
doc! { "_id": repository_tux_id },
doc! { "_id": repository_dee_id },
],
"url":"https://github.com/bar",
};
let user_dee = doc! {
"__typename": "User",
"_id": user_dee_id,
"avatarUrl": "https://dee.com/avatar.jpg",
"email": "[email protected]",
"following": vec![
doc! { "_id": user_foo_id },
doc! { "_id": user_bar_id },
],
"login": "user_dee",
"organizations": vec![doc! { "_id": organization_acme_id }],
"url":"https://github.com/bar",
};
let user_empty_user = doc! {
"__typename": "User",
"_id": random_id(),
"avatarUrl": "https://empty_user.com/avatar.jpg",
"email": "[email protected]",
"login": "empty_user",
"url":"https://github.com/empty_user",
};
let repository_tux = doc! {
"_id": repository_tux_id,
"forkCount": 9.0,
"name": "repository_tux",
"owner": { "_id": organization_acme_id, "ref": "organizations" }
};
let repository_mar = doc! {
"_id": repository_mar_id,
"forkCount": 12.0,
"name": "repository_mar",
"owner": { "_id": organization_acme_id, "ref": "organizations" }
};
let repository_bar = doc! {
"_id": repository_bar_id,
"forkCount": 2.0,
"name": "repository_bar",
"owner": { "_id": user_bar_id, "ref": "users" }
};
let repository_dee = doc! {
"_id": repository_dee_id,
"forkCount": 2.0,
"name": "repository_dee",
"owner": { "_id": user_dee_id, "ref": "users" }
};
insert_organization(db, organization_acme).await?;
insert_organization(db, organization_foo).await?;
insert_organization(db, organization_empty_org).await?;
insert_user(db, user_foo).await?;
insert_user(db, user_bar).await?;
insert_user(db, user_dee).await?;
insert_user(db, user_empty_user).await?;
insert_repository(db, repository_tux).await?;
insert_repository(db, repository_mar).await?;
insert_repository(db, repository_bar).await?;
insert_repository(db, repository_dee).await?;
Ok(())
}
async fn drop_collections(db: &Database) {
let orgs_collection = db.collection::<bson::Document>("organizations");
let repo_collection = db.collection::<bson::Document>("repositories");
let users_collection = db.collection::<bson::Document>("users");
orgs_collection.drop(None).await.unwrap();
repo_collection.drop(None).await.unwrap();
users_collection.drop(None).await.unwrap();
}
async fn insert_organization(db: &Database, document: bson::Document) -> Result<InsertOneResult, MongodbError> {
db.collection::<bson::Document>("organizations")
.insert_one(document, None)
.await
}
async fn insert_repository(db: &Database, document: bson::Document) -> Result<InsertOneResult, MongodbError> {
db.collection::<bson::Document>("repositories")
.insert_one(document, None)
.await
}
async fn insert_user(db: &Database, document: bson::Document) -> Result<InsertOneResult, MongodbError> {
db.collection::<bson::Document>("users")
.insert_one(document, None)
.await
}
| 30.06044 | 112 | 0.636081 |
5056cc50259864940dbec0668ce0ca91e0261b93 | 19,244 | // Copyright 2020 Evgeniy Reizner
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Based on https://github.com/Lokathor/wide (Zlib)
use bytemuck::cast;
#[cfg(feature = "simd")] use safe_arch::*;
use crate::wide::{u32x8, i32x8};
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
#[cfg(all(feature = "simd", target_feature = "avx"))]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
#[repr(C, align(32))]
pub struct f32x8(m256);
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
#[cfg(all(feature = "simd", target_feature = "sse2"))]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
#[repr(C, align(32))]
pub struct f32x8(m128, m128);
} else {
#[cfg(not(feature = "simd"))]
#[derive(Default, Clone, Copy, PartialEq, Debug)]
#[repr(C, align(32))]
pub struct f32x8([f32; 8]);
}
}
unsafe impl bytemuck::Zeroable for f32x8 {}
unsafe impl bytemuck::Pod for f32x8 {}
impl f32x8 {
pub fn splat(n: f32) -> Self {
cast([n, n, n, n, n, n, n, n])
}
pub fn floor(self) -> Self {
let roundtrip: f32x8 = cast(self.trunc_int().to_f32x8());
roundtrip - roundtrip.cmp_gt(self).blend(f32x8::splat(1.0), f32x8::default())
}
pub fn fract(self) -> Self {
self - self.floor()
}
pub fn normalize(self) -> Self {
self.max(f32x8::default()).min(f32x8::splat(1.0))
}
pub fn to_i32x8_bitcast(self) -> i32x8 {
bytemuck::cast(self)
}
pub fn to_u32x8_bitcast(self) -> u32x8 {
bytemuck::cast(self)
}
pub fn cmp_eq(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(cmp_op_mask_m256!(self.0, EqualOrdered, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(cmp_eq_mask_m128(self.0, rhs.0), cmp_eq_mask_m128(self.1, rhs.1))
} else {
Self(impl_x8_cmp!(self, eq, rhs, f32::from_bits(u32::MAX), 0.0))
}
}
}
pub fn cmp_ge(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(cmp_op_mask_m256!(self.0, GreaterEqualOrdered, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(cmp_ge_mask_m128(self.0, rhs.0), cmp_ge_mask_m128(self.1, rhs.1))
} else {
Self(impl_x8_cmp!(self, ge, rhs, f32::from_bits(u32::MAX), 0.0))
}
}
}
pub fn cmp_gt(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(cmp_op_mask_m256!(self.0, GreaterThanOrdered, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(cmp_gt_mask_m128(self.0, rhs.0), cmp_gt_mask_m128(self.1, rhs.1))
} else {
Self(impl_x8_cmp!(self, gt, rhs, f32::from_bits(u32::MAX), 0.0))
}
}
}
pub fn cmp_ne(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(cmp_op_mask_m256!(self.0, NotEqualOrdered, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(cmp_neq_mask_m128(self.0, rhs.0), cmp_neq_mask_m128(self.1, rhs.1))
} else {
Self(impl_x8_cmp!(self, ne, rhs, f32::from_bits(u32::MAX), 0.0))
}
}
}
pub fn cmp_le(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(cmp_op_mask_m256!(self.0, LessEqualOrdered, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(cmp_le_mask_m128(self.0, rhs.0), cmp_le_mask_m128(self.1, rhs.1))
} else {
Self(impl_x8_cmp!(self, le, rhs, f32::from_bits(u32::MAX), 0.0))
}
}
}
pub fn cmp_lt(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(cmp_op_mask_m256!(self.0, LessThanOrdered, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(cmp_lt_mask_m128(self.0, rhs.0), cmp_lt_mask_m128(self.1, rhs.1))
} else {
Self(impl_x8_cmp!(self, lt, rhs, f32::from_bits(u32::MAX), 0.0))
}
}
}
pub fn blend(self, t: Self, f: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(blend_varying_m256(f.0, t.0, self.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse4.1"))] {
Self(blend_varying_m128(f.0, t.0, self.0), blend_varying_m128(f.1, t.1, self.1))
} else {
super::generic_bit_blend(self, t, f)
}
}
}
pub fn abs(self) -> Self {
let non_sign_bits = f32x8::splat(f32::from_bits(i32::MAX as u32));
self & non_sign_bits
}
pub fn max(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(max_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(max_m128(self.0, rhs.0), max_m128(self.1, rhs.1))
} else {
Self(impl_x8_op!(self, max, rhs))
}
}
}
pub fn min(self, rhs: Self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(min_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(min_m128(self.0, rhs.0), min_m128(self.1, rhs.1))
} else {
Self(impl_x8_op!(self, min, rhs))
}
}
}
pub fn is_finite(self) -> Self {
let shifted_exp_mask = u32x8::splat(0xFF000000);
let u: u32x8 = cast(self);
let shift_u = u << 1;
let out = !(shift_u & shifted_exp_mask).cmp_eq(shifted_exp_mask);
cast(out)
}
pub fn round(self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(round_m256!(self.0, Nearest))
} else if #[cfg(all(feature = "simd", target_feature = "sse4.1"))] {
Self(round_m128!(self.0, Nearest), round_m128!(self.1, Nearest))
} else {
let to_int = f32x8::splat(1.0 / f32::EPSILON);
let u: u32x8 = cast(self);
let e: i32x8 = cast((u >> 23) & u32x8::splat(0xff));
let mut y: f32x8;
let no_op_magic = i32x8::splat(0x7f + 23);
let no_op_mask: f32x8 = cast(e.cmp_gt(no_op_magic) | e.cmp_eq(no_op_magic));
let no_op_val: f32x8 = self;
let zero_magic = i32x8::splat(0x7f - 1);
let zero_mask: f32x8 = cast(e.cmp_lt(zero_magic));
let zero_val: f32x8 = self * f32x8::splat(0.0);
let neg_bit: f32x8 = cast(cast::<u32x8, i32x8>(u).cmp_lt(i32x8::default()));
let x: f32x8 = neg_bit.blend(-self, self);
y = x + to_int - to_int - x;
y = y.cmp_gt(f32x8::splat(0.5)).blend(
y + x - f32x8::splat(-1.0),
y.cmp_lt(f32x8::splat(-0.5)).blend(y + x + f32x8::splat(1.0), y + x),
);
y = neg_bit.blend(-y, y);
no_op_mask.blend(no_op_val, zero_mask.blend(zero_val, y))
}
}
}
pub fn round_int(self) -> i32x8 {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
cast(convert_to_i32_m256i_from_m256(self.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
i32x8(
convert_to_i32_m128i_from_m128(self.0),
convert_to_i32_m128i_from_m128(self.1),
)
} else {
let rounded: [f32; 8] = cast(self.round());
let rounded_ints: i32x8 = cast([
rounded[0] as i32,
rounded[1] as i32,
rounded[2] as i32,
rounded[3] as i32,
rounded[4] as i32,
rounded[5] as i32,
rounded[6] as i32,
rounded[7] as i32,
]);
cast::<f32x8, i32x8>(self.is_finite()).blend(
rounded_ints,
i32x8::splat(i32::MIN)
)
}
}
}
pub fn trunc_int(self) -> i32x8 {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
cast(convert_truncate_to_i32_m256i_from_m256(self.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
i32x8(truncate_m128_to_m128i(self.0), truncate_m128_to_m128i(self.1))
} else {
let n: [f32; 8] = cast(self);
let ints: i32x8 = cast([
n[0].trunc() as i32,
n[1].trunc() as i32,
n[2].trunc() as i32,
n[3].trunc() as i32,
n[4].trunc() as i32,
n[5].trunc() as i32,
n[6].trunc() as i32,
n[7].trunc() as i32,
]);
cast::<f32x8, i32x8>(self.is_finite()).blend(ints,i32x8::splat(i32::MIN))
}
}
}
pub fn recip(self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(reciprocal_m256(self.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(reciprocal_m128(self.0), reciprocal_m128(self.1))
} else {
Self::from([
1.0 / self.0[0],
1.0 / self.0[1],
1.0 / self.0[2],
1.0 / self.0[3],
1.0 / self.0[4],
1.0 / self.0[5],
1.0 / self.0[6],
1.0 / self.0[7],
])
}
}
}
pub fn recip_sqrt(self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(reciprocal_sqrt_m256(self.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(reciprocal_sqrt_m128(self.0), reciprocal_sqrt_m128(self.1))
} else {
Self::from([
1.0 / self.0[0].sqrt(),
1.0 / self.0[1].sqrt(),
1.0 / self.0[2].sqrt(),
1.0 / self.0[3].sqrt(),
1.0 / self.0[4].sqrt(),
1.0 / self.0[5].sqrt(),
1.0 / self.0[6].sqrt(),
1.0 / self.0[7].sqrt(),
])
}
}
}
pub fn sqrt(self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(sqrt_m256(self.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(sqrt_m128(self.0), sqrt_m128(self.1))
} else {
Self::from([
self.0[0].sqrt(),
self.0[1].sqrt(),
self.0[2].sqrt(),
self.0[3].sqrt(),
self.0[4].sqrt(),
self.0[5].sqrt(),
self.0[6].sqrt(),
self.0[7].sqrt(),
])
}
}
}
}
impl From<[f32; 8]> for f32x8 {
fn from(v: [f32; 8]) -> Self {
cast(v)
}
}
impl From<f32x8> for [f32; 8] {
fn from(v: f32x8) -> Self {
cast(v)
}
}
impl std::ops::Add for f32x8 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(add_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(add_m128(self.0, rhs.0), add_m128(self.1, rhs.1))
} else {
Self(impl_x8_op!(self, add, rhs))
}
}
}
}
impl std::ops::AddAssign for f32x8 {
fn add_assign(&mut self, rhs: f32x8) {
*self = *self + rhs;
}
}
impl std::ops::Sub for f32x8 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(sub_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(sub_m128(self.0, rhs.0), sub_m128(self.1, rhs.1))
} else {
Self(impl_x8_op!(self, sub, rhs))
}
}
}
}
impl std::ops::Mul for f32x8 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(mul_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(mul_m128(self.0, rhs.0), mul_m128(self.1, rhs.1))
} else {
Self(impl_x8_op!(self, mul, rhs))
}
}
}
}
impl std::ops::MulAssign for f32x8 {
fn mul_assign(&mut self, rhs: f32x8) {
*self = *self * rhs;
}
}
impl std::ops::Div for f32x8 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(div_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(div_m128(self.0, rhs.0), div_m128(self.1, rhs.1))
} else {
Self(impl_x8_op!(self, div, rhs))
}
}
}
}
impl std::ops::BitAnd for f32x8 {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(bitand_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(bitand_m128(self.0, rhs.0), bitand_m128(self.1, rhs.1))
} else {
Self([
f32::from_bits(self.0[0].to_bits() & rhs.0[0].to_bits()),
f32::from_bits(self.0[1].to_bits() & rhs.0[1].to_bits()),
f32::from_bits(self.0[2].to_bits() & rhs.0[2].to_bits()),
f32::from_bits(self.0[3].to_bits() & rhs.0[3].to_bits()),
f32::from_bits(self.0[4].to_bits() & rhs.0[4].to_bits()),
f32::from_bits(self.0[5].to_bits() & rhs.0[5].to_bits()),
f32::from_bits(self.0[6].to_bits() & rhs.0[6].to_bits()),
f32::from_bits(self.0[7].to_bits() & rhs.0[7].to_bits()),
])
}
}
}
}
impl std::ops::BitOr for f32x8 {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(bitor_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(bitor_m128(self.0, rhs.0), bitor_m128(self.1, rhs.1))
} else {
Self([
f32::from_bits(self.0[0].to_bits() | rhs.0[0].to_bits()),
f32::from_bits(self.0[1].to_bits() | rhs.0[1].to_bits()),
f32::from_bits(self.0[2].to_bits() | rhs.0[2].to_bits()),
f32::from_bits(self.0[3].to_bits() | rhs.0[3].to_bits()),
f32::from_bits(self.0[4].to_bits() | rhs.0[4].to_bits()),
f32::from_bits(self.0[5].to_bits() | rhs.0[5].to_bits()),
f32::from_bits(self.0[6].to_bits() | rhs.0[6].to_bits()),
f32::from_bits(self.0[7].to_bits() | rhs.0[7].to_bits()),
])
}
}
}
}
impl std::ops::BitXor for f32x8 {
type Output = Self;
fn bitxor(self, rhs: Self) -> Self::Output {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(bitxor_m256(self.0, rhs.0))
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(bitxor_m128(self.0, rhs.0), bitxor_m128(self.1, rhs.1))
} else {
Self([
f32::from_bits(self.0[0].to_bits() ^ rhs.0[0].to_bits()),
f32::from_bits(self.0[1].to_bits() ^ rhs.0[1].to_bits()),
f32::from_bits(self.0[2].to_bits() ^ rhs.0[2].to_bits()),
f32::from_bits(self.0[3].to_bits() ^ rhs.0[3].to_bits()),
f32::from_bits(self.0[4].to_bits() ^ rhs.0[4].to_bits()),
f32::from_bits(self.0[5].to_bits() ^ rhs.0[5].to_bits()),
f32::from_bits(self.0[6].to_bits() ^ rhs.0[6].to_bits()),
f32::from_bits(self.0[7].to_bits() ^ rhs.0[7].to_bits()),
])
}
}
}
}
impl std::ops::Neg for f32x8 {
type Output = Self;
fn neg(self) -> Self {
Self::default() - self
}
}
impl std::ops::Not for f32x8 {
type Output = Self;
fn not(self) -> Self {
cfg_if::cfg_if! {
if #[cfg(all(feature = "simd", target_feature = "avx"))] {
Self(self.0.not())
} else if #[cfg(all(feature = "simd", target_feature = "sse2"))] {
Self(self.0.not(), self.1.not())
} else {
Self::from([
f32::from_bits(self.0[0].to_bits() ^ u32::MAX),
f32::from_bits(self.0[1].to_bits() ^ u32::MAX),
f32::from_bits(self.0[2].to_bits() ^ u32::MAX),
f32::from_bits(self.0[3].to_bits() ^ u32::MAX),
f32::from_bits(self.0[4].to_bits() ^ u32::MAX),
f32::from_bits(self.0[5].to_bits() ^ u32::MAX),
f32::from_bits(self.0[6].to_bits() ^ u32::MAX),
f32::from_bits(self.0[7].to_bits() ^ u32::MAX),
])
}
}
}
}
| 36.516129 | 96 | 0.468873 |
9ca7d9b5c1251d795bc0be19d77fbf8155a74e38 | 11,828 | use crate::domain;
use crate::reverse_proxy;
use bytes::Bytes;
use hyper::Method;
use std::fmt;
#[derive(PartialEq)]
struct CreateEvent {
event: domain::session::SessionStatus,
desired_capabilities: domain::DesiredCapabilities,
}
#[derive(PartialEq)]
struct CommandEvent {
event: domain::session::SessionStatus,
session_id: String,
url: String,
}
#[derive(PartialEq)]
struct DeleteEvent {
event: domain::session::SessionStatus,
session_id: String,
}
impl fmt::Display for CommandEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}] [{}] [{}]", self.event, self.session_id, self.url)
}
}
impl fmt::Display for CreateEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}] {}", self.event, self.desired_capabilities)
}
}
impl fmt::Display for DeleteEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}] [{}]", self.event, self.session_id)
}
}
pub async fn inspect<'m, 'b>(request: &reverse_proxy::CapturedRequest<'m, 'b>) {
let id = request.id.to_owned();
let method = request.method.to_owned();
let path = request.path.to_owned();
let body = request.body.to_owned();
if method == Method::DELETE {
info!("{}, Request Id : {}", capture_delete_event(path).await, id);
} else if method == Method::POST && is_a_new_session(&path) {
info!("{}, Request Id : {}", capture_create_event(&body).await, id);
} else if method == "POST" && !is_a_new_session(&path) {
if let Some(url_event) = capture_url_event(path, &body) {
info!("{}, Request Id : {}", url_event, id);
}
}
}
async fn capture_delete_event(path: String) -> DeleteEvent {
let session_id = session_id_of_path(path).unwrap_or_else(|| "".to_string());
DeleteEvent {
event: domain::session::SessionStatus::Deleting,
session_id,
}
}
/// Capture new sessions events
async fn capture_create_event(body: &Bytes) -> CreateEvent {
let capabilities: domain::Capabilities = serde_json::from_slice(body)
.map_err(|_| {
error!(
"Fail to deserialize the capabilities for the given payload : {}",
std::str::from_utf8(body).unwrap_or("cannot read the body")
);
})
.unwrap_or_else(|_| domain::Capabilities::new());
let desired_capabilities = capabilities.desired_capabilities;
CreateEvent {
event: domain::session::SessionStatus::Creating,
desired_capabilities,
}
}
/// Capture asked url events
fn capture_url_event(path: String, body: &Bytes) -> Option<CommandEvent> {
if path.contains("/url") {
let command: domain::Command = serde_json::from_slice(body)
.map_err(|_| {
error!(
"Fail to deserialize the capabilities for the given payload : {}",
std::str::from_utf8(body).unwrap_or("cannot read the body")
);
})
.unwrap_or_else(|_| domain::Command::new());
let session_id = session_id_of_path(path).unwrap_or_else(|| "".to_string());
// event | session_status | session ID | url_command | url
return Some(CommandEvent {
event: domain::session::SessionStatus::UrlCommand,
session_id,
url: command.url(),
});
}
None
}
/// Split the path to determine if it's a new session
/// (the path doesn't contain the session's id) or if it's
/// an existing session (the path contains the session's id).
/// If the head and the tail of the path are empty,
/// it's a new session event that we want to capture.
pub fn is_a_new_session(path: &str) -> bool {
let splitted_path: Vec<&str> = path
.split("/wd/hub/session")
.filter(|item| !item.is_empty())
.collect();
splitted_path.is_empty()
}
/// Split the given path and try to retrieve the
/// session id.
fn session_id_of_path(path: String) -> Option<String> {
// we only do the check if the path concerns a valid session endpoint
if !path.contains("wd/hub/session") {
return None;
}
// Try to get the session's id part
// e.g. possible patterns :
// /wd/hub/session
// /wd/hub/session/:id
// /wd/hub/session/:id/:cmd
let tail: Vec<&str> = path
.split("/wd/hub/session")
.filter(|item| !item.is_empty())
.collect();
// Check if there is a remainder with a session's id
// e.g. possible patterns :
// /:id
// /:id/:cmd
if !tail.is_empty() {
let remainder: Vec<&str> = tail[0].split('/').filter(|s| !s.is_empty()).collect();
if !remainder.is_empty() {
return Some(remainder[0].to_string());
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn capture_delete_event_should_return_a_well_formatted_log_with_the_session_id() {
let path = "/wd/hub/session/123";
let delete_event = capture_delete_event(path.to_string()).await;
let expected_delete_event = DeleteEvent {
event: domain::session::SessionStatus::Deleting,
session_id: "123".to_string(),
};
assert!(delete_event == expected_delete_event);
}
#[test]
fn session_id_of_path_returns_none_when_session_id_is_missing() {
let path: String = "/wd/hub/session//".to_string();
assert!(session_id_of_path(path).is_none());
}
#[test]
fn session_id_of_path_returns_some_when_session_id_exists() {
let path: String = "/wd/hub/session/123/screenshot".to_string();
assert_eq!(session_id_of_path(path), Some("123".to_string()));
}
#[test]
fn session_id_of_path_returns_none_when_path_is_malformed() {
let path: String = "/bad/hub/session/123/screenshot".to_string();
assert!(session_id_of_path(path).is_none());
}
#[tokio::test]
async fn capture_create_event_returns_a_struct_with_non_empty_desired_capabilities_when_the_http_request_is_valid(
) {
let desired: domain::DesiredCapabilities = domain::DesiredCapabilities {
browser_name: Some("chrome".to_string()),
platform: Some("LINUX".to_string()),
soda_user: Some("user123".to_string()),
};
let mock_post_http_request_body = r#"
{
"capabilities":{
"desiredCapabilities":{
"soda:user":"user123",
"browserName":"chrome",
"testLocal":"false",
"acceptSslCerts":true,
"platform":"LINUX"
},
"requiredCapabilities":{
}
},
"desiredCapabilities":{
"soda:user":"user123",
"browserName":"chrome",
"testLocal":"false",
"acceptSslCerts":true,
"platform":"LINUX"
},
"requiredCapabilities":{
}
}"#;
let body = Bytes::from(mock_post_http_request_body);
let create_event = capture_create_event(&body).await;
let expected_create_event = CreateEvent {
event: domain::SessionStatus::Creating,
desired_capabilities: desired,
};
assert!(create_event == expected_create_event);
}
#[tokio::test]
async fn capture_create_event_returns_a_struct_with_empty_capabilities_when_it_fails_to_deserialize_the_http_request(
) {
let mock_post_http_request_body = r#"
{
"capabilities":{
"desiredCapabilities":{
"soda:user":"",
"browserName":"",
"testLocal":"false",
"acceptSslCerts":true,
"platform":""
},
"requiredCapabilities":{
}
},
"desiredCapabilities":{
"soda:user":"",
"browserName":"",
"testLocal":"false",
"acceptSslCerts":true,
"platform":""
},
"requiredCapabilities":{
}
}"#;
let body = Bytes::from(mock_post_http_request_body);
let create_event = capture_create_event(&body).await;
let desired: domain::DesiredCapabilities = domain::DesiredCapabilities {
browser_name: Some("".to_string()),
platform: Some("".to_string()),
soda_user: Some("".to_string()),
};
let expected_create_event = CreateEvent {
event: domain::SessionStatus::Creating,
desired_capabilities: desired,
};
assert!(create_event == expected_create_event);
}
#[tokio::test]
async fn capture_delete_event_should_return_an_empty_session_id_when_there_is_an_unexpected_path(
) {
let path = "/bad/path/session/123";
let delete_event = capture_delete_event(path.to_string()).await;
let expected_delete_event = DeleteEvent {
event: domain::session::SessionStatus::Deleting,
session_id: "".to_string(),
};
assert!(delete_event == expected_delete_event);
}
#[tokio::test]
async fn capture_url_event_should_return_a_filled_command_event() {
let mock_post_http_request_body = r#"
{
"url":"https://duckduckgo.com/"
}"#;
let body = Bytes::from(mock_post_http_request_body);
let path = "/wd/hub/session/f52c41e5-3c3f-4cf3-9fe2-963e4a744aa7/url".to_string();
let expected_event = Some(CommandEvent {
event: domain::session::SessionStatus::UrlCommand,
session_id: "f52c41e5-3c3f-4cf3-9fe2-963e4a744aa7".to_string(),
url: "https://duckduckgo.com/".to_string(),
});
let capture_event = capture_url_event(path, &body);
assert!(capture_event == expected_event);
}
#[tokio::test]
async fn capture_url_event_should_return_none_when_the_path_does_not_contain_url() {
let mock_post_http_request_body = r#"
{
"url":"https://duckduckgo.com/"
}"#;
let body = Bytes::from(mock_post_http_request_body);
let path = "/wd/hub/session/f52c41e5-3c3f-4cf3-9fe2-963e4a744aa7".to_string();
let capture_event = capture_url_event(path, &body);
assert!(capture_event.is_none());
}
#[tokio::test]
async fn capture_url_event_should_return_an_empty_url_when_the_http_request_is_malformed() {
let mock_post_http_request_body = r#"
{
}"#;
let body = Bytes::from(mock_post_http_request_body);
let path = "/wd/hub/session/f52c41e5-3c3f-4cf3-9fe2-963e4a744aa7/url".to_string();
let expected_event = Some(CommandEvent {
event: domain::session::SessionStatus::UrlCommand,
session_id: "f52c41e5-3c3f-4cf3-9fe2-963e4a744aa7".to_string(),
url: "".to_string(),
});
let capture_event = capture_url_event(path, &body);
assert!(capture_event == expected_event);
}
#[test]
fn is_a_new_session_returns_true_when_the_path_does_not_contain_session_id() {
let path = "/wd/hub/session".to_string();
assert!(is_a_new_session(&path));
}
#[test]
fn is_a_new_session_returns_false_when_there_is_a_session_id() {
let path = "/wd/hub/session/123/screenshot".to_string();
assert!(!is_a_new_session(&path));
}
#[test]
fn is_a_new_session_returns_false_when_the_path_is_malformed() {
let path = "/wd/hub/session//screenshot".to_string();
assert!(!is_a_new_session(&path));
}
}
| 31.374005 | 121 | 0.595874 |
d660fbb16836470211d4e440d0000071027878f5 | 6,959 | use hyper;
use serde_json;
use crate::Client;
use crate::models::ApiResultExtendedAuction;
use crate::models::ApiResultAuctions;
use crate::models::AuctionRequest;
use hyper::{Method,header};
use async_trait::async_trait;
#[async_trait]
pub trait AuctionApi {
async fn auction_get(&self, id: &str) -> Result<ApiResultExtendedAuction,String>;
async fn auction_get_active(&self, options: AuctionRequest)
-> Result<ApiResultAuctions,String>;
}
#[async_trait]
impl AuctionApi for Client {
async fn auction_get(&self, id: &str) -> Result<ApiResultExtendedAuction,String> {
let token = &self.token;
let mut builder = hyper::Request::builder()
.method(Method::GET)
.header(header::AUTHORIZATION, format!("Bearer {token}"));
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/api/v1/auction/{id}?{}", self.base_path, query_string, id=id);
let uri: hyper::Uri = uri_str.parse().unwrap();
builder = builder.uri(uri);
let req = builder.body(hyper::Body::empty()).unwrap();
let resp = self.client.request(req).await;
match resp {
Ok(mut resp) => {
let bytes = hyper::body::to_bytes(resp.body_mut()).await.unwrap();
let result = String::from_utf8(bytes.into_iter().collect()).expect("");
match serde_json::from_str(&result) {
Ok(data) => Ok(data),
Err(err) => Err(format!("{:?}",err)),
}
}
Err(err) => Err(format!("{:?}",err)),
}
}
async fn auction_get_active(&self, options: AuctionRequest)
-> Result<ApiResultAuctions,String> {
let token = &self.token;
let mut builder = hyper::Request::builder()
.method(Method::GET)
.header(header::AUTHORIZATION, format!("Bearer {token}"));
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
if let Some(x) = &options.countries {
query.append_pair("request.countries", &x.join(",").to_string());
}
if let Some(x) = &options.ratings {
query.append_pair("request.ratings", &x.join(",").to_string());
}
if let Some(x) = &options.gender {
query.append_pair("request.gender", &x.to_string());
}
if let Some(x) = &options.sum_min {
query.append_pair("sumMin", &x.to_string());
}
if let Some(x) = &options.sum_max {
query.append_pair("sumMax", &x.to_string());
}
if let Some(x) = &options.terms {
let terms_str: String = x.iter().map( |&id| id.to_string() + ",").collect();
query.append_pair("request.terms", &terms_str);
}
if let Some(x) = &options.age_min {
query.append_pair("request.ageMin", &x.to_string());
}
if let Some(x) = &options.age_max {
query.append_pair("request.ageMax", &x.to_string());
}
if let Some(x) = &options.loan_number {
query.append_pair("request.loanNumber", &x.to_string());
}
if let Some(x) = &options.user_name {
query.append_pair("request.userName", &x.to_string());
}
if let Some(x) = &options.application_date_from {
query.append_pair("request.applicationDateFrom", &x.to_string());
}
if let Some(x) = &options.application_date_to {
query.append_pair("request.applicationDateTo", &x.to_string());
}
if let Some(x) = &options.credit_score_min {
query.append_pair("request.creditScoreMin", &x.to_string());
}
if let Some(x) = &options.credit_score_max {
query.append_pair("request.creditScoreMax", &x.to_string());
}
if let Some(x) = &options.credit_scores_ee_mini {
query.append_pair("request.creditScoresEeMini", &x.join(",").to_string());
}
if let Some(x) = &options.interest_min {
query.append_pair("request.interestMin", &x.to_string());
}
if let Some(x) = &options.interest_max {
query.append_pair("request.interestMax", &x.to_string());
}
if let Some(x) = &options.income_total_min {
query.append_pair("request.incomeTotalMin", &x.to_string());
}
if let Some(x) = &options.income_total_max {
query.append_pair("request.incomeTotalMax", &x.to_string());
}
if let Some(x) = &options.model_version {
query.append_pair("request.modelVersion", &x.to_string());
}
if let Some(x) = &options.expected_loss_min {
query.append_pair("request.expectedLossMin", &x.to_string());
}
if let Some(x) = &options.expected_loss_max {
query.append_pair("request.expectedLossMax", &x.to_string());
}
if let Some(x) = &options.listed_on_utc_from {
query.append_pair("request.listedOnUTCFrom", &x.to_string());
}
if let Some(x) = &options.listed_on_utc_to {
query.append_pair("request.listedOnUTCTo", &x.to_string());
}
if let Some(x) = &options.page_size {
query.append_pair("request.pageSize", &x.to_string());
}
if let Some(x) = &options.page_nr {
query.append_pair("request.pageNr", &x.to_string());
}
query.finish()
};
let uri_str = format!("{}/api/v1/auctions?{}", self.base_path, query_string);
let uri: hyper::Uri = uri_str.parse().unwrap();
builder = builder.uri(uri);
let req = builder.body(hyper::Body::empty()).unwrap();
let https = hyper_rustls::HttpsConnectorBuilder::new()
.with_native_roots()
.https_only()
.enable_http1().build();
let client = hyper::Client::builder().build(https);
let resp = client.request(req).await;
match resp {
Ok(mut resp) => {
let bytes = hyper::body::to_bytes(resp.body_mut()).await.unwrap();
let result = String::from_utf8(bytes.into_iter().collect()).expect("");
match serde_json::from_str(&result) {
Ok(data) => Ok(data),
Err(err) => Err(format!("{:?} response payload= {}",err,result)),
}
}
Err(err) => Err(format!("{:?}",err)),
}
}
}
| 40.935294 | 96 | 0.535134 |
ddd264eeaa2de4705ad0ca8e44fa3eed44287fda | 1,202 | /// Returns a cross-platform-filename-safe version of any string.
///
/// This is used internally to generate app data directories based on app
/// name/author. App developers can use it for consistency when dealing with
/// file system operations.
///
/// Do not apply this function to full paths, as it will sanitize '/' and '\';
/// it should only be used on directory or file names (i.e. path segments).
pub fn sanitized(component: &str) -> String {
let mut buf = String::with_capacity(component.len());
for (i, c) in component.chars().enumerate() {
let is_lower = 'a' <= c && c <= 'z';
let is_upper = 'A' <= c && c <= 'Z';
let is_letter = is_upper || is_lower;
let is_number = '0' <= c && c <= '9';
let is_space = c == ' ';
let is_hyphen = c == '-';
let is_underscore = c == '_';
let is_period = c == '.' && i != 0; // Disallow accidentally hidden folders
let is_valid = is_letter || is_number || is_space || is_hyphen || is_underscore ||
is_period;
if is_valid {
buf.push(c);
} else {
buf.push_str(&format!(",{},", c as u32));
}
}
buf
}
| 40.066667 | 90 | 0.56406 |
142346b2ba2eda1259da8fdf658301beba5bf183 | 24,410 | use super::{PositionIterInternal, PyGenericAlias, PySlice, PyTupleRef, PyTypeRef};
use crate::common::lock::{
PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard,
};
use crate::{
function::{ArgIterable, FuncArgs, IntoPyObject, OptionalArg},
protocol::{PyIterReturn, PyMappingMethods},
sequence::{self, SimpleSeq},
sliceable::{saturate_index, PySliceableSequence, PySliceableSequenceMut, SequenceIndex},
stdlib::sys,
types::{
richcompare_wrapper, AsMapping, Comparable, Constructor, Hashable, IterNext,
IterNextIterable, Iterable, PyComparisonOp, RichCompareFunc, Unconstructible, Unhashable,
},
utils::Either,
vm::{ReprGuard, VirtualMachine},
IdProtocol, PyClassDef, PyClassImpl, PyComparisonValue, PyContext, PyObject, PyObjectRef,
PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
};
use std::fmt;
use std::mem::size_of;
use std::ops::{DerefMut, Range};
/// Built-in mutable sequence.
///
/// If no argument is given, the constructor creates a new empty list.
/// The argument must be an iterable if specified.
#[pyclass(module = false, name = "list")]
#[derive(Default)]
pub struct PyList {
elements: PyRwLock<Vec<PyObjectRef>>,
}
impl fmt::Debug for PyList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO: implement more detailed, non-recursive Debug formatter
f.write_str("list")
}
}
impl From<Vec<PyObjectRef>> for PyList {
fn from(elements: Vec<PyObjectRef>) -> Self {
PyList {
elements: PyRwLock::new(elements),
}
}
}
impl FromIterator<PyObjectRef> for PyList {
fn from_iter<T: IntoIterator<Item = PyObjectRef>>(iter: T) -> Self {
Vec::from_iter(iter).into()
}
}
impl PyValue for PyList {
fn class(vm: &VirtualMachine) -> &PyTypeRef {
&vm.ctx.types.list_type
}
}
impl IntoPyObject for Vec<PyObjectRef> {
fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
PyList::new_ref(self, &vm.ctx).into()
}
}
impl PyList {
pub fn new_ref(elements: Vec<PyObjectRef>, ctx: &PyContext) -> PyRef<Self> {
PyRef::new_ref(Self::from(elements), ctx.types.list_type.clone(), None)
}
pub fn borrow_vec(&self) -> PyMappedRwLockReadGuard<'_, [PyObjectRef]> {
PyRwLockReadGuard::map(self.elements.read(), |v| &**v)
}
pub fn borrow_vec_mut(&self) -> PyRwLockWriteGuard<'_, Vec<PyObjectRef>> {
self.elements.write()
}
}
#[derive(FromArgs, Default)]
pub(crate) struct SortOptions {
#[pyarg(named, default)]
key: Option<PyObjectRef>,
#[pyarg(named, default = "false")]
reverse: bool,
}
pub type PyListRef = PyRef<PyList>;
#[pyimpl(with(AsMapping, Iterable, Hashable, Comparable), flags(BASETYPE))]
impl PyList {
#[pymethod]
pub(crate) fn append(&self, x: PyObjectRef) {
self.borrow_vec_mut().push(x);
}
#[pymethod]
fn extend(&self, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut new_elements = vm.extract_elements(&x)?;
self.borrow_vec_mut().append(&mut new_elements);
Ok(())
}
#[pymethod]
pub(crate) fn insert(&self, position: isize, element: PyObjectRef) {
let mut elements = self.borrow_vec_mut();
let position = elements.saturate_index(position);
elements.insert(position, element);
}
#[pymethod(magic)]
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let other = other.payload_if_subclass::<PyList>(vm).ok_or_else(|| {
vm.new_type_error(format!(
"Cannot add {} and {}",
Self::class(vm).name(),
other.class().name()
))
})?;
let mut elements = self.borrow_vec().to_vec();
elements.extend(other.borrow_vec().iter().cloned());
Ok(Self::new_ref(elements, &vm.ctx))
}
#[pymethod(magic)]
fn iadd(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Ok(new_elements) = vm.extract_elements(&other) {
let mut e = new_elements;
zelf.borrow_vec_mut().append(&mut e);
zelf.into()
} else {
vm.ctx.not_implemented()
}
}
#[pymethod(magic)]
fn bool(&self) -> bool {
!self.borrow_vec().is_empty()
}
#[pymethod]
fn clear(&self) {
let _removed = std::mem::take(self.borrow_vec_mut().deref_mut());
}
#[pymethod]
fn copy(&self, vm: &VirtualMachine) -> PyRef<Self> {
Self::new_ref(self.borrow_vec().to_vec(), &vm.ctx)
}
#[pymethod(magic)]
fn len(&self) -> usize {
self.borrow_vec().len()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
size_of::<Self>() + self.elements.read().capacity() * size_of::<PyObjectRef>()
}
#[pymethod]
fn reverse(&self) {
self.borrow_vec_mut().reverse();
}
#[pymethod(magic)]
fn reversed(zelf: PyRef<Self>) -> PyListReverseIterator {
let position = zelf.len().saturating_sub(1);
PyListReverseIterator {
internal: PyMutex::new(PositionIterInternal::new(zelf, position)),
}
}
#[pymethod(magic)]
fn getitem(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let result = match zelf.borrow_vec().get_item(vm, needle, Self::NAME)? {
Either::A(obj) => obj,
Either::B(vec) => Self::new_ref(vec, &vm.ctx).into(),
};
Ok(result)
}
#[pymethod(magic)]
fn setitem(
&self,
needle: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
match SequenceIndex::try_from_object_for(vm, needle, Self::NAME)? {
SequenceIndex::Int(index) => self.setindex(index, value, vm),
SequenceIndex::Slice(slice) => {
if let Ok(sec) = ArgIterable::try_from_object(vm, value) {
return self.setslice(slice, sec, vm);
}
Err(vm.new_type_error("can only assign an iterable to a slice".to_owned()))
}
}
}
fn setindex(&self, index: isize, mut value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut elements = self.borrow_vec_mut();
if let Some(pos_index) = elements.wrap_index(index) {
std::mem::swap(&mut elements[pos_index], &mut value);
Ok(())
} else {
Err(vm.new_index_error("list assignment index out of range".to_owned()))
}
}
fn setslice(
&self,
slice: PyRef<PySlice>,
sec: ArgIterable,
vm: &VirtualMachine,
) -> PyResult<()> {
let items: Result<Vec<PyObjectRef>, _> = sec.iter(vm)?.collect();
let items = items?;
let slice = slice.to_saturated(vm)?;
let mut elements = self.borrow_vec_mut();
elements.set_slice_items(vm, slice, items.as_slice())
}
#[pymethod(magic)]
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<String> {
let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let elements = zelf.borrow_vec().to_vec();
let mut str_parts = Vec::with_capacity(elements.len());
for elem in elements.iter() {
let s = vm.to_repr(elem)?;
str_parts.push(s.as_str().to_owned());
}
format!("[{}]", str_parts.join(", "))
} else {
"[...]".to_owned()
};
Ok(s)
}
#[pymethod(magic)]
#[pymethod(name = "__rmul__")]
fn mul(&self, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let new_elements = sequence::seq_mul(vm, &self.borrow_vec(), value)?
.cloned()
.collect();
Ok(Self::new_ref(new_elements, &vm.ctx))
}
#[pymethod(magic)]
fn imul(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let mut elements = zelf.borrow_vec_mut();
let mut new_elements: Vec<PyObjectRef> =
sequence::seq_mul(vm, &*elements, value)?.cloned().collect();
std::mem::swap(elements.deref_mut(), &mut new_elements);
Ok(zelf.clone())
}
fn _iter_equal<F: FnMut(), const SHORT: bool>(
&self,
needle: &PyObject,
range: Range<usize>,
mut f: F,
vm: &VirtualMachine,
) -> PyResult<usize> {
let needle_cls = needle.class();
let needle_cmp = needle_cls
.mro_find_map(|cls| cls.slots.richcompare.load())
.unwrap();
let mut borrower = None;
let mut i = range.start;
let index = loop {
if i >= range.end {
break usize::MAX;
}
let guard = if let Some(x) = borrower.take() {
x
} else {
self.borrow_vec()
};
let elem = if let Some(x) = guard.get(i) {
x
} else {
break usize::MAX;
};
if elem.is(needle) {
f();
if SHORT {
break i;
}
borrower = Some(guard);
} else {
let elem_cls = elem.class();
let reverse_first = !elem_cls.is(&needle_cls) && elem_cls.issubclass(&needle_cls);
let eq = if reverse_first {
let elem_cmp = elem_cls
.mro_find_map(|cls| cls.slots.richcompare.load())
.unwrap();
drop(elem_cls);
fn cmp(
elem: &PyObject,
needle: &PyObject,
elem_cmp: RichCompareFunc,
needle_cmp: RichCompareFunc,
vm: &VirtualMachine,
) -> PyResult<bool> {
match elem_cmp(elem, needle, PyComparisonOp::Eq, vm)? {
Either::B(PyComparisonValue::Implemented(value)) => Ok(value),
Either::A(obj) if !obj.is(&vm.ctx.not_implemented) => {
obj.try_to_bool(vm)
}
_ => match needle_cmp(needle, elem, PyComparisonOp::Eq, vm)? {
Either::B(PyComparisonValue::Implemented(value)) => Ok(value),
Either::A(obj) if !obj.is(&vm.ctx.not_implemented) => {
obj.try_to_bool(vm)
}
_ => Ok(false),
},
}
}
if elem_cmp as usize == richcompare_wrapper as usize {
let elem = elem.clone();
drop(guard);
cmp(&elem, needle, elem_cmp, needle_cmp, vm)?
} else {
let eq = cmp(elem, needle, elem_cmp, needle_cmp, vm)?;
borrower = Some(guard);
eq
}
} else {
match needle_cmp(needle, elem, PyComparisonOp::Eq, vm)? {
Either::B(PyComparisonValue::Implemented(value)) => {
drop(elem_cls);
borrower = Some(guard);
value
}
Either::A(obj) if !obj.is(&vm.ctx.not_implemented) => {
drop(elem_cls);
borrower = Some(guard);
obj.try_to_bool(vm)?
}
_ => {
let elem_cmp = elem_cls
.mro_find_map(|cls| cls.slots.richcompare.load())
.unwrap();
drop(elem_cls);
fn cmp(
elem: &PyObject,
needle: &PyObject,
elem_cmp: RichCompareFunc,
vm: &VirtualMachine,
) -> PyResult<bool> {
match elem_cmp(elem, needle, PyComparisonOp::Eq, vm)? {
Either::B(PyComparisonValue::Implemented(value)) => Ok(value),
Either::A(obj) if !obj.is(&vm.ctx.not_implemented) => {
obj.try_to_bool(vm)
}
_ => Ok(false),
}
}
if elem_cmp as usize == richcompare_wrapper as usize {
let elem = elem.clone();
drop(guard);
cmp(&elem, needle, elem_cmp, vm)?
} else {
let eq = cmp(elem, needle, elem_cmp, vm)?;
borrower = Some(guard);
eq
}
}
}
};
if eq {
f();
if SHORT {
break i;
}
}
}
i += 1;
};
// TODO: Optioned<usize>
Ok(index)
}
fn foreach_equal<F: FnMut()>(
&self,
needle: &PyObject,
f: F,
vm: &VirtualMachine,
) -> PyResult<()> {
self._iter_equal::<_, false>(needle, 0..usize::MAX, f, vm)
.map(|_| ())
}
fn find_equal(
&self,
needle: &PyObject,
range: Range<usize>,
vm: &VirtualMachine,
) -> PyResult<usize> {
self._iter_equal::<_, true>(needle, range, || {}, vm)
}
#[pymethod]
fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
let mut count = 0;
self.foreach_equal(&needle, || count += 1, vm)?;
Ok(count)
}
#[pymethod(magic)]
pub(crate) fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
Ok(self.find_equal(&needle, 0..usize::MAX, vm)? != usize::MAX)
}
#[pymethod]
fn index(
&self,
needle: PyObjectRef,
start: OptionalArg<isize>,
stop: OptionalArg<isize>,
vm: &VirtualMachine,
) -> PyResult<usize> {
let len = self.len();
let start = start.map(|i| saturate_index(i, len)).unwrap_or(0);
let stop = stop
.map(|i| saturate_index(i, len))
.unwrap_or(sys::MAXSIZE as usize);
let index = self.find_equal(&needle, start..stop, vm)?;
if index == usize::MAX {
Err(vm.new_value_error(format!("'{}' is not in list", needle.str(vm)?)))
} else {
Ok(index)
}
}
#[pymethod]
fn pop(&self, i: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult {
let mut i = i.into_option().unwrap_or(-1);
let mut elements = self.borrow_vec_mut();
if i < 0 {
i += elements.len() as isize;
}
if elements.is_empty() {
Err(vm.new_index_error("pop from empty list".to_owned()))
} else if i < 0 || i as usize >= elements.len() {
Err(vm.new_index_error("pop index out of range".to_owned()))
} else {
Ok(elements.remove(i as usize))
}
}
#[pymethod]
fn remove(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let index = self.find_equal(&needle, 0..usize::MAX, vm)?;
if index != usize::MAX {
// defer delete out of borrow
Ok(self.borrow_vec_mut().remove(index))
} else {
Err(vm.new_value_error(format!("'{}' is not in list", needle.str(vm)?)))
}
.map(drop)
}
#[pymethod(magic)]
fn delitem(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
match SequenceIndex::try_from_object_for(vm, subscript, Self::NAME)? {
SequenceIndex::Int(index) => self.delindex(index, vm),
SequenceIndex::Slice(slice) => self.delslice(slice, vm),
}
}
fn delindex(&self, index: isize, vm: &VirtualMachine) -> PyResult<()> {
let removed = {
let mut elements = self.borrow_vec_mut();
if let Some(pos_index) = elements.wrap_index(index) {
// defer delete out of borrow
Ok(elements.remove(pos_index))
} else {
Err(vm.new_index_error("Index out of bounds!".to_owned()))
}
};
removed.map(drop)
}
fn delslice(&self, slice: PyRef<PySlice>, vm: &VirtualMachine) -> PyResult<()> {
let slice = slice.to_saturated(vm)?;
self.borrow_vec_mut().delete_slice(vm, slice)
}
#[pymethod]
pub(crate) fn sort(&self, options: SortOptions, vm: &VirtualMachine) -> PyResult<()> {
// replace list contents with [] for duration of sort.
// this prevents keyfunc from messing with the list and makes it easy to
// check if it tries to append elements to it.
let mut elements = std::mem::take(self.borrow_vec_mut().deref_mut());
let res = do_sort(vm, &mut elements, options.key, options.reverse);
std::mem::swap(self.borrow_vec_mut().deref_mut(), &mut elements);
res?;
if !elements.is_empty() {
return Err(vm.new_value_error("list modified during sort".to_owned()));
}
Ok(())
}
#[pyslot]
fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
PyList::default().into_pyresult_with_type(vm, cls)
}
#[pymethod(magic)]
fn init(&self, iterable: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> {
let mut elements = if let OptionalArg::Present(iterable) = iterable {
vm.extract_elements(&iterable)?
} else {
vec![]
};
std::mem::swap(self.borrow_vec_mut().deref_mut(), &mut elements);
Ok(())
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
impl AsMapping for PyList {
fn as_mapping(_zelf: &crate::PyObjectView<Self>, _vm: &VirtualMachine) -> PyMappingMethods {
PyMappingMethods {
length: Some(Self::length),
subscript: Some(Self::subscript),
ass_subscript: Some(Self::ass_subscript),
}
}
#[inline]
fn length(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
Self::downcast_ref(&zelf, vm).map(|zelf| Ok(zelf.len()))?
}
#[inline]
fn subscript(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Self::downcast(zelf, vm).map(|zelf| Self::getitem(zelf, needle, vm))?
}
#[inline]
fn ass_subscript(
zelf: PyObjectRef,
needle: PyObjectRef,
value: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
Self::downcast_ref(&zelf, vm).map(|zelf| match value {
Some(value) => zelf.setitem(needle, value, vm),
None => zelf.delitem(needle, vm),
})?
}
}
impl Iterable for PyList {
fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
Ok(PyListIterator {
internal: PyMutex::new(PositionIterInternal::new(zelf, 0)),
}
.into_object(vm))
}
}
impl Comparable for PyList {
fn cmp(
zelf: &crate::PyObjectView<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
if let Some(res) = op.identical_optimization(zelf, other) {
return Ok(res.into());
}
let other = class_or_notimplemented!(Self, other);
let a = zelf.borrow_vec();
let b = other.borrow_vec();
sequence::cmp(vm, a.boxed_iter(), b.boxed_iter(), op).map(PyComparisonValue::Implemented)
}
}
impl Unhashable for PyList {}
fn do_sort(
vm: &VirtualMachine,
values: &mut Vec<PyObjectRef>,
key_func: Option<PyObjectRef>,
reverse: bool,
) -> PyResult<()> {
let op = if reverse {
PyComparisonOp::Lt
} else {
PyComparisonOp::Gt
};
let cmp = |a: &PyObjectRef, b: &PyObjectRef| a.rich_compare_bool(b, op, vm);
if let Some(ref key_func) = key_func {
let mut items = values
.iter()
.map(|x| Ok((x.clone(), vm.invoke(key_func, (x.clone(),))?)))
.collect::<Result<Vec<_>, _>>()?;
timsort::try_sort_by_gt(&mut items, |a, b| cmp(&a.1, &b.1))?;
*values = items.into_iter().map(|(val, _)| val).collect();
} else {
timsort::try_sort_by_gt(values, cmp)?;
}
Ok(())
}
#[pyclass(module = false, name = "list_iterator")]
#[derive(Debug)]
pub struct PyListIterator {
internal: PyMutex<PositionIterInternal<PyListRef>>,
}
impl PyValue for PyListIterator {
fn class(vm: &VirtualMachine) -> &PyTypeRef {
&vm.ctx.types.list_iterator_type
}
}
#[pyimpl(with(Constructor, IterNext))]
impl PyListIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
}
}
impl Unconstructible for PyListIterator {}
impl IterNextIterable for PyListIterator {}
impl IterNext for PyListIterator {
fn next(zelf: &crate::PyObjectView<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|list, pos| {
let vec = list.borrow_vec();
Ok(match vec.get(pos) {
Some(x) => PyIterReturn::Return(x.clone()),
None => PyIterReturn::StopIteration(None),
})
})
}
}
#[pyclass(module = false, name = "list_reverseiterator")]
#[derive(Debug)]
pub struct PyListReverseIterator {
internal: PyMutex<PositionIterInternal<PyListRef>>,
}
impl PyValue for PyListReverseIterator {
fn class(vm: &VirtualMachine) -> &PyTypeRef {
&vm.ctx.types.list_reverseiterator_type
}
}
#[pyimpl(with(Constructor, IterNext))]
impl PyListReverseIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().rev_length_hint(|obj| obj.len())
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_reversed_reduce(|x| x.clone().into(), vm)
}
}
impl Unconstructible for PyListReverseIterator {}
impl IterNextIterable for PyListReverseIterator {}
impl IterNext for PyListReverseIterator {
fn next(zelf: &crate::PyObjectView<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().rev_next(|list, pos| {
let vec = list.borrow_vec();
Ok(match vec.get(pos) {
Some(x) => PyIterReturn::Return(x.clone()),
None => PyIterReturn::StopIteration(None),
})
})
}
}
pub fn init(context: &PyContext) {
let list_type = &context.types.list_type;
PyList::extend_class(context, list_type);
PyListIterator::extend_class(context, &context.types.list_iterator_type);
PyListReverseIterator::extend_class(context, &context.types.list_reverseiterator_type);
}
| 33.256131 | 99 | 0.532528 |
ed1ad29927cca40a31d7f8b8bdd9a8b1dad901f3 | 1,061 | use yew::prelude::*;
use yew_hooks::prelude::*;
/// `use_title` demo
#[function_component(MyComponent)]
fn my_component() -> Html {
use_title("This is an awesome title".to_string());
html! {
<>{ "My Component" }</>
}
}
#[function_component(UseTitle)]
pub fn title() -> Html {
let toggle = use_toggle("Mount to change title", "Unmount to restore title");
let onclick = {
let toggle = toggle.clone();
Callback::from(move |_| toggle.toggle())
};
html! {
<div class="app">
<header class="app-header">
<div>
<button {onclick}>{ *toggle }</button>
<p>
{
if *toggle == "Unmount to restore title" {
html! { <MyComponent /> }
} else {
html! {}
}
}
</p>
</div>
</header>
</div>
}
}
| 25.261905 | 81 | 0.406221 |
5691e4f5736d1a883e28e2684fdac9b760e423db | 219 | #[test]
#[ignore]
fn test_test_strcmp_uni() {
assert_emscripten_output!(
"../../emtests/test_strcmp_uni.wasm",
"test_strcmp_uni",
vec![],
"../../emtests/test_strcmp_uni.out"
);
}
| 19.909091 | 45 | 0.570776 |
ddc38798b067bcd73534a899c8b881451582eb11 | 3,438 | use rayon::prelude::*;
use ae1::*;
use std::path::Path;
use std::fs::File;
use std::io::Read;
fn load_file<P: AsRef<Path>>(file: P) -> (Vec<NodeInfo>, Vec<EdgeInfo>) {
let mut buffer = String::new();
let mut file = File::open(file).expect("File could not be opened");
file.read_to_string(&mut buffer).expect(
"Could not read file",
);
let lines: Vec<&str> = buffer
.lines()
.skip_while(|l| l.starts_with('#') || l.is_empty())
.collect();
let node_count: usize = lines[0].parse().expect("Node Count could not be parsed");
let nodes = lines[2..node_count + 2]
.par_iter()
.map(|l| {
let mut raw_node_data = l.split(' ');
raw_node_data.next(); // id is not necessary
let osm_id: OsmNodeId = raw_node_data
.next()
.map(str::parse)
.expect("No OSM ID Data")
.expect("OSM ID not parse-able");
let lat: Latitude = raw_node_data
.next()
.map(str::parse)
.expect("No Latitude Data")
.expect("Latitude not parse-able");
let long: Longitude = raw_node_data
.next()
.map(str::parse)
.expect("No Longitude Data")
.expect("Longitude not parse-able");
let height: Height = raw_node_data
.next()
.map(str::parse)
.expect("No Height Data")
.expect("Height not parse-able");
NodeInfo::new(osm_id, lat, long, height)
})
.collect();
let edges = lines[node_count + 2..]
.par_iter()
.map(|l| {
let mut raw_node_data = l.split(' ');
let source: NodeId = raw_node_data
.next()
.map(str::parse)
.expect("No source Id found")
.expect("Source id not parse-able");
let dest: NodeId = raw_node_data
.next()
.map(str::parse)
.expect("No destination Id found")
.expect("Destination id not parse-able");
let length: Length = raw_node_data
.next()
.map(str::parse)
.expect("No length found")
.expect("Length id not parse-able");
raw_node_data.next(); //ignore type
let speed: Speed = raw_node_data
.next()
.map(str::parse)
.expect("No speed found")
.expect("Speed id not parse-able");
EdgeInfo::new(source, dest, length, speed)
})
.collect();
(nodes, edges)
}
pub fn load_graph<P: AsRef<Path>>(file: P) -> Graph {
use std::time::Instant;
let start = Instant::now();
let (nodes, edges) = load_file(file);
let file_loaded = Instant::now();
let g = Graph::new(nodes, edges);
let graph_created = Instant::now();
println!(
"file loading time: {:?}",
file_loaded.duration_since(start)
);
println!(
"graph creation time: {:?}",
graph_created.duration_since(file_loaded)
);
g
}
#[test]
#[ignore]
fn load_test() {
let (nodes, edges) = load_file("/home/flo/workspaces/rust/graphdata/saarland.graph");
assert_eq!(nodes.len(), 595294);
assert_eq!(edges.len(), 1241741);
}
| 31.833333 | 89 | 0.507563 |
871d0c7d6967d42f70cc6d22ec87e8fbb5a4b7e6 | 2,099 | pub fn remquof(mut x: f32, mut y: f32) -> (f32, i32) {
let ux: u32 = x.to_bits();
let mut uy: u32 = y.to_bits();
let mut ex = ((ux >> 23) & 0xff) as i32;
let mut ey = ((uy >> 23) & 0xff) as i32;
let sx = (ux >> 31) != 0;
let sy = (uy >> 31) != 0;
let mut q: u32;
let mut i: u32;
let mut uxi: u32 = ux;
if (uy << 1) == 0 || y.is_nan() || ex == 0xff {
return ((x * y) / (x * y), 0);
}
if (ux << 1) == 0 {
return (x, 0);
}
/* normalize x and y */
if ex == 0 {
i = uxi << 9;
while (i >> 31) == 0 {
ex -= 1;
i <<= 1;
}
uxi <<= -ex + 1;
} else {
uxi &= (!0) >> 9;
uxi |= 1 << 23;
}
if ey == 0 {
i = uy << 9;
while (i >> 31) == 0 {
ey -= 1;
i <<= 1;
}
uy <<= -ey + 1;
} else {
uy &= (!0) >> 9;
uy |= 1 << 23;
}
q = 0;
if ex + 1 != ey {
if ex < ey {
return (x, 0);
}
/* x mod y */
while ex > ey {
i = uxi.wrapping_sub(uy);
if (i >> 31) == 0 {
uxi = i;
q += 1;
}
uxi <<= 1;
q <<= 1;
ex -= 1;
}
i = uxi.wrapping_sub(uy);
if (i >> 31) == 0 {
uxi = i;
q += 1;
}
if uxi == 0 {
ex = -30;
} else {
while (uxi >> 23) == 0 {
uxi <<= 1;
ex -= 1;
}
}
}
/* scale result and decide between |x| and |x|-|y| */
if ex > 0 {
uxi -= 1 << 23;
uxi |= (ex as u32) << 23;
} else {
uxi >>= -ex + 1;
}
x = f32::from_bits(uxi);
if sy {
y = -y;
}
if ex == ey || (ex + 1 == ey && (2.0 * x > y || (2.0 * x == y && (q % 2) != 0))) {
x -= y;
q += 1;
}
q &= 0x7fffffff;
let quo = if sx ^ sy { -(q as i32) } else { q as i32 };
if sx {
(-x, quo)
} else {
(x, quo)
}
}
| 21.639175 | 86 | 0.29252 |
037f443c3eb68350d2636eee633e0fb9ef3465b8 | 19,317 | pub mod host_memory;
use host_memory::MmapMemoryCreator;
pub use host_memory::WasmtimeMemoryCreator;
mod signal_stack;
mod system_api;
#[cfg(test)]
mod wasmtime_embedder_tests;
use super::InstanceRunResult;
use crate::cow_memory_creator::{CowMemoryCreator, CowMemoryCreatorProxy};
use crate::{Embedder, Instance};
use ic_config::embedders::{Config, PersistenceType};
use ic_interfaces::execution_environment::{
HypervisorError, HypervisorResult, InstanceStats, SystemApi, TrapCode,
};
use ic_logger::{debug, ReplicaLogger};
use ic_replicated_state::{EmbedderCache, Global, NumWasmPages, PageIndex, PageMap};
use ic_types::{
methods::{FuncRef, WasmMethod},
NumInstructions,
};
use ic_wasm_types::BinaryEncodedWasm;
use memory_tracker::SigsegvMemoryTracker;
use signal_stack::WasmtimeSignalStack;
use std::cell::RefCell;
use std::convert::TryFrom;
use std::rc::Rc;
use std::sync::Arc;
use system_api::SystemApiHandle;
use wasmtime::{unix::StoreExt, Memory, Mutability, Store, Val, ValType};
fn trap_to_error(err: anyhow::Error) -> HypervisorError {
let message = format!("{}", err);
let re_signature_mismatch =
regex::Regex::new("expected \\d+ arguments, got \\d+").expect("signature mismatch regex");
if message.contains("wasm trap: call stack exhausted") {
HypervisorError::Trapped(TrapCode::StackOverflow)
} else if message.contains("wasm trap: out of bounds memory access") {
HypervisorError::Trapped(TrapCode::HeapOutOfBounds)
} else if message.contains("wasm trap: integer divide by zero") {
HypervisorError::Trapped(TrapCode::IntegerDivByZero)
} else if message.contains("wasm trap: unreachable") {
HypervisorError::Trapped(TrapCode::Unreachable)
} else if message.contains("wasm trap: undefined element: out of bounds") {
HypervisorError::Trapped(TrapCode::TableOutOfBounds)
} else if message.contains("argument type mismatch") || re_signature_mismatch.is_match(&message)
{
HypervisorError::ContractViolation(
"function invocation does not match its signature".to_string(),
)
} else {
HypervisorError::Trapped(TrapCode::Other)
}
}
pub struct WasmtimeEmbedder {
log: ReplicaLogger,
max_wasm_stack_size: usize,
}
impl WasmtimeEmbedder {
pub fn new(config: Config, log: ReplicaLogger) -> Self {
let Config {
max_wasm_stack_size,
..
} = config;
WasmtimeEmbedder {
log,
max_wasm_stack_size,
}
}
}
impl Embedder for WasmtimeEmbedder {
fn compile(
&self,
persistence_type: PersistenceType,
wasm_binary: &BinaryEncodedWasm,
) -> HypervisorResult<EmbedderCache> {
let mut config = wasmtime::Config::default();
let cached_mem_creator = match persistence_type {
PersistenceType::Sigsegv => {
let raw_creator = MmapMemoryCreator {};
let mem_creator = Arc::new(WasmtimeMemoryCreator::new(raw_creator));
config.with_host_memory(mem_creator);
None
}
_ /*Pagemap*/ => {
let raw_creator = CowMemoryCreatorProxy::new(Arc::new(CowMemoryCreator::new_uninitialized()));
let mem_creator = Arc::new(WasmtimeMemoryCreator::new(raw_creator.clone()));
config.with_host_memory(mem_creator);
Some(raw_creator)
}
};
config
// maximum size in bytes where a linear memory is considered
// static. setting this to maximum Wasm memory size will guarantee
// the memory is always static.
.static_memory_maximum_size(
wasmtime_environ::WASM_PAGE_SIZE as u64 * wasmtime_environ::WASM_MAX_PAGES as u64,
)
.cranelift_nan_canonicalization(true)
.max_wasm_stack(self.max_wasm_stack_size);
let engine = wasmtime::Engine::new(&config);
let module = wasmtime::Module::new(&engine, wasm_binary.as_slice())
.expect("failed to instantiate module");
Ok(EmbedderCache::new((module, cached_mem_creator)))
}
fn new_instance(
&self,
cache: &EmbedderCache,
exported_globals: &[Global],
heap_size: NumWasmPages,
memory_creator: Option<Arc<CowMemoryCreator>>,
memory_initializer: Option<PageMap>,
) -> Box<dyn Instance> {
let (module, memory_creator_proxy) = cache
.downcast::<(wasmtime::Module, Option<CowMemoryCreatorProxy>)>()
.expect("incompatible embedder cache, expected BinaryEncodedWasm");
assert_eq!(
memory_creator.is_some(),
memory_creator_proxy.is_some(),
"We are caching mem creator if and only if mem_creator argument is not None,\
and both happen if persistence type is Pagemap"
);
let store = Store::new(&module.engine());
let system_api_handle = SystemApiHandle::new();
let canister_num_instructions_global = Rc::new(RefCell::new(None));
// We need to pass a weak pointer to the cycles_global, because wasmtime::Global
// internally references Store and it would create a cyclic reference.
// Since Store holds both the global and our syscalls, syscalls won't outlive
// the global
let linker: wasmtime::Linker = system_api::syscalls(
&store,
system_api_handle.clone(),
Rc::downgrade(&canister_num_instructions_global),
);
let (instance, persistence_type) = if let Some(cow_mem_creator_proxy) = memory_creator_proxy
{
// If we have the CowMemoryCreator we want to ensure it is used
// atomically
let _lock = cow_mem_creator_proxy.memory_creator_lock.lock().unwrap();
cow_mem_creator_proxy.replace(memory_creator.unwrap());
let instance = linker
.instantiate(&module)
.expect("failed to create Wasmtime instance");
// After the Wasm module instance and its corresponding memory
// are created we want to ensure that this particular
// MemoryCreator can't be reused
cow_mem_creator_proxy
.replace(std::sync::Arc::new(CowMemoryCreator::new_uninitialized()));
(instance, PersistenceType::Pagemap)
} else {
(
linker
.instantiate(&module)
.expect("failed to create Wasmtime instance"),
PersistenceType::Sigsegv,
)
};
// in wasmtime only exported globals are accessible
let instance_globals: Vec<_> = instance.exports().filter_map(|e| e.into_global()).collect();
if exported_globals.len() > instance_globals.len() {
panic!(
"Given exported globals length {} is more than instance exported globals length {}",
exported_globals.len(),
instance_globals.len()
);
}
// set the globals to persisted values
for ((ix, v), instance_global) in exported_globals
.iter()
.enumerate()
.zip(instance_globals.iter())
{
if instance_global.ty().mutability() == Mutability::Var {
instance_global
.set(match v {
Global::I32(val) => Val::I32(*val),
Global::I64(val) => Val::I64(*val),
Global::F32(val) => Val::F32((val).to_bits()),
Global::F64(val) => Val::F64((val).to_bits()),
})
.unwrap_or_else(|e| {
let v = match v {
Global::I32(val) => (val).to_string(),
Global::I64(val) => (val).to_string(),
Global::F32(val) => (val).to_string(),
Global::F64(val) => (val).to_string(),
};
panic!("error while setting exported global {} to {}: {}", ix, v, e)
})
} else {
debug!(
self.log,
"skipping initialization of immutable global {}", ix
);
}
}
let instance_memory = instance
.get_memory("memory")
.map(|instance_memory| {
let current_heap_size = instance_memory.size();
let requested_size = heap_size.get();
if current_heap_size < requested_size {
let delta = requested_size - current_heap_size;
// TODO(DFN-1305): It is OK to panic here. `requested_size` is
// value we store only after we've successfully grown module memory in some
// previous execution.
// Example: module starts with (memory 1 2) and calls (memory.grow 1). Then
// requested_size will be 2.
instance_memory.grow(delta).expect("memory grow failed");
}
instance_memory
})
.map(Arc::new);
// if `wasmtime::Instance` does not have memory we don't need a memory tracker
let memory_tracker =
instance_memory
.as_ref()
.map(|instance_memory| match persistence_type {
PersistenceType::Sigsegv => sigsegv_memory_tracker(
Arc::downgrade(instance_memory),
&store,
memory_initializer,
self.log.clone(),
),
PersistenceType::Pagemap => sigsegv_memory_tracker(
Arc::downgrade(instance_memory),
&store,
None,
self.log.clone(),
),
});
let signal_stack = WasmtimeSignalStack::new();
// canister_num_instructions_global is an Option because some wasmtime tests
// invoke this function without exporting the "canister counter_instructions"
// global
*canister_num_instructions_global.borrow_mut() =
instance.get_global("canister counter_instructions");
let instance_impl = WasmtimeInstance {
system_api_handle,
instance,
instance_memory,
memory_tracker,
signal_stack,
canister_num_instructions_global,
log: self.log.clone(),
};
Box::new(instance_impl)
}
}
fn sigsegv_memory_tracker(
instance_memory: std::sync::Weak<wasmtime::Memory>,
store: &wasmtime::Store,
memory_initializer: Option<PageMap>,
log: ReplicaLogger,
) -> Rc<SigsegvMemoryTracker> {
let (base, size) = {
let memory = instance_memory.upgrade().unwrap();
(memory.data_ptr(), memory.data_size())
};
let sigsegv_memory_tracker = {
// For both SIGSEGV and in the future UFFD memory tracking we need
// the base address of the heap and its size
let base = base as *mut libc::c_void;
let page_size = *ic_sys::PAGE_SIZE;
assert!(base as usize % page_size == 0, "heap must be page aligned");
assert!(
size % page_size == 0,
"heap size must be a multiple of page size"
);
std::rc::Rc::new(
SigsegvMemoryTracker::new(base, size, log)
.expect("failed to instantiate SIGSEGV memory tracker"),
)
};
// http://man7.org/linux/man-pages/man7/signal-safety.7.html
unsafe {
let current_heap_size = Box::new(move || {
instance_memory
.upgrade()
.map(|x| x.data_size())
.unwrap_or(0)
}) as Box<dyn Fn() -> usize>;
let default_handler = || {
#[cfg(feature = "sigsegv_handler_debug")]
eprintln!("> instance signal handler: calling default signal handler");
false
};
let memory_initializer = Rc::new(memory_initializer);
let handler = crate::signal_handler::sigsegv_memory_tracker_handler(
std::rc::Rc::clone(&sigsegv_memory_tracker),
memory_initializer,
current_heap_size,
default_handler,
|| true,
|| false,
);
store.set_signal_handler(handler);
};
sigsegv_memory_tracker as std::rc::Rc<SigsegvMemoryTracker>
}
struct WasmtimeInstance {
system_api_handle: SystemApiHandle,
instance: wasmtime::Instance,
// if instance memory exists we need to keep the Arc alive as long as the
// Instance is alive. This is because we are sending the Weak pointer to a
// signal handler.
#[allow(dead_code)]
instance_memory: Option<Arc<wasmtime::Memory>>,
memory_tracker: Option<Rc<SigsegvMemoryTracker>>,
signal_stack: WasmtimeSignalStack,
canister_num_instructions_global: Rc<RefCell<Option<wasmtime::Global>>>,
log: ReplicaLogger,
}
impl WasmtimeInstance {
fn invoke_export(&mut self, export: &str, args: &[Val]) -> HypervisorResult<Vec<Val>> {
Ok(self
.instance
.get_export(export)
.ok_or_else(|| {
HypervisorError::MethodNotFound(WasmMethod::try_from(export.to_string()).unwrap())
})?
.into_func()
.ok_or_else(|| {
HypervisorError::ContractViolation("export is not a function".to_string())
})?
.call(args)
.map_err(trap_to_error)?
.to_vec())
}
fn dirty_pages(&self) -> Vec<PageIndex> {
if let Some(memory_tracker) = self.memory_tracker.as_ref() {
let base = memory_tracker.area().addr();
let page_size = *ic_sys::PAGE_SIZE;
memory_tracker
.dirty_pages()
.into_iter()
.map(|addr| {
let off = addr as usize - base as usize;
debug_assert!(off % page_size == 0);
let page_num = off / page_size;
PageIndex::from(page_num as u64)
})
.collect::<Vec<PageIndex>>()
} else {
debug!(
self.log,
"Memory tracking disabled. Returning empty list of dirty pages"
);
vec![]
}
}
fn memory(&self) -> HypervisorResult<Memory> {
match self.instance.get_export("memory") {
Some(export) => export.into_memory().ok_or_else(|| {
HypervisorError::ContractViolation("export 'memory' is not a memory".to_string())
}),
None => Err(HypervisorError::ContractViolation(
"export 'memory' not found".to_string(),
)),
}
}
}
impl Instance for WasmtimeInstance {
fn run(
&mut self,
system_api: &mut (dyn SystemApi + 'static),
func_ref: FuncRef,
) -> HypervisorResult<InstanceRunResult> {
self.system_api_handle.replace(system_api);
let _alt_sig_stack = unsafe { self.signal_stack.register() };
match &func_ref {
FuncRef::Method(wasm_method) => self.invoke_export(&wasm_method.to_string(), &[]),
FuncRef::QueryClosure(closure) | FuncRef::UpdateClosure(closure) => self
.instance
.get_export("table")
.ok_or_else(|| HypervisorError::ContractViolation("table not found".to_string()))?
.into_table()
.ok_or_else(|| {
HypervisorError::ContractViolation("export 'table' is not a table".to_string())
})?
.get(closure.func_idx)
.ok_or(HypervisorError::FunctionNotFound(0, closure.func_idx))?
.funcref()
.ok_or_else(|| {
HypervisorError::ContractViolation("not a function reference".to_string())
})?
.ok_or_else(|| {
HypervisorError::ContractViolation(
"unexpected null function reference".to_string(),
)
})?
.call(&[Val::I32(closure.env as i32)])
.map_err(trap_to_error)
.map(|boxed_slice| boxed_slice.to_vec()),
}
.map_err(|e| system_api.get_execution_error().cloned().unwrap_or(e))?;
self.system_api_handle.clear();
Ok(InstanceRunResult {
exported_globals: self.get_exported_globals(),
dirty_pages: self.dirty_pages(),
})
}
fn set_num_instructions(&mut self, num_instructions: NumInstructions) {
match &*self.canister_num_instructions_global.borrow_mut() {
Some(num_instructions_global) => {
match num_instructions_global.set(Val::I64(num_instructions.get() as i64)) {
Ok(_) => (),
Err(e) => panic!("couldn't set the num_instructions counter: {:?}", e),
}
}
None => panic!("couldn't find the num_instructions counter in the canister globals"),
}
}
fn get_num_instructions(&self) -> NumInstructions {
match &*self.canister_num_instructions_global.borrow() {
Some(num_instructions) => match num_instructions.get() {
Val::I64(num_instructions_i64) => {
NumInstructions::from(num_instructions_i64.max(0) as u64)
}
_ => panic!("invalid num_instructions counter type"),
},
None => panic!("couldn't find the num_instructions counter in the canister globals"),
}
}
fn heap_size(&self) -> NumWasmPages {
NumWasmPages::from(self.memory().map_or(0, |mem| mem.size()))
}
fn get_exported_globals(&self) -> Vec<Global> {
self.instance
.exports()
.filter_map(|e| e.into_global())
.map(|g| match g.ty().content() {
ValType::I32 => Global::I32(g.get().i32().expect("global i32")),
ValType::I64 => Global::I64(g.get().i64().expect("global i64")),
ValType::F32 => Global::F32(g.get().f32().expect("global f32")),
ValType::F64 => Global::F64(g.get().f64().expect("global f64")),
_ => panic!("unexpected global value type"),
})
.collect()
}
unsafe fn heap_addr(&self) -> *const u8 {
self.memory()
.map(|mem| mem.data_unchecked().as_ptr())
.unwrap_or_else(|_| std::ptr::null())
}
fn get_stats(&self) -> InstanceStats {
InstanceStats {
accessed_pages: self
.memory_tracker
.as_ref()
.map_or(0, |tracker| tracker.num_accessed_pages()),
dirty_pages: self
.memory_tracker
.as_ref()
.map_or(0, |tracker| tracker.num_dirty_pages()),
}
}
}
| 38.327381 | 110 | 0.566548 |
fced63b9ae530e56d8ccdef985740bb6ce9501d2 | 509 | use crate::*;
use near_sdk::json_types::ValidAccountId;
use oysterpack_smart_account_management::AccountStorageUsage;
use oysterpack_smart_near::domain::StorageUsage;
#[near_bindgen]
impl AccountStorageUsage for Contract {
fn ops_storage_usage_bounds(&self) -> StorageUsageBounds {
Self::account_manager().ops_storage_usage_bounds()
}
fn ops_storage_usage(&self, account_id: ValidAccountId) -> Option<StorageUsage> {
Self::account_manager().ops_storage_usage(account_id)
}
}
| 31.8125 | 85 | 0.766208 |
bfec023d7707890c80aee58437a6511a92fdf0c3 | 28,267 | use crate::rvsdg::{Node, NodeCtxt, NodeId, NodeKind, Sig, SigS, ValOrigin};
use std::{collections::HashMap, hash::Hash};
trait Lower<'g, 'h: 'g, S: Sig, T: Sig> {
fn lower(&mut self, node: Node<'h, S>, ncx: &'g NodeCtxt<T>) -> Node<'g, T>;
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Hir {
I32(i32),
Usize(usize),
Array(Vec<i32>),
GlobalState,
Subscript,
Add,
Sub,
Mul,
Div,
Le,
Lt,
Ge,
Gt,
And,
Or,
Xor,
Not,
Neg,
Shl,
Shr,
Mod,
}
impl Sig for Hir {
fn sig(&self) -> SigS {
match self {
Hir::I32(..) | Hir::Usize(..) | Hir::Array(..) => SigS {
val_outs: 1,
..SigS::default()
},
Hir::GlobalState => SigS {
st_outs: 1,
..SigS::default()
},
Hir::Add
| Hir::Subscript
| Hir::Mul
| Hir::Sub
| Hir::Div
| Hir::Le
| Hir::Lt
| Hir::Ge
| Hir::Gt
| Hir::And
| Hir::Or
| Hir::Xor
| Hir::Shl
| Hir::Shr
| Hir::Mod => SigS {
val_ins: 2,
val_outs: 1,
..SigS::default()
},
Hir::Not | Hir::Neg => SigS {
val_ins: 1,
val_outs: 1,
..SigS::default()
},
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Lir {
I32(i32),
Usize(usize),
Alloc,
Free,
GlobalState,
Load,
Store,
Add,
Sub,
Mul,
DivMod,
Cmp,
BitAnd,
BitOr,
BitXor,
BitNot,
Shl,
Shr,
Inc,
Dec,
Merge {
num_of_values: usize,
num_of_states: usize,
},
}
impl Sig for Lir {
fn sig(&self) -> SigS {
match self {
Lir::I32(..) | Lir::Usize(..) => SigS {
val_outs: 1,
..SigS::default()
},
Lir::Alloc => SigS {
val_ins: 1,
val_outs: 1,
st_outs: 1,
..SigS::default()
},
Lir::Free => SigS {
val_ins: 1,
..SigS::default()
},
Lir::GlobalState => SigS {
st_outs: 1,
..SigS::default()
},
Lir::Add
| Lir::Mul
| Lir::Sub
| Lir::Cmp
| Lir::BitAnd
| Lir::BitOr
| Lir::BitXor
| Lir::Shl
| Lir::Shr
| Lir::BitNot => SigS {
val_ins: 2,
val_outs: 1,
..SigS::default()
},
Lir::DivMod => SigS {
val_ins: 2,
val_outs: 2,
..SigS::default()
},
Lir::Inc | Lir::Dec => SigS {
val_ins: 1,
val_outs: 1,
..SigS::default()
},
Lir::Load => SigS {
val_ins: 1,
st_ins: 1,
val_outs: 1,
..SigS::default()
},
Lir::Store => SigS {
val_ins: 2,
st_ins: 1,
st_outs: 1,
..SigS::default()
},
Lir::Merge {
num_of_values,
num_of_states,
} => SigS {
val_ins: *num_of_values,
val_outs: *num_of_values,
st_ins: *num_of_states,
st_outs: 1,
..SigS::default()
},
}
}
}
struct HirToLir {
visited: HashMap<NodeId, NodeId>,
}
impl HirToLir {
fn new() -> HirToLir {
HirToLir {
visited: HashMap::new(),
}
}
}
impl<'g, 'h: 'g> Lower<'g, 'h, Hir, Lir> for HirToLir {
fn lower(&mut self, node: Node<'h, Hir>, ncx: &'g NodeCtxt<Lir>) -> Node<'g, Lir> {
if let Some(existing_node_id) = self.visited.get(&node.id()) {
return ncx.node_ref(*existing_node_id);
}
let node_kind = &*node.kind();
let op = match node_kind {
NodeKind::Op(op) => op,
_ => unimplemented!(),
};
let lir_node = match op {
Hir::I32(val) => ncx.mk_node(Lir::I32(*val)),
Hir::Usize(val) => ncx.mk_node(Lir::Usize(*val)),
Hir::Array(elems) => {
// Creates an allocation node for the array size, creates a store node for every
// array element, then merge all stores' state outputs.
let element_size_in_bytes = 4usize;
let array_length = ncx.mk_node(Lir::Usize(elems.len()));
let array_size_node = ncx
.node_builder(Lir::Mul)
.operand(array_length.val_out(0))
.operand(ncx.mk_node(Lir::Usize(element_size_in_bytes)).val_out(0))
.finish();
let alloc_node = ncx
.node_builder(Lir::Alloc)
.operand(array_size_node.val_out(0))
.finish();
let mut merge_node_builder = ncx.node_builder(Lir::Merge {
num_of_values: 1, // the array base address
num_of_states: elems.len(),
});
for (i, &val) in elems.iter().enumerate() {
let elem_byte_offset = ncx
.node_builder(Lir::Mul)
.operand(ncx.mk_node(Lir::Usize(i)).val_out(0))
.operand(ncx.mk_node(Lir::Usize(element_size_in_bytes)).val_out(0))
.finish();
let elem_addr = ncx
.node_builder(Lir::Add)
.operand(alloc_node.val_out(0))
.operand(elem_byte_offset.val_out(0))
.finish();
let store_node = ncx
.node_builder(Lir::Store)
.operand(elem_addr.val_out(0))
.operand(ncx.mk_node(Lir::I32(val)).val_out(0))
.state(alloc_node.st_out(0))
.finish();
merge_node_builder = merge_node_builder.state(store_node.st_out(0));
}
let merge_node = merge_node_builder.operand(alloc_node.val_out(0)).finish();
merge_node
}
Hir::GlobalState => ncx.mk_node(Lir::GlobalState),
Hir::Subscript => {
let base = self.lower(node.val_in(0).origin().producer(), ncx);
let index = self.lower(node.val_in(1).origin().producer(), ncx);
let state_port = if base.kind().sig().st_outs > 0 {
base.st_out(0)
} else {
ncx.mk_node(Lir::GlobalState).st_out(0)
};
let offset = ncx
.node_builder(Lir::Mul)
.operand(index.val_out(0))
.operand(ncx.mk_node(Lir::Usize(4)).val_out(0))
.finish();
let base_offset = ncx
.node_builder(Lir::Add)
.operand(base.val_out(0))
.operand(offset.val_out(0))
.finish();
ncx.node_builder(Lir::Load)
.operand(base_offset.val_out(0))
.state(state_port)
.finish()
}
Hir::Add => {
let lhs = self.lower(node.val_in(0).origin().producer(), ncx);
let rhs = self.lower(node.val_in(1).origin().producer(), ncx);
ncx.node_builder(Lir::Add)
.operand(lhs.val_out(0))
.operand(rhs.val_out(0))
.finish()
}
Hir::Sub => {
let lhs = self.lower(node.val_in(0).origin().producer(), ncx);
let rhs = self.lower(node.val_in(1).origin().producer(), ncx);
ncx.node_builder(Lir::Sub)
.operand(lhs.val_out(0))
.operand(rhs.val_out(0))
.finish()
}
Hir::Mul => {
let lhs = self.lower(node.val_in(0).origin().producer(), ncx);
let rhs = self.lower(node.val_in(1).origin().producer(), ncx);
ncx.node_builder(Lir::Mul)
.operand(lhs.val_out(0))
.operand(rhs.val_out(0))
.finish()
}
_ => unimplemented!(),
};
self.visited.insert(node.id(), lir_node.id());
lir_node
}
}
struct ConstFoldOpt<'graph, S> {
memory_stack: Vec<u8>,
alloc_stack_addrs: HashMap<ValOrigin<'graph, S>, usize>,
}
impl<'graph, S> ConstFoldOpt<'graph, S> {
fn new() -> ConstFoldOpt<'graph, S>
where
S: Eq + Hash,
{
ConstFoldOpt {
memory_stack: vec![],
alloc_stack_addrs: HashMap::new(),
}
}
}
impl<'g, 'h: 'g> Lower<'g, 'h, Lir, Lir> for ConstFoldOpt<'g, Lir> {
fn lower(&mut self, node: Node<'h, Lir>, ncx: &'g NodeCtxt<Lir>) -> Node<'g, Lir> {
let op = match &*node.kind() {
NodeKind::Op(op) => op.clone(),
_ => unimplemented!(),
};
// TODO: states = self.lower in st_ins
match op {
Lir::I32(val) => ncx.mk_node(Lir::I32(val)),
Lir::Usize(val) => ncx.mk_node(Lir::Usize(val)),
Lir::Alloc => {
let alloc_size_node = self.lower(node.val_in(0).origin().producer(), ncx);
match *alloc_size_node.kind() {
NodeKind::Op(Lir::Usize(val)) => {
let cur_sp = self.memory_stack.len();
self.memory_stack.resize(cur_sp + val, 0);
self.alloc_stack_addrs.insert(node.val_out(0), cur_sp);
}
_ => {}
}
ncx.node_builder(Lir::Alloc)
.operand(alloc_size_node.val_out(0))
.finish()
}
Lir::Add => {
let lhs = node.val_in(0).origin().producer();
let rhs = node.val_in(1).origin().producer();
match (lhs.kind().clone(), rhs.kind().clone()) {
(_, NodeKind::Op(Lir::I32(0))) => {
self.lower(lhs, ncx)
}
(NodeKind::Op(Lir::I32(0)), _) => {
self.lower(rhs, ncx)
}
(NodeKind::Op(Lir::I32(val_lhs)), NodeKind::Op(Lir::I32(val_rhs))) => {
ncx.mk_node(Lir::I32(val_lhs + val_rhs))
}
(_, NodeKind::Op(Lir::Usize(0))) => {
self.lower(lhs, ncx)
}
(NodeKind::Op(Lir::Usize(0)), _) => {
self.lower(rhs, ncx)
}
(NodeKind::Op(Lir::Usize(val_lhs)), NodeKind::Op(Lir::Usize(val_rhs))) => {
ncx.mk_node(Lir::Usize(val_lhs + val_rhs))
}
(NodeKind::Op(Lir::Usize(val)), NodeKind::Op(Lir::Alloc))
if self.alloc_stack_addrs.contains_key(&rhs.val_out(0)) =>
{
let stack_base_index = self.alloc_stack_addrs.get(&rhs.val_out(0)).unwrap();
ncx.mk_node(Lir::Usize(val + stack_base_index))
}
_ => {
let lhs = self.lower(node.val_in(0).origin().producer(), ncx);
let rhs = self.lower(node.val_in(1).origin().producer(), ncx);
let add_builder = ncx
.node_builder(Lir::Add)
.operand(lhs.val_out(0))
.operand(rhs.val_out(0));
let add = add_builder.finish();
add
}
}
}
Lir::Mul => {
let lhs = node.val_in(0).origin().producer();
let rhs = node.val_in(1).origin().producer();
match (lhs.kind().clone(), rhs.kind().clone()) {
(NodeKind::Op(Lir::I32(val_lhs)), NodeKind::Op(Lir::I32(val_rhs))) => {
ncx.mk_node(Lir::I32(val_lhs * val_rhs))
}
(NodeKind::Op(Lir::Usize(val_lhs)), NodeKind::Op(Lir::Usize(val_rhs))) => {
ncx.mk_node(Lir::Usize(val_lhs * val_rhs))
}
_ => {
let lhs = self.lower(lhs, ncx);
let rhs = self.lower(rhs, ncx);
ncx.node_builder(Lir::Add)
.operand(lhs.val_out(0))
.operand(rhs.val_out(0))
.finish()
}
}
}
_ => {
let mut node_builder = ncx.node_builder(op.clone());
for i in 0..op.sig().st_ins {
let opi = self.lower(node.st_in(i).origin().producer(), ncx);
node_builder = node_builder.state(opi.st_out(0));
}
for i in 0..op.sig().val_ins {
let opi = self.lower(node.val_in(i).origin().producer(), ncx);
node_builder = node_builder.operand(opi.val_out(0));
}
node_builder.finish()
}
}
}
}
#[cfg(test)]
mod test {
use super::{ConstFoldOpt, Hir, HirToLir, Lower};
use crate::rvsdg::{Node, NodeCtxt, NodeKind, Sig, SigS};
use std::io;
#[test]
fn hir_to_lir() {
let hir = NodeCtxt::new();
let subscript = hir
.node_builder(Hir::Subscript)
.operand(hir.mk_node(Hir::Usize(110)).val_out(0))
.operand(hir.mk_node(Hir::Usize(7)).val_out(0))
.finish();
let mut hir_buffer = Vec::new();
hir.print(&mut hir_buffer).unwrap();
let hir_content = String::from_utf8(hir_buffer).unwrap();
assert_eq!(
hir_content,
r#"digraph rvsdg {
node [shape=record]
edge [arrowhead=none]
n0 [label="{{Usize(110)}|{<o0>0}}"]
n1 [label="{{Usize(7)}|{<o0>0}}"]
n2 [label="{{<i0>0|<i1>1}|{Subscript}|{<o0>0}}"]
n0:o0 -> n2:i0 [color=blue]
n1:o0 -> n2:i1 [color=blue]
}
"#
);
let mut hir_to_lir = HirToLir::new();
let lir = NodeCtxt::new();
hir_to_lir.lower(subscript, &lir);
let mut lir_buffer = Vec::new();
lir.print(&mut lir_buffer).unwrap();
let lir_content = String::from_utf8(lir_buffer).unwrap();
assert_eq!(
lir_content,
r#"digraph rvsdg {
node [shape=record]
edge [arrowhead=none]
n0 [label="{{Usize(110)}|{<o0>0}}"]
n1 [label="{{Usize(7)}|{<o0>0}}"]
n2 [label="{{GlobalState}|{<o0>0}}"]
n3 [label="{{Usize(4)}|{<o0>0}}"]
n4 [label="{{<i0>0|<i1>1}|{Mul}|{<o0>0}}"]
n1:o0 -> n4:i0 [color=blue]
n3:o0 -> n4:i1 [color=blue]
n5 [label="{{<i0>0|<i1>1}|{Add}|{<o0>0}}"]
n0:o0 -> n5:i0 [color=blue]
n4:o0 -> n5:i1 [color=blue]
n6 [label="{{<i0>0|<i1>1}|{Load}|{<o0>0}}"]
n5:o0 -> n6:i0 [color=blue]
n2:o0 -> n6:i1 [style=dashed, color=red]
}
"#
);
}
#[test]
fn constant_folding() {
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Ir {
Lit(i32),
Var(&'static str),
Add,
}
impl Sig for Ir {
fn sig(&self) -> SigS {
match self {
Ir::Lit(..) => SigS {
val_outs: 1,
..<_>::default()
},
Ir::Var(..) => SigS {
val_outs: 1,
..<_>::default()
},
Ir::Add => SigS {
val_ins: 2,
val_outs: 1,
..<_>::default()
},
}
}
}
struct ConstFoldOpt;
impl<'g, 'h: 'g> Lower<'g, 'h, Ir, Ir> for ConstFoldOpt {
fn lower(&mut self, node: Node<'h, Ir>, ncx: &'g NodeCtxt<Ir>) -> Node<'g, Ir> {
let op = match node.kind().clone() {
NodeKind::Op(op) => op,
_ => unimplemented!(),
};
match op {
Ir::Lit(lit) => ncx.mk_node(Ir::Lit(lit)),
Ir::Var(var) => ncx.mk_node(Ir::Var(var)),
Ir::Add => {
let lhs = node.val_in(0).origin().producer();
let rhs = node.val_in(1).origin().producer();
match (lhs.kind().clone(), rhs.kind().clone()) {
(NodeKind::Op(Ir::Lit(val_lhs)), NodeKind::Op(Ir::Lit(val_rhs))) => {
ncx.mk_node(Ir::Lit(val_lhs + val_rhs))
}
_ => {
let lhs = self.lower(lhs, ncx);
let rhs = self.lower(rhs, ncx);
ncx.node_builder(Ir::Add)
.operand(lhs.val_out(0))
.operand(rhs.val_out(0))
.finish()
}
}
}
}
}
}
let ncx_noopt = NodeCtxt::new();
let n0 = ncx_noopt
.node_builder(Ir::Add)
.operand(ncx_noopt.mk_node(Ir::Lit(2)).val_out(0))
.operand(ncx_noopt.mk_node(Ir::Lit(3)).val_out(0))
.finish();
let n1 = ncx_noopt
.node_builder(Ir::Add)
.operand(n0.val_out(0))
.operand(ncx_noopt.mk_node(Ir::Var("x")).val_out(0))
.finish();
let mut noopt_buffer = Vec::new();
ncx_noopt.print(&mut noopt_buffer).unwrap();
let noopt_content = String::from_utf8(noopt_buffer).unwrap();
assert_eq!(
noopt_content,
r#"digraph rvsdg {
node [shape=record]
edge [arrowhead=none]
n0 [label="{{Lit(2)}|{<o0>0}}"]
n1 [label="{{Lit(3)}|{<o0>0}}"]
n2 [label="{{<i0>0|<i1>1}|{Add}|{<o0>0}}"]
n0:o0 -> n2:i0 [color=blue]
n1:o0 -> n2:i1 [color=blue]
n3 [label="{{Var("x")}|{<o0>0}}"]
n4 [label="{{<i0>0|<i1>1}|{Add}|{<o0>0}}"]
n2:o0 -> n4:i0 [color=blue]
n3:o0 -> n4:i1 [color=blue]
}
"#
);
let mut cfopt = ConstFoldOpt;
let ncx_opt = NodeCtxt::new();
cfopt.lower(n1, &ncx_opt);
let mut opt_buffer = Vec::new();
ncx_opt.print(&mut opt_buffer).unwrap();
let opt_content = String::from_utf8(opt_buffer).unwrap();
assert_eq!(
opt_content,
r#"digraph rvsdg {
node [shape=record]
edge [arrowhead=none]
n0 [label="{{Lit(5)}|{<o0>0}}"]
n1 [label="{{Var("x")}|{<o0>0}}"]
n2 [label="{{<i0>0|<i1>1}|{Add}|{<o0>0}}"]
n0:o0 -> n2:i0 [color=blue]
n1:o0 -> n2:i1 [color=blue]
}
"#
);
}
#[test]
fn array_10x42_to_stores() {
use crate::rvsdg::NodeCtxtConfig;
let hir = NodeCtxt::new();
let arr = hir.mk_node(Hir::Array(vec![42; 10]));
let subscript = hir
.node_builder(Hir::Subscript)
.operand(arr.val_out(0))
.operand(hir.mk_node(Hir::Usize(1)).val_out(0))
.finish();
hir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-10x42-hir - nodes({}), edges({})",
hir.num_nodes(),
hir.num_edges()
);
let mut hir_to_lir = HirToLir::new();
let lir = NodeCtxt::with_config(NodeCtxtConfig {
opt_interning: false,
});
let merge = hir_to_lir.lower(subscript.clone(), &lir);
lir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-10x42-lir - nodes({}), edges({})",
lir.num_nodes(),
lir.num_edges()
);
let mut hir_to_lir = HirToLir::new();
let lir = NodeCtxt::with_config(NodeCtxtConfig {
opt_interning: true,
});
let merge = hir_to_lir.lower(subscript, &lir);
lir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-10x42-lir-valuenum - nodes({}), edges({})",
lir.num_nodes(),
lir.num_edges()
);
let lir_opt = NodeCtxt::new();
let mut const_fold = ConstFoldOpt::new();
let _ = const_fold.lower(merge, &lir_opt);
lir_opt.print(&mut io::stdout().lock()).unwrap();
println!(
"array-10x42-lir-valuenum-constfold - nodes({}), edges({})",
lir_opt.num_nodes(),
lir_opt.num_edges()
);
}
#[test]
fn array_0to9_to_stores() {
use crate::rvsdg::NodeCtxtConfig;
{
let hir = NodeCtxt::with_config(NodeCtxtConfig { opt_interning: false });
let arr1 = hir.mk_node(Hir::Array((0..2).collect()));
let arr2 = hir.mk_node(Hir::Array((0..2).collect()));
let subscript1 = hir
.node_builder(Hir::Subscript)
.operand(arr1.val_out(0))
.operand(hir.mk_node(Hir::Usize(1)).val_out(0))
.finish();
let subscript2 = hir
.node_builder(Hir::Subscript)
.operand(arr2.val_out(0))
.operand(hir.mk_node(Hir::Usize(1)).val_out(0))
.finish();
let add = hir
.node_builder(Hir::Add)
.operand(subscript1.val_out(0))
.operand(subscript2.val_out(0))
.finish();
hir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-0to9-hir noopt - nodes({}), edges({})",
hir.num_nodes(),
hir.num_edges()
);
}
let hir = NodeCtxt::new();
let arr1 = hir.mk_node(Hir::Array((0..4).collect()));
let arr2 = hir.mk_node(Hir::Array((0..4).collect()));
let subscript1 = hir
.node_builder(Hir::Subscript)
.operand(arr1.val_out(0))
.operand(hir.mk_node(Hir::Usize(1)).val_out(0))
.finish();
let subscript2 = hir
.node_builder(Hir::Subscript)
.operand(arr2.val_out(0))
.operand(hir.mk_node(Hir::Usize(1)).val_out(0))
.finish();
let add = hir
.node_builder(Hir::Add)
.operand(subscript1.val_out(0))
.operand(subscript2.val_out(0))
.finish();
hir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-0to9-hir noopt - nodes({}), edges({})",
hir.num_nodes(),
hir.num_edges()
);
let mut hir_to_lir = HirToLir::new();
let lir = NodeCtxt::with_config(NodeCtxtConfig {
opt_interning: false,
});
let merge = hir_to_lir.lower(add.clone(), &lir);
lir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-0to9-lir - nodes({}), edges({})",
lir.num_nodes(),
lir.num_edges()
);
let mut hir_to_lir = HirToLir::new();
let lir = NodeCtxt::with_config(NodeCtxtConfig {
opt_interning: true,
});
let merge = hir_to_lir.lower(add, &lir);
lir.print(&mut io::stdout().lock()).unwrap();
println!(
"array-0to9-lir-valuenum - nodes({}), edges({})",
lir.num_nodes(),
lir.num_edges()
);
let lir_opt1 = NodeCtxt::new();
let lir_opt2 = NodeCtxt::new();
let mut const_fold = ConstFoldOpt::new();
let merge1 = const_fold.lower(merge, &lir_opt1);
let _ = const_fold.lower(merge1, &lir_opt2);
lir_opt2.print(&mut io::stdout().lock()).unwrap();
println!(
"array-0to9-lir-valuenum-constfold - nodes({}), edges({})",
lir_opt2.num_nodes(),
lir_opt2.num_edges()
);
}
#[test]
#[should_panic]
fn bug_traverse() {
struct Traverser;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum D {
A(usize),
B,
}
impl Sig for D {
fn sig(&self) -> SigS {
match self {
D::A(..) => SigS {
val_outs: 1,
..SigS::default()
},
D::B => SigS {
val_ins: 2,
val_outs: 1,
..SigS::default()
},
}
}
}
impl<'g, 'h: 'g> Lower<'g, 'h, D, D> for Traverser {
fn lower(&mut self, node: Node<'h, D>, ncx: &'g NodeCtxt<D>) -> Node<'g, D> {
let op = match &*node.kind() {
NodeKind::Op(op) => op.clone(),
_ => unreachable!(),
};
match op {
D::A(val) => {
println!("D::A");
ncx.mk_node(D::A(10))
}
D::B => {
let p1 = self.lower(node.val_in(0).origin().producer(), ncx);
let p2 = self.lower(node.val_in(1).origin().producer(), ncx);
match (p1.kind().clone(), p2.kind().clone()) {
(NodeKind::Op(D::A(l)), NodeKind::Op(D::A(r))) => {
let x = ncx.mk_node(D::A(l + r));
println!("two D::A");
x
}
_ => {
println!("D::B");
ncx.node_builder(D::B)
.operand(p1.val_out(0))
.operand(p2.val_out(0))
.finish()
}
}
}
}
}
}
let ncx = NodeCtxt::new();
let a1 = ncx.mk_node(D::A(2));
let a2 = ncx.mk_node(D::A(3));
let b1 = ncx
.node_builder(D::B)
.operand(a1.val_out(0))
.operand(a2.val_out(0))
.finish();
let mut trav = Traverser;
let ncx_out = NodeCtxt::new();
let x = trav.lower(b1, &ncx_out);
}
#[test]
fn unreachable_code_elimination() {
let hir = NodeCtxt::new();
let n_sub = hir
.node_builder(Hir::Sub)
.operand(hir.mk_node(Hir::I32(2)).val_out(0))
.operand(hir.mk_node(Hir::I32(5)).val_out(0))
.finish();
let n_add = hir
.node_builder(Hir::Add)
.operand(n_sub.val_out(0))
.operand(hir.mk_node(Hir::I32(8)).val_out(0))
.finish();
let n_mul = hir
.node_builder(Hir::Mul)
.operand(hir.mk_node(Hir::I32(2)).val_out(0))
.operand(hir.mk_node(Hir::I32(5)).val_out(0))
.finish();
hir.print(&mut io::stdout().lock()).unwrap();
let mut hir_to_lir = HirToLir::new();
let lir = NodeCtxt::new();
let lir_add = hir_to_lir.lower(n_add, &lir);
lir.print(&mut io::stdout().lock()).unwrap();
}
}
| 32.231471 | 100 | 0.426681 |
79cd133a6135d6769c82e487144e0fc973468c7e | 1,957 | //! Utilities for serialize/deserialize vectors.
#![cfg(target_pointer_width = "64")]
use std::io::{Read, Write};
use std::mem::size_of;
use anyhow::Result;
use super::IntIO;
/// Trait to serialize/deserialize vectors of integers.
pub trait VecIO {
/// The vector type.
type Vec;
/// Serializes the vector into the writer,
/// returning the number of serialized bytes.
///
/// # Arguments
///
/// - `writer`: [`std::io::Write`] variable.
fn serialize_into<W: Write>(&self, writer: W) -> Result<usize>;
/// Deserializes the vector from the reader.
///
/// # Arguments
///
/// - `reader`: [`std::io::Read`] variable.
fn deserialize_from<R: Read>(reader: R) -> Result<Self::Vec>;
/// Returns the number of bytes to serialize the vector.
fn size_in_bytes(&self) -> usize;
}
macro_rules! common_def {
($int:ident) => {
impl VecIO for Vec<$int> {
type Vec = Vec<$int>;
fn serialize_into<W: Write>(&self, mut writer: W) -> Result<usize> {
let mut mem = self.len().serialize_into(&mut writer)?;
for x in self {
mem += x.serialize_into(&mut writer)?;
}
Ok(mem)
}
fn deserialize_from<R: Read>(mut reader: R) -> Result<Self::Vec> {
let len = usize::deserialize_from(&mut reader)?;
let mut vec = Vec::with_capacity(len);
for _ in 0..len {
vec.push($int::deserialize_from(&mut reader)?);
}
Ok(vec)
}
fn size_in_bytes(&self) -> usize {
size_of::<u64>() + ($int::size_in_bytes() * self.len())
}
}
};
}
common_def!(u8);
common_def!(u16);
common_def!(u32);
common_def!(u64);
common_def!(usize);
common_def!(i8);
common_def!(i16);
common_def!(i32);
common_def!(i64);
common_def!(isize);
| 26.445946 | 80 | 0.541134 |
181308e493ce308afbc79cd4b015cd6414ec92da | 3,492 | use crate::gen::RustCodeGenerator;
use crate::model::rust::{DataEnum, Field};
use crate::model::sql::Sql;
use crate::model::{Model, RustType};
pub(crate) fn select_statement_single(name: &str) -> String {
format!("SELECT * FROM {} WHERE id = $1", name)
}
#[cfg(feature = "async-psql")]
pub(crate) fn select_statement_many(name: &str) -> String {
format!("SELECT * FROM {} WHERE id = ANY($1)", name)
}
pub(crate) fn tuple_struct_insert_statement(name: &str) -> String {
format!("INSERT INTO {} DEFAULT VALUES RETURNING id", name)
}
pub(crate) fn struct_insert_statement(name: &str, fields: &[Field]) -> String {
format!(
"INSERT INTO {}({}) VALUES({}) RETURNING id",
name,
fields
.iter()
.filter_map(|field| if field.r#type().is_vec() {
None
} else {
Some(Model::sql_column_name(field.name()))
})
.collect::<Vec<String>>()
.join(", "),
fields
.iter()
.filter_map(|field| if field.r#type().is_vec() {
None
} else {
Some(field.name())
})
.enumerate()
.map(|(num, _)| format!("${}", num + 1))
.collect::<Vec<String>>()
.join(", "),
)
}
pub(crate) fn data_enum_insert_statement(name: &str, enumeration: &DataEnum) -> String {
format!(
"INSERT INTO {}({}) VALUES({}) RETURNING id",
name,
enumeration
.variants()
.map(|variant| RustCodeGenerator::rust_module_name(variant.name()))
.collect::<Vec<String>>()
.join(", "),
enumeration
.variants()
.enumerate()
.map(|(num, _)| format!("${}", num + 1))
.collect::<Vec<String>>()
.join(", "),
)
}
pub(crate) fn struct_list_entry_insert_statement(struct_name: &str, field_name: &str) -> String {
format!(
"INSERT INTO {}(list, value) VALUES ($1, $2)",
Model::<Sql>::struct_list_entry_table_name(struct_name, field_name),
)
}
pub(crate) fn struct_list_entry_select_referenced_value_statement(
struct_name: &str,
field_name: &str,
other_type: &str,
) -> String {
let listentry_table = Model::<Sql>::struct_list_entry_table_name(struct_name, field_name);
format!(
"SELECT * FROM {} WHERE id IN (SELECT value FROM {} WHERE list = $1)",
RustCodeGenerator::rust_variant_name(other_type),
listentry_table,
)
}
pub(crate) fn struct_list_entry_select_value_statement(
struct_name: &str,
field_name: &str,
) -> String {
let listentry_table = Model::<Sql>::struct_list_entry_table_name(struct_name, field_name);
format!("SELECT value FROM {} WHERE list = $1", listentry_table,)
}
pub(crate) fn list_entry_insert_statement(name: &str) -> String {
format!("INSERT INTO {}ListEntry(list, value) VALUES ($1, $2)", name)
}
pub(crate) fn list_entry_query_statement(name: &str, inner: &RustType) -> String {
if Model::<Sql>::is_primitive(inner) {
format!(
"SELECT value FROM {}ListEntry WHERE {}ListEntry.list = $1",
name, name
)
} else {
let inner = inner.clone().as_inner_type().to_string();
format!(
"SELECT * FROM {} INNER JOIN {}ListEntry ON {}.id = {}ListEntry.value WHERE {}ListEntry.list = $1",
inner, name, inner, name, name
)
}
}
| 31.745455 | 111 | 0.566724 |
c1c528e8354639b9a9ac0e71af1c8d3985d52548 | 5,999 | use diesel::{self, prelude::*, dsl};
use errors::SResult;
use models::question_option::{QuestionOption, QuestionOptionForm, QuestionOptionsUpdate};
use schema::test_questions;
use uuid::Uuid;
use Context;
#[derive(Identifiable, Queryable)]
pub struct TestQuestion {
pub id: i32,
pub uuid: Uuid,
pub question: String,
pub test_paper_id: i32,
}
impl TestQuestion {
pub fn find(id: i32, conn: &PgConnection) -> SResult<TestQuestion> {
Ok(test_questions::table.find(id).get_result(conn)?)
}
pub fn find_all(test_paper_id: i32, conn: &PgConnection) -> SResult<Vec<TestQuestion>> {
Ok(test_questions::table
.filter(test_questions::test_paper_id.eq(test_paper_id))
.load(conn)?)
}
pub fn find_by_uuid_for_test_paper(
uuid: Uuid,
test_paper_id: i32,
conn: &PgConnection,
) -> SResult<TestQuestion> {
Ok(test_questions::table
.filter(
test_questions::test_paper_id
.eq(test_paper_id)
.and(test_questions::uuid.eq(uuid)),
).get_result(conn)?)
}
pub fn count_questions_for_paper(test_paper_id: i32, conn: &PgConnection) -> SResult<i32> {
let count: i64 = test_questions::table
.filter(test_questions::test_paper_id.eq(test_paper_id))
.select(dsl::count_star())
.get_result(conn)?;
Ok(count as i32)
}
fn delete_multiple(vec: Vec<Uuid>, test_paper_id: i32, conn: &PgConnection) -> SResult<()> {
let delete_count = diesel::delete(
test_questions::table.filter(
test_questions::uuid
.eq_any(&vec)
.and(test_questions::test_paper_id.eq(test_paper_id)),
),
).execute(conn)?;
if delete_count != vec.len() {
Err(diesel::NotFound)?;
}
Ok(())
}
}
graphql_object!(TestQuestion: Context |&self| {
description: "A type representing a test question."
field id() -> Uuid
as "Id of a question."
{
self.uuid
}
field question() -> &str
as "The actual question."
{
&self.question
}
field options(&executor) -> SResult<Vec<QuestionOption>>
as "Options of a question."
{
QuestionOption::find_all(self.id, &executor.context().conn)
}
field option(&executor, id: Uuid) -> SResult<QuestionOption>
as "Option of a question with the given id."
{
QuestionOption::find_by_uuid_for_test_question(id, self.id, &executor.context().conn)
}
});
#[derive(Insertable)]
#[table_name = "test_questions"]
struct NewTestQuestion {
question: String,
test_paper_id: i32,
}
impl NewTestQuestion {
fn save(self, conn: &PgConnection) -> SResult<i32> {
Ok(diesel::insert_into(test_questions::table)
.values(self)
.returning(test_questions::id)
.get_result(conn)?)
}
}
#[derive(AsChangeset)]
#[table_name = "test_questions"]
struct TestQuestionPatch {
question: Option<String>,
}
impl TestQuestionPatch {
fn save(self, uuid: Uuid, test_paper_id: i32, conn: &PgConnection) -> SResult<i32> {
let id = diesel::update(
test_questions::table.filter(
test_questions::uuid
.eq(uuid)
.and(test_questions::test_paper_id.eq(test_paper_id)),
),
).set(self)
.returning(test_questions::id)
.get_result(conn)?;
Ok(id)
}
fn save_or_find(self, uuid: Uuid, test_paper_id: i32, conn: &PgConnection) -> SResult<i32> {
if self.question.is_some() {
self.save(uuid, test_paper_id, conn)
} else {
Ok(TestQuestion::find_by_uuid_for_test_paper(uuid, test_paper_id, conn)?.id)
}
}
}
/// A type to create new test question.
#[derive(GraphQLInputObject)]
pub struct TestQuestionForm {
/// Question text.
question: String,
/// List of options for this question.
options: Vec<QuestionOptionForm>,
}
impl TestQuestionForm {
pub fn save_multiple(
vec: Vec<TestQuestionForm>,
test_paper_id: i32,
conn: &PgConnection,
) -> SResult<()> {
for quest in vec {
let new_quest = NewTestQuestion {
question: quest.question,
test_paper_id,
};
let new_id = new_quest.save(conn)?;
QuestionOptionForm::save_multiple(quest.options, new_id, conn)?;
}
Ok(())
}
}
/// A type to update a test question.
#[derive(GraphQLInputObject)]
struct TestQuestionUpdate {
/// Id of a test question.
id: Uuid,
/// New question text.
question: Option<String>,
/// Update type for options.
options: QuestionOptionsUpdate,
}
impl TestQuestionUpdate {
fn save_multiple(
vec: Vec<TestQuestionUpdate>,
test_paper_id: i32,
conn: &PgConnection,
) -> SResult<()> {
for quest in vec {
let quest_patch = TestQuestionPatch {
question: quest.question,
};
let question_id = quest_patch.save_or_find(quest.id, test_paper_id, conn)?;
quest.options.save(question_id, conn)?;
}
Ok(())
}
}
/// A type to update questions.
#[derive(GraphQLInputObject)]
pub struct TestQuestionsUpdate {
/// List of new questions.
new: Vec<TestQuestionForm>,
/// List of updated questions.
update: Vec<TestQuestionUpdate>,
/// List of ids to delete older questions.
remove: Vec<Uuid>,
}
impl TestQuestionsUpdate {
pub fn save(self, test_paper_id: i32, conn: &PgConnection) -> SResult<()> {
TestQuestionForm::save_multiple(self.new, test_paper_id, conn)?;
TestQuestionUpdate::save_multiple(self.update, test_paper_id, conn)?;
TestQuestion::delete_multiple(self.remove, test_paper_id, conn)?;
Ok(())
}
}
| 28.43128 | 96 | 0.6026 |
fcb9f70cd768d66f1b17dbe9b74af7982a259d35 | 42,950 | use std::io::{BufRead, Seek, Write};
use super::*;
// This library was code-generated using an experimental CDDL to rust tool:
// https://github.com/Emurgo/cddl-codegen
use cbor_event::{self, de::Deserializer, se::{Serialize, Serializer}};
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PlutusScript(Vec<u8>);
to_from_bytes!(PlutusScript);
#[wasm_bindgen]
impl PlutusScript {
/**
* Creates a new Plutus script from the RAW bytes of the compiled script.
* This does NOT include any CBOR encoding around these bytes (e.g. from "cborBytes" in cardano-cli)
* If you creating this from those you should use PlutusScript::from_bytes() instead.
*/
pub fn new(bytes: Vec<u8>) -> PlutusScript {
Self(bytes)
}
/**
* The raw bytes of this compiled Plutus script.
* If you need "cborBytes" for cardano-cli use PlutusScript::to_bytes() instead.
*/
pub fn bytes(&self) -> Vec<u8> {
self.0.clone()
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PlutusScripts(Vec<PlutusScript>);
to_from_bytes!(PlutusScripts);
#[wasm_bindgen]
impl PlutusScripts {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> PlutusScript {
self.0[index].clone()
}
pub fn add(&mut self, elem: &PlutusScript) {
self.0.push(elem.clone());
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ConstrPlutusData {
alternative: BigNum,
data: PlutusList,
}
to_from_bytes!(ConstrPlutusData);
#[wasm_bindgen]
impl ConstrPlutusData {
pub fn alternative(&self) -> BigNum {
self.alternative.clone()
}
pub fn data(&self) -> PlutusList {
self.data.clone()
}
pub fn new(alternative: &BigNum, data: &PlutusList) -> Self {
Self {
alternative: alternative.clone(),
data: data.clone(),
}
}
}
impl ConstrPlutusData {
// see: https://github.com/input-output-hk/plutus/blob/1f31e640e8a258185db01fa899da63f9018c0e85/plutus-core/plutus-core/src/PlutusCore/Data.hs#L61
// We don't directly serialize the alternative in the tag, instead the scheme is:
// - Alternatives 0-6 -> tags 121-127, followed by the arguments in a list
// - Alternatives 7-127 -> tags 1280-1400, followed by the arguments in a list
// - Any alternatives, including those that don't fit in the above -> tag 102 followed by a list containing
// an unsigned integer for the actual alternative, and then the arguments in a (nested!) list.
const GENERAL_FORM_TAG: u64 = 102;
// None -> needs general tag serialization, not compact
fn alternative_to_compact_cbor_tag(alt: u64) -> Option<u64> {
if alt <= 6 {
Some(121 + alt)
} else if alt >= 7 && alt <= 127 {
Some(1280 - 7 + alt)
} else {
None
}
}
// None -> General tag(=102) OR Invalid CBOR tag for this scheme
fn compact_cbor_tag_to_alternative(cbor_tag: u64) -> Option<u64> {
if cbor_tag >= 121 && cbor_tag <= 127 {
Some(cbor_tag - 121)
} else if cbor_tag >= 1280 && cbor_tag <= 1400 {
Some(cbor_tag - 1280 + 7)
} else {
None
}
}
}
const COST_MODEL_OP_COUNT: usize = 166;
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct CostModel(Vec<Int>);
to_from_bytes!(CostModel);
#[wasm_bindgen]
impl CostModel {
pub fn new() -> Self {
let mut costs = Vec::with_capacity(COST_MODEL_OP_COUNT);
for _ in 0 .. COST_MODEL_OP_COUNT {
costs.push(Int::new_i32(0));
}
Self(costs)
}
pub fn set(&mut self, operation: usize, cost: &Int) -> Result<Int, JsError> {
if operation >= COST_MODEL_OP_COUNT {
return Err(JsError::from_str(&format!("CostModel operation {} out of bounds. Max is {}", operation, COST_MODEL_OP_COUNT)));
}
let old = self.0[operation].clone();
self.0[operation] = cost.clone();
Ok(old)
}
pub fn get(&self, operation: usize) -> Result<Int, JsError> {
if operation >= COST_MODEL_OP_COUNT {
return Err(JsError::from_str(&format!("CostModel operation {} out of bounds. Max is {}", operation, COST_MODEL_OP_COUNT)));
}
Ok(self.0[operation].clone())
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Costmdls(std::collections::BTreeMap<Language, CostModel>);
to_from_bytes!(Costmdls);
#[wasm_bindgen]
impl Costmdls {
pub fn new() -> Self {
Self(std::collections::BTreeMap::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn insert(&mut self, key: &Language, value: &CostModel) -> Option<CostModel> {
self.0.insert(key.clone(), value.clone())
}
pub fn get(&self, key: &Language) -> Option<CostModel> {
self.0.get(key).map(|v| v.clone())
}
pub fn keys(&self) -> Languages {
Languages(self.0.iter().map(|(k, _v)| k.clone()).collect::<Vec<_>>())
}
pub(crate) fn language_views_encoding(&self) -> Vec<u8> {
let mut serializer = Serializer::new_vec();
let mut keys_bytes: Vec<(Language, Vec<u8>)> = self.0.iter().map(|(k, _v)| (k.clone(), k.to_bytes())).collect();
// keys must be in canonical ordering first
keys_bytes.sort_by(|lhs, rhs| match lhs.1.len().cmp(&rhs.1.len()) {
std::cmp::Ordering::Equal => lhs.1.cmp(&rhs.1),
len_order => len_order,
});
serializer.write_map(cbor_event::Len::Len(self.0.len() as u64)).unwrap();
for (key, key_bytes) in keys_bytes.iter() {
serializer.write_bytes(key_bytes).unwrap();
let cost_model = self.0.get(&key).unwrap();
// Due to a bug in the cardano-node input-output-hk/cardano-ledger-specs/issues/2512
// we must use indefinite length serialization in this inner bytestring to match it
let mut cost_model_serializer = Serializer::new_vec();
cost_model_serializer.write_array(cbor_event::Len::Indefinite).unwrap();
for cost in &cost_model.0 {
cost.serialize(&mut cost_model_serializer).unwrap();
}
cost_model_serializer.write_special(cbor_event::Special::Break).unwrap();
serializer.write_bytes(cost_model_serializer.finalize()).unwrap();
}
let out = serializer.finalize();
println!("language_views = {}", hex::encode(out.clone()));
out
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExUnitPrices {
mem_price: SubCoin,
step_price: SubCoin,
}
to_from_bytes!(ExUnitPrices);
#[wasm_bindgen]
impl ExUnitPrices {
pub fn mem_price(&self) -> SubCoin {
self.mem_price.clone()
}
pub fn step_price(&self) -> SubCoin {
self.step_price.clone()
}
pub fn new(mem_price: &SubCoin, step_price: &SubCoin) -> Self {
Self {
mem_price: mem_price.clone(),
step_price: step_price.clone(),
}
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExUnits {
// TODO: should these be u32 or BigNum?
mem: BigNum,
steps: BigNum,
}
to_from_bytes!(ExUnits);
#[wasm_bindgen]
impl ExUnits {
pub fn mem(&self) -> BigNum {
self.mem.clone()
}
pub fn steps(&self) -> BigNum {
self.steps.clone()
}
pub fn new(mem: &BigNum, steps: &BigNum) -> Self {
Self {
mem: mem.clone(),
steps: steps.clone(),
}
}
}
#[wasm_bindgen]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum LanguageKind {
PlutusV1,
}
#[wasm_bindgen]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Language(LanguageKind);
to_from_bytes!(Language);
#[wasm_bindgen]
impl Language {
pub fn new_plutus_v1() -> Self {
Self(LanguageKind::PlutusV1)
}
pub fn kind(&self) -> LanguageKind {
self.0
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Languages(Vec<Language>);
#[wasm_bindgen]
impl Languages {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Language {
self.0[index]
}
pub fn add(&mut self, elem: Language) {
self.0.push(elem);
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PlutusMap(std::collections::BTreeMap<PlutusData, PlutusData>);
to_from_bytes!(PlutusMap);
#[wasm_bindgen]
impl PlutusMap {
pub fn new() -> Self {
Self(std::collections::BTreeMap::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn insert(&mut self, key: &PlutusData, value: &PlutusData) -> Option<PlutusData> {
self.0.insert(key.clone(), value.clone())
}
pub fn get(&self, key: &PlutusData) -> Option<PlutusData> {
self.0.get(key).map(|v| v.clone())
}
pub fn keys(&self) -> PlutusList {
PlutusList {
elems: self.0.iter().map(|(k, _v)| k.clone()).collect::<Vec<_>>(),
definite_encoding: None,
}
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum PlutusDataKind {
ConstrPlutusData,
Map,
List,
Integer,
Bytes,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum PlutusDataEnum {
ConstrPlutusData(ConstrPlutusData),
Map(PlutusMap),
List(PlutusList),
Integer(BigInt),
Bytes(Vec<u8>),
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PlutusData {
datum: PlutusDataEnum,
// We should always preserve the original datums when deserialized as this is NOT canonicized
// before computing datum hashes. So this field stores the original bytes to re-use.
original_bytes: Option<Vec<u8>>,
}
to_from_bytes!(PlutusData);
#[wasm_bindgen]
impl PlutusData {
pub fn new_constr_plutus_data(constr_plutus_data: &ConstrPlutusData) -> Self {
Self {
datum: PlutusDataEnum::ConstrPlutusData(constr_plutus_data.clone()),
original_bytes: None,
}
}
pub fn new_map(map: &PlutusMap) -> Self {
Self {
datum: PlutusDataEnum::Map(map.clone()),
original_bytes: None,
}
}
pub fn new_list(list: &PlutusList) -> Self {
Self {
datum: PlutusDataEnum::List(list.clone()),
original_bytes: None,
}
}
pub fn new_integer(integer: &BigInt) -> Self {
Self {
datum: PlutusDataEnum::Integer(integer.clone()),
original_bytes: None,
}
}
pub fn new_bytes(bytes: Vec<u8>) -> Self {
Self {
datum: PlutusDataEnum::Bytes(bytes),
original_bytes: None,
}
}
pub fn kind(&self) -> PlutusDataKind {
match &self.datum {
PlutusDataEnum::ConstrPlutusData(_) => PlutusDataKind::ConstrPlutusData,
PlutusDataEnum::Map(_) => PlutusDataKind::Map,
PlutusDataEnum::List(_) => PlutusDataKind::List,
PlutusDataEnum::Integer(_) => PlutusDataKind::Integer,
PlutusDataEnum::Bytes(_) => PlutusDataKind::Bytes,
}
}
pub fn as_constr_plutus_data(&self) -> Option<ConstrPlutusData> {
match &self.datum {
PlutusDataEnum::ConstrPlutusData(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_map(&self) -> Option<PlutusMap> {
match &self.datum {
PlutusDataEnum::Map(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_list(&self) -> Option<PlutusList> {
match &self.datum {
PlutusDataEnum::List(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_integer(&self) -> Option<BigInt> {
match &self.datum {
PlutusDataEnum::Integer(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_bytes(&self) -> Option<Vec<u8>> {
match &self.datum {
PlutusDataEnum::Bytes(x) => Some(x.clone()),
_ => None,
}
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PlutusList {
elems: Vec<PlutusData>,
// We should always preserve the original datums when deserialized as this is NOT canonicized
// before computing datum hashes. This field will default to cardano-cli behavior if None
// and will re-use the provided one if deserialized, unless the list is modified.
definite_encoding: Option<bool>,
}
to_from_bytes!(PlutusList);
#[wasm_bindgen]
impl PlutusList {
pub fn new() -> Self {
Self {
elems: Vec::new(),
definite_encoding: None,
}
}
pub fn len(&self) -> usize {
self.elems.len()
}
pub fn get(&self, index: usize) -> PlutusData {
self.elems[index].clone()
}
pub fn add(&mut self, elem: &PlutusData) {
self.elems.push(elem.clone());
self.definite_encoding = None;
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Redeemer {
tag: RedeemerTag,
index: BigNum,
data: PlutusData,
ex_units: ExUnits,
}
to_from_bytes!(Redeemer);
#[wasm_bindgen]
impl Redeemer {
pub fn tag(&self) -> RedeemerTag {
self.tag.clone()
}
pub fn index(&self) -> BigNum {
self.index.clone()
}
pub fn data(&self) -> PlutusData {
self.data.clone()
}
pub fn ex_units(&self) -> ExUnits {
self.ex_units.clone()
}
pub fn new(tag: &RedeemerTag, index: &BigNum, data: &PlutusData, ex_units: &ExUnits) -> Self {
Self {
tag: tag.clone(),
index: index.clone(),
data: data.clone(),
ex_units: ex_units.clone(),
}
}
}
#[wasm_bindgen]
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum RedeemerTagKind {
Spend,
Mint,
Cert,
Reward,
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct RedeemerTag(RedeemerTagKind);
to_from_bytes!(RedeemerTag);
#[wasm_bindgen]
impl RedeemerTag {
pub fn new_spend() -> Self {
Self(RedeemerTagKind::Spend)
}
pub fn new_mint() -> Self {
Self(RedeemerTagKind::Mint)
}
pub fn new_cert() -> Self {
Self(RedeemerTagKind::Cert)
}
pub fn new_reward() -> Self {
Self(RedeemerTagKind::Reward)
}
pub fn kind(&self) -> RedeemerTagKind {
self.0
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Redeemers(Vec<Redeemer>);
to_from_bytes!(Redeemers);
#[wasm_bindgen]
impl Redeemers {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Redeemer {
self.0[index].clone()
}
pub fn add(&mut self, elem: &Redeemer) {
self.0.push(elem.clone());
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Strings(Vec<String>);
#[wasm_bindgen]
impl Strings {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> String {
self.0[index].clone()
}
pub fn add(&mut self, elem: String) {
self.0.push(elem);
}
}
// Serialization
use std::io::{SeekFrom};
impl cbor_event::se::Serialize for PlutusScript {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_bytes(&self.0)
}
}
impl Deserialize for PlutusScript {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
Ok(Self(raw.bytes()?))
}
}
impl cbor_event::se::Serialize for PlutusScripts {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
element.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for PlutusScripts {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len { cbor_event::Len::Len(n) => arr.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(PlutusScript::deserialize(raw)?);
}
Ok(())
})().map_err(|e| e.annotate("PlutusScripts"))?;
Ok(Self(arr))
}
}
// TODO: write tests for this hand-coded implementation?
impl cbor_event::se::Serialize for ConstrPlutusData {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
if let Some(compact_tag) = Self::alternative_to_compact_cbor_tag(from_bignum(&self.alternative)) {
// compact form
serializer.write_tag(compact_tag as u64)?;
self.data.serialize(serializer)
} else {
// general form
serializer.write_tag(Self::GENERAL_FORM_TAG)?;
serializer.write_array(cbor_event::Len::Len(2))?;
self.alternative.serialize(serializer)?;
self.data.serialize(serializer)
}
}
}
impl Deserialize for ConstrPlutusData {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let (alternative, data) = match raw.tag()? {
// general form
Self::GENERAL_FORM_TAG => {
let len = raw.array()?;
let mut read_len = CBORReadLen::new(len);
read_len.read_elems(2)?;
let alternative = BigNum::deserialize(raw)?;
let data = (|| -> Result<_, DeserializeError> {
Ok(PlutusList::deserialize(raw)?)
})().map_err(|e| e.annotate("datas"))?;
match len {
cbor_event::Len::Len(_) => (),
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break => (),
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
(alternative, data)
},
// concise form
tag => {
if let Some(alternative) = Self::compact_cbor_tag_to_alternative(tag) {
(to_bignum(alternative), PlutusList::deserialize(raw)?)
} else {
return Err(DeserializeFailure::TagMismatch{
found: tag,
expected: Self::GENERAL_FORM_TAG,
}.into());
}
},
};
Ok(ConstrPlutusData{
alternative,
data,
})
})().map_err(|e| e.annotate("ConstrPlutusData"))
}
}
impl cbor_event::se::Serialize for CostModel {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(COST_MODEL_OP_COUNT as u64))?;
for cost in &self.0 {
cost.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for CostModel {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len { cbor_event::Len::Len(n) => arr.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(Int::deserialize(raw)?);
}
if arr.len() != COST_MODEL_OP_COUNT {
return Err(DeserializeFailure::OutOfRange{
min: COST_MODEL_OP_COUNT,
max: COST_MODEL_OP_COUNT,
found: arr.len()
}.into());
}
Ok(())
})().map_err(|e| e.annotate("CostModel"))?;
Ok(Self(arr.try_into().unwrap()))
}
}
impl cbor_event::se::Serialize for Costmdls {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_map(cbor_event::Len::Len(self.0.len() as u64))?;
for (key, value) in &self.0 {
key.serialize(serializer)?;
value.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for Costmdls {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut table = std::collections::BTreeMap::new();
(|| -> Result<_, DeserializeError> {
let len = raw.map()?;
while match len { cbor_event::Len::Len(n) => table.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
let key = Language::deserialize(raw)?;
let value = CostModel::deserialize(raw)?;
if table.insert(key.clone(), value).is_some() {
return Err(DeserializeFailure::DuplicateKey(Key::Str(String::from("some complicated/unsupported type"))).into());
}
}
Ok(())
})().map_err(|e| e.annotate("Costmdls"))?;
Ok(Self(table))
}
}
impl cbor_event::se::Serialize for ExUnitPrices {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(2))?;
self.mem_price.serialize(serializer)?;
self.step_price.serialize(serializer)?;
Ok(serializer)
}
}
impl Deserialize for ExUnitPrices {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let mut read_len = CBORReadLen::new(len);
read_len.read_elems(2)?;
let mem_price = (|| -> Result<_, DeserializeError> {
Ok(SubCoin::deserialize(raw)?)
})().map_err(|e| e.annotate("mem_price"))?;
let step_price = (|| -> Result<_, DeserializeError> {
Ok(SubCoin::deserialize(raw)?)
})().map_err(|e| e.annotate("step_price"))?;
match len {
cbor_event::Len::Len(_) => (),
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break => (),
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
Ok(ExUnitPrices {
mem_price,
step_price,
})
})().map_err(|e| e.annotate("ExUnitPrices"))
}
}
impl cbor_event::se::Serialize for ExUnits {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(2))?;
self.mem.serialize(serializer)?;
self.steps.serialize(serializer)?;
Ok(serializer)
}
}
impl Deserialize for ExUnits {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let mut read_len = CBORReadLen::new(len);
read_len.read_elems(2)?;
let mem = (|| -> Result<_, DeserializeError> {
Ok(BigNum::deserialize(raw)?)
})().map_err(|e| e.annotate("mem"))?;
let steps = (|| -> Result<_, DeserializeError> {
Ok(BigNum::deserialize(raw)?)
})().map_err(|e| e.annotate("steps"))?;
match len {
cbor_event::Len::Len(_) => (),
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break => (),
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
Ok(ExUnits {
mem,
steps,
})
})().map_err(|e| e.annotate("ExUnits"))
}
}
impl cbor_event::se::Serialize for Language {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
match self.0 {
LanguageKind::PlutusV1 => {
serializer.write_unsigned_integer(0u64)
},
}
}
}
impl Deserialize for Language {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
match raw.unsigned_integer()? {
0 => Ok(Language::new_plutus_v1()),
_ => Err(DeserializeError::new("Language", DeserializeFailure::NoVariantMatched.into())),
}
})().map_err(|e| e.annotate("Language"))
}
}
impl cbor_event::se::Serialize for Languages {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
element.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for Languages {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len { cbor_event::Len::Len(n) => arr.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(Language::deserialize(raw)?);
}
Ok(())
})().map_err(|e| e.annotate("Languages"))?;
Ok(Self(arr))
}
}
impl cbor_event::se::Serialize for PlutusMap {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_map(cbor_event::Len::Len(self.0.len() as u64))?;
for (key, value) in &self.0 {
key.serialize(serializer)?;
value.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for PlutusMap {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut table = std::collections::BTreeMap::new();
(|| -> Result<_, DeserializeError> {
let len = raw.map()?;
while match len { cbor_event::Len::Len(n) => table.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
let key = PlutusData::deserialize(raw)?;
let value = PlutusData::deserialize(raw)?;
if table.insert(key.clone(), value).is_some() {
return Err(DeserializeFailure::DuplicateKey(Key::Str(String::from("some complicated/unsupported type"))).into());
}
}
Ok(())
})().map_err(|e| e.annotate("PlutusMap"))?;
Ok(Self(table))
}
}
impl cbor_event::se::Serialize for PlutusDataEnum {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
match self {
PlutusDataEnum::ConstrPlutusData(x) => {
x.serialize(serializer)
},
PlutusDataEnum::Map(x) => {
x.serialize(serializer)
},
PlutusDataEnum::List(x) => {
x.serialize(serializer)
},
PlutusDataEnum::Integer(x) => {
x.serialize(serializer)
},
PlutusDataEnum::Bytes(x) => {
write_bounded_bytes(serializer, &x)
},
}
}
}
impl Deserialize for PlutusDataEnum {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let initial_position = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap();
match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
Ok(ConstrPlutusData::deserialize(raw)?)
})(raw)
{
Ok(variant) => return Ok(PlutusDataEnum::ConstrPlutusData(variant)),
Err(_) => raw.as_mut_ref().seek(SeekFrom::Start(initial_position)).unwrap(),
};
match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
Ok(PlutusMap::deserialize(raw)?)
})(raw)
{
Ok(variant) => return Ok(PlutusDataEnum::Map(variant)),
Err(_) => raw.as_mut_ref().seek(SeekFrom::Start(initial_position)).unwrap(),
};
match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
Ok(PlutusList::deserialize(raw)?)
})(raw)
{
Ok(variant) => return Ok(PlutusDataEnum::List(variant)),
Err(_) => raw.as_mut_ref().seek(SeekFrom::Start(initial_position)).unwrap(),
};
match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
Ok(BigInt::deserialize(raw)?)
})(raw)
{
Ok(variant) => return Ok(PlutusDataEnum::Integer(variant)),
Err(_) => raw.as_mut_ref().seek(SeekFrom::Start(initial_position)).unwrap(),
};
match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
Ok(read_bounded_bytes(raw)?)
})(raw)
{
Ok(variant) => return Ok(PlutusDataEnum::Bytes(variant)),
Err(_) => raw.as_mut_ref().seek(SeekFrom::Start(initial_position)).unwrap(),
};
Err(DeserializeError::new("PlutusDataEnum", DeserializeFailure::NoVariantMatched.into()))
})().map_err(|e| e.annotate("PlutusDataEnum"))
}
}
impl cbor_event::se::Serialize for PlutusData {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
match &self.original_bytes {
Some(bytes) => serializer.write_raw_bytes(bytes),
None => self.datum.serialize(serializer),
}
}
}
impl Deserialize for PlutusData {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
// these unwraps are fine since we're seeking the current position
let before = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap();
let datum = PlutusDataEnum::deserialize(raw)?;
let after = raw.as_mut_ref().seek(SeekFrom::Current(0)).unwrap();
let bytes_read = (after - before) as usize;
raw.as_mut_ref().seek(SeekFrom::Start(before)).unwrap();
// these unwraps are fine since we read the above already
let original_bytes = raw.as_mut_ref().fill_buf().unwrap()[..bytes_read].to_vec();
raw.as_mut_ref().consume(bytes_read);
Ok(Self {
datum,
original_bytes: Some(original_bytes),
})
}
}
impl cbor_event::se::Serialize for PlutusList {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
let use_definite_encoding = match self.definite_encoding {
Some(definite) => definite,
None => self.elems.is_empty(),
};
if use_definite_encoding {
serializer.write_array(cbor_event::Len::Len(self.elems.len() as u64))?;
} else {
serializer.write_array(cbor_event::Len::Indefinite)?;
}
for element in &self.elems {
element.serialize(serializer)?;
}
if !use_definite_encoding {
serializer.write_special(cbor_event::Special::Break)?;
}
Ok(serializer)
}
}
impl Deserialize for PlutusList {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
let len = (|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len { cbor_event::Len::Len(n) => arr.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(PlutusData::deserialize(raw)?);
}
Ok(len)
})().map_err(|e| e.annotate("PlutusList"))?;
Ok(Self {
elems: arr,
definite_encoding: Some(len != cbor_event::Len::Indefinite),
})
}
}
impl cbor_event::se::Serialize for Redeemer {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(4))?;
self.tag.serialize(serializer)?;
self.index.serialize(serializer)?;
self.data.serialize(serializer)?;
self.ex_units.serialize(serializer)?;
Ok(serializer)
}
}
impl Deserialize for Redeemer {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let mut read_len = CBORReadLen::new(len);
read_len.read_elems(4)?;
let tag = (|| -> Result<_, DeserializeError> {
Ok(RedeemerTag::deserialize(raw)?)
})().map_err(|e| e.annotate("tag"))?;
let index = (|| -> Result<_, DeserializeError> {
Ok(BigNum::deserialize(raw)?)
})().map_err(|e| e.annotate("index"))?;
let data = (|| -> Result<_, DeserializeError> {
Ok(PlutusData::deserialize(raw)?)
})().map_err(|e| e.annotate("data"))?;
let ex_units = (|| -> Result<_, DeserializeError> {
Ok(ExUnits::deserialize(raw)?)
})().map_err(|e| e.annotate("ex_units"))?;
match len {
cbor_event::Len::Len(_) => (),
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break => (),
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
Ok(Redeemer {
tag,
index,
data,
ex_units,
})
})().map_err(|e| e.annotate("Redeemer"))
}
}
impl cbor_event::se::Serialize for RedeemerTagKind {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
match self {
RedeemerTagKind::Spend => {
serializer.write_unsigned_integer(0u64)
},
RedeemerTagKind::Mint => {
serializer.write_unsigned_integer(1u64)
},
RedeemerTagKind::Cert => {
serializer.write_unsigned_integer(2u64)
},
RedeemerTagKind::Reward => {
serializer.write_unsigned_integer(3u64)
},
}
}
}
impl Deserialize for RedeemerTagKind {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
match raw.unsigned_integer() {
Ok(0) => Ok(RedeemerTagKind::Spend),
Ok(1) => Ok(RedeemerTagKind::Mint),
Ok(2) => Ok(RedeemerTagKind::Cert),
Ok(3) => Ok(RedeemerTagKind::Reward),
Ok(_) | Err(_) => Err(DeserializeFailure::NoVariantMatched.into()),
}
})().map_err(|e| e.annotate("RedeemerTagEnum"))
}
}
impl cbor_event::se::Serialize for RedeemerTag {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
self.0.serialize(serializer)
}
}
impl Deserialize for RedeemerTag {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
Ok(Self(RedeemerTagKind::deserialize(raw)?))
}
}
impl cbor_event::se::Serialize for Redeemers {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
element.serialize(serializer)?;
}
Ok(serializer)
}
}
impl Deserialize for Redeemers {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len { cbor_event::Len::Len(n) => arr.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(Redeemer::deserialize(raw)?);
}
Ok(())
})().map_err(|e| e.annotate("Redeemers"))?;
Ok(Self(arr))
}
}
impl cbor_event::se::Serialize for Strings {
fn serialize<'se, W: Write>(&self, serializer: &'se mut Serializer<W>) -> cbor_event::Result<&'se mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(self.0.len() as u64))?;
for element in &self.0 {
serializer.write_text(&element)?;
}
Ok(serializer)
}
}
impl Deserialize for Strings {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
let mut arr = Vec::new();
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
while match len { cbor_event::Len::Len(n) => arr.len() < n as usize, cbor_event::Len::Indefinite => true, } {
if raw.cbor_type()? == CBORType::Special {
assert_eq!(raw.special()?, CBORSpecial::Break);
break;
}
arr.push(String::deserialize(raw)?);
}
Ok(())
})().map_err(|e| e.annotate("Strings"))?;
Ok(Self(arr))
}
}
#[cfg(test)]
mod tests {
use super::*;
use hex::*;
#[test]
pub fn plutus_constr_data() {
let constr_0 = PlutusData::new_constr_plutus_data(
&ConstrPlutusData::new(&to_bignum(0), &PlutusList::new())
);
let constr_0_hash = hex::encode(hash_plutus_data(&constr_0).to_bytes());
assert_eq!(constr_0_hash, "923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec");
let constr_0_roundtrip = PlutusData::from_bytes(constr_0.to_bytes()).unwrap();
// TODO: do we want semantic equality or bytewise equality?
//assert_eq!(constr_0, constr_0_roundtrip);
let constr_1854 = PlutusData::new_constr_plutus_data(
&ConstrPlutusData::new(&to_bignum(1854), &PlutusList::new())
);
let constr_1854_roundtrip = PlutusData::from_bytes(constr_1854.to_bytes()).unwrap();
//assert_eq!(constr_1854, constr_1854_roundtrip);
}
#[test]
pub fn plutus_list_serialization_cli_compatibility() {
// mimic cardano-cli array encoding, see https://github.com/Emurgo/cardano-serialization-lib/issues/227
let datum_cli = "d8799f4100d8799fd8799fd8799f581cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd8799fd8799fd8799f581cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd87a80ff1a002625a0d8799fd879801a000f4240d87a80ffff";
let datum = PlutusData::from_bytes(Vec::from_hex(datum_cli).unwrap()).unwrap();
assert_eq!(datum_cli, hex::encode(datum.to_bytes()));
// encode empty arrays as fixed
assert_eq!("80", hex::encode(PlutusList::new().to_bytes()));
// encode arrays as indefinite length array
let mut list = PlutusList::new();
list.add(&PlutusData::new_integer(&BigInt::from_str("1").unwrap()));
assert_eq!("9f01ff", hex::encode(list.to_bytes()));
// witness_set should have fixed length array
let mut witness_set = TransactionWitnessSet::new();
witness_set.set_plutus_data(&list);
assert_eq!("a1048101", hex::encode(witness_set.to_bytes()));
list = PlutusList::new();
list.add(&datum);
witness_set.set_plutus_data(&list);
assert_eq!(format!("a10481{}", datum_cli), hex::encode(witness_set.to_bytes()));
}
#[test]
pub fn plutus_datums_respect_deserialized_encoding() {
let orig_bytes = Vec::from_hex("81d8799f581ce1cbb80db89e292269aeb93ec15eb963dda5176b66949fe1c2a6a38da140a1401864ff").unwrap();
let datums = PlutusList::from_bytes(orig_bytes.clone()).unwrap();
let new_bytes = datums.to_bytes();
assert_eq!(orig_bytes, new_bytes);
}
}
| 33.268784 | 253 | 0.568498 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.