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
fe3553229667fee6652f38584c68958585aa70b7
2,788
use buf::{Buf, MutBuf}; use os; use error::MioResult; use self::NonBlock::{Ready, WouldBlock}; use error::MioErrorKind as mek; #[deriving(Show)] pub enum NonBlock<T> { Ready(T), WouldBlock } impl<T> NonBlock<T> { pub fn would_block(&self) -> bool { match *self { WouldBlock => true, _ => false } } pub fn unwrap(self) -> T { match self { Ready(v) => v, _ => panic!("would have blocked, no result to take") } } } pub trait IoHandle { fn desc(&self) -> &os::IoDesc; } pub trait IoReader { fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<(uint)>>; } pub trait IoWriter { fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<(uint)>>; } pub trait IoAcceptor<T> { fn accept(&mut self) -> MioResult<NonBlock<T>>; } pub fn pipe() -> MioResult<(PipeReader, PipeWriter)> { let (rd, wr) = try!(os::pipe()); Ok((PipeReader { desc: rd }, PipeWriter { desc: wr })) } pub struct PipeReader { desc: os::IoDesc } impl IoHandle for PipeReader { fn desc(&self) -> &os::IoDesc { &self.desc } } pub struct PipeWriter { desc: os::IoDesc } impl IoHandle for PipeWriter { fn desc(&self) -> &os::IoDesc { &self.desc } } impl IoReader for PipeReader { fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<(uint)>> { read(self, buf) } } impl IoWriter for PipeWriter { fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<(uint)>> { write(self, buf) } } /// Reads the length of the slice supplied by buf.mut_bytes into the buffer /// This is not guaranteed to consume an entire datagram or segment. /// If your protocol is msg based (instead of continuous stream) you should /// ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo /// frames) #[inline] pub fn read<I: IoHandle>(io: &mut I, buf: &mut MutBuf) -> MioResult<NonBlock<uint>> { match os::read(io.desc(), buf.mut_bytes()) { // Successfully read some bytes, advance the cursor Ok(cnt) => { buf.advance(cnt); Ok(Ready(cnt)) } Err(e) => { match e.kind { mek::WouldBlock => Ok(WouldBlock), _ => Err(e) } } } } ///writes the length of the slice supplied by Buf.bytes into the socket #[inline] pub fn write<O: IoHandle>(io: &mut O, buf: &mut Buf) -> MioResult<NonBlock<uint>> { match os::write(io.desc(), buf.bytes()) { Ok(cnt) => { buf.advance(cnt); Ok(Ready(cnt)) } Err(e) => { match e.kind { mek::WouldBlock => Ok(WouldBlock), _ => Err(e) } } } }
23.627119
94
0.560617
e688bcd9a18ebf241681abfd752b36921e54451d
1,767
//! ockam_node - Ockam Node API #![deny( missing_docs, dead_code, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications )] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate core; #[cfg(feature = "alloc")] #[macro_use] extern crate alloc; #[macro_use] extern crate tracing; #[cfg(not(feature = "std"))] pub use ockam_executor::{interrupt, tokio}; #[cfg(feature = "std")] pub use tokio; mod address_record; mod context; mod error; mod executor; mod mailbox; mod messages; mod node; mod parser; mod relay; mod router; mod tests; pub(crate) use address_record::*; pub use context::*; pub use executor::*; pub use mailbox::*; pub use messages::*; pub use node::{start_node, NullWorker}; #[cfg(feature = "std")] use core::future::Future; #[cfg(feature = "std")] use tokio::{runtime::Runtime, task}; /// Execute a future without blocking the executor /// /// This is a wrapper around two simple tokio functions to allow /// ockam_node to wait for a task to be completed in a non-async /// environment. /// /// This function is not meant to be part of the ockam public API, but /// as an implementation utility for other ockam utilities that use /// tokio. #[doc(hidden)] #[cfg(feature = "std")] pub fn block_future<'r, F>(rt: &'r Runtime, f: F) -> <F as Future>::Output where F: Future + Send, F::Output: Send, { task::block_in_place(move || { let local = task::LocalSet::new(); local.block_on(rt, f) }) } #[doc(hidden)] #[cfg(feature = "std")] pub fn spawn<F: 'static>(f: F) where F: Future + Send, F::Output: Send, { task::spawn(f); } #[cfg(not(feature = "std"))] pub use crate::tokio::runtime::{block_future, spawn};
20.310345
74
0.660441
6719242da308a3be94565d6ecabc60630546cd4b
10,357
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ epoch_manager::LivenessStorageData, persistent_liveness_storage::{ LedgerRecoveryData, PersistentLivenessStorage, RecoveryData, RootMetadata, }, }; use anyhow::Result; use consensus_types::{ block::Block, common::Payload, quorum_cert::QuorumCert, timeout_certificate::TimeoutCertificate, vote::Vote, }; use libra_crypto::HashValue; use libra_types::{ epoch_change::EpochChangeProof, ledger_info::{LedgerInfo, LedgerInfoWithSignatures}, on_chain_config::ValidatorSet, }; use std::{ collections::{BTreeMap, HashMap}, marker::PhantomData, sync::{Arc, Mutex}, }; use storage_interface::DbReader; pub struct MockSharedStorage<T> { // Safety state pub block: Mutex<HashMap<HashValue, Block<T>>>, pub qc: Mutex<HashMap<HashValue, QuorumCert>>, pub lis: Mutex<HashMap<u64, LedgerInfoWithSignatures>>, pub last_vote: Mutex<Option<Vote>>, // Liveness state pub highest_timeout_certificate: Mutex<Option<TimeoutCertificate>>, pub validator_set: ValidatorSet, } impl<T: Payload> MockSharedStorage<T> { pub fn new(validator_set: ValidatorSet) -> Self { MockSharedStorage { block: Mutex::new(HashMap::new()), qc: Mutex::new(HashMap::new()), lis: Mutex::new(HashMap::new()), last_vote: Mutex::new(None), highest_timeout_certificate: Mutex::new(None), validator_set, } } } /// A storage that simulates the operations in-memory, used in the tests that cares about storage /// consistency. pub struct MockStorage<T> { pub shared_storage: Arc<MockSharedStorage<T>>, storage_ledger: Mutex<LedgerInfo>, } impl<T: Payload> MockStorage<T> { pub fn new(shared_storage: Arc<MockSharedStorage<T>>) -> Self { let validator_set = Some(shared_storage.validator_set.clone()); let li = LedgerInfo::mock_genesis(validator_set); let lis = LedgerInfoWithSignatures::new(li.clone(), BTreeMap::new()); shared_storage .lis .lock() .unwrap() .insert(lis.ledger_info().version(), lis); MockStorage { shared_storage, storage_ledger: Mutex::new(li), } } pub fn new_with_ledger_info( shared_storage: Arc<MockSharedStorage<T>>, ledger_info: LedgerInfo, ) -> Self { let li = if ledger_info.next_epoch_info().is_some() { ledger_info.clone() } else { let validator_set = Some(shared_storage.validator_set.clone()); LedgerInfo::mock_genesis(validator_set) }; let lis = LedgerInfoWithSignatures::new(li, BTreeMap::new()); shared_storage .lis .lock() .unwrap() .insert(lis.ledger_info().version(), lis); MockStorage { shared_storage, storage_ledger: Mutex::new(ledger_info), } } pub fn get_ledger_info(&self) -> LedgerInfo { self.storage_ledger.lock().unwrap().clone() } pub fn commit_to_storage(&self, ledger: LedgerInfo) { *self.storage_ledger.lock().unwrap() = ledger; if let Err(e) = self.verify_consistency() { panic!("invalid db after commit: {}", e); } } pub fn get_validator_set(&self) -> &ValidatorSet { &self.shared_storage.validator_set } pub fn get_ledger_recovery_data(&self) -> LedgerRecoveryData { LedgerRecoveryData::new(self.storage_ledger.lock().unwrap().clone()) } pub fn try_start(&self) -> Result<RecoveryData<T>> { let ledger_recovery_data = self.get_ledger_recovery_data(); let mut blocks: Vec<_> = self .shared_storage .block .lock() .unwrap() .clone() .into_iter() .map(|(_, v)| v) .collect(); let quorum_certs = self .shared_storage .qc .lock() .unwrap() .clone() .into_iter() .map(|(_, v)| v) .collect(); blocks.sort_by_key(Block::round); RecoveryData::new( self.shared_storage.last_vote.lock().unwrap().clone(), ledger_recovery_data, blocks, RootMetadata::new_empty(), quorum_certs, self.shared_storage .highest_timeout_certificate .lock() .unwrap() .clone(), ) } pub fn verify_consistency(&self) -> Result<()> { self.try_start().map(|_| ()) } pub fn start_for_testing(validator_set: ValidatorSet) -> (RecoveryData<T>, Arc<Self>) { let shared_storage = Arc::new(MockSharedStorage { block: Mutex::new(HashMap::new()), qc: Mutex::new(HashMap::new()), lis: Mutex::new(HashMap::new()), last_vote: Mutex::new(None), highest_timeout_certificate: Mutex::new(None), validator_set: validator_set.clone(), }); let genesis_li = LedgerInfo::mock_genesis(Some(validator_set)); let storage = Self::new_with_ledger_info(shared_storage, genesis_li); let recovery_data = storage .start() .expect_recovery_data("Mock storage should never fail constructing recovery data"); (recovery_data, Arc::new(storage)) } } // A impl that always start from genesis. impl<T: Payload> PersistentLivenessStorage<T> for MockStorage<T> { fn save_tree(&self, blocks: Vec<Block<T>>, quorum_certs: Vec<QuorumCert>) -> Result<()> { // When the shared storage is empty, we are expected to not able to construct an block tree // from it. During test we will intentionally clear shared_storage to simulate the situation // of restarting from an empty consensusDB let should_check_for_consistency = !(self.shared_storage.block.lock().unwrap().is_empty() && self.shared_storage.qc.lock().unwrap().is_empty()); for block in blocks { self.shared_storage .block .lock() .unwrap() .insert(block.id(), block); } for qc in quorum_certs { self.shared_storage .qc .lock() .unwrap() .insert(qc.certified_block().id(), qc); } if should_check_for_consistency { if let Err(e) = self.verify_consistency() { panic!("invalid db after save tree: {}", e); } } Ok(()) } fn prune_tree(&self, block_id: Vec<HashValue>) -> Result<()> { for id in block_id { self.shared_storage.block.lock().unwrap().remove(&id); self.shared_storage.qc.lock().unwrap().remove(&id); } if let Err(e) = self.verify_consistency() { panic!("invalid db after prune tree: {}", e); } Ok(()) } fn save_vote(&self, last_vote: &Vote) -> Result<()> { self.shared_storage .last_vote .lock() .unwrap() .replace(last_vote.clone()); Ok(()) } fn recover_from_ledger(&self) -> LedgerRecoveryData { self.get_ledger_recovery_data() } fn start(&self) -> LivenessStorageData<T> { match self.try_start() { Ok(recovery_data) => LivenessStorageData::RecoveryData(recovery_data), Err(_) => LivenessStorageData::LedgerRecoveryData(self.recover_from_ledger()), } } fn save_highest_timeout_cert( &self, highest_timeout_certificate: TimeoutCertificate, ) -> Result<()> { self.shared_storage .highest_timeout_certificate .lock() .unwrap() .replace(highest_timeout_certificate); Ok(()) } fn retrieve_epoch_change_proof(&self, version: u64) -> Result<EpochChangeProof> { let lis = self .shared_storage .lis .lock() .unwrap() .get(&version) .cloned() .ok_or_else(|| anyhow::anyhow!("LedgerInfo for version not found"))?; Ok(EpochChangeProof::new(vec![lis], false)) } fn libra_db(&self) -> Arc<dyn DbReader> { unimplemented!() } } /// A storage that ignores any requests, used in the tests that don't care about the storage. pub struct EmptyStorage<T> { _phantom: PhantomData<T>, } impl<T: Payload> EmptyStorage<T> { pub fn new() -> Self { Self { _phantom: PhantomData, } } pub fn start_for_testing() -> (RecoveryData<T>, Arc<Self>) { let storage = Arc::new(EmptyStorage::new()); let recovery_data = storage .start() .expect_recovery_data("Empty storage should never fail constructing recovery data"); (recovery_data, storage) } } impl<T: Payload> PersistentLivenessStorage<T> for EmptyStorage<T> { fn save_tree(&self, _: Vec<Block<T>>, _: Vec<QuorumCert>) -> Result<()> { Ok(()) } fn prune_tree(&self, _: Vec<HashValue>) -> Result<()> { Ok(()) } fn save_vote(&self, _: &Vote) -> Result<()> { Ok(()) } fn recover_from_ledger(&self) -> LedgerRecoveryData { LedgerRecoveryData::new(LedgerInfo::mock_genesis(None)) } fn start(&self) -> LivenessStorageData<T> { match RecoveryData::new( None, self.recover_from_ledger(), vec![], RootMetadata::new_empty(), vec![], None, ) { Ok(recovery_data) => LivenessStorageData::RecoveryData(recovery_data), Err(e) => { eprintln!("{}", e); panic!("Construct recovery data during genesis should never fail"); } } } fn save_highest_timeout_cert(&self, _: TimeoutCertificate) -> Result<()> { Ok(()) } fn retrieve_epoch_change_proof(&self, _version: u64) -> Result<EpochChangeProof> { unimplemented!() } fn libra_db(&self) -> Arc<dyn DbReader> { unimplemented!() } }
31.102102
100
0.574394
fe46a29dab8fd5df300809d3430eb23904e294a6
1,812
use std::rc::Rc; use awsm_web::loaders::helpers::AsyncLoader; use futures_signals::signal::Mutable; use shared::domain::jig::JigId; use utils::jig::JigPlayerOptions; use utils::routes::{AssetRoute, Route}; use utils::prelude::*; pub struct ShareJig { pub active_popup: Mutable<Option<ActivePopup>>, pub student_code: Mutable<Option<String>>, pub loader: AsyncLoader, pub jig_id: JigId, pub copied_embed: Mutable<bool>, pub link_copied: Mutable<bool>, pub copied_student_url: Mutable<bool>, pub copied_student_code: Mutable<bool>, } impl ShareJig { pub fn new(jig_id: JigId) -> Rc<Self> { Rc::new(Self { jig_id, student_code: Mutable::new(None), loader: AsyncLoader::new(), active_popup: Mutable::new(None), copied_embed: Mutable::new(false), link_copied: Mutable::new(false), copied_student_url: Mutable::new(false), copied_student_code: Mutable::new(false), }) } pub fn embed_code(&self) -> String { let link = self.jig_link(true); format!( r#"<iframe src="{}" width="960" height="540"></iframe>"#, link ) } pub fn jig_link(&self, is_student: bool) -> String { let url = Route::Asset(AssetRoute::Play(AssetPlayRoute::Jig( self.jig_id, None, JigPlayerOptions { is_student, ..Default::default() }, ))) .to_string(); let origin = web_sys::window() .unwrap_ji() .location() .origin() .unwrap_ji(); format!("{}{}", origin, url) } } #[derive(Clone)] pub enum ActivePopup { ShareMain, ShareStudents, ShareEmbed, }
25.885714
69
0.56457
0eac96fc39a4b1d2ae3bfd12701afeb646867ac0
10,857
use crate::cmp; use crate::io::{self, SeekFrom, Read, Initializer, Write, Seek, BufRead, Error, ErrorKind, IoVecMut, IoVec}; use crate::fmt; use crate::mem; // ============================================================================= // Forwarding implementations #[stable(feature = "rust1", since = "1.0.0")] impl<R: Read + ?Sized> Read for &mut R { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) } #[inline] fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> { (**self).read_vectored(bufs) } #[inline] unsafe fn initializer(&self) -> Initializer { (**self).initializer() } #[inline] fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_to_end(buf) } #[inline] fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { (**self).read_to_string(buf) } #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { (**self).read_exact(buf) } } #[stable(feature = "rust1", since = "1.0.0")] impl<W: Write + ?Sized> Write for &mut W { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) } #[inline] fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> { (**self).write_vectored(bufs) } #[inline] fn flush(&mut self) -> io::Result<()> { (**self).flush() } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { (**self).write_all(buf) } #[inline] fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { (**self).write_fmt(fmt) } } #[stable(feature = "rust1", since = "1.0.0")] impl<S: Seek + ?Sized> Seek for &mut S { #[inline] fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) } } #[stable(feature = "rust1", since = "1.0.0")] impl<B: BufRead + ?Sized> BufRead for &mut B { #[inline] fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() } #[inline] fn consume(&mut self, amt: usize) { (**self).consume(amt) } #[inline] fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_until(byte, buf) } #[inline] fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { (**self).read_line(buf) } } #[stable(feature = "rust1", since = "1.0.0")] impl<R: Read + ?Sized> Read for Box<R> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) } #[inline] fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> { (**self).read_vectored(bufs) } #[inline] unsafe fn initializer(&self) -> Initializer { (**self).initializer() } #[inline] fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_to_end(buf) } #[inline] fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { (**self).read_to_string(buf) } #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { (**self).read_exact(buf) } } #[stable(feature = "rust1", since = "1.0.0")] impl<W: Write + ?Sized> Write for Box<W> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) } #[inline] fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> { (**self).write_vectored(bufs) } #[inline] fn flush(&mut self) -> io::Result<()> { (**self).flush() } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { (**self).write_all(buf) } #[inline] fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { (**self).write_fmt(fmt) } } #[stable(feature = "rust1", since = "1.0.0")] impl<S: Seek + ?Sized> Seek for Box<S> { #[inline] fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) } } #[stable(feature = "rust1", since = "1.0.0")] impl<B: BufRead + ?Sized> BufRead for Box<B> { #[inline] fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() } #[inline] fn consume(&mut self, amt: usize) { (**self).consume(amt) } #[inline] fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_until(byte, buf) } #[inline] fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { (**self).read_line(buf) } } // Used by panicking::default_hook #[cfg(test)] /// This impl is only used by printing logic, so any error returned is always /// of kind `Other`, and should be ignored. impl Write for Box<dyn (::realstd::io::Write) + Send> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf).map_err(|_| ErrorKind::Other.into()) } fn flush(&mut self) -> io::Result<()> { (**self).flush().map_err(|_| ErrorKind::Other.into()) } } // ============================================================================= // In-memory buffer implementations /// Read is implemented for `&[u8]` by copying from the slice. /// /// Note that reading updates the slice to point to the yet unread part. /// The slice will be empty when EOF is reached. #[stable(feature = "rust1", since = "1.0.0")] impl Read for &[u8] { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let amt = cmp::min(buf.len(), self.len()); let (a, b) = self.split_at(amt); // First check if the amount of bytes we want to read is small: // `copy_from_slice` will generally expand to a call to `memcpy`, and // for a single byte the overhead is significant. if amt == 1 { buf[0] = a[0]; } else { buf[..amt].copy_from_slice(a); } *self = b; Ok(amt) } #[inline] fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> { let mut nread = 0; for buf in bufs { nread += self.read(buf)?; if self.is_empty() { break; } } Ok(nread) } #[inline] unsafe fn initializer(&self) -> Initializer { Initializer::nop() } #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { if buf.len() > self.len() { return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")); } let (a, b) = self.split_at(buf.len()); // First check if the amount of bytes we want to read is small: // `copy_from_slice` will generally expand to a call to `memcpy`, and // for a single byte the overhead is significant. if buf.len() == 1 { buf[0] = a[0]; } else { buf.copy_from_slice(a); } *self = b; Ok(()) } #[inline] fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { buf.extend_from_slice(*self); let len = self.len(); *self = &self[len..]; Ok(len) } } #[stable(feature = "rust1", since = "1.0.0")] impl BufRead for &[u8] { #[inline] fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) } #[inline] fn consume(&mut self, amt: usize) { *self = &self[amt..]; } } /// Write is implemented for `&mut [u8]` by copying into the slice, overwriting /// its data. /// /// Note that writing updates the slice to point to the yet unwritten part. /// The slice will be empty when it has been completely overwritten. #[stable(feature = "rust1", since = "1.0.0")] impl Write for &mut [u8] { #[inline] fn write(&mut self, data: &[u8]) -> io::Result<usize> { let amt = cmp::min(data.len(), self.len()); let (a, b) = mem::replace(self, &mut []).split_at_mut(amt); a.copy_from_slice(&data[..amt]); *self = b; Ok(amt) } #[inline] fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> { let mut nwritten = 0; for buf in bufs { nwritten += self.write(buf)?; if self.is_empty() { break; } } Ok(nwritten) } #[inline] fn write_all(&mut self, data: &[u8]) -> io::Result<()> { if self.write(data)? == data.len() { Ok(()) } else { Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer")) } } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } /// Write is implemented for `Vec<u8>` by appending to the vector. /// The vector will grow as needed. #[stable(feature = "rust1", since = "1.0.0")] impl Write for Vec<u8> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.extend_from_slice(buf); Ok(buf.len()) } #[inline] fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> { let len = bufs.iter().map(|b| b.len()).sum(); self.reserve(len); for buf in bufs { self.extend_from_slice(buf); } Ok(len) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.extend_from_slice(buf); Ok(()) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod tests { use crate::io::prelude::*; #[bench] fn bench_read_slice(b: &mut test::Bencher) { let buf = [5; 1024]; let mut dst = [0; 128]; b.iter(|| { let mut rd = &buf[..]; for _ in 0..8 { let _ = rd.read(&mut dst); test::black_box(&dst); } }) } #[bench] fn bench_write_slice(b: &mut test::Bencher) { let mut buf = [0; 1024]; let src = [5; 128]; b.iter(|| { let mut wr = &mut buf[..]; for _ in 0..8 { let _ = wr.write_all(&src); test::black_box(&wr); } }) } #[bench] fn bench_read_vec(b: &mut test::Bencher) { let buf = vec![5; 1024]; let mut dst = [0; 128]; b.iter(|| { let mut rd = &buf[..]; for _ in 0..8 { let _ = rd.read(&mut dst); test::black_box(&dst); } }) } #[bench] fn bench_write_vec(b: &mut test::Bencher) { let mut buf = Vec::with_capacity(1024); let src = [5; 128]; b.iter(|| { let mut wr = &mut buf[..]; for _ in 0..8 { let _ = wr.write_all(&src); test::black_box(&wr); } }) } }
27.278894
100
0.506862
e2fc521eb3a9529ce5ec77d08885884122026896
36,218
// Copyright (c) 2016 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use crate::entry_point; use crate::parse; use crate::parse::Instruction; pub use crate::parse::ParseError; use crate::read_file_to_string; use crate::spec_consts; use crate::structs; use crate::TypesMeta; use proc_macro2::{Span, TokenStream}; pub use shaderc::{CompilationArtifact, IncludeType, ResolvedInclude, ShaderKind}; use shaderc::{CompileOptions, Compiler, EnvVersion, SpirvVersion, TargetEnv}; use spirv_headers::{Capability, StorageClass}; use std::iter::Iterator; use std::path::Path; use std::{ cell::{RefCell, RefMut}, io::Error as IoError, }; use syn::Ident; pub(super) fn path_to_str(path: &Path) -> &str { path.to_str().expect( "Could not stringify the file to be included. Make sure the path consists of \ valid unicode characters.", ) } fn include_callback( requested_source_path_raw: &str, directive_type: IncludeType, contained_within_path_raw: &str, recursion_depth: usize, include_directories: &[impl AsRef<Path>], root_source_has_path: bool, base_path: &impl AsRef<Path>, mut includes_tracker: RefMut<Vec<String>>, ) -> Result<ResolvedInclude, String> { let file_to_include = match directive_type { IncludeType::Relative => { let requested_source_path = Path::new(requested_source_path_raw); // Is embedded current shader source embedded within a rust macro? // If so, abort unless absolute path. if !root_source_has_path && recursion_depth == 1 && !requested_source_path.is_absolute() { let requested_source_name = requested_source_path .file_name() .expect("Could not get the name of the requested source file.") .to_string_lossy(); let requested_source_directory = requested_source_path .parent() .expect("Could not get the directory of the requested source file.") .to_string_lossy(); return Err(format!( "Usage of relative paths in imports in embedded GLSL is not \ allowed, try using `#include <{}>` and adding the directory \ `{}` to the `include` array in your `shader!` macro call \ instead.", requested_source_name, requested_source_directory )); } let mut resolved_path = if recursion_depth == 1 { Path::new(contained_within_path_raw) .parent() .map(|parent| base_path.as_ref().join(parent)) } else { Path::new(contained_within_path_raw) .parent() .map(|parent| parent.to_owned()) } .unwrap_or_else(|| { panic!( "The file `{}` does not reside in a directory. This is \ an implementation error.", contained_within_path_raw ) }); resolved_path.push(requested_source_path); if !resolved_path.is_file() { return Err(format!( "Invalid inclusion path `{}`, the path does not point to a file.", requested_source_path_raw )); } resolved_path } IncludeType::Standard => { let requested_source_path = Path::new(requested_source_path_raw); if requested_source_path.is_absolute() { // This message is printed either when using a missing file with an absolute path // in the relative include directive or when using absolute paths in a standard // include directive. return Err(format!( "No such file found, as specified by the absolute path. \ Keep in mind, that absolute paths cannot be used with \ inclusion from standard directories (`#include <...>`), try \ using `#include \"...\"` instead. Requested path: {}", requested_source_path_raw )); } let found_requested_source_path = include_directories .iter() .map(|include_directory| include_directory.as_ref().join(requested_source_path)) .find(|resolved_requested_source_path| resolved_requested_source_path.is_file()); if let Some(found_requested_source_path) = found_requested_source_path { found_requested_source_path } else { return Err(format!( "Could not include the file `{}` from any include directories.", requested_source_path_raw )); } } }; let file_to_include_string = path_to_str(file_to_include.as_path()).to_string(); let content = read_file_to_string(file_to_include.as_path()).map_err(|_| { format!( "Could not read the contents of file `{}` to be included in the \ shader source.", &file_to_include_string ) })?; includes_tracker.push(file_to_include_string.clone()); Ok(ResolvedInclude { resolved_name: file_to_include_string, content, }) } pub fn compile( path: Option<String>, base_path: &impl AsRef<Path>, code: &str, ty: ShaderKind, include_directories: &[impl AsRef<Path>], macro_defines: &[(impl AsRef<str>, impl AsRef<str>)], vulkan_version: Option<EnvVersion>, spirv_version: Option<SpirvVersion>, ) -> Result<(CompilationArtifact, Vec<String>), String> { let includes_tracker = RefCell::new(Vec::new()); let mut compiler = Compiler::new().ok_or("failed to create GLSL compiler")?; let mut compile_options = CompileOptions::new().ok_or("failed to initialize compile option")?; compile_options.set_target_env( TargetEnv::Vulkan, vulkan_version.unwrap_or(EnvVersion::Vulkan1_0) as u32, ); if let Some(spirv_version) = spirv_version { compile_options.set_target_spirv(spirv_version); } let root_source_path = if let &Some(ref path) = &path { path } else { // An arbitrary placeholder file name for embedded shaders "shader.glsl" }; // Specify file resolution callback for the `#include` directive compile_options.set_include_callback( |requested_source_path, directive_type, contained_within_path, recursion_depth| { include_callback( requested_source_path, directive_type, contained_within_path, recursion_depth, include_directories, path.is_some(), base_path, includes_tracker.borrow_mut(), ) }, ); for (macro_name, macro_value) in macro_defines.iter() { compile_options.add_macro_definition(macro_name.as_ref(), Some(macro_value.as_ref())); } let content = compiler .compile_into_spirv(&code, ty, root_source_path, "main", Some(&compile_options)) .map_err(|e| e.to_string())?; let includes = includes_tracker.borrow().clone(); Ok((content, includes)) } pub(super) fn reflect<'a, I>( name: &str, spirv: &[u32], types_meta: TypesMeta, input_paths: I, exact_entrypoint_interface: bool, dump: bool, ) -> Result<TokenStream, Error> where I: Iterator<Item = &'a str>, { let struct_name = Ident::new(&name, Span::call_site()); let doc = parse::parse_spirv(spirv)?; // checking whether each required capability is enabled in the Vulkan device let mut cap_checks: Vec<TokenStream> = vec![]; match doc.version { (1, 0) => {} (1, 1) | (1, 2) | (1, 3) => { cap_checks.push(quote! { if device.api_version() < Version::V1_1 { panic!("Device API version 1.1 required"); } }); } (1, 4) => { cap_checks.push(quote! { if device.api_version() < Version::V1_2 && !device.enabled_extensions().khr_spirv_1_4 { panic!("Device API version 1.2 or extension VK_KHR_spirv_1_4 required"); } }); } (1, 5) => { cap_checks.push(quote! { if device.api_version() < Version::V1_2 { panic!("Device API version 1.2 required"); } }); } _ => return Err(Error::UnsupportedSpirvVersion), } for i in doc.instructions.iter() { let dev_req = { match i { Instruction::Variable { result_type_id: _, result_id: _, storage_class, initializer: _, } => storage_class_requirement(storage_class), Instruction::TypePointer { result_id: _, storage_class, type_id: _, } => storage_class_requirement(storage_class), Instruction::Capability(cap) => capability_requirement(cap), _ => DeviceRequirement::None, } }; match dev_req { DeviceRequirement::None => continue, DeviceRequirement::Features(features) => { for feature in features { let ident = Ident::new(feature, Span::call_site()); cap_checks.push(quote! { if !device.enabled_features().#ident { panic!("Device feature {:?} required", #feature); } }); } } DeviceRequirement::Extensions(extensions) => { for extension in extensions { let ident = Ident::new(extension, Span::call_site()); cap_checks.push(quote! { if !device.enabled_extensions().#ident { panic!("Device extension {:?} required", #extension); } }); } } } } // writing one method for each entry point of this module let mut entry_points_inside_impl: Vec<TokenStream> = vec![]; for instruction in doc.instructions.iter() { if let &Instruction::EntryPoint { .. } = instruction { let entry_point = entry_point::write_entry_point( &doc, instruction, &types_meta, exact_entrypoint_interface, ); entry_points_inside_impl.push(entry_point); } } let include_bytes = input_paths.map(|s| { quote! { // using include_bytes here ensures that changing the shader will force recompilation. // The bytes themselves can be optimized out by the compiler as they are unused. ::std::include_bytes!( #s ) } }); let structs = structs::write_structs(&doc, &types_meta); let specialization_constants = spec_consts::write_specialization_constants(&doc, &types_meta); let uses = &types_meta.uses; let ast = quote! { #[allow(unused_imports)] use std::sync::Arc; #[allow(unused_imports)] use std::vec::IntoIter as VecIntoIter; #[allow(unused_imports)] use vulkano::device::Device; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorDesc; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorDescTy; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorBufferDesc; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorImageDesc; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorImageDescDimensions; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorImageDescArray; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorSetDesc; #[allow(unused_imports)] use vulkano::descriptor_set::layout::DescriptorSetLayout; #[allow(unused_imports)] use vulkano::descriptor_set::DescriptorSet; #[allow(unused_imports)] use vulkano::format::Format; #[allow(unused_imports)] use vulkano::pipeline::layout::PipelineLayout; #[allow(unused_imports)] use vulkano::pipeline::layout::PipelineLayoutPcRange; #[allow(unused_imports)] use vulkano::pipeline::shader::ShaderStages; #[allow(unused_imports)] use vulkano::pipeline::shader::SpecializationConstants as SpecConstsTrait; #[allow(unused_imports)] use vulkano::pipeline::shader::SpecializationMapEntry; #[allow(unused_imports)] use vulkano::Version; pub struct #struct_name { shader: ::std::sync::Arc<::vulkano::pipeline::shader::ShaderModule>, } impl #struct_name { /// Loads the shader in Vulkan as a `ShaderModule`. #[inline] #[allow(unsafe_code)] pub fn load(device: ::std::sync::Arc<::vulkano::device::Device>) -> Result<#struct_name, ::vulkano::OomError> { let _bytes = ( #( #include_bytes),* ); #( #cap_checks )* static WORDS: &[u32] = &[ #( #spirv ),* ]; unsafe { Ok(#struct_name { shader: ::vulkano::pipeline::shader::ShaderModule::from_words(device, WORDS)? }) } } /// Returns the module that was created. #[allow(dead_code)] #[inline] pub fn module(&self) -> &::std::sync::Arc<::vulkano::pipeline::shader::ShaderModule> { &self.shader } #( #entry_points_inside_impl )* } pub mod ty { #( #uses )* #structs } #specialization_constants }; if dump { println!("{}", ast.to_string()); panic!("`shader!` rust codegen dumped") // TODO: use span from dump } Ok(ast) } #[derive(Debug)] pub enum Error { UnsupportedSpirvVersion, IoError(IoError), ParseError(ParseError), } impl From<IoError> for Error { #[inline] fn from(err: IoError) -> Error { Error::IoError(err) } } impl From<ParseError> for Error { #[inline] fn from(err: ParseError) -> Error { Error::ParseError(err) } } /// Returns the Vulkan device requirement for a SPIR-V `OpCapability`. // TODO: this function is a draft, as the actual names may not be the same fn capability_requirement(cap: &Capability) -> DeviceRequirement { match *cap { Capability::Matrix => DeviceRequirement::None, Capability::Shader => DeviceRequirement::None, Capability::Geometry => DeviceRequirement::Features(&["geometry_shader"]), Capability::Tessellation => DeviceRequirement::Features(&["tessellation_shader"]), Capability::Addresses => panic!(), // not supported Capability::Linkage => panic!(), // not supported Capability::Kernel => panic!(), // not supported Capability::Vector16 => panic!(), // not supported Capability::Float16Buffer => panic!(), // not supported Capability::Float16 => panic!(), // not supported Capability::Float64 => DeviceRequirement::Features(&["shader_float64"]), Capability::Int64 => DeviceRequirement::Features(&["shader_int64"]), Capability::Int64Atomics => panic!(), // not supported Capability::ImageBasic => panic!(), // not supported Capability::ImageReadWrite => panic!(), // not supported Capability::ImageMipmap => panic!(), // not supported Capability::Pipes => panic!(), // not supported Capability::Groups => panic!(), // not supported Capability::DeviceEnqueue => panic!(), // not supported Capability::LiteralSampler => panic!(), // not supported Capability::AtomicStorage => panic!(), // not supported Capability::Int16 => DeviceRequirement::Features(&["shader_int16"]), Capability::TessellationPointSize => { DeviceRequirement::Features(&["shader_tessellation_and_geometry_point_size"]) } Capability::GeometryPointSize => { DeviceRequirement::Features(&["shader_tessellation_and_geometry_point_size"]) } Capability::ImageGatherExtended => { DeviceRequirement::Features(&["shader_image_gather_extended"]) } Capability::StorageImageMultisample => { DeviceRequirement::Features(&["shader_storage_image_multisample"]) } Capability::UniformBufferArrayDynamicIndexing => { DeviceRequirement::Features(&["shader_uniform_buffer_array_dynamic_indexing"]) } Capability::SampledImageArrayDynamicIndexing => { DeviceRequirement::Features(&["shader_sampled_image_array_dynamic_indexing"]) } Capability::StorageBufferArrayDynamicIndexing => { DeviceRequirement::Features(&["shader_storage_buffer_array_dynamic_indexing"]) } Capability::StorageImageArrayDynamicIndexing => { DeviceRequirement::Features(&["shader_storage_image_array_dynamic_indexing"]) } Capability::ClipDistance => DeviceRequirement::Features(&["shader_clip_distance"]), Capability::CullDistance => DeviceRequirement::Features(&["shader_cull_distance"]), Capability::ImageCubeArray => DeviceRequirement::Features(&["image_cube_array"]), Capability::SampleRateShading => DeviceRequirement::Features(&["sample_rate_shading"]), Capability::ImageRect => panic!(), // not supported Capability::SampledRect => panic!(), // not supported Capability::GenericPointer => panic!(), // not supported Capability::Int8 => DeviceRequirement::Extensions(&["khr_8bit_storage"]), Capability::InputAttachment => DeviceRequirement::None, Capability::SparseResidency => DeviceRequirement::Features(&["shader_resource_residency"]), Capability::MinLod => DeviceRequirement::Features(&["shader_resource_min_lod"]), Capability::Sampled1D => DeviceRequirement::None, Capability::Image1D => DeviceRequirement::None, Capability::SampledCubeArray => DeviceRequirement::Features(&["image_cube_array"]), Capability::SampledBuffer => DeviceRequirement::None, Capability::ImageBuffer => DeviceRequirement::None, Capability::ImageMSArray => { DeviceRequirement::Features(&["shader_storage_image_multisample"]) } Capability::StorageImageExtendedFormats => { DeviceRequirement::Features(&["shader_storage_image_extended_formats"]) } Capability::ImageQuery => DeviceRequirement::None, Capability::DerivativeControl => DeviceRequirement::None, Capability::InterpolationFunction => DeviceRequirement::Features(&["sample_rate_shading"]), Capability::TransformFeedback => panic!(), // not supported Capability::GeometryStreams => panic!(), // not supported Capability::StorageImageReadWithoutFormat => { DeviceRequirement::Features(&["shader_storage_image_read_without_format"]) } Capability::StorageImageWriteWithoutFormat => { DeviceRequirement::Features(&["shader_storage_image_write_without_format"]) } Capability::MultiViewport => DeviceRequirement::Features(&["multi_viewport"]), Capability::DrawParameters => DeviceRequirement::Features(&["shader_draw_parameters"]), Capability::StorageBuffer16BitAccess => { DeviceRequirement::Extensions(&["khr_16bit_storage"]) } Capability::UniformAndStorageBuffer16BitAccess => { DeviceRequirement::Extensions(&["khr_16bit_storage"]) } Capability::StoragePushConstant16 => DeviceRequirement::Extensions(&["khr_16bit_storage"]), Capability::StorageInputOutput16 => DeviceRequirement::Extensions(&["khr_16bit_storage"]), Capability::MultiView => DeviceRequirement::Features(&["multiview"]), Capability::StoragePushConstant8 => DeviceRequirement::Extensions(&["khr_8bit_storage"]), Capability::SubgroupDispatch => todo!(), Capability::NamedBarrier => todo!(), Capability::PipeStorage => todo!(), Capability::GroupNonUniform => todo!(), Capability::GroupNonUniformVote => todo!(), Capability::GroupNonUniformArithmetic => todo!(), Capability::GroupNonUniformBallot => todo!(), Capability::GroupNonUniformShuffle => todo!(), Capability::GroupNonUniformShuffleRelative => todo!(), Capability::GroupNonUniformClustered => todo!(), Capability::GroupNonUniformQuad => todo!(), Capability::ShaderLayer => todo!(), Capability::ShaderViewportIndex => todo!(), Capability::SubgroupBallotKHR => todo!(), Capability::SubgroupVoteKHR => todo!(), Capability::DeviceGroup => todo!(), Capability::VariablePointersStorageBuffer => todo!(), Capability::VariablePointers => todo!(), Capability::AtomicStorageOps => todo!(), Capability::SampleMaskPostDepthCoverage => todo!(), Capability::StorageBuffer8BitAccess => todo!(), Capability::UniformAndStorageBuffer8BitAccess => todo!(), Capability::DenormPreserve => todo!(), Capability::DenormFlushToZero => todo!(), Capability::SignedZeroInfNanPreserve => todo!(), Capability::RoundingModeRTE => todo!(), Capability::RoundingModeRTZ => todo!(), Capability::RayQueryProvisionalKHR => todo!(), Capability::RayTraversalPrimitiveCullingProvisionalKHR => todo!(), Capability::Float16ImageAMD => todo!(), Capability::ImageGatherBiasLodAMD => todo!(), Capability::FragmentMaskAMD => todo!(), Capability::StencilExportEXT => todo!(), Capability::ImageReadWriteLodAMD => todo!(), Capability::ShaderClockKHR => todo!(), Capability::SampleMaskOverrideCoverageNV => todo!(), Capability::GeometryShaderPassthroughNV => todo!(), Capability::ShaderViewportIndexLayerEXT => todo!(), Capability::ShaderViewportMaskNV => todo!(), Capability::ShaderStereoViewNV => todo!(), Capability::PerViewAttributesNV => todo!(), Capability::FragmentFullyCoveredEXT => todo!(), Capability::MeshShadingNV => todo!(), Capability::ImageFootprintNV => todo!(), Capability::FragmentBarycentricNV => todo!(), Capability::ComputeDerivativeGroupQuadsNV => todo!(), Capability::FragmentDensityEXT => todo!(), Capability::GroupNonUniformPartitionedNV => todo!(), Capability::ShaderNonUniform => todo!(), Capability::RuntimeDescriptorArray => todo!(), Capability::InputAttachmentArrayDynamicIndexing => todo!(), Capability::UniformTexelBufferArrayDynamicIndexing => todo!(), Capability::StorageTexelBufferArrayDynamicIndexing => todo!(), Capability::UniformBufferArrayNonUniformIndexing => todo!(), Capability::SampledImageArrayNonUniformIndexing => todo!(), Capability::StorageBufferArrayNonUniformIndexing => todo!(), Capability::StorageImageArrayNonUniformIndexing => todo!(), Capability::InputAttachmentArrayNonUniformIndexing => todo!(), Capability::UniformTexelBufferArrayNonUniformIndexing => todo!(), Capability::StorageTexelBufferArrayNonUniformIndexing => todo!(), Capability::RayTracingNV => todo!(), Capability::VulkanMemoryModel => todo!(), Capability::VulkanMemoryModelDeviceScope => todo!(), Capability::PhysicalStorageBufferAddresses => todo!(), Capability::ComputeDerivativeGroupLinearNV => todo!(), Capability::RayTracingProvisionalKHR => todo!(), Capability::CooperativeMatrixNV => todo!(), Capability::FragmentShaderSampleInterlockEXT => todo!(), Capability::FragmentShaderShadingRateInterlockEXT => todo!(), Capability::ShaderSMBuiltinsNV => todo!(), Capability::FragmentShaderPixelInterlockEXT => todo!(), Capability::DemoteToHelperInvocationEXT => todo!(), Capability::SubgroupShuffleINTEL => todo!(), Capability::SubgroupBufferBlockIOINTEL => todo!(), Capability::SubgroupImageBlockIOINTEL => todo!(), Capability::SubgroupImageMediaBlockIOINTEL => todo!(), Capability::IntegerFunctions2INTEL => todo!(), Capability::SubgroupAvcMotionEstimationINTEL => todo!(), Capability::SubgroupAvcMotionEstimationIntraINTEL => todo!(), Capability::SubgroupAvcMotionEstimationChromaINTEL => todo!(), } } /// Returns the Vulkan device requirement for a SPIR-V storage class. fn storage_class_requirement(storage_class: &StorageClass) -> DeviceRequirement { match *storage_class { StorageClass::UniformConstant => DeviceRequirement::None, StorageClass::Input => DeviceRequirement::None, StorageClass::Uniform => DeviceRequirement::None, StorageClass::Output => DeviceRequirement::None, StorageClass::Workgroup => DeviceRequirement::None, StorageClass::CrossWorkgroup => DeviceRequirement::None, StorageClass::Private => DeviceRequirement::None, StorageClass::Function => DeviceRequirement::None, StorageClass::Generic => DeviceRequirement::None, StorageClass::PushConstant => DeviceRequirement::None, StorageClass::AtomicCounter => DeviceRequirement::None, StorageClass::Image => DeviceRequirement::None, StorageClass::StorageBuffer => { DeviceRequirement::Extensions(&["khr_storage_buffer_storage_class"]) } StorageClass::CallableDataNV => todo!(), StorageClass::IncomingCallableDataNV => todo!(), StorageClass::RayPayloadNV => todo!(), StorageClass::HitAttributeNV => todo!(), StorageClass::IncomingRayPayloadNV => todo!(), StorageClass::ShaderRecordBufferNV => todo!(), StorageClass::PhysicalStorageBuffer => todo!(), } } enum DeviceRequirement { None, Features(&'static [&'static str]), Extensions(&'static [&'static str]), } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; #[cfg(not(target_os = "windows"))] pub fn path_separator() -> &'static str { "/" } #[cfg(target_os = "windows")] pub fn path_separator() -> &'static str { "\\" } fn convert_paths(root_path: &Path, paths: &[String]) -> Vec<String> { paths .iter() .map(|p| path_to_str(root_path.join(p).as_path()).to_owned()) .collect() } #[test] fn test_bad_alignment() { // vec3/mat3/mat3x* are problematic in arrays since their rust // representations don't have the same array stride as the SPIR-V // ones. E.g. in a vec3[2], the second element starts on the 16th // byte, but in a rust [[f32;3];2], the second element starts on the // 12th byte. Since we can't generate code for these types, we should // create an error instead of generating incorrect code. let includes: [PathBuf; 0] = []; let defines: [(String, String); 0] = []; let (comp, _) = compile( None, &Path::new(""), " #version 450 struct MyStruct { vec3 vs[2]; }; layout(binding=0) uniform UBO { MyStruct s; }; void main() {} ", ShaderKind::Vertex, &includes, &defines, None, None, ) .unwrap(); let doc = parse::parse_spirv(comp.as_binary()).unwrap(); let res = std::panic::catch_unwind(|| structs::write_structs(&doc, &TypesMeta::default())); assert!(res.is_err()); } #[test] fn test_trivial_alignment() { let includes: [PathBuf; 0] = []; let defines: [(String, String); 0] = []; let (comp, _) = compile( None, &Path::new(""), " #version 450 struct MyStruct { vec4 vs[2]; }; layout(binding=0) uniform UBO { MyStruct s; }; void main() {} ", ShaderKind::Vertex, &includes, &defines, None, None, ) .unwrap(); let doc = parse::parse_spirv(comp.as_binary()).unwrap(); structs::write_structs(&doc, &TypesMeta::default()); } #[test] fn test_wrap_alignment() { // This is a workaround suggested in the case of test_bad_alignment, // so we should make sure it works. let includes: [PathBuf; 0] = []; let defines: [(String, String); 0] = []; let (comp, _) = compile( None, &Path::new(""), " #version 450 struct Vec3Wrap { vec3 v; }; struct MyStruct { Vec3Wrap vs[2]; }; layout(binding=0) uniform UBO { MyStruct s; }; void main() {} ", ShaderKind::Vertex, &includes, &defines, None, None, ) .unwrap(); let doc = parse::parse_spirv(comp.as_binary()).unwrap(); structs::write_structs(&doc, &TypesMeta::default()); } #[test] fn test_include_resolution() { let root_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let empty_includes: [PathBuf; 0] = []; let defines: [(String, String); 0] = []; let (_compile_relative, _) = compile( Some(String::from("tests/include_test.glsl")), &root_path, " #version 450 #include \"include_dir_a/target_a.glsl\" #include \"include_dir_b/target_b.glsl\" void main() {} ", ShaderKind::Vertex, &empty_includes, &defines, None, None, ) .expect("Cannot resolve include files"); let (_compile_include_paths, includes) = compile( Some(String::from("tests/include_test.glsl")), &root_path, " #version 450 #include <target_a.glsl> #include <target_b.glsl> void main() {} ", ShaderKind::Vertex, &[ root_path.join("tests").join("include_dir_a"), root_path.join("tests").join("include_dir_b"), ], &defines, None, None, ) .expect("Cannot resolve include files"); assert_eq!( includes, convert_paths( &root_path, &[ vec!["tests", "include_dir_a", "target_a.glsl"].join(path_separator()), vec!["tests", "include_dir_b", "target_b.glsl"].join(path_separator()), ] ) ); let (_compile_include_paths_with_relative, includes_with_relative) = compile( Some(String::from("tests/include_test.glsl")), &root_path, " #version 450 #include <target_a.glsl> #include <../include_dir_b/target_b.glsl> void main() {} ", ShaderKind::Vertex, &[root_path.join("tests").join("include_dir_a")], &defines, None, None, ) .expect("Cannot resolve include files"); assert_eq!( includes_with_relative, convert_paths( &root_path, &[ vec!["tests", "include_dir_a", "target_a.glsl"].join(path_separator()), vec!["tests", "include_dir_a", "../include_dir_b/target_b.glsl"] .join(path_separator()), ] ) ); let absolute_path = root_path .join("tests") .join("include_dir_a") .join("target_a.glsl"); let absolute_path_str = absolute_path .to_str() .expect("Cannot run tests in a folder with non unicode characters"); let (_compile_absolute_path, includes_absolute_path) = compile( Some(String::from("tests/include_test.glsl")), &root_path, &format!( " #version 450 #include \"{}\" void main() {{}} ", absolute_path_str ), ShaderKind::Vertex, &empty_includes, &defines, None, None, ) .expect("Cannot resolve include files"); assert_eq!( includes_absolute_path, convert_paths( &root_path, &[vec!["tests", "include_dir_a", "target_a.glsl"].join(path_separator())] ) ); let (_compile_recursive_, includes_recursive) = compile( Some(String::from("tests/include_test.glsl")), &root_path, " #version 450 #include <target_c.glsl> void main() {} ", ShaderKind::Vertex, &[ root_path.join("tests").join("include_dir_b"), root_path.join("tests").join("include_dir_c"), ], &defines, None, None, ) .expect("Cannot resolve include files"); assert_eq!( includes_recursive, convert_paths( &root_path, &[ vec!["tests", "include_dir_c", "target_c.glsl"].join(path_separator()), vec!["tests", "include_dir_c", "../include_dir_a/target_a.glsl"] .join(path_separator()), vec!["tests", "include_dir_b", "target_b.glsl"].join(path_separator()), ] ) ); } #[test] fn test_macros() { let empty_includes: [PathBuf; 0] = []; let defines = vec![("NAME1", ""), ("NAME2", "58")]; let no_defines: [(String, String); 0] = []; let need_defines = " #version 450 #if defined(NAME1) && NAME2 > 29 void main() {} #endif "; let compile_no_defines = compile( None, &Path::new(""), need_defines, ShaderKind::Vertex, &empty_includes, &no_defines, None, None, ); assert!(compile_no_defines.is_err()); let compile_defines = compile( None, &Path::new(""), need_defines, ShaderKind::Vertex, &empty_includes, &defines, None, None, ); compile_defines.expect("Setting shader macros did not work"); } }
38.57082
101
0.574742
e2f4d69f55493e1f03d99ec6d1a5c3fe3206b1ee
11,059
//! This module provides utility types and traits for managing a test session //! //! Tests start by using one of the `TestApp` constructors: `init`, `with_proxy`, or `full`. This returns a //! `TestAppBuilder` which provides convience methods for creating up to one user, optionally with //! a token. The builder methods all return at least an initialized `TestApp` and a //! `MockAnonymousUser`. The `MockAnonymousUser` can be used to issue requests in an //! unauthenticated session. //! //! A `TestApp` value provides raw access to the database through the `db` function and can //! construct new users via the `db_new_user` function. This function returns a //! `MockCookieUser`, which can be used to generate one or more tokens via its `db_new_token` //! function, which in turn returns a `MockTokenUser`. //! //! All three user types implement the `RequestHelper` trait which provides convenience methods for //! constructing requests. Some of these methods, such as `publish` are expected to fail for an //! unauthenticated user (or for other reasons) and return a `Response<T>`. The `Response<T>` //! provides several functions to check the response status and deserialize the JSON response. //! //! `MockCookieUser` and `MockTokenUser` provide an `as_model` function which returns a reference //! to the underlying database model value (`User` and `ApiToken` respectively). use crate::{ builders::PublishBuilder, CategoryListResponse, CategoryResponse, CrateList, CrateResponse, GoodCrate, OkBool, OwnersResponse, VersionResponse, }; use cargo_registry::models::{ApiToken, CreatedApiToken, User}; use conduit::{BoxError, Handler, Method}; use conduit_cookie::SessionMiddleware; use conduit_test::MockRequest; use conduit::header; use cookie::Cookie; use std::collections::HashMap; mod chaosproxy; mod fresh_schema; mod response; mod test_app; pub(crate) use chaosproxy::ChaosProxy; pub(crate) use fresh_schema::FreshSchema; pub use response::Response; pub use test_app::TestApp; /// This function can be used to create a `Cookie` header for mock requests that /// include cookie-based authentication. /// /// ``` /// let cookie = encode_session_header(session_key, user_id); /// request.header(header::COOKIE, &cookie); /// ``` /// /// The implementation matches roughly what is happening inside of the /// `SessionMiddleware` from `conduit_cookie`. pub fn encode_session_header(session_key: &str, user_id: i32) -> String { let cookie_name = "cargo_session"; let cookie_key = cookie::Key::derive_from(session_key.as_bytes()); // build session data map let mut map = HashMap::new(); map.insert("user_id".into(), user_id.to_string()); // encode the map into a cookie value string let encoded = SessionMiddleware::encode(&map); // put the cookie into a signed cookie jar let cookie = Cookie::build(cookie_name, encoded).finish(); let mut jar = cookie::CookieJar::new(); jar.signed_mut(&cookie_key).add(cookie); // read the raw cookie from the cookie jar jar.get(cookie_name).unwrap().to_string() } /// A collection of helper methods for the 3 authentication types /// /// Helper methods go through public APIs, and should not modify the database directly pub trait RequestHelper { fn request_builder(&self, method: Method, path: &str) -> MockRequest; fn app(&self) -> &TestApp; /// Run a request that is expected to succeed #[track_caller] fn run<T>(&self, mut request: MockRequest) -> Response<T> { Response::new(self.app().as_middleware().call(&mut request)) } /// Run a request that is expected to error #[track_caller] fn run_err(&self, mut request: MockRequest) -> BoxError { self.app().as_middleware().call(&mut request).err().unwrap() } /// Create a get request fn get_request(&self, path: &str) -> MockRequest { self.request_builder(Method::GET, path) } /// Issue a GET request #[track_caller] fn get<T>(&self, path: &str) -> Response<T> { self.run(self.get_request(path)) } /// Issue a GET request that includes query parameters #[track_caller] fn get_with_query<T>(&self, path: &str, query: &str) -> Response<T> { let mut request = self.request_builder(Method::GET, path); request.with_query(query); self.run(request) } /// Issue a PUT request #[track_caller] fn put<T>(&self, path: &str, body: &[u8]) -> Response<T> { let mut request = self.request_builder(Method::PUT, path); request.with_body(body); self.run(request) } /// Issue a DELETE request #[track_caller] fn delete<T>(&self, path: &str) -> Response<T> { let request = self.request_builder(Method::DELETE, path); self.run(request) } /// Issue a DELETE request with a body... yes we do it, for crate owner removal #[track_caller] fn delete_with_body<T>(&self, path: &str, body: &[u8]) -> Response<T> { let mut request = self.request_builder(Method::DELETE, path); request.with_body(body); self.run(request) } /// Search for crates matching a query string fn search(&self, query: &str) -> CrateList { self.get_with_query("/api/v1/crates", query).good() } /// Search for crates owned by the specified user. fn search_by_user_id(&self, id: i32) -> CrateList { self.search(&format!("user_id={id}")) } /// Enqueue a crate for publishing /// /// The publish endpoint will enqueue a background job to update the index. A test must run /// any pending background jobs if it intends to observe changes to the index. /// /// Any pending jobs are run when the `TestApp` is dropped to ensure that the test fails unless /// all background tasks complete successfully. #[track_caller] fn enqueue_publish(&self, publish_builder: PublishBuilder) -> Response<GoodCrate> { self.put("/api/v1/crates/new", &publish_builder.body()) } /// Request the JSON used for a crate's page fn show_crate(&self, krate_name: &str) -> CrateResponse { let url = format!("/api/v1/crates/{krate_name}"); self.get(&url).good() } /// Request the JSON used to list a crate's owners fn show_crate_owners(&self, krate_name: &str) -> OwnersResponse { let url = format!("/api/v1/crates/{krate_name}/owners"); self.get(&url).good() } /// Request the JSON used for a crate version's page fn show_version(&self, krate_name: &str, version: &str) -> VersionResponse { let url = format!("/api/v1/crates/{krate_name}/{version}"); self.get(&url).good() } fn show_category(&self, category_name: &str) -> CategoryResponse { let url = format!("/api/v1/categories/{category_name}"); self.get(&url).good() } fn show_category_list(&self) -> CategoryListResponse { let url = "/api/v1/categories"; self.get(url).good() } } fn req(method: conduit::Method, path: &str) -> MockRequest { let mut request = MockRequest::new(method, path); request.header(header::USER_AGENT, "conduit-test"); request } /// A type that can generate unauthenticated requests pub struct MockAnonymousUser { app: TestApp, } impl RequestHelper for MockAnonymousUser { fn request_builder(&self, method: Method, path: &str) -> MockRequest { req(method, path) } fn app(&self) -> &TestApp { &self.app } } /// A type that can generate cookie authenticated requests /// /// The `user.id` value is directly injected into a request extension and thus the conduit_cookie /// session logic is not exercised. pub struct MockCookieUser { app: TestApp, user: User, } impl RequestHelper for MockCookieUser { fn request_builder(&self, method: Method, path: &str) -> MockRequest { let session_key = &self.app.as_inner().session_key(); let cookie = encode_session_header(session_key, self.user.id); let mut request = req(method, path); request.header(header::COOKIE, &cookie); request } fn app(&self) -> &TestApp { &self.app } } impl MockCookieUser { /// Creates an instance from a database `User` instance pub fn new(app: &TestApp, user: User) -> Self { Self { app: app.clone(), user, } } /// Returns a reference to the database `User` model pub fn as_model(&self) -> &User { &self.user } /// Creates a token and wraps it in a helper struct /// /// This method updates the database directly pub fn db_new_token(&self, name: &str) -> MockTokenUser { let token = self .app .db(|conn| ApiToken::insert(conn, self.user.id, name).unwrap()); MockTokenUser { app: self.app.clone(), token, } } } /// A type that can generate token authenticated requests pub struct MockTokenUser { app: TestApp, token: CreatedApiToken, } impl RequestHelper for MockTokenUser { fn request_builder(&self, method: Method, path: &str) -> MockRequest { let mut request = req(method, path); request.header(header::AUTHORIZATION, &self.token.plaintext); request } fn app(&self) -> &TestApp { &self.app } } impl MockTokenUser { /// Returns a reference to the database `ApiToken` model pub fn as_model(&self) -> &ApiToken { &self.token.model } pub fn plaintext(&self) -> &str { &self.token.plaintext } /// Add to the specified crate the specified owners. pub fn add_named_owners(&self, krate_name: &str, owners: &[&str]) -> Response<OkBool> { self.modify_owners(krate_name, owners, Self::put) } /// Add a single owner to the specified crate. pub fn add_named_owner(&self, krate_name: &str, owner: &str) -> Response<OkBool> { self.add_named_owners(krate_name, &[owner]) } /// Remove from the specified crate the specified owners. pub fn remove_named_owners(&self, krate_name: &str, owners: &[&str]) -> Response<OkBool> { self.modify_owners(krate_name, owners, Self::delete_with_body) } /// Remove a single owner to the specified crate. pub fn remove_named_owner(&self, krate_name: &str, owner: &str) -> Response<OkBool> { self.remove_named_owners(krate_name, &[owner]) } fn modify_owners<F>(&self, krate_name: &str, owners: &[&str], method: F) -> Response<OkBool> where F: Fn(&MockTokenUser, &str, &[u8]) -> Response<OkBool>, { let url = format!("/api/v1/crates/{krate_name}/owners"); let body = json!({ "owners": owners }).to_string(); method(self, &url, body.as_bytes()) } /// Add a user as an owner for a crate. pub fn add_user_owner(&self, krate_name: &str, username: &str) { self.add_named_owner(krate_name, username).good(); } } #[derive(Deserialize, Debug)] pub struct Error { pub detail: String, }
33.716463
108
0.655484
08ea048b9f73cd5b6a6a3fdb619e9fa12866cbe0
1,591
pub struct IconSimCardDownload { props: crate::Props, } impl yew::Component for IconSimCardDownload { type Properties = crate::Props; type Message = (); fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender { true } fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender { false } fn view(&self) -> yew::prelude::Html { yew::prelude::html! { <svg class=self.props.class.unwrap_or("") width=self.props.size.unwrap_or(24).to_string() height=self.props.size.unwrap_or(24).to_string() viewBox="0 0 24 24" fill=self.props.fill.unwrap_or("none") stroke=self.props.color.unwrap_or("currentColor") stroke-width=self.props.stroke_width.unwrap_or(2).to_string() stroke-linecap=self.props.stroke_linecap.unwrap_or("round") stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round") > <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><path d="M0,0h24v24H0V0z" fill="none"/></g><g><g><path d="M18,2h-8L4,8v12c0,1.1,0.9,2,2,2h12c1.1,0,2-0.9,2-2V4C20,2.9,19.1,2,18,2z M18,4v16H6V8.83L10.83,4H18z"/><path d="M16,13l-4,4l-4-4l1.41-1.41L11,13.17V9.02L13,9v4.17l1.59-1.59L16,13z"/></g></g></svg> </svg> } } }
34.586957
386
0.582652
0abd420863ff978de1ec3abfa8c0d5852ee622d0
464
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // WARNING: THIS FILE IS MACHINE GENERATED. DO NOT EDIT. // Generated from the banjo.examples.example8 banjo file #![allow(unused_imports, non_camel_case_types)] #[repr(C)] #[derive(Copy, Clone, Debug, PartialEq)] pub struct foo { pub u8_0: u8, pub u64_0: u64, pub u8_1: u8, }
18.56
73
0.702586
211c444cad56cefd411ede531b761b97380f486d
9,924
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 mod state; use super::absint::*; use crate::{ errors::*, hlir::ast::*, parser::ast::{BinOp_, StructName, Var}, shared::unique_map::UniqueMap, }; use omc_ir_types::location::*; use state::*; use std::collections::BTreeMap; //************************************************************************************************** // Entry and trait bindings //************************************************************************************************** struct BorrowSafety { local_numbers: UniqueMap<Var, usize>, } impl BorrowSafety { fn new<T>(local_types: &UniqueMap<Var, T>) -> Self { let mut local_numbers = UniqueMap::new(); for (idx, (v, _)) in local_types.iter().enumerate() { local_numbers.add(v, idx).unwrap(); } Self { local_numbers } } } struct Context<'a, 'b> { local_numbers: &'a UniqueMap<Var, usize>, borrow_state: &'b mut BorrowState, errors: Errors, } impl<'a, 'b> Context<'a, 'b> { fn new(safety: &'a BorrowSafety, borrow_state: &'b mut BorrowState) -> Self { let local_numbers = &safety.local_numbers; Self { local_numbers, borrow_state, errors: vec![], } } fn get_errors(self) -> Errors { self.errors } fn add_errors(&mut self, mut additional: Errors) { self.errors.append(&mut additional); } } impl TransferFunctions for BorrowSafety { type State = BorrowState; fn execute( &mut self, pre: &mut Self::State, _lbl: Label, _idx: usize, cmd: &Command, ) -> Errors { let mut context = Context::new(self, pre); command(&mut context, cmd); context .borrow_state .canonicalize_locals(&context.local_numbers); context.get_errors() } } impl AbstractInterpreter for BorrowSafety {} pub fn verify( errors: &mut Errors, signature: &FunctionSignature, acquires: &BTreeMap<StructName, Loc>, locals: &UniqueMap<Var, SingleType>, cfg: &super::cfg::BlockCFG, ) -> BTreeMap<Label, BorrowState> { let mut initial_state = BorrowState::initial(locals, acquires.clone(), !errors.is_empty()); initial_state.bind_arguments(&signature.parameters); let mut safety = BorrowSafety::new(locals); initial_state.canonicalize_locals(&safety.local_numbers); let (final_state, mut es) = safety.analyze_function(cfg, initial_state); errors.append(&mut es); final_state } //************************************************************************************************** // Command //************************************************************************************************** fn command(context: &mut Context, sp!(loc, cmd_): &Command) { use Command_ as C; match cmd_ { C::Assign(ls, e) => { let values = exp(context, e); lvalues(context, ls, values); } C::Mutate(el, er) => { let value = assert_single_value(exp(context, er)); assert!(!value.is_ref()); let lvalue = assert_single_value(exp(context, el)); let errors = context.borrow_state.mutate(*loc, lvalue); context.add_errors(errors); } C::JumpIf { cond: e, .. } => { let value = assert_single_value(exp(context, e)); assert!(!value.is_ref()); } C::IgnoreAndPop { exp: e, .. } => { let values = exp(context, e); context.borrow_state.release_values(values); } C::Return(e) => { let values = exp(context, e); let errors = context.borrow_state.return_(*loc, values); context.add_errors(errors); } C::Abort(e) => { let value = assert_single_value(exp(context, e)); assert!(!value.is_ref()); context.borrow_state.abort() } C::Jump(_) => (), C::Break | C::Continue => panic!("ICE break/continue not translated to jumps"), } } fn lvalues(context: &mut Context, ls: &[LValue], values: Values) { assert!(ls.len() == values.len()); ls.iter() .zip(values) .for_each(|(l, value)| lvalue(context, l, value)) } fn lvalue(context: &mut Context, sp!(loc, l_): &LValue, value: Value) { use LValue_ as L; match l_ { L::Ignore => { context.borrow_state.release_value(value); } L::Var(v, _) => { let errors = context.borrow_state.assign_local(*loc, v, value); context.add_errors(errors) } L::Unpack(_, _, fields) => { assert!(!value.is_ref()); fields .iter() .for_each(|(_, l)| lvalue(context, l, Value::NonRef)) } } } fn exp(context: &mut Context, parent_e: &Exp) -> Values { use UnannotatedExp_ as E; let eloc = &parent_e.exp.loc; let svalue = || vec![Value::NonRef]; match &parent_e.exp.value { E::Move { var, .. } => { let (errors, value) = context.borrow_state.move_local(*eloc, var); context.add_errors(errors); vec![value] } E::Copy { var, .. } => { let (errors, value) = context.borrow_state.copy_local(*eloc, var); context.add_errors(errors); vec![value] } E::BorrowLocal(mut_, var) => { let (errors, value) = context.borrow_state.borrow_local(*eloc, *mut_, var); context.add_errors(errors); assert!(value.is_ref()); vec![value] } E::Freeze(e) => { let evalue = assert_single_value(exp(context, e)); let (errors, value) = context.borrow_state.freeze(*eloc, evalue); context.add_errors(errors); vec![value] } E::Dereference(e) => { let evalue = assert_single_value(exp(context, e)); let (errors, value) = context.borrow_state.dereference(*eloc, evalue); context.add_errors(errors); vec![value] } E::Borrow(mut_, e, f) => { let evalue = assert_single_value(exp(context, e)); let (errors, value) = context.borrow_state.borrow_field(*eloc, *mut_, evalue, f); context.add_errors(errors); vec![value] } E::Builtin(b, e) => { let evalues = exp(context, e); let b: &BuiltinFunction = b; match b { sp!(_, BuiltinFunction_::BorrowGlobal(mut_, t)) => { assert!(!assert_single_value(evalues).is_ref()); let (errors, value) = context.borrow_state.borrow_global(*eloc, *mut_, t); context.add_errors(errors); vec![value] } sp!(_, BuiltinFunction_::MoveFrom(t)) => { assert!(!assert_single_value(evalues).is_ref()); let (errors, value) = context.borrow_state.move_from(*eloc, t); assert!(!value.is_ref()); context.add_errors(errors); vec![value] } _ => { let ret_ty = &parent_e.ty; let (errors, values) = context .borrow_state .call(*eloc, evalues, &BTreeMap::new(), ret_ty); context.add_errors(errors); values } } } E::ModuleCall(mcall) => { let evalues = exp(context, &mcall.arguments); let ret_ty = &parent_e.ty; let (errors, values) = context .borrow_state .call(*eloc, evalues, &mcall.acquires, ret_ty); context.add_errors(errors); values } E::Unit { .. } | E::Value(_) | E::Constant(_) | E::Spec(_, _) | E::UnresolvedError => { svalue() } E::Cast(e, _) | E::UnaryExp(_, e) => { let v = exp(context, e); assert!(!assert_single_value(v).is_ref()); svalue() } E::BinopExp(e1, sp!(_, BinOp_::Eq), e2) | E::BinopExp(e1, sp!(_, BinOp_::Neq), e2) => { let v1 = assert_single_value(exp(context, e1)); let v2 = assert_single_value(exp(context, e2)); if v1.is_ref() { // derefrence releases the id and checks that it is readable assert!(v2.is_ref()); let (errors, _) = context.borrow_state.dereference(e1.exp.loc, v1); assert!(errors.is_empty(), "ICE eq freezing failed"); let (errors, _) = context.borrow_state.dereference(e1.exp.loc, v2); assert!(errors.is_empty(), "ICE eq freezing failed"); } svalue() } E::BinopExp(e1, _, e2) => { let v1 = assert_single_value(exp(context, e1)); let v2 = assert_single_value(exp(context, e2)); assert!(!v1.is_ref()); assert!(!v2.is_ref()); svalue() } E::Pack(_, _, fields) => { fields.iter().for_each(|(_, _, e)| { let arg = exp(context, e); assert!(!assert_single_value(arg).is_ref()); }); svalue() } E::ExpList(es) => es .iter() .flat_map(|item| exp_list_item(context, item)) .collect(), E::Unreachable => panic!("ICE should not analyze dead code"), } } fn exp_list_item(context: &mut Context, item: &ExpListItem) -> Values { match item { ExpListItem::Single(e, _) | ExpListItem::Splat(_, e, _) => exp(context, e), } }
33.640678
100
0.500705
e9aad5e32f0f51af6c34b69822bd63fcd8615a59
14,097
use std::borrow::Cow; use std::fmt; use std::io; use std::thread; use std::time::{Duration, Instant}; use crate::draw_target::{ProgressDrawState, ProgressDrawTarget}; use crate::style::{ProgressFinish, ProgressStyle}; /// The state of a progress bar at a moment in time. pub(crate) struct ProgressState { pub(crate) style: ProgressStyle, pub(crate) pos: u64, pub(crate) len: u64, pub(crate) tick: u64, pub(crate) started: Instant, pub(crate) draw_target: ProgressDrawTarget, pub(crate) message: Cow<'static, str>, pub(crate) prefix: Cow<'static, str>, pub(crate) draw_delta: u64, pub(crate) draw_rate: u64, pub(crate) draw_next: u64, pub(crate) status: Status, pub(crate) est: Estimate, pub(crate) tick_thread: Option<thread::JoinHandle<()>>, pub(crate) steady_tick: u64, } impl ProgressState { pub(crate) fn new(len: u64, draw_target: ProgressDrawTarget) -> Self { ProgressState { style: ProgressStyle::default_bar(), draw_target, message: "".into(), prefix: "".into(), pos: 0, len, tick: 0, draw_delta: 0, draw_rate: 0, draw_next: 0, status: Status::InProgress, started: Instant::now(), est: Estimate::new(), tick_thread: None, steady_tick: 0, } } /// Returns the string that should be drawn for the /// current spinner string. pub fn current_tick_str(&self) -> &str { if self.is_finished() { self.style.get_final_tick_str() } else { self.style.get_tick_str(self.tick) } } /// Indicates that the progress bar finished. pub fn is_finished(&self) -> bool { match self.status { Status::InProgress => false, Status::DoneVisible => true, Status::DoneHidden => true, } } /// Returns `false` if the progress bar should no longer be /// drawn. pub fn should_render(&self) -> bool { !matches!(self.status, Status::DoneHidden) } /// Returns the completion as a floating-point number between 0 and 1 pub fn fraction(&self) -> f32 { let pct = match (self.pos, self.len) { (_, 0) => 1.0, (0, _) => 0.0, (pos, len) => pos as f32 / len as f32, }; pct.max(0.0).min(1.0) } /// Returns the position of the status bar as `(pos, len)` tuple. pub fn position(&self) -> (u64, u64) { (self.pos, self.len) } /// Returns the current message of the progress bar. pub fn message(&self) -> &str { &self.message } /// Returns the current prefix of the progress bar. pub fn prefix(&self) -> &str { &self.prefix } /// The entire draw width pub fn width(&self) -> usize { self.draw_target.width() } /// The expected ETA pub fn eta(&self) -> Duration { if self.len == !0 || self.is_finished() { return Duration::new(0, 0); } let t = self.est.seconds_per_step(); // add 0.75 to leave 0.25 sec of 0s for the user secs_to_duration(t * self.len.saturating_sub(self.pos) as f64 + 0.75) } /// The expected total duration (that is, elapsed time + expected ETA) pub fn duration(&self) -> Duration { if self.len == !0 || self.is_finished() { return Duration::new(0, 0); } self.started.elapsed() + self.eta() } /// The number of steps per second pub fn per_sec(&self) -> u64 { let avg_time = self.est.seconds_per_step(); if avg_time == 0.0 { 0 } else { (1.0 / avg_time) as u64 } } /// Call the provided `FnOnce` to update the state. Then redraw the /// progress bar if the state has changed. pub fn update_and_draw<F: FnOnce(&mut ProgressState)>(&mut self, f: F) { if self.update(f) { self.draw().ok(); } } /// Call the provided `FnOnce` to update the state. Then unconditionally redraw the /// progress bar. pub fn update_and_force_draw<F: FnOnce(&mut ProgressState)>(&mut self, f: F) { self.update(|state| { state.draw_next = state.pos; f(state); }); self.draw().ok(); } /// Call the provided `FnOnce` to update the state. If a draw should be run, returns `true`. pub fn update<F: FnOnce(&mut ProgressState)>(&mut self, f: F) -> bool { let old_pos = self.pos; f(self); let new_pos = self.pos; if new_pos != old_pos { self.est.record_step(new_pos, Instant::now()); } if new_pos >= self.draw_next { self.draw_next = new_pos.saturating_add(if self.draw_rate != 0 { self.per_sec() / self.draw_rate } else { self.draw_delta }); true } else { false } } /// Finishes the progress bar and leaves the current message. pub fn finish(&mut self) { self.update_and_force_draw(|state| { state.pos = state.len; state.status = Status::DoneVisible; }); } /// Finishes the progress bar at current position and leaves the current message. pub fn finish_at_current_pos(&mut self) { self.update_and_force_draw(|state| { state.status = Status::DoneVisible; }); } /// Finishes the progress bar and sets a message. pub fn finish_with_message(&mut self, msg: impl Into<Cow<'static, str>>) { let msg = msg.into(); self.update_and_force_draw(|state| { state.message = msg; state.pos = state.len; state.status = Status::DoneVisible; }); } /// Finishes the progress bar and completely clears it. pub fn finish_and_clear(&mut self) { self.update_and_force_draw(|state| { state.pos = state.len; state.status = Status::DoneHidden; }); } /// Finishes the progress bar and leaves the current message and progress. pub fn abandon(&mut self) { self.update_and_force_draw(|state| { state.status = Status::DoneVisible; }); } /// Finishes the progress bar and sets a message, and leaves the current progress. pub fn abandon_with_message(&mut self, msg: impl Into<Cow<'static, str>>) { let msg = msg.into(); self.update_and_force_draw(|state| { state.message = msg; state.status = Status::DoneVisible; }); } /// Finishes the progress bar using the [`ProgressFinish`] behavior stored /// in the [`ProgressStyle`]. pub fn finish_using_style(&mut self) { match self.style.get_on_finish() { ProgressFinish::AndLeave => self.finish(), ProgressFinish::AtCurrentPos => self.finish_at_current_pos(), ProgressFinish::WithMessage(msg) => { // Equivalent to `self.finish_with_message` but avoids borrow checker error self.message.clone_from(msg); self.finish(); } ProgressFinish::AndClear => self.finish_and_clear(), ProgressFinish::Abandon => self.abandon(), ProgressFinish::AbandonWithMessage(msg) => { // Equivalent to `self.abandon_with_message` but avoids borrow checker error self.message.clone_from(msg); self.abandon(); } } } pub(crate) fn draw(&mut self) -> io::Result<()> { // we can bail early if the draw target is hidden. if self.draw_target.is_hidden() { return Ok(()); } let lines = match self.should_render() { true => self.style.format_state(&self), false => Vec::new(), }; let draw_state = ProgressDrawState::new(lines, self.is_finished()); self.draw_target.apply_draw_state(draw_state) } } impl Drop for ProgressState { fn drop(&mut self) { // Progress bar is already finished. Do not need to do anything. if self.is_finished() { return; } self.finish_using_style(); } } /// Ring buffer with constant capacity. Used by `ProgressBar`s to display `{eta}`, `{eta_precise}`, /// and `{*_per_sec}`. pub(crate) struct Estimate { buf: Box<[f64; 15]>, /// Lower 4 bits signify the current length, meaning how many values of `buf` are actually /// meaningful (and not just set to 0 by initialization). /// /// The upper 4 bits signify the last used index in the `buf`. The estimate is currently /// implemented as a ring buffer and when recording a new step the oldest value is overwritten. /// Last index is the most recently used position, and as elements are always stored with /// insertion order, `last_index + 1` is the least recently used position and is the first /// to be overwritten. data: u8, start_time: Instant, start_value: u64, } impl Estimate { fn len(&self) -> u8 { self.data & 0x0F } fn set_len(&mut self, len: u8) { // Sanity check to make sure math is correct as otherwise it could result in unexpected bugs debug_assert!(len < 16); self.data = (self.data & 0xF0) | len; } fn last_idx(&self) -> u8 { (self.data & 0xF0) >> 4 } fn set_last_idx(&mut self, last_idx: u8) { // This will wrap last_idx on overflow (setting to 16 will result in 0); this is fine // because Estimate::buf is 15 elements long and this is a ring buffer, so overwriting // the oldest value is correct self.data = ((last_idx & 0x0F) << 4) | (self.data & 0x0F); } fn new() -> Self { let this = Self { buf: Box::new([0.0; 15]), data: 0, start_time: Instant::now(), start_value: 0, }; // Make sure not to break anything accidentally as self.data can't handle bufs longer than // 15 elements (not enough space in a u8) debug_assert!(this.buf.len() < 16); this } pub(crate) fn reset(&mut self, start_value: u64) { self.start_time = Instant::now(); self.start_value = start_value; self.data = 0; } fn record_step(&mut self, value: u64, current_time: Instant) { let elapsed = current_time - self.start_time; let item = { let divisor = value.saturating_sub(self.start_value) as f64; if divisor == 0.0 { 0.0 } else { duration_to_secs(elapsed) / divisor } }; self.push(item); } /// Adds the `value` into the buffer, overwriting the oldest one if full, or increasing length /// by 1 and appending otherwise. fn push(&mut self, value: f64) { let len = self.len(); let last_idx = self.last_idx(); if self.buf.len() > usize::from(len) { // Buffer isn't yet full, increase it's size self.set_len(len + 1); self.buf[usize::from(last_idx)] = value; } else { // Buffer is full, overwrite the oldest value let idx = last_idx % len; self.buf[usize::from(idx)] = value; } self.set_last_idx(last_idx + 1); } /// Average time per step in seconds, using rolling buffer of last 15 steps fn seconds_per_step(&self) -> f64 { let len = self.len(); self.buf[0..usize::from(len)].iter().sum::<f64>() / f64::from(len) } } impl fmt::Debug for Estimate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Estimate") .field("buf", &self.buf) .field("len", &self.len()) .field("last_idx", &self.last_idx()) .field("start_time", &self.start_time) .field("start_value", &self.start_value) .finish() } } pub fn duration_to_secs(d: Duration) -> f64 { d.as_secs() as f64 + f64::from(d.subsec_nanos()) / 1_000_000_000f64 } pub fn secs_to_duration(s: f64) -> Duration { let secs = s.trunc() as u64; let nanos = (s.fract() * 1_000_000_000f64) as u32; Duration::new(secs, nanos) } #[derive(Debug)] pub(crate) enum Status { InProgress, DoneVisible, DoneHidden, } #[cfg(test)] mod tests { use super::*; #[test] fn test_time_per_step() { let test_rate = |items_per_second| { let mut est = Estimate::new(); let mut current_time = est.start_time; let mut current_value = 0; for _ in 0..est.buf.len() { current_value += items_per_second; current_time += Duration::from_secs(1); est.record_step(current_value, current_time); } let avg_seconds_per_step = est.seconds_per_step(); assert!(avg_seconds_per_step > 0.0); assert!(avg_seconds_per_step.is_finite()); let expected_rate = 1.0 / items_per_second as f64; let absolute_error = (avg_seconds_per_step - expected_rate).abs(); assert!( absolute_error < f64::EPSILON, "Expected rate: {}, actual: {}, absolute error: {}", expected_rate, avg_seconds_per_step, absolute_error ); }; test_rate(1); test_rate(1_000); test_rate(1_000_000); test_rate(1_000_000_000); test_rate(1_000_000_001); test_rate(100_000_000_000); test_rate(1_000_000_000_000); test_rate(100_000_000_000_000); test_rate(1_000_000_000_000_000); } #[test] fn test_duration_stuff() { let duration = Duration::new(42, 100_000_000); let secs = duration_to_secs(duration); assert_eq!(secs_to_duration(secs), duration); } }
31.75
100
0.567071
fc50f722d8e0e3971862dfc3afdb11fb383bde53
15,373
use std::{ collections::{HashMap, HashSet}, path::PathBuf, sync::Arc, }; use prost::Message; use candid::Encode; use canister_test::{Canister, Project, Wasm}; use dfn_candid::candid_one; use ic_base_types::CanisterInstallMode; use ic_canister_client::Sender; use ic_nns_common::{ pb::v1::MethodAuthzInfo, types::NeuronId, types::UpdateIcpXdrConversionRatePayload, }; use ic_nns_constants::{ ids::{TEST_NEURON_2_OWNER_KEYPAIR, TEST_NEURON_2_OWNER_PRINCIPAL}, GOVERNANCE_CANISTER_ID, LIFELINE_CANISTER_ID, }; use ic_nns_governance::pb::v1::{Governance as GovernanceProto, NnsFunction}; use ic_nns_gtc::{ der_encode, pb::v1::{AccountState, Gtc as GtcProto}, test_constants::{TEST_IDENTITY_1, TEST_IDENTITY_2, TEST_IDENTITY_3, TEST_IDENTITY_4}, }; use ic_nns_test_utils::{ governance::{ append_inert, get_pending_proposals, reinstall_nns_canister_by_proposal, submit_external_update_proposal, upgrade_nns_canister_by_proposal, upgrade_nns_canister_with_arg_by_proposal, upgrade_root_canister_by_proposal, }, ids::TEST_NEURON_2_ID, itest_helpers::{ local_test_on_nns_subnet, NnsCanisters, NnsInitPayloads, NnsInitPayloadsBuilder, }, }; use ledger_canister::{LedgerCanisterInitPayload, Tokens}; use lifeline::LIFELINE_CANISTER_WASM; /// Seed Round (SR) neurons are released over 48 months in the following tests const SR_MONTHS_TO_RELEASE: u8 = 48; /// Early Contributor Tokenholder (ECT) neurons are released over 12 months in /// the following tests const ECT_MONTHS_TO_RELEASE: u8 = 12; const TEST_SR_ACCOUNTS: &[(&str, u32); 2] = &[ (TEST_IDENTITY_1.gtc_address, 1200), (TEST_IDENTITY_3.gtc_address, 14500), ]; const TEST_ECT_ACCOUNTS: &[(&str, u32); 2] = &[ (TEST_IDENTITY_2.gtc_address, 8544), (TEST_IDENTITY_4.gtc_address, 3789), ]; #[test] fn test_reinstall_and_upgrade_canisters_canonical_ordering() { local_test_on_nns_subnet(|runtime| async move { let init_state = construct_init_state(); let nns_canisters = NnsCanisters::set_up(&runtime, init_state.clone()).await; for CanisterInstallInfo { wasm, use_root, canister, init_payload, mode, } in get_nns_canister_wasm(&nns_canisters, init_state).into_iter() { if use_root { if mode == CanisterInstallMode::Upgrade { if canister.canister_id() == LIFELINE_CANISTER_ID { let methods_authz: Vec<MethodAuthzInfo> = vec![]; upgrade_nns_canister_with_arg_by_proposal( canister, &nns_canisters.governance, &nns_canisters.root, append_inert(Some(&wasm)), Encode!(&methods_authz).unwrap(), ) .await; } else { upgrade_nns_canister_by_proposal( canister, &nns_canisters.governance, &nns_canisters.root, true, // Method fails if wasm stays the same append_inert(Some(&wasm)), ) .await; } } else if mode == CanisterInstallMode::Reinstall { reinstall_nns_canister_by_proposal( canister, &nns_canisters.governance, &nns_canisters.root, wasm, init_payload, ) .await; } } else { // Root Upgrade via Lifeline upgrade_root_canister_by_proposal( &nns_canisters.governance, &nns_canisters.lifeline, wasm, ) .await; } } Ok(()) }); } #[test] #[ignore] fn test_reinstall_and_upgrade_canisters_with_state_changes() { local_test_on_nns_subnet(|runtime| async move { let init_state = construct_init_state(); let nns_canisters = NnsCanisters::set_up(&runtime, init_state.clone()).await; make_changes_to_state(&nns_canisters).await; assert!(check_changes_to_state(&nns_canisters).await); submit_external_update_proposal( &nns_canisters.governance, Sender::from_keypair(&TEST_NEURON_2_OWNER_KEYPAIR), NeuronId(TEST_NEURON_2_ID), // Random proposal type NnsFunction::IcpXdrConversionRate, // Payload itself doesn't matter UpdateIcpXdrConversionRatePayload { data_source: "".to_string(), timestamp_seconds: 1, xdr_permyriad_per_icp: 100, }, "<proposal created by test_reinstall_and_upgrade_canisters_with_state_changes>" .to_string(), "".to_string(), ) .await; // Should have 1 pending proposal let pending_proposals = get_pending_proposals(&nns_canisters.governance).await; assert_eq!(pending_proposals.len(), 1); let canister_install_info = get_nns_canister_wasm(&nns_canisters, init_state); // Reinstall for CanisterInstallInfo { wasm, use_root, canister, init_payload, mode: _, } in canister_install_info.clone().into_iter() { if use_root { reinstall_nns_canister_by_proposal( canister, &nns_canisters.governance, &nns_canisters.root, wasm, init_payload, ) .await; } } // Changes should have been reverted assert!(!check_changes_to_state(&nns_canisters).await); // Should have 0 pending proposals let pending_proposals = get_pending_proposals(&nns_canisters.governance).await; assert_eq!(pending_proposals.len(), 0); // Redo changes for upgrade make_changes_to_state(&nns_canisters).await; submit_external_update_proposal( &nns_canisters.governance, Sender::from_keypair(&TEST_NEURON_2_OWNER_KEYPAIR), NeuronId(TEST_NEURON_2_ID), // Random proposal type NnsFunction::IcpXdrConversionRate, // Payload itself doesn't matter UpdateIcpXdrConversionRatePayload { data_source: "".to_string(), timestamp_seconds: 1, xdr_permyriad_per_icp: 100, }, "<proposal created by test_reinstall_and_upgrade_canisters_with_state_changes>" .to_string(), "".to_string(), ) .await; // Should have 1 pending proposal let pending_proposals = get_pending_proposals(&nns_canisters.governance).await; assert_eq!(pending_proposals.len(), 1); // Upgrade for CanisterInstallInfo { wasm, use_root, canister, init_payload: _, mode: _, } in canister_install_info { if use_root { upgrade_nns_canister_by_proposal( canister, &nns_canisters.governance, &nns_canisters.root, false, wasm, ) .await; } else { // Root Upgrade via Lifeline upgrade_root_canister_by_proposal( &nns_canisters.governance, &nns_canisters.lifeline, wasm, ) .await; } } // Should still have 1 pending proposal let pending_proposals = get_pending_proposals(&nns_canisters.governance).await; assert_eq!(pending_proposals.len(), 1); // Check that changes have persisted assert!(check_changes_to_state(&nns_canisters).await); Ok(()) }); } fn encode_init_state(init_state: NnsInitPayloads) -> Vec<Vec<u8>> { let ledger_init_vec = Encode!(&init_state.ledger).unwrap(); let mut gtc_init_vec = Vec::new(); GtcProto::encode(&init_state.genesis_token, &mut gtc_init_vec).unwrap(); let cmc_init_vec = Encode!(&init_state.cycles_minting).unwrap(); let lifeline_init_vec = Encode!(&init_state.lifeline).unwrap(); let mut governance_init_vec = Vec::new(); GovernanceProto::encode(&init_state.governance, &mut governance_init_vec).unwrap(); let root_init_vec = Encode!(&init_state.root).unwrap(); let registry_init_vec = Encode!(&init_state.registry).unwrap(); vec![ ledger_init_vec, gtc_init_vec, cmc_init_vec, lifeline_init_vec, governance_init_vec, root_init_vec, registry_init_vec, ] } #[derive(Clone)] struct CanisterInstallInfo<'a> { wasm: Wasm, use_root: bool, canister: &'a Canister<'a>, init_payload: Vec<u8>, mode: CanisterInstallMode, } /// Returns a struct of each NNS canister's WASM, whether it is upgraded through /// the Root canister, its installed canister, and its initial payload, in the /// canonical ordering. fn get_nns_canister_wasm<'a>( nns_canisters: &'a NnsCanisters, init_state: NnsInitPayloads, ) -> Vec<CanisterInstallInfo<'a>> { let encoded_init_state = encode_init_state(init_state); vec![ CanisterInstallInfo { wasm: Project::cargo_bin_maybe_use_path_relative_to_rs( "rosetta-api/ledger_canister", "ledger-canister", ), use_root: true, canister: &nns_canisters.ledger, init_payload: encoded_init_state[0].clone(), mode: CanisterInstallMode::Reinstall, }, CanisterInstallInfo { wasm: Project::cargo_bin_maybe_use_path_relative_to_rs( "nns/gtc", "genesis-token-canister", ), use_root: true, canister: &nns_canisters.genesis_token, init_payload: encoded_init_state[1].clone(), mode: CanisterInstallMode::Reinstall, }, CanisterInstallInfo { wasm: Project::cargo_bin_maybe_use_path_relative_to_rs( "rosetta-api/cycles_minting_canister", "cycles-minting-canister", ), use_root: true, canister: &nns_canisters.cycles_minting, init_payload: encoded_init_state[2].clone(), mode: CanisterInstallMode::Reinstall, }, CanisterInstallInfo { wasm: Wasm::from_bytes(LIFELINE_CANISTER_WASM), use_root: true, canister: &nns_canisters.lifeline, init_payload: encoded_init_state[3].clone(), mode: CanisterInstallMode::Upgrade, }, CanisterInstallInfo { wasm: Project::cargo_bin_maybe_use_path_relative_to_rs( "nns/governance", "governance-canister", ), use_root: true, canister: &nns_canisters.governance, init_payload: encoded_init_state[4].clone(), mode: CanisterInstallMode::Reinstall, }, CanisterInstallInfo { wasm: Project::cargo_bin_maybe_use_path_relative_to_rs( "nns/handlers/root", "root-canister", ), use_root: false, canister: &nns_canisters.root, init_payload: encoded_init_state[5].clone(), mode: CanisterInstallMode::Upgrade, }, CanisterInstallInfo { wasm: Project::cargo_bin_maybe_use_path_relative_to_rs( "registry/canister", "registry-canister", ), use_root: true, canister: &nns_canisters.registry, init_payload: encoded_init_state[6].clone(), mode: CanisterInstallMode::Upgrade, }, ] } async fn make_changes_to_state(nns_canisters: &NnsCanisters<'_>) { // GTC change: have TEST_IDENTITY_1 donate their neurons let sign_cmd = move |msg: &[u8]| Ok(TEST_IDENTITY_1.sign(msg)); let sender = Sender::ExternalHsm { pub_key: der_encode(&TEST_IDENTITY_1.public_key()), sign: Arc::new(sign_cmd), }; let donate_account_response: Result<Result<(), String>, String> = nns_canisters .genesis_token .update_from_sender( "donate_account", candid_one, TEST_IDENTITY_1.public_key_hex.to_string(), &sender, ) .await; assert!(donate_account_response.unwrap().is_ok()); } async fn check_changes_to_state(nns_canisters: &NnsCanisters<'_>) -> bool { // GTC change: Assert that TEST_IDENTITY_1 has donated their neurons let sign_cmd = move |msg: &[u8]| Ok(TEST_IDENTITY_1.sign(msg)); let sender = Sender::ExternalHsm { pub_key: der_encode(&TEST_IDENTITY_1.public_key()), sign: Arc::new(sign_cmd), }; let get_account_response: Result<Result<AccountState, String>, String> = nns_canisters .genesis_token .update_from_sender( "get_account", candid_one, TEST_IDENTITY_1.gtc_address.to_string(), &sender, ) .await; let account_after_donation = get_account_response.unwrap().unwrap(); account_after_donation.has_donated } fn construct_init_state() -> NnsInitPayloads { let mut nns_init_payload_builder = NnsInitPayloadsBuilder::new(); // Initialize the ledger with an account for a user let mut ledger_init_state = HashMap::new(); ledger_init_state.insert( (*TEST_NEURON_2_OWNER_PRINCIPAL).into(), Tokens::from_tokens(1000).unwrap(), ); nns_init_payload_builder.ledger = LedgerCanisterInitPayload::new( GOVERNANCE_CANISTER_ID.into(), ledger_init_state, None, None, None, HashSet::new(), ); nns_init_payload_builder .genesis_token .genesis_timestamp_seconds = 1; nns_init_payload_builder.genesis_token.sr_months_to_release = Some(SR_MONTHS_TO_RELEASE); nns_init_payload_builder.genesis_token.ect_months_to_release = Some(ECT_MONTHS_TO_RELEASE); nns_init_payload_builder .genesis_token .add_sr_neurons(TEST_SR_ACCOUNTS); nns_init_payload_builder .genesis_token .add_ect_neurons(TEST_ECT_ACCOUNTS); nns_init_payload_builder .genesis_token .donate_account_recipient_neuron_id = Some(NeuronId(TEST_NEURON_2_ID).into()); let csv_file: PathBuf = ["src", "neurons.csv"].iter().collect(); nns_init_payload_builder .governance .with_test_neurons() .add_all_neurons_from_csv_file(&csv_file); // The registry checks invariants when it is upgraded nns_init_payload_builder.with_initial_invariant_compliant_mutations(); nns_init_payload_builder.build() }
35.17849
95
0.598582
5d8f1e1f6a79e95a7777e97f0d6c455e612dd5dc
4,268
// Copyright (c) The enable-ansi-support Contributors // SPDX-License-Identifier: MIT //! Enable ANSI code support on Windows 10 and above. //! //! This crate provides one function, `enable_ansi_support`, which allows [ANSI escape codes] //! to work on Windows 10 and above. //! //! Call `enable_ansi_support` *once*, early on in `main()`, to enable ANSI escape codes generated //! by crates like //! [`ansi_term`](https://docs.rs/ansi_term) or [`owo-colors`](https://docs.rs/owo-colors) //! to work on Windows just like they do on Unix platforms. //! //! ## Examples //! //! ```rust //! fn main() { //! match enable_ansi_support::enable_ansi_support() { //! Ok(()) => { //! // ANSI escape codes were successfully enabled, or this is a non-Windows platform. //! } //! Err(_) => { //! // The operation was unsuccessful, typically because it's running on an older //! // version of Windows. The program may choose to disable ANSI color code output in //! // this case. //! } //! } //! //! // Use your terminal color library of choice here. //! } //! ``` //! //! ## How it works //! //! `enable_ansi_support` uses Windows API calls to alter the properties of the console that //! the program is running in. See the //! [Windows documentation](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) //! for more information. //! //! On non-Windows platforms, `enable_ansi_support` is a no-op. //! //! [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code #![allow(clippy::needless_doctest_main)] /// Enables ANSI code support on Windows 10. /// /// Returns the Windows error code if unsuccessful. /// /// On non-Windows platforms, this is a no-op that always returns `Ok(())`. /// /// # Examples /// /// See the [crate documentation](crate). #[cfg(windows)] pub fn enable_ansi_support() -> Result<(), u32> { // ref: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#EXAMPLE_OF_ENABLING_VIRTUAL_TERMINAL_PROCESSING @@ https://archive.is/L7wRJ#76% use std::{ffi::OsStr, iter::once, os::windows::ffi::OsStrExt, ptr::null_mut}; use winapi::um::{ consoleapi::{GetConsoleMode, SetConsoleMode}, errhandlingapi::GetLastError, fileapi::{CreateFileW, OPEN_EXISTING}, handleapi::INVALID_HANDLE_VALUE, winnt::{FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE}, }; const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004; unsafe { // ref: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew // Using `CreateFileW("CONOUT$", ...)` to retrieve the console handle works correctly even if STDOUT and/or STDERR are redirected let console_out_name: Vec<u16> = OsStr::new("CONOUT$").encode_wide().chain(once(0)).collect(); let console_handle = CreateFileW( console_out_name.as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, null_mut(), OPEN_EXISTING, 0, null_mut(), ); if console_handle == INVALID_HANDLE_VALUE { return Err(GetLastError()); } // ref: https://docs.microsoft.com/en-us/windows/console/getconsolemode let mut console_mode: u32 = 0; if 0 == GetConsoleMode(console_handle, &mut console_mode) { return Err(GetLastError()); } // VT processing not already enabled? if console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0 { // https://docs.microsoft.com/en-us/windows/console/setconsolemode if 0 == SetConsoleMode( console_handle, console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING, ) { return Err(GetLastError()); } } } Ok(()) } /// Enables ANSI code support on Windows 10. /// /// Returns the Windows error code if unsuccessful. /// /// On non-Windows platforms, this is a no-op that always returns `Ok(())`. /// /// # Examples /// /// See the [crate documentation](crate). #[cfg(not(windows))] #[inline] pub fn enable_ansi_support() -> Result<(), u32> { Ok(()) }
34.983607
175
0.629569
231e7344b4ea12a8f4ccd0fe8bb3512ee449daa3
21,732
//! The workflow and queue consumer for DhtOp integration use super::*; use crate::core::{ queue_consumer::{OneshotWriter, TriggerSender, WorkComplete}, state::{ cascade::error::CascadeResult, cascade::Cascade, cascade::DbPair, dht_op_integration::{ IntegratedDhtOpsStore, IntegratedDhtOpsValue, IntegrationLimboStore, IntegrationLimboValue, }, element_buf::ElementBuf, metadata::{MetadataBuf, MetadataBufT}, validation_db::ValidationLimboStore, workspace::{Workspace, WorkspaceResult}, }, validation::DhtOpOrder, validation::OrderedOp, }; use error::WorkflowResult; use fallible_iterator::FallibleIterator; use holo_hash::{DhtOpHash, EntryHash, HeaderHash}; use holochain_state::{ buffer::BufferedStore, buffer::KvBufFresh, db::{INTEGRATED_DHT_OPS, INTEGRATION_LIMBO}, error::DatabaseResult, fresh_reader, prelude::*, }; use holochain_types::{ dht_op::{produce_op_lights_from_elements, DhtOp, DhtOpLight, UniqueForm}, element::{Element, SignedHeaderHashed, SignedHeaderHashedExt}, validate::ValidationStatus, Entry, EntryHashed, Timestamp, }; use holochain_zome_types::{element::ElementEntry, signature::Signature}; use holochain_zome_types::{element::SignedHeader, Header}; use produce_dht_ops_workflow::dht_op_light::{ error::{DhtOpConvertError, DhtOpConvertResult}, light_to_op, }; use std::{collections::BinaryHeap, convert::TryInto}; use tracing::*; pub use disintegrate::*; mod disintegrate; mod tests; #[instrument(skip(workspace, writer, trigger_sys))] pub async fn integrate_dht_ops_workflow( mut workspace: IntegrateDhtOpsWorkspace, writer: OneshotWriter, trigger_sys: &mut TriggerSender, ) -> WorkflowResult<WorkComplete> { // one of many possible ways to access the env let env = workspace.elements.headers().env().clone(); // Pull ops out of queue // TODO: PERF: Combine this collect with the sort when ElementBuf gets // aren't async let ops: Vec<IntegrationLimboValue> = fresh_reader!(env, |r| workspace .integration_limbo .drain_iter(&r)? .collect())?; // Sort the ops let mut sorted_ops = BinaryHeap::new(); for iv in ops { let op = light_to_op(iv.op.clone(), &workspace.element_pending)?; let hash = DhtOpHash::with_data_sync(&op); let order = DhtOpOrder::from(&op); let v = OrderedOp { order, hash, op, value: iv, }; sorted_ops.push(v); } let mut total_integrated: usize = 0; // Try to process the queue over and over again, until we either exhaust // the queue, or we can no longer integrate anything in the queue. // We do this because items in the queue may depend on one another but may // be out-of-order wrt. dependencies, so there is a chance that by repeating // integration, we may be able to integrate at least one more item. loop { let mut num_integrated: usize = 0; let mut next_ops = BinaryHeap::new(); for so in sorted_ops.into_sorted_vec() { let OrderedOp { hash, op, value, order, } = so; // Check validation status and put in correct dbs let outcome = integrate_single_dht_op(value.clone(), op, &mut workspace).await?; match outcome { Outcome::Integrated(integrated) => { // TODO We could create a prefix for the integrated ops db // and separate rejected ops from valid ops. // Currently you need to check the IntegratedDhtOpsValue for // the status workspace.integrate(hash, integrated)?; num_integrated += 1; total_integrated += 1; } Outcome::Deferred(op) => next_ops.push(OrderedOp { hash, order, op, value, }), } } sorted_ops = next_ops; // Either all ops are integrated or we couldn't integrate any on this pass if sorted_ops.is_empty() || num_integrated == 0 { break; } } let result = if sorted_ops.is_empty() { // There were no ops deferred, meaning we exhausted the queue WorkComplete::Complete } else { // Re-add the remaining ops to the queue, to be picked up next time. for so in sorted_ops { // TODO: it may be desirable to retain the original timestamp // when re-adding items to the queue for later processing. This is // challenging for now since we don't have access to that original // key. Just a possible note for the future. workspace.integration_limbo.put(so.hash, so.value)?; } WorkComplete::Incomplete }; // --- END OF WORKFLOW, BEGIN FINISHER BOILERPLATE --- // commit the workspace writer.with_writer(|writer| Ok(workspace.flush_to_txn(writer)?))?; // trigger other workflows if total_integrated > 0 { trigger_sys.trigger(); } Ok(result) } /// Integrate a single DhtOp to the stores based on the /// validation status. /// /// Check for dependencies in any of our other stores. #[instrument(skip(iv, workspace))] async fn integrate_single_dht_op( iv: IntegrationLimboValue, op: DhtOp, workspace: &mut IntegrateDhtOpsWorkspace, ) -> WorkflowResult<Outcome> { if op_dependencies_held(&op, workspace).await? { match iv.validation_status { ValidationStatus::Valid => Ok(integrate_data_and_meta( iv, op, &mut workspace.elements, &mut workspace.meta, )?), ValidationStatus::Rejected => Ok(integrate_data_and_meta( iv, op, &mut workspace.element_rejected, &mut workspace.meta_rejected, )?), ValidationStatus::Abandoned => { // Throwing away abandoned ops // TODO: keep abandoned ops but remove the entries // and put them in a AbandonedPrefix db let integrated = IntegratedDhtOpsValue { validation_status: iv.validation_status, op: iv.op, when_integrated: Timestamp::now(), }; Ok(Outcome::Integrated(integrated)) } } } else { debug!("deferring"); Ok(Outcome::Deferred(op)) } } fn integrate_data_and_meta<P: PrefixType>( iv: IntegrationLimboValue, op: DhtOp, element_store: &mut ElementBuf<P>, meta_store: &mut MetadataBuf<P>, ) -> DhtOpConvertResult<Outcome> { integrate_single_data(op, element_store)?; integrate_single_metadata(iv.op.clone(), element_store, meta_store)?; let integrated = IntegratedDhtOpsValue { validation_status: iv.validation_status, op: iv.op, when_integrated: Timestamp::now(), }; debug!("integrating"); Ok(Outcome::Integrated(integrated)) } /// Check if we have the required dependencies held before integrating. async fn op_dependencies_held( op: &DhtOp, workspace: &mut IntegrateDhtOpsWorkspace, ) -> CascadeResult<bool> { { match op { DhtOp::StoreElement(_, _, _) | DhtOp::StoreEntry(_, _, _) => (), DhtOp::RegisterAgentActivity(_, header) => { // RegisterAgentActivity is the exception where we need to make // sure that we have integrated the previous RegisterAgentActivity DhtOp // from the same chain. // This is because to say if the chain is valid as a whole we can't // have parts missing. let mut cascade = workspace.cascade(); let prev_header_hash = header.prev_header(); if let Some(prev_header_hash) = prev_header_hash.cloned() { match cascade .retrieve_header(prev_header_hash, Default::default()) .await? { Some(prev_header) => { let op_hash = DhtOpHash::with_data_sync( &UniqueForm::RegisterAgentActivity(prev_header.header()), ); if workspace.integration_limbo.contains(&op_hash)? { return Ok(true); } } None => return Ok(false), } } } DhtOp::RegisterUpdatedBy(_, entry_update, _) => { // Check if we have the header with entry that we are updating // or defer the op. if !header_with_entry_is_stored( &entry_update.original_header_address, workspace.cascade(), ) .await? { return Ok(false); } } DhtOp::RegisterDeletedBy(_, element_delete) | DhtOp::RegisterDeletedEntryHeader(_, element_delete) => { // Check if we have the header with the entry that we are removing // or defer the op. if !header_with_entry_is_stored( &element_delete.deletes_address, workspace.cascade(), ) .await? { return Ok(false); } } DhtOp::RegisterAddLink(_, create_link) => { // Check whether we have the base address. // If not then this should put the op back on the queue. if !entry_is_stored(&create_link.base_address, workspace.cascade()).await? { return Ok(false); } } DhtOp::RegisterRemoveLink(_, delete_link) => { // Check whether we have the link add address. // If not then this should put the op back on the queue. if !header_is_stored(&delete_link.link_add_address, workspace.cascade()).await? { return Ok(false); } } } Ok(true) } } /// Check the cascade to see if this Header is also stored with an Entry async fn header_with_entry_is_stored( hash: &HeaderHash, mut cascade: Cascade<'_>, ) -> CascadeResult<bool> { // TODO: PERF: Add contains() to cascade so we don't deserialize // the entry match cascade .retrieve(hash.clone().into(), Default::default()) .await? { Some(el) => match el.entry() { ElementEntry::Present(_) | ElementEntry::Hidden => Ok(true), ElementEntry::NotApplicable => Err(DhtOpConvertError::HeaderEntryMismatch.into()), // This means we have just the header (probably through register agent activity) ElementEntry::NotStored => Ok(false), }, None => Ok(false), } } /// Check if an Entry is stored in the cascade async fn entry_is_stored(hash: &EntryHash, mut cascade: Cascade<'_>) -> CascadeResult<bool> { // TODO: PERF: Add contains() to cascade so we don't deserialize // the entry match cascade .retrieve_entry(hash.clone(), Default::default()) .await? { Some(_) => Ok(true), None => Ok(false), } } /// Check if a header is stored in the cascade async fn header_is_stored(hash: &HeaderHash, mut cascade: Cascade<'_>) -> CascadeResult<bool> { match cascade .retrieve_header(hash.clone(), Default::default()) .await? { Some(_) => Ok(true), None => Ok(false), } } pub fn integrate_single_metadata<C, P>( op: DhtOpLight, element_store: &ElementBuf<P>, meta_store: &mut C, ) -> DhtOpConvertResult<()> where P: PrefixType, C: MetadataBufT<P>, { match op { DhtOpLight::StoreElement(hash, _, _) => { let header = get_header(hash, element_store)?; meta_store.register_element_header(&header)?; } DhtOpLight::StoreEntry(hash, _, _) => { let new_entry_header = get_header(hash, element_store)?.try_into()?; // Reference to headers meta_store.register_header(new_entry_header)?; } DhtOpLight::RegisterAgentActivity(hash, _) => { let header = get_header(hash, element_store)?; // register agent activity on this agents pub key meta_store.register_activity(&header)?; } DhtOpLight::RegisterUpdatedBy(hash, _, _) => { let header = get_header(hash, element_store)?.try_into()?; meta_store.register_update(header)?; } DhtOpLight::RegisterDeletedEntryHeader(hash, _) | DhtOpLight::RegisterDeletedBy(hash, _) => { let header = get_header(hash, element_store)?.try_into()?; meta_store.register_delete(header)? } DhtOpLight::RegisterAddLink(hash, _) => { let header = get_header(hash, element_store)?.try_into()?; meta_store.add_link(header)?; } DhtOpLight::RegisterRemoveLink(hash, _) => { let header = get_header(hash, element_store)?.try_into()?; meta_store.delete_link(header)?; } } Ok(()) } /// Store a DhtOp's data in an element buf pub fn integrate_single_data<P: PrefixType>( op: DhtOp, element_store: &mut ElementBuf<P>, ) -> DhtOpConvertResult<()> { { match op { DhtOp::StoreElement(signature, header, maybe_entry) => { put_data(signature, header, maybe_entry.map(|e| *e), element_store)?; } DhtOp::StoreEntry(signature, new_entry_header, entry) => { put_data( signature, new_entry_header.into(), Some(*entry), element_store, )?; } DhtOp::RegisterAgentActivity(signature, header) => { put_data(signature, header, None, element_store)?; } DhtOp::RegisterUpdatedBy(signature, entry_update, _) => { put_data(signature, entry_update.into(), None, element_store)?; } DhtOp::RegisterDeletedEntryHeader(signature, element_delete) => { put_data(signature, element_delete.into(), None, element_store)?; } DhtOp::RegisterDeletedBy(signature, element_delete) => { put_data(signature, element_delete.into(), None, element_store)?; } DhtOp::RegisterAddLink(signature, link_add) => { put_data(signature, link_add.into(), None, element_store)?; } DhtOp::RegisterRemoveLink(signature, link_remove) => { put_data(signature, link_remove.into(), None, element_store)?; } } Ok(()) } } fn put_data<P: PrefixType>( signature: Signature, header: Header, maybe_entry: Option<Entry>, element_store: &mut ElementBuf<P>, ) -> DhtOpConvertResult<()> { let signed_header = SignedHeaderHashed::from_content_sync(SignedHeader(header, signature)); let maybe_entry_hashed = match maybe_entry { Some(entry) => Some(EntryHashed::from_content_sync(entry)), None => None, }; element_store.put(signed_header, maybe_entry_hashed)?; Ok(()) } fn get_header<P: PrefixType>( hash: HeaderHash, element_store: &ElementBuf<P>, ) -> DhtOpConvertResult<Header> { Ok(element_store .get_header(&hash)? .ok_or_else(|| DhtOpConvertError::MissingData(hash.into()))? .into_header_and_signature() .0 .into_content()) } /// After writing an Element to our chain, we want to integrate the meta ops /// inline, so that they are immediately available in the authored metadata. /// NB: We skip integrating the element data, since it is already available in /// our source chain. pub async fn integrate_to_authored<C: MetadataBufT<AuthoredPrefix>>( element: &Element, element_store: &ElementBuf<AuthoredPrefix>, meta_store: &mut C, ) -> DhtOpConvertResult<()> { // Produce the light directly for op in produce_op_lights_from_elements(vec![element]).await? { // we don't integrate element data, because it is already in our vault. integrate_single_metadata(op, element_store, meta_store)? } Ok(()) } /// The outcome of integrating a single DhtOp: either it was, or it wasn't enum Outcome { Integrated(IntegratedDhtOpsValue), Deferred(DhtOp), } pub struct IntegrateDhtOpsWorkspace { /// integration queue pub integration_limbo: IntegrationLimboStore, /// integrated ops pub integrated_dht_ops: IntegratedDhtOpsStore, /// Cas for storing pub elements: ElementBuf, /// metadata store pub meta: MetadataBuf, /// Data that has progressed past validation and is pending Integration pub element_pending: ElementBuf<PendingPrefix>, pub meta_pending: MetadataBuf<PendingPrefix>, pub element_rejected: ElementBuf<RejectedPrefix>, pub meta_rejected: MetadataBuf<RejectedPrefix>, /// Ops to disintegrate pub to_disintegrate_pending: Vec<DhtOpLight>, /// READ ONLY /// Need the validation limbo to make sure we don't /// remove data that is in this limbo pub validation_limbo: ValidationLimboStore, } impl Workspace for IntegrateDhtOpsWorkspace { fn flush_to_txn_ref(&mut self, writer: &mut Writer) -> WorkspaceResult<()> { self.update_element_stores(writer)?; // flush elements self.elements.flush_to_txn_ref(writer)?; // flush metadata store self.meta.flush_to_txn_ref(writer)?; // flush integrated self.integrated_dht_ops.flush_to_txn_ref(writer)?; // flush integration queue self.integration_limbo.flush_to_txn_ref(writer)?; self.element_pending.flush_to_txn_ref(writer)?; self.meta_pending.flush_to_txn_ref(writer)?; self.element_rejected.flush_to_txn_ref(writer)?; self.meta_rejected.flush_to_txn_ref(writer)?; Ok(()) } } impl IntegrateDhtOpsWorkspace { /// Constructor pub fn new(env: EnvironmentRead) -> WorkspaceResult<Self> { let db = env.get_db(&*INTEGRATED_DHT_OPS)?; let integrated_dht_ops = KvBufFresh::new(env.clone(), db); let db = env.get_db(&*INTEGRATION_LIMBO)?; let integration_limbo = KvBufFresh::new(env.clone(), db); let validation_limbo = ValidationLimboStore::new(env.clone())?; let elements = ElementBuf::vault(env.clone(), true)?; let meta = MetadataBuf::vault(env.clone())?; let element_pending = ElementBuf::pending(env.clone())?; let meta_pending = MetadataBuf::pending(env.clone())?; let element_rejected = ElementBuf::rejected(env.clone())?; let meta_rejected = MetadataBuf::rejected(env)?; Ok(Self { integration_limbo, integrated_dht_ops, elements, meta, element_pending, meta_pending, element_rejected, meta_rejected, validation_limbo, to_disintegrate_pending: Vec::new(), }) } #[tracing::instrument(skip(self, hash))] fn integrate(&mut self, hash: DhtOpHash, v: IntegratedDhtOpsValue) -> DhtOpConvertResult<()> { disintegrate_single_metadata(v.op.clone(), &self.element_pending, &mut self.meta_pending)?; self.to_disintegrate_pending.push(v.op.clone()); self.integrated_dht_ops.put(hash, v)?; Ok(()) } pub fn op_exists(&self, hash: &DhtOpHash) -> DatabaseResult<bool> { Ok(self.integrated_dht_ops.contains(&hash)? || self.integration_limbo.contains(&hash)?) } /// Create a cascade through the integrated and rejected stores // TODO: Might need to add abandoned here but will need some // thought as abandoned entries are not stored. pub fn cascade(&self) -> Cascade<'_> { let integrated_data = DbPair { element: &self.elements, meta: &self.meta, }; let rejected_data = DbPair { element: &self.element_rejected, meta: &self.meta_rejected, }; Cascade::empty() .with_integrated(integrated_data) .with_rejected(rejected_data) } #[tracing::instrument(skip(self, writer))] /// We need to cancel any deletes for the judged data /// where the ops still in integration limbo reference that data fn update_element_stores(&mut self, writer: &mut Writer) -> WorkspaceResult<()> { for op in self.to_disintegrate_pending.drain(..) { disintegrate_single_data(op, &mut self.element_pending); } let mut int_iter = self.integration_limbo.iter(writer)?; while let Some((_, vlv)) = int_iter.next()? { reintegrate_single_data(vlv.op, &mut self.element_pending); } let mut val_iter = self.validation_limbo.iter(writer)?; while let Some((_, vlv)) = val_iter.next()? { reintegrate_single_data(vlv.op, &mut self.element_pending); } Ok(()) } }
36.40201
99
0.595389
09af865230234abf06618d241aaec30d9982a0cf
42,894
use std::collections::HashMap; use std::hash::BuildHasher; use std::path::{Path, PathBuf}; use std::{env, fs, io}; use glob::glob; use crate::builtins_util::*; use crate::environment::*; use crate::eval::*; use crate::interner::*; use crate::types::*; use crate::{param_eval, params_done, rand_alphanumeric_str}; use core::iter; use same_file; use std::ffi::OsStr; use std::fs::{File, Metadata}; use std::time::SystemTime; use walkdir::{DirEntry, WalkDir}; const LEN: u64 = 5; fn cd_expand_all_dots(cd: String) -> String { let mut all_dots = false; if cd.len() > 2 { all_dots = true; for ch in cd.chars() { if ch != '.' { all_dots = false; break; } } } if all_dots { let mut new_cd = String::new(); let paths_up = cd.len() - 2; new_cd.push_str("../"); for _i in 0..paths_up { new_cd.push_str("../"); } new_cd } else { cd } } fn builtin_cd( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let home = match env::var("HOME") { Ok(val) => val, Err(_) => "/".to_string(), }; let old_dir = match env::var("OLDPWD") { Ok(val) => val, Err(_) => home.to_string(), }; let new_dir = if let Some(arg) = args.next() { if args.next().is_none() { let arg_d = arg.get(); let new_arg = match &arg_d.data { ExpEnum::Symbol(s, _) => match get_expression(environment, arg.clone()) { Some(exp) => match &exp.get().data { ExpEnum::Function(_) => eval( environment, Expression::alloc_data(ExpEnum::String((*s).into(), None)), )?, ExpEnum::Lambda(_) => eval( environment, Expression::alloc_data(ExpEnum::String((*s).into(), None)), )?, ExpEnum::Macro(_) => eval( environment, Expression::alloc_data(ExpEnum::String((*s).into(), None)), )?, _ => { drop(arg_d); eval(environment, &arg)? } }, _ => { drop(arg_d); eval(environment, &arg)? } }, _ => { drop(arg_d); eval(environment, &arg)? } } .as_string(environment)?; if let Some(h) = expand_tilde(&new_arg) { h } else { new_arg } } else { return Err(LispError::new("cd can not have more then one form")); } } else { home }; let new_dir = if new_dir == "-" { &old_dir } else { &new_dir }; let new_dir = cd_expand_all_dots(new_dir.to_string()); let root = Path::new(&new_dir); if let Ok(oldpwd) = env::current_dir() { env::set_var("OLDPWD", oldpwd); } if let Err(e) = env::set_current_dir(&root) { eprintln!("Error changing to {}, {}", root.display(), e); Ok(Expression::make_nil()) } else { env::set_var("PWD", env::current_dir()?); Ok(Expression::make_true()) } } pub fn get_file(environment: &mut Environment, p: Expression) -> Option<PathBuf> { let p = match &eval(environment, p).ok()?.get().data { ExpEnum::String(p, _) => { match expand_tilde(p) { Some(p) => p, None => p.to_string(), // XXX not great. } } _ => return None, }; let p = Path::new(&p); Some((*p.to_path_buf()).to_owned()) } fn file_test( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, test: fn(path: &Path) -> bool, fn_name: &str, ) -> Result<Expression, LispError> { if let Some(p) = args.next() { if args.next().is_none() { if let Some(path) = get_file(environment, p) { if test(path.as_path()) { return Ok(Expression::make_true()); } else { return Ok(Expression::make_nil()); } } else { let msg = format!("{} takes a string (a path)", fn_name); return Err(LispError::new(msg)); } } } let msg = format!("{} takes a string (a path)", fn_name); Err(LispError::new(msg)) } fn builtin_path_exists( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { file_test(environment, args, |path| path.exists(), "fs-exists?") } fn builtin_is_file( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { file_test(environment, args, |path| path.is_file(), "fs-file?") } fn builtin_is_dir( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { file_test(environment, args, |path| path.is_dir(), "fs-dir?") } fn builtin_glob( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { fn remove_escapes(pat: &str) -> String { let mut ret = String::new(); let mut last_esc = false; for ch in pat.chars() { match ch { '\\' if last_esc => { ret.push('\\'); last_esc = false; } '\\' => last_esc = true, '*' if last_esc => { ret.push('*'); last_esc = false; } '?' if last_esc => { ret.push('?'); last_esc = false; } '[' if last_esc => { ret.push('['); last_esc = false; } ']' if last_esc => { ret.push(']'); last_esc = false; } _ => { if last_esc { ret.push('\\'); } ret.push(ch); } } } ret } let mut files = Vec::new(); for pat in args { let pat = match &eval(environment, pat)?.get().data { ExpEnum::String(s, _) => s.to_string(), _ => return Err(LispError::new("globs need to be strings")), }; let pat = match expand_tilde(&pat) { Some(p) => p, None => pat, }; if let Ok(paths) = glob(&pat) { for p in paths { match p { Ok(p) => { if let Some(p) = p.to_str() { files.push(Expression::alloc_data(ExpEnum::String( p.to_string().into(), None, ))); } } Err(err) => { let msg = format!("glob error on while iterating {}, {}", pat, err); return Err(LispError::new(msg)); } } } if files.is_empty() { // Got nothing so fall back on pattern. if pat.contains('\\') { files.push(Expression::alloc_data(ExpEnum::String( remove_escapes(&pat).into(), None, ))); } else { files.push(Expression::alloc_data(ExpEnum::String(pat.into(), None))); } } } else if pat.contains('\\') { files.push(Expression::alloc_data(ExpEnum::String( remove_escapes(&pat).into(), None, ))); } else { files.push(Expression::alloc_data(ExpEnum::String(pat.into(), None))); } } Ok(Expression::with_list(files)) } fn builtin_fs_parent( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "fs-parent"; let arg = param_eval(environment, args, fn_name)?; params_done(args, fn_name)?; match get_file(environment, arg) { Some(path) => { let mut path = path.canonicalize().map_err(|_| { let msg = format!("{} failed to get full filepath of parent", fn_name); LispError::new(msg) })?; let _ = path.pop(); let path = path.as_path().to_str().ok_or_else(|| { let msg = format!("{} failed to get parent path", fn_name); LispError::new(msg) })?; let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); Ok(path) } None => { let msg = format!("{} first arg is not a valid path", fn_name); Err(LispError::new(msg)) } } } fn builtin_fs_base( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "fs-base"; let arg = param_eval(environment, args, fn_name)?; params_done(args, fn_name)?; match get_file(environment, arg) { Some(path) => { let path = path.file_name().and_then(|s| s.to_str()).ok_or_else(|| { let msg = format!("{} failed to extract name of file", fn_name); LispError::new(msg) })?; let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); Ok(path) } None => { let msg = format!("{} first arg is not a valid path", fn_name); Err(LispError::new(msg)) } } } fn builtin_same_file( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "fs-same?"; let arg0 = param_eval(environment, args, fn_name)?; let arg1 = param_eval(environment, args, fn_name)?; params_done(args, fn_name)?; let path_0 = match get_file(environment, arg0) { Some(path) => path, None => { let msg = format!("{} first arg is not a valid path", fn_name); return Err(LispError::new(msg)); } }; let path_1 = match get_file(environment, arg1) { Some(path) => path, None => { let msg = format!("{} second arg is not a valid path", fn_name); return Err(LispError::new(msg)); } }; if let Ok(b) = same_file::is_same_file(path_0.as_path(), path_1.as_path()) { if b { Ok(Expression::make_true()) } else { Ok(Expression::make_false()) } } else { let msg = format!( "{} one or more paths does not exist, or there were not enough \ permissions.", fn_name ); Err(LispError::new(msg)) } } fn builtin_fs_crawl( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "fs-crawl"; let arg0 = param_eval(environment, args, fn_name)?; let file_or_dir = get_file(environment, arg0); let lambda_exp = param_eval(environment, args, fn_name)?; let mut depth = None; let mut sym_links = None; for _ in 0..2 { if let Ok(depth_or_sym_link) = param_eval(environment, args, fn_name) { if let Ok(d) = depth_or_sym_link.make_int(environment) { depth = Some(d); } else if let Ok(s) = depth_or_sym_link.make_string(environment) { if s == ":follow-syms" { sym_links = Some(true); } } }; } // TODO cb masks fact that call_lambda can fail, // this is bad, an error should be (optionally?) passed up // not swallowed s.t. silent failure occurs. let mut cb = |entry: &DirEntry| { let path = entry.path(); if let Some(path) = path.to_str() { let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); let mut args = iter::once(path); let _ = call_lambda(environment, lambda_exp.copy(), &mut args, true); } }; let mut iterate = |file_or_dir, depth, sym_links| match (depth, sym_links) { (Some(depth), Some(sym_links)) => { for entry in WalkDir::new(file_or_dir) .max_depth(depth as usize) .follow_links(sym_links) .into_iter() .filter_map(|e| e.ok()) { cb(&entry); } } (Some(depth), None) => { for entry in WalkDir::new(file_or_dir) .max_depth(depth as usize) .into_iter() .filter_map(|e| e.ok()) { cb(&entry); } } (None, Some(sym_links)) => { for entry in WalkDir::new(file_or_dir) .follow_links(sym_links) .into_iter() .filter_map(|e| e.ok()) { cb(&entry); } } (None, None) => { for entry in WalkDir::new(file_or_dir).into_iter().filter_map(|e| e.ok()) { cb(&entry); } } }; let lambda_exp_d = &lambda_exp.get().data; params_done(args, fn_name)?; match lambda_exp_d { ExpEnum::Lambda(_) => { if let Some(file_or_dir) = file_or_dir { iterate(file_or_dir, depth, sym_links); Ok(Expression::make_true()) } else { let msg = format!("{} provided path does not exist", fn_name); Err(LispError::new(msg)) } } _ => { let msg = format!("{} second argument must be function", fn_name); Err(LispError::new(msg)) } } } fn builtin_fs_len( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "fs-len"; let arg0 = param_eval(environment, args, fn_name)?; let file_or_dir = get_file(environment, arg0); params_done(args, fn_name)?; if let Some(file_or_dir) = file_or_dir { if let Ok(metadata) = fs::metadata(file_or_dir) { let len = metadata.len(); Ok(Expression::alloc_data(ExpEnum::Int(len as i64))) } else { let msg = format!("{} can not fetch metadata at provided path", fn_name); Err(LispError::new(msg)) } } else { let msg = format!("{} provided path does not exist", fn_name); Err(LispError::new(msg)) } } fn get_file_time( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, fn_name: &str, to_time: fn(Metadata) -> io::Result<SystemTime>, ) -> Result<Expression, LispError> { let arg0 = param_eval(environment, args, fn_name)?; let file_or_dir = get_file(environment, arg0); params_done(args, fn_name)?; if let Some(file_or_dir) = file_or_dir { if let Ok(metadata) = fs::metadata(file_or_dir) { if let Ok(sys_time) = to_time(metadata) { match sys_time.duration_since(SystemTime::UNIX_EPOCH) { Ok(n) => { let n = n.as_millis() as i64; Ok(Expression::alloc_data(ExpEnum::Int(n))) } Err(_) => { let msg = format!("{} can not parse time", fn_name); Err(LispError::new(msg)) } } } else { let msg = format!("{} can not fetch time", fn_name); Err(LispError::new(msg)) } } else { let msg = format!("{} can not fetch metadata at provided path", fn_name); Err(LispError::new(msg)) } } else { let msg = format!("{} provided path does not exist", fn_name); Err(LispError::new(msg)) } } fn builtin_fs_modified( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { get_file_time(environment, args, "fs-modified", |md| md.modified()) } fn builtin_fs_accessed( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { get_file_time(environment, args, "fs-accessed", |md| md.accessed()) } fn temp_dir() -> PathBuf { std::env::temp_dir() } fn builtin_get_temp_dir( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "get-temp"; let dir; let mut prefix = String::from(""); let mut suffix = String::from(""); let mut len = LEN; if let Some(s) = args.next() { let fp = eval(environment, s)?; if let Some(path) = get_file(environment, fp) { let p = path.as_path(); if p.exists() && p.is_dir() { dir = path; let (p, s, l) = get_temp_name_defaults(environment, args)?; params_done(args, fn_name)?; prefix = p; suffix = s; len = l; } else { let msg = format!( "{} unable to provide temporary file in provided directory", fn_name ); return Err(LispError::new(msg)); } } else { let msg = format!("{} unable to access provided file", fn_name); return Err(LispError::new(msg)); } } else { dir = temp_dir(); } let dir = get_temp_dir(&dir, &prefix, &suffix, len, fn_name)?; if let Some(path) = dir.to_str() { let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); Ok(path) } else { let msg = format!("{} unable to provide temporary directory", fn_name); Err(LispError::new(msg)) } } fn random_name(prefix: &str, suffix: &str, len: u64) -> String { let prefix = if prefix.is_empty() { ".tmp" } else { prefix }; let name = rand_alphanumeric_str(len); format!("{}{}{}", prefix, name, suffix) } fn get_temp_dir( path: &Path, prefix: &str, suffix: &str, len: u64, fn_name: &str, ) -> Result<PathBuf, LispError> { if path.exists() && path.is_dir() { let dir_name = random_name(prefix, suffix, len); let dir = Path::new::<OsStr>(dir_name.as_ref()); let dir = path.join(dir); fs::create_dir(dir.as_path()).map_err(|err| { let msg = format!("{} unable to create temporary directory inside default temporary directory ({:?}), reason: {:?}", fn_name, dir.as_path(), err); LispError::new(msg) })?; Ok(dir) } else { let msg = format!("{} unable to provide temporary directory", fn_name); Err(LispError::new(msg)) } } fn get_temp_name_defaults<'a>( environment: &'a mut Environment, args: &'a mut dyn Iterator<Item = Expression>, ) -> Result<(String, String, u64), LispError> { let mut prefix = String::from(""); let mut suffix = String::from(""); let mut len = LEN; if let Some(arg) = args.next() { let exp = eval(environment, arg)?; if let ExpEnum::String(s, _) = &exp.get().data { prefix = s.parse().unwrap_or_default(); if let Some(arg) = args.next() { let exp = eval(environment, arg)?; if let ExpEnum::String(s, _) = &exp.get().data { suffix = s.parse().unwrap_or_default(); if let Some(arg) = args.next() { let exp = eval(environment, arg)?; if let Ok(i) = exp.make_float(environment) { len = i as u64; }; }; }; }; }; }; Ok((prefix, suffix, len)) } fn builtin_with_temp_dir( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "with-temp"; let lambda_exp = param_eval(environment, args, fn_name)?; let lambda_exp_d = &lambda_exp.get().data; let (prefix, suffix, len) = get_temp_name_defaults(environment, args)?; params_done(args, fn_name)?; match lambda_exp_d { ExpEnum::Lambda(_) => { let p = &temp_dir(); let dir = get_temp_dir(p, &prefix, &suffix, len, fn_name)?; if let Some(path) = dir.as_path().to_str() { let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); let mut args = iter::once(path); let ret = call_lambda(environment, lambda_exp.copy(), &mut args, true); let _ = fs::remove_dir_all(dir.as_path()); ret } else { let msg = format!("{} unable to provide temporary directory", fn_name); Err(LispError::new(msg)) } } _ => { let msg = format!("{} first argument must be function", fn_name); Err(LispError::new(msg)) } } } fn get_temp( dir: PathBuf, prefix: &str, suffix: &str, len: u64, fn_name: &str, ) -> Result<PathBuf, LispError> { let filename = random_name(prefix, suffix, len); let p = Path::new::<OsStr>(filename.as_ref()); let file = dir.join(p); let p = file.as_path(); File::create(p).map_err(|err| { let msg = format!( "{} unable to create temporary file inside temporary directory ({:?}), reason: {:?}", fn_name, dir.as_path(), err ); LispError::new(msg) })?; Ok(file) } fn builtin_get_temp_file( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "get-temp-file"; let dir; let mut prefix = String::from(""); let mut suffix = String::from(""); let mut len = LEN; if let Some(s) = args.next() { let fp = eval(environment, s)?; if let Some(path) = get_file(environment, fp) { let p = path.as_path(); if p.exists() && p.is_dir() { dir = path; let (p, s, l) = get_temp_name_defaults(environment, args)?; params_done(args, fn_name)?; prefix = p; suffix = s; len = l; } else { let msg = format!( "{} unable to provide temporary file in provided directory", fn_name ); return Err(LispError::new(msg)); } } else { let msg = format!("{} unable to access provided file", fn_name); return Err(LispError::new(msg)); } } else { let p = &temp_dir(); dir = get_temp_dir(p, &prefix, &suffix, len, fn_name)?; } let file = get_temp(dir, &prefix, &suffix, len, fn_name)?; if let Some(path) = file.as_path().to_str() { let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); Ok(path) } else { let msg = format!("{} unable to provide temporary file", fn_name); Err(LispError::new(msg)) } } fn builtin_with_temp_file( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "with-temp-file"; let lambda_exp = param_eval(environment, args, fn_name)?; let lambda_exp_d = &lambda_exp.get().data; let (prefix, suffix, len) = get_temp_name_defaults(environment, args)?; params_done(args, fn_name)?; match lambda_exp_d { ExpEnum::Lambda(_) => { let p = &temp_dir(); let dir = get_temp_dir(p, &prefix, &suffix, len, fn_name)?; let file = get_temp(dir, &prefix, &suffix, len, fn_name)?; if let Some(path) = file.as_path().to_str() { let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); let mut args = iter::once(path); let ret = call_lambda(environment, lambda_exp.copy(), &mut args, true); let _ = fs::remove_file(file.as_path()); ret } else { let msg = format!("{} unable to provide temporary file", fn_name); Err(LispError::new(msg)) } } _ => { let msg = format!("{} first argument must be function", fn_name); Err(LispError::new(msg)) } } } fn builtin_temp_dir( _environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { let fn_name = "temp-dir"; params_done(args, fn_name)?; if let Some(path) = temp_dir().to_str() { let path = Expression::alloc_data(ExpEnum::String(path.to_string().into(), None)); Ok(path) } else { let msg = format!("{} unable to provide temporary directory", fn_name); Err(LispError::new(msg)) } } pub fn add_file_builtins<S: BuildHasher>( interner: &mut Interner, data: &mut HashMap<&'static str, (Expression, String), S>, ) { data.insert( interner.intern("cd"), Expression::make_function( builtin_cd, r#"Usage: (cd dir-to-change-to) Change directory. Section: file Example: (syscall 'mkdir "/tmp/tst-fs-cd") (syscall 'touch "/tmp/tst-fs-cd/fs-cd-marker") (test::assert-false (fs-exists? "fs-cd-marker")) (pushd "/tmp/tst-fs-cd") (root::cd "/tmp") (root::cd "/tmp/tst-fs-cd") (test::assert-true (fs-exists? "fs-cd-marker")) (syscall 'rm "/tmp/tst-fs-cd/fs-cd-marker") (popd) (syscall 'rmdir "/tmp/tst-fs-cd") "#, ), ); data.insert( interner.intern("fs-exists?"), Expression::make_function( builtin_path_exists, r#"Usage: (fs-exists? path-to-test) Does the given path exist? Section: file Example: $(mkdir /tmp/tst-fs-exists) $(touch /tmp/tst-fs-exists/fs-exists) (test::assert-true (fs-exists? "/tmp/tst-fs-exists/fs-exists")) (test::assert-true (fs-exists? "/tmp/tst-fs-exists")) (test::assert-false (fs-exists? "/tmp/tst-fs-exists/fs-exists-nope")) $(rm /tmp/tst-fs-exists/fs-exists) $(rmdir /tmp/tst-fs-exists) "#, ), ); data.insert( interner.intern("fs-file?"), Expression::make_function( builtin_is_file, r#"Usage: (fs-file? path-to-test) Is the given path a file? Section: file Example: $(mkdir /tmp/tst-fs-file) $(touch "/tmp/tst-fs-file/fs-file") (test::assert-true (fs-file? "/tmp/tst-fs-file/fs-file")) (test::assert-false (fs-file? "/tmp/tst-fs-file")) (test::assert-false (fs-file? "/tmp/tst-fs-file/fs-file-nope")) $(rm "/tmp/tst-fs-file/fs-file") $(rmdir /tmp/tst-fs-file) "#, ), ); data.insert( interner.intern("fs-dir?"), Expression::make_function( builtin_is_dir, r#"Usage: (fs-dir? path-to-test) Is the given path a directory? Section: file Example: $(mkdir /tmp/tst-fs-dir) $(touch /tmp/tst-fs-dir/fs-dir-file) (test::assert-false (fs-dir? "/tmp/tst-fs-dir/fs-dir-file")) (test::assert-true (fs-dir? "/tmp/tst-fs-dir")) (test::assert-false (fs-dir? "/tmp/tst-fs-dir/fs-dir-nope")) $(rm /tmp/tst-fs-dir/fs-dir-file) $(rmdir /tmp/tst-fs-dir) "#, ), ); data.insert( interner.intern("glob"), Expression::make_function( builtin_glob, r#"Usage: (glob /path/with/*) Takes a list/varargs of globs and return the list of them expanded. Section: file Example: (syscall 'mkdir "/tmp/tst-fs-glob") (syscall 'touch "/tmp/tst-fs-glob/g1") (syscall 'touch "/tmp/tst-fs-glob/g2") (syscall 'touch "/tmp/tst-fs-glob/g3") (test::assert-equal '("/tmp/tst-fs-glob/g1" "/tmp/tst-fs-glob/g2" "/tmp/tst-fs-glob/g3") (glob "/tmp/tst-fs-glob/*")) (syscall 'rm "/tmp/tst-fs-glob/g1") (syscall 'rm "/tmp/tst-fs-glob/g2") (syscall 'rm "/tmp/tst-fs-glob/g3") (syscall 'rmdir "/tmp/tst-fs-glob") "#, ), ); data.insert( interner.intern("fs-crawl"), Expression::make_function( builtin_fs_crawl, r#"Usage: (fs-crawl /path/to/file/or/dir (fn (x) (println "found path" x) [max-depth] [:follow-syms]) If a directory is provided the path is recursively searched and every file and directory is called as an argument to the provided function. If a file is provided the path is provided as an argument to the provided function. Takes two optional arguments (in any order) an integer, representing max depth to traverse if file is a directory, or the symbol, :follow-syms, to follow symbol links when traversing if desired. Section: file Example: (with-temp-file (fn (tmp-file) (def cnt 0) (fs-crawl tmp-file (fn (x) (test::assert-equal (fs-base tmp-file) (fs-base x)) (set! cnt (+ 1 cnt)))) (test::assert-equal 1 cnt))) (defn create-in (in-dir num-files visited) (dotimes-i i num-files (hash-set! visited (get-temp-file in-dir) nil))) (defn create-dir (tmp-dir visited) (let ((new-tmp (get-temp tmp-dir))) (hash-set! visited new-tmp nil) new-tmp)) (with-temp (fn (root-tmp-dir) (let ((tmp-file-count 5) (visited (make-hash))) (def cnt 0) (hash-set! visited root-tmp-dir nil) (create-in root-tmp-dir tmp-file-count visited) (let* ((tmp-dir (create-dir root-tmp-dir visited)) (new-files (create-in tmp-dir tmp-file-count visited)) (tmp-dir (create-dir tmp-dir visited)) (new-files (create-in tmp-dir tmp-file-count visited))) (fs-crawl root-tmp-dir (fn (x) (let ((file (hash-get visited x))) (test::assert-true (not file)) ;; also tests double counting (hash-set! visited x #t) (set! cnt (+ 1 cnt))))) (test::assert-equal (+ 3 (* 3 tmp-file-count)) cnt) (test::assert-equal (+ 3 (* 3 tmp-file-count)) (length (hash-keys visited))) (iterator::map (fn (x) (test::assert-true (hash-get visited y))) (hash-keys visited)))))) (with-temp (fn (root-tmp-dir) (let ((tmp-file-count 5) (visited (make-hash))) (def cnt 0) (hash-set! visited root-tmp-dir nil) (create-in root-tmp-dir tmp-file-count visited) (let* ((tmp-dir (create-dir root-tmp-dir visited)) (new-files (create-in tmp-dir tmp-file-count visited)) (tmp-dir (create-dir tmp-dir (make-hash))) (new-files (create-in tmp-dir tmp-file-count (make-hash)))) (fs-crawl root-tmp-dir (fn (x) (let ((file (hash-get visited x))) (test::assert-true (not file)) ;; also tests double counting (hash-set! visited x #t) (set! cnt (+ 1 cnt)))) 2) (test::assert-equal (+ 3 (* 2 tmp-file-count)) cnt) (test::assert-equal (+ 3 (* 2 tmp-file-count)) (length (hash-keys visited))) (iterator::map (fn (x) (test::assert-true (hash-get visited y))) (hash-keys visited)))))) (with-temp (fn (root-tmp-dir) (let ((tmp-file-count 5) (visited (make-hash))) (def cnt 0) (hash-set! visited root-tmp-dir nil) (create-in root-tmp-dir tmp-file-count visited) (let* ((tmp-dir (create-dir root-tmp-dir (make-hash))) (new-files (create-in tmp-dir tmp-file-count (make-hash))) (tmp-dir (create-dir tmp-dir (make-hash))) (new-files (create-in tmp-dir tmp-file-count (make-hash)))) (fs-crawl root-tmp-dir (fn (x) (let ((file (hash-get visited x))) (test::assert-true (not file)) ;; also tests double counting (hash-set! visited x #t) (set! cnt (+ 1 cnt)))) 1) (test::assert-equal (+ 2 tmp-file-count) cnt) (test::assert-equal (+ 2 tmp-file-count) (length (hash-keys visited))) (iterator::map (fn (x) (test::assert-true (hash-get visited y))) (hash-keys visited)))))) "#, ), ); data.insert( interner.intern("fs-same?"), Expression::make_function( builtin_same_file, r#"Usage: (fs-same? /path/to/file/or/dir /path/to/file/or/dir) Returns true if the two provided file paths refer to the same file or directory. Section: file Example: (with-temp-file (fn (tmp-file) (test::assert-true (fs-same? tmp-file tmp-file))) "#, ), ); data.insert( interner.intern("fs-base"), Expression::make_function( builtin_fs_base, r#"Usage: (fs-base /path/to/file/or/dir) Returns base name of file or directory passed to function. Section: file Example: (with-temp (fn (tmp) (let ((tmp-file (temp-file tmp))) (test::assert-equal (length \".tmp01234\") (length (fs-base tmp-file)))))) "#, ), ); data.insert( interner.intern("fs-parent"), Expression::make_function( builtin_fs_parent, r#"Usage: (fs-parent /path/to/file/or/dir) Returns base name of file or directory passed to function. Section: file Example: (with-temp (fn (tmp) (let ((tmp-file (get-temp-file tmp))) (test::assert-true (fs-same? (fs-parent tmp-file) tmp))))) "#, ), ); data.insert( interner.intern("fs-len"), Expression::make_function( builtin_fs_len, r#"Usage: (fs-len /path/to/file/or/dir) Returns the size of the file in bytes. Section: file Example: (with-temp-file (fn (tmp) (let ((tst-file (open tmp :create :truncate))) (write-line tst-file \"Test Line Read Line One\") (write-string tst-file \"Test Line Read Line Two\") (flush tst-file) (close tst-file) (println \"fs-len is: \" (fs-len tst-file)) (test::assert-equal 47 (fs-len tst-file))))) "#, ), ); data.insert( interner.intern("fs-modified"), Expression::make_function( builtin_fs_modified, r#"Usage: (fs-modified /path/to/file/or/dir) Returns the unix time file last modified in ms. Section: file Example: (with-temp-file (fn (tmp) (let ((tst-file (open tmp :create :truncate)) (last-mod (fs-modified tmp))) (write-line tst-file \"Test Line Read Line One\") (write-string tst-file \"Test Line Read Line Two\") (flush tst-file) (close tst-file) (test::assert-true (> (fs-modified tmp) last-mod))))) "#, ), ); data.insert( interner.intern("fs-accessed"), Expression::make_function( builtin_fs_accessed, r#"Usage: (fs-accessed /path/to/file/or/dir) Returns the unix time file last accessed in ms. Section: file Example: (with-temp-file (fn (tmp) (let ((tst-file (open tmp :read)) (last-acc (fs-accessed tmp))) (close tst-file) (let ((tst-file (open tmp :read))) (test::assert-true (> (fs-accessed tmp) last-acc)) (close tst-file)))) "#, ), ); data.insert( interner.intern("get-temp"), Expression::make_function( builtin_get_temp_dir, "Usage: (get-temp [\"/path/to/directory/to/use/as/base\" \"optional-prefix\" \"optional-suffix\" length]) Creates a directory inside of an OS specific temporary directory. See [temp-dir](root::temp-dir) for OS specific notes. Also accepts an optional prefix, an optional suffix, and an optional length for the random number of characters in the temporary file created. Defaults to prefix of \".tmp\", no suffix, and five random characters. Section: file Example: (test::assert-true (str-contains (temp-dir) (get-temp))) (with-temp (fn (tmp) (let ((tmp-dir (get-temp tmp))) (test::assert-true (str-contains tmp tmp-dir))))) (with-temp (fn (tmp) (let ((tmp-dir (get-temp tmp \"some-prefix\"))) (test::assert-true (str-contains tmp tmp-dir)) (test::assert-true (str-contains \"some-prefix\" tmp-dir))))) (with-temp (fn (tmp) (let ((tmp-dir (get-temp tmp \"some-prefix\" \"some-suffix\"))) (test::assert-true (str-contains tmp tmp-dir)) (test::assert-true (str-contains \"some-prefix\" tmp-dir)) (test::assert-true (str-contains \"some-suffix\" tmp-dir))))) (with-temp (fn (tmp) (let ((tmp-dir (get-temp tmp \"some-prefix\" \"some-suffix\" 6))) (test::assert-true (str-contains tmp tmp-dir)) (test::assert-true (str-contains \"some-prefix\" tmp-dir)) (test::assert-true (str-contains \"some-suffix\" tmp-dir)) (test::assert-equal (length \"some-prefix012345some-suffix\") (length (fs-base tmp-dir)))))) ", ), ); data.insert( interner.intern("get-temp-file"), Expression::make_function( builtin_get_temp_file, "Usage: (get-temp-file [\"/path/to/directory/to/use/as/base\" \"optional-prefix\" \"optional-suffix\" length]) Returns name of file created inside temporary directory. Optionally takes a directory to use as the parent directory of the temporary file. Also accepts an optional prefix, an optional suffix, and an optional length for the random number of characters in the temporary files created. Defaults to prefix of \".tmp\", no suffix, and five random characters. Section: file Example: (test::assert-true (str-contains (temp-dir) (get-temp-file))) (with-temp (fn (tmp) (let ((tmp-file (get-temp-file tmp))) (test::assert-true (str-contains tmp tmp-file))))) (with-temp (fn (tmp) (let ((tmp-file (get-temp-file tmp \"some-prefix\"))) (test::assert-true (str-contains \"some-prefix\" tmp-file))))) (with-temp (fn (tmp) (let ((tmp-file (get-temp-file tmp \"some-prefix\" \"some-suffix\"))) (test::assert-true (str-contains \"some-prefix\" tmp-file)) (test::assert-true (str-contains \"some-suffix\" tmp-file))))) (with-temp (fn (tmp) (let ((tmp-file (get-temp-file tmp \"some-prefix\" \"some-suffix\" 10))) (test::assert-true (str-contains \"some-prefix\" tmp-file)) (test::assert-true (str-contains \"some-suffix\" tmp-file)) (test::assert-equal (length \"some-prefix0123456789some-suffix\") (length (fs-base tmp-file)))))) ", ), ); data.insert( interner.intern("with-temp-file"), Expression::make_function( builtin_with_temp_file, "Usage: (with-temp-file (fn (x) (println \"given temp file:\" x)) [\"optional-prefix\" \"optional-suffix\" length]) Takes a function that accepts a temporary file. This file will be removed when the provided function is finished executing. Also accepts an optional prefix, an optional suffix, and an optional length for the random number of characters in the temporary file created. Defaults to prefix of \".tmp\", no suffix, and five random characters. Section: file Example: (def fp nil) (with-temp-file (fn (tmp-file) (let* ((a-file (open tmp-file :create :truncate))) (test::assert-true (fs-exists? tmp-file)) (set! fp tmp-file) (close a-file)))) (test::assert-false (nil? fp)) (test::assert-false (fs-exists? fp)) (with-temp-file (fn (tmp) (test::assert-true (str-contains \"some-prefix\" tmp))) \"some-prefix\") (with-temp-file (fn (tmp) (test::assert-true (str-contains \"some-prefix\" tmp)) (test::assert-true (str-contains \"some-suffix\" tmp))) \"some-prefix\" \"some-suffix\") (with-temp-file (fn (tmp) (test::assert-true (str-contains \"some-prefix\" tmp)) (test::assert-true (str-contains \"some-suffix\" tmp)) (test::assert-equal (length \"some-prefix0123456789some-suffix\") (length (fs-base tmp)))) \"some-prefix\" \"some-suffix\" 10) ", ), ); data.insert( interner.intern("with-temp"), Expression::make_function( builtin_with_temp_dir, "Usage: (with-temp (fn (x) (println \"given temp dir:\" x)) [\"optional-prefix\" \"optional-suffix\" length]) Takes a function that accepts a temporary directory. This directory will be recursively removed when the provided function is finished executing. Also accepts an optional prefix, an optional suffix, and an optional length for the random number of characters in the temporary directory created. Defaults to prefix of \".tmp\", no suffix, and five random characters. Section: file Example: (def fp nil) (with-temp (fn (tmp-dir) (let* ((tmp-file (str tmp-dir \"/sl-sh-tmp-file.txt\")) (a-file (open tmp-file :create :truncate))) (test::assert-true (fs-exists? tmp-file)) (set! fp tmp-file) (close a-file)))) (test::assert-false (nil? fp)) (test::assert-false (fs-exists? fp)) (with-temp (fn (tmp) (test::assert-true (str-contains \"some-prefix\" tmp))) \"some-prefix\") (with-temp (fn (tmp) (test::assert-true (str-contains \"some-prefix\" tmp)) (test::assert-true (str-contains \"some-suffix\" tmp))) \"some-prefix\" \"some-suffix\") (with-temp (fn (tmp) (test::assert-true (str-contains \"some-prefix\" tmp)) (test::assert-true (str-contains \"some-suffix\" tmp)) (test::assert-equal (length \"some-prefix0123456789some-suffix\") (length (fs-base tmp)))) \"some-prefix\" \"some-suffix\" 10) ", ), ); data.insert( interner.intern("temp-dir"), Expression::make_function( builtin_temp_dir, "Usage: (temp-dir) Returns a string representing the temporary directory. See [get-temp](root::get-temp) for higher level temporary directory creation mechanism. On Unix: Returns the value of the TMPDIR environment variable if it is set, otherwise for non-Android it returns /tmp. If Android, since there is no global temporary folder (it is usually allocated per-app), it returns /data/local/tmp. On Windows: Returns the value of, in order, the TMP, TEMP, USERPROFILE environment variable if any are set and not the empty string. Otherwise, temp_dir returns the path of the Windows directory. This behavior is identical to that of GetTempPath, which this function uses internally. Section: file Example: #t ", ), ); } // fix fs-notify to have default to-sleep
33.328671
158
0.550217
917176dc9ab58054c5d5be91f21d01d80f8d1386
33,346
//! A set of utilities to help with common use cases that are not required to //! fully use the library. #[cfg(all(feature = "client", feature = "cache"))] mod argument_convert; mod colour; mod custom_message; mod message_builder; #[cfg(all(feature = "client", feature = "cache"))] pub use argument_convert::*; use reqwest::Url; pub use self::{ colour::{colours, Colour}, custom_message::CustomMessage, message_builder::{Content, ContentModifier, EmbedMessageBuilding, MessageBuilder}, }; pub type Color = Colour; #[cfg(feature = "cache")] use std::str::FromStr; use std::{ collections::HashMap, ffi::OsStr, fs::File, hash::{BuildHasher, Hash}, io::Read, path::Path, }; #[cfg(feature = "cache")] use crate::cache::Cache; use crate::internal::prelude::*; #[cfg(feature = "cache")] use crate::model::channel::Channel; #[cfg(feature = "cache")] use crate::model::id::{ChannelId, GuildId, RoleId, UserId}; use crate::model::{id::EmojiId, misc::EmojiIdentifier}; /// Converts a HashMap into a final [`serde_json::Map`] representation. pub fn hashmap_to_json_map<H, T>(map: HashMap<T, Value, H>) -> Map<String, Value> where H: BuildHasher, T: Eq + Hash + ToString, { let mut json_map = Map::new(); for (key, value) in map { json_map.insert(key.to_string(), value); } json_map } /// Retrieves the "code" part of an invite out of a URL. /// /// # Examples /// /// Two formats of [invite][`RichInvite`] codes are supported, both regardless of protocol prefix. /// Some examples: /// /// 1. Retrieving the code from the URL `"https://discord.gg/0cDvIgU2voY8RSYL"`: /// /// ```rust /// use serenity::utils; /// /// let url = "https://discord.gg/0cDvIgU2voY8RSYL"; /// /// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL"); /// ``` /// /// 2. Retrieving the code from the URL `"http://discord.com/invite/0cDvIgU2voY8RSYL"`: /// /// ```rust /// use serenity::utils; /// /// let url = "http://discord.com/invite/0cDvIgU2voY8RSYL"; /// /// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL"); /// ``` /// /// [`RichInvite`]: crate::model::invite::RichInvite pub fn parse_invite(code: &str) -> &str { let code = code.trim_start_matches("http://").trim_start_matches("https://"); let lower = code.to_lowercase(); if lower.starts_with("discord.gg/") { &code[11..] } else if lower.starts_with("discord.com/invite/") { &code[19..] } else { code } } /// Retrieves an Id from a user mention. /// /// If the mention is invalid, then [`None`] is returned. /// /// # Examples /// /// Retrieving an Id from a valid [`User`] mention: /// /// ```rust /// use serenity::utils::parse_username; /// /// // regular username mention /// assert_eq!(parse_username("<@114941315417899012>"), Some(114941315417899012)); /// /// // nickname mention /// assert_eq!(parse_username("<@!114941315417899012>"), Some(114941315417899012)); /// ``` /// /// Asserting that an invalid username or nickname mention returns [`None`]: /// /// ```rust /// use serenity::utils::parse_username; /// /// assert!(parse_username("<@1149413154aa17899012").is_none()); /// assert!(parse_username("<@!11494131541789a90b1c2").is_none()); /// ``` /// /// [`User`]: crate::model::user::User pub fn parse_username(mention: impl AsRef<str>) -> Option<u64> { let mention = mention.as_ref(); if mention.len() < 4 { return None; } if mention.starts_with("<@!") { let len = mention.len() - 1; mention[3..len].parse::<u64>().ok() } else if mention.starts_with("<@") { let len = mention.len() - 1; mention[2..len].parse::<u64>().ok() } else { None } } /// Retrieves an Id from a role mention. /// /// If the mention is invalid, then [`None`] is returned. /// /// # Examples /// /// Retrieving an Id from a valid [`Role`] mention: /// /// ```rust /// use serenity::utils::parse_role; /// /// assert_eq!(parse_role("<@&136107769680887808>"), Some(136107769680887808)); /// ``` /// /// Asserting that an invalid role mention returns [`None`]: /// /// ```rust /// use serenity::utils::parse_role; /// /// assert!(parse_role("<@&136107769680887808").is_none()); /// ``` /// /// [`Role`]: crate::model::guild::Role pub fn parse_role(mention: impl AsRef<str>) -> Option<u64> { let mention = mention.as_ref(); if mention.len() < 4 { return None; } if mention.starts_with("<@&") && mention.ends_with('>') { let len = mention.len() - 1; mention[3..len].parse::<u64>().ok() } else { None } } /// Retrieves an Id from a channel mention. /// /// If the channel mention is invalid, then [`None`] is returned. /// /// # Examples /// /// Retrieving an Id from a valid [`Channel`] mention: /// /// ```rust /// use serenity::utils::parse_channel; /// /// assert_eq!(parse_channel("<#81384788765712384>"), Some(81384788765712384)); /// ``` /// /// Asserting that an invalid channel mention returns [`None`]: /// /// ```rust /// use serenity::utils::parse_channel; /// /// assert!(parse_channel("<#!81384788765712384>").is_none()); /// assert!(parse_channel("<#81384788765712384").is_none()); /// ``` /// /// [`Channel`]: crate::model::channel::Channel pub fn parse_channel(mention: impl AsRef<str>) -> Option<u64> { let mention = mention.as_ref(); if mention.len() < 4 { return None; } if mention.starts_with("<#") && mention.ends_with('>') { let len = mention.len() - 1; mention[2..len].parse::<u64>().ok() } else { None } } /// Retrieve the ID number out of a channel, role, or user mention. /// /// If the mention is invalid, [`None`] is returned. /// /// # Examples /// /// ```rust /// use serenity::utils::parse_mention; /// /// assert_eq!(parse_mention("<@136510335967297536>"), Some(136510335967297536)); /// assert_eq!(parse_mention("<@&137235212097683456>"), Some(137235212097683456)); /// assert_eq!(parse_mention("<#137234234728251392>"), Some(137234234728251392)); /// ``` pub fn parse_mention(mention: impl AsRef<str>) -> Option<u64> { let mention = mention.as_ref(); if mention.starts_with("<@&") { parse_role(mention) } else if mention.starts_with("<@") || mention.starts_with("<@!") { parse_username(mention) } else if mention.starts_with("<#") { parse_channel(mention) } else { None } } /// Retrieves the animated state, name and Id from an emoji mention, in the form of an /// [`EmojiIdentifier`]. /// /// If the emoji usage is invalid, then [`None`] is returned. /// /// # Examples /// /// Ensure that a valid [`Emoji`] usage is correctly parsed: /// /// ```rust /// use serenity::model::id::{EmojiId, GuildId}; /// use serenity::model::misc::EmojiIdentifier; /// use serenity::utils::parse_emoji; /// /// let expected = EmojiIdentifier { /// animated: false, /// id: EmojiId(302516740095606785), /// name: "smugAnimeFace".to_string(), /// }; /// /// assert_eq!(parse_emoji("<:smugAnimeFace:302516740095606785>").unwrap(), expected); /// ``` /// /// Asserting that an invalid emoji usage returns [`None`]: /// /// ```rust /// use serenity::utils::parse_emoji; /// /// assert!(parse_emoji("<:smugAnimeFace:302516740095606785").is_none()); /// ``` /// /// [`Emoji`]: crate::model::guild::Emoji pub fn parse_emoji(mention: impl AsRef<str>) -> Option<EmojiIdentifier> { let mention = mention.as_ref(); let len = mention.len(); if !(6..=56).contains(&len) { return None; } if (mention.starts_with("<:") || mention.starts_with("<a:")) && mention.ends_with('>') { let mut name = String::default(); let mut id = String::default(); let animated = &mention[1..3] == "a:"; let start = if animated { 3 } else { 2 }; for (i, x) in mention[start..].chars().enumerate() { if x == ':' { let from = i + start + 1; for y in mention[from..].chars() { if y == '>' { break; } else { id.push(y); } } break; } else { name.push(x); } } match id.parse::<u64>() { Ok(x) => Some(EmojiIdentifier { animated, name, id: EmojiId(x), }), _ => None, } } else { None } } /// Reads an image from a path and encodes it into base64. /// /// This can be used for methods like [`EditProfile::avatar`]. /// /// # Examples /// /// Reads an image located at `./cat.png` into a base64-encoded string: /// /// ```rust,no_run /// use serenity::utils; /// /// let image = utils::read_image("./cat.png").expect("Failed to read image"); /// ``` /// /// # Errors /// /// Returns an [`Error::Io`] if the path does not exist. /// /// [`EditProfile::avatar`]: crate::builder::EditProfile::avatar /// [`Error::Io`]: crate::error::Error::Io #[inline] pub fn read_image<P: AsRef<Path>>(path: P) -> Result<String> { _read_image(path.as_ref()) } fn _read_image(path: &Path) -> Result<String> { let mut v = Vec::default(); let mut f = File::open(path)?; // errors here are intentionally ignored #[allow(clippy::let_underscore_must_use)] let _ = f.read_to_end(&mut v); let b64 = base64::encode(&v); let ext = if path.extension() == Some(OsStr::new("png")) { "png" } else { "jpg" }; Ok(format!("data:image/{};base64,{}", ext, b64)) } /// Turns a string into a vector of string arguments, splitting by spaces, but /// parsing content within quotes as one individual argument. /// /// # Examples /// /// Parsing two quoted commands: /// /// ```rust /// use serenity::utils::parse_quotes; /// /// let command = r#""this is the first" "this is the second""#; /// let expected = vec!["this is the first".to_string(), "this is the second".to_string()]; /// /// assert_eq!(parse_quotes(command), expected); /// ``` /// /// ```rust /// use serenity::utils::parse_quotes; /// /// let command = r#""this is a quoted command that doesn't have an ending quotation"#; /// let expected = /// vec!["this is a quoted command that doesn't have an ending quotation".to_string()]; /// /// assert_eq!(parse_quotes(command), expected); /// ``` pub fn parse_quotes(s: impl AsRef<str>) -> Vec<String> { let s = s.as_ref(); let mut args = vec![]; let mut in_string = false; let mut escaping = false; let mut current_str = String::default(); for x in s.chars() { if in_string { if x == '\\' && !escaping { escaping = true; } else if x == '"' && !escaping { if !current_str.is_empty() { args.push(current_str); } current_str = String::default(); in_string = false; } else { current_str.push(x); escaping = false; } } else if x == ' ' { if !current_str.is_empty() { args.push(current_str.clone()); } current_str = String::default(); } else if x == '"' { if !current_str.is_empty() { args.push(current_str.clone()); } in_string = true; current_str = String::default(); } else { current_str.push(x); } } if !current_str.is_empty() { args.push(current_str); } args } /// Parses the id and token from a webhook url. Expects a [`reqwest::Url`] object rather than a [`&str`]. /// /// # Examples /// /// ```rust /// use serenity::utils; /// /// let url_str = "https://discord.com/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV"; /// let url = url_str.parse().unwrap(); /// let (id, token) = utils::parse_webhook(&url).unwrap(); /// /// assert_eq!(id, 245037420704169985); /// assert_eq!(token, "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV"); /// ``` pub fn parse_webhook(url: &Url) -> Option<(u64, &str)> { let path = url.path().strip_prefix("/api/webhooks/")?; let split_idx = path.find('/')?; let webhook_id = &path[..split_idx]; let token = &path[split_idx + 1..]; if !["http", "https"].contains(&url.scheme()) || !["discord.com", "discordapp.com"].contains(&url.domain()?) || !(17..=20).contains(&webhook_id.len()) || !(60..=68).contains(&token.len()) { return None; } Some((webhook_id.parse().ok()?, token)) } /// Calculates the Id of the shard responsible for a guild, given its Id and /// total number of shards used. /// /// # Examples /// /// Retrieve the Id of the shard for a guild with Id `81384788765712384`, using /// 17 shards: /// /// ```rust /// use serenity::utils; /// /// assert_eq!(utils::shard_id(81384788765712384 as u64, 17), 7); /// ``` #[inline] pub fn shard_id(guild_id: impl Into<u64>, shard_count: u64) -> u64 { (guild_id.into() >> 22) % shard_count } /// Struct that allows to alter [`content_safe`]'s behaviour. #[cfg(feature = "cache")] #[derive(Clone, Debug)] pub struct ContentSafeOptions { clean_role: bool, clean_user: bool, clean_channel: bool, clean_here: bool, clean_everyone: bool, show_discriminator: bool, guild_reference: Option<GuildId>, } #[cfg(feature = "cache")] impl ContentSafeOptions { pub fn new() -> Self { ContentSafeOptions::default() } /// [`content_safe`] will replace role mentions (`<@&{id}>`) with its name /// prefixed with `@` (`@rolename`) or with `@deleted-role` if the /// identifier is invalid. pub fn clean_role(mut self, b: bool) -> Self { self.clean_role = b; self } /// If set to true, [`content_safe`] will replace user mentions /// (`<@!{id}>` or `<@{id}>`) with the user's name prefixed with `@` /// (`@username`) or with `@invalid-user` if the identifier is invalid. pub fn clean_user(mut self, b: bool) -> Self { self.clean_user = b; self } /// If set to true, [`content_safe`] will replace channel mentions /// (`<#{id}>`) with the channel's name prefixed with `#` /// (`#channelname`) or with `#deleted-channel` if the identifier is /// invalid. pub fn clean_channel(mut self, b: bool) -> Self { self.clean_channel = b; self } /// If set to true, if [`content_safe`] replaces a user mention it will /// add their four digit discriminator with a preceeding `#`, /// turning `@username` to `@username#discriminator`. pub fn show_discriminator(mut self, b: bool) -> Self { self.show_discriminator = b; self } /// If set, [`content_safe`] will replace a user mention with the user's /// display name in passed `guild`. pub fn display_as_member_from<G: Into<GuildId>>(mut self, guild: G) -> Self { self.guild_reference = Some(guild.into()); self } /// If set, [`content_safe`] will replace `@here` with a non-pinging /// alternative. pub fn clean_here(mut self, b: bool) -> Self { self.clean_here = b; self } /// If set, [`content_safe`] will replace `@everyone` with a non-pinging /// alternative. pub fn clean_everyone(mut self, b: bool) -> Self { self.clean_everyone = b; self } } #[cfg(feature = "cache")] impl Default for ContentSafeOptions { /// Instantiates with all options set to `true`. fn default() -> Self { ContentSafeOptions { clean_role: true, clean_user: true, clean_channel: true, clean_here: true, clean_everyone: true, show_discriminator: true, guild_reference: None, } } } #[cfg(feature = "cache")] #[inline] async fn clean_roles(cache: impl AsRef<Cache>, s: &mut String) { let mut progress = 0; while let Some(mut mention_start) = s[progress..].find("<@&") { mention_start += progress; if let Some(mut mention_end) = s[mention_start..].find('>') { mention_end += mention_start; mention_start += "<@&".len(); if let Ok(id) = RoleId::from_str(&s[mention_start..mention_end]) { let to_replace = format!("<@&{}>", &s[mention_start..mention_end]); *s = if let Some(role) = id.to_role_cached(&cache).await { s.replace(&to_replace, &format!("@{}", &role.name)) } else { s.replace(&to_replace, "@deleted-role") }; } else { let id = &s[mention_start..mention_end].to_string(); if !id.is_empty() && id.as_bytes().iter().all(u8::is_ascii_digit) { let to_replace = format!("<@&{}>", id); *s = s.replace(&to_replace, "@deleted-role"); } else { progress = mention_end; } } } else { break; } } } #[cfg(feature = "cache")] #[inline] async fn clean_channels(cache: &impl AsRef<Cache>, s: &mut String) { let mut progress = 0; while let Some(mut mention_start) = s[progress..].find("<#") { mention_start += progress; if let Some(mut mention_end) = s[mention_start..].find('>') { mention_end += mention_start; mention_start += "<#".len(); if let Ok(id) = ChannelId::from_str(&s[mention_start..mention_end]) { let to_replace = format!("<#{}>", &s[mention_start..mention_end]); *s = if let Some(Channel::Guild(channel)) = id.to_channel_cached(&cache).await { let replacement = format!("#{}", &channel.name); s.replace(&to_replace, &replacement) } else { s.replace(&to_replace, "#deleted-channel") }; } else { let id = &s[mention_start..mention_end].to_string(); if !id.is_empty() && id.as_bytes().iter().all(u8::is_ascii_digit) { let to_replace = format!("<#{}>", id); *s = s.replace(&to_replace, "#deleted-channel"); } else { progress = mention_end; } } } else { break; } } } #[cfg(feature = "cache")] #[inline] async fn clean_users( cache: &impl AsRef<Cache>, s: &mut String, show_discriminator: bool, guild: Option<GuildId>, ) { let cache = cache.as_ref(); let mut progress = 0; while let Some(mut mention_start) = s[progress..].find("<@") { mention_start += progress; if let Some(mut mention_end) = s[mention_start..].find('>') { mention_end += mention_start; mention_start += "<@".len(); let has_exclamation = if s[mention_start..].as_bytes().get(0).map_or(false, |c| *c == b'!') { mention_start += "!".len(); true } else { false }; if let Ok(id) = UserId::from_str(&s[mention_start..mention_end]) { let replacement = if let Some(guild_id) = guild { if let Some(guild) = cache.guild(&guild_id).await { if let Some(member) = guild.members.get(&id) { if show_discriminator { format!("@{}", member.distinct()) } else { format!("@{}", member.display_name()) } } else { "@invalid-user".to_string() } } else { "@invalid-user".to_string() } } else if let Some(user) = cache.user(id).await { if show_discriminator { format!("@{}#{:04}", user.name, user.discriminator) } else { format!("@{}", user.name) } } else { "@invalid-user".to_string() }; let code_start = if has_exclamation { "<@!" } else { "<@" }; let to_replace = format!("{}{}>", code_start, &s[mention_start..mention_end]); *s = s.replace(&to_replace, &replacement) } else { let id = &s[mention_start..mention_end].to_string(); if !id.is_empty() && id.as_bytes().iter().all(u8::is_ascii_digit) { let code_start = if has_exclamation { "<@!" } else { "<@" }; let to_replace = format!("{}{}>", code_start, id); *s = s.replace(&to_replace, "@invalid-user"); } else { progress = mention_end; } } } else { break; } } } /// Transforms role, channel, user, `@everyone` and `@here` mentions /// into raw text by using the [`Cache`] only. /// /// [`ContentSafeOptions`] decides what kind of mentions should be filtered /// and how the raw-text will be displayed. /// /// # Examples /// /// Sanitise an `@everyone` mention. /// /// ```rust /// # use std::sync::Arc; /// # use serenity::client::Cache; /// # use tokio::sync::RwLock; /// # /// # async fn run() { /// # let cache = Cache::default(); /// use serenity::utils::{content_safe, ContentSafeOptions}; /// /// let with_mention = "@everyone"; /// let without_mention = content_safe(&cache, &with_mention, &ContentSafeOptions::default()).await; /// /// assert_eq!("@\u{200B}everyone".to_string(), without_mention); /// # } /// ``` /// /// [`Cache`]: crate::cache::Cache #[cfg(feature = "cache")] pub async fn content_safe( cache: impl AsRef<Cache>, s: impl AsRef<str>, options: &ContentSafeOptions, ) -> String { let mut content = s.as_ref().to_string(); if options.clean_role { clean_roles(&cache, &mut content).await; } if options.clean_channel { clean_channels(&cache, &mut content).await; } if options.clean_user { clean_users(&cache, &mut content, options.show_discriminator, options.guild_reference) .await; } if options.clean_here { content = content.replace("@here", "@\u{200B}here"); } if options.clean_everyone { content = content.replace("@everyone", "@\u{200B}everyone"); } content } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::non_ascii_literal)] mod test { use super::*; #[cfg(feature = "cache")] use crate::cache::Cache; #[test] fn test_invite_parser() { assert_eq!(parse_invite("https://discord.gg/abc"), "abc"); assert_eq!(parse_invite("http://discord.gg/abc"), "abc"); assert_eq!(parse_invite("discord.gg/abc"), "abc"); assert_eq!(parse_invite("DISCORD.GG/ABC"), "ABC"); assert_eq!(parse_invite("https://discord.com/invite/abc"), "abc"); assert_eq!(parse_invite("http://discord.com/invite/abc"), "abc"); assert_eq!(parse_invite("discord.com/invite/abc"), "abc"); } #[test] fn test_username_parser() { assert_eq!(parse_username("<@12345>").unwrap(), 12_345); assert_eq!(parse_username("<@!12345>").unwrap(), 12_345); } #[test] fn role_parser() { assert_eq!(parse_role("<@&12345>").unwrap(), 12_345); } #[test] fn test_channel_parser() { assert_eq!(parse_channel("<#12345>").unwrap(), 12_345); } #[test] fn test_emoji_parser() { let emoji = parse_emoji("<:name:12345>").unwrap(); assert_eq!(emoji.name, "name"); assert_eq!(emoji.id, 12_345); } #[test] fn test_quote_parser() { let parsed = parse_quotes("a \"b c\" d\"e f\" g"); assert_eq!(parsed, ["a", "b c", "d", "e f", "g"]); } #[test] fn test_webhook_parser() { let url = "https://discord.com/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV".parse().unwrap(); let (id, token) = parse_webhook(&url).unwrap(); assert_eq!(id, 245037420704169985); assert_eq!(token, "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV"); } #[cfg(feature = "cache")] #[tokio::test] async fn test_content_safe() { use std::{collections::HashMap, sync::Arc}; use chrono::{DateTime, Utc}; use crate::model::{prelude::*, user::User, Permissions}; let user = User { id: UserId(100000000000000000), avatar: None, bot: false, discriminator: 0000, name: "Crab".to_string(), public_flags: None, banner: None, accent_colour: None, }; #[allow(deprecated)] let mut guild = Guild { afk_channel_id: None, afk_timeout: 0, application_id: None, channels: HashMap::new(), default_message_notifications: DefaultMessageNotificationLevel::All, emojis: HashMap::new(), explicit_content_filter: ExplicitContentFilter::None, features: Vec::new(), icon: None, id: GuildId(381880193251409931), joined_at: DateTime::parse_from_str( "1983 Apr 13 12:09:14.274 +0000", "%Y %b %d %H:%M:%S%.3f %z", ) .unwrap() .with_timezone(&Utc), large: false, member_count: 1, members: HashMap::new(), mfa_level: MfaLevel::None, name: "serenity".to_string(), owner_id: UserId(114941315417899012), presences: HashMap::new(), region: "Ferris Island".to_string(), roles: HashMap::new(), splash: None, discovery_splash: None, system_channel_id: None, system_channel_flags: Default::default(), rules_channel_id: None, public_updates_channel_id: None, verification_level: VerificationLevel::None, voice_states: HashMap::new(), description: None, premium_tier: PremiumTier::Tier0, premium_subscription_count: 0, banner: None, vanity_url_code: Some("bruhmoment1".to_string()), preferred_locale: "en-US".to_string(), welcome_screen: None, approximate_member_count: None, approximate_presence_count: None, nsfw: false, nsfw_level: NsfwLevel::Default, max_video_channel_users: None, max_presences: None, max_members: None, widget_enabled: Some(false), widget_channel_id: None, stage_instances: vec![], threads: vec![], }; let member = Member { deaf: false, guild_id: guild.id, joined_at: None, mute: false, nick: Some("Ferris".to_string()), roles: Vec::new(), user: user.clone(), pending: false, premium_since: None, #[cfg(feature = "unstable_discord_api")] permissions: None, avatar: None, communication_disabled_until: None, }; let role = Role { id: RoleId(333333333333333333), colour: Colour::ORANGE, guild_id: guild.id, hoist: true, managed: false, mentionable: true, name: "ferris-club-member".to_string(), permissions: Permissions::all(), position: 0, tags: RoleTags::default(), }; let channel = GuildChannel { id: ChannelId(111880193700067777), bitrate: None, category_id: None, guild_id: guild.id, kind: ChannelType::Text, last_message_id: None, last_pin_timestamp: None, name: "general".to_string(), permission_overwrites: Vec::new(), position: 0, topic: None, user_limit: None, nsfw: false, slow_mode_rate: Some(0), rtc_region: None, video_quality_mode: None, message_count: None, member_count: None, thread_metadata: None, member: None, default_auto_archive_duration: None, }; let cache = Arc::new(Cache::default()); guild.members.insert(user.id, member.clone()); guild.roles.insert(role.id, role.clone()); cache.users.write().await.insert(user.id, user.clone()); cache.guilds.write().await.insert(guild.id, guild.clone()); cache.channels.write().await.insert(channel.id, channel.clone()); let with_user_mentions = "<@!100000000000000000> <@!000000000000000000> <@123> <@!123> \ <@!123123123123123123123> <@123> <@123123123123123123> <@!invalid> \ <@invalid> <@日本語 한국어$§)[/__#\\(/&2032$§#> \ <@!i)/==(<<>z/9080)> <@!1231invalid> <@invalid123> \ <@123invalid> <@> <@ "; let without_user_mentions = "@Crab#0000 @invalid-user @invalid-user @invalid-user \ @invalid-user @invalid-user @invalid-user <@!invalid> \ <@invalid> <@日本語 한국어$§)[/__#\\(/&2032$§#> \ <@!i)/==(<<>z/9080)> <@!1231invalid> <@invalid123> \ <@123invalid> <@> <@ "; // User mentions let options = ContentSafeOptions::default(); assert_eq!(without_user_mentions, content_safe(&cache, with_user_mentions, &options).await); let options = ContentSafeOptions::default(); assert_eq!( format!("@{}#{:04}", user.name, user.discriminator), content_safe(&cache, "<@!100000000000000000>", &options).await ); let options = ContentSafeOptions::default(); assert_eq!( format!("@{}#{:04}", user.name, user.discriminator), content_safe(&cache, "<@100000000000000000>", &options).await ); let options = options.show_discriminator(false); assert_eq!( format!("@{}", user.name), content_safe(&cache, "<@!100000000000000000>", &options).await ); let options = options.show_discriminator(false); assert_eq!( format!("@{}", user.name), content_safe(&cache, "<@100000000000000000>", &options).await ); let options = options.display_as_member_from(guild.id); assert_eq!( format!("@{}", member.nick.unwrap()), content_safe(&cache, "<@!100000000000000000>", &options).await ); let options = options.clean_user(false); assert_eq!(with_user_mentions, content_safe(&cache, with_user_mentions, &options).await); // Channel mentions let with_channel_mentions = "<#> <#deleted-channel> #deleted-channel <#0> \ #unsafe-club <#111880193700067777> <#ferrisferrisferris> \ <#000000000000000000>"; let without_channel_mentions = "<#> <#deleted-channel> #deleted-channel \ #deleted-channel #unsafe-club #general <#ferrisferrisferris> \ #deleted-channel"; assert_eq!( without_channel_mentions, content_safe(&cache, with_channel_mentions, &options).await ); let options = options.clean_channel(false); assert_eq!( with_channel_mentions, content_safe(&cache, with_channel_mentions, &options).await ); // Role mentions let with_role_mentions = "<@&> @deleted-role <@&9829> \ <@&333333333333333333> <@&000000000000000000>"; let without_role_mentions = "<@&> @deleted-role @deleted-role \ @ferris-club-member @deleted-role"; assert_eq!(without_role_mentions, content_safe(&cache, with_role_mentions, &options).await); let options = options.clean_role(false); assert_eq!(with_role_mentions, content_safe(&cache, with_role_mentions, &options).await); // Everyone mentions let with_everyone_mention = "@everyone"; let without_everyone_mention = "@\u{200B}everyone"; assert_eq!( without_everyone_mention, content_safe(&cache, with_everyone_mention, &options).await ); let options = options.clean_everyone(false); assert_eq!( with_everyone_mention, content_safe(&cache, with_everyone_mention, &options).await ); // Here mentions let with_here_mention = "@here"; let without_here_mention = "@\u{200B}here"; assert_eq!(without_here_mention, content_safe(&cache, with_here_mention, &options).await); let options = options.clean_here(false); assert_eq!(with_here_mention, content_safe(&cache, with_here_mention, &options).await); } }
30.677093
158
0.558838
f40c508a035e8f71fa4fdd69d5457dfbecaec886
22,401
use crate::{AlertLocation, CarID, Event, ParkingSpot, TripID, TripMode, TripPhaseType}; use abstutil::Counter; use geom::{Distance, Duration, Histogram, Time}; use map_model::{ BusRouteID, BusStopID, IntersectionID, LaneID, Map, ParkingLotID, Path, PathRequest, RoadID, Traversable, TurnGroupID, }; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, VecDeque}; #[derive(Clone, Serialize, Deserialize)] pub struct Analytics { pub road_thruput: TimeSeriesCount<RoadID>, pub intersection_thruput: TimeSeriesCount<IntersectionID>, // Unlike everything else in Analytics, this is just for a moment in time. pub demand: BTreeMap<TurnGroupID, usize>, pub bus_arrivals: Vec<(Time, CarID, BusRouteID, BusStopID)>, pub bus_passengers_waiting: Vec<(Time, BusStopID, BusRouteID)>, pub started_trips: BTreeMap<TripID, Time>, // TODO Hack: No TripMode means aborted // Finish time, ID, mode (or None as aborted), trip duration pub finished_trips: Vec<(Time, TripID, Option<TripMode>, Duration)>, // TODO This subsumes finished_trips pub trip_log: Vec<(Time, TripID, Option<PathRequest>, TripPhaseType)>, pub intersection_delays: BTreeMap<IntersectionID, Vec<(Time, Duration, TripMode)>>, // Per parking lane or lot, when does a spot become filled (true) or free (false) pub parking_lane_changes: BTreeMap<LaneID, Vec<(Time, bool)>>, pub parking_lot_changes: BTreeMap<ParkingLotID, Vec<(Time, bool)>>, pub(crate) alerts: Vec<(Time, AlertLocation, String)>, // After we restore from a savestate, don't record anything. This is only going to make sense // if savestates are only used for quickly previewing against prebaked results, where we have // the full Analytics anyway. record_anything: bool, } impl Analytics { pub fn new() -> Analytics { Analytics { road_thruput: TimeSeriesCount::new(), intersection_thruput: TimeSeriesCount::new(), demand: BTreeMap::new(), bus_arrivals: Vec::new(), bus_passengers_waiting: Vec::new(), started_trips: BTreeMap::new(), finished_trips: Vec::new(), trip_log: Vec::new(), intersection_delays: BTreeMap::new(), parking_lane_changes: BTreeMap::new(), parking_lot_changes: BTreeMap::new(), alerts: Vec::new(), record_anything: true, } } pub fn event(&mut self, ev: Event, time: Time, map: &Map) { if !self.record_anything { return; } // Throughput if let Event::AgentEntersTraversable(a, to) = ev { let mode = TripMode::from_agent(a); match to { Traversable::Lane(l) => { self.road_thruput.record(time, map.get_l(l).parent, mode); } Traversable::Turn(t) => { self.intersection_thruput.record(time, t.parent, mode); if let Some(id) = map.get_turn_group(t) { *self.demand.entry(id).or_insert(0) -= 1; } } }; } match ev { Event::PersonLeavesMap(_, mode, i, _) | Event::PersonEntersMap(_, mode, i, _) => { self.intersection_thruput.record(time, i, mode); } _ => {} } // Bus arrivals if let Event::BusArrivedAtStop(bus, route, stop) = ev { self.bus_arrivals.push((time, bus, route, stop)); } // Bus passengers if let Event::TripPhaseStarting(_, _, _, ref tpt) = ev { if let TripPhaseType::WaitingForBus(route, stop) = tpt { self.bus_passengers_waiting.push((time, *stop, *route)); } } // Started trips if let Event::TripPhaseStarting(id, _, _, _) = ev { self.started_trips.entry(id).or_insert(time); } // Finished trips if let Event::TripFinished { trip, mode, total_time, .. } = ev { self.finished_trips .push((time, trip, Some(mode), total_time)); } else if let Event::TripAborted(id) = ev { self.started_trips.entry(id).or_insert(time); self.finished_trips.push((time, id, None, Duration::ZERO)); } // Intersection delays if let Event::IntersectionDelayMeasured(id, delay, mode) = ev { self.intersection_delays .entry(id) .or_insert_with(Vec::new) .push((time, delay, mode)); } // Parking spot changes if let Event::CarReachedParkingSpot(_, spot) = ev { if let ParkingSpot::Onstreet(l, _) = spot { self.parking_lane_changes .entry(l) .or_insert_with(Vec::new) .push((time, true)); } else if let ParkingSpot::Lot(pl, _) = spot { self.parking_lot_changes .entry(pl) .or_insert_with(Vec::new) .push((time, true)); } } if let Event::CarLeftParkingSpot(_, spot) = ev { if let ParkingSpot::Onstreet(l, _) = spot { self.parking_lane_changes .entry(l) .or_insert_with(Vec::new) .push((time, false)); } else if let ParkingSpot::Lot(pl, _) = spot { self.parking_lot_changes .entry(pl) .or_insert_with(Vec::new) .push((time, false)); } } // TODO Kinda hacky, but these all consume the event, so kinda bundle em. match ev { Event::TripPhaseStarting(id, _, maybe_req, phase_type) => { self.trip_log.push((time, id, maybe_req, phase_type)); } Event::TripAborted(id) => { self.trip_log.push((time, id, None, TripPhaseType::Aborted)); } Event::TripFinished { trip, .. } => { self.trip_log .push((time, trip, None, TripPhaseType::Finished)); } Event::PathAmended(path) => { self.record_demand(&path, map); } Event::Alert(loc, msg) => { self.alerts.push((time, loc, msg)); } _ => {} } } pub fn record_demand(&mut self, path: &Path, map: &Map) { for step in path.get_steps() { if let Traversable::Turn(t) = step.as_traversable() { if let Some(id) = map.get_turn_group(t) { *self.demand.entry(id).or_insert(0) += 1; } } } } // TODO If these ever need to be speeded up, just cache the histogram and index in the events // list. // Ignores the current time. Returns None for aborted trips. pub fn finished_trip_time(&self, trip: TripID) -> Option<Duration> { // TODO This is so inefficient! for (_, id, maybe_mode, dt) in &self.finished_trips { if *id == trip { if maybe_mode.is_some() { return Some(*dt); } else { return None; } } } None } // Returns pairs of trip times for finished trips in both worlds. (before, after, mode) pub fn both_finished_trips( &self, now: Time, before: &Analytics, ) -> Vec<(Duration, Duration, TripMode)> { let mut a = BTreeMap::new(); for (t, id, maybe_mode, dt) in &self.finished_trips { if *t > now { break; } if maybe_mode.is_some() { a.insert(*id, *dt); } } let mut results = Vec::new(); for (t, id, maybe_mode, dt) in &before.finished_trips { if *t > now { break; } if let Some(mode) = maybe_mode { if let Some(dt1) = a.remove(id) { results.push((*dt, dt1, *mode)); } } } results } // Find intersections where the cumulative sum of delay has changed. Negative means faster. pub fn compare_delay(&self, now: Time, before: &Analytics) -> Vec<(IntersectionID, Duration)> { let mut results = Vec::new(); for (i, list1) in &self.intersection_delays { if let Some(list2) = before.intersection_delays.get(i) { let mut sum1 = Duration::ZERO; for (t, dt, _) in list1 { if *t > now { break; } sum1 += *dt; } let mut sum2 = Duration::ZERO; for (t, dt, _) in list2 { if *t > now { break; } sum2 += *dt; } if sum1 != sum2 { results.push((*i, sum1 - sum2)); } } } results } pub fn bus_arrivals( &self, now: Time, r: BusRouteID, ) -> BTreeMap<BusStopID, Histogram<Duration>> { let mut per_bus: BTreeMap<CarID, Vec<(Time, BusStopID)>> = BTreeMap::new(); for (t, car, route, stop) in &self.bus_arrivals { if *t > now { break; } if *route == r { per_bus .entry(*car) .or_insert_with(Vec::new) .push((*t, *stop)); } } let mut delay_to_stop: BTreeMap<BusStopID, Histogram<Duration>> = BTreeMap::new(); for events in per_bus.values() { for pair in events.windows(2) { delay_to_stop .entry(pair[1].1) .or_insert_with(Histogram::new) .add(pair[1].0 - pair[0].0); } } delay_to_stop } // TODO Refactor! // For each stop, a list of (time, delay) pub fn bus_arrivals_over_time( &self, now: Time, r: BusRouteID, ) -> BTreeMap<BusStopID, Vec<(Time, Duration)>> { let mut per_bus: BTreeMap<CarID, Vec<(Time, BusStopID)>> = BTreeMap::new(); for (t, car, route, stop) in &self.bus_arrivals { if *t > now { break; } if *route == r { per_bus .entry(*car) .or_insert_with(Vec::new) .push((*t, *stop)); } } let mut delays_to_stop: BTreeMap<BusStopID, Vec<(Time, Duration)>> = BTreeMap::new(); for events in per_bus.values() { for pair in events.windows(2) { delays_to_stop .entry(pair[1].1) .or_insert_with(Vec::new) .push((pair[1].0, pair[1].0 - pair[0].0)); } } delays_to_stop } // At some moment in time, what's the distribution of passengers waiting for a route like? pub fn bus_passenger_delays( &self, now: Time, r: BusRouteID, ) -> BTreeMap<BusStopID, Histogram<Duration>> { let mut waiting_per_stop = BTreeMap::new(); for (t, stop, route) in &self.bus_passengers_waiting { if *t > now { break; } if *route == r { waiting_per_stop .entry(*stop) .or_insert_with(Vec::new) .push(*t); } } for (t, _, route, stop) in &self.bus_arrivals { if *t > now { break; } if *route == r { if let Some(ref mut times) = waiting_per_stop.get_mut(stop) { times.retain(|time| *time > *t); } } } waiting_per_stop .into_iter() .filter_map(|(k, v)| { let mut delays = Histogram::new(); for t in v { delays.add(now - t); } if delays.count() == 0 { None } else { Some((k, delays)) } }) .collect() } pub fn get_trip_phases(&self, trip: TripID, map: &Map) -> Vec<TripPhase> { let mut phases: Vec<TripPhase> = Vec::new(); for (t, id, maybe_req, phase_type) in &self.trip_log { if *id != trip { continue; } if let Some(ref mut last) = phases.last_mut() { last.end_time = Some(*t); } if *phase_type == TripPhaseType::Finished || *phase_type == TripPhaseType::Aborted { break; } phases.push(TripPhase { start_time: *t, end_time: None, // Unwrap should be safe, because this is the request that was actually done... // TODO Not if this is prebaked data and we've made edits. Woops. path: maybe_req.as_ref().and_then(|req| { map.pathfind(req.clone()) .map(|path| (req.start.dist_along(), path)) }), has_path_req: maybe_req.is_some(), phase_type: *phase_type, }) } phases } pub fn get_all_trip_phases(&self) -> BTreeMap<TripID, Vec<TripPhase>> { let mut trips = BTreeMap::new(); for (t, id, maybe_req, phase_type) in &self.trip_log { let phases: &mut Vec<TripPhase> = trips.entry(*id).or_insert_with(Vec::new); if let Some(ref mut last) = phases.last_mut() { last.end_time = Some(*t); } if *phase_type == TripPhaseType::Finished { continue; } // Remove aborted trips if *phase_type == TripPhaseType::Aborted { trips.remove(id); continue; } phases.push(TripPhase { start_time: *t, end_time: None, // Don't compute any paths path: None, has_path_req: maybe_req.is_some(), phase_type: *phase_type, }) } trips } pub fn active_agents(&self, now: Time) -> Vec<(Time, usize)> { let mut starts_stops: Vec<(Time, bool)> = Vec::new(); for t in self.started_trips.values() { if *t <= now { starts_stops.push((*t, false)); } } for (t, _, _, _) in &self.finished_trips { if *t > now { break; } starts_stops.push((*t, true)); } // Make sure the start events get sorted before the stops. starts_stops.sort(); let mut pts = Vec::new(); let mut cnt = 0; let mut last_t = Time::START_OF_DAY; for (t, ended) in starts_stops { if t != last_t { // Step functions. Don't interpolate. pts.push((last_t, cnt)); } last_t = t; if ended { // release mode disables this check, so... if cnt == 0 { panic!("active_agents at {} has more ended trips than started", t); } cnt -= 1; } else { cnt += 1; } } pts.push((last_t, cnt)); if last_t != now { pts.push((now, cnt)); } pts } // Returns the free spots over time pub fn parking_lane_availability( &self, now: Time, l: LaneID, capacity: usize, ) -> Vec<(Time, usize)> { if let Some(changes) = self.parking_lane_changes.get(&l) { Analytics::parking_spot_availability(now, changes, capacity) } else { vec![(Time::START_OF_DAY, capacity), (now, capacity)] } } pub fn parking_lot_availability( &self, now: Time, pl: ParkingLotID, capacity: usize, ) -> Vec<(Time, usize)> { if let Some(changes) = self.parking_lot_changes.get(&pl) { Analytics::parking_spot_availability(now, changes, capacity) } else { vec![(Time::START_OF_DAY, capacity), (now, capacity)] } } fn parking_spot_availability( now: Time, changes: &Vec<(Time, bool)>, capacity: usize, ) -> Vec<(Time, usize)> { let mut pts = Vec::new(); let mut cnt = capacity; let mut last_t = Time::START_OF_DAY; for (t, filled) in changes { if *t > now { break; } if *t != last_t { // Step functions. Don't interpolate. pts.push((last_t, cnt)); } last_t = *t; if *filled { if cnt == 0 { panic!("parking_spot_availability at {} went below 0", t); } cnt -= 1; } else { cnt += 1; } } pts.push((last_t, cnt)); if last_t != now { pts.push((now, cnt)); } pts } } impl Default for Analytics { fn default() -> Analytics { let mut a = Analytics::new(); a.record_anything = false; a } } #[derive(Debug)] pub struct TripPhase { pub start_time: Time, pub end_time: Option<Time>, // Plumb along start distance pub path: Option<(Distance, Path)>, pub has_path_req: bool, pub phase_type: TripPhaseType, } // Slightly misleading -- TripMode::Transit means buses, not pedestrians taking transit #[derive(Clone, Serialize, Deserialize)] pub struct TimeSeriesCount<X: Ord + Clone> { // (Road or intersection, mode, hour block) -> count for that hour pub counts: BTreeMap<(X, TripMode, usize), usize>, // Very expensive to store, so it's optional. But useful to flag on to experiment with // representations better than the hour count above. pub raw: Vec<(Time, TripMode, X)>, } impl<X: Ord + Clone> TimeSeriesCount<X> { fn new() -> TimeSeriesCount<X> { TimeSeriesCount { counts: BTreeMap::new(), raw: Vec::new(), } } fn record(&mut self, time: Time, id: X, mode: TripMode) { // TODO Manually change flag if false { self.raw.push((time, mode, id.clone())); } let hour = time.get_parts().0; *self.counts.entry((id, mode, hour)).or_insert(0) += 1; } pub fn total_for(&self, id: X) -> usize { let mut cnt = 0; for mode in TripMode::all() { // TODO Hmm for hour in 0..24 { cnt += self .counts .get(&(id.clone(), mode, hour)) .cloned() .unwrap_or(0); } } cnt } pub fn all_total_counts(&self) -> Counter<X> { let mut cnt = Counter::new(); for ((id, _, _), value) in &self.counts { cnt.add(id.clone(), *value); } cnt } pub fn count_per_hour(&self, id: X, time: Time) -> Vec<(TripMode, Vec<(Time, usize)>)> { let hour = time.get_hours(); let mut results = Vec::new(); for mode in TripMode::all() { let mut pts = Vec::new(); for hour in 0..=hour { let cnt = self .counts .get(&(id.clone(), mode, hour)) .cloned() .unwrap_or(0); pts.push((Time::START_OF_DAY + Duration::hours(hour), cnt)); pts.push((Time::START_OF_DAY + Duration::hours(hour + 1), cnt)); } pts.pop(); results.push((mode, pts)); } results } pub fn raw_throughput(&self, now: Time, id: X) -> Vec<(TripMode, Vec<(Time, usize)>)> { let window_size = Duration::hours(1); let mut pts_per_mode: BTreeMap<TripMode, Vec<(Time, usize)>> = BTreeMap::new(); let mut windows_per_mode: BTreeMap<TripMode, Window> = BTreeMap::new(); for mode in TripMode::all() { pts_per_mode.insert(mode, vec![(Time::START_OF_DAY, 0)]); windows_per_mode.insert(mode, Window::new(window_size)); } for (t, m, x) in &self.raw { if *x != id { continue; } if *t > now { break; } let count = windows_per_mode.get_mut(m).unwrap().add(*t); pts_per_mode.get_mut(m).unwrap().push((*t, count)); } for (m, pts) in pts_per_mode.iter_mut() { let mut window = windows_per_mode.remove(m).unwrap(); // Add a drop-off after window_size (+ a little epsilon!) let t = (pts.last().unwrap().0 + window_size + Duration::seconds(0.1)).min(now); if pts.last().unwrap().0 != t { pts.push((t, window.count(t))); } if pts.last().unwrap().0 != now { pts.push((now, window.count(now))); } } pts_per_mode.into_iter().collect() } } struct Window { times: VecDeque<Time>, window_size: Duration, } impl Window { fn new(window_size: Duration) -> Window { Window { times: VecDeque::new(), window_size, } } // Returns the count at time fn add(&mut self, time: Time) -> usize { self.times.push_back(time); self.count(time) } // Grab the count at this time, but don't add a new time fn count(&mut self, end: Time) -> usize { while !self.times.is_empty() && end - *self.times.front().unwrap() > self.window_size { self.times.pop_front(); } self.times.len() } }
32.846041
99
0.487746
8a5d79214fd0dc09a4dcbad55d5ca42c5ec06e1a
6,161
//! `serde::Serialize` and `serde::Deserialize` implementations for `Automaton`. //! //! Rather than prefix each serialized field with which field it is, we always //! serialize fields in alphabetical order. Make sure to maintain this if you //! add or remove fields! //! //! Each time you add/remove a field, or change serialization in any other way, //! make sure to bump `SERIALIZATION_VERSION`. use crate::{Automaton, Output, State}; use serde::{ de::{self, Deserializer, SeqAccess, Visitor}, ser::SerializeTupleStruct, Deserialize, Serialize, Serializer, }; use std::collections::BTreeMap; use std::fmt; use std::hash::Hash; use std::marker::PhantomData; const SERIALIZATION_VERSION: u32 = 1; impl Serialize for State { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u32(self.0) } } impl<'de> Deserialize<'de> for State { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { Ok(State(deserializer.deserialize_u32(U32Visitor)?)) } } struct U32Visitor; impl<'de> Visitor<'de> for U32Visitor { type Value = u32; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("an integer between `0` and `2^32 - 1`") } fn visit_u8<E>(self, value: u8) -> Result<Self::Value, E> where E: de::Error, { Ok(u32::from(value)) } fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E> where E: de::Error, { Ok(value) } fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> where E: de::Error, { use std::u32; if value <= u64::from(u32::MAX) { Ok(value as u32) } else { Err(E::custom(format!("u32 out of range: {}", value))) } } } impl<TAlphabet, TState, TOutput> Serialize for Automaton<TAlphabet, TState, TOutput> where TAlphabet: Serialize + Clone + Eq + Hash + Ord, TState: Serialize + Clone + Eq + Hash, TOutput: Serialize + Output, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let Automaton { final_states, start_state, state_data, transitions, } = self; let mut s = serializer.serialize_tuple_struct("Automaton", 5)?; s.serialize_field(&SERIALIZATION_VERSION)?; s.serialize_field(final_states)?; s.serialize_field(start_state)?; s.serialize_field(state_data)?; s.serialize_field(transitions)?; s.end() } } impl<'de, TAlphabet, TState, TOutput> Deserialize<'de> for Automaton<TAlphabet, TState, TOutput> where TAlphabet: 'de + Deserialize<'de> + Clone + Eq + Hash + Ord, TState: 'de + Deserialize<'de> + Clone + Eq + Hash, TOutput: 'de + Deserialize<'de> + Output, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_tuple_struct( "Automaton", 5, AutomatonVisitor { phantom: PhantomData, }, ) } } struct AutomatonVisitor<'de, TAlphabet, TState, TOutput> where TAlphabet: 'de + Deserialize<'de> + Clone + Eq + Hash + Ord, TState: 'de + Deserialize<'de> + Clone + Eq + Hash, TOutput: 'de + Deserialize<'de> + Output, { phantom: PhantomData<&'de (TAlphabet, TState, TOutput)>, } impl<'de, TAlphabet, TState, TOutput> Visitor<'de> for AutomatonVisitor<'de, TAlphabet, TState, TOutput> where TAlphabet: 'de + Deserialize<'de> + Clone + Eq + Hash + Ord, TState: 'de + Deserialize<'de> + Clone + Eq + Hash, TOutput: 'de + Deserialize<'de> + Output, { type Value = Automaton<TAlphabet, TState, TOutput>; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Automaton") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { match seq.next_element::<u32>()? { Some(v) if v == SERIALIZATION_VERSION => {} Some(v) => { return Err(de::Error::invalid_value( de::Unexpected::Unsigned(v as u64), &self, )); } None => { return Err(de::Error::invalid_length( 0, &"Automaton expects 5 elements", )) } } let final_states = match seq.next_element::<BTreeMap<State, TOutput>>()? { Some(x) => x, None => { return Err(de::Error::invalid_length( 1, &"Automaton expects 5 elements", )) } }; let start_state = match seq.next_element::<State>()? { Some(x) => x, None => { return Err(de::Error::invalid_length( 2, &"Automaton expects 5 elements", )) } }; let state_data = match seq.next_element::<Vec<Option<TState>>>()? { Some(x) => x, None => { return Err(de::Error::invalid_length( 3, &"Automaton expects 5 elements", )) } }; let transitions = match seq.next_element::<Vec<BTreeMap<TAlphabet, (State, TOutput)>>>()? { Some(x) => x, None => { return Err(de::Error::invalid_length( 4, &"Automaton expects 5 elements", )) } }; let automata = Automaton { final_states, start_state, state_data, transitions, }; // Ensure that the deserialized automata is well-formed. automata .check_representation() .map_err(|msg| de::Error::custom(msg))?; Ok(automata) } }
27.877828
99
0.534329
1cf8d0eb8ac6fe532232eb4447fb299b87f65140
2,461
// Copyright (c) Facebook, Inc. and its affiliates. // // 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 chrono::{DateTime, Local}; use cursive::utils::markup::StyledString; use cursive::view::{Identifiable, View}; use cursive::views::TextView; use cursive::Cursive; use crate::ViewState; fn get_spacing() -> &'static str { " " } fn get_content(c: &mut Cursive) -> impl Into<StyledString> { let view_state = &c .user_data::<ViewState>() .expect("No data stored in Cursive object!"); let datetime = DateTime::<Local>::from(view_state.timestamp); let mut header_str = StyledString::plain(format!( "{}{}", datetime.format("%m/%d/%Y %H:%M:%S UTC%:z").to_string(), get_spacing() )); header_str.append_plain("Elapsed: "); let elapsed_rendered = format!("{}s", view_state.time_elapsed.as_secs(),); let lowest = view_state.lowest_time_elapsed.as_secs(); let this = view_state.time_elapsed.as_secs(); // 1 second jitter happens pretty often due to integer rounding if lowest != 0 && this >= (lowest + 2) { header_str.append_styled( elapsed_rendered, cursive::theme::Color::Light(cursive::theme::BaseColor::Red), ); } else { header_str.append_plain(elapsed_rendered); } header_str.append_plain(format!( "{}{}{}", get_spacing(), &view_state.system.borrow().hostname, get_spacing(), )); header_str.append_plain(crate::get_version_str()); header_str.append_plain(get_spacing()); header_str.append_plain(view_state.view_mode_str()); header_str } pub fn refresh(c: &mut Cursive) { let content = get_content(c); let mut v = c .find_name::<TextView>("status_bar") .expect("No status_bar view found!"); v.set_content(content); } pub fn new(c: &mut Cursive) -> impl View { TextView::new(get_content(c)).with_name("status_bar") }
31.961039
78
0.659894
9c445edd8447805e2afdc95da50e285b366ebcfb
5,194
use super::super::super::events::field::SiemIp; use crossbeam_channel::Sender; use std::borrow::Cow; use std::collections::BTreeMap; use std::sync::Arc; use serde::Serialize; #[derive(Serialize, Debug)] pub enum UpdateNetIp { Add((SiemIp, u8, Cow<'static, str>)), Remove((SiemIp, u8)), Replace(IpNetDataset), } #[derive(Debug, Clone)] pub struct IpNetSynDataset { dataset: Arc<IpNetDataset>, comm: Sender<UpdateNetIp>, } impl IpNetSynDataset { pub fn new(dataset: Arc<IpNetDataset>, comm: Sender<UpdateNetIp>) -> IpNetSynDataset { return IpNetSynDataset { dataset, comm }; } pub fn add_ip(&mut self, ip: SiemIp, net: u8, data: Cow<'static, str>) { // Todo: improve with local cache to send retries match self.comm.try_send(UpdateNetIp::Add((ip, net, data))) { Ok(_) => {} Err(_) => {} }; } pub fn remove_ip(&mut self, ip: SiemIp, net: u8) { // Todo: improve with local cache to send retries match self.comm.try_send(UpdateNetIp::Remove((ip, net))) { Ok(_) => {} Err(_) => {} }; } pub fn replace_ip(&mut self, data : IpNetDataset) { // Todo: improve with local cache to send retries match self.comm.try_send(UpdateNetIp::Replace(data)) { Ok(_) => {} Err(_) => {} }; } pub fn get(&self, ip: SiemIp) -> Option<&Cow<'static, str>> { // Todo improve with cached content self.dataset.get(ip) } } #[derive(Serialize, Debug)] pub struct IpNetDataset { data4: BTreeMap<u32, BTreeMap<u32, Cow<'static, str>>>, data6: BTreeMap<u32, BTreeMap<u128, Cow<'static, str>>>, } impl IpNetDataset { pub fn new() -> IpNetDataset { return IpNetDataset { data4: BTreeMap::new(), data6: BTreeMap::new(), }; } pub fn insert(&mut self, ip: SiemIp, net: u8, data: Cow<'static, str>) { match ip { SiemIp::V4(ip) => { let ip_net = ip & std::u32::MAX.checked_shl((32 - net) as u32).unwrap_or(0); if self.data4.contains_key(&(net as u32)) { match self.data4.get_mut(&(net as u32)) { Some(dataset) => { dataset.insert(ip_net, data); } None => {} }; } else { let mut new_net = BTreeMap::new(); new_net.insert(ip_net, data); self.data4.insert(net as u32, new_net); } } SiemIp::V6(ip) => { let ip_net = ip & std::u128::MAX.checked_shl((128 - net) as u32).unwrap_or(0); if self.data6.contains_key(&(net as u32)) { match self.data6.get_mut(&(net as u32)) { Some(dataset) => { dataset.insert(ip_net, data); } None => {} }; } else { let mut new_net = BTreeMap::new(); new_net.insert(ip_net, data); self.data6.insert(net as u32, new_net); } } } } pub fn get(&self, ip: SiemIp) -> Option<&Cow<'static, str>> { match ip { SiemIp::V4(ip) => { let zeros = ip.trailing_zeros(); for i in zeros..32 { let ip_net = ip & std::u32::MAX.checked_shl(32 - i).unwrap_or(0); match self.data4.get(&i) { Some(map) => match map.get(&ip_net) { Some(v) => return Some(v), None => { continue; } }, None => { continue; } } } None } SiemIp::V6(ip) => { let zeros = ip.trailing_zeros(); for i in zeros..128 { let ip_net = ip & std::u128::MAX.checked_shl(128 - i).unwrap_or(0); match self.data6.get(&i) { Some(map) => match map.get(&ip_net) { Some(v) => return Some(v), None => { continue; } }, None => { continue; } } } None } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_dataset_creation() { let mut dataset = IpNetDataset::new(); dataset.insert( SiemIp::from_ip_str("192.168.1.1").unwrap(), 24, Cow::Borrowed("Local IP "), ); assert_eq!( dataset.get(SiemIp::from_ip_str("192.168.1.1").unwrap()), Some(&Cow::Borrowed("Local IP ")) ); } }
33.509677
94
0.433
569d9b92c0cc8b268f337d25021b6a6c471516e1
2,708
use std::collections::HashSet; use crate::prelude::*; /// ThreadId implements self-managed thread IDs. /// /// Each instance of ThreadID are guaranteed to have a unique ID. /// And when a ThreadID instance is freed, its ID is automatically freed too. #[derive(Debug, PartialEq)] pub struct ThreadId { pub tid: u32, } impl ThreadId { /// Create a new thread ID. /// /// The thread ID returned is guaranteed to have a value greater than zero. pub fn new() -> ThreadId { let mut alloc = THREAD_ID_ALLOC.lock().unwrap(); let tid = alloc.alloc(); Self { tid } } /// Create a "zero" thread ID. /// /// This "zero" thread ID is used exclusively by the idle process. pub fn zero() -> ThreadId { Self { tid: 0 } } /// Return the value of the thread ID. pub fn as_u32(&self) -> u32 { self.tid } } impl Drop for ThreadId { fn drop(&mut self) { if self.tid == 0 { return; } let mut alloc = THREAD_ID_ALLOC.lock().unwrap(); alloc.free(self.tid); } } lazy_static! { static ref THREAD_ID_ALLOC: SgxMutex<IdAlloc> = SgxMutex::new(IdAlloc::new()); } /// PID/TID allocator. /// /// The allocation strategy is to start from the minimal value (here, 1) and increments /// each returned ID, until a maximum value (e.g., 2^32-1) is reached. After that, recycle /// from the minimal value and see if it is still in use. If not, use the value; otherwise, /// increments again. /// /// The allocation strategy above follows the *nix tradition. /// /// Note that PID/TID 0 is reserved for the idle process. So the id allocator starts from 1. #[derive(Debug, Clone)] struct IdAlloc { next_id: u32, used_ids: HashSet<u32>, } impl IdAlloc { pub fn new() -> Self { Self { next_id: 0, used_ids: HashSet::new(), } } pub fn alloc(&mut self) -> u32 { let new_id = loop { // Increments the ID and wrap around if necessary self.next_id = self.next_id.wrapping_add(1); if self.next_id == 0 { self.next_id = 1; } if !self.used_ids.contains(&self.next_id) { break self.next_id; } }; self.used_ids.insert(new_id); new_id } pub fn free(&mut self, id: u32) -> Option<u32> { // Note: When enableing "execve", there is situation that the ThreadId is reused. // And thus when exit, it may free twice. // debug_assert!(self.used_ids.contains(&id)); if self.used_ids.remove(&id) { Some(id) } else { None } } }
26.291262
92
0.578656
64992494703c91572a8348180bb383c5d64868b1
5,414
use crate::{BlockDuration, NanoErg}; use reqwest::header::HeaderValue; use yaml_rust::{Yaml, YamlLoader}; /// Pool Parameters as defined in the `oracle-config.yaml` pub struct PoolParameters { pub minimum_pool_box_value: u64, pub oracle_payout_price: NanoErg, pub live_epoch_length: BlockDuration, pub epoch_preparation_length: BlockDuration, pub buffer_length: BlockDuration, pub deviation_range: u64, pub consensus_num: u64, pub base_fee: u64, } impl PoolParameters { pub fn new() -> PoolParameters { let config = &YamlLoader::load_from_str(&get_config_yaml()).unwrap()[0]; PoolParameters::new_from_yaml_string(config) } /// Create a `PoolParameters` from a `&Yaml` string pub fn new_from_yaml_string(config: &Yaml) -> PoolParameters { let lel = config["live_epoch_length"] .as_i64() .expect("No live_epoch_length specified in config file."); let epl = config["epoch_preparation_length"] .as_i64() .expect("No epoch_preparation_length specified in config file."); let buf = config["buffer_length"] .as_i64() .expect("No buffer_length specified in config file."); let price = config["oracle_payout_price"] .as_i64() .expect("No oracle_payout_price specified in config file."); let num = config["minimum_pool_box_value"] .as_i64() .expect("No minimum_pool_box_value specified in config file."); let deviation_range = config["deviation_range"] .as_i64() .expect("No deviation_range specified in config file."); let consensus_num = config["consensus_num"] .as_i64() .expect("No consensus_num specified in config file."); let base_fee = config["base_fee"] .as_i64() .expect("No base_fee specified in config file."); PoolParameters { minimum_pool_box_value: num as u64, oracle_payout_price: price as u64, live_epoch_length: lel as u64, epoch_preparation_length: epl as u64, buffer_length: buf as u64, deviation_range: deviation_range as u64, consensus_num: consensus_num as u64, base_fee: base_fee as u64, } } } pub fn get_pool_deposits_contract_address() -> String { let config = &YamlLoader::load_from_str(&get_config_yaml()).unwrap()[0]; config["pool_deposit_contract_address"] .as_str() .expect("No pool_deposit_contract_address specified in config file.") .to_string() } /// Returns "core_api_port" from the config file pub fn get_core_api_port() -> String { let config = &YamlLoader::load_from_str(&get_config_yaml()).unwrap()[0]; config["core_api_port"] .as_str() .expect("No core_api_port specified in config file.") .to_string() } /// Reads the `oracle-config.yaml` file pub fn get_config_yaml() -> String { std::fs::read_to_string("oracle-config.yaml").expect("Failed to open oracle-config.yaml") } /// Returns `http://ip:port` using `node_ip` and `node_port` from the config file pub fn get_node_url() -> String { let ip = get_node_ip(); let port = get_node_port(); "http://".to_string() + &ip + ":" + &port } pub fn get_node_ip() -> String { let config = &YamlLoader::load_from_str(&get_config_yaml()).unwrap()[0]; config["node_ip"] .as_str() .expect("No node_ip specified in config file.") .to_string() } pub fn get_node_port() -> String { let config = &YamlLoader::load_from_str(&get_config_yaml()).unwrap()[0]; config["node_port"] .as_str() .expect("No node_port specified in config file.") .to_string() } /// Acquires the `node_api_key` and builds a `HeaderValue` pub fn get_node_api_header() -> HeaderValue { let api_key = get_node_api_key(); match HeaderValue::from_str(&api_key) { Ok(k) => k, _ => HeaderValue::from_static("None"), } } /// Returns the `node_api_key` pub fn get_node_api_key() -> String { let config = &YamlLoader::load_from_str(&get_config_yaml()).unwrap()[0]; config["node_api_key"] .as_str() .expect("No node_api_key specified in config file.") .to_string() } #[cfg(test)] mod tests { use super::*; #[test] fn valid_ip_port_from_config() { assert_eq!(get_node_url(), "http://0.0.0.0:9053".to_string()) } #[test] fn pool_parameter_parsing_works() { let yaml_string = " minimum_pool_box_value: 10000000 live_epoch_length: 20 epoch_preparation_length: 10 buffer_length: 4 deviation_range: 5 oracle_payout_price: 1000000 base_fee: 1000000 "; let config = &YamlLoader::load_from_str(yaml_string).unwrap()[0]; let pool_params = PoolParameters::new_from_yaml_string(&config); assert_eq!(pool_params.live_epoch_length, 20); assert_eq!(pool_params.epoch_preparation_length, 10); assert_eq!(pool_params.buffer_length, 4); assert_eq!(pool_params.minimum_pool_box_value, 10000000); assert_eq!(pool_params.deviation_range, 5); assert_eq!(pool_params.oracle_payout_price, 1000000); assert_eq!(pool_params.base_fee, 1000000); } }
34.929032
93
0.638345
1cb6bd41b8d788c296f70e59755d05fd2b616e86
12,628
// Copyright 2021 Carsten Andrich <base64decode("Y2Fyc3Rlblx4NDBhbmRyaWNoXHgyZW5hbWU=")> // // 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. // WARNING: THIS PROGRAM WILL WRITE A BUNCH OF NULL CHARACTERS (0x00) ON A // WINDOWS COM PORT OF YOUR CHOICE. DO **NOT** USE IT ON ANY COM PORT // UNLESS YOU'RE **ABSOLUTELY** SURE THAT THIS WILL NOT HAVE ANY // UNDESIRED EFFECTS ON THAT PORT OR DEVICES ACCESSED VIA IT. // // This example illustrates the Windows COM port read/write timeout behavior // by opening a COM port with 10 millisecond read/write timeout and reading/ // writing a couple of times. extern crate winapi; use std::ffi::{OsStr, OsString}; use std::io; use std::mem; use std::os::windows::ffi::OsStrExt; use std::ptr; use std::time::Duration; use winapi::ctypes::c_void; use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE}; use winapi::shared::ntdef::NULL; use winapi::shared::winerror::{ERROR_IO_PENDING, ERROR_SEM_TIMEOUT}; use winapi::um::commapi::{SetCommState, SetCommTimeouts}; use winapi::um::errhandlingapi::GetLastError; use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING, FlushFileBuffers, QueryDosDeviceW, ReadFile, WriteFile}; use winapi::um::handleapi::{CloseHandle, DuplicateHandle, INVALID_HANDLE_VALUE}; use winapi::um::ioapiset::GetOverlappedResult; use winapi::um::minwinbase::OVERLAPPED; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi::um::synchapi::CreateEventW; use winapi::um::winbase::{CBR_256000, COMMTIMEOUTS, DCB, FILE_FLAG_OVERLAPPED, NOPARITY, ONESTOPBIT}; use winapi::um::winnt::{DUPLICATE_SAME_ACCESS, GENERIC_READ, GENERIC_WRITE, HANDLE, MAXDWORD}; pub struct SerialPort { comdev: HANDLE, event: HANDLE } // HANDLE is type *mut c_void which does not implement Send and Sync, so // implement it here, because sharing HANDLEs is inherently thread-safe unsafe impl Send for SerialPort {} unsafe impl Sync for SerialPort {} impl SerialPort { pub fn open<T>(port_name: &T, timeout: Option<Duration>) -> io::Result<Self> where T: AsRef<OsStr> + ?Sized { // construct prefixed COM port name to support COMn with n > 9 let mut name = Vec::<u16>::new(); name.extend(OsStr::new("\\\\.\\").encode_wide()); name.extend(port_name.as_ref().encode_wide()); name.push(0); // open COM port as raw HANDLE let comdev = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, ptr::null_mut(), OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0 as HANDLE) }; if comdev == INVALID_HANDLE_VALUE { return Err(io::Error::last_os_error()); } // create unnamed event object for asynchronous I/O let event = unsafe { // https://docs.microsoft.com/de-de/windows/win32/api/synchapi/nf-synchapi-createeventa CreateEventW(ptr::null_mut(), FALSE, FALSE, ptr::null_mut()) }; if event == NULL { let error = io::Error::last_os_error(); let _res = unsafe { CloseHandle(comdev) }; debug_assert_ne!(_res, 0); return Err(error); } // configure COM port for raw communication // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-dcb let mut dcb: DCB = unsafe { mem::zeroed() }; dcb.DCBlength = mem::size_of::<DCB>() as u32; dcb.set_fBinary(TRUE as u32); dcb.BaudRate = CBR_256000; dcb.ByteSize = 8; dcb.StopBits = ONESTOPBIT; dcb.Parity = NOPARITY; if unsafe { SetCommState(comdev, &mut dcb) } == 0 { let error = io::Error::last_os_error(); let _res = unsafe { CloseHandle(comdev) }; debug_assert_ne!(_res, 0); let _res = unsafe { CloseHandle(event) }; debug_assert_ne!(_res, 0); return Err(error); } // populate COMMTIMEOUTS struct from Option<Duration> // https://docs.microsoft.com/en-us/windows/win32/devio/time-outs // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-commtimeouts let mut timeouts = if let Some(dur) = timeout { let mut dur_ms = dur.as_secs() * 1000 + dur.subsec_millis() as u64; // clip dur_ms to valid range from 1 to MAXDWORD - 1 // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-commtimeouts#remarks if dur_ms < 1 { dur_ms = 1; } else if dur_ms >= MAXDWORD as u64 { dur_ms = (MAXDWORD - 1) as u64; } COMMTIMEOUTS { // return immediately if bytes are available (like POSIX would) // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-commtimeouts#remarks ReadIntervalTimeout: MAXDWORD, ReadTotalTimeoutMultiplier: MAXDWORD, ReadTotalTimeoutConstant: dur_ms as DWORD, // MAXDWORD is *not* a reserved WriteTotalTimeoutMultiplier // value, i.e., setting it incurs an very long write timeout WriteTotalTimeoutMultiplier: 0, WriteTotalTimeoutConstant: dur_ms as DWORD, } } else { // blocking read/write without timeout // FIXME: read() blocks until the read buffer is full COMMTIMEOUTS { ReadIntervalTimeout: 0, ReadTotalTimeoutMultiplier: 0, ReadTotalTimeoutConstant: 0, WriteTotalTimeoutMultiplier: 0, WriteTotalTimeoutConstant: 0, } }; // set timeouts if unsafe { SetCommTimeouts(comdev, &mut timeouts) } == 0 { let error = io::Error::last_os_error(); let _res = unsafe { CloseHandle(comdev) }; debug_assert_ne!(_res, 0); let _res = unsafe { CloseHandle(event) }; debug_assert_ne!(_res, 0); return Err(error); } Ok(Self { comdev, event }) } pub fn try_clone(&self) -> io::Result<Self> { // create new unnamed event object for asynchronous I/O let event = unsafe { // https://docs.microsoft.com/de-de/windows/win32/api/synchapi/nf-synchapi-createeventa CreateEventW(ptr::null_mut(), FALSE, FALSE, ptr::null_mut()) }; if event == NULL { return Err(io::Error::last_os_error()); } // duplicate communications device handle let mut comdev = INVALID_HANDLE_VALUE; let process = unsafe { GetCurrentProcess() }; let res = unsafe { // https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-duplicatehandle DuplicateHandle(process, self.comdev, process, &mut comdev, 0, FALSE, DUPLICATE_SAME_ACCESS) }; if res == 0 { let error = io::Error::last_os_error(); let _res = unsafe { CloseHandle(event) }; debug_assert_ne!(_res, 0); Err(error) } else { Ok(Self { comdev, event }) } } pub fn list_devices() -> Vec<OsString> { let mut devices = Vec::new(); let mut path_wide = [0u16; 1024]; // check result of QueryDosDeviceW() for COM0 thru COM255 to find // existing COM ports (see: https://stackoverflow.com/a/18691898) for n in 0 ..= 255 { // construct wide string for COMn let name = OsString::from(format!("COM{}", n)); let mut name_wide: Vec<u16> = name.encode_wide().collect(); name_wide.push(0); // QueryDosDeviceW() returns 0 if the COM port does not exist let len = unsafe { QueryDosDeviceW(name_wide.as_ptr(), path_wide.as_mut_ptr(), path_wide.len() as DWORD) } as usize; if len > 0 { devices.push(name); } } devices } } impl Drop for SerialPort { fn drop(&mut self) { // https://docs.microsoft.com/de-de/windows/win32/api/handleapi/nf-handleapi-closehandle let _res = unsafe { CloseHandle(self.comdev) }; debug_assert_ne!(_res, 0); let _res = unsafe { CloseHandle(self.event) }; debug_assert_ne!(_res, 0); } } impl io::Read for SerialPort { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { // queue async read let mut overlapped: OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.event; let res: BOOL = unsafe { // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfile ReadFile(self.comdev, buf.as_mut_ptr() as *mut c_void, buf.len() as DWORD, ptr::null_mut(), &mut overlapped) }; // async read request can (theoretically) succeed immediately, queue // successfully, or fail. even if it returns TRUE, the number of bytes // written should be retrieved via GetOverlappedResult(). if res == FALSE && unsafe { GetLastError() } != ERROR_IO_PENDING { return Err(io::Error::last_os_error()); } // wait for completion let mut len: DWORD = 0; let res: BOOL = unsafe { // https://docs.microsoft.com/de-de/windows/win32/api/ioapiset/nf-ioapiset-getoverlappedresult GetOverlappedResult(self.comdev, &mut overlapped, &mut len, TRUE) }; if res == FALSE { return Err(io::Error::last_os_error()); } match len { 0 if buf.len() == 0 => Ok(0), 0 => Err(io::Error::new(io::ErrorKind::TimedOut, "ReadFile() timed out (0 bytes read)")), _ => Ok(len as usize) } } } impl io::Write for SerialPort { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { // queue async write let mut overlapped: OVERLAPPED = unsafe { mem::zeroed() }; overlapped.hEvent = self.event; let res: BOOL = unsafe { // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefile WriteFile(self.comdev, buf.as_ptr() as *const c_void, buf.len() as DWORD, ptr::null_mut(), &mut overlapped) }; // async write request can (theoretically) succeed immediately, queue // successfully, or fail. even if it returns TRUE, the number of bytes // written should be retrieved via GetOverlappedResult(). if res == FALSE && unsafe { GetLastError() } != ERROR_IO_PENDING { return Err(io::Error::last_os_error()); } // wait for completion let mut len: DWORD = 0; let res: BOOL = unsafe { // https://docs.microsoft.com/de-de/windows/win32/api/ioapiset/nf-ioapiset-getoverlappedresult GetOverlappedResult(self.comdev, &mut overlapped, &mut len, TRUE) }; if res == FALSE { // WriteFile() may fail with ERROR_SEM_TIMEOUT, which is not // io::ErrorKind::TimedOut prior to Rust 1.46, so create a custom // error with kind TimedOut to simplify subsequent error handling. // https://github.com/rust-lang/rust/pull/71756 let error = io::Error::last_os_error(); // TODO: wrap if clause in if_rust_version! { < 1.46 { ... }} if error.raw_os_error().unwrap() as DWORD == ERROR_SEM_TIMEOUT && error.kind() != io::ErrorKind::TimedOut { return Err(io::Error::new(io::ErrorKind::TimedOut, "WriteFile() timed out (ERROR_SEM_TIMEOUT)")); } return Err(error); } match len { 0 if buf.len() == 0 => Ok(0), 0 => Err(io::Error::new(io::ErrorKind::TimedOut, "WriteFile() timed out (0 bytes written)")), _ => Ok(len as usize) } } fn flush(&mut self) -> io::Result<()> { // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-purgecomm#remarks match unsafe { FlushFileBuffers(self.comdev) } { 0 => Err(io::Error::last_os_error()), _ => Ok(()), } } } use std::env; use std::io::{Read, Write}; use std::thread; use std::time::Instant; fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { println!("Usage: {} COMn", args[0]); return; } // open port with small timeout duration to get timeouts below let mut com = SerialPort::open( &args[1], Some(Duration::from_millis(10)) ).expect("Opening COM port failed"); let mut com_clone = com.try_clone().expect("Cloning COM port failed"); let t = thread::spawn(move || { println!("{:?}", Instant::now()); let mut buf = [0u8; 1024]; for _ in 0..50 { let res = com.read(&mut buf); println!("< {:?} {:?}", Instant::now(), res); } }); println!("\n{:?}", Instant::now()); let buf = [0u8; 1024]; for _ in 0..20 { let res = com_clone.write(&buf); println!("> {:?} {:?}", Instant::now(), res); } t.join().unwrap(); }
34.692308
110
0.685461
6ab2e32068d47d44c1965e010db12edbb9994058
1,170
pub use skidscan_macros::*; #[cfg(feature = "obfuscate")] pub use obfstr::obfstr; mod signatures; pub use signatures::*; mod modulescan; pub use modulescan::ModuleSigScanError; pub trait SigscanPtr: Copy + Ord { unsafe fn next(self) -> Self; unsafe fn byte(self) -> u8; unsafe fn rewind(self, bytes: usize) -> Self; } impl SigscanPtr for *const u8 { #[inline] unsafe fn next(self) -> Self { self.add(1) } #[inline] unsafe fn byte(self) -> u8 { *self } #[inline] unsafe fn rewind(self, bytes: usize) -> Self { self.sub(bytes) } } impl SigscanPtr for *mut u8 { #[inline] unsafe fn next(self) -> Self { self.add(1) } #[inline] unsafe fn byte(self) -> u8 { *self } #[inline] unsafe fn rewind(self, bytes: usize) -> Self { self.sub(bytes) } } trait SigScan { /// Scans this slice of bytes for a given signature /// /// Returns the index of the first occurrence of the signature in the slice, or None if not found fn sigscan(&self, signature: &Signature) -> Option<usize>; } impl<B: AsRef<[u8]>> SigScan for B { fn sigscan(&self, signature: &Signature) -> Option<usize> { signature.scan(self.as_ref()) } } #[cfg(test)] mod test;
19.5
98
0.657265
69171923a46301a720803532398dac4f96c874b6
650
#![cfg_attr(target_os = "wasi", feature(wasi_ext))] #![cfg_attr(io_lifetimes_use_std, feature(io_safety))] #[cfg(not(feature = "rustc-dep-of-std"))] #[cfg(not(windows))] mod dup2_to_replace_stdio; #[cfg(not(feature = "rustc-dep-of-std"))] // TODO #[cfg(not(windows))] mod epoll; mod error; #[cfg(not(windows))] mod eventfd; #[cfg(not(windows))] mod from_into; #[cfg(not(windows))] mod isatty; #[cfg(not(windows))] mod mmap; #[cfg(not(windows))] mod prot; #[cfg(not(windows))] #[cfg(not(target_os = "redox"))] // redox doesn't have cwd/openat #[cfg(not(target_os = "wasi"))] // wasi support for S_IRUSR etc. submitted to libc in #2264 mod readwrite;
26
91
0.684615
d598effecf6c8b5f53387cac435ab5f9dcd690e5
1,592
// less support in Rust use std::collections::HashMap; fn construct() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 20); println!("{:?}", scores); let teams = vec![String::from("Blue"), String::from("Yellow")]; let scores = vec![10, 50]; let scores: HashMap<_, _> = teams.iter().zip(scores.iter()).collect(); println!("{:?}", scores); } fn mget() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 20); scores.insert(String::from("Yellow"), 50); let team_name = String::from("Blue"); let score = scores.get(&team_name); // no move match score { Some(v) => println!("score of {} is {}", team_name, v), _ => (), } // nice syntax for (key, value) in &scores { println!("{}: {}", key, value); } } fn update() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 20); scores.insert(String::from("Yellow"), 50); // insert twice will update the value scores.insert(String::from("Blue"), 10); println!("{:?}", scores); // insert only no value scores.entry(String::from("Blue")).or_insert(20); scores.entry(String::from("Red")).or_insert(20); println!("{:?}", scores); // update base on old value { let score = scores.entry(String::from("Blue")).or_insert(0); *score += 1; } // mutable borrow score go out of scope println!("{:?}", scores); } fn main() { construct(); mget(); update(); }
24.492308
74
0.557789
ebd5667a7b17b8e6d4fa13f121a0b96eadd6dbed
24
pub(crate) mod sumstats;
24
24
0.791667
f4725a1411ac66ee7fc3ba17378e76b6994301b3
3,637
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] pub type AnotherInt = ::std::os::raw::c_int; #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct C { pub c: C_MyInt, pub ptr: *mut C_MyInt, pub arr: [C_MyInt; 10usize], pub d: AnotherInt, pub other_ptr: *mut AnotherInt, } pub type C_MyInt = ::std::os::raw::c_int; pub type C_Lookup = *const ::std::os::raw::c_char; #[test] fn bindgen_test_layout_C() { assert_eq!( ::std::mem::size_of::<C>(), 72usize, concat!("Size of: ", stringify!(C)) ); assert_eq!( ::std::mem::align_of::<C>(), 8usize, concat!("Alignment of ", stringify!(C)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<C>())).c as *const _ as usize }, 0usize, concat!("Offset of field: ", stringify!(C), "::", stringify!(c)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<C>())).ptr as *const _ as usize }, 8usize, concat!("Offset of field: ", stringify!(C), "::", stringify!(ptr)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<C>())).arr as *const _ as usize }, 16usize, concat!("Offset of field: ", stringify!(C), "::", stringify!(arr)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<C>())).d as *const _ as usize }, 56usize, concat!("Offset of field: ", stringify!(C), "::", stringify!(d)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<C>())).other_ptr as *const _ as usize }, 64usize, concat!( "Offset of field: ", stringify!(C), "::", stringify!(other_ptr) ) ); } extern "C" { #[bindgen_original_name("method")] #[link_name = "\u{1}_ZN1C6methodEi"] pub fn C_method(this: *mut C, c: C_MyInt); } extern "C" { #[bindgen_original_name("methodRef")] #[link_name = "\u{1}_ZN1C9methodRefERi"] pub fn C_methodRef(this: *mut C, c: *mut C_MyInt); } extern "C" { #[bindgen_original_name("complexMethodRef")] #[link_name = "\u{1}_ZN1C16complexMethodRefERPKc"] pub fn C_complexMethodRef(this: *mut C, c: *mut C_Lookup); } extern "C" { #[bindgen_original_name("anotherMethod")] #[link_name = "\u{1}_ZN1C13anotherMethodEi"] pub fn C_anotherMethod(this: *mut C, c: AnotherInt); } impl Default for C { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } impl C { #[inline] pub unsafe fn method(&mut self, c: C_MyInt) { C_method(self, c) } #[inline] pub unsafe fn methodRef(&mut self, c: *mut C_MyInt) { C_methodRef(self, c) } #[inline] pub unsafe fn complexMethodRef(&mut self, c: *mut C_Lookup) { C_complexMethodRef(self, c) } #[inline] pub unsafe fn anotherMethod(&mut self, c: AnotherInt) { C_anotherMethod(self, c) } } #[repr(C)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct D { pub _base: C, pub ptr: *mut C_MyInt, } #[test] fn bindgen_test_layout_D() { assert_eq!( ::std::mem::size_of::<D>(), 80usize, concat!("Size of: ", stringify!(D)) ); assert_eq!( ::std::mem::align_of::<D>(), 8usize, concat!("Alignment of ", stringify!(D)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<D>())).ptr as *const _ as usize }, 72usize, concat!("Offset of field: ", stringify!(D), "::", stringify!(ptr)) ); } impl Default for D { fn default() -> Self { unsafe { ::std::mem::zeroed() } } }
26.940741
80
0.54358
0ac3532215a76cd5fd34657ab7770d3d8c4d5ce7
41,005
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[derive(Debug)] pub(crate) struct Handle< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { client: aws_smithy_client::Client<C, M, R>, conf: crate::Config, } /// An ergonomic service client for `AWSMobileService`. /// /// This client allows ergonomic access to a `AWSMobileService`-shaped service. /// Each method corresponds to an endpoint defined in the service's Smithy model, /// and the request and response shapes are auto-generated from that same model. /// /// # Using a Client /// /// Once you have a client set up, you can access the service's endpoints /// by calling the appropriate method on [`Client`]. Each such method /// returns a request builder for that endpoint, with methods for setting /// the various fields of the request. Once your request is complete, use /// the `send` method to send the request. `send` returns a future, which /// you then have to `.await` to get the service's response. /// /// [builder pattern]: https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder /// [SigV4-signed requests]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html #[derive(std::fmt::Debug)] pub struct Client< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<Handle<C, M, R>>, } impl<C, M, R> std::clone::Clone for Client<C, M, R> { fn clone(&self) -> Self { Self { handle: self.handle.clone(), } } } #[doc(inline)] pub use aws_smithy_client::Builder; impl<C, M, R> From<aws_smithy_client::Client<C, M, R>> for Client<C, M, R> { fn from(client: aws_smithy_client::Client<C, M, R>) -> Self { Self::with_config(client, crate::Config::builder().build()) } } impl<C, M, R> Client<C, M, R> { /// Creates a client with the given service configuration. pub fn with_config(client: aws_smithy_client::Client<C, M, R>, conf: crate::Config) -> Self { Self { handle: std::sync::Arc::new(Handle { client, conf }), } } /// Returns the client's configuration. pub fn conf(&self) -> &crate::Config { &self.handle.conf } } impl<C, M, R> Client<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Constructs a fluent builder for the `CreateProject` operation. /// /// See [`CreateProject`](crate::client::fluent_builders::CreateProject) for more information about the /// operation and its arguments. pub fn create_project(&self) -> fluent_builders::CreateProject<C, M, R> { fluent_builders::CreateProject::new(self.handle.clone()) } /// Constructs a fluent builder for the `DeleteProject` operation. /// /// See [`DeleteProject`](crate::client::fluent_builders::DeleteProject) for more information about the /// operation and its arguments. pub fn delete_project(&self) -> fluent_builders::DeleteProject<C, M, R> { fluent_builders::DeleteProject::new(self.handle.clone()) } /// Constructs a fluent builder for the `DescribeBundle` operation. /// /// See [`DescribeBundle`](crate::client::fluent_builders::DescribeBundle) for more information about the /// operation and its arguments. pub fn describe_bundle(&self) -> fluent_builders::DescribeBundle<C, M, R> { fluent_builders::DescribeBundle::new(self.handle.clone()) } /// Constructs a fluent builder for the `DescribeProject` operation. /// /// See [`DescribeProject`](crate::client::fluent_builders::DescribeProject) for more information about the /// operation and its arguments. pub fn describe_project(&self) -> fluent_builders::DescribeProject<C, M, R> { fluent_builders::DescribeProject::new(self.handle.clone()) } /// Constructs a fluent builder for the `ExportBundle` operation. /// /// See [`ExportBundle`](crate::client::fluent_builders::ExportBundle) for more information about the /// operation and its arguments. pub fn export_bundle(&self) -> fluent_builders::ExportBundle<C, M, R> { fluent_builders::ExportBundle::new(self.handle.clone()) } /// Constructs a fluent builder for the `ExportProject` operation. /// /// See [`ExportProject`](crate::client::fluent_builders::ExportProject) for more information about the /// operation and its arguments. pub fn export_project(&self) -> fluent_builders::ExportProject<C, M, R> { fluent_builders::ExportProject::new(self.handle.clone()) } /// Constructs a fluent builder for the `ListBundles` operation. /// /// See [`ListBundles`](crate::client::fluent_builders::ListBundles) for more information about the /// operation and its arguments. pub fn list_bundles(&self) -> fluent_builders::ListBundles<C, M, R> { fluent_builders::ListBundles::new(self.handle.clone()) } /// Constructs a fluent builder for the `ListProjects` operation. /// /// See [`ListProjects`](crate::client::fluent_builders::ListProjects) for more information about the /// operation and its arguments. pub fn list_projects(&self) -> fluent_builders::ListProjects<C, M, R> { fluent_builders::ListProjects::new(self.handle.clone()) } /// Constructs a fluent builder for the `UpdateProject` operation. /// /// See [`UpdateProject`](crate::client::fluent_builders::UpdateProject) for more information about the /// operation and its arguments. pub fn update_project(&self) -> fluent_builders::UpdateProject<C, M, R> { fluent_builders::UpdateProject::new(self.handle.clone()) } } pub mod fluent_builders { //! //! Utilities to ergonomically construct a request to the service. //! //! Fluent builders are created through the [`Client`](crate::client::Client) by calling //! one if its operation methods. After parameters are set using the builder methods, //! the `send` method can be called to initiate the request. //! /// Fluent builder constructing a request to `CreateProject`. /// /// <p> /// Creates an AWS Mobile Hub project. /// </p> #[derive(std::fmt::Debug)] pub struct CreateProject< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::create_project_input::Builder, } impl<C, M, R> CreateProject<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `CreateProject`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::CreateProjectOutput, aws_smithy_http::result::SdkError<crate::error::CreateProjectError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::CreateProjectInputOperationOutputAlias, crate::output::CreateProjectOutput, crate::error::CreateProjectError, crate::input::CreateProjectInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Name of the project. /// </p> pub fn name(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.name(inp); self } /// <p> /// Name of the project. /// </p> pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_name(input); self } /// <p> /// Default region where project resources should be created. /// </p> pub fn region(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.region(inp); self } /// <p> /// Default region where project resources should be created. /// </p> pub fn set_region(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_region(input); self } /// <p> /// ZIP or YAML file which contains configuration settings to be used when creating /// the project. This may be the contents of the file downloaded from the URL provided /// in an export project operation. /// </p> pub fn contents(mut self, inp: aws_smithy_types::Blob) -> Self { self.inner = self.inner.contents(inp); self } /// <p> /// ZIP or YAML file which contains configuration settings to be used when creating /// the project. This may be the contents of the file downloaded from the URL provided /// in an export project operation. /// </p> pub fn set_contents(mut self, input: std::option::Option<aws_smithy_types::Blob>) -> Self { self.inner = self.inner.set_contents(input); self } /// <p> /// Unique identifier for an exported snapshot of project configuration. This /// snapshot identifier is included in the share URL when a project is exported. /// </p> pub fn snapshot_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.snapshot_id(inp); self } /// <p> /// Unique identifier for an exported snapshot of project configuration. This /// snapshot identifier is included in the share URL when a project is exported. /// </p> pub fn set_snapshot_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_snapshot_id(input); self } } /// Fluent builder constructing a request to `DeleteProject`. /// /// <p> /// Delets a project in AWS Mobile Hub. /// </p> #[derive(std::fmt::Debug)] pub struct DeleteProject< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::delete_project_input::Builder, } impl<C, M, R> DeleteProject<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DeleteProject`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DeleteProjectOutput, aws_smithy_http::result::SdkError<crate::error::DeleteProjectError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DeleteProjectInputOperationOutputAlias, crate::output::DeleteProjectOutput, crate::error::DeleteProjectError, crate::input::DeleteProjectInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Unique project identifier. /// </p> pub fn project_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.project_id(inp); self } /// <p> /// Unique project identifier. /// </p> pub fn set_project_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_project_id(input); self } } /// Fluent builder constructing a request to `DescribeBundle`. /// /// <p> /// Get the bundle details for the requested bundle id. /// </p> #[derive(std::fmt::Debug)] pub struct DescribeBundle< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::describe_bundle_input::Builder, } impl<C, M, R> DescribeBundle<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DescribeBundle`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DescribeBundleOutput, aws_smithy_http::result::SdkError<crate::error::DescribeBundleError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DescribeBundleInputOperationOutputAlias, crate::output::DescribeBundleOutput, crate::error::DescribeBundleError, crate::input::DescribeBundleInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Unique bundle identifier. /// </p> pub fn bundle_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.bundle_id(inp); self } /// <p> /// Unique bundle identifier. /// </p> pub fn set_bundle_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_bundle_id(input); self } } /// Fluent builder constructing a request to `DescribeProject`. /// /// <p> /// Gets details about a project in AWS Mobile Hub. /// </p> #[derive(std::fmt::Debug)] pub struct DescribeProject< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::describe_project_input::Builder, } impl<C, M, R> DescribeProject<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DescribeProject`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DescribeProjectOutput, aws_smithy_http::result::SdkError<crate::error::DescribeProjectError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DescribeProjectInputOperationOutputAlias, crate::output::DescribeProjectOutput, crate::error::DescribeProjectError, crate::input::DescribeProjectInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Unique project identifier. /// </p> pub fn project_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.project_id(inp); self } /// <p> /// Unique project identifier. /// </p> pub fn set_project_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_project_id(input); self } /// <p> /// If set to true, causes AWS Mobile Hub to synchronize information from other services, e.g., update state of AWS CloudFormation stacks in the AWS Mobile Hub project. /// </p> pub fn sync_from_resources(mut self, inp: bool) -> Self { self.inner = self.inner.sync_from_resources(inp); self } /// <p> /// If set to true, causes AWS Mobile Hub to synchronize information from other services, e.g., update state of AWS CloudFormation stacks in the AWS Mobile Hub project. /// </p> pub fn set_sync_from_resources(mut self, input: std::option::Option<bool>) -> Self { self.inner = self.inner.set_sync_from_resources(input); self } } /// Fluent builder constructing a request to `ExportBundle`. /// /// <p> /// Generates customized software development kit (SDK) and or tool packages /// used to integrate mobile web or mobile app clients with backend AWS resources. /// </p> #[derive(std::fmt::Debug)] pub struct ExportBundle< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::export_bundle_input::Builder, } impl<C, M, R> ExportBundle<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ExportBundle`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::ExportBundleOutput, aws_smithy_http::result::SdkError<crate::error::ExportBundleError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::ExportBundleInputOperationOutputAlias, crate::output::ExportBundleOutput, crate::error::ExportBundleError, crate::input::ExportBundleInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Unique bundle identifier. /// </p> pub fn bundle_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.bundle_id(inp); self } /// <p> /// Unique bundle identifier. /// </p> pub fn set_bundle_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_bundle_id(input); self } /// <p> /// Unique project identifier. /// </p> pub fn project_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.project_id(inp); self } /// <p> /// Unique project identifier. /// </p> pub fn set_project_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_project_id(input); self } /// <p> /// Developer desktop or target application platform. /// </p> pub fn platform(mut self, inp: crate::model::Platform) -> Self { self.inner = self.inner.platform(inp); self } /// <p> /// Developer desktop or target application platform. /// </p> pub fn set_platform(mut self, input: std::option::Option<crate::model::Platform>) -> Self { self.inner = self.inner.set_platform(input); self } } /// Fluent builder constructing a request to `ExportProject`. /// /// <p> /// Exports project configuration to a snapshot which can be downloaded and shared. /// Note that mobile app push credentials are encrypted in exported projects, so they /// can only be shared successfully within the same AWS account. /// </p> #[derive(std::fmt::Debug)] pub struct ExportProject< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::export_project_input::Builder, } impl<C, M, R> ExportProject<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ExportProject`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::ExportProjectOutput, aws_smithy_http::result::SdkError<crate::error::ExportProjectError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::ExportProjectInputOperationOutputAlias, crate::output::ExportProjectOutput, crate::error::ExportProjectError, crate::input::ExportProjectInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Unique project identifier. /// </p> pub fn project_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.project_id(inp); self } /// <p> /// Unique project identifier. /// </p> pub fn set_project_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_project_id(input); self } } /// Fluent builder constructing a request to `ListBundles`. /// /// <p> /// List all available bundles. /// </p> #[derive(std::fmt::Debug)] pub struct ListBundles< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::list_bundles_input::Builder, } impl<C, M, R> ListBundles<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ListBundles`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::ListBundlesOutput, aws_smithy_http::result::SdkError<crate::error::ListBundlesError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::ListBundlesInputOperationOutputAlias, crate::output::ListBundlesOutput, crate::error::ListBundlesError, crate::input::ListBundlesInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Maximum number of records to list in a single response. /// </p> pub fn max_results(mut self, inp: i32) -> Self { self.inner = self.inner.max_results(inp); self } /// <p> /// Maximum number of records to list in a single response. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.inner = self.inner.set_max_results(input); self } /// <p> /// Pagination token. Set to null to start listing bundles from start. /// If non-null pagination token is returned in a result, then pass its /// value in here in another request to list more bundles. /// </p> pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.next_token(inp); self } /// <p> /// Pagination token. Set to null to start listing bundles from start. /// If non-null pagination token is returned in a result, then pass its /// value in here in another request to list more bundles. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_next_token(input); self } } /// Fluent builder constructing a request to `ListProjects`. /// /// <p> /// Lists projects in AWS Mobile Hub. /// </p> #[derive(std::fmt::Debug)] pub struct ListProjects< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::list_projects_input::Builder, } impl<C, M, R> ListProjects<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ListProjects`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::ListProjectsOutput, aws_smithy_http::result::SdkError<crate::error::ListProjectsError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::ListProjectsInputOperationOutputAlias, crate::output::ListProjectsOutput, crate::error::ListProjectsError, crate::input::ListProjectsInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// Maximum number of records to list in a single response. /// </p> pub fn max_results(mut self, inp: i32) -> Self { self.inner = self.inner.max_results(inp); self } /// <p> /// Maximum number of records to list in a single response. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.inner = self.inner.set_max_results(input); self } /// <p> /// Pagination token. Set to null to start listing projects from start. /// If non-null pagination token is returned in a result, then pass its /// value in here in another request to list more projects. /// </p> pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.next_token(inp); self } /// <p> /// Pagination token. Set to null to start listing projects from start. /// If non-null pagination token is returned in a result, then pass its /// value in here in another request to list more projects. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_next_token(input); self } } /// Fluent builder constructing a request to `UpdateProject`. /// /// <p> /// Update an existing project. /// </p> #[derive(std::fmt::Debug)] pub struct UpdateProject< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::update_project_input::Builder, } impl<C, M, R> UpdateProject<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `UpdateProject`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::UpdateProjectOutput, aws_smithy_http::result::SdkError<crate::error::UpdateProjectError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::UpdateProjectInputOperationOutputAlias, crate::output::UpdateProjectOutput, crate::error::UpdateProjectError, crate::input::UpdateProjectInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p> /// ZIP or YAML file which contains project configuration to be updated. This should /// be the contents of the file downloaded from the URL provided in an export project /// operation. /// </p> pub fn contents(mut self, inp: aws_smithy_types::Blob) -> Self { self.inner = self.inner.contents(inp); self } /// <p> /// ZIP or YAML file which contains project configuration to be updated. This should /// be the contents of the file downloaded from the URL provided in an export project /// operation. /// </p> pub fn set_contents(mut self, input: std::option::Option<aws_smithy_types::Blob>) -> Self { self.inner = self.inner.set_contents(input); self } /// <p> /// Unique project identifier. /// </p> pub fn project_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.project_id(inp); self } /// <p> /// Unique project identifier. /// </p> pub fn set_project_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_project_id(input); self } } } impl<C> Client<C, aws_hyper::AwsMiddleware, aws_smithy_client::retry::Standard> { /// Creates a client with the given service config and connector override. pub fn from_conf_conn(conf: crate::Config, conn: C) -> Self { let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default(); let timeout_config = conf.timeout_config.as_ref().cloned().unwrap_or_default(); let sleep_impl = conf.sleep_impl.clone(); let mut client = aws_hyper::Client::new(conn) .with_retry_config(retry_config.into()) .with_timeout_config(timeout_config); client.set_sleep_impl(sleep_impl); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } } impl Client< aws_smithy_client::erase::DynConnector, aws_hyper::AwsMiddleware, aws_smithy_client::retry::Standard, > { /// Creates a new client from a shared config. #[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn new(config: &aws_types::config::Config) -> Self { Self::from_conf(config.into()) } /// Creates a new client from the service [`Config`](crate::Config). #[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn from_conf(conf: crate::Config) -> Self { let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default(); let timeout_config = conf.timeout_config.as_ref().cloned().unwrap_or_default(); let sleep_impl = conf.sleep_impl.clone(); let mut client = aws_hyper::Client::https() .with_retry_config(retry_config.into()) .with_timeout_config(timeout_config); client.set_sleep_impl(sleep_impl); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } }
40.083089
176
0.57849
0391e82b0744d173e6acaa66023c9464dcc46a08
2,163
// Test where we change the body of a private method in an impl. // We then test what sort of functions must be rebuilt as a result. // revisions:cfail1 cfail2 // compile-flags: -Z query-dep-graph // aux-build:point.rs // compile-pass #![crate_type = "rlib"] #![feature(rustc_attrs)] #![feature(stmt_expr_attributes)] #![allow(dead_code)] #![no_trace] #![rustc_partition_reused(module="struct_point-fn_calls_methods_in_same_impl", cfg="cfail2")] #![rustc_partition_reused(module="struct_point-fn_calls_methods_in_another_impl", cfg="cfail2")] #![rustc_partition_reused(module="struct_point-fn_read_field", cfg="cfail2")] #![rustc_partition_reused(module="struct_point-fn_write_field", cfg="cfail2")] #![rustc_partition_reused(module="struct_point-fn_make_struct", cfg="cfail2")] extern crate point; /// A fn item that calls (public) methods on `Point` from the same impl which changed pub mod fn_calls_methods_in_same_impl { use point::Point; #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); } } /// A fn item that calls (public) methods on `Point` from another impl pub mod fn_calls_methods_in_another_impl { use point::Point; #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] pub fn check() { let mut x = Point { x: 2.0, y: 2.0 }; x.translate(3.0, 3.0); } } /// A fn item that makes an instance of `Point` but does not invoke methods pub mod fn_make_struct { use point::Point; #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } } /// A fn item that reads fields from `Point` but does not invoke methods pub mod fn_read_field { use point::Point; #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } } /// A fn item that writes to a field of `Point` but does not invoke methods pub mod fn_write_field { use point::Point; #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } }
29.22973
96
0.675451
649af8eec2d14e14a683449a98de577c5a74b67b
4,550
const NTAB: i32 = 32; const IA: i32 = 16807; const IM: i32 = i32::MAX; const IQ: i32 = 127_773; const IR: i32 = 2836; const NDIV: i32 = 1 + (IM - 1) / NTAB; const MAX_RANDOM_RANGE: i32 = IM; const AM: f64 = 1.0 / IM as f64; const EPS: f64 = 1.2e-7; const RNMX: f64 = 1.0 - EPS; /// The Uniform Random Number Generator /// /// Should be instantiated with the `with_seed` method. /// /// # Usage /// /// ``` /// use valve_sdk13_rng::UniformRandomStream; /// /// let mut gen = UniformRandomStream::with_seed(72); /// let res = gen.random_f64(0_f64, 1_f64); /// assert_eq!(0.543_099_8, res); /// ``` /// #[derive(Debug, Clone)] pub struct UniformRandomStream { pub m_idum: i32, pub m_iy: i32, pub m_iv: Vec<i32>, } impl UniformRandomStream { pub fn with_seed(i_seed: i32) -> Self { let midum = -i_seed.abs(); Self { m_idum: midum, m_iy: 0, m_iv: vec![0; NTAB as usize], } } fn generate_random_number(&mut self) -> i32 { let mut k; let mut j; let mut m_idum = self.m_idum; let mut m_iy = self.m_iy; let m_iv = &mut self.m_iv; if m_idum <= 0 || m_iy == 0 { if -m_idum < 1 { m_idum = 1; } else { m_idum = -m_idum; } j = NTAB + 7; while j >= 0 { k = m_idum / IQ; m_idum = IA * (m_idum - k * IQ) - IR * k; if m_idum < 0 { m_idum += IM; } if j < NTAB { m_iv[j as usize] = m_idum; } j -= 1; } m_iy = m_iv[0]; } k = m_idum / IQ; m_idum = IA * (m_idum - k * IQ) - IR * k; if m_idum < 0 { m_idum += IM; } let j = m_iy / NDIV; m_iy = m_iv[j as usize]; m_iv[j as usize] = m_idum; self.m_idum = m_idum; self.m_iy = m_iy; m_iy } pub fn random_f64(&mut self, low: f64, high: f64) -> f64 { let mut fl = AM * f64::from(self.generate_random_number()); if fl > RNMX { fl = RNMX; } fl.mul_add(high - low, low) } pub fn random_f64_exp(&mut self, low: f64, high: f64, exponent: f64) -> f64 { let mut fl = AM * f64::from(self.generate_random_number()); if fl > RNMX { fl = RNMX; } if exponent != 1.0 { fl = fl.powf(exponent); } fl.mul_add(high - low, low) } pub fn random_i32(&mut self, low: i32, high: i32) -> i32 { let x = high - low + 1; if x <= 1 { return low; } // From Source Engine 2007: // The following maps a uniform distribution on the interval [0,MAX_RANDOM_RANGE] // to a smaller, client-specified range of [0,x-1] in a way that doesn't bias // the uniform distribution unfavorably. Even for a worst case x, the loop is // guaranteed to be taken no more than half the time, so for that worst case x, // the average number of times through the loop is 2. For cases where x is // much smaller than MAX_RANDOM_RANGE, the average number of times through the // loop is very close to 1. let x1 = MAX_RANDOM_RANGE.wrapping_add(1) % x; let max_acceptable = MAX_RANDOM_RANGE.saturating_sub(x1); let number = loop { let n = self.generate_random_number(); if n <= max_acceptable { break n; } }; low + (number % x) } } #[cfg(test)] mod tests { use super::*; #[test] fn t_random_float() { let proper: Vec<f32> = vec![0.543_099_8, 0.406_318_28, 62.147_213, 0.058_990_162]; let mut u_rng = UniformRandomStream::with_seed(72); let results = vec![ u_rng.random_f64(0.0, 1.0) as f32, u_rng.random_f64(0.0, 1.0) as f32, u_rng.random_f64(0.0, 100.0) as f32, u_rng.random_f64(0.0, 1.0) as f32, ]; assert_eq!(proper, results); } #[test] fn t_random_int() { let proper: Vec<i32> = vec![6, 9, 95, 8]; let mut u_rng = UniformRandomStream::with_seed(555); let results = vec![ u_rng.random_i32(0, 10), u_rng.random_i32(0, 10), u_rng.random_i32(0, 100), u_rng.random_i32(0, 10), ]; assert_eq!(proper, results); } }
24.863388
90
0.504176
3ac822519044b3ddee27e59f175406ee957bc7eb
2,016
#[doc = "Reader of register NAK_POLL"] pub type R = crate::R<u32, super::NAK_POLL>; #[doc = "Writer for register NAK_POLL"] pub type W = crate::W<u32, super::NAK_POLL>; #[doc = "Register NAK_POLL `reset()`'s with value 0x0010_0010"] impl crate::ResetValue for super::NAK_POLL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0010_0010 } } #[doc = "Reader of field `DELAY_FS`"] pub type DELAY_FS_R = crate::R<u16, u16>; #[doc = "Write proxy for field `DELAY_FS`"] pub struct DELAY_FS_W<'a> { w: &'a mut W, } impl<'a> DELAY_FS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03ff << 16)) | (((value as u32) & 0x03ff) << 16); self.w } } #[doc = "Reader of field `DELAY_LS`"] pub type DELAY_LS_R = crate::R<u16, u16>; #[doc = "Write proxy for field `DELAY_LS`"] pub struct DELAY_LS_W<'a> { w: &'a mut W, } impl<'a> DELAY_LS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x03ff) | ((value as u32) & 0x03ff); self.w } } impl R { #[doc = "Bits 16:25 - NAK polling interval for a full speed device"] #[inline(always)] pub fn delay_fs(&self) -> DELAY_FS_R { DELAY_FS_R::new(((self.bits >> 16) & 0x03ff) as u16) } #[doc = "Bits 0:9 - NAK polling interval for a low speed device"] #[inline(always)] pub fn delay_ls(&self) -> DELAY_LS_R { DELAY_LS_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 16:25 - NAK polling interval for a full speed device"] #[inline(always)] pub fn delay_fs(&mut self) -> DELAY_FS_W { DELAY_FS_W { w: self } } #[doc = "Bits 0:9 - NAK polling interval for a low speed device"] #[inline(always)] pub fn delay_ls(&mut self) -> DELAY_LS_W { DELAY_LS_W { w: self } } }
31.015385
90
0.589286
3ad84bd092df14ae88558156c768f2f311e004bb
12,127
use makepad_render::*; use crate::buttonlogic::*; use crate::tabclose::*; use crate::widgetstyle::*; #[derive(Clone)] pub struct Tab { pub bg: Quad, pub text: Text, pub tab_close: TabClose, pub label: String, pub is_closeable: bool, pub animator: Animator, pub z: f32, pub abs_origin: Option<Vec2>, pub _is_selected: bool, pub _is_focussed: bool, pub _bg_area: Area, pub _bg_inst: Option<InstanceArea>, pub _text_area: Area, pub _close_anim_rect: Rect, pub _is_down: bool, pub _is_drag: bool } #[derive(Clone, PartialEq)] pub enum TabEvent { None, DragMove(FingerMoveEvent), DragEnd(FingerUpEvent), Closing, Close, Select, } impl Tab { pub fn new(cx: &mut Cx) -> Self { let mut tab = Self { label: "Tab".to_string(), is_closeable: true, z: 0., bg: Quad ::new(cx), tab_close: TabClose::new(cx), text: Text::new(cx), animator: Animator::default(), abs_origin: None, _is_selected: false, _is_focussed: false, _is_down: false, _is_drag: false, _close_anim_rect: Rect::default(), _text_area: Area::Empty, _bg_area: Area::Empty, _bg_inst: None, }; tab.animator.set_anim_as_last_values(&tab.anim_default(cx)); tab } pub fn layout_bg() -> LayoutId {uid!()} pub fn text_style_title() -> TextStyleId {uid!()} pub fn border_color() -> ColorId {uid!()} pub fn tab_closing() -> FloatId {uid!()} pub fn shader_bg() -> ShaderId {uid!()} pub fn style(cx: &mut Cx, opt: &StyleOptions) { Self::layout_bg().set(cx, Layout { align: Align::left_center(), walk: Walk::wh(Width::Compute, Height::Fix(40. * opt.scale.powf(0.5))), padding: Padding {l: 16.0, t: 1.0, r: 16.0, b: 0.0}, ..Default::default() }); Self::text_style_title().set(cx, Theme::text_style_normal().get(cx)); Self::shader_bg().set(cx, Quad::def_quad_shader().compose(shader!{" instance border_color: Self::border_color(); const border_width: float = 1.0; fn pixel() -> vec4 { let cx = Df::viewport(pos * vec2(w, h)); cx.rect(-1., -1., w + 2., h + 2.); cx.fill(color); cx.move_to(w, 0.); cx.line_to(w, h); cx.move_to(0., 0.); cx.line_to(0., h); return cx.stroke(border_color, 1.); } "})); } pub fn get_bg_color(&self, cx: &Cx) -> Color { if self._is_selected { Theme::color_bg_selected().get(cx) } else { Theme::color_bg_normal().get(cx) } } pub fn get_text_color(&self, cx: &Cx) -> Color { if self._is_selected { if self._is_focussed { Theme::color_text_selected_focus().get(cx) } else { Theme::color_text_selected_defocus().get(cx) } } else { if self._is_focussed { Theme::color_text_deselected_focus().get(cx) } else { Theme::color_text_deselected_defocus().get(cx) } } } pub fn anim_default(&self, cx: &Cx) -> Anim { Anim::new(Play::Cut {duration: 0.05}, vec![ Track::color(Quad::color(), Ease::Lin, vec![(1.0, self.get_bg_color(cx))]), Track::color(Self::border_color(), Ease::Lin, vec![(1.0, Theme::color_bg_selected().get(cx))]), Track::color(Text::color(), Ease::Lin, vec![(1.0, self.get_text_color(cx))]), //Track::color_id(cx, "icon.color", Ease::Lin, vec![(1.0, self.get_text_color(cx))]) ]) } pub fn anim_over(&self, cx: &Cx) -> Anim { Anim::new(Play::Cut {duration: 0.01}, vec![ Track::color(Quad::color(), Ease::Lin, vec![(1.0, self.get_bg_color(cx))]), Track::color(Self::border_color(), Ease::Lin, vec![(1.0, Theme::color_bg_selected().get(cx))]), Track::color(Text::color(), Ease::Lin, vec![(1.0, self.get_text_color(cx))]), //Track::color_id(cx, "icon.color", Ease::Lin, vec![(1.0, self.get_text_color(cx))]) ]) } pub fn anim_down(&self, cx: &Cx) -> Anim { Anim::new(Play::Cut {duration: 0.01}, vec![ Track::color(Quad::color(), Ease::Lin, vec![(1.0, self.get_bg_color(cx))]), Track::color(Self::border_color(), Ease::Lin, vec![(1.0, Theme::color_bg_selected().get(cx))]), Track::color(Text::color(), Ease::Lin, vec![(1.0, self.get_text_color(cx))]), // Track::color_id(cx, "icon.color", Ease::Lin, vec![(1.0, self.get_text_color(cx))]) ]) } pub fn anim_close(&self, _cx: &Cx) -> Anim { Anim::new(Play::Single {duration: 0.1, cut: true, term: true, end: 1.0}, vec![ Track::float(Self::tab_closing(), Ease::OutExp, vec![(0.0, 1.0), (1.0, 0.0)]), ]) } pub fn set_tab_focus(&mut self, cx: &mut Cx, focus: bool) { if focus != self._is_focussed { self._is_focussed = focus; self.animator.play_anim(cx, self.anim_default(cx)); } } pub fn set_tab_selected(&mut self, cx: &mut Cx, selected: bool) { if selected != self._is_selected { self._is_selected = selected; self.animator.play_anim(cx, self.anim_default(cx)); } } pub fn set_tab_state(&mut self, cx: &mut Cx, selected: bool, focus: bool) { self._is_selected = selected; self._is_focussed = focus; self.animator.set_anim_as_last_values(&self.anim_default(cx)); } pub fn handle_tab(&mut self, cx: &mut Cx, event: &mut Event) -> TabEvent { if !self.animator.term_anim_playing() { match self.tab_close.handle_tab_close(cx, event) { ButtonEvent::Down => { self._close_anim_rect = self._bg_area.get_rect(cx); self.animator.play_anim(cx, self.anim_close(cx)); return TabEvent::Closing; }, _ => () } } match event.hits(cx, self._bg_area, HitOpt::default()) { Event::Animate(ae) => { // its playing the term anim, run a redraw if self.animator.term_anim_playing() { self.animator.calc_float(cx, Self::tab_closing(), ae.time); cx.redraw_child_area(self._bg_area); } else { self.animator.calc_area(cx, self._bg_area, ae.time); self.animator.calc_area(cx, self._text_area, ae.time); } }, Event::AnimEnded(_ae) => { if self.animator.term_anim_playing() { return TabEvent::Close; } else { self.animator.end(); } }, Event::FingerDown(_fe) => { if self.animator.term_anim_playing() { return TabEvent::None } cx.set_down_mouse_cursor(MouseCursor::Hand); self._is_down = true; self._is_drag = false; self._is_selected = true; self._is_focussed = true; self.animator.play_anim(cx, self.anim_down(cx)); return TabEvent::Select; }, Event::FingerHover(fe) => { cx.set_hover_mouse_cursor(MouseCursor::Hand); match fe.hover_state { HoverState::In => { if self._is_down { self.animator.play_anim(cx, self.anim_down(cx)); } else { self.animator.play_anim(cx, self.anim_over(cx)); } }, HoverState::Out => { self.animator.play_anim(cx, self.anim_default(cx)); }, _ => () } }, Event::FingerUp(fe) => { self._is_down = false; if fe.is_over { if !fe.is_touch { self.animator.play_anim(cx, self.anim_over(cx)); } else { self.animator.play_anim(cx, self.anim_default(cx)); } } else { self.animator.play_anim(cx, self.anim_default(cx)); } if self._is_drag { self._is_drag = false; return TabEvent::DragEnd(fe); } }, Event::FingerMove(fe) => { if !self._is_drag { if fe.move_distance() > 10. { //cx.set_down_mouse_cursor(MouseCursor::Hidden); self._is_drag = true; } } if self._is_drag { return TabEvent::DragMove(fe); } //self.animator.play_anim(cx, self.animator.default.clone()); }, _ => () }; TabEvent::None } pub fn get_tab_rect(&mut self, cx: &Cx) -> Rect { self._bg_area.get_rect(cx) } pub fn begin_tab(&mut self, cx: &mut Cx) -> Result<(), ()> { // pull the bg color from our animation system, uses 'default' value otherwise self.bg.shader = Self::shader_bg().get(cx); self.bg.z = self.z; self.bg.color = self.animator.last_color(cx, Quad::color()); // check if we are closing if self.animator.term_anim_playing() { // so so BUT how would we draw this thing with its own clipping let bg_inst = self.bg.draw_quad( cx, Walk::wh( Width::Fix(self._close_anim_rect.w * self.animator.last_float(cx, Self::tab_closing())), Height::Fix(self._close_anim_rect.h), ) ); bg_inst.push_last_color(cx, &self.animator, Self::border_color()); self._bg_area = bg_inst.into(); self.animator.set_area(cx, self._bg_area); return Err(()) } else { let layout = if let Some(abs_origin) = self.abs_origin { Layout {abs_origin: Some(abs_origin), ..Self::layout_bg().get(cx)} } else { Self::layout_bg().get(cx) }; let bg_inst = self.bg.begin_quad(cx, layout); bg_inst.push_last_color(cx, &self.animator, Self::border_color()); if self.is_closeable { self.tab_close.draw_tab_close(cx); cx.turtle_align_y(); } // push the 2 vars we added to bg shader self.text.z = self.z; self.text.text_style = Self::text_style_title().get(cx); self.text.color = self.animator.last_color(cx, Text::color()); self._text_area = self.text.draw_text(cx, &self.label); cx.turtle_align_y(); self._bg_inst = Some(bg_inst); return Ok(()) } } pub fn end_tab(&mut self, cx: &mut Cx) { if let Some(bg_inst) = self._bg_inst.take() { self._bg_area = self.bg.end_quad(cx, bg_inst); self.animator.set_area(cx, self._bg_area); // if our area changed, update animation } } pub fn draw_tab(&mut self, cx: &mut Cx) { if self.begin_tab(cx).is_err() {return}; self.end_tab(cx); } }
35.878698
108
0.489899
d78dbc9c64b1e2cd17f4b989060eb035a388b664
2,657
// industrial-io/examples/riio_detect.rs // // Simple Rust IIO example to list the devices found in the specified context. // // Note that, if no context is requested at the command line, this will create // a network context if the IIOD_REMOTE environment variable is set, otherwise // it will create a local context. See Context::new(). // // Copyright (c) 2018-2019, Frank Pagliughi // // Licensed under the MIT license: // <LICENSE or http://opensource.org/licenses/MIT> // This file may not be copied, modified, or distributed except according // to those terms. // #[macro_use] extern crate clap; extern crate industrial_io as iio; use std::process; use clap::{Arg, App}; fn main() { let matches = App::new("riio_free_scan") .version(crate_version!()) .about("Rust IIO free scan buffered reads.") .arg(Arg::with_name("network") .short("n") .long("network") .help("Use the network backend with the provided hostname") .takes_value(true)) .arg(Arg::with_name("uri") .short("u") .long("uri") .help("Use the context with the provided URI") .takes_value(true)) .get_matches(); let ctx = if let Some(hostname) = matches.value_of("network") { iio::Context::create_network(hostname) } else if let Some(uri) = matches.value_of("uri") { iio::Context::create_from_uri(uri) } else { iio::Context::new() } .unwrap_or_else(|_err| { println!("Couldn't open IIO context."); process::exit(1); }); let mut trigs = Vec::new(); if ctx.num_devices() == 0 { println!("No devices in the default IIO context"); } else { println!("IIO Devices:"); for dev in ctx.devices() { if dev.is_trigger() { if let Some(id) = dev.id() { trigs.push(id); } } else { print!(" {} ", dev.id().unwrap_or_default()); print!("[{}]", dev.name().unwrap_or_default()); println!(": {} channel(s)", dev.num_channels()); } } if !trigs.is_empty() { println!("\nTriggers Devices:"); for s in trigs { println!(" {}", s); } } } }
32.402439
84
0.488145
3a32e00e9be8eefa92a0ea97179f0e543ff26090
1,854
use std::borrow::Cow; use crate::{ctrl::Error, ServerState}; pub fn trim_message<'a>(state: &ServerState, content: &'a str) -> Result<Cow<'a, str>, Error> { let mut trimmed_content = Cow::Borrowed(content); if !trimmed_content.is_empty() { let mut trimming = false; let mut new_content = String::new(); let mut count = 0; // TODO: Don't strip newlines inside code blocks? for (idx, &byte) in trimmed_content.as_bytes().iter().enumerate() { // if we encounted a newline if byte == b'\n' { count += 1; // count up // if over 2 consecutive newlines, begin trimming if count > 2 { // if not already trimming, push everything tested up until this point // notably not including the third newline if !trimming { trimming = true; new_content.push_str(&trimmed_content[..idx]); } // skip any additional newlines continue; } } else { // reset count if newline streak broken count = 0; } // if trimming, push the new byte if trimming { unsafe { new_content.as_mut_vec().push(byte) }; } } if trimming { trimmed_content = Cow::Owned(new_content); } let newlines = bytecount::count(trimmed_content.as_bytes(), b'\n'); let too_large = !state.config.message.message_len.contains(&trimmed_content.len()); let too_long = newlines > state.config.message.max_newlines; if too_large || too_long { return Err(Error::BadRequest); } } Ok(trimmed_content) }
31.965517
95
0.519417
1a7f86ac31fd130eba0345868ca8d04e43a8ddfa
9,724
//! `Value`s hold arbitrary borrowed or owneed bencode data. Unlike `Objects`, //! they can be cloned and traversed multiple times. //! //! `Value` implements `FromBencode`, `ToBencode`. If the `serde` feature is //! enabled, it also implements `Serialize` and `Deserialize`. use alloc::{ borrow::{Cow, ToOwned}, collections::BTreeMap, vec::Vec, }; #[cfg(feature = "serde")] use std::{ convert::TryInto, fmt::{self, Formatter}, marker::PhantomData, }; #[cfg(feature = "serde")] use serde_ as serde; #[cfg(feature = "serde")] use serde::{ ser::{SerializeMap, SerializeSeq}, Serialize, }; use crate::{ decoding::{FromBencode, Object}, encoding::{SingleItemEncoder, ToBencode}, }; /// An owned or borrowed bencoded value. #[derive(PartialEq, Eq, Clone, Debug)] pub enum Value<'a> { /// An owned or borrowed byte string Bytes(Cow<'a, [u8]>), /// A dictionary mapping byte strings to values Dict(BTreeMap<Cow<'a, [u8]>, Value<'a>>), /// A signed integer Integer(i64), /// A list of values List(Vec<Value<'a>>), } impl<'a> Value<'a> { /// Convert this Value into an owned Value with static lifetime pub fn into_owned(self) -> Value<'static> { match self { Value::Bytes(bytes) => Value::Bytes(Cow::Owned(bytes.into_owned())), Value::Dict(dict) => Value::Dict( dict.into_iter() .map(|(key, value)| (Cow::Owned(key.into_owned()), value.into_owned())) .collect(), ), Value::Integer(integer) => Value::Integer(integer), Value::List(list) => Value::List(list.into_iter().map(Value::into_owned).collect()), } } } impl<'a> ToBencode for Value<'a> { // This leaves some room for external containers. // TODO(#38): Change this to 0 for v0.4 const MAX_DEPTH: usize = usize::max_value() / 4; fn encode(&self, encoder: SingleItemEncoder) -> Result<(), crate::encoding::Error> { match self { Value::Bytes(bytes) => encoder.emit_bytes(bytes), Value::Dict(dict) => dict.encode(encoder), Value::Integer(integer) => integer.encode(encoder), Value::List(list) => list.encode(encoder), } } } impl<'a> FromBencode for Value<'a> { const EXPECTED_RECURSION_DEPTH: usize = <Self as ToBencode>::MAX_DEPTH; fn decode_bencode_object(object: Object) -> Result<Self, crate::decoding::Error> { match object { Object::Bytes(bytes) => Ok(Value::Bytes(Cow::Owned(bytes.to_owned()))), Object::Dict(mut decoder) => { let mut dict = BTreeMap::new(); while let Some((key, value)) = decoder.next_pair()? { dict.insert( Cow::Owned(key.to_owned()), Value::decode_bencode_object(value)?, ); } Ok(Value::Dict(dict)) }, Object::Integer(text) => Ok(Value::Integer(text.parse()?)), Object::List(mut decoder) => { let mut list = Vec::new(); while let Some(object) = decoder.next_object()? { list.push(Value::decode_bencode_object(object)?); } Ok(Value::List(list)) }, } } } #[cfg(feature = "serde")] mod serde_impls { use super::*; use serde_bytes::Bytes; impl<'a> Serialize for Value<'a> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, { match self { Value::Bytes(string) => serializer.serialize_bytes(string), Value::Integer(int) => serializer.serialize_i64(*int), Value::List(list) => { let mut seed = serializer.serialize_seq(Some(list.len()))?; for value in list { seed.serialize_element(value)?; } seed.end() }, Value::Dict(dict) => { let mut seed = serializer.serialize_map(Some(dict.len()))?; for (k, v) in dict { let bytes = Bytes::new(k); seed.serialize_entry(bytes, v)?; } seed.end() }, } } } impl<'de: 'a, 'a> serde::de::Deserialize<'de> for Value<'a> { #[inline] fn deserialize<D>(deserializer: D) -> Result<Value<'a>, D::Error> where D: serde::de::Deserializer<'de>, { deserializer.deserialize_any(Visitor(PhantomData)) } } struct Visitor<'a>(PhantomData<&'a ()>); impl<'de: 'a, 'a> serde::de::Visitor<'de> for Visitor<'a> { type Value = Value<'a>; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { formatter.write_str("any valid BEncode value") } fn visit_i64<E>(self, value: i64) -> Result<Value<'a>, E> { Ok(Value::Integer(value)) } fn visit_u64<E>(self, value: u64) -> Result<Value<'a>, E> { Ok(Value::Integer(value.try_into().unwrap())) } fn visit_borrowed_bytes<E>(self, value: &'de [u8]) -> Result<Value<'a>, E> where E: serde::de::Error, { Ok(Value::Bytes(Cow::Borrowed(value))) } fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Value<'a>, E> where E: serde::de::Error, { Ok(Value::Bytes(Cow::Borrowed(value.as_bytes()))) } fn visit_string<E>(self, value: String) -> Result<Value<'a>, E> { Ok(Value::Bytes(Cow::Owned(value.into_bytes()))) } fn visit_byte_buf<E>(self, value: Vec<u8>) -> Result<Value<'a>, E> { Ok(Value::Bytes(Cow::Owned(value))) } fn visit_seq<V>(self, mut access: V) -> Result<Value<'a>, V::Error> where V: serde::de::SeqAccess<'de>, { let mut list = Vec::new(); while let Some(e) = access.next_element()? { list.push(e); } Ok(Value::List(list)) } fn visit_map<V>(self, mut access: V) -> Result<Value<'a>, V::Error> where V: serde::de::MapAccess<'de>, { let mut map = BTreeMap::new(); while let Some((k, v)) = access.next_entry::<&Bytes, _>()? { map.insert(Cow::Borrowed(k.as_ref()), v); } Ok(Value::Dict(map)) } } } #[cfg(test)] mod tests { use super::*; use alloc::{string::String, vec}; fn case(value: Value, expected: impl AsRef<[u8]>) { let expected = expected.as_ref(); let encoded = match value.to_bencode() { Ok(bytes) => bytes, Err(err) => panic!("Failed to encode `{:?}`: {}", value, err), }; if encoded != expected { panic!( "Expected `{:?}` to encode as `{}`, but got `{}", value, String::from_utf8_lossy(expected), String::from_utf8_lossy(&encoded) ) } let decoded = match Value::from_bencode(&encoded) { Ok(decoded) => decoded, Err(err) => panic!( "Failed to decode value from `{}`: {}", String::from_utf8_lossy(&encoded), err, ), }; assert_eq!(decoded, value); #[cfg(feature = "serde")] { let deserialized = match crate::serde::de::from_bytes::<Value>(expected) { Ok(deserialized) => deserialized, Err(err) => panic!( "Failed to deserialize value from `{}`: {}", String::from_utf8_lossy(&expected), err ), }; if deserialized != value { panic!( "Deserialize Serialize produced unexpected value: `{:?}` != `{:?}`", deserialized, value ); } let serialized = match crate::serde::ser::to_bytes(&value) { Ok(serialized) => serialized, Err(err) => panic!("Failed to serialize `{:?}`: {}", value, err), }; if serialized != expected { panic!( "Serialize Serialize produced unexpected bencode: `{:?}` != `{:?}`", String::from_utf8_lossy(&serialized), String::from_utf8_lossy(expected) ); } } } #[test] fn bytes() { case(Value::Bytes(Cow::Borrowed(&[1, 2, 3])), b"3:\x01\x02\x03"); case(Value::Bytes(Cow::Owned(vec![1, 2, 3])), b"3:\x01\x02\x03"); } #[test] fn dict() { case(Value::Dict(BTreeMap::new()), "de"); let mut dict = BTreeMap::new(); dict.insert(Cow::Borrowed("foo".as_bytes()), Value::Integer(1)); dict.insert(Cow::Borrowed("bar".as_bytes()), Value::Integer(2)); case(Value::Dict(dict), "d3:bari2e3:fooi1ee"); } #[test] fn integer() { case(Value::Integer(0), "i0e"); case(Value::Integer(-1), "i-1e"); } #[test] fn list() { case(Value::List(Vec::new()), "le"); case( Value::List(vec![ Value::Integer(0), Value::Bytes(Cow::Borrowed(&[1, 2, 3])), ]), b"li0e3:\x01\x02\x03e", ); } }
31.067093
96
0.490333
711313350303333ae887ea9ea739db238bf25ae8
3,871
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{parse_macro_input, Data, DeriveInput, GenericParam, Ident, TypeParamBound}; /// Derives Fold for structs and enums for which one of the following is true: /// - It has a `#[has_type_family(TheTypeFamily)]` attribute /// - There is a parameter `T: HasTypeFamily` /// - There is a parameter `T: TypeFamily` #[proc_macro_derive(Fold, attributes(has_type_family))] pub fn derive_fold(item: TokenStream) -> TokenStream { let input = parse_macro_input!(item as DeriveInput); let (impl_generics, ty_generics, where_clause_ref) = input.generics.split_for_impl(); let mut where_clause = where_clause_ref.cloned(); let generics = if let Some(attr) = input .attrs .iter() .find(|a| a.path.is_ident("has_type_family")) { let arg = attr .parse_args::<proc_macro2::TokenStream>() .expect("Expected has_type_family argument"); quote! { < #arg > } } else if let Some(param) = input .generics .params .iter() .find_map(|p| has_type_family_bound(p)) { let tf = quote! { <#param as HasTypeFamily>::TypeFamily }; where_clause .get_or_insert(syn::parse2(quote![where]).unwrap()) .predicates .push(syn::parse2(quote! { #param: Fold<#tf, Result = #param> }).unwrap()); quote! { <#tf> } } else { ty_generics.to_token_stream() }; let name = input.ident; let body = derive_fold_body(input.data); TokenStream::from(quote! { impl #impl_generics Fold #generics for #name #ty_generics #where_clause { type Result = Self; fn fold_with( &self, folder: &mut dyn Folder #generics, binders: usize, ) -> ::chalk_engine::fallible::Fallible<Self::Result> { #body } } }) } /// Generates the body of the Fold impl fn derive_fold_body(data: Data) -> proc_macro2::TokenStream { match data { Data::Struct(s) => { let fields = s.fields.into_iter().map(|f| { let name = f.ident.as_ref().expect("Unnamed field in Foldable struct"); quote! { #name: self.#name.fold_with(folder, binders)? } }); quote! { Ok(Self { #(#fields),* }) } } Data::Enum(e) => { let matches = e.variants.into_iter().map(|v| { let variant = v.ident; let names: Vec<_> = (0..v.fields.iter().count()) .map(|index| format_ident!("a{}", index)) .collect(); quote! { Self::#variant( #(ref #names),* ) => { Ok(Self::#variant( #(#names.fold_with(folder, binders)?),* )) } } }); quote! { match *self { #(#matches)* } } } Data::Union(..) => panic!("Fold can not be derived for unions"), } } /// Checks whether a generic parameter has a `: HasTypeFamily` bound fn has_type_family_bound(param: &GenericParam) -> Option<&Ident> { match param { GenericParam::Type(ref t) => t.bounds.iter().find_map(|b| { if let TypeParamBound::Trait(trait_bound) = b { if trait_bound .path .segments .last() .map(|s| s.ident.to_string()) == Some(String::from("HasTypeFamily")) { return Some(&t.ident); } } None }), _ => None, } }
33.08547
89
0.508654
72b895a5a88302212b445a95900028fcb37e9684
4,368
// // Copyright (C) 2018 Kubos Corporation // // 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 super::*; use byteorder::{LittleEndian, WriteBytesExt}; pub trait Message { fn serialize(&self) -> Vec<u8>; } pub struct SetAcsMode { pub id: u8, pub mode: u8, pub qbi_cmd: [i16; 4], } impl Default for SetAcsMode { fn default() -> Self { SetAcsMode { id: 0, mode: 0, qbi_cmd: [0; 4], } } } impl Message for SetAcsMode { fn serialize(&self) -> Vec<u8> { let mut vec = SYNC.to_vec(); vec.push(self.id); vec.push(self.mode); vec.write_i16::<LittleEndian>(self.qbi_cmd[0]).unwrap(); vec.write_i16::<LittleEndian>(self.qbi_cmd[1]).unwrap(); vec.write_i16::<LittleEndian>(self.qbi_cmd[2]).unwrap(); vec.write_i16::<LittleEndian>(self.qbi_cmd[3]).unwrap(); vec.append(&mut vec![0; 26]); vec } } pub struct SetAcsModeSun { pub id: u8, pub mode: u8, pub sun_angle_enable: i16, pub sun_rot_angle: f32, } impl Default for SetAcsModeSun { fn default() -> Self { SetAcsModeSun { id: 0, mode: 0, sun_angle_enable: 0, sun_rot_angle: 0.0, } } } impl Message for SetAcsModeSun { fn serialize(&self) -> Vec<u8> { let mut vec = SYNC.to_vec(); vec.push(self.id); vec.push(self.mode); vec.write_i16::<LittleEndian>(self.sun_angle_enable) .unwrap(); vec.write_f32::<LittleEndian>(self.sun_rot_angle).unwrap(); vec.append(&mut vec![0; 28]); vec } } pub struct SetGPSTime { pub id: u8, pub gps_time: u32, } impl Default for SetGPSTime { fn default() -> Self { SetGPSTime { id: 0x44, gps_time: 0, } } } impl Message for SetGPSTime { fn serialize(&self) -> Vec<u8> { let mut vec = SYNC.to_vec(); vec.push(self.id); vec.write_u32::<LittleEndian>(self.gps_time).unwrap(); vec.append(&mut vec![0; 31]); vec } } pub struct SetRV { pub id: u8, pub eci_pos: [f32; 3], pub eci_vel: [f32; 3], pub time_epoch: u32, } impl Default for SetRV { fn default() -> Self { SetRV { id: 0x41, eci_pos: [0.0, 0.0, 0.0], eci_vel: [0.0, 0.0, 0.0], time_epoch: 0, } } } impl Message for SetRV { fn serialize(&self) -> Vec<u8> { let mut vec = SYNC.to_vec(); vec.push(self.id); vec.write_f32::<LittleEndian>(self.eci_pos[0]).unwrap(); vec.write_f32::<LittleEndian>(self.eci_pos[1]).unwrap(); vec.write_f32::<LittleEndian>(self.eci_pos[2]).unwrap(); vec.write_f32::<LittleEndian>(self.eci_vel[0]).unwrap(); vec.write_f32::<LittleEndian>(self.eci_vel[1]).unwrap(); vec.write_f32::<LittleEndian>(self.eci_vel[2]).unwrap(); vec.write_u32::<LittleEndian>(self.time_epoch).unwrap(); vec.append(&mut vec![0; 7]); vec } } pub struct RequestReset(pub [u8; 38]); impl Default for RequestReset { fn default() -> Self { let mut array = [0; 38]; array[0] = 0x90; // SYNC byte 1 array[1] = 0xEB; // SYNC byte 2 array[2] = 0x5A; // Command ID RequestReset(array) } } impl Message for RequestReset { fn serialize(&self) -> Vec<u8> { self.0.to_vec() } } pub struct ConfirmReset([u8; 38]); impl Default for ConfirmReset { fn default() -> Self { let mut array = [0; 38]; array[0] = 0x90; // SYNC byte 1 array[1] = 0xEB; // SYNC byte 2 array[2] = 0xF1; // Command ID ConfirmReset(array) } } impl Message for ConfirmReset { fn serialize(&self) -> Vec<u8> { self.0.to_vec() } }
24
75
0.571658
f9c6da78ddd125e719a6e2ffe379e8e0e7f7acee
769
/* * Copyright 2018 Alistair Francis <[email protected]> * * 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 course; pub mod display; pub mod gps; pub mod imu; pub mod obdii; pub mod prepare; pub mod read_track; pub mod temp; pub mod threading;
29.576923
75
0.743823
0ee06b725a99a1ae886cd935b956d6bd7f3dfe6e
66,451
use crate::Element; use crate::{UncertainFloat, Isotope, AtomicScatteringFactor, XrayScatteringFactor}; pub fn load() -> Element { Element { atomic_number: 84, name: "Polonium", symbol: "Po", mass: 209.0_f64, common_ions: vec![-2, 2, 4], uncommon_ions: vec![5, 6], xray_scattering: Some(XrayScatteringFactor { table: vec![ AtomicScatteringFactor { energy: 0.01_f64, f1: None, f2: Some(4.927_63_f64) }, AtomicScatteringFactor { energy: 0.010_161_7_f64, f1: None, f2: Some(4.957_84_f64) }, AtomicScatteringFactor { energy: 0.010_326_1_f64, f1: None, f2: Some(4.988_23_f64) }, AtomicScatteringFactor { energy: 0.010_493_1_f64, f1: None, f2: Some(5.018_81_f64) }, AtomicScatteringFactor { energy: 0.010_662_8_f64, f1: None, f2: Some(5.049_57_f64) }, AtomicScatteringFactor { energy: 0.010_835_3_f64, f1: None, f2: Some(5.106_34_f64) }, AtomicScatteringFactor { energy: 0.011_010_6_f64, f1: None, f2: Some(5.173_68_f64) }, AtomicScatteringFactor { energy: 0.011_188_6_f64, f1: None, f2: Some(5.241_91_f64) }, AtomicScatteringFactor { energy: 0.011_369_6_f64, f1: None, f2: Some(5.311_04_f64) }, AtomicScatteringFactor { energy: 0.011_553_5_f64, f1: None, f2: Some(5.381_08_f64) }, AtomicScatteringFactor { energy: 0.011_740_4_f64, f1: None, f2: Some(5.418_89_f64) }, AtomicScatteringFactor { energy: 0.011_930_3_f64, f1: None, f2: Some(5.448_83_f64) }, AtomicScatteringFactor { energy: 0.012_123_2_f64, f1: None, f2: Some(5.478_94_f64) }, AtomicScatteringFactor { energy: 0.012_319_3_f64, f1: None, f2: Some(5.509_22_f64) }, AtomicScatteringFactor { energy: 0.012_518_6_f64, f1: None, f2: Some(5.539_66_f64) }, AtomicScatteringFactor { energy: 0.012_721_f64, f1: None, f2: Some(5.522_45_f64) }, AtomicScatteringFactor { energy: 0.012_926_8_f64, f1: None, f2: Some(5.489_02_f64) }, AtomicScatteringFactor { energy: 0.013_135_9_f64, f1: None, f2: Some(5.455_8_f64) }, AtomicScatteringFactor { energy: 0.013_348_3_f64, f1: None, f2: Some(5.422_78_f64) }, AtomicScatteringFactor { energy: 0.013_564_2_f64, f1: None, f2: Some(5.389_84_f64) }, AtomicScatteringFactor { energy: 0.013_783_6_f64, f1: None, f2: Some(5.351_12_f64) }, AtomicScatteringFactor { energy: 0.014_006_6_f64, f1: None, f2: Some(5.312_67_f64) }, AtomicScatteringFactor { energy: 0.014_233_1_f64, f1: None, f2: Some(5.274_49_f64) }, AtomicScatteringFactor { energy: 0.014_463_3_f64, f1: None, f2: Some(5.236_6_f64) }, AtomicScatteringFactor { energy: 0.014_697_3_f64, f1: None, f2: Some(5.198_97_f64) }, AtomicScatteringFactor { energy: 0.014_935_f64, f1: None, f2: Some(5.172_13_f64) }, AtomicScatteringFactor { energy: 0.015_176_5_f64, f1: None, f2: Some(5.146_02_f64) }, AtomicScatteringFactor { energy: 0.015_422_f64, f1: None, f2: Some(5.120_04_f64) }, AtomicScatteringFactor { energy: 0.015_671_4_f64, f1: None, f2: Some(5.094_19_f64) }, AtomicScatteringFactor { energy: 0.015_924_9_f64, f1: None, f2: Some(5.068_48_f64) }, AtomicScatteringFactor { energy: 0.016_182_5_f64, f1: None, f2: Some(5.042_89_f64) }, AtomicScatteringFactor { energy: 0.016_444_2_f64, f1: None, f2: Some(5.017_93_f64) }, AtomicScatteringFactor { energy: 0.016_710_2_f64, f1: None, f2: Some(4.996_41_f64) }, AtomicScatteringFactor { energy: 0.016_980_5_f64, f1: None, f2: Some(4.974_98_f64) }, AtomicScatteringFactor { energy: 0.017_255_1_f64, f1: None, f2: Some(4.953_63_f64) }, AtomicScatteringFactor { energy: 0.017_534_2_f64, f1: None, f2: Some(4.932_39_f64) }, AtomicScatteringFactor { energy: 0.017_817_8_f64, f1: None, f2: Some(4.844_46_f64) }, AtomicScatteringFactor { energy: 0.018_106_f64, f1: None, f2: Some(4.719_19_f64) }, AtomicScatteringFactor { energy: 0.018_398_9_f64, f1: None, f2: Some(4.597_17_f64) }, AtomicScatteringFactor { energy: 0.018_696_4_f64, f1: None, f2: Some(4.478_29_f64) }, AtomicScatteringFactor { energy: 0.018_998_8_f64, f1: None, f2: Some(4.360_91_f64) }, AtomicScatteringFactor { energy: 0.019_306_1_f64, f1: None, f2: Some(4.243_39_f64) }, AtomicScatteringFactor { energy: 0.019_618_4_f64, f1: None, f2: Some(4.129_03_f64) }, AtomicScatteringFactor { energy: 0.019_935_7_f64, f1: None, f2: Some(4.017_76_f64) }, AtomicScatteringFactor { energy: 0.020_258_2_f64, f1: None, f2: Some(3.909_48_f64) }, AtomicScatteringFactor { energy: 0.020_585_8_f64, f1: None, f2: Some(3.781_32_f64) }, AtomicScatteringFactor { energy: 0.020_918_8_f64, f1: None, f2: Some(3.653_18_f64) }, AtomicScatteringFactor { energy: 0.021_257_1_f64, f1: None, f2: Some(3.529_38_f64) }, AtomicScatteringFactor { energy: 0.021_600_9_f64, f1: None, f2: Some(3.397_49_f64) }, AtomicScatteringFactor { energy: 0.021_950_3_f64, f1: None, f2: Some(3.183_59_f64) }, AtomicScatteringFactor { energy: 0.022_305_3_f64, f1: None, f2: Some(2.983_15_f64) }, AtomicScatteringFactor { energy: 0.022_666_1_f64, f1: None, f2: Some(2.795_34_f64) }, AtomicScatteringFactor { energy: 0.023_032_7_f64, f1: None, f2: Some(2.638_f64) }, AtomicScatteringFactor { energy: 0.023_405_3_f64, f1: None, f2: Some(2.501_03_f64) }, AtomicScatteringFactor { energy: 0.023_783_8_f64, f1: None, f2: Some(2.371_17_f64) }, AtomicScatteringFactor { energy: 0.024_168_5_f64, f1: None, f2: Some(2.243_61_f64) }, AtomicScatteringFactor { energy: 0.024_559_4_f64, f1: None, f2: Some(2.117_49_f64) }, AtomicScatteringFactor { energy: 0.024_956_6_f64, f1: None, f2: Some(1.998_46_f64) }, AtomicScatteringFactor { energy: 0.025_360_3_f64, f1: None, f2: Some(1.899_02_f64) }, AtomicScatteringFactor { energy: 0.025_770_5_f64, f1: None, f2: Some(1.811_38_f64) }, AtomicScatteringFactor { energy: 0.026_187_3_f64, f1: None, f2: Some(1.727_79_f64) }, AtomicScatteringFactor { energy: 0.026_610_9_f64, f1: None, f2: Some(1.714_17_f64) }, AtomicScatteringFactor { energy: 0.027_041_3_f64, f1: None, f2: Some(1.710_27_f64) }, AtomicScatteringFactor { energy: 0.027_478_6_f64, f1: None, f2: Some(1.694_68_f64) }, AtomicScatteringFactor { energy: 0.027_923_1_f64, f1: None, f2: Some(1.662_48_f64) }, AtomicScatteringFactor { energy: 0.028_374_7_f64, f1: None, f2: Some(1.656_59_f64) }, AtomicScatteringFactor { energy: 0.028_833_7_f64, f1: None, f2: Some(1.696_68_f64) }, AtomicScatteringFactor { energy: 0.029_3_f64, f1: Some(-0.327_474_f64), f2: Some(1.739_76_f64) }, AtomicScatteringFactor { energy: 0.029_773_9_f64, f1: Some(-0.805_751_f64), f2: Some(1.806_21_f64) }, AtomicScatteringFactor { energy: 0.030_255_5_f64, f1: Some(-1.433_87_f64), f2: Some(1.875_2_f64) }, AtomicScatteringFactor { energy: 0.030_744_9_f64, f1: Some(-2.388_48_f64), f2: Some(2.313_78_f64) }, AtomicScatteringFactor { energy: 0.031_242_1_f64, f1: Some(-3.058_f64), f2: Some(3.368_04_f64) }, AtomicScatteringFactor { energy: 0.031_747_5_f64, f1: Some(-2.952_32_f64), f2: Some(4.850_98_f64) }, AtomicScatteringFactor { energy: 0.032_260_9_f64, f1: Some(-2.425_57_f64), f2: Some(5.183_13_f64) }, AtomicScatteringFactor { energy: 0.032_782_7_f64, f1: Some(-2.156_57_f64), f2: Some(5.504_92_f64) }, AtomicScatteringFactor { energy: 0.033_313_f64, f1: Some(-1.991_61_f64), f2: Some(5.811_93_f64) }, AtomicScatteringFactor { energy: 0.033_851_8_f64, f1: Some(-1.774_01_f64), f2: Some(6.135_34_f64) }, AtomicScatteringFactor { energy: 0.034_399_3_f64, f1: Some(-1.560_68_f64), f2: Some(6.247_56_f64) }, AtomicScatteringFactor { energy: 0.034_955_7_f64, f1: Some(-1.428_88_f64), f2: Some(6.361_82_f64) }, AtomicScatteringFactor { energy: 0.035_521_1_f64, f1: Some(-1.310_19_f64), f2: Some(6.449_93_f64) }, AtomicScatteringFactor { energy: 0.036_095_6_f64, f1: Some(-1.260_7_f64), f2: Some(6.483_06_f64) }, AtomicScatteringFactor { energy: 0.036_679_4_f64, f1: Some(-1.270_61_f64), f2: Some(6.516_36_f64) }, AtomicScatteringFactor { energy: 0.037_272_7_f64, f1: Some(-1.327_12_f64), f2: Some(6.549_68_f64) }, AtomicScatteringFactor { energy: 0.037_875_5_f64, f1: Some(-1.433_92_f64), f2: Some(6.583_15_f64) }, AtomicScatteringFactor { energy: 0.038_488_2_f64, f1: Some(-1.617_52_f64), f2: Some(6.616_8_f64) }, AtomicScatteringFactor { energy: 0.039_110_7_f64, f1: Some(-1.853_59_f64), f2: Some(6.767_08_f64) }, AtomicScatteringFactor { energy: 0.039_743_2_f64, f1: Some(-2.066_99_f64), f2: Some(6.939_13_f64) }, AtomicScatteringFactor { energy: 0.040_386_1_f64, f1: Some(-2.297_38_f64), f2: Some(7.115_55_f64) }, AtomicScatteringFactor { energy: 0.041_039_3_f64, f1: Some(-2.595_66_f64), f2: Some(7.344_85_f64) }, AtomicScatteringFactor { energy: 0.041_703_1_f64, f1: Some(-2.861_85_f64), f2: Some(7.645_36_f64) }, AtomicScatteringFactor { energy: 0.042_377_6_f64, f1: Some(-3.135_25_f64), f2: Some(7.958_16_f64) }, AtomicScatteringFactor { energy: 0.043_063_f64, f1: Some(-3.467_63_f64), f2: Some(8.284_49_f64) }, AtomicScatteringFactor { energy: 0.043_759_5_f64, f1: Some(-3.791_79_f64), f2: Some(8.800_56_f64) }, AtomicScatteringFactor { energy: 0.044_467_3_f64, f1: Some(-4.044_38_f64), f2: Some(9.348_78_f64) }, AtomicScatteringFactor { energy: 0.045_186_5_f64, f1: Some(-4.256_59_f64), f2: Some(9.931_14_f64) }, AtomicScatteringFactor { energy: 0.045_917_4_f64, f1: Some(-4.437_04_f64), f2: Some(10.557_3_f64) }, AtomicScatteringFactor { energy: 0.046_66_f64, f1: Some(-4.569_56_f64), f2: Some(11.229_4_f64) }, AtomicScatteringFactor { energy: 0.047_414_7_f64, f1: Some(-4.649_49_f64), f2: Some(11.944_2_f64) }, AtomicScatteringFactor { energy: 0.048_181_6_f64, f1: Some(-4.655_22_f64), f2: Some(12.704_5_f64) }, AtomicScatteringFactor { energy: 0.048_960_9_f64, f1: Some(-4.529_65_f64), f2: Some(13.513_2_f64) }, AtomicScatteringFactor { energy: 0.049_752_8_f64, f1: Some(-4.344_02_f64), f2: Some(14.149_4_f64) }, AtomicScatteringFactor { energy: 0.050_557_6_f64, f1: Some(-4.196_53_f64), f2: Some(14.8_f64) }, AtomicScatteringFactor { energy: 0.051_375_3_f64, f1: Some(-4.037_5_f64), f2: Some(15.480_5_f64) }, AtomicScatteringFactor { energy: 0.052_206_2_f64, f1: Some(-3.844_89_f64), f2: Some(16.192_3_f64) }, AtomicScatteringFactor { energy: 0.053_050_6_f64, f1: Some(-3.591_61_f64), f2: Some(16.936_8_f64) }, AtomicScatteringFactor { energy: 0.053_908_7_f64, f1: Some(-3.221_09_f64), f2: Some(17.715_6_f64) }, AtomicScatteringFactor { energy: 0.054_780_6_f64, f1: Some(-2.811_38_f64), f2: Some(18.330_9_f64) }, AtomicScatteringFactor { energy: 0.055_666_7_f64, f1: Some(-2.423_03_f64), f2: Some(18.967_2_f64) }, AtomicScatteringFactor { energy: 0.056_567_f64, f1: Some(-2.006_24_f64), f2: Some(19.625_5_f64) }, AtomicScatteringFactor { energy: 0.057_482_f64, f1: Some(-1.522_33_f64), f2: Some(20.306_8_f64) }, AtomicScatteringFactor { energy: 0.058_411_7_f64, f1: Some(-0.879_052_f64), f2: Some(20.903_2_f64) }, AtomicScatteringFactor { energy: 0.059_356_4_f64, f1: Some(-0.325_593_f64), f2: Some(21.37_f64) }, AtomicScatteringFactor { energy: 0.060_316_5_f64, f1: Some(0.196_99_f64), f2: Some(21.847_3_f64) }, AtomicScatteringFactor { energy: 0.061_292_1_f64, f1: Some(0.718_284_f64), f2: Some(22.335_2_f64) }, AtomicScatteringFactor { energy: 0.062_283_4_f64, f1: Some(1.252_34_f64), f2: Some(22.834_f64) }, AtomicScatteringFactor { energy: 0.063_290_8_f64, f1: Some(1.809_21_f64), f2: Some(23.343_9_f64) }, AtomicScatteringFactor { energy: 0.064_314_5_f64, f1: Some(2.398_99_f64), f2: Some(23.865_3_f64) }, AtomicScatteringFactor { energy: 0.065_354_7_f64, f1: Some(3.033_83_f64), f2: Some(24.398_2_f64) }, AtomicScatteringFactor { energy: 0.066_411_8_f64, f1: Some(3.732_53_f64), f2: Some(24.943_1_f64) }, AtomicScatteringFactor { energy: 0.067_485_9_f64, f1: Some(4.535_99_f64), f2: Some(25.500_2_f64) }, AtomicScatteringFactor { energy: 0.068_577_5_f64, f1: Some(5.582_37_f64), f2: Some(25.917_1_f64) }, AtomicScatteringFactor { energy: 0.069_686_7_f64, f1: Some(6.478_25_f64), f2: Some(26.070_4_f64) }, AtomicScatteringFactor { energy: 0.070_813_8_f64, f1: Some(7.287_94_f64), f2: Some(26.224_5_f64) }, AtomicScatteringFactor { energy: 0.071_959_1_f64, f1: Some(8.061_14_f64), f2: Some(26.379_5_f64) }, AtomicScatteringFactor { energy: 0.073_123_f64, f1: Some(8.820_59_f64), f2: Some(26.535_5_f64) }, AtomicScatteringFactor { energy: 0.074_305_7_f64, f1: Some(9.578_3_f64), f2: Some(26.692_4_f64) }, AtomicScatteringFactor { energy: 0.075_507_6_f64, f1: Some(10.344_1_f64), f2: Some(26.850_1_f64) }, AtomicScatteringFactor { energy: 0.076_728_9_f64, f1: Some(11.127_9_f64), f2: Some(27.008_9_f64) }, AtomicScatteringFactor { energy: 0.077_969_9_f64, f1: Some(11.943_8_f64), f2: Some(27.168_6_f64) }, AtomicScatteringFactor { energy: 0.079_231_f64, f1: Some(12.823_2_f64), f2: Some(27.329_2_f64) }, AtomicScatteringFactor { energy: 0.080_512_5_f64, f1: Some(13.800_9_f64), f2: Some(27.382_9_f64) }, AtomicScatteringFactor { energy: 0.081_814_7_f64, f1: Some(14.708_3_f64), f2: Some(27.344_4_f64) }, AtomicScatteringFactor { energy: 0.083_138_f64, f1: Some(15.599_7_f64), f2: Some(27.305_9_f64) }, AtomicScatteringFactor { energy: 0.084_482_7_f64, f1: Some(16.508_7_f64), f2: Some(27.267_5_f64) }, AtomicScatteringFactor { energy: 0.085_849_1_f64, f1: Some(17.465_7_f64), f2: Some(27.229_1_f64) }, AtomicScatteringFactor { energy: 0.087_237_7_f64, f1: Some(18.527_5_f64), f2: Some(27.190_8_f64) }, AtomicScatteringFactor { energy: 0.088_648_7_f64, f1: Some(19.896_7_f64), f2: Some(27.061_9_f64) }, AtomicScatteringFactor { energy: 0.090_082_5_f64, f1: Some(21.088_4_f64), f2: Some(26.273_3_f64) }, AtomicScatteringFactor { energy: 0.091_539_5_f64, f1: Some(21.994_4_f64), f2: Some(25.507_6_f64) }, AtomicScatteringFactor { energy: 0.093_020_1_f64, f1: Some(22.683_8_f64), f2: Some(24.782_6_f64) }, AtomicScatteringFactor { energy: 0.094_524_6_f64, f1: Some(23.337_8_f64), f2: Some(24.193_1_f64) }, AtomicScatteringFactor { energy: 0.096_053_5_f64, f1: Some(24.012_1_f64), f2: Some(23.617_6_f64) }, AtomicScatteringFactor { energy: 0.097_607_1_f64, f1: Some(24.759_5_f64), f2: Some(23.055_7_f64) }, AtomicScatteringFactor { energy: 0.099_185_8_f64, f1: Some(25.642_9_f64), f2: Some(22.192_4_f64) }, AtomicScatteringFactor { energy: 0.100_79_f64, f1: Some(26.181_4_f64), f2: Some(21.142_8_f64) }, AtomicScatteringFactor { energy: 0.102_42_f64, f1: Some(26.417_3_f64), f2: Some(20.143_f64) }, AtomicScatteringFactor { energy: 0.104_077_f64, f1: Some(26.532_5_f64), f2: Some(19.408_3_f64) }, AtomicScatteringFactor { energy: 0.105_76_f64, f1: Some(26.712_7_f64), f2: Some(18.763_8_f64) }, AtomicScatteringFactor { energy: 0.107_471_f64, f1: Some(26.905_9_f64), f2: Some(18.140_8_f64) }, AtomicScatteringFactor { energy: 0.109_209_f64, f1: Some(27.100_2_f64), f2: Some(17.538_4_f64) }, AtomicScatteringFactor { energy: 0.110_975_f64, f1: Some(27.305_7_f64), f2: Some(16.956_1_f64) }, AtomicScatteringFactor { energy: 0.112_77_f64, f1: Some(27.582_4_f64), f2: Some(16.393_f64) }, AtomicScatteringFactor { energy: 0.114_594_f64, f1: Some(27.893_3_f64), f2: Some(15.617_8_f64) }, AtomicScatteringFactor { energy: 0.116_448_f64, f1: Some(27.988_1_f64), f2: Some(14.763_6_f64) }, AtomicScatteringFactor { energy: 0.118_331_f64, f1: Some(27.950_9_f64), f2: Some(13.956_2_f64) }, AtomicScatteringFactor { energy: 0.120_245_f64, f1: Some(27.809_2_f64), f2: Some(13.192_8_f64) }, AtomicScatteringFactor { energy: 0.122_19_f64, f1: Some(27.525_7_f64), f2: Some(12.471_3_f64) }, AtomicScatteringFactor { energy: 0.124_166_f64, f1: Some(27.107_9_f64), f2: Some(12.032_4_f64) }, AtomicScatteringFactor { energy: 0.126_175_f64, f1: Some(26.846_7_f64), f2: Some(11.743_6_f64) }, AtomicScatteringFactor { energy: 0.128_215_f64, f1: Some(26.69_f64), f2: Some(11.461_8_f64) }, AtomicScatteringFactor { energy: 0.130_289_f64, f1: Some(26.571_1_f64), f2: Some(11.186_7_f64) }, AtomicScatteringFactor { energy: 0.132_397_f64, f1: Some(26.480_7_f64), f2: Some(10.918_2_f64) }, AtomicScatteringFactor { energy: 0.134_538_f64, f1: Some(26.415_1_f64), f2: Some(10.656_2_f64) }, AtomicScatteringFactor { energy: 0.136_714_f64, f1: Some(26.375_3_f64), f2: Some(10.400_5_f64) }, AtomicScatteringFactor { energy: 0.138_925_f64, f1: Some(26.371_1_f64), f2: Some(10.150_9_f64) }, AtomicScatteringFactor { energy: 0.141_172_f64, f1: Some(26.458_7_f64), f2: Some(9.907_26_f64) }, AtomicScatteringFactor { energy: 0.143_456_f64, f1: Some(26.605_3_f64), f2: Some(9.466_53_f64) }, AtomicScatteringFactor { energy: 0.145_776_f64, f1: Some(26.587_3_f64), f2: Some(8.936_11_f64) }, AtomicScatteringFactor { energy: 0.148_134_f64, f1: Some(26.479_8_f64), f2: Some(8.435_4_f64) }, AtomicScatteringFactor { energy: 0.150_53_f64, f1: Some(26.318_f64), f2: Some(7.962_73_f64) }, AtomicScatteringFactor { energy: 0.152_964_f64, f1: Some(26.115_f64), f2: Some(7.516_56_f64) }, AtomicScatteringFactor { energy: 0.155_439_f64, f1: Some(25.876_1_f64), f2: Some(7.095_39_f64) }, AtomicScatteringFactor { energy: 0.157_953_f64, f1: Some(25.593_8_f64), f2: Some(6.704_03_f64) }, AtomicScatteringFactor { energy: 0.160_507_f64, f1: Some(25.304_6_f64), f2: Some(6.370_63_f64) }, AtomicScatteringFactor { energy: 0.163_103_f64, f1: Some(25.011_f64), f2: Some(6.053_8_f64) }, AtomicScatteringFactor { energy: 0.165_742_f64, f1: Some(24.707_3_f64), f2: Some(5.752_74_f64) }, AtomicScatteringFactor { energy: 0.168_422_f64, f1: Some(24.388_7_f64), f2: Some(5.466_63_f64) }, AtomicScatteringFactor { energy: 0.171_146_f64, f1: Some(24.051_7_f64), f2: Some(5.194_77_f64) }, AtomicScatteringFactor { energy: 0.173_915_f64, f1: Some(23.689_2_f64), f2: Some(4.936_42_f64) }, AtomicScatteringFactor { energy: 0.176_727_f64, f1: Some(23.256_f64), f2: Some(4.690_93_f64) }, AtomicScatteringFactor { energy: 0.179_586_f64, f1: Some(22.827_5_f64), f2: Some(4.589_96_f64) }, AtomicScatteringFactor { energy: 0.182_491_f64, f1: Some(22.457_7_f64), f2: Some(4.505_14_f64) }, AtomicScatteringFactor { energy: 0.185_442_f64, f1: Some(22.111_8_f64), f2: Some(4.421_9_f64) }, AtomicScatteringFactor { energy: 0.188_442_f64, f1: Some(21.785_5_f64), f2: Some(4.336_65_f64) }, AtomicScatteringFactor { energy: 0.191_489_f64, f1: Some(21.450_8_f64), f2: Some(4.232_82_f64) }, AtomicScatteringFactor { energy: 0.194_587_f64, f1: Some(21.098_7_f64), f2: Some(4.131_48_f64) }, AtomicScatteringFactor { energy: 0.197_734_f64, f1: Some(20.726_6_f64), f2: Some(4.032_56_f64) }, AtomicScatteringFactor { energy: 0.200_932_f64, f1: Some(20.328_8_f64), f2: Some(3.949_1_f64) }, AtomicScatteringFactor { energy: 0.204_182_f64, f1: Some(19.912_1_f64), f2: Some(3.875_86_f64) }, AtomicScatteringFactor { energy: 0.207_485_f64, f1: Some(19.435_7_f64), f2: Some(3.832_58_f64) }, AtomicScatteringFactor { energy: 0.210_84_f64, f1: Some(18.967_7_f64), f2: Some(3.841_29_f64) }, AtomicScatteringFactor { energy: 0.214_251_f64, f1: Some(18.478_9_f64), f2: Some(3.881_f64) }, AtomicScatteringFactor { energy: 0.217_716_f64, f1: Some(18.005_2_f64), f2: Some(3.959_29_f64) }, AtomicScatteringFactor { energy: 0.221_237_f64, f1: Some(17.525_f64), f2: Some(4.039_17_f64) }, AtomicScatteringFactor { energy: 0.224_816_f64, f1: Some(16.998_6_f64), f2: Some(4.158_28_f64) }, AtomicScatteringFactor { energy: 0.228_452_f64, f1: Some(16.489_4_f64), f2: Some(4.334_61_f64) }, AtomicScatteringFactor { energy: 0.232_147_f64, f1: Some(15.954_6_f64), f2: Some(4.518_42_f64) }, AtomicScatteringFactor { energy: 0.235_902_f64, f1: Some(15.420_8_f64), f2: Some(4.811_45_f64) }, AtomicScatteringFactor { energy: 0.239_717_f64, f1: Some(14.916_8_f64), f2: Some(5.132_99_f64) }, AtomicScatteringFactor { energy: 0.243_595_f64, f1: Some(14.437_1_f64), f2: Some(5.482_18_f64) }, AtomicScatteringFactor { energy: 0.247_535_f64, f1: Some(13.968_7_f64), f2: Some(5.855_11_f64) }, AtomicScatteringFactor { energy: 0.251_538_f64, f1: Some(13.497_8_f64), f2: Some(6.253_43_f64) }, AtomicScatteringFactor { energy: 0.255_607_f64, f1: Some(13.031_6_f64), f2: Some(6.704_06_f64) }, AtomicScatteringFactor { energy: 0.259_741_f64, f1: Some(12.586_6_f64), f2: Some(7.196_81_f64) }, AtomicScatteringFactor { energy: 0.263_942_f64, f1: Some(12.160_4_f64), f2: Some(7.725_77_f64) }, AtomicScatteringFactor { energy: 0.268_211_f64, f1: Some(11.750_3_f64), f2: Some(8.293_61_f64) }, AtomicScatteringFactor { energy: 0.272_549_f64, f1: Some(11.354_8_f64), f2: Some(8.908_74_f64) }, AtomicScatteringFactor { energy: 0.276_957_f64, f1: Some(10.994_3_f64), f2: Some(9.582_76_f64) }, AtomicScatteringFactor { energy: 0.281_437_f64, f1: Some(10.679_7_f64), f2: Some(10.307_8_f64) }, AtomicScatteringFactor { energy: 0.285_989_f64, f1: Some(10.455_9_f64), f2: Some(11.087_7_f64) }, AtomicScatteringFactor { energy: 0.290_615_f64, f1: Some(10.285_5_f64), f2: Some(11.818_8_f64) }, AtomicScatteringFactor { energy: 0.295_315_f64, f1: Some(10.119_9_f64), f2: Some(12.573_6_f64) }, AtomicScatteringFactor { energy: 0.300_092_f64, f1: Some(9.993_3_f64), f2: Some(13.376_6_f64) }, AtomicScatteringFactor { energy: 0.304_945_f64, f1: Some(9.984_81_f64), f2: Some(14.230_9_f64) }, AtomicScatteringFactor { energy: 0.309_878_f64, f1: Some(10.037_8_f64), f2: Some(14.972_6_f64) }, AtomicScatteringFactor { energy: 0.314_89_f64, f1: Some(10.061_5_f64), f2: Some(15.705_1_f64) }, AtomicScatteringFactor { energy: 0.319_983_f64, f1: Some(10.099_7_f64), f2: Some(16.473_5_f64) }, AtomicScatteringFactor { energy: 0.325_158_f64, f1: Some(10.197_2_f64), f2: Some(17.279_4_f64) }, AtomicScatteringFactor { energy: 0.330_418_f64, f1: Some(10.408_6_f64), f2: Some(18.049_f64) }, AtomicScatteringFactor { energy: 0.335_762_f64, f1: Some(10.578_4_f64), f2: Some(18.725_3_f64) }, AtomicScatteringFactor { energy: 0.341_192_f64, f1: Some(10.730_3_f64), f2: Some(19.427_f64) }, AtomicScatteringFactor { energy: 0.346_711_f64, f1: Some(10.893_2_f64), f2: Some(20.155_f64) }, AtomicScatteringFactor { energy: 0.352_319_f64, f1: Some(11.083_7_f64), f2: Some(20.910_3_f64) }, AtomicScatteringFactor { energy: 0.358_017_f64, f1: Some(11.358_5_f64), f2: Some(21.693_9_f64) }, AtomicScatteringFactor { energy: 0.363_808_f64, f1: Some(11.658_6_f64), f2: Some(22.385_6_f64) }, AtomicScatteringFactor { energy: 0.369_692_f64, f1: Some(11.933_1_f64), f2: Some(23.079_7_f64) }, AtomicScatteringFactor { energy: 0.375_672_f64, f1: Some(12.211_8_f64), f2: Some(23.795_3_f64) }, AtomicScatteringFactor { energy: 0.381_748_f64, f1: Some(12.508_1_f64), f2: Some(24.533_1_f64) }, AtomicScatteringFactor { energy: 0.387_922_f64, f1: Some(12.831_9_f64), f2: Some(25.293_7_f64) }, AtomicScatteringFactor { energy: 0.394_197_f64, f1: Some(13.191_9_f64), f2: Some(26.078_f64) }, AtomicScatteringFactor { energy: 0.400_573_f64, f1: Some(13.599_3_f64), f2: Some(26.886_5_f64) }, AtomicScatteringFactor { energy: 0.407_052_f64, f1: Some(14.128_9_f64), f2: Some(27.712_1_f64) }, AtomicScatteringFactor { energy: 0.413_635_f64, f1: Some(14.672_3_f64), f2: Some(28.417_5_f64) }, AtomicScatteringFactor { energy: 0.420_326_f64, f1: Some(15.198_9_f64), f2: Some(29.140_8_f64) }, AtomicScatteringFactor { energy: 0.427_124_f64, f1: Some(15.750_2_f64), f2: Some(29.882_5_f64) }, AtomicScatteringFactor { energy: 0.434_032_f64, f1: Some(16.341_3_f64), f2: Some(30.643_1_f64) }, AtomicScatteringFactor { energy: 0.441_052_f64, f1: Some(16.989_2_f64), f2: Some(31.423_1_f64) }, AtomicScatteringFactor { energy: 0.448_186_f64, f1: Some(17.720_1_f64), f2: Some(32.222_9_f64) }, AtomicScatteringFactor { energy: 0.455_435_f64, f1: Some(18.639_4_f64), f2: Some(32.990_5_f64) }, AtomicScatteringFactor { energy: 0.462_802_f64, f1: Some(19.526_3_f64), f2: Some(33.557_4_f64) }, AtomicScatteringFactor { energy: 0.470_287_f64, f1: Some(20.392_5_f64), f2: Some(34.134_f64) }, AtomicScatteringFactor { energy: 0.477_894_f64, f1: Some(21.288_5_f64), f2: Some(34.720_5_f64) }, AtomicScatteringFactor { energy: 0.485_623_f64, f1: Some(22.249_4_f64), f2: Some(35.317_1_f64) }, AtomicScatteringFactor { energy: 0.493_478_f64, f1: Some(23.462_3_f64), f2: Some(35.823_3_f64) }, AtomicScatteringFactor { energy: 0.501_459_f64, f1: Some(24.587_9_f64), f2: Some(36.069_8_f64) }, AtomicScatteringFactor { energy: 0.509_57_f64, f1: Some(25.604_7_f64), f2: Some(36.318_1_f64) }, AtomicScatteringFactor { energy: 0.517_812_f64, f1: Some(26.626_3_f64), f2: Some(36.568_1_f64) }, AtomicScatteringFactor { energy: 0.526_187_f64, f1: Some(27.802_9_f64), f2: Some(36.819_8_f64) }, AtomicScatteringFactor { energy: 0.534_698_f64, f1: Some(28.943_9_f64), f2: Some(36.770_1_f64) }, AtomicScatteringFactor { energy: 0.543_346_f64, f1: Some(29.948_7_f64), f2: Some(36.696_9_f64) }, AtomicScatteringFactor { energy: 0.552_134_f64, f1: Some(30.900_3_f64), f2: Some(36.623_8_f64) }, AtomicScatteringFactor { energy: 0.561_065_f64, f1: Some(31.834_4_f64), f2: Some(36.550_9_f64) }, AtomicScatteringFactor { energy: 0.570_139_f64, f1: Some(32.796_2_f64), f2: Some(36.478_1_f64) }, AtomicScatteringFactor { energy: 0.579_361_f64, f1: Some(33.852_1_f64), f2: Some(36.257_f64) }, AtomicScatteringFactor { energy: 0.588_732_f64, f1: Some(34.768_1_f64), f2: Some(35.864_9_f64) }, AtomicScatteringFactor { energy: 0.598_254_f64, f1: Some(35.530_3_f64), f2: Some(35.476_9_f64) }, AtomicScatteringFactor { energy: 0.607_93_f64, f1: Some(36.220_7_f64), f2: Some(35.093_2_f64) }, AtomicScatteringFactor { energy: 0.617_763_f64, f1: Some(36.861_7_f64), f2: Some(34.700_2_f64) }, AtomicScatteringFactor { energy: 0.627_755_f64, f1: Some(37.42_f64), f2: Some(34.284_4_f64) }, AtomicScatteringFactor { energy: 0.637_908_f64, f1: Some(37.872_9_f64), f2: Some(33.873_7_f64) }, AtomicScatteringFactor { energy: 0.648_226_f64, f1: Some(38.198_1_f64), f2: Some(33.522_1_f64) }, AtomicScatteringFactor { energy: 0.658_711_f64, f1: Some(38.526_7_f64), f2: Some(33.294_f64) }, AtomicScatteringFactor { energy: 0.669_365_f64, f1: Some(38.848_f64), f2: Some(33.078_6_f64) }, AtomicScatteringFactor { energy: 0.680_191_f64, f1: Some(39.129_2_f64), f2: Some(32.896_8_f64) }, AtomicScatteringFactor { energy: 0.691_193_f64, f1: Some(39.363_6_f64), f2: Some(32.747_8_f64) }, AtomicScatteringFactor { energy: 0.702_372_f64, f1: Some(39.488_1_f64), f2: Some(32.661_4_f64) }, AtomicScatteringFactor { energy: 0.713_733_f64, f1: Some(39.577_f64), f2: Some(32.829_4_f64) }, AtomicScatteringFactor { energy: 0.725_277_f64, f1: Some(39.873_f64), f2: Some(33.176_6_f64) }, AtomicScatteringFactor { energy: 0.737_008_f64, f1: Some(40.327_f64), f2: Some(33.527_4_f64) }, AtomicScatteringFactor { energy: 0.748_928_f64, f1: Some(40.908_4_f64), f2: Some(33.881_9_f64) }, AtomicScatteringFactor { energy: 0.761_042_f64, f1: Some(41.648_6_f64), f2: Some(34.231_2_f64) }, AtomicScatteringFactor { energy: 0.773_351_f64, f1: Some(42.610_7_f64), f2: Some(34.487_5_f64) }, AtomicScatteringFactor { energy: 0.785_859_f64, f1: Some(43.700_1_f64), f2: Some(34.432_8_f64) }, AtomicScatteringFactor { energy: 0.798_57_f64, f1: Some(44.583_4_f64), f2: Some(34.120_8_f64) }, AtomicScatteringFactor { energy: 0.811_486_f64, f1: Some(45.329_9_f64), f2: Some(33.811_9_f64) }, AtomicScatteringFactor { energy: 0.824_611_f64, f1: Some(46.008_5_f64), f2: Some(33.505_7_f64) }, AtomicScatteringFactor { energy: 0.837_949_f64, f1: Some(46.646_6_f64), f2: Some(33.202_2_f64) }, AtomicScatteringFactor { energy: 0.851_502_f64, f1: Some(47.255_1_f64), f2: Some(32.885_2_f64) }, AtomicScatteringFactor { energy: 0.865_274_f64, f1: Some(47.831_7_f64), f2: Some(32.550_4_f64) }, AtomicScatteringFactor { energy: 0.879_269_f64, f1: Some(48.356_9_f64), f2: Some(32.200_6_f64) }, AtomicScatteringFactor { energy: 0.893_491_f64, f1: Some(48.835_8_f64), f2: Some(31.854_7_f64) }, AtomicScatteringFactor { energy: 0.907_943_f64, f1: Some(49.266_3_f64), f2: Some(31.512_3_f64) }, AtomicScatteringFactor { energy: 0.922_628_f64, f1: Some(49.600_9_f64), f2: Some(31.173_5_f64) }, AtomicScatteringFactor { energy: 0.937_551_f64, f1: Some(49.927_f64), f2: Some(31.008_6_f64) }, AtomicScatteringFactor { energy: 0.952_715_f64, f1: Some(50.295_2_f64), f2: Some(30.890_6_f64) }, AtomicScatteringFactor { energy: 0.968_124_f64, f1: Some(50.745_5_f64), f2: Some(30.813_4_f64) }, AtomicScatteringFactor { energy: 0.983_783_f64, f1: Some(51.269_3_f64), f2: Some(30.736_3_f64) }, AtomicScatteringFactor { energy: 0.999_695_f64, f1: Some(51.878_5_f64), f2: Some(30.628_9_f64) }, AtomicScatteringFactor { energy: 1.015_86_f64, f1: Some(52.622_4_f64), f2: Some(30.489_4_f64) }, AtomicScatteringFactor { energy: 1.032_29_f64, f1: Some(53.303_8_f64), f2: Some(30.038_8_f64) }, AtomicScatteringFactor { energy: 1.048_99_f64, f1: Some(53.876_1_f64), f2: Some(29.584_6_f64) }, AtomicScatteringFactor { energy: 1.065_96_f64, f1: Some(54.368_2_f64), f2: Some(29.129_f64) }, AtomicScatteringFactor { energy: 1.083_2_f64, f1: Some(54.813_f64), f2: Some(28.679_7_f64) }, AtomicScatteringFactor { energy: 1.100_72_f64, f1: Some(55.221_8_f64), f2: Some(28.237_1_f64) }, AtomicScatteringFactor { energy: 1.118_52_f64, f1: Some(55.601_f64), f2: Some(27.801_f64) }, AtomicScatteringFactor { energy: 1.136_61_f64, f1: Some(55.954_7_f64), f2: Some(27.371_f64) }, AtomicScatteringFactor { energy: 1.155_f64, f1: Some(56.286_f64), f2: Some(26.947_5_f64) }, AtomicScatteringFactor { energy: 1.173_68_f64, f1: Some(56.597_4_f64), f2: Some(26.530_3_f64) }, AtomicScatteringFactor { energy: 1.192_66_f64, f1: Some(56.890_4_f64), f2: Some(26.119_1_f64) }, AtomicScatteringFactor { energy: 1.211_95_f64, f1: Some(57.167_f64), f2: Some(25.713_8_f64) }, AtomicScatteringFactor { energy: 1.231_55_f64, f1: Some(57.428_1_f64), f2: Some(25.314_3_f64) }, AtomicScatteringFactor { energy: 1.251_47_f64, f1: Some(57.674_2_f64), f2: Some(24.920_2_f64) }, AtomicScatteringFactor { energy: 1.271_72_f64, f1: Some(57.906_5_f64), f2: Some(24.531_9_f64) }, AtomicScatteringFactor { energy: 1.292_29_f64, f1: Some(58.125_8_f64), f2: Some(24.149_5_f64) }, AtomicScatteringFactor { energy: 1.313_19_f64, f1: Some(58.333_f64), f2: Some(23.772_6_f64) }, AtomicScatteringFactor { energy: 1.334_43_f64, f1: Some(58.528_9_f64), f2: Some(23.401_1_f64) }, AtomicScatteringFactor { energy: 1.356_01_f64, f1: Some(58.713_7_f64), f2: Some(23.034_7_f64) }, AtomicScatteringFactor { energy: 1.377_94_f64, f1: Some(58.887_9_f64), f2: Some(22.673_6_f64) }, AtomicScatteringFactor { energy: 1.400_23_f64, f1: Some(59.052_4_f64), f2: Some(22.317_8_f64) }, AtomicScatteringFactor { energy: 1.422_88_f64, f1: Some(59.208_4_f64), f2: Some(21.967_2_f64) }, AtomicScatteringFactor { energy: 1.445_89_f64, f1: Some(59.357_3_f64), f2: Some(21.621_3_f64) }, AtomicScatteringFactor { energy: 1.469_28_f64, f1: Some(59.502_f64), f2: Some(21.277_f64) }, AtomicScatteringFactor { energy: 1.493_04_f64, f1: Some(59.643_4_f64), f2: Some(20.932_5_f64) }, AtomicScatteringFactor { energy: 1.517_19_f64, f1: Some(59.769_2_f64), f2: Some(20.572_1_f64) }, AtomicScatteringFactor { energy: 1.541_73_f64, f1: Some(59.875_1_f64), f2: Some(20.214_6_f64) }, AtomicScatteringFactor { energy: 1.566_67_f64, f1: Some(59.963_5_f64), f2: Some(19.862_6_f64) }, AtomicScatteringFactor { energy: 1.592_01_f64, f1: Some(60.037_7_f64), f2: Some(19.515_9_f64) }, AtomicScatteringFactor { energy: 1.617_76_f64, f1: Some(60.098_4_f64), f2: Some(19.175_1_f64) }, AtomicScatteringFactor { energy: 1.643_92_f64, f1: Some(60.147_1_f64), f2: Some(18.840_2_f64) }, AtomicScatteringFactor { energy: 1.670_51_f64, f1: Some(60.184_f64), f2: Some(18.510_2_f64) }, AtomicScatteringFactor { energy: 1.697_53_f64, f1: Some(60.209_3_f64), f2: Some(18.185_5_f64) }, AtomicScatteringFactor { energy: 1.724_99_f64, f1: Some(60.230_3_f64), f2: Some(17.866_f64) }, AtomicScatteringFactor { energy: 1.752_89_f64, f1: Some(60.237_9_f64), f2: Some(17.537_6_f64) }, AtomicScatteringFactor { energy: 1.781_24_f64, f1: Some(60.225_7_f64), f2: Some(17.210_3_f64) }, AtomicScatteringFactor { energy: 1.810_05_f64, f1: Some(60.194_4_f64), f2: Some(16.885_6_f64) }, AtomicScatteringFactor { energy: 1.839_32_f64, f1: Some(60.143_5_f64), f2: Some(16.566_f64) }, AtomicScatteringFactor { energy: 1.869_07_f64, f1: Some(60.074_4_f64), f2: Some(16.252_1_f64) }, AtomicScatteringFactor { energy: 1.899_3_f64, f1: Some(59.986_9_f64), f2: Some(15.944_f64) }, AtomicScatteringFactor { energy: 1.930_02_f64, f1: Some(59.880_9_f64), f2: Some(15.641_7_f64) }, AtomicScatteringFactor { energy: 1.961_24_f64, f1: Some(59.755_6_f64), f2: Some(15.344_6_f64) }, AtomicScatteringFactor { energy: 1.992_96_f64, f1: Some(59.606_6_f64), f2: Some(15.052_2_f64) }, AtomicScatteringFactor { energy: 2.025_2_f64, f1: Some(59.446_7_f64), f2: Some(14.774_1_f64) }, AtomicScatteringFactor { energy: 2.057_95_f64, f1: Some(59.264_8_f64), f2: Some(14.483_2_f64) }, AtomicScatteringFactor { energy: 2.091_24_f64, f1: Some(59.048_6_f64), f2: Some(14.194_6_f64) }, AtomicScatteringFactor { energy: 2.125_06_f64, f1: Some(58.800_2_f64), f2: Some(13.910_2_f64) }, AtomicScatteringFactor { energy: 2.159_43_f64, f1: Some(58.515_6_f64), f2: Some(13.628_4_f64) }, AtomicScatteringFactor { energy: 2.194_36_f64, f1: Some(58.190_9_f64), f2: Some(13.351_1_f64) }, AtomicScatteringFactor { energy: 2.229_85_f64, f1: Some(57.820_1_f64), f2: Some(13.076_5_f64) }, AtomicScatteringFactor { energy: 2.265_92_f64, f1: Some(57.395_6_f64), f2: Some(12.805_6_f64) }, AtomicScatteringFactor { energy: 2.302_57_f64, f1: Some(56.907_8_f64), f2: Some(12.538_2_f64) }, AtomicScatteringFactor { energy: 2.339_81_f64, f1: Some(56.344_f64), f2: Some(12.274_3_f64) }, AtomicScatteringFactor { energy: 2.377_66_f64, f1: Some(55.686_6_f64), f2: Some(12.014_f64) }, AtomicScatteringFactor { energy: 2.416_11_f64, f1: Some(54.910_8_f64), f2: Some(11.757_f64) }, AtomicScatteringFactor { energy: 2.455_19_f64, f1: Some(53.979_5_f64), f2: Some(11.503_4_f64) }, AtomicScatteringFactor { energy: 2.494_9_f64, f1: Some(52.835_1_f64), f2: Some(11.253_5_f64) }, AtomicScatteringFactor { energy: 2.535_26_f64, f1: Some(51.378_2_f64), f2: Some(11.006_9_f64) }, AtomicScatteringFactor { energy: 2.576_26_f64, f1: Some(49.413_5_f64), f2: Some(10.763_8_f64) }, AtomicScatteringFactor { energy: 2.617_93_f64, f1: Some(46.458_9_f64), f2: Some(10.524_2_f64) }, AtomicScatteringFactor { energy: 2.660_27_f64, f1: Some(40.424_5_f64), f2: Some(10.288_2_f64) }, AtomicScatteringFactor { energy: 2.682_9_f64, f1: Some(11.504_5_f64), f2: Some(10.165_8_f64) }, AtomicScatteringFactor { energy: 2.683_1_f64, f1: Some(11.508_5_f64), f2: Some(26.829_1_f64) }, AtomicScatteringFactor { energy: 2.703_3_f64, f1: Some(39.208_6_f64), f2: Some(26.527_1_f64) }, AtomicScatteringFactor { energy: 2.747_03_f64, f1: Some(43.59_f64), f2: Some(25.892_5_f64) }, AtomicScatteringFactor { energy: 2.791_46_f64, f1: Some(39.460_7_f64), f2: Some(25.273_7_f64) }, AtomicScatteringFactor { energy: 2.797_9_f64, f1: Some(24.754_f64), f2: Some(25.186_f64) }, AtomicScatteringFactor { energy: 2.798_1_f64, f1: Some(24.767_7_f64), f2: Some(36.536_1_f64) }, AtomicScatteringFactor { energy: 2.836_61_f64, f1: Some(48.203_6_f64), f2: Some(35.786_8_f64) }, AtomicScatteringFactor { energy: 2.882_49_f64, f1: Some(52.681_1_f64), f2: Some(34.926_7_f64) }, AtomicScatteringFactor { energy: 2.929_11_f64, f1: Some(55.530_6_f64), f2: Some(34.087_f64) }, AtomicScatteringFactor { energy: 2.976_48_f64, f1: Some(57.634_4_f64), f2: Some(33.269_f64) }, AtomicScatteringFactor { energy: 3.024_63_f64, f1: Some(59.271_5_f64), f2: Some(32.471_f64) }, AtomicScatteringFactor { energy: 3.073_55_f64, f1: Some(60.565_1_f64), f2: Some(31.694_2_f64) }, AtomicScatteringFactor { energy: 3.123_26_f64, f1: Some(61.568_8_f64), f2: Some(30.936_7_f64) }, AtomicScatteringFactor { energy: 3.173_78_f64, f1: Some(62.281_7_f64), f2: Some(30.198_4_f64) }, AtomicScatteringFactor { energy: 3.225_11_f64, f1: Some(62.605_3_f64), f2: Some(29.477_5_f64) }, AtomicScatteringFactor { energy: 3.277_27_f64, f1: Some(61.978_6_f64), f2: Some(28.775_4_f64) }, AtomicScatteringFactor { energy: 3.301_8_f64, f1: Some(54.617_9_f64), f2: Some(28.454_8_f64) }, AtomicScatteringFactor { energy: 3.302_f64, f1: Some(54.630_5_f64), f2: Some(33.050_9_f64) }, AtomicScatteringFactor { energy: 3.330_28_f64, f1: Some(63.058_8_f64), f2: Some(32.633_6_f64) }, AtomicScatteringFactor { energy: 3.384_15_f64, f1: Some(65.393_6_f64), f2: Some(31.863_f64) }, AtomicScatteringFactor { energy: 3.438_88_f64, f1: Some(66.818_5_f64), f2: Some(31.111_8_f64) }, AtomicScatteringFactor { energy: 3.494_5_f64, f1: Some(67.909_f64), f2: Some(30.378_5_f64) }, AtomicScatteringFactor { energy: 3.551_02_f64, f1: Some(68.798_3_f64), f2: Some(29.664_8_f64) }, AtomicScatteringFactor { energy: 3.608_46_f64, f1: Some(69.538_4_f64), f2: Some(28.968_4_f64) }, AtomicScatteringFactor { energy: 3.666_82_f64, f1: Some(70.148_2_f64), f2: Some(28.289_f64) }, AtomicScatteringFactor { energy: 3.726_13_f64, f1: Some(70.621_9_f64), f2: Some(27.626_3_f64) }, AtomicScatteringFactor { energy: 3.786_4_f64, f1: Some(70.899_5_f64), f2: Some(26.981_f64) }, AtomicScatteringFactor { energy: 3.847_64_f64, f1: Some(70.264_8_f64), f2: Some(26.351_6_f64) }, AtomicScatteringFactor { energy: 3.854_f64, f1: Some(68.232_6_f64), f2: Some(26.287_6_f64) }, AtomicScatteringFactor { energy: 3.854_2_f64, f1: Some(68.239_7_f64), f2: Some(27.883_4_f64) }, AtomicScatteringFactor { energy: 3.909_87_f64, f1: Some(71.850_1_f64), f2: Some(27.293_1_f64) }, AtomicScatteringFactor { energy: 3.973_11_f64, f1: Some(72.64_f64), f2: Some(26.647_4_f64) }, AtomicScatteringFactor { energy: 4.037_38_f64, f1: Some(73.170_7_f64), f2: Some(26.016_8_f64) }, AtomicScatteringFactor { energy: 4.102_68_f64, f1: Some(74.136_6_f64), f2: Some(25.401_1_f64) }, AtomicScatteringFactor { energy: 4.149_3_f64, f1: Some(72.250_9_f64), f2: Some(24.976_1_f64) }, AtomicScatteringFactor { energy: 4.149_5_f64, f1: Some(72.258_6_f64), f2: Some(26.007_5_f64) }, AtomicScatteringFactor { energy: 4.169_03_f64, f1: Some(73.683_1_f64), f2: Some(25.838_5_f64) }, AtomicScatteringFactor { energy: 4.236_46_f64, f1: Some(74.599_2_f64), f2: Some(25.269_7_f64) }, AtomicScatteringFactor { energy: 4.304_98_f64, f1: Some(75.204_5_f64), f2: Some(24.709_4_f64) }, AtomicScatteringFactor { energy: 4.374_62_f64, f1: Some(75.707_9_f64), f2: Some(24.157_6_f64) }, AtomicScatteringFactor { energy: 4.445_37_f64, f1: Some(76.149_2_f64), f2: Some(23.617_2_f64) }, AtomicScatteringFactor { energy: 4.517_27_f64, f1: Some(76.545_9_f64), f2: Some(23.086_5_f64) }, AtomicScatteringFactor { energy: 4.590_33_f64, f1: Some(76.906_8_f64), f2: Some(22.565_4_f64) }, AtomicScatteringFactor { energy: 4.664_58_f64, f1: Some(77.236_6_f64), f2: Some(22.052_9_f64) }, AtomicScatteringFactor { energy: 4.740_03_f64, f1: Some(77.538_1_f64), f2: Some(21.549_7_f64) }, AtomicScatteringFactor { energy: 4.816_69_f64, f1: Some(77.815_1_f64), f2: Some(21.056_6_f64) }, AtomicScatteringFactor { energy: 4.894_6_f64, f1: Some(78.070_4_f64), f2: Some(20.573_f64) }, AtomicScatteringFactor { energy: 4.973_77_f64, f1: Some(78.305_6_f64), f2: Some(20.098_5_f64) }, AtomicScatteringFactor { energy: 5.054_21_f64, f1: Some(78.522_1_f64), f2: Some(19.633_5_f64) }, AtomicScatteringFactor { energy: 5.135_96_f64, f1: Some(78.721_5_f64), f2: Some(19.177_6_f64) }, AtomicScatteringFactor { energy: 5.219_03_f64, f1: Some(78.905_1_f64), f2: Some(18.730_7_f64) }, AtomicScatteringFactor { energy: 5.303_44_f64, f1: Some(79.073_7_f64), f2: Some(18.292_7_f64) }, AtomicScatteringFactor { energy: 5.389_22_f64, f1: Some(79.228_3_f64), f2: Some(17.863_7_f64) }, AtomicScatteringFactor { energy: 5.476_39_f64, f1: Some(79.37_f64), f2: Some(17.443_5_f64) }, AtomicScatteringFactor { energy: 5.564_97_f64, f1: Some(79.499_4_f64), f2: Some(17.032_f64) }, AtomicScatteringFactor { energy: 5.654_98_f64, f1: Some(79.617_2_f64), f2: Some(16.629_f64) }, AtomicScatteringFactor { energy: 5.746_44_f64, f1: Some(79.724_2_f64), f2: Some(16.234_6_f64) }, AtomicScatteringFactor { energy: 5.839_39_f64, f1: Some(79.820_8_f64), f2: Some(15.848_6_f64) }, AtomicScatteringFactor { energy: 5.933_83_f64, f1: Some(79.907_9_f64), f2: Some(15.470_9_f64) }, AtomicScatteringFactor { energy: 6.029_81_f64, f1: Some(79.985_9_f64), f2: Some(15.101_3_f64) }, AtomicScatteringFactor { energy: 6.127_33_f64, f1: Some(80.055_1_f64), f2: Some(14.739_6_f64) }, AtomicScatteringFactor { energy: 6.226_44_f64, f1: Some(80.116_f64), f2: Some(14.385_8_f64) }, AtomicScatteringFactor { energy: 6.327_15_f64, f1: Some(80.169_3_f64), f2: Some(14.040_1_f64) }, AtomicScatteringFactor { energy: 6.429_48_f64, f1: Some(80.215_3_f64), f2: Some(13.701_7_f64) }, AtomicScatteringFactor { energy: 6.533_48_f64, f1: Some(80.254_f64), f2: Some(13.370_9_f64) }, AtomicScatteringFactor { energy: 6.639_15_f64, f1: Some(80.286_1_f64), f2: Some(13.047_6_f64) }, AtomicScatteringFactor { energy: 6.746_54_f64, f1: Some(80.311_7_f64), f2: Some(12.731_6_f64) }, AtomicScatteringFactor { energy: 6.855_65_f64, f1: Some(80.331_4_f64), f2: Some(12.422_9_f64) }, AtomicScatteringFactor { energy: 6.966_54_f64, f1: Some(80.345_4_f64), f2: Some(12.121_1_f64) }, AtomicScatteringFactor { energy: 7.079_22_f64, f1: Some(80.353_7_f64), f2: Some(11.825_9_f64) }, AtomicScatteringFactor { energy: 7.193_72_f64, f1: Some(80.356_7_f64), f2: Some(11.538_f64) }, AtomicScatteringFactor { energy: 7.310_07_f64, f1: Some(80.354_8_f64), f2: Some(11.256_4_f64) }, AtomicScatteringFactor { energy: 7.428_31_f64, f1: Some(80.347_8_f64), f2: Some(10.981_4_f64) }, AtomicScatteringFactor { energy: 7.548_45_f64, f1: Some(80.336_f64), f2: Some(10.713_f64) }, AtomicScatteringFactor { energy: 7.670_54_f64, f1: Some(80.320_1_f64), f2: Some(10.450_9_f64) }, AtomicScatteringFactor { energy: 7.794_61_f64, f1: Some(80.299_7_f64), f2: Some(10.194_8_f64) }, AtomicScatteringFactor { energy: 7.920_68_f64, f1: Some(80.275_f64), f2: Some(9.944_71_f64) }, AtomicScatteringFactor { energy: 8.048_79_f64, f1: Some(80.246_2_f64), f2: Some(9.700_51_f64) }, AtomicScatteringFactor { energy: 8.178_98_f64, f1: Some(80.213_3_f64), f2: Some(9.462_18_f64) }, AtomicScatteringFactor { energy: 8.311_26_f64, f1: Some(80.176_6_f64), f2: Some(9.229_46_f64) }, AtomicScatteringFactor { energy: 8.445_69_f64, f1: Some(80.136_f64), f2: Some(9.002_26_f64) }, AtomicScatteringFactor { energy: 8.582_29_f64, f1: Some(80.091_6_f64), f2: Some(8.780_71_f64) }, AtomicScatteringFactor { energy: 8.721_11_f64, f1: Some(80.043_5_f64), f2: Some(8.564_15_f64) }, AtomicScatteringFactor { energy: 8.862_16_f64, f1: Some(79.991_6_f64), f2: Some(8.353_12_f64) }, AtomicScatteringFactor { energy: 9.005_5_f64, f1: Some(79.936_1_f64), f2: Some(8.146_86_f64) }, AtomicScatteringFactor { energy: 9.151_16_f64, f1: Some(79.876_7_f64), f2: Some(7.945_77_f64) }, AtomicScatteringFactor { energy: 9.299_17_f64, f1: Some(79.813_9_f64), f2: Some(7.749_59_f64) }, AtomicScatteringFactor { energy: 9.449_58_f64, f1: Some(79.747_5_f64), f2: Some(7.558_f64) }, AtomicScatteringFactor { energy: 9.602_42_f64, f1: Some(79.677_5_f64), f2: Some(7.371_03_f64) }, AtomicScatteringFactor { energy: 9.757_73_f64, f1: Some(79.604_f64), f2: Some(7.188_94_f64) }, AtomicScatteringFactor { energy: 9.915_55_f64, f1: Some(79.533_9_f64), f2: Some(7.011_03_f64) }, AtomicScatteringFactor { energy: 10.075_9_f64, f1: Some(79.459_2_f64), f2: Some(6.821_41_f64) }, AtomicScatteringFactor { energy: 10.238_9_f64, f1: Some(79.365_f64), f2: Some(6.637_38_f64) }, AtomicScatteringFactor { energy: 10.404_5_f64, f1: Some(79.263_1_f64), f2: Some(6.458_81_f64) }, AtomicScatteringFactor { energy: 10.572_8_f64, f1: Some(79.152_3_f64), f2: Some(6.285_58_f64) }, AtomicScatteringFactor { energy: 10.743_8_f64, f1: Some(79.032_7_f64), f2: Some(6.117_59_f64) }, AtomicScatteringFactor { energy: 10.917_6_f64, f1: Some(78.903_7_f64), f2: Some(5.954_72_f64) }, AtomicScatteringFactor { energy: 11.094_2_f64, f1: Some(78.764_6_f64), f2: Some(5.796_85_f64) }, AtomicScatteringFactor { energy: 11.273_6_f64, f1: Some(78.614_3_f64), f2: Some(5.643_88_f64) }, AtomicScatteringFactor { energy: 11.455_9_f64, f1: Some(78.451_4_f64), f2: Some(5.495_69_f64) }, AtomicScatteringFactor { energy: 11.641_2_f64, f1: Some(78.274_f64), f2: Some(5.352_17_f64) }, AtomicScatteringFactor { energy: 11.829_5_f64, f1: Some(78.079_6_f64), f2: Some(5.213_2_f64) }, AtomicScatteringFactor { energy: 12.020_8_f64, f1: Some(77.864_6_f64), f2: Some(5.078_69_f64) }, AtomicScatteringFactor { energy: 12.215_3_f64, f1: Some(77.624_3_f64), f2: Some(4.948_51_f64) }, AtomicScatteringFactor { energy: 12.412_8_f64, f1: Some(77.351_6_f64), f2: Some(4.822_58_f64) }, AtomicScatteringFactor { energy: 12.613_6_f64, f1: Some(77.036_2_f64), f2: Some(4.700_77_f64) }, AtomicScatteringFactor { energy: 12.817_6_f64, f1: Some(76.661_4_f64), f2: Some(4.583_f64) }, AtomicScatteringFactor { energy: 13.025_f64, f1: Some(76.198_f64), f2: Some(4.469_15_f64) }, AtomicScatteringFactor { energy: 13.235_6_f64, f1: Some(75.588_4_f64), f2: Some(4.359_12_f64) }, AtomicScatteringFactor { energy: 13.449_7_f64, f1: Some(74.689_6_f64), f2: Some(4.252_82_f64) }, AtomicScatteringFactor { energy: 13.667_2_f64, f1: Some(72.926_6_f64), f2: Some(4.150_14_f64) }, AtomicScatteringFactor { energy: 13.813_7_f64, f1: Some(58.490_1_f64), f2: Some(4.083_31_f64) }, AtomicScatteringFactor { energy: 13.813_9_f64, f1: Some(58.490_6_f64), f2: Some(10.337_9_f64) }, AtomicScatteringFactor { energy: 13.888_3_f64, f1: Some(71.717_1_f64), f2: Some(10.242_8_f64) }, AtomicScatteringFactor { energy: 14.112_9_f64, f1: Some(74.522_6_f64), f2: Some(9.963_77_f64) }, AtomicScatteringFactor { energy: 14.341_2_f64, f1: Some(75.621_3_f64), f2: Some(9.692_4_f64) }, AtomicScatteringFactor { energy: 14.573_1_f64, f1: Some(76.269_4_f64), f2: Some(9.428_41_f64) }, AtomicScatteringFactor { energy: 14.808_9_f64, f1: Some(76.685_6_f64), f2: Some(9.171_63_f64) }, AtomicScatteringFactor { energy: 15.048_4_f64, f1: Some(76.944_f64), f2: Some(8.921_83_f64) }, AtomicScatteringFactor { energy: 15.291_8_f64, f1: Some(77.069_9_f64), f2: Some(8.678_85_f64) }, AtomicScatteringFactor { energy: 15.539_1_f64, f1: Some(77.056_7_f64), f2: Some(8.442_5_f64) }, AtomicScatteringFactor { energy: 15.790_4_f64, f1: Some(76.850_1_f64), f2: Some(8.212_57_f64) }, AtomicScatteringFactor { energy: 16.045_8_f64, f1: Some(76.224_3_f64), f2: Some(7.988_92_f64) }, AtomicScatteringFactor { energy: 16.244_2_f64, f1: Some(68.989_9_f64), f2: Some(7.821_79_f64) }, AtomicScatteringFactor { energy: 16.244_4_f64, f1: Some(68.990_7_f64), f2: Some(10.927_4_f64) }, AtomicScatteringFactor { energy: 16.305_4_f64, f1: Some(75.185_f64), f2: Some(10.868_8_f64) }, AtomicScatteringFactor { energy: 16.569_1_f64, f1: Some(76.843_2_f64), f2: Some(10.621_8_f64) }, AtomicScatteringFactor { energy: 16.837_1_f64, f1: Some(77.109_4_f64), f2: Some(10.380_3_f64) }, AtomicScatteringFactor { energy: 16.939_2_f64, f1: Some(74.409_7_f64), f2: Some(10.290_8_f64) }, AtomicScatteringFactor { energy: 16.939_4_f64, f1: Some(74.410_2_f64), f2: Some(11.621_f64) }, AtomicScatteringFactor { energy: 17.109_4_f64, f1: Some(77.903_6_f64), f2: Some(11.461_6_f64) }, AtomicScatteringFactor { energy: 17.386_1_f64, f1: Some(78.762_1_f64), f2: Some(11.210_1_f64) }, AtomicScatteringFactor { energy: 17.667_4_f64, f1: Some(79.342_9_f64), f2: Some(10.961_7_f64) }, AtomicScatteringFactor { energy: 17.953_1_f64, f1: Some(79.803_7_f64), f2: Some(10.716_4_f64) }, AtomicScatteringFactor { energy: 18.243_5_f64, f1: Some(80.190_6_f64), f2: Some(10.474_5_f64) }, AtomicScatteringFactor { energy: 18.538_6_f64, f1: Some(80.524_9_f64), f2: Some(10.236_f64) }, AtomicScatteringFactor { energy: 18.838_4_f64, f1: Some(80.819_1_f64), f2: Some(10.000_9_f64) }, AtomicScatteringFactor { energy: 19.143_1_f64, f1: Some(81.081_1_f64), f2: Some(9.769_48_f64) }, AtomicScatteringFactor { energy: 19.452_7_f64, f1: Some(81.316_1_f64), f2: Some(9.541_66_f64) }, AtomicScatteringFactor { energy: 19.767_4_f64, f1: Some(81.528_4_f64), f2: Some(9.317_52_f64) }, AtomicScatteringFactor { energy: 20.087_1_f64, f1: Some(81.720_9_f64), f2: Some(9.097_13_f64) }, AtomicScatteringFactor { energy: 20.412_f64, f1: Some(81.896_1_f64), f2: Some(8.880_5_f64) }, AtomicScatteringFactor { energy: 20.742_1_f64, f1: Some(82.055_9_f64), f2: Some(8.667_67_f64) }, AtomicScatteringFactor { energy: 21.077_6_f64, f1: Some(82.201_9_f64), f2: Some(8.458_65_f64) }, AtomicScatteringFactor { energy: 21.418_5_f64, f1: Some(82.335_4_f64), f2: Some(8.253_46_f64) }, AtomicScatteringFactor { energy: 21.765_f64, f1: Some(82.457_6_f64), f2: Some(8.052_11_f64) }, AtomicScatteringFactor { energy: 22.117_f64, f1: Some(82.569_4_f64), f2: Some(7.854_6_f64) }, AtomicScatteringFactor { energy: 22.474_7_f64, f1: Some(82.671_8_f64), f2: Some(7.660_92_f64) }, AtomicScatteringFactor { energy: 22.838_2_f64, f1: Some(82.765_5_f64), f2: Some(7.471_05_f64) }, AtomicScatteringFactor { energy: 23.207_6_f64, f1: Some(82.851_1_f64), f2: Some(7.284_99_f64) }, AtomicScatteringFactor { energy: 23.583_f64, f1: Some(82.929_3_f64), f2: Some(7.102_71_f64) }, AtomicScatteringFactor { energy: 23.964_4_f64, f1: Some(83.000_6_f64), f2: Some(6.924_19_f64) }, AtomicScatteringFactor { energy: 24.352_f64, f1: Some(83.065_4_f64), f2: Some(6.749_39_f64) }, AtomicScatteringFactor { energy: 24.745_9_f64, f1: Some(83.124_3_f64), f2: Some(6.578_3_f64) }, AtomicScatteringFactor { energy: 25.146_2_f64, f1: Some(83.177_6_f64), f2: Some(6.410_87_f64) }, AtomicScatteringFactor { energy: 25.552_9_f64, f1: Some(83.225_8_f64), f2: Some(6.247_08_f64) }, AtomicScatteringFactor { energy: 25.966_2_f64, f1: Some(83.269_1_f64), f2: Some(6.086_87_f64) }, AtomicScatteringFactor { energy: 26.386_1_f64, f1: Some(83.307_8_f64), f2: Some(5.930_21_f64) }, AtomicScatteringFactor { energy: 26.812_9_f64, f1: Some(83.342_3_f64), f2: Some(5.777_05_f64) }, AtomicScatteringFactor { energy: 27.246_6_f64, f1: Some(83.372_8_f64), f2: Some(5.627_35_f64) }, AtomicScatteringFactor { energy: 27.687_3_f64, f1: Some(83.399_7_f64), f2: Some(5.481_07_f64) }, AtomicScatteringFactor { energy: 28.135_1_f64, f1: Some(83.423_f64), f2: Some(5.338_14_f64) }, AtomicScatteringFactor { energy: 28.590_2_f64, f1: Some(83.443_f64), f2: Some(5.198_53_f64) }, AtomicScatteringFactor { energy: 29.052_6_f64, f1: Some(83.46_f64), f2: Some(5.062_18_f64) }, AtomicScatteringFactor { energy: 29.522_5_f64, f1: Some(83.474_2_f64), f2: Some(4.929_04_f64) }, AtomicScatteringFactor { energy: 30.0_f64, f1: Some(83.485_6_f64), f2: Some(4.799_06_f64) }, ] }), neutron_scattering: None, isotopes: vec![ Isotope { mass_number: 190, mass: UncertainFloat::new(189.995_11_f64, 0.000_51_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 191, mass: UncertainFloat::new(190.994_65_f64, 0.000_32_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 192, mass: UncertainFloat::new(191.991_52_f64, 0.000_22_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 193, mass: UncertainFloat::new(192.991_1_f64, 0.003_0_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 194, mass: UncertainFloat::new(193.988_28_f64, 0.000_22_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 195, mass: UncertainFloat::new(194.988_05_f64, 0.000_24_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 196, mass: UncertainFloat::new(195.985_51_f64, 0.000_19_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 197, mass: UncertainFloat::new(196.985_57_f64, 0.000_21_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 198, mass: UncertainFloat::new(197.983_34_f64, 0.000_16_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 199, mass: UncertainFloat::new(198.983_6_f64, 0.004_4_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 200, mass: UncertainFloat::new(199.981_74_f64, 0.000_15_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 201, mass: UncertainFloat::new(200.982_21_f64, 0.000_11_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 202, mass: UncertainFloat::new(201.980_7_f64, 0.001_0_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 203, mass: UncertainFloat::new(202.981_41_f64, 0.000_70_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 204, mass: UncertainFloat::new(203.980_307_f64, 0.000_014_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 205, mass: UncertainFloat::new(204.981_17_f64, 0.000_30_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 206, mass: UncertainFloat::new(205.980_465_f64, 0.000_011_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 207, mass: UncertainFloat::new(206.981_578_f64, 0.000_008_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 208, mass: UncertainFloat::new(207.981_231_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 209, mass: UncertainFloat::new(208.982_416_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 210, mass: UncertainFloat::new(209.982_857_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 211, mass: UncertainFloat::new(210.986_637_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 212, mass: UncertainFloat::new(211.988_852_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 213, mass: UncertainFloat::new(212.992_843_f64, 0.000_004_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 214, mass: UncertainFloat::new(213.995_186_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 215, mass: UncertainFloat::new(214.999_415_f64, 0.000_003_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 216, mass: UncertainFloat::new(216.001_905_2_f64, 0.000_002_9_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 217, mass: UncertainFloat::new(217.006_25_f64, 0.000_11_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, Isotope { mass_number: 218, mass: UncertainFloat::new(218.008_965_8_f64, 0.000_002_7_f64), abundance: UncertainFloat::new(0.0, 0.0), xray_scattering: None, neutron_scattering: None }, ] } }
89.677463
117
0.624596
611d22afcbdde19edcb34b7ab7c58969619df721
1,646
use alga::general::Real; use super::super::Limiter; #[allow(dead_code)] pub struct AngularLimiter<T: Real> { max_angular_acceleration: T, max_angular_speed: T, } impl<T: Real> Limiter<T> for AngularLimiter<T> { fn get_zero_linear_speed_threshold(&self) -> T { unreachable!("get_zero_linear_speed_threshold is not implemented for AngularLimiter"); } #[allow(unused)] fn set_zero_linear_speed_threshold(&mut self, speed_threshold: T) { unreachable!("set_zero_linear_speed_threshold is not implemented for AngularLimiter"); } fn get_max_linear_speed(&self) -> T { unreachable!("get_max_linear_speed is not implmented for AngularLimiter"); } #[allow(unused)] fn set_max_linear_speed(&mut self, linear_speed: T) { unreachable!("set_max_linear_speed is not implemented for AngularLimiter"); } fn get_max_linear_acceleration(&self) -> T { unreachable!("get_max_linear_acceleration is not implemented for AngularLimiter"); } #[allow(unused)] fn set_max_linear_acceleration(&mut self, linear_acceleration: T) { unreachable!("set_max_linear_acceleration is not implemented for AngularLimiter"); } fn get_max_angular_speed(&self) -> T { self.max_angular_speed } fn set_max_angular_speed(&mut self, angular_speed: T) { self.max_angular_speed = angular_speed; } fn get_max_angular_acceleration(&self) -> T { self.max_angular_acceleration } fn set_max_angular_acceleration(&mut self, angular_acceleration: T) { self.max_angular_acceleration = angular_acceleration; } }
30.481481
94
0.704131
f8b374607d3521d0879d945039c05fd191516b9d
176
#![deny(clippy::all, clippy::perf, clippy::correctness)] #![allow(clippy::missing_safety_doc)] #[macro_use] extern crate log; pub mod api; pub mod reexported; pub mod types;
17.6
56
0.727273
69e33ee3411f281250f47657efa971bcdbd3f646
12,031
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO: remove pub mod in lib.rs use crate::lossy_text::LossyText; use crate::reassembler::Reassembler; use anyhow::{format_err, Error}; use fuchsia_async::TimeoutExt; use futures::channel::{mpsc, oneshot}; use futures::lock::Mutex; use futures::prelude::*; use std::collections::HashMap; use std::time::Duration; use stream_framer::{DeframerReader, FramerWriter, ReadBytes}; // Flag bits for fragment id's pub const END_OF_MSG: u8 = 0x80; const ACK: u8 = 0x40; pub fn new_fragment_io( framer_writer: FramerWriter<LossyText>, deframer_reader: DeframerReader<LossyText>, ) -> (FragmentWriter, FragmentReader, impl Future<Output = Result<(), Error>>) { let (tx_write, rx_write) = mpsc::channel(0); let (tx_read, rx_read) = mpsc::channel(0); ( FragmentWriter { frame_sender: tx_write }, FragmentReader { frame_receiver: rx_read }, run_fragment_io(rx_write, tx_read, framer_writer, deframer_reader), ) } async fn run_fragment_io( rx_write: mpsc::Receiver<Vec<u8>>, tx_read: mpsc::Sender<ReadBytes>, framer_writer: FramerWriter<LossyText>, deframer_reader: DeframerReader<LossyText>, ) -> Result<(), Error> { let framer_writer = &Mutex::new(framer_writer); let (tx_frag, rx_frag) = mpsc::channel(0); let ack_set = &Mutex::new(HashMap::new()); let (mut tx_bat1, rx_bat1) = mpsc::channel(0); let (tx_bat2, rx_bat2) = mpsc::channel(0); let (tx_bat3, rx_bat3) = mpsc::channel(0); futures::future::try_join5( read_fragments(tx_read, framer_writer, deframer_reader, ack_set), split_fragments(rx_write, tx_frag), fragment_sender(rx_bat1, tx_bat2, framer_writer, ack_set), fragment_sender(rx_bat2, tx_bat3, framer_writer, ack_set), async move { // kick off the baton send and then run the third sender tx_bat1.send(rx_frag).await?; fragment_sender(rx_bat3, tx_bat1, framer_writer, ack_set).await }, ) .map_ok(drop) .await } async fn read_fragments( mut tx_read: mpsc::Sender<ReadBytes>, framer_writer: &Mutex<FramerWriter<LossyText>>, mut deframer_reader: DeframerReader<LossyText>, ack_set: &Mutex<HashMap<(u8, u8), oneshot::Sender<()>>>, ) -> Result<(), Error> { let mut reassembler = Reassembler::new(); loop { match deframer_reader.read().await? { ReadBytes::Unframed(bytes) => tx_read.send(ReadBytes::Unframed(bytes)).await?, ReadBytes::Framed(mut frame) => { let fragment_id = frame.pop().ok_or_else(|| format_err!("packet too short (no fragment id)"))?; let msg_id = frame.pop().ok_or_else(|| format_err!("packet too short (no msg id)"))?; if fragment_id & ACK == ACK { if !frame.is_empty() { log::warn!("non-empty ack received for ({}, {})", msg_id, fragment_id); } if let Some(tx) = ack_set.lock().await.remove(&(msg_id, fragment_id & !ACK)) { let _ = tx.send(()); } continue; } log::trace!("READ FRAG: msg_id={} fragment_id={} {:?}", msg_id, fragment_id, frame); framer_writer.lock().await.write(&[msg_id, fragment_id | ACK]).await?; if let Some(frame) = reassembler.recv(msg_id, fragment_id, frame) { tx_read.send(ReadBytes::Framed(frame)).await?; } } } } } async fn split_fragments( mut rx_write: mpsc::Receiver<Vec<u8>>, mut tx_frag: mpsc::Sender<(u8, u8, Vec<u8>)>, ) -> Result<(), Error> { let mut msg_id = 0u8; const MAX_FRAGMENT_SIZE: usize = 160; while let Some(frame) = rx_write.next().await { if frame.len() > 64 * MAX_FRAGMENT_SIZE { continue; } msg_id = msg_id.wrapping_add(1); let mut fragment_id = 0u8; let mut frame: &[u8] = &frame; while frame.len() > MAX_FRAGMENT_SIZE { tx_frag.send((msg_id, fragment_id, frame[..MAX_FRAGMENT_SIZE].to_vec())).await?; frame = &frame[MAX_FRAGMENT_SIZE..]; fragment_id += 1; } tx_frag.send((msg_id, fragment_id | END_OF_MSG, frame.to_vec())).await?; } Ok(()) } async fn fragment_sender( mut rx_baton: mpsc::Receiver<mpsc::Receiver<(u8, u8, Vec<u8>)>>, mut tx_baton: mpsc::Sender<mpsc::Receiver<(u8, u8, Vec<u8>)>>, framer_writer: &Mutex<FramerWriter<LossyText>>, ack_set: &Mutex<HashMap<(u8, u8), oneshot::Sender<()>>>, ) -> Result<(), Error> { 'next_fragment: loop { let mut baton = rx_baton.next().await.ok_or_else(|| format_err!("fragment baton passer closed"))?; let (msg_id, fragment_id, mut fragment) = baton.next().await.ok_or_else(|| format_err!("fragment receiver closed"))?; tx_baton.send(baton).await?; let (tx_ack, mut rx_ack) = oneshot::channel(); let tag = (msg_id, fragment_id); ack_set.lock().await.insert(tag, tx_ack); log::trace!( "SEND FRAG: msg_id={:?} fragment_id={:?} bytes={:?}", msg_id, fragment_id, fragment ); fragment.push(msg_id); fragment.push(fragment_id); enum RxError { Timeout, Canceled, } 'retry_fragment: for _ in 0..10 { framer_writer.lock().await.write(&fragment).await?; match (&mut rx_ack) .map_err(|_| RxError::Canceled) .on_timeout(Duration::from_millis(100), || Err(RxError::Timeout)) .await { Ok(()) => continue 'next_fragment, Err(RxError::Timeout) => continue 'retry_fragment, Err(RxError::Canceled) => break 'retry_fragment, } } // if we reach here we timed out a bunch ack_set.lock().await.remove(&tag); } } pub struct FragmentWriter { frame_sender: mpsc::Sender<Vec<u8>>, } impl FragmentWriter { pub async fn write(&mut self, bytes: Vec<u8>) -> Result<(), Error> { Ok(self.frame_sender.send(bytes).await?) } } pub struct FragmentReader { frame_receiver: mpsc::Receiver<ReadBytes>, } impl FragmentReader { pub async fn read(&mut self) -> Result<ReadBytes, Error> { Ok(self .frame_receiver .next() .await .ok_or_else(|| format_err!("failed to receive next frame"))?) } } #[cfg(test)] mod test { use super::{new_fragment_io, FragmentReader, FragmentWriter}; use crate::lossy_text::LossyText; use crate::test_util::{init, DodgyPipe}; use anyhow::{format_err, Error}; use fuchsia_async::TimeoutExt; use futures::future::{try_join, try_join4}; use futures::prelude::*; use std::collections::HashSet; use std::time::Duration; use stream_framer::{new_deframer, new_framer, DeframerWriter, FramerReader, ReadBytes}; async fn framer_write( mut framer_reader: FramerReader<LossyText>, mut pipe: impl AsyncWrite + Unpin, ) -> Result<(), Error> { loop { let frame = framer_reader.read().await?; pipe.write_all(&frame).await?; } } async fn deframer_read( mut pipe: impl AsyncRead + Unpin, mut deframer_writer: DeframerWriter<LossyText>, ) -> Result<(), Error> { loop { let mut buf = [0u8; 1]; match pipe.read(&mut buf).await? { 0 => return Ok(()), 1 => deframer_writer.write(&buf).await?, _ => unreachable!(), } } } async fn must_not_become_readable(mut rx: FragmentReader) -> Result<(), Error> { loop { match rx.read().await? { ReadBytes::Unframed(_) => (), ReadBytes::Framed(_) => panic!("Expected to see no framed data"), } } } async fn run_test( name: &'static str, run: usize, failures_per_64kib: u16, messages: &'static [&[u8]], ) -> Result<(), Error> { init(); const INCOMING_BYTE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100); let (c2s_rx, c2s_tx) = DodgyPipe::new(failures_per_64kib).split(); let (s2c_rx, s2c_tx) = DodgyPipe::new(failures_per_64kib).split(); let (c_frm_tx, c_frm_rx) = new_framer(LossyText::new(INCOMING_BYTE_TIMEOUT), 256); let (s_frm_tx, s_frm_rx) = new_framer(LossyText::new(INCOMING_BYTE_TIMEOUT), 256); let (c_dfrm_tx, c_dfrm_rx) = new_deframer(LossyText::new(INCOMING_BYTE_TIMEOUT)); let (s_dfrm_tx, s_dfrm_rx) = new_deframer(LossyText::new(INCOMING_BYTE_TIMEOUT)); let (mut c_tx, c_rx, c_run) = new_fragment_io(c_frm_tx, c_dfrm_rx); let (_s_tx, mut s_rx, s_run) = new_fragment_io(s_frm_tx, s_dfrm_rx); let (support_fut, support_handle) = try_join4( try_join(c_run, s_run), try_join(framer_write(c_frm_rx, c2s_tx), framer_write(s_frm_rx, s2c_tx)), try_join(deframer_read(c2s_rx, s_dfrm_tx), deframer_read(s2c_rx, c_dfrm_tx)), must_not_become_readable(c_rx), ) .map_ok(drop) .remote_handle(); try_join( async move { support_fut.await; Ok(()) }, async move { one_test(name, run, &messages, &mut c_tx, &mut s_rx) .on_timeout(Duration::from_secs(120), || Err(format_err!("timeout"))) .await?; drop(support_handle); Ok(()) }, ) .map_ok(drop) .await } async fn one_test( name: &str, iteration: usize, messages: &[&[u8]], tx: &mut FragmentWriter, rx: &mut FragmentReader, ) -> Result<(), Error> { try_join( async move { for (i, message) in messages.iter().enumerate() { log::info!("{}[run {}, msg {}] begin write", name, iteration, i); tx.write(message.to_vec()).await?; log::info!("{}[run {}, msg {}] done write", name, iteration, i); } Ok(()) }, async move { let n = messages.len(); let mut found = HashSet::new(); while found.len() != n { log::info!("{}[run {}, msg {}] begin read", name, iteration, found.len()); let msg = match rx.read().await? { ReadBytes::Unframed(_) => continue, ReadBytes::Framed(msg) => msg, }; let index = messages .iter() .enumerate() .find(|(_, message)| msg == **message) .unwrap() .0; assert!(found.insert(index)); } Ok(()) }, ) .map_ok(drop) .await } const LONG_PACKET: &'static [u8; 8192] = std::include_bytes!("long_packet.bin"); #[fuchsia_async::run_singlethreaded(test)] async fn simple(run: usize) -> Result<(), Error> { run_test("simple", run, 0, &[b"hello world"]).await } #[fuchsia_async::run_singlethreaded(test)] async fn long(run: usize) -> Result<(), Error> { run_test("long", run, 0, &[LONG_PACKET]).await } #[fuchsia_async::run_singlethreaded(test)] async fn long_flaky(run: usize) -> Result<(), Error> { run_test("long_flaky", run, 10, &[LONG_PACKET]).await } }
35.385294
100
0.558391
18c3549600464da77df1b1ffefd92eed96159a93
2,651
use super::*; use wtools::error::BasicError; use wca::command::Command; use wca::instruction::Instruction; // fn commands_form() -> std::collections::HashMap< String, Command > { let help_command : Command = wca::CommandOptions::default() .hint( "Get help." ) .long_hint( "Get help for command [command]" ) .phrase( ".help" ) .routine( &| _i : &Instruction | { println!( "this is help" ); Ok( () ) } ) .form(); let list_command : Command = wca::CommandOptions::default() .hint( "Get list." ) .long_hint( "Get list of" ) .phrase( ".list" ) .subject_hint( "some subject" ) .routine( &| _i : &Instruction | { println!( "this is list" ); Ok( () ) } ) .form(); let err_command : Command = wca::CommandOptions::default() .hint( "Error." ) .long_hint( "Throw error" ) .phrase( ".error" ) .routine( &| _i : &Instruction | { Err( BasicError::new( "err" ) ) } ) .form(); let commands : std::collections::HashMap< String, Command > = std::collections::HashMap::from ([ ( ".help".to_string(), help_command ), ( ".list".to_string(), list_command ), ( ".error".to_string(), err_command ), ]); commands } tests_impls! { fn basic() { let ca = wca::commands_aggregator() .form(); a_id!( ca.base_path, None ); a_id!( ca.command_prefix, "".to_string() ); a_id!( ca.delimeter, vec![ ".".to_string(), " ".to_string() ] ); a_id!( ca.command_explicit_delimeter, ";".to_string() ); a_id!( ca.command_implicit_delimeter, " ".to_string() ); a_id!( ca.commands_explicit_delimiting, true ); a_id!( ca.commands_implicit_delimiting, false ); a_id!( ca.properties_map_parsing, false ); a_id!( ca.several_values, true ); a_id!( ca.with_help, true ); a_id!( ca.changing_exit_code, true ); a_id!( ca.commands, std::collections::HashMap::new() ); } fn instruction_perform_basic() { /* no commands in aggregator */ let ca = wca::commands_aggregator() .changing_exit_code( false ) .form(); let got = ca.instruction_perform( ".help" ); a_id!( got, Ok( () ) ); /* command returns Ok */ let ca = wca::commands_aggregator() .changing_exit_code( false ) .commands().replace( commands_form() ).end() .form(); let got = ca.instruction_perform( ".help" ); a_id!( got, Ok( () ) ); /* command returns Err */ let ca = wca::commands_aggregator() .changing_exit_code( false ) .commands().replace( commands_form() ).end() .form(); let got = ca.instruction_perform( ".error" ); a_id!( got, Err( BasicError::new( "err" ) ) ); } } // tests_index! { basic, instruction_perform_basic, }
28.202128
95
0.611845
266975994ec3ae01d9061cd2291d71e76b431ff8
78,931
// Copyright 2012-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. /* # Collect phase The collect phase of type check has the job of visiting all items, determining their type, and writing that type into the `tcx.types` table. Despite its name, this table does not really operate as a *cache*, at least not for the types of items defined within the current crate: we assume that after the collect phase, the types of all local items will be present in the table. Unlike most of the types that are present in Rust, the types computed for each item are in fact type schemes. This means that they are generic types that may have type parameters. TypeSchemes are represented by a pair of `Generics` and `Ty`. Type parameters themselves are represented as `ty_param()` instances. The phasing of type conversion is somewhat complicated. There is no clear set of phases we can enforce (e.g., converting traits first, then types, or something like that) because the user can introduce arbitrary interdependencies. So instead we generally convert things lazilly and on demand, and include logic that checks for cycles. Demand is driven by calls to `AstConv::get_item_type_scheme` or `AstConv::lookup_trait_def`. Currently, we "convert" types and traits in two phases (note that conversion only affects the types of items / enum variants / methods; it does not e.g. compute the types of individual expressions): 0. Intrinsics 1. Trait/Type definitions Conversion itself is done by simply walking each of the items in turn and invoking an appropriate function (e.g., `trait_def_of_item` or `convert_item`). However, it is possible that while converting an item, we may need to compute the *type scheme* or *trait definition* for other items. There are some shortcomings in this design: - Before walking the set of supertraits for a given trait, you must call `ensure_super_predicates` on that trait def-id. Otherwise, `item_super_predicates` will result in ICEs. - Because the item generics include defaults, cycles through type parameter defaults are illegal even if those defaults are never employed. This is not necessarily a bug. */ use astconv::{AstConv, Bounds}; use lint; use constrained_type_params as ctp; use middle::lang_items::SizedTraitLangItem; use middle::const_val::ConstVal; use rustc_const_eval::EvalHint::UncheckedExprHint; use rustc_const_eval::{ConstContext, report_const_eval_err}; use rustc::ty::subst::Substs; use rustc::ty::{ToPredicate, ImplContainer, AssociatedItemContainer, TraitContainer}; use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt}; use rustc::ty::util::IntTypeExt; use rustc::dep_graph::DepNode; use util::common::{ErrorReported, MemoizationMap}; use util::nodemap::{NodeMap, FxHashMap}; use CrateCtxt; use rustc_const_math::ConstInt; use std::cell::RefCell; use syntax::{abi, ast, attr}; use syntax::symbol::{Symbol, keywords}; use syntax_pos::Span; use rustc::hir::{self, map as hir_map}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::def::{Def, CtorKind}; use rustc::hir::def_id::DefId; /////////////////////////////////////////////////////////////////////////// // Main entry point pub fn collect_item_types(ccx: &CrateCtxt) { let mut visitor = CollectItemTypesVisitor { ccx: ccx }; ccx.tcx.visit_all_item_likes_in_krate(DepNode::CollectItem, &mut visitor.as_deep_visitor()); } /////////////////////////////////////////////////////////////////////////// /// Context specific to some particular item. This is what implements /// AstConv. It has information about the predicates that are defined /// on the trait. Unfortunately, this predicate information is /// available in various different forms at various points in the /// process. So we can't just store a pointer to e.g. the AST or the /// parsed ty form, we have to be more flexible. To this end, the /// `ItemCtxt` is parameterized by a `GetTypeParameterBounds` object /// that it uses to satisfy `get_type_parameter_bounds` requests. /// This object might draw the information from the AST /// (`hir::Generics`) or it might draw from a `ty::GenericPredicates` /// or both (a tuple). struct ItemCtxt<'a,'tcx:'a> { ccx: &'a CrateCtxt<'a,'tcx>, param_bounds: &'a (GetTypeParameterBounds<'tcx>+'a), } #[derive(Copy, Clone, PartialEq, Eq)] pub enum AstConvRequest { GetGenerics(DefId), GetItemTypeScheme(DefId), GetTraitDef(DefId), EnsureSuperPredicates(DefId), GetTypeParameterBounds(ast::NodeId), } /////////////////////////////////////////////////////////////////////////// struct CollectItemTypesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> } impl<'a, 'tcx> CollectItemTypesVisitor<'a, 'tcx> { /// Collect item types is structured into two tasks. The outer /// task, `CollectItem`, walks the entire content of an item-like /// thing, including its body. It also spawns an inner task, /// `CollectItemSig`, which walks only the signature. This inner /// task is the one that writes the item-type into the various /// maps. This setup ensures that the item body is never /// accessible to the task that computes its signature, so that /// changes to the body don't affect the signature. /// /// Consider an example function `foo` that also has a closure in its body: /// /// ``` /// fn foo(<sig>) { /// ... /// let bar = || ...; // we'll label this closure as "bar" below /// } /// ``` /// /// This results in a dep-graph like so. I've labeled the edges to /// document where they arise. /// /// ``` /// [HirBody(foo)] -2--> [CollectItem(foo)] -4-> [ItemSignature(bar)] /// ^ ^ /// 1 3 /// [Hir(foo)] -----------+-6-> [CollectItemSig(foo)] -5-> [ItemSignature(foo)] /// ``` /// /// 1. This is added by the `visit_all_item_likes_in_krate`. /// 2. This is added when we fetch the item body. /// 3. This is added because `CollectItem` launches `CollectItemSig`. /// - it is arguably false; if we refactor the `with_task` system; /// we could get probably rid of it, but it is also harmless enough. /// 4. This is added by the code in `visit_expr` when we write to `item_types`. /// 5. This is added by the code in `convert_item` when we write to `item_types`; /// note that this write occurs inside the `CollectItemSig` task. /// 6. Added by explicit `read` below fn with_collect_item_sig<OP>(&self, id: ast::NodeId, op: OP) where OP: FnOnce() { let def_id = self.ccx.tcx.hir.local_def_id(id); self.ccx.tcx.dep_graph.with_task(DepNode::CollectItemSig(def_id), || { self.ccx.tcx.hir.read(id); op(); }); } } impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::OnlyBodies(&self.ccx.tcx.hir) } fn visit_item(&mut self, item: &'tcx hir::Item) { self.with_collect_item_sig(item.id, || convert_item(self.ccx, item)); intravisit::walk_item(self, item); } fn visit_expr(&mut self, expr: &'tcx hir::Expr) { if let hir::ExprClosure(..) = expr.node { let def_id = self.ccx.tcx.hir.local_def_id(expr.id); generics_of_def_id(self.ccx, def_id); type_of_def_id(self.ccx, def_id); } intravisit::walk_expr(self, expr); } fn visit_ty(&mut self, ty: &'tcx hir::Ty) { if let hir::TyImplTrait(..) = ty.node { let def_id = self.ccx.tcx.hir.local_def_id(ty.id); generics_of_def_id(self.ccx, def_id); } intravisit::walk_ty(self, ty); } fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) { self.with_collect_item_sig(trait_item.id, || { convert_trait_item(self.ccx, trait_item) }); intravisit::walk_trait_item(self, trait_item); } fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) { self.with_collect_item_sig(impl_item.id, || { convert_impl_item(self.ccx, impl_item) }); intravisit::walk_impl_item(self, impl_item); } } /////////////////////////////////////////////////////////////////////////// // Utility types and common code for the above passes. impl<'a,'tcx> CrateCtxt<'a,'tcx> { fn icx(&'a self, param_bounds: &'a GetTypeParameterBounds<'tcx>) -> ItemCtxt<'a,'tcx> { ItemCtxt { ccx: self, param_bounds: param_bounds, } } fn cycle_check<F,R>(&self, span: Span, request: AstConvRequest, code: F) -> Result<R,ErrorReported> where F: FnOnce() -> Result<R,ErrorReported> { { let mut stack = self.stack.borrow_mut(); if let Some((i, _)) = stack.iter().enumerate().rev().find(|&(_, r)| *r == request) { let cycle = &stack[i..]; self.report_cycle(span, cycle); return Err(ErrorReported); } stack.push(request); } let result = code(); self.stack.borrow_mut().pop(); result } fn report_cycle(&self, span: Span, cycle: &[AstConvRequest]) { assert!(!cycle.is_empty()); let tcx = self.tcx; let mut err = struct_span_err!(tcx.sess, span, E0391, "unsupported cyclic reference between types/traits detected"); err.span_label(span, &format!("cyclic reference")); match cycle[0] { AstConvRequest::GetGenerics(def_id) | AstConvRequest::GetItemTypeScheme(def_id) | AstConvRequest::GetTraitDef(def_id) => { err.note( &format!("the cycle begins when processing `{}`...", tcx.item_path_str(def_id))); } AstConvRequest::EnsureSuperPredicates(def_id) => { err.note( &format!("the cycle begins when computing the supertraits of `{}`...", tcx.item_path_str(def_id))); } AstConvRequest::GetTypeParameterBounds(id) => { let def = tcx.type_parameter_def(id); err.note( &format!("the cycle begins when computing the bounds \ for type parameter `{}`...", def.name)); } } for request in &cycle[1..] { match *request { AstConvRequest::GetGenerics(def_id) | AstConvRequest::GetItemTypeScheme(def_id) | AstConvRequest::GetTraitDef(def_id) => { err.note( &format!("...which then requires processing `{}`...", tcx.item_path_str(def_id))); } AstConvRequest::EnsureSuperPredicates(def_id) => { err.note( &format!("...which then requires computing the supertraits of `{}`...", tcx.item_path_str(def_id))); } AstConvRequest::GetTypeParameterBounds(id) => { let def = tcx.type_parameter_def(id); err.note( &format!("...which then requires computing the bounds \ for type parameter `{}`...", def.name)); } } } match cycle[0] { AstConvRequest::GetGenerics(def_id) | AstConvRequest::GetItemTypeScheme(def_id) | AstConvRequest::GetTraitDef(def_id) => { err.note( &format!("...which then again requires processing `{}`, completing the cycle.", tcx.item_path_str(def_id))); } AstConvRequest::EnsureSuperPredicates(def_id) => { err.note( &format!("...which then again requires computing the supertraits of `{}`, \ completing the cycle.", tcx.item_path_str(def_id))); } AstConvRequest::GetTypeParameterBounds(id) => { let def = tcx.type_parameter_def(id); err.note( &format!("...which then again requires computing the bounds \ for type parameter `{}`, completing the cycle.", def.name)); } } err.emit(); } /// Loads the trait def for a given trait, returning ErrorReported if a cycle arises. fn get_trait_def(&self, def_id: DefId) -> &'tcx ty::TraitDef { let tcx = self.tcx; if let Some(trait_id) = tcx.hir.as_local_node_id(def_id) { let item = match tcx.hir.get(trait_id) { hir_map::NodeItem(item) => item, _ => bug!("get_trait_def({:?}): not an item", trait_id) }; generics_of_def_id(self, def_id); trait_def_of_item(self, &item) } else { tcx.lookup_trait_def(def_id) } } /// Ensure that the (transitive) super predicates for /// `trait_def_id` are available. This will report a cycle error /// if a trait `X` (transitively) extends itself in some form. fn ensure_super_predicates(&self, span: Span, trait_def_id: DefId) -> Result<(), ErrorReported> { self.cycle_check(span, AstConvRequest::EnsureSuperPredicates(trait_def_id), || { let def_ids = ensure_super_predicates_step(self, trait_def_id); for def_id in def_ids { self.ensure_super_predicates(span, def_id)?; } Ok(()) }) } } impl<'a,'tcx> ItemCtxt<'a,'tcx> { fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { AstConv::ast_ty_to_ty(self, ast_ty) } } impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.ccx.tcx } fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> { &self.ccx.ast_ty_to_ty_cache } fn get_generics(&self, span: Span, id: DefId) -> Result<&'tcx ty::Generics<'tcx>, ErrorReported> { self.ccx.cycle_check(span, AstConvRequest::GetGenerics(id), || { Ok(generics_of_def_id(self.ccx, id)) }) } fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported> { self.ccx.cycle_check(span, AstConvRequest::GetItemTypeScheme(id), || { Ok(type_of_def_id(self.ccx, id)) }) } fn get_trait_def(&self, span: Span, id: DefId) -> Result<&'tcx ty::TraitDef, ErrorReported> { self.ccx.cycle_check(span, AstConvRequest::GetTraitDef(id), || { Ok(self.ccx.get_trait_def(id)) }) } fn ensure_super_predicates(&self, span: Span, trait_def_id: DefId) -> Result<(), ErrorReported> { debug!("ensure_super_predicates(trait_def_id={:?})", trait_def_id); self.ccx.ensure_super_predicates(span, trait_def_id) } fn get_type_parameter_bounds(&self, span: Span, node_id: ast::NodeId) -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported> { self.ccx.cycle_check(span, AstConvRequest::GetTypeParameterBounds(node_id), || { let v = self.param_bounds.get_type_parameter_bounds(self, span, node_id) .into_iter() .filter_map(|p| p.to_opt_poly_trait_ref()) .collect(); Ok(v) }) } fn get_free_substs(&self) -> Option<&Substs<'tcx>> { None } fn re_infer(&self, _span: Span, _def: Option<&ty::RegionParameterDef>) -> Option<&'tcx ty::Region> { None } fn ty_infer(&self, span: Span) -> Ty<'tcx> { struct_span_err!( self.tcx().sess, span, E0121, "the type placeholder `_` is not allowed within types on item signatures" ).span_label(span, &format!("not allowed in type signatures")) .emit(); self.tcx().types.err } fn projected_ty_from_poly_trait_ref(&self, span: Span, poly_trait_ref: ty::PolyTraitRef<'tcx>, item_name: ast::Name) -> Ty<'tcx> { if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) { self.projected_ty(span, trait_ref, item_name) } else { // no late-bound regions, we can just ignore the binder span_err!(self.tcx().sess, span, E0212, "cannot extract an associated type from a higher-ranked trait bound \ in this context"); self.tcx().types.err } } fn projected_ty(&self, _span: Span, trait_ref: ty::TraitRef<'tcx>, item_name: ast::Name) -> Ty<'tcx> { self.tcx().mk_projection(trait_ref, item_name) } fn set_tainted_by_errors(&self) { // no obvious place to track this, just let it go } } /// Interface used to find the bounds on a type parameter from within /// an `ItemCtxt`. This allows us to use multiple kinds of sources. trait GetTypeParameterBounds<'tcx> { fn get_type_parameter_bounds(&self, astconv: &AstConv<'tcx, 'tcx>, span: Span, node_id: ast::NodeId) -> Vec<ty::Predicate<'tcx>>; } /// Find bounds from both elements of the tuple. impl<'a,'b,'tcx,A,B> GetTypeParameterBounds<'tcx> for (&'a A,&'b B) where A : GetTypeParameterBounds<'tcx>, B : GetTypeParameterBounds<'tcx> { fn get_type_parameter_bounds(&self, astconv: &AstConv<'tcx, 'tcx>, span: Span, node_id: ast::NodeId) -> Vec<ty::Predicate<'tcx>> { let mut v = self.0.get_type_parameter_bounds(astconv, span, node_id); v.extend(self.1.get_type_parameter_bounds(astconv, span, node_id)); v } } /// Empty set of bounds. impl<'tcx> GetTypeParameterBounds<'tcx> for () { fn get_type_parameter_bounds(&self, _astconv: &AstConv<'tcx, 'tcx>, _span: Span, _node_id: ast::NodeId) -> Vec<ty::Predicate<'tcx>> { Vec::new() } } /// Find bounds from the parsed and converted predicates. This is /// used when converting methods, because by that time the predicates /// from the trait/impl have been fully converted. impl<'tcx> GetTypeParameterBounds<'tcx> for ty::GenericPredicates<'tcx> { fn get_type_parameter_bounds(&self, astconv: &AstConv<'tcx, 'tcx>, span: Span, node_id: ast::NodeId) -> Vec<ty::Predicate<'tcx>> { let def = astconv.tcx().type_parameter_def(node_id); let mut results = self.parent.map_or(vec![], |def_id| { let parent = astconv.tcx().item_predicates(def_id); parent.get_type_parameter_bounds(astconv, span, node_id) }); results.extend(self.predicates.iter().filter(|predicate| { match **predicate { ty::Predicate::Trait(ref data) => { data.skip_binder().self_ty().is_param(def.index) } ty::Predicate::TypeOutlives(ref data) => { data.skip_binder().0.is_param(def.index) } ty::Predicate::Equate(..) | ty::Predicate::RegionOutlives(..) | ty::Predicate::WellFormed(..) | ty::Predicate::ObjectSafe(..) | ty::Predicate::ClosureKind(..) | ty::Predicate::Projection(..) => { false } } }).cloned()); results } } /// Find bounds from hir::Generics. This requires scanning through the /// AST. We do this to avoid having to convert *all* the bounds, which /// would create artificial cycles. Instead we can only convert the /// bounds for a type parameter `X` if `X::Foo` is used. impl<'tcx> GetTypeParameterBounds<'tcx> for hir::Generics { fn get_type_parameter_bounds(&self, astconv: &AstConv<'tcx, 'tcx>, _: Span, node_id: ast::NodeId) -> Vec<ty::Predicate<'tcx>> { // In the AST, bounds can derive from two places. Either // written inline like `<T:Foo>` or in a where clause like // `where T:Foo`. let def = astconv.tcx().type_parameter_def(node_id); let ty = astconv.tcx().mk_param_from_def(&def); let from_ty_params = self.ty_params .iter() .filter(|p| p.id == node_id) .flat_map(|p| p.bounds.iter()) .flat_map(|b| predicates_from_bound(astconv, ty, b)); let from_where_clauses = self.where_clause .predicates .iter() .filter_map(|wp| match *wp { hir::WherePredicate::BoundPredicate(ref bp) => Some(bp), _ => None }) .filter(|bp| is_param(astconv.tcx(), &bp.bounded_ty, node_id)) .flat_map(|bp| bp.bounds.iter()) .flat_map(|b| predicates_from_bound(astconv, ty, b)); from_ty_params.chain(from_where_clauses).collect() } } /// Tests whether this is the AST for a reference to the type /// parameter with id `param_id`. We use this so as to avoid running /// `ast_ty_to_ty`, because we want to avoid triggering an all-out /// conversion of the type to avoid inducing unnecessary cycles. fn is_param<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ast_ty: &hir::Ty, param_id: ast::NodeId) -> bool { if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = ast_ty.node { match path.def { Def::SelfTy(Some(def_id), None) | Def::TyParam(def_id) => { def_id == tcx.hir.local_def_id(param_id) } _ => false } } else { false } } fn convert_field<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, struct_generics: &'tcx ty::Generics<'tcx>, struct_predicates: &ty::GenericPredicates<'tcx>, field: &hir::StructField, ty_f: &'tcx ty::FieldDef) { let tt = ccx.icx(struct_predicates).to_ty(&field.ty); ccx.tcx.item_types.borrow_mut().insert(ty_f.did, tt); let def_id = ccx.tcx.hir.local_def_id(field.id); assert_eq!(def_id, ty_f.did); ccx.tcx.generics.borrow_mut().insert(def_id, struct_generics); ccx.tcx.predicates.borrow_mut().insert(def_id, struct_predicates.clone()); } fn convert_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, id: ast::NodeId, sig: &hir::MethodSig, rcvr_ty_predicates: &ty::GenericPredicates<'tcx>,) { let def_id = ccx.tcx.hir.local_def_id(id); let ty_generics = generics_of_def_id(ccx, def_id); let ty_generic_predicates = ty_generic_predicates(ccx, &sig.generics, ty_generics.parent, vec![], false); let fty = AstConv::ty_of_fn(&ccx.icx(&(rcvr_ty_predicates, &sig.generics)), sig.unsafety, sig.abi, &sig.decl); let substs = mk_item_substs(&ccx.icx(&(rcvr_ty_predicates, &sig.generics)), ccx.tcx.hir.span(id), def_id); let fty = ccx.tcx.mk_fn_def(def_id, substs, fty); ccx.tcx.item_types.borrow_mut().insert(def_id, fty); ccx.tcx.predicates.borrow_mut().insert(def_id, ty_generic_predicates); } fn convert_associated_const<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, container: AssociatedItemContainer, id: ast::NodeId, ty: ty::Ty<'tcx>) { let predicates = ty::GenericPredicates { parent: Some(container.id()), predicates: vec![] }; let def_id = ccx.tcx.hir.local_def_id(id); ccx.tcx.predicates.borrow_mut().insert(def_id, predicates); ccx.tcx.item_types.borrow_mut().insert(def_id, ty); } fn convert_associated_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, container: AssociatedItemContainer, id: ast::NodeId, ty: Option<Ty<'tcx>>) { let predicates = ty::GenericPredicates { parent: Some(container.id()), predicates: vec![] }; let def_id = ccx.tcx.hir.local_def_id(id); ccx.tcx.predicates.borrow_mut().insert(def_id, predicates); if let Some(ty) = ty { ccx.tcx.item_types.borrow_mut().insert(def_id, ty); } } fn ensure_no_ty_param_bounds(ccx: &CrateCtxt, span: Span, generics: &hir::Generics, thing: &'static str) { let mut warn = false; for ty_param in generics.ty_params.iter() { for bound in ty_param.bounds.iter() { match *bound { hir::TraitTyParamBound(..) => { warn = true; } hir::RegionTyParamBound(..) => { } } } } for predicate in generics.where_clause.predicates.iter() { match *predicate { hir::WherePredicate::BoundPredicate(..) => { warn = true; } hir::WherePredicate::RegionPredicate(..) => { } hir::WherePredicate::EqPredicate(..) => { } } } if warn { // According to accepted RFC #XXX, we should // eventually accept these, but it will not be // part of this PR. Still, convert to warning to // make bootstrapping easier. span_warn!(ccx.tcx.sess, span, E0122, "trait bounds are not (yet) enforced \ in {} definitions", thing); } } fn convert_item(ccx: &CrateCtxt, it: &hir::Item) { let tcx = ccx.tcx; debug!("convert: item {} with id {}", it.name, it.id); let def_id = ccx.tcx.hir.local_def_id(it.id); match it.node { // These don't define types. hir::ItemExternCrate(_) | hir::ItemUse(..) | hir::ItemMod(_) => { } hir::ItemForeignMod(ref foreign_mod) => { for item in &foreign_mod.items { convert_foreign_item(ccx, item); } } hir::ItemEnum(ref enum_definition, _) => { let ty = type_of_def_id(ccx, def_id); let generics = generics_of_def_id(ccx, def_id); let predicates = predicates_of_item(ccx, it); convert_enum_variant_types(ccx, tcx.lookup_adt_def(ccx.tcx.hir.local_def_id(it.id)), ty, generics, predicates, &enum_definition.variants); }, hir::ItemDefaultImpl(_, ref ast_trait_ref) => { let trait_ref = AstConv::instantiate_mono_trait_ref(&ccx.icx(&()), ast_trait_ref, tcx.mk_self_type()); tcx.record_trait_has_default_impl(trait_ref.def_id); tcx.impl_trait_refs.borrow_mut().insert(ccx.tcx.hir.local_def_id(it.id), Some(trait_ref)); } hir::ItemImpl(.., ref generics, ref opt_trait_ref, ref selfty, _) => { // Create generics from the generics specified in the impl head. debug!("convert: ast_generics={:?}", generics); generics_of_def_id(ccx, def_id); let mut ty_predicates = ty_generic_predicates(ccx, generics, None, vec![], false); debug!("convert: impl_bounds={:?}", ty_predicates); let selfty = ccx.icx(&ty_predicates).to_ty(&selfty); tcx.item_types.borrow_mut().insert(def_id, selfty); let trait_ref = opt_trait_ref.as_ref().map(|ast_trait_ref| { AstConv::instantiate_mono_trait_ref(&ccx.icx(&ty_predicates), ast_trait_ref, selfty) }); tcx.impl_trait_refs.borrow_mut().insert(def_id, trait_ref); // Subtle: before we store the predicates into the tcx, we // sort them so that predicates like `T: Foo<Item=U>` come // before uses of `U`. This avoids false ambiguity errors // in trait checking. See `setup_constraining_predicates` // for details. ctp::setup_constraining_predicates(&mut ty_predicates.predicates, trait_ref, &mut ctp::parameters_for_impl(selfty, trait_ref)); tcx.predicates.borrow_mut().insert(def_id, ty_predicates.clone()); }, hir::ItemTrait(..) => { generics_of_def_id(ccx, def_id); trait_def_of_item(ccx, it); let _: Result<(), ErrorReported> = // any error is already reported, can ignore ccx.ensure_super_predicates(it.span, def_id); convert_trait_predicates(ccx, it); }, hir::ItemStruct(ref struct_def, _) | hir::ItemUnion(ref struct_def, _) => { let ty = type_of_def_id(ccx, def_id); let generics = generics_of_def_id(ccx, def_id); let predicates = predicates_of_item(ccx, it); let variant = tcx.lookup_adt_def(def_id).struct_variant(); for (f, ty_f) in struct_def.fields().iter().zip(variant.fields.iter()) { convert_field(ccx, generics, &predicates, f, ty_f) } if !struct_def.is_struct() { convert_variant_ctor(ccx, struct_def.id(), variant, ty, predicates); } }, hir::ItemTy(_, ref generics) => { ensure_no_ty_param_bounds(ccx, it.span, generics, "type"); type_of_def_id(ccx, def_id); generics_of_def_id(ccx, def_id); predicates_of_item(ccx, it); }, _ => { type_of_def_id(ccx, def_id); generics_of_def_id(ccx, def_id); predicates_of_item(ccx, it); }, } } fn convert_trait_item(ccx: &CrateCtxt, trait_item: &hir::TraitItem) { let tcx = ccx.tcx; // we can lookup details about the trait because items are visited // before trait-items let trait_def_id = tcx.hir.get_parent_did(trait_item.id); let trait_predicates = tcx.item_predicates(trait_def_id); match trait_item.node { hir::TraitItemKind::Const(ref ty, _) => { let const_def_id = ccx.tcx.hir.local_def_id(trait_item.id); generics_of_def_id(ccx, const_def_id); let ty = ccx.icx(&trait_predicates).to_ty(&ty); convert_associated_const(ccx, TraitContainer(trait_def_id), trait_item.id, ty); } hir::TraitItemKind::Type(_, ref opt_ty) => { let type_def_id = ccx.tcx.hir.local_def_id(trait_item.id); generics_of_def_id(ccx, type_def_id); let typ = opt_ty.as_ref().map({ |ty| ccx.icx(&trait_predicates).to_ty(&ty) }); convert_associated_type(ccx, TraitContainer(trait_def_id), trait_item.id, typ); } hir::TraitItemKind::Method(ref sig, _) => { convert_method(ccx, trait_item.id, sig, &trait_predicates); } } } fn convert_impl_item(ccx: &CrateCtxt, impl_item: &hir::ImplItem) { let tcx = ccx.tcx; // we can lookup details about the impl because items are visited // before impl-items let impl_def_id = tcx.hir.get_parent_did(impl_item.id); let impl_predicates = tcx.item_predicates(impl_def_id); let impl_trait_ref = tcx.impl_trait_ref(impl_def_id); match impl_item.node { hir::ImplItemKind::Const(ref ty, _) => { let const_def_id = ccx.tcx.hir.local_def_id(impl_item.id); generics_of_def_id(ccx, const_def_id); let ty = ccx.icx(&impl_predicates).to_ty(&ty); convert_associated_const(ccx, ImplContainer(impl_def_id), impl_item.id, ty); } hir::ImplItemKind::Type(ref ty) => { let type_def_id = ccx.tcx.hir.local_def_id(impl_item.id); generics_of_def_id(ccx, type_def_id); if impl_trait_ref.is_none() { span_err!(tcx.sess, impl_item.span, E0202, "associated types are not allowed in inherent impls"); } let typ = ccx.icx(&impl_predicates).to_ty(ty); convert_associated_type(ccx, ImplContainer(impl_def_id), impl_item.id, Some(typ)); } hir::ImplItemKind::Method(ref sig, _) => { convert_method(ccx, impl_item.id, sig, &impl_predicates); } } } fn convert_variant_ctor<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, ctor_id: ast::NodeId, variant: &'tcx ty::VariantDef, ty: Ty<'tcx>, predicates: ty::GenericPredicates<'tcx>) { let tcx = ccx.tcx; let def_id = tcx.hir.local_def_id(ctor_id); generics_of_def_id(ccx, def_id); let ctor_ty = match variant.ctor_kind { CtorKind::Fictive | CtorKind::Const => ty, CtorKind::Fn => { let inputs = variant.fields.iter().map(|field| tcx.item_type(field.did)); let substs = mk_item_substs(&ccx.icx(&predicates), ccx.tcx.hir.span(ctor_id), def_id); tcx.mk_fn_def(def_id, substs, tcx.mk_bare_fn(ty::BareFnTy { unsafety: hir::Unsafety::Normal, abi: abi::Abi::Rust, sig: ty::Binder(ccx.tcx.mk_fn_sig(inputs, ty, false)) })) } }; tcx.item_types.borrow_mut().insert(def_id, ctor_ty); tcx.predicates.borrow_mut().insert(tcx.hir.local_def_id(ctor_id), predicates); } fn convert_enum_variant_types<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, def: &'tcx ty::AdtDef, ty: Ty<'tcx>, generics: &'tcx ty::Generics<'tcx>, predicates: ty::GenericPredicates<'tcx>, variants: &[hir::Variant]) { // fill the field types for (variant, ty_variant) in variants.iter().zip(def.variants.iter()) { for (f, ty_f) in variant.node.data.fields().iter().zip(ty_variant.fields.iter()) { convert_field(ccx, generics, &predicates, f, ty_f) } // Convert the ctor, if any. This also registers the variant as // an item. convert_variant_ctor( ccx, variant.node.data.id(), ty_variant, ty, predicates.clone() ); } } fn convert_struct_variant<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, did: DefId, name: ast::Name, disr_val: ty::Disr, def: &hir::VariantData) -> ty::VariantDef { let mut seen_fields: FxHashMap<ast::Name, Span> = FxHashMap(); let node_id = ccx.tcx.hir.as_local_node_id(did).unwrap(); let fields = def.fields().iter().map(|f| { let fid = ccx.tcx.hir.local_def_id(f.id); let dup_span = seen_fields.get(&f.name).cloned(); if let Some(prev_span) = dup_span { struct_span_err!(ccx.tcx.sess, f.span, E0124, "field `{}` is already declared", f.name) .span_label(f.span, &"field already declared") .span_label(prev_span, &format!("`{}` first declared here", f.name)) .emit(); } else { seen_fields.insert(f.name, f.span); } ty::FieldDef { did: fid, name: f.name, vis: ty::Visibility::from_hir(&f.vis, node_id, ccx.tcx) } }).collect(); ty::VariantDef { did: did, name: name, disr_val: disr_val, fields: fields, ctor_kind: CtorKind::from_hir(def), } } fn convert_struct_def<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item, def: &hir::VariantData) -> &'tcx ty::AdtDef { let did = ccx.tcx.hir.local_def_id(it.id); // Use separate constructor id for unit/tuple structs and reuse did for braced structs. let ctor_id = if !def.is_struct() { Some(ccx.tcx.hir.local_def_id(def.id())) } else { None }; let variants = vec![convert_struct_variant(ccx, ctor_id.unwrap_or(did), it.name, ConstInt::Infer(0), def)]; let adt = ccx.tcx.alloc_adt_def(did, AdtKind::Struct, variants); if let Some(ctor_id) = ctor_id { // Make adt definition available through constructor id as well. ccx.tcx.adt_defs.borrow_mut().insert(ctor_id, adt); } ccx.tcx.adt_defs.borrow_mut().insert(did, adt); adt } fn convert_union_def<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item, def: &hir::VariantData) -> &'tcx ty::AdtDef { let did = ccx.tcx.hir.local_def_id(it.id); let variants = vec![convert_struct_variant(ccx, did, it.name, ConstInt::Infer(0), def)]; let adt = ccx.tcx.alloc_adt_def(did, AdtKind::Union, variants); ccx.tcx.adt_defs.borrow_mut().insert(did, adt); adt } fn evaluate_disr_expr(ccx: &CrateCtxt, repr_ty: attr::IntType, body: hir::BodyId) -> Option<ty::Disr> { let e = &ccx.tcx.hir.body(body).value; debug!("disr expr, checking {}", ccx.tcx.hir.node_to_pretty_string(e.id)); let ty_hint = repr_ty.to_ty(ccx.tcx); let print_err = |cv: ConstVal| { struct_span_err!(ccx.tcx.sess, e.span, E0079, "mismatched types") .note_expected_found(&"type", &ty_hint, &format!("{}", cv.description())) .span_label(e.span, &format!("expected '{}' type", ty_hint)) .emit(); }; let hint = UncheckedExprHint(ty_hint); match ConstContext::new(ccx.tcx, body).eval(e, hint) { Ok(ConstVal::Integral(i)) => { // FIXME: eval should return an error if the hint is wrong match (repr_ty, i) { (attr::SignedInt(ast::IntTy::I8), ConstInt::I8(_)) | (attr::SignedInt(ast::IntTy::I16), ConstInt::I16(_)) | (attr::SignedInt(ast::IntTy::I32), ConstInt::I32(_)) | (attr::SignedInt(ast::IntTy::I64), ConstInt::I64(_)) | (attr::SignedInt(ast::IntTy::I128), ConstInt::I128(_)) | (attr::SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) | (attr::UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) | (attr::UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) | (attr::UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) | (attr::UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) | (attr::UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) | (attr::UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => Some(i), (_, i) => { print_err(ConstVal::Integral(i)); None }, } }, Ok(cv) => { print_err(cv); None }, // enum variant evaluation happens before the global constant check // so we need to report the real error Err(err) => { let mut diag = report_const_eval_err( ccx.tcx, &err, e.span, "enum discriminant"); diag.emit(); None } } } fn convert_enum_def<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item, def: &hir::EnumDef) -> &'tcx ty::AdtDef { let tcx = ccx.tcx; let did = tcx.hir.local_def_id(it.id); let repr_hints = tcx.lookup_repr_hints(did); let repr_type = tcx.enum_repr_type(repr_hints.get(0)); let initial = repr_type.initial_discriminant(tcx); let mut prev_disr = None::<ty::Disr>; let variants = def.variants.iter().map(|v| { let wrapped_disr = prev_disr.map_or(initial, |d| d.wrap_incr()); let disr = if let Some(e) = v.node.disr_expr { evaluate_disr_expr(ccx, repr_type, e) } else if let Some(disr) = repr_type.disr_incr(tcx, prev_disr) { Some(disr) } else { struct_span_err!(tcx.sess, v.span, E0370, "enum discriminant overflowed") .span_label(v.span, &format!("overflowed on value after {}", prev_disr.unwrap())) .note(&format!("explicitly set `{} = {}` if that is desired outcome", v.node.name, wrapped_disr)) .emit(); None }.unwrap_or(wrapped_disr); prev_disr = Some(disr); let did = tcx.hir.local_def_id(v.node.data.id()); convert_struct_variant(ccx, did, v.node.name, disr, &v.node.data) }).collect(); let adt = tcx.alloc_adt_def(did, AdtKind::Enum, variants); tcx.adt_defs.borrow_mut().insert(did, adt); adt } /// Ensures that the super-predicates of the trait with def-id /// trait_def_id are converted and stored. This does NOT ensure that /// the transitive super-predicates are converted; that is the job of /// the `ensure_super_predicates()` method in the `AstConv` impl /// above. Returns a list of trait def-ids that must be ensured as /// well to guarantee that the transitive superpredicates are /// converted. fn ensure_super_predicates_step(ccx: &CrateCtxt, trait_def_id: DefId) -> Vec<DefId> { let tcx = ccx.tcx; debug!("ensure_super_predicates_step(trait_def_id={:?})", trait_def_id); let trait_node_id = if let Some(n) = tcx.hir.as_local_node_id(trait_def_id) { n } else { // If this trait comes from an external crate, then all of the // supertraits it may depend on also must come from external // crates, and hence all of them already have their // super-predicates "converted" (and available from crate // meta-data), so there is no need to transitively test them. return Vec::new(); }; let superpredicates = tcx.super_predicates.borrow().get(&trait_def_id).cloned(); let superpredicates = superpredicates.unwrap_or_else(|| { let item = match ccx.tcx.hir.get(trait_node_id) { hir_map::NodeItem(item) => item, _ => bug!("trait_node_id {} is not an item", trait_node_id) }; let (generics, bounds) = match item.node { hir::ItemTrait(_, ref generics, ref supertraits, _) => (generics, supertraits), _ => span_bug!(item.span, "ensure_super_predicates_step invoked on non-trait"), }; // In-scope when converting the superbounds for `Trait` are // that `Self:Trait` as well as any bounds that appear on the // generic types: generics_of_def_id(ccx, trait_def_id); trait_def_of_item(ccx, item); let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: Substs::identity_for_item(tcx, trait_def_id) }; let self_predicate = ty::GenericPredicates { parent: None, predicates: vec![trait_ref.to_predicate()] }; let scope = &(generics, &self_predicate); // Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`. let self_param_ty = tcx.mk_self_type(); let superbounds1 = compute_bounds(&ccx.icx(scope), self_param_ty, bounds, SizedByDefault::No, item.span); let superbounds1 = superbounds1.predicates(tcx, self_param_ty); // Convert any explicit superbounds in the where clause, // e.g. `trait Foo where Self : Bar`: let superbounds2 = generics.get_type_parameter_bounds(&ccx.icx(scope), item.span, item.id); // Combine the two lists to form the complete set of superbounds: let superbounds = superbounds1.into_iter().chain(superbounds2).collect(); let superpredicates = ty::GenericPredicates { parent: None, predicates: superbounds }; debug!("superpredicates for trait {:?} = {:?}", tcx.hir.local_def_id(item.id), superpredicates); tcx.super_predicates.borrow_mut().insert(trait_def_id, superpredicates.clone()); superpredicates }); let def_ids: Vec<_> = superpredicates.predicates .iter() .filter_map(|p| p.to_opt_poly_trait_ref()) .map(|tr| tr.def_id()) .collect(); debug!("ensure_super_predicates_step: def_ids={:?}", def_ids); def_ids } fn trait_def_of_item<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item) -> &'tcx ty::TraitDef { let def_id = ccx.tcx.hir.local_def_id(it.id); let tcx = ccx.tcx; tcx.trait_defs.memoize(def_id, || { let unsafety = match it.node { hir::ItemTrait(unsafety, ..) => unsafety, _ => span_bug!(it.span, "trait_def_of_item invoked on non-trait"), }; let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar"); if paren_sugar && !ccx.tcx.sess.features.borrow().unboxed_closures { let mut err = ccx.tcx.sess.struct_span_err( it.span, "the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \ which traits can use parenthetical notation"); help!(&mut err, "add `#![feature(unboxed_closures)]` to \ the crate attributes to use it"); err.emit(); } let def_path_hash = tcx.def_path(def_id).deterministic_hash(tcx); tcx.alloc_trait_def(ty::TraitDef::new(def_id, unsafety, paren_sugar, def_path_hash)) }) } fn convert_trait_predicates<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item) { let tcx = ccx.tcx; let def_id = ccx.tcx.hir.local_def_id(it.id); generics_of_def_id(ccx, def_id); trait_def_of_item(ccx, it); let (generics, items) = match it.node { hir::ItemTrait(_, ref generics, _, ref items) => (generics, items), ref s => { span_bug!( it.span, "trait_def_of_item invoked on {:?}", s); } }; let super_predicates = ccx.tcx.item_super_predicates(def_id); // `ty_generic_predicates` below will consider the bounds on the type // parameters (including `Self`) and the explicit where-clauses, // but to get the full set of predicates on a trait we need to add // in the supertrait bounds and anything declared on the // associated types. let mut base_predicates = super_predicates.predicates; // Add in a predicate that `Self:Trait` (where `Trait` is the // current trait). This is needed for builtin bounds. let trait_ref = ty::TraitRef { def_id: def_id, substs: Substs::identity_for_item(tcx, def_id) }; let self_predicate = trait_ref.to_poly_trait_ref().to_predicate(); base_predicates.push(self_predicate); // add in the explicit where-clauses let mut trait_predicates = ty_generic_predicates(ccx, generics, None, base_predicates, true); let assoc_predicates = predicates_for_associated_types(ccx, generics, &trait_predicates, trait_ref, items); trait_predicates.predicates.extend(assoc_predicates); tcx.predicates.borrow_mut().insert(def_id, trait_predicates); return; fn predicates_for_associated_types<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, ast_generics: &hir::Generics, trait_predicates: &ty::GenericPredicates<'tcx>, self_trait_ref: ty::TraitRef<'tcx>, trait_item_refs: &[hir::TraitItemRef]) -> Vec<ty::Predicate<'tcx>> { trait_item_refs.iter().flat_map(|trait_item_ref| { let trait_item = ccx.tcx.hir.trait_item(trait_item_ref.id); let bounds = match trait_item.node { hir::TraitItemKind::Type(ref bounds, _) => bounds, _ => { return vec![].into_iter(); } }; let assoc_ty = ccx.tcx.mk_projection(self_trait_ref, trait_item.name); let bounds = compute_bounds(&ccx.icx(&(ast_generics, trait_predicates)), assoc_ty, bounds, SizedByDefault::Yes, trait_item.span); bounds.predicates(ccx.tcx, assoc_ty).into_iter() }).collect() } } fn generics_of_def_id<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, def_id: DefId) -> &'tcx ty::Generics<'tcx> { let tcx = ccx.tcx; let node_id = if let Some(id) = tcx.hir.as_local_node_id(def_id) { id } else { return tcx.item_generics(def_id); }; tcx.generics.memoize(def_id, || { use rustc::hir::map::*; use rustc::hir::*; let node = tcx.hir.get(node_id); let parent_def_id = match node { NodeImplItem(_) | NodeTraitItem(_) | NodeVariant(_) | NodeStructCtor(_) => { let parent_id = tcx.hir.get_parent(node_id); Some(tcx.hir.local_def_id(parent_id)) } NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) => { Some(tcx.closure_base_def_id(def_id)) } NodeTy(&hir::Ty { node: hir::TyImplTrait(..), .. }) => { let mut parent_id = node_id; loop { match tcx.hir.get(parent_id) { NodeItem(_) | NodeImplItem(_) | NodeTraitItem(_) => break, _ => { parent_id = tcx.hir.get_parent_node(parent_id); } } } Some(tcx.hir.local_def_id(parent_id)) } _ => None }; let mut opt_self = None; let mut allow_defaults = false; let no_generics = hir::Generics::empty(); let ast_generics = match node { NodeTraitItem(item) => { match item.node { TraitItemKind::Method(ref sig, _) => &sig.generics, _ => &no_generics } } NodeImplItem(item) => { match item.node { ImplItemKind::Method(ref sig, _) => &sig.generics, _ => &no_generics } } NodeItem(item) => { match item.node { ItemFn(.., ref generics, _) | ItemImpl(_, _, ref generics, ..) => generics, ItemTy(_, ref generics) | ItemEnum(_, ref generics) | ItemStruct(_, ref generics) | ItemUnion(_, ref generics) => { allow_defaults = true; generics } ItemTrait(_, ref generics, ..) => { // Add in the self type parameter. // // Something of a hack: use the node id for the trait, also as // the node id for the Self type parameter. let param_id = item.id; let parent = ccx.tcx.hir.get_parent(param_id); let def = ty::TypeParameterDef { index: 0, name: keywords::SelfType.name(), def_id: tcx.hir.local_def_id(param_id), default_def_id: tcx.hir.local_def_id(parent), default: None, pure_wrt_drop: false, }; tcx.ty_param_defs.borrow_mut().insert(param_id, def.clone()); opt_self = Some(def); allow_defaults = true; generics } _ => &no_generics } } NodeForeignItem(item) => { match item.node { ForeignItemStatic(..) => &no_generics, ForeignItemFn(_, _, ref generics) => generics } } _ => &no_generics }; let has_self = opt_self.is_some(); let mut parent_has_self = false; let mut own_start = has_self as u32; let (parent_regions, parent_types) = parent_def_id.map_or((0, 0), |def_id| { let generics = generics_of_def_id(ccx, def_id); assert_eq!(has_self, false); parent_has_self = generics.has_self; own_start = generics.count() as u32; (generics.parent_regions + generics.regions.len() as u32, generics.parent_types + generics.types.len() as u32) }); let early_lifetimes = early_bound_lifetimes_from_generics(ccx, ast_generics); let regions = early_lifetimes.iter().enumerate().map(|(i, l)| { ty::RegionParameterDef { name: l.lifetime.name, index: own_start + i as u32, def_id: tcx.hir.local_def_id(l.lifetime.id), pure_wrt_drop: l.pure_wrt_drop, } }).collect::<Vec<_>>(); // Now create the real type parameters. let type_start = own_start + regions.len() as u32; let types = ast_generics.ty_params.iter().enumerate().map(|(i, p)| { let i = type_start + i as u32; get_or_create_type_parameter_def(ccx, i, p, allow_defaults) }); let mut types: Vec<_> = opt_self.into_iter().chain(types).collect(); // provide junk type parameter defs - the only place that // cares about anything but the length is instantiation, // and we don't do that for closures. if let NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) = node { tcx.with_freevars(node_id, |fv| { types.extend(fv.iter().enumerate().map(|(i, _)| ty::TypeParameterDef { index: type_start + i as u32, name: Symbol::intern("<upvar>"), def_id: def_id, default_def_id: parent_def_id.unwrap(), default: None, pure_wrt_drop: false, })); }); } tcx.alloc_generics(ty::Generics { parent: parent_def_id, parent_regions: parent_regions, parent_types: parent_types, regions: regions, types: types, has_self: has_self || parent_has_self }) }) } fn type_of_def_id<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, def_id: DefId) -> Ty<'tcx> { let node_id = if let Some(id) = ccx.tcx.hir.as_local_node_id(def_id) { id } else { return ccx.tcx.item_type(def_id); }; ccx.tcx.item_types.memoize(def_id, || { use rustc::hir::map::*; use rustc::hir::*; // Alway bring in generics, as computing the type needs them. generics_of_def_id(ccx, def_id); let ty = match ccx.tcx.hir.get(node_id) { NodeItem(item) => { match item.node { ItemStatic(ref t, ..) | ItemConst(ref t, _) => { ccx.icx(&()).to_ty(&t) } ItemFn(ref decl, unsafety, _, abi, ref generics, _) => { let tofd = AstConv::ty_of_fn(&ccx.icx(generics), unsafety, abi, &decl); let substs = mk_item_substs(&ccx.icx(generics), item.span, def_id); ccx.tcx.mk_fn_def(def_id, substs, tofd) } ItemTy(ref t, ref generics) => { ccx.icx(generics).to_ty(&t) } ItemEnum(ref ei, ref generics) => { let def = convert_enum_def(ccx, item, ei); let substs = mk_item_substs(&ccx.icx(generics), item.span, def_id); ccx.tcx.mk_adt(def, substs) } ItemStruct(ref si, ref generics) => { let def = convert_struct_def(ccx, item, si); let substs = mk_item_substs(&ccx.icx(generics), item.span, def_id); ccx.tcx.mk_adt(def, substs) } ItemUnion(ref un, ref generics) => { let def = convert_union_def(ccx, item, un); let substs = mk_item_substs(&ccx.icx(generics), item.span, def_id); ccx.tcx.mk_adt(def, substs) } ItemDefaultImpl(..) | ItemTrait(..) | ItemImpl(..) | ItemMod(..) | ItemForeignMod(..) | ItemExternCrate(..) | ItemUse(..) => { span_bug!( item.span, "compute_type_of_item: unexpected item type: {:?}", item.node); } } } NodeForeignItem(foreign_item) => { let abi = ccx.tcx.hir.get_foreign_abi(node_id); match foreign_item.node { ForeignItemFn(ref fn_decl, _, ref generics) => { compute_type_of_foreign_fn_decl( ccx, ccx.tcx.hir.local_def_id(foreign_item.id), fn_decl, generics, abi) } ForeignItemStatic(ref t, _) => { ccx.icx(&()).to_ty(t) } } } NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) => { ccx.tcx.mk_closure(def_id, Substs::for_item( ccx.tcx, def_id, |def, _| { let region = def.to_early_bound_region_data(); ccx.tcx.mk_region(ty::ReEarlyBound(region)) }, |def, _| ccx.tcx.mk_param_from_def(def) )) } x => { bug!("unexpected sort of node in type_of_def_id(): {:?}", x); } }; ty }) } fn predicates_of_item<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::Item) -> ty::GenericPredicates<'tcx> { let def_id = ccx.tcx.hir.local_def_id(it.id); let no_generics = hir::Generics::empty(); let generics = match it.node { hir::ItemFn(.., ref generics, _) | hir::ItemTy(_, ref generics) | hir::ItemEnum(_, ref generics) | hir::ItemStruct(_, ref generics) | hir::ItemUnion(_, ref generics) => generics, _ => &no_generics }; let predicates = ty_generic_predicates(ccx, generics, None, vec![], false); ccx.tcx.predicates.borrow_mut().insert(def_id, predicates.clone()); predicates } fn convert_foreign_item<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, it: &hir::ForeignItem) { // For reasons I cannot fully articulate, I do so hate the AST // map, and I regard each time that I use it as a personal and // moral failing, but at the moment it seems like the only // convenient way to extract the ABI. - ndm let def_id = ccx.tcx.hir.local_def_id(it.id); type_of_def_id(ccx, def_id); generics_of_def_id(ccx, def_id); let no_generics = hir::Generics::empty(); let generics = match it.node { hir::ForeignItemFn(_, _, ref generics) => generics, hir::ForeignItemStatic(..) => &no_generics }; let predicates = ty_generic_predicates(ccx, generics, None, vec![], false); ccx.tcx.predicates.borrow_mut().insert(def_id, predicates); } // Is it marked with ?Sized fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, ast_bounds: &[hir::TyParamBound], span: Span) -> bool { let tcx = astconv.tcx(); // Try to find an unbound in bounds. let mut unbound = None; for ab in ast_bounds { if let &hir::TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = ab { if unbound.is_none() { unbound = Some(ptr.trait_ref.clone()); } else { span_err!(tcx.sess, span, E0203, "type parameter has more than one relaxed default \ bound, only one is supported"); } } } let kind_id = tcx.lang_items.require(SizedTraitLangItem); match unbound { Some(ref tpb) => { // FIXME(#8559) currently requires the unbound to be built-in. if let Ok(kind_id) = kind_id { if tpb.path.def != Def::Trait(kind_id) { tcx.sess.span_warn(span, "default bound relaxed for a type parameter, but \ this does nothing because the given bound is not \ a default. Only `?Sized` is supported"); } } } _ if kind_id.is_ok() => { return false; } // No lang item for Sized, so we can't add it as a bound. None => {} } true } /// Returns the early-bound lifetimes declared in this generics /// listing. For anything other than fns/methods, this is just all /// the lifetimes that are declared. For fns or methods, we have to /// screen out those that do not appear in any where-clauses etc using /// `resolve_lifetime::early_bound_lifetimes`. fn early_bound_lifetimes_from_generics<'a, 'tcx, 'hir>( ccx: &CrateCtxt<'a, 'tcx>, ast_generics: &'hir hir::Generics) -> Vec<&'hir hir::LifetimeDef> { ast_generics .lifetimes .iter() .filter(|l| !ccx.tcx.named_region_map.late_bound.contains_key(&l.lifetime.id)) .collect() } fn ty_generic_predicates<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, ast_generics: &hir::Generics, parent: Option<DefId>, super_predicates: Vec<ty::Predicate<'tcx>>, has_self: bool) -> ty::GenericPredicates<'tcx> { let tcx = ccx.tcx; let parent_count = parent.map_or(0, |def_id| { let generics = generics_of_def_id(ccx, def_id); assert_eq!(generics.parent, None); assert_eq!(generics.parent_regions, 0); assert_eq!(generics.parent_types, 0); generics.count() as u32 }); let ref base_predicates = match parent { Some(def_id) => { assert_eq!(super_predicates, vec![]); tcx.item_predicates(def_id) } None => { ty::GenericPredicates { parent: None, predicates: super_predicates.clone() } } }; let mut predicates = super_predicates; // Collect the region predicates that were declared inline as // well. In the case of parameters declared on a fn or method, we // have to be careful to only iterate over early-bound regions. let own_start = parent_count + has_self as u32; let early_lifetimes = early_bound_lifetimes_from_generics(ccx, ast_generics); for (index, param) in early_lifetimes.iter().enumerate() { let index = own_start + index as u32; let region = ccx.tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { index: index, name: param.lifetime.name })); for bound in &param.bounds { let bound_region = AstConv::ast_region_to_region(&ccx.icx(&()), bound, None); let outlives = ty::Binder(ty::OutlivesPredicate(region, bound_region)); predicates.push(outlives.to_predicate()); } } // Collect the predicates that were written inline by the user on each // type parameter (e.g., `<T:Foo>`). let type_start = own_start + early_lifetimes.len() as u32; for (index, param) in ast_generics.ty_params.iter().enumerate() { let index = type_start + index as u32; let param_ty = ty::ParamTy::new(index, param.name).to_ty(ccx.tcx); let bounds = compute_bounds(&ccx.icx(&(base_predicates, ast_generics)), param_ty, &param.bounds, SizedByDefault::Yes, param.span); predicates.extend(bounds.predicates(ccx.tcx, param_ty)); } // Add in the bounds that appear in the where-clause let where_clause = &ast_generics.where_clause; for predicate in &where_clause.predicates { match predicate { &hir::WherePredicate::BoundPredicate(ref bound_pred) => { let ty = AstConv::ast_ty_to_ty(&ccx.icx(&(base_predicates, ast_generics)), &bound_pred.bounded_ty); for bound in bound_pred.bounds.iter() { match bound { &hir::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => { let mut projections = Vec::new(); let trait_ref = AstConv::instantiate_poly_trait_ref(&ccx.icx(&(base_predicates, ast_generics)), poly_trait_ref, ty, &mut projections); predicates.push(trait_ref.to_predicate()); for projection in &projections { predicates.push(projection.to_predicate()); } } &hir::TyParamBound::RegionTyParamBound(ref lifetime) => { let region = AstConv::ast_region_to_region(&ccx.icx(&()), lifetime, None); let pred = ty::Binder(ty::OutlivesPredicate(ty, region)); predicates.push(ty::Predicate::TypeOutlives(pred)) } } } } &hir::WherePredicate::RegionPredicate(ref region_pred) => { let r1 = AstConv::ast_region_to_region(&ccx.icx(&()), &region_pred.lifetime, None); for bound in &region_pred.bounds { let r2 = AstConv::ast_region_to_region(&ccx.icx(&()), bound, None); let pred = ty::Binder(ty::OutlivesPredicate(r1, r2)); predicates.push(ty::Predicate::RegionOutlives(pred)) } } &hir::WherePredicate::EqPredicate(..) => { // FIXME(#20041) } } } ty::GenericPredicates { parent: parent, predicates: predicates } } fn get_or_create_type_parameter_def<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, index: u32, param: &hir::TyParam, allow_defaults: bool) -> ty::TypeParameterDef<'tcx> { let tcx = ccx.tcx; match tcx.ty_param_defs.borrow().get(&param.id) { Some(d) => { return d.clone(); } None => { } } let default = param.default.as_ref().map(|def| ccx.icx(&()).to_ty(def)); let parent = tcx.hir.get_parent(param.id); if !allow_defaults && default.is_some() { if !tcx.sess.features.borrow().default_type_parameter_fallback { tcx.sess.add_lint( lint::builtin::INVALID_TYPE_PARAM_DEFAULT, param.id, param.span, format!("defaults for type parameters are only allowed in `struct`, \ `enum`, `type`, or `trait` definitions.")); } } let def = ty::TypeParameterDef { index: index, name: param.name, def_id: ccx.tcx.hir.local_def_id(param.id), default_def_id: ccx.tcx.hir.local_def_id(parent), default: default, pure_wrt_drop: param.pure_wrt_drop, }; if def.name == keywords::SelfType.name() { span_bug!(param.span, "`Self` should not be the name of a regular parameter"); } tcx.ty_param_defs.borrow_mut().insert(param.id, def.clone()); debug!("get_or_create_type_parameter_def: def for type param: {:?}", def); def } pub enum SizedByDefault { Yes, No, } /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the /// built-in trait (formerly known as kind): Send. pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, param_ty: ty::Ty<'tcx>, ast_bounds: &[hir::TyParamBound], sized_by_default: SizedByDefault, span: Span) -> Bounds<'tcx> { let mut region_bounds = vec![]; let mut trait_bounds = vec![]; for ast_bound in ast_bounds { match *ast_bound { hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => { trait_bounds.push(b); } hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {} hir::RegionTyParamBound(ref l) => { region_bounds.push(l); } } } let mut projection_bounds = vec![]; let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| { astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds) }).collect(); let region_bounds = region_bounds.into_iter().map(|r| { astconv.ast_region_to_region(r, None) }).collect(); trait_bounds.sort_by(|a,b| a.def_id().cmp(&b.def_id())); let implicitly_sized = if let SizedByDefault::Yes = sized_by_default { !is_unsized(astconv, ast_bounds, span) } else { false }; Bounds { region_bounds: region_bounds, implicitly_sized: implicitly_sized, trait_bounds: trait_bounds, projection_bounds: projection_bounds, } } /// Converts a specific TyParamBound from the AST into a set of /// predicates that apply to the self-type. A vector is returned /// because this can be anywhere from 0 predicates (`T:?Sized` adds no /// predicates) to 1 (`T:Foo`) to many (`T:Bar<X=i32>` adds `T:Bar` /// and `<T as Bar>::X == i32`). fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>, param_ty: Ty<'tcx>, bound: &hir::TyParamBound) -> Vec<ty::Predicate<'tcx>> { match *bound { hir::TraitTyParamBound(ref tr, hir::TraitBoundModifier::None) => { let mut projections = Vec::new(); let pred = astconv.instantiate_poly_trait_ref(tr, param_ty, &mut projections); projections.into_iter() .map(|p| p.to_predicate()) .chain(Some(pred.to_predicate())) .collect() } hir::RegionTyParamBound(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); let pred = ty::Binder(ty::OutlivesPredicate(param_ty, region)); vec![ty::Predicate::TypeOutlives(pred)] } hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => { Vec::new() } } } fn compute_type_of_foreign_fn_decl<'a, 'tcx>( ccx: &CrateCtxt<'a, 'tcx>, def_id: DefId, decl: &hir::FnDecl, ast_generics: &hir::Generics, abi: abi::Abi) -> Ty<'tcx> { let fty = AstConv::ty_of_fn(&ccx.icx(ast_generics), hir::Unsafety::Unsafe, abi, decl); // feature gate SIMD types in FFI, since I (huonw) am not sure the // ABIs are handled at all correctly. if abi != abi::Abi::RustIntrinsic && abi != abi::Abi::PlatformIntrinsic && !ccx.tcx.sess.features.borrow().simd_ffi { let check = |ast_ty: &hir::Ty, ty: ty::Ty| { if ty.is_simd() { ccx.tcx.sess.struct_span_err(ast_ty.span, &format!("use of SIMD type `{}` in FFI is highly experimental and \ may result in invalid code", ccx.tcx.hir.node_to_pretty_string(ast_ty.id))) .help("add #![feature(simd_ffi)] to the crate attributes to enable") .emit(); } }; for (input, ty) in decl.inputs.iter().zip(*fty.sig.inputs().skip_binder()) { check(&input, ty) } if let hir::Return(ref ty) = decl.output { check(&ty, *fty.sig.output().skip_binder()) } } let id = ccx.tcx.hir.as_local_node_id(def_id).unwrap(); let substs = mk_item_substs(&ccx.icx(ast_generics), ccx.tcx.hir.span(id), def_id); ccx.tcx.mk_fn_def(def_id, substs, fty) } fn mk_item_substs<'tcx>(astconv: &AstConv<'tcx, 'tcx>, span: Span, def_id: DefId) -> &'tcx Substs<'tcx> { let tcx = astconv.tcx(); // FIXME(eddyb) Do this request from Substs::for_item in librustc. if let Err(ErrorReported) = astconv.get_generics(span, def_id) { // No convenient way to recover from a cycle here. Just bail. Sorry! tcx.sess.abort_if_errors(); bug!("ErrorReported returned, but no errors reports?") } Substs::identity_for_item(tcx, def_id) }
39.723704
99
0.526244
b92001157e4ee6f0c0d2a20c9bf32a1ef8e4a8f2
1,120
#![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { # [wasm_bindgen (extends = CssRule , extends = :: js_sys :: Object , js_name = CSSFontFaceRule , typescript_type = "CSSFontFaceRule")] #[derive(Debug, Clone, PartialEq, Eq)] #[doc = "The `CssFontFaceRule` class."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `CssFontFaceRule`*"] pub type CssFontFaceRule; #[cfg(feature = "CssStyleDeclaration")] # [wasm_bindgen (structural , method , getter , js_class = "CSSFontFaceRule" , js_name = style)] #[doc = "Getter for the `style` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule/style)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `CssFontFaceRule`, `CssStyleDeclaration`*"] pub fn style(this: &CssFontFaceRule) -> CssStyleDeclaration; }
48.695652
138
0.665179
e2f5b21f7bb1da1f72ea654bc1f22721d01b9cef
12,761
use std::{ convert::TryInto, io::{self, ErrorKind}, mem::MaybeUninit, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, pin::Pin, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, task::{Context, Poll}, time::Duration, }; use anyhow::Result; use futures::Stream; use hyper::server::accept::Accept; use hyper::server::conn::{AddrIncoming, AddrStream}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tonic::transport::server::Connected; #[derive(Clone, Copy)] pub enum ProxyMode { None, Accept, Require, } pub struct WrappedIncoming { inner: AddrIncoming, conn_count: Arc<AtomicU64>, proxy_mode: ProxyMode, } impl WrappedIncoming { pub fn new( addr: SocketAddr, nodelay: bool, keepalive: Option<Duration>, proxy_mode: ProxyMode, ) -> Result<Self> { let mut inner = AddrIncoming::bind(&addr)?; inner.set_nodelay(nodelay); inner.set_keepalive(keepalive); Ok(WrappedIncoming { inner, conn_count: Arc::new(AtomicU64::new(0)), proxy_mode, }) } pub fn get_conn_count(&self) -> Arc<AtomicU64> { self.conn_count.clone() } } impl Stream for WrappedIncoming { type Item = Result<WrappedStream, std::io::Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match Pin::new(&mut self.inner).poll_accept(cx) { Poll::Ready(Some(Ok(stream))) => { self.conn_count.fetch_add(1, Ordering::SeqCst); Poll::Ready(Some(Ok(WrappedStream { inner: Box::pin(stream), conn_count: self.conn_count.clone(), proxy_header: [0u8; PROXY_PACKET_HEADER_LEN + PROXY_PACKET_MAX_PROXY_ADDR_SIZE], // maybe uninit? proxy_header_index: 0, proxy_header_rewrite_index: 0, proxy_header_target: if matches!(self.proxy_mode, ProxyMode::None) { 0 } else { PROXY_PACKET_HEADER_LEN + PROXY_PACKET_MAX_PROXY_ADDR_SIZE }, discovered_remote: None, proxy_mode: self.proxy_mode, }))) } Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))), Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, } } } const PROXY_PACKET_HEADER_LEN: usize = 16; const PROXY_PACKET_MAX_PROXY_ADDR_SIZE: usize = 36; const PROXY_SIGNATURE: [u8; 12] = [ 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A, ]; pub struct WrappedStream { inner: Pin<Box<AddrStream>>, conn_count: Arc<AtomicU64>, proxy_header: [u8; PROXY_PACKET_HEADER_LEN + PROXY_PACKET_MAX_PROXY_ADDR_SIZE], proxy_header_index: usize, proxy_header_rewrite_index: usize, proxy_header_target: usize, discovered_remote: Option<SocketAddr>, proxy_mode: ProxyMode, } impl Connected for WrappedStream { type ConnectInfo = Option<SocketAddr>; fn connect_info(&self) -> Self::ConnectInfo { Some( self.discovered_remote .unwrap_or_else(|| self.inner.remote_addr()), ) } } impl AsyncRead for WrappedStream { #[inline] fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { if !matches!(self.proxy_mode, ProxyMode::None) && self.proxy_header_target > 0 { let index = self.proxy_header_index; let target = self.proxy_header_target; let mut proxy_header = [MaybeUninit::uninit(); PROXY_PACKET_HEADER_LEN + PROXY_PACKET_MAX_PROXY_ADDR_SIZE]; let mut read_buf = ReadBuf::uninit(&mut proxy_header[index..target]); match self.inner.as_mut().poll_read(cx, &mut read_buf) { Poll::Pending => return Poll::Pending, Poll::Ready(Err(e)) => return Poll::Ready(Err(e)), Poll::Ready(Ok(())) => { (&mut self.proxy_header[index..index + read_buf.filled().len()]) .copy_from_slice(read_buf.filled()); self.proxy_header_index += read_buf.filled().len(); let signature_end = self.proxy_header_index.min(12); if self.proxy_header[0..signature_end] != PROXY_SIGNATURE[0..signature_end] { // re-emit everything / not a proxy connection if matches!(self.proxy_mode, ProxyMode::Require) { debug!("attempted non-proxy connection"); return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, anyhow!("invalid proxy protocol version"), ))); } self.proxy_header_target = 0; } else if self.proxy_header_index >= PROXY_PACKET_HEADER_LEN { let version = (self.proxy_header[12] & 0xf0) >> 4; if version != 2 { debug!("invalid proxy protocol version: {}", version); return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, anyhow!("invalid proxy protocol version"), ))); } let command = self.proxy_header[12] & 0x0f; if command > 0x01 { // 0 and 1 are only valid values debug!("invalid proxy protocol command: {}", command); return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, anyhow!("invalid proxy protocol command"), ))); } let is_proxy = command == 0x01; let family = (self.proxy_header[13] & 0xf0) >> 4; let protocol = self.proxy_header[13] & 0x0f; if protocol != 0x01 { // tcp/stream debug!("invalid proxy protocol protocol target: {}", protocol); return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, anyhow!("invalid proxy protocol protocol target"), ))); } let is_ipv4 = family == 0x01; let is_ipv6 = family == 0x02; if !is_ipv4 && !is_ipv6 { debug!("invalid proxy address family: {}", family); return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, anyhow!("invalid proxy address family"), ))); } let len = u16::from_be_bytes([self.proxy_header[14], self.proxy_header[15]]); let target_len = if !is_proxy { 0 } else if is_ipv4 { 12 } else { // is_ipv6 36 }; if len != target_len { debug!("invalid proxy address length: {}", target_len); return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, anyhow!("invalid proxy address length"), ))); } self.proxy_header_target = PROXY_PACKET_HEADER_LEN + len as usize; if self.proxy_header_index as usize >= self.proxy_header_target { if is_ipv4 { let src_addr = &self.proxy_header [PROXY_PACKET_HEADER_LEN..PROXY_PACKET_HEADER_LEN + 4]; // let dest_addr = &self.proxy_header[PROXY_PACKET_HEADER_LEN + 4..PROXY_PACKET_HEADER_LEN + 8]; let src_port = &self.proxy_header [PROXY_PACKET_HEADER_LEN + 8..PROXY_PACKET_HEADER_LEN + 10]; let src_port = u16::from_be_bytes([src_port[0], src_port[1]]); // let dest_port = &self.proxy_header[PROXY_PACKET_HEADER_LEN + 10..PROXY_PACKET_HEADER_LEN + 12]; self.discovered_remote = Some(SocketAddr::new( IpAddr::V4(Ipv4Addr::new( src_addr[0], src_addr[1], src_addr[2], src_addr[3], )), src_port, )); } else if is_ipv6 { // ipv6 let src_addr = &self.proxy_header [PROXY_PACKET_HEADER_LEN..PROXY_PACKET_HEADER_LEN + 16]; // let dest_addr = &self.proxy_header[PROXY_PACKET_HEADER_LEN + 16..PROXY_PACKET_HEADER_LEN + 32]; let src_port = &self.proxy_header [PROXY_PACKET_HEADER_LEN + 32..PROXY_PACKET_HEADER_LEN + 34]; let src_port = u16::from_be_bytes([src_port[0], src_port[1]]); // let dest_port = &self.proxy_header[PROXY_PACKET_HEADER_LEN + 34..PROXY_PACKET_HEADER_LEN + 36]; let src_addr: [u8; 16] = src_addr.try_into().expect("corrupt array length"); self.discovered_remote = Some(SocketAddr::new( IpAddr::V6(Ipv6Addr::from(src_addr)), src_port, )); } else if is_proxy { } self.proxy_header_rewrite_index = self.proxy_header_target; self.proxy_header_target = 0; } } } } } if !matches!(self.as_ref().proxy_mode, ProxyMode::None) && self.proxy_header_target == 0 && self.proxy_header_rewrite_index < self.proxy_header_index { let len = self.proxy_header_index - self.proxy_header_rewrite_index; let actual_len = if len < buf.remaining() { len } else { buf.remaining() }; buf.put_slice( &self.proxy_header [self.proxy_header_rewrite_index..self.proxy_header_rewrite_index + actual_len], ); self.proxy_header_rewrite_index += actual_len; if buf.remaining() == 0 { return Poll::Ready(Ok(())); } } self.inner.as_mut().poll_read(cx, buf) } } impl AsyncWrite for WrappedStream { #[inline] fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { self.inner.as_mut().poll_write(cx, buf) } #[inline] fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll<io::Result<usize>> { self.inner.as_mut().poll_write_vectored(cx, bufs) } #[inline] fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { self.inner.as_mut().poll_flush(cx) } #[inline] fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { self.inner.as_mut().poll_shutdown(cx) } #[inline] fn is_write_vectored(&self) -> bool { self.inner.is_write_vectored() } } impl Drop for WrappedStream { fn drop(&mut self) { self.conn_count.fetch_sub(1, Ordering::SeqCst); } }
41.164516
130
0.477784
62154dc363b931453530baddfa745770892732e2
3,179
pub use merkletree::store::StoreConfig; pub use storage_proofs_core::merkle::{MerkleProof, MerkleTreeTrait}; pub use storage_proofs_porep::stacked::{Labels, PersistentAux, TemporaryAux}; use cess_hashers::Hasher; use serde::{Deserialize, Serialize}; use storage_proofs_core::{merkle::BinaryMerkleTree, sector::SectorId}; use storage_proofs_porep::stacked; use storage_proofs_post::fallback; use crate::constants::DefaultPieceHasher; mod bytes_amount; mod piece_info; mod porep_config; mod porep_proof_partitions; mod post_config; mod post_proof_partitions; mod private_replica_info; mod public_replica_info; mod sector_class; mod sector_size; pub use bytes_amount::*; pub use piece_info::*; pub use porep_config::*; pub use porep_proof_partitions::*; pub use post_config::*; pub use post_proof_partitions::*; pub use private_replica_info::*; pub use public_replica_info::*; pub use sector_class::*; pub use sector_size::*; pub type Commitment = [u8; 32]; pub type ChallengeSeed = [u8; 32]; pub type ProverId = [u8; 32]; pub type Ticket = [u8; 32]; pub type DataTree = BinaryMerkleTree<DefaultPieceHasher>; /// Arity for oct trees, used for comm_r_last. pub const OCT_ARITY: usize = 8; /// Arity for binary trees, used for comm_d. pub const BINARY_ARITY: usize = 2; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SealPreCommitOutput { pub comm_r: Commitment, pub comm_d: Commitment, } pub type VanillaSealProof<Tree> = stacked::Proof<Tree, DefaultPieceHasher>; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct SealCommitPhase1Output<Tree: MerkleTreeTrait> { #[serde(bound( serialize = "VanillaSealProof<Tree>: Serialize", deserialize = "VanillaSealProof<Tree>: Deserialize<'de>" ))] pub vanilla_proofs: Vec<Vec<VanillaSealProof<Tree>>>, pub comm_r: Commitment, pub comm_d: Commitment, pub replica_id: <Tree::Hasher as Hasher>::Domain, pub seed: Ticket, pub ticket: Ticket, } #[derive(Clone, Debug)] pub struct SealCommitOutput { pub proof: Vec<u8>, } #[derive(Debug, Serialize, Deserialize)] pub struct SealPreCommitPhase1Output<Tree: MerkleTreeTrait> { #[serde(bound( serialize = "Labels<Tree>: Serialize", deserialize = "Labels<Tree>: Deserialize<'de>" ))] pub labels: Labels<Tree>, pub config: StoreConfig, pub comm_d: Commitment, } #[repr(transparent)] #[derive(Clone, Debug)] pub struct PartitionSnarkProof(pub Vec<u8>); pub type SnarkProof = Vec<u8>; pub type AggregateSnarkProof = Vec<u8>; pub type VanillaProof<Tree> = fallback::Proof<<Tree as MerkleTreeTrait>::Proof>; // This FallbackPoStSectorProof is used during Fallback PoSt, but // contains only Vanilla proof information and is not a full Fallback // PoSt proof. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FallbackPoStSectorProof<Tree: MerkleTreeTrait> { pub sector_id: SectorId, pub comm_r: <Tree::Hasher as Hasher>::Domain, #[serde(bound( serialize = "VanillaProof<Tree>: Serialize", deserialize = "VanillaProof<Tree>: Deserialize<'de>" ))] pub vanilla_proof: VanillaProof<Tree>, // Has comm_c, comm_r_last, inclusion_proofs }
29.990566
87
0.735451
e4d6992f3d9ecf76a23e717e3ba57da3431dc2cc
34,522
#[allow(dead_code,unused_imports)] use std::io::{BufWriter,Write,BufReader,BufRead}; use std::fs::File; use std::collections::HashMap; #[allow(unused_imports)] use std::collections::HashSet; use regex::Regex; use super::pdbdata::*; use super::geometry::Vector3D; const IS_MULTILINE:i64 = 0; const IS_SINGLELINE:i64 = 1; const NO_SEQ_ID:i64 = -999; const SECTION_NUMLETTER_MAX:usize = 30;//これより長いと複数行モードにされる const _ATOM_SITE_GROUP_PDB:&str ="_atom_site.group_PDB"; const _ATOM_SITE_ID:&str ="_atom_site.id"; const _ATOM_SITE_TYPE_SYMBOL:&str ="_atom_site.type_symbol"; const _ATOM_SITE_LABEL_ATOM_ID:&str ="_atom_site.label_atom_id"; const _ATOM_SITE_LABEL_ALT_ID:&str ="_atom_site.label_alt_id"; const _ATOM_SITE_LABEL_COMP_ID:&str ="_atom_site.label_comp_id"; const _ATOM_SITE_LABEL_ASYM_ID:&str ="_atom_site.label_asym_id"; const _ATOM_SITE_LABEL_ENTITY_ID:&str ="_atom_site.label_entity_id"; const _ATOM_SITE_LABEL_SEQ_ID:&str ="_atom_site.label_seq_id"; const _ATOM_SITE_PDBX_PDB_INS_CODE:&str ="_atom_site.pdbx_PDB_ins_code"; const _ATOM_SITE_CARTN_X:&str ="_atom_site.Cartn_x"; const _ATOM_SITE_CARTN_Y:&str ="_atom_site.Cartn_y"; const _ATOM_SITE_CARTN_Z:&str ="_atom_site.Cartn_z"; const _ATOM_SITE_OCCUPANCY:&str ="_atom_site.occupancy"; const _ATOM_SITE_B_ISO_OR_EQUIV:&str ="_atom_site.B_iso_or_equiv"; const _ATOM_SITE_PDBX_FORMAL_CHARGE:&str ="_atom_site.pdbx_formal_charge"; const _ATOM_SITE_AUTH_SEQ_ID:&str ="_atom_site.auth_seq_id"; const _ATOM_SITE_AUTH_COMP_ID:&str ="_atom_site.auth_comp_id"; const _ATOM_SITE_AUTH_ASYM_ID:&str ="_atom_site.auth_asym_id"; const _ATOM_SITE_AUTH_ATOM_ID:&str ="_atom_site.auth_atom_id"; const _ATOM_SITE_PDBX_PDB_MODEL_NUM:&str ="_atom_site.pdbx_PDB_model_num"; /*ToDo テスト構造で unknown polymer entity '1' near line 27 Unknown polymer entity '2' near line 230 Unknown polymer entity '3' near line 2196 Missing or incomplete entity_poly_seq table. Inferred polymer connectivity. と言われた。 */ lazy_static! { static ref REGEX_TAILBLANK:Regex = Regex::new(r"[\s]*$").unwrap(); static ref REGEX_DECIMAL:Regex = Regex::new(r"^([0-9\-]+)\.([0-9]+)$").unwrap(); static ref REGEX_QUOTATION_NEEDED:Regex = Regex::new("[\\s\"'\\(\\)]").unwrap(); //" static ref REGEX_WS:Regex = Regex::new(r"[\s]").unwrap(); } pub fn write_to_file(filename:&str,contents:Vec<String>){ let mut f = BufWriter::new(File::create(filename).unwrap()); for ll in contents{ f.write_all(ll.as_bytes()).unwrap(); f.write_all("\n".as_bytes()).unwrap(); } } pub fn start_with(target:&str,fragment:&str)-> bool{ if let Some(x) = target.find(fragment){ if x == 0{ return true; } } return false; } //一つの生要素を引用符着け、複数行化等 mmcif の値として互換の形にして MMCIF に書き込めるようにする //複数行にわたる場合は .1 が true pub fn get_compatible_values(target:&str)->(String,i64){ let re = regex::Regex::new(r"\r\n").unwrap(); let re2 = regex::Regex::new(r"[\r\n]").unwrap(); let mut lines:Vec<String> = vec![]; for pp in re.split(target){ for qq in re2.split(pp){ lines.push(qq.to_string()); } } if lines.len() > 1{ let mut ret:String=";".to_string(); for ll in lines.into_iter(){ ret += &ll; ret += "\n"; } return (ret+";",IS_MULTILINE); } let ret = quote(&lines[0]); return ret.unwrap_or((lines.remove(0),IS_SINGLELINE)); } //二番目は一行か複数行かを示す値が入る。 //閾値より長い、もしくは //ダブルクォート、シングルクォート両方があると複数行に分けられる。 pub fn quote(target:&str)->Option<(String,i64)>{ if let None = REGEX_QUOTATION_NEEDED.captures(&target){ return None; } let q:bool = match target.find("'"){ Some(_x)=>{true}, None=>{false}, }; let dq:bool = match target.find("\""){ Some(_x)=>{true}, None=>{false}, }; if q && dq || target.len() > SECTION_NUMLETTER_MAX{ return Some((";".to_string()+target+"\n;",IS_MULTILINE)); }else{ if q{ return Some(("\"".to_string()+target+"\"",IS_SINGLELINE)); }else if dq{ return Some(("'".to_string()+target+"'",IS_SINGLELINE)); }else{ return Some(("'".to_string()+target+"'",IS_SINGLELINE)); } } } pub fn parse_block(block:&Vec<String>) ->(Vec<String>,Vec<Vec<String>>){ let mut keys:Vec<String> = vec![]; let mut values:Vec<Vec<String>> = vec![]; //From https://github.com/rcsb/py-mmcif/blob/cf7d45a0c178658c856443c14dd2a2cd0b36a87b/mmcif/io/PdbxReader.py#L115 //rcsb @jdwestbrook //APL v2 let mmcif_re = Regex::new( ("(?:".to_string()+ "(?:_(.+?)[.](\\S+))"+//1:親ラベル、2:子ラベル "|"+ "(?:['](.*?)(?:[']\\s|[']$))"+//3:クオート "|"+ "(?:[\"](.*?)(?:[\"]\\s|[\"]$))"+//4:ダブルクオート "|"+ "(?:\\s*#.*$)"+//コメント "|"+ "(\\S+)"+//5:通常文字列 ")").as_str() ).unwrap(); let get_values = |l:&str|->Vec<String>{ let mut ret:Vec<String> = vec![]; let capp = mmcif_re.captures_iter(l); for cc in capp.into_iter(){ if let Some(x) = cc.get(3){ ret.push(x.as_str().to_string()); } if let Some(x) = cc.get(4){ ret.push(x.as_str().to_string()); } if let Some(x) = cc.get(5){ ret.push(x.as_str().to_string()); } } return ret; }; let oneline = Regex::new(r"^(_[^\s]+)[\s]+([^\s].*)[\r\n]*$").unwrap(); let mut multiline_flag = false; let mut buff:Vec<String> = vec![]; let loopmode:bool = start_with(&block[0],"loop_"); values.push(vec![]); for (lii,line) in block.iter().enumerate(){ if loopmode && lii == 0{ continue; } let mut currentblock:usize = values.len()-1; if !multiline_flag && start_with(line,"_"){ if let Some(x) = oneline.captures(line){ let keyy:String = x.get(1).unwrap().as_str().to_string(); let vall:String = x.get(2).unwrap().as_str().to_string(); values.get_mut(currentblock).unwrap().push(get_values(vall.as_str())[0].clone()); keys.push(keyy); }else{ keys.push(line.to_string()); } continue; } if start_with(line,";"){ if multiline_flag{ values[currentblock].push( buff.iter().fold("".to_string(),|s,m|s+m+"\n") ); multiline_flag = false; buff.clear(); }else{ assert!(buff.len() == 0); multiline_flag = true; let slen = line.len(); buff.push((&line[1..slen]).to_string()); } if loopmode && values[currentblock].len() == keys.len(){ values.push(vec![]); } continue; }else{ if multiline_flag{ buff.push(line.to_string()); }else{ let parsed = get_values(line.as_str()); for pp in parsed.into_iter(){ values.get_mut(currentblock).unwrap().push(pp); if loopmode && values[currentblock].len() == keys.len(){ values.push(vec![]); currentblock += 1; } } } //if loopmode && values[currentblock].len() == keys.len(){ // values.push(vec![]); //} } } for kk in keys.iter_mut(){ *kk = (*REGEX_TAILBLANK.replace_all(kk, "")).to_string(); } if values[values.len()-1].len() == 0{ values.pop(); } return (keys,values) } pub fn parse_mmcif(filename:&str)->Vec<(Vec<String>,Vec<Vec<String>>)>{ let mut ret:Vec<(Vec<String>,Vec<Vec<String>>)> = vec![]; let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut buff:Vec<String> = vec![]; for (_lcount,line_) in reader.lines().enumerate() { let line = line_.unwrap(); if start_with(&line,"#"){ if buff.len() > 0{ ret.push(parse_block(&buff)); buff.clear(); } continue; }else{ buff.push(line); } } if buff.len() > 0{ ret.push(parse_block(&buff)); buff.clear(); } return ret; } #[allow(dead_code)] pub struct MMCIFEntry{ //二番目要素はベクトルを持っていて、そのベクトルの値に対応するラベルが一番目の要素に入っている atom_site:(Vec<String>,Vec<AtomSite>), misc_section:Vec<(Vec<String>,Vec<MiscSection>)>, entry_id:String, header:String, } impl MMCIFEntry{ pub fn set_atom_site_section(&mut self,kk:Vec<String>,vll:Vec<AtomSite>){ /*何をしようとしていたか忘れてしまった。 let atom_site_map:HashMap<String,usize> = MMCIFEntry::get_key_index_map(&self.atom_site.0); let pxx:(i64,i64,i64)=( match atom_site_map.get(_ATOM_SITE_CARTN_X){Some(x)=>{*x as i64},None=>{-1}}, match atom_site_map.get(_ATOM_SITE_CARTN_Y){Some(x)=>{*x as i64},None=>{-1}}, match atom_site_map.get(_ATOM_SITE_CARTN_Z){Some(x)=>{*x as i64},None=>{-1}} ); */ self.atom_site =(kk,vll); self.update_atom_site_index(); } pub fn update_atom_site_index(&mut self){ for (aii,aa) in self.atom_site.1.iter_mut().enumerate(){ aa.set_atom_index(aii as i64); } } //PDB データに見つからなかった AtomSite のインデクスを返す pub fn assign_cartn(&mut self,pdbb:&PDBEntry,add_new_atoms:bool) ->Vec<usize>{ let atom_site_map:HashMap<String,usize> = MMCIFEntry::get_key_index_map(&self.atom_site.0); let mut newatoms_all:Vec<AtomSite> = vec![]; let mut newatoms_notassigned:Vec<AtomSite> = vec![]; let xyz:(usize,usize,usize) = ( *atom_site_map.get(_ATOM_SITE_CARTN_X).expect("Cartn_x is not found.") ,*atom_site_map.get(_ATOM_SITE_CARTN_Y).expect("Cartn_y is not found.") ,*atom_site_map.get(_ATOM_SITE_CARTN_Z).expect("Cartn_z is not found.") ); let occ:i64 = match atom_site_map.get(_ATOM_SITE_OCCUPANCY){Some(x) => {*x as i64},None=>{-1}}; let biso:i64 = match atom_site_map.get(_ATOM_SITE_B_ISO_OR_EQUIV){Some(x) => {*x as i64},None=>{-1}}; let f_charge:i64 = match atom_site_map.get(_ATOM_SITE_PDBX_FORMAL_CHARGE){Some(x) => {*x as i64},None=>{-1}}; let mut updated:Vec<bool> = vec![false;self.atom_site.1.len()]; let mut haspointer_all:i64 = -1;//最後に Model num とかを付ける場合に使用 for cc in pdbb.chains.iter(){ for rr in cc.residues.iter(){ let mut newatoms:Vec<AtomSite> = vec![]; for aa in rr.iter_atoms(){ let p_ = aa.get_external_array_pointer(); let mut targetatom_:Option<&mut AtomSite> = None; if p_ > -1{ if haspointer_all < 0{ haspointer_all = p_; } let p:usize = p_ as usize; updated[p] = true; targetatom_ = Some(&mut self.atom_site.1[p]); }else if add_new_atoms{ let mut naa:AtomSite = AtomSite::new(); naa.set_num_values(self.atom_site.0.len()); if aa.het{ naa.set_value_of(_ATOM_SITE_GROUP_PDB,"HETATM".to_string(),&atom_site_map,true); }else{ naa.set_value_of(_ATOM_SITE_GROUP_PDB,"ATOM".to_string(),&atom_site_map,true); } naa.set_value_of(_ATOM_SITE_ID,aa.index.to_string(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_TYPE_SYMBOL,aa.atom_symbol.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_LABEL_ATOM_ID,aa.atom_code.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_LABEL_ALT_ID,aa.alt_code.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_AUTH_ATOM_ID,aa.atom_code.to_string(),&atom_site_map,true); newatoms.push(naa); targetatom_ = Some(newatoms.last_mut().unwrap()); } if let None = targetatom_{ continue; } let targetatom:&mut AtomSite = targetatom_.unwrap(); targetatom.set_xyz( aa.get_x(), aa.get_y(), aa.get_z(), xyz ); if occ > -1{ targetatom.set_occupancy(aa.occupancy,(occ as usize,)); } if biso > -1{ targetatom.set_temperature_factor(aa.temp_factor,(biso as usize,)); } if f_charge > -1{ if let Some(x) = aa.charge.as_ref(){ targetatom.set_formal_charge(x.clone(),(f_charge as usize,)); } } } let mut haspointer:i64 = -1; for (aii,aa) in rr.iter_atoms().enumerate(){ let p_ = aa.get_external_array_pointer(); if p_ > -1{ haspointer = aii as i64; } } if haspointer > -1{ let refatom:&AtomSite = &self.atom_site.1[haspointer as usize]; let ikeys:Vec<&str> = vec![ _ATOM_SITE_LABEL_COMP_ID ,_ATOM_SITE_LABEL_ASYM_ID ,_ATOM_SITE_LABEL_ENTITY_ID ,_ATOM_SITE_LABEL_SEQ_ID ,_ATOM_SITE_PDBX_PDB_INS_CODE ,_ATOM_SITE_AUTH_SEQ_ID ,_ATOM_SITE_AUTH_COMP_ID ,_ATOM_SITE_AUTH_ASYM_ID ,_ATOM_SITE_PDBX_PDB_MODEL_NUM ]; for nn in newatoms.iter_mut(){ nn.copy_information_from(refatom,&ikeys,&atom_site_map); } newatoms_all.append(&mut newatoms); }else{ for naa in newatoms.iter_mut(){ //同じ Residue 中にマップされた原子が無い場合 residue とかの情報を使って再構成する naa.set_value_of(_ATOM_SITE_LABEL_COMP_ID,rr.residue_name.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_LABEL_ASYM_ID,cc.chain_name.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_LABEL_SEQ_ID,rr.get_residue_number().to_string(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_AUTH_COMP_ID,rr.residue_name.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_AUTH_ASYM_ID,cc.chain_name.clone(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_AUTH_SEQ_ID,rr.get_residue_number().to_string(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_PDBX_PDB_INS_CODE,rr.get_ins_code().to_string(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_LABEL_ENTITY_ID,"?".to_string(),&atom_site_map,true); naa.set_value_of(_ATOM_SITE_PDBX_PDB_MODEL_NUM,"?".to_string(),&atom_site_map,true); } newatoms_notassigned.append(&mut newatoms); } } } if haspointer_all > -1 && newatoms_notassigned.len() > 0{ let refatom:&AtomSite = &self.atom_site.1[haspointer_all as usize]; let ikeys:Vec<&str> = vec![ _ATOM_SITE_LABEL_ENTITY_ID ,_ATOM_SITE_PDBX_PDB_MODEL_NUM ]; for nn in newatoms_notassigned.iter_mut(){ nn.copy_information_from(refatom,&ikeys,&atom_site_map); } newatoms_all.append(&mut newatoms_notassigned); } self.atom_site.1.append(&mut newatoms_all); let mut ret:Vec<usize> = vec![]; for mm in 0..updated.len(){ if !updated[mm]{ ret.push(mm); } } return ret; } //ToDo: use auth 途中 pub fn load_mmcif(filename:&str,use_auth:bool)->(MMCIFEntry,PDBEntry){ let mut blocks:Vec<(Vec<String>,Vec<Vec<String>>)> = parse_mmcif(filename); let mut atom_site_block_:Option<(Vec<String>,Vec<Vec<String>>)> = None; //let mut atom_sites:Vec<AtomSite> = vec![]; let header = blocks.remove(0); //println!("{}",MMCIFEntry::blocks_to_string(&blocks)); let mut misc_section:Vec<(Vec<String>,Vec<MiscSection>)> = vec![]; let mut entry_id:String = "NONE".to_string(); for bb in blocks.into_iter(){ if bb.0.len() == 0{//entry continue; } if start_with(&bb.0[0],"_atom_site."){ atom_site_block_ = Some(bb); }else if start_with(&bb.0[0],"_entry."){ let mut eindex:i64 = -1; for eii in 0..bb.0.len(){ if bb.0[eii] == "_entry.id"{ eindex = eii as i64; } } if eindex > -1{ entry_id = bb.1[0][eindex as usize].clone(); } misc_section.push( (bb.0,bb.1.into_iter().map(|m|MiscSection{values:m}).collect()) ); }else{ misc_section.push( (bb.0,bb.1.into_iter().map(|m|MiscSection{values:m}).collect()) ); } } let mut ret = MMCIFEntry{ atom_site:(vec![],vec![]), entry_id:entry_id, header:header.1[0][0].clone(), misc_section:misc_section }; if let Some(x) = atom_site_block_{ let (keys,values) = x; let mut atoms:Vec<AtomSite> = vec![]; for vv in values.into_iter(){ if vv.len() == 0{ continue; } let mut atom:AtomSite = AtomSite::new(); atom.values = vv; atoms.push(atom); } ret.set_atom_site_section(keys,atoms); }else{ panic!("can not find _atom_site. block!"); } let ret2:PDBEntry = MMCIFEntry::atomsite_to_entry(&ret,false); return (ret,ret2); } pub fn get_key_index_map(vs:&Vec<String>)->HashMap<String,usize>{ let mut ret:HashMap<String,usize> = HashMap::new(); for (vii,vss) in vs.iter().enumerate(){ ret.insert(vss.to_string(),vii); } return ret; } pub fn atomsite_to_entry(mmcif:&MMCIFEntry,use_auth:bool)->PDBEntry{ let mut ret:PDBEntry = PDBEntry::new(); let mut chains:HashMap<String,Vec<Vec<&AtomSite>>> = HashMap::new(); let mut chains_rindex:HashMap<String,HashMap<String,usize>> = HashMap::new(); let atom_site_map:HashMap<String,usize> = MMCIFEntry::get_key_index_map(&mmcif.atom_site.0); let asym_id_label:String; let _atom_id_label:String;//CA とか CB とか atom_name let comp_id_label:String; let seq_id_label:String; if use_auth{ asym_id_label = _ATOM_SITE_AUTH_ASYM_ID.to_string(); comp_id_label = _ATOM_SITE_AUTH_COMP_ID.to_string(); _atom_id_label = _ATOM_SITE_AUTH_ATOM_ID.to_string(); seq_id_label = _ATOM_SITE_AUTH_SEQ_ID.to_string(); }else{ asym_id_label = _ATOM_SITE_LABEL_ASYM_ID.to_string(); comp_id_label = _ATOM_SITE_LABEL_COMP_ID.to_string(); _atom_id_label = _ATOM_SITE_LABEL_ATOM_ID.to_string(); seq_id_label = _ATOM_SITE_LABEL_SEQ_ID.to_string(); } let asym_id_:usize = *atom_site_map.get(&asym_id_label).unwrap_or_else(||panic!("{} is not defined.",asym_id_label)); let comp_id_:usize = *atom_site_map.get(&comp_id_label).unwrap_or_else(||panic!("{} is not defined.",comp_id_label)); let seq_id_:usize = *atom_site_map.get(&seq_id_label).unwrap_or_else(||panic!("{} is not defined.",seq_id_label)); //let atom_id_:usize = *atom_site_map.get(&atom_id_label).unwrap_or_else(||panic!("{} is not defined.",atom_id_label)); for (_aii,aa) in mmcif.atom_site.1.iter().enumerate(){ let asym_id:String = aa.values[asym_id_].clone(); if !chains.contains_key(&asym_id){ chains.insert(asym_id.clone(),vec![]); chains_rindex.insert(asym_id.clone(),HashMap::new()); } let r_label:String = aa.get_unique_residue_label(&atom_site_map); if !chains_rindex.get(&asym_id).unwrap().contains_key(r_label.as_str()){ chains_rindex.get_mut(&asym_id).unwrap().insert( r_label.clone(),chains.get(&asym_id).unwrap().len()); chains.get_mut(&asym_id).unwrap().push(vec![]); } //一つの残基につき一意になるような Reside label をハッシュキーにしてが同じものは一つの Vector に入れる。 let rpos:&usize = chains_rindex.get_mut(asym_id.as_str()).unwrap().get(r_label.as_str()).unwrap(); chains.get_mut(asym_id.as_str()).unwrap()[*rpos].push(aa); } for (_cc,rr) in chains.into_iter(){ //Chain の実体を作成する let mut cc:PDBChain = PDBChain::new(&_cc); for vv in rr.into_iter(){ //Residue の実体を作成する let atoms_v:Vec<&AtomSite> = vv; let aa = &atoms_v[0]; let comp_id:String = aa.values[comp_id_].clone(); let seq_id:String = aa.values[seq_id_].clone(); let ins_code:String = aa.get_value_of(_ATOM_SITE_PDBX_PDB_INS_CODE,&atom_site_map).to_string(); let mut rr:PDBResidue = PDBResidue::new(); if seq_id == "."{ //HOH に seq_id が設定されていない。。。 rr.set_residue_number(NO_SEQ_ID); }else{ rr.set_residue_number(seq_id.parse::<i64>().unwrap_or_else(|_|panic!("{} can not parse.",seq_id))); if rr.get_residue_number() == NO_SEQ_ID{ panic!("{} is not allowed!",NO_SEQ_ID); } } rr.residue_name = comp_id.clone(); rr.ins_code = ins_code; for aa in atoms_v.iter(){ let att:PDBAtom = aa.atom_site_to_pdbatom(&atom_site_map ,use_auth); rr.add_atom(att,true); } cc.add_residue(rr,true); } ret.add_chain(cc,true); } for (cii,cc) in ret.chains.iter().enumerate(){ for (rii,rr) in cc.residues.iter().enumerate(){ assert_eq!(cii as i64,rr.parent_chain.unwrap()); for (_aii,aa) in rr.iter_atoms().enumerate(){ assert_eq!(cii as i64,aa.parent_chain.unwrap()); assert_eq!(rii as i64,aa.parent_residue.unwrap()); //println!("{} {} {} {} {} {} ",cc.chain_name,rr.residue_name,aa.atom_code,aa.get_x(),aa.get_y(),aa.get_z()); } } } return ret; } //それぞれのセクションが持っているのは //(Vec<key>,Vec<Vec<value>>) というタプルであるべきで、それを MMCIF フォーマットに整形する。 pub fn blocks_to_strings(blocks:&Vec<(&Vec<String>,&Vec<&Vec<String>>)>)->Vec<String>{ let mut ret:Vec<String> = vec![]; for vv in blocks.iter(){ ret.push("# ".to_string()); let lab = &vv.0; let val = &vv.1; if val.len() == 1{ let lines:&Vec<String> = &val[0]; assert_eq!(lab.len(),lines.len()); for ii in 0..lines.len(){ let cval = get_compatible_values(&lines[ii]); if cval.1 == IS_MULTILINE{ ret.push(format!("{} \n{}",lab[ii],&cval.0)); }else{ ret.push(format!("{} {} ",lab[ii],&cval.0)); } } }else{ ret.push("loop_".to_string()); for ii in 0..lab.len(){ ret.push(lab[ii].clone()+" "); } //カラムサイズが同じでないと駄目らしい。少なくとも UCSF Chimera では let mut maxnumletter:Vec<usize> = vec![0;lab.len()]; for vv in val.iter(){ if vv.len() == 0{ continue; } assert_eq!(lab.len(),vv.len()); for ii in 0..lab.len(){ let cval = get_compatible_values(&vv[ii]); if cval.1 == IS_SINGLELINE{ maxnumletter[ii] = maxnumletter[ii].max(cval.0.len()); } } } let mut ws_maxnum:Vec<String> = vec![]; for sii in maxnumletter.iter(){ //文字の位置を他の行と合わせる ws_maxnum.push((0..*sii).into_iter().fold(" ".to_string(),|s,_|s+" ")+" "); } for vv in val.iter(){ if vv.len() == 0{ continue; } let mut lline:String = "".to_string(); let mut prev_cr:i64 = IS_SINGLELINE; for ii in 0..lab.len(){ let cval = get_compatible_values(&vv[ii]); if cval.1 == IS_MULTILINE{ if ii != 0 && prev_cr == IS_SINGLELINE{ lline += "\n"; } lline += cval.0.as_str(); if ii != lab.len()-1{ lline += "\n"; } }else{ lline += &((format!("{}",cval.0.as_str())+ws_maxnum[ii].as_str())[0..=maxnumletter[ii]]); } prev_cr = cval.1; } ret.push(lline); } } } return ret; } //めちゃ遅い・・・ pub fn save(&self,filename:&str){ let mut lines:Vec<String> = vec![]; lines.push(self.header.clone()); for ll in self.misc_section.iter(){ let val:Vec<&Vec<String>> = ll.1.iter().map(|m|{&m.values}).collect(); lines.append(&mut MMCIFEntry::blocks_to_strings( &vec![(&ll.0,&val)] )); } let asite:Vec<&Vec<String>> = self.atom_site.1.iter().map(|m|&m.values).collect(); lines.append(&mut MMCIFEntry::blocks_to_strings( &vec![(&self.atom_site.0,&asite)] )); lines.push("# ".to_string()); write_to_file(filename,lines); } } pub struct MiscSection{ pub values:Vec<String> } #[allow(non_snake_case)] pub struct AtomSite{ pub values:Vec<String>, pub atom_index:i64, //MMCIFEntry 内の Vec にあるこのインスタンスのインデクス。PDBAtom から参照する pub used_auth:bool } impl AtomSite{ //残基名とかチェーン名とか、上位情報をコピーする pub fn copy_information_from(&mut self,src:&AtomSite,keys:&Vec<&str>,vmap:&HashMap<String,usize>){ assert_eq!(self.values.len(),src.values.len()); for ii in 0..keys.len(){ if vmap.contains_key(keys[ii]){ let uii:usize = *vmap.get(keys[ii]).unwrap(); self.values[uii] = src.values[uii].clone(); } } } pub fn set_num_values(&mut self,siz:usize){ assert!(self.values.len() == 0); self.values = vec!["?".to_string();siz]; } pub fn new()->AtomSite{ return AtomSite{ values:vec![], atom_index:-1, used_auth:false }; } //MMCIFEntry 内の Vec にあるこのインスタンスのインデクスを与えてください pub fn set_atom_index(&mut self,i:i64){ self.atom_index = i; } //PDBAtom 以外から変更されることを今のところ想定していない //小数点以下の桁数を合わせるためであり、あまり意味はない。 //set_value とかでもよいと思う。 fn set_xyz(&mut self,x:f64,y:f64,z:f64,indices:(usize,usize,usize)){ self.values[indices.0] = format!("{:.3}",x); self.values[indices.1] = format!("{:.3}",y); self.values[indices.2] = format!("{:.3}",z); } fn set_occupancy(&mut self,v:f64,indices:(usize,)){ self.values[indices.0] = format!("{:.2}",v); } fn set_temperature_factor(&mut self,v:f64,indices:(usize,)){ self.values[indices.0] = format!("{:.2}",v); } fn set_formal_charge(&mut self,v:String,indices:(usize,)){ self.values[indices.0] = v; } pub fn set_value_of(&mut self,k:&str,v:String,vmap:&HashMap<String,usize>,dont_panic:bool){ if !vmap.contains_key(k){ if !dont_panic{ panic!("{} is not found in key list.",k); } return; } self.values[*vmap.get(k).unwrap()] = v; } pub fn atom_site_to_pdbatom(&self,vmap:&HashMap<String,usize>,use_auth:bool)->PDBAtom{ let mut ret = PDBAtom::new(); if self.get_atom_index() < 0{ panic!("update_atom_site_index must have been performed at first."); } ret.set_external_array_pointer(self.get_atom_index()); ret.set_xyz(self.get_value_of(_ATOM_SITE_CARTN_X,&vmap).parse::<f64>().unwrap_or_else(|_|panic!("can not parse x")) ,self.get_value_of(_ATOM_SITE_CARTN_Y,&vmap).parse::<f64>().unwrap_or_else(|_|panic!("can not parse y")) ,self.get_value_of(_ATOM_SITE_CARTN_Z,&vmap).parse::<f64>().unwrap_or_else(|_|panic!("can not parse z")) ); ret.serial_number = self.get_value_of(_ATOM_SITE_ID,vmap).parse::<i64>().expect("Cannot parse atom id."); ret.atom_symbol = self.get_value_of(_ATOM_SITE_TYPE_SYMBOL,vmap).to_string(); ret.alt_code = self.get_value_of(_ATOM_SITE_LABEL_ALT_ID,vmap).to_string(); if ret.alt_code == "?" || ret.alt_code == "."{ ret.alt_code = "".to_string(); } ret.dummy = false; if self.get_value_of(_ATOM_SITE_GROUP_PDB,vmap) == "HETATM"{ ret.het = true; }else{ ret.het = false; } if vmap.contains_key(_ATOM_SITE_PDBX_FORMAL_CHARGE){ let fcc:String = self.get_value_of(_ATOM_SITE_PDBX_FORMAL_CHARGE,vmap).to_string(); if fcc == "?" || fcc == "."{ ret.charge = None; }else{ ret.charge = Some(fcc); } } if vmap.contains_key(_ATOM_SITE_OCCUPANCY){ ret.occupancy = self.get_value_of(_ATOM_SITE_OCCUPANCY,vmap).parse::<f64>().unwrap(); } if vmap.contains_key(_ATOM_SITE_B_ISO_OR_EQUIV){ ret.temp_factor = self.get_value_of(_ATOM_SITE_B_ISO_OR_EQUIV,vmap).parse::<f64>().unwrap(); } if use_auth{ ret.atom_code = self.get_value_of(_ATOM_SITE_AUTH_ATOM_ID,vmap).to_string(); }else{ ret.atom_code = self.get_value_of(_ATOM_SITE_LABEL_ATOM_ID,vmap).to_string(); } return ret; } pub fn get_atom_index(&self)->i64{ return self.atom_index; } pub fn get_value_of(&self,key:&str,vmap:&HashMap<String,usize>)->&str{ return match vmap.get(key){ Some(x)=>self.values[*x].as_str(), None=>"?"}; } pub fn get_unique_residue_label(&self,vmap:&HashMap<String,usize>)->String{ return "".to_string() +self.get_value_of(_ATOM_SITE_LABEL_COMP_ID,vmap) +"#" +self.get_value_of(_ATOM_SITE_LABEL_SEQ_ID,vmap) +"#" +self.get_value_of(_ATOM_SITE_AUTH_COMP_ID,vmap) +"#" +self.get_value_of(_ATOM_SITE_AUTH_SEQ_ID,vmap) +"#" +self.get_value_of(_ATOM_SITE_PDBX_PDB_INS_CODE,vmap) ; } } #[test] fn regextest(){ let mmcif_re = Regex::new( ("(?:".to_string()+ "(?:_(.+?)[.](\\S+))"+//1:親ラベル、2:子ラベル "|"+ "(?:['](.*?)(?:[']\\s|[']$))"+//3:クオート "|"+ "(?:[\"](.*?)(?:[\"]\\s|[\"]$))"+//4:ダブルクオート "|"+ "(?:\\s*#.*$)"+//コメント "|"+ "(\\S+)"+//5:通常文字列 ")").as_str() ).unwrap(); let line = "HETATM 2274 C \"C1'\" . 'QWE' F 5 . ? 16.593 -13.014 18.550 1.00 33.08 ? 373 QWE H \"C1'\" 1 "; let capp = mmcif_re.captures_iter(line); for cc in capp.into_iter(){ println!("{:?}",cc); } } #[test] fn mmcifloadtest(){ let pdbentry = MMCIFEntry::load_mmcif("example_files/ins_example_1a4w.cif",false); for mm in pdbentry.0.misc_section.iter(){//atom_site を間違うと他でエラーが出ると思う for ii in 0..(mm.1).len(){ assert_eq!(mm.0.len(),mm.1[ii].values.len()); } } pdbentry.1.save("test/mmcifout_1a4w.pdb"); pdbentry.0.save("test/mmcifout_1a4w.cif"); } #[test] fn quote_check(){ //こういう仕様だと思うが間違っているかもしれない。 assert_eq!(get_compatible_values("test"),("test".to_string(),IS_SINGLELINE)); assert_eq!(get_compatible_values("(test)"),("'(test)'".to_string(),IS_SINGLELINE)); assert_eq!(get_compatible_values("t\"est"),("'t\"est'".to_string(),IS_SINGLELINE)); //ダブルクォートとシングルクォートが混ざっている場合が特に不明 assert_eq!(get_compatible_values("t\"'est"),(";t\"'est\n;".to_string(),IS_MULTILINE)); assert_eq!(get_compatible_values("t'est"),("\"t'est\"".to_string(),IS_SINGLELINE)); assert_eq!(get_compatible_values("te\nst"),(";te\nst\n;".to_string(),IS_MULTILINE)); assert_eq!(get_compatible_values("te\rst"),(";te\nst\n;".to_string(),IS_MULTILINE)); assert_eq!(get_compatible_values("te\r\nst"),(";te\nst\n;".to_string(),IS_MULTILINE)); assert_eq!(get_compatible_values("t'e\r\ns't"),(";t'e\ns't\n;".to_string(),IS_MULTILINE)); }
38.145856
129
0.532443
e423762ae73c8e2bbbf3369071def102fe4d73ff
12,251
#[doc = "Register `INTFLAG` reader"] pub struct R(crate::R<INTFLAG_SPEC>); impl core::ops::Deref for R { type Target = crate::R<INTFLAG_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<INTFLAG_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<INTFLAG_SPEC>) -> Self { R(reader) } } #[doc = "Register `INTFLAG` writer"] pub struct W(crate::W<INTFLAG_SPEC>); impl core::ops::Deref for W { type Target = crate::W<INTFLAG_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<INTFLAG_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<INTFLAG_SPEC>) -> Self { W(writer) } } #[doc = "Field `HSOF` reader - Host Start Of Frame"] pub struct HSOF_R(crate::FieldReader<bool, bool>); impl HSOF_R { pub(crate) fn new(bits: bool) -> Self { HSOF_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for HSOF_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `HSOF` writer - Host Start Of Frame"] pub struct HSOF_W<'a> { w: &'a mut W, } impl<'a> HSOF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u16 & 0x01) << 2); self.w } } #[doc = "Field `RST` reader - Bus Reset"] pub struct RST_R(crate::FieldReader<bool, bool>); impl RST_R { pub(crate) fn new(bits: bool) -> Self { RST_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RST_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RST` writer - Bus Reset"] pub struct RST_W<'a> { w: &'a mut W, } impl<'a> RST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u16 & 0x01) << 3); self.w } } #[doc = "Field `WAKEUP` reader - Wake Up"] pub struct WAKEUP_R(crate::FieldReader<bool, bool>); impl WAKEUP_R { pub(crate) fn new(bits: bool) -> Self { WAKEUP_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for WAKEUP_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `WAKEUP` writer - Wake Up"] pub struct WAKEUP_W<'a> { w: &'a mut W, } impl<'a> WAKEUP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u16 & 0x01) << 4); self.w } } #[doc = "Field `DNRSM` reader - Downstream"] pub struct DNRSM_R(crate::FieldReader<bool, bool>); impl DNRSM_R { pub(crate) fn new(bits: bool) -> Self { DNRSM_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DNRSM_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DNRSM` writer - Downstream"] pub struct DNRSM_W<'a> { w: &'a mut W, } impl<'a> DNRSM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u16 & 0x01) << 5); self.w } } #[doc = "Field `UPRSM` reader - Upstream Resume from the Device"] pub struct UPRSM_R(crate::FieldReader<bool, bool>); impl UPRSM_R { pub(crate) fn new(bits: bool) -> Self { UPRSM_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for UPRSM_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `UPRSM` writer - Upstream Resume from the Device"] pub struct UPRSM_W<'a> { w: &'a mut W, } impl<'a> UPRSM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u16 & 0x01) << 6); self.w } } #[doc = "Field `RAMACER` reader - Ram Access"] pub struct RAMACER_R(crate::FieldReader<bool, bool>); impl RAMACER_R { pub(crate) fn new(bits: bool) -> Self { RAMACER_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RAMACER_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RAMACER` writer - Ram Access"] pub struct RAMACER_W<'a> { w: &'a mut W, } impl<'a> RAMACER_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u16 & 0x01) << 7); self.w } } #[doc = "Field `DCONN` reader - Device Connection"] pub struct DCONN_R(crate::FieldReader<bool, bool>); impl DCONN_R { pub(crate) fn new(bits: bool) -> Self { DCONN_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DCONN_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DCONN` writer - Device Connection"] pub struct DCONN_W<'a> { w: &'a mut W, } impl<'a> DCONN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u16 & 0x01) << 8); self.w } } #[doc = "Field `DDISC` reader - Device Disconnection"] pub struct DDISC_R(crate::FieldReader<bool, bool>); impl DDISC_R { pub(crate) fn new(bits: bool) -> Self { DDISC_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DDISC_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DDISC` writer - Device Disconnection"] pub struct DDISC_W<'a> { w: &'a mut W, } impl<'a> DDISC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u16 & 0x01) << 9); self.w } } impl R { #[doc = "Bit 2 - Host Start Of Frame"] #[inline(always)] pub fn hsof(&self) -> HSOF_R { HSOF_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Bus Reset"] #[inline(always)] pub fn rst(&self) -> RST_R { RST_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Wake Up"] #[inline(always)] pub fn wakeup(&self) -> WAKEUP_R { WAKEUP_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Downstream"] #[inline(always)] pub fn dnrsm(&self) -> DNRSM_R { DNRSM_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Upstream Resume from the Device"] #[inline(always)] pub fn uprsm(&self) -> UPRSM_R { UPRSM_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Ram Access"] #[inline(always)] pub fn ramacer(&self) -> RAMACER_R { RAMACER_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Device Connection"] #[inline(always)] pub fn dconn(&self) -> DCONN_R { DCONN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Device Disconnection"] #[inline(always)] pub fn ddisc(&self) -> DDISC_R { DDISC_R::new(((self.bits >> 9) & 0x01) != 0) } } impl W { #[doc = "Bit 2 - Host Start Of Frame"] #[inline(always)] pub fn hsof(&mut self) -> HSOF_W { HSOF_W { w: self } } #[doc = "Bit 3 - Bus Reset"] #[inline(always)] pub fn rst(&mut self) -> RST_W { RST_W { w: self } } #[doc = "Bit 4 - Wake Up"] #[inline(always)] pub fn wakeup(&mut self) -> WAKEUP_W { WAKEUP_W { w: self } } #[doc = "Bit 5 - Downstream"] #[inline(always)] pub fn dnrsm(&mut self) -> DNRSM_W { DNRSM_W { w: self } } #[doc = "Bit 6 - Upstream Resume from the Device"] #[inline(always)] pub fn uprsm(&mut self) -> UPRSM_W { UPRSM_W { w: self } } #[doc = "Bit 7 - Ram Access"] #[inline(always)] pub fn ramacer(&mut self) -> RAMACER_W { RAMACER_W { w: self } } #[doc = "Bit 8 - Device Connection"] #[inline(always)] pub fn dconn(&mut self) -> DCONN_W { DCONN_W { w: self } } #[doc = "Bit 9 - Device Disconnection"] #[inline(always)] pub fn ddisc(&mut self) -> DDISC_W { DDISC_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.0.bits(bits); self } } #[doc = "HOST Host Interrupt Flag\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 [intflag](index.html) module"] pub struct INTFLAG_SPEC; impl crate::RegisterSpec for INTFLAG_SPEC { type Ux = u16; } #[doc = "`read()` method returns [intflag::R](R) reader structure"] impl crate::Readable for INTFLAG_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [intflag::W](W) writer structure"] impl crate::Writable for INTFLAG_SPEC { type Writer = W; } #[doc = "`reset()` method sets INTFLAG to value 0"] impl crate::Resettable for INTFLAG_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
28.163218
412
0.553751
f8eb22ed7de8b9d0d930b95980bb483a4ede6c09
1,168
struct Solution; impl Solution { pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> { let mut left = 0; let mut right = numbers.len() - 1; while left < right { match numbers[left] + numbers[right] { x if x == target => return vec![left as i32 + 1, right as i32 + 1], x if x < target => left += 1, _ => right -= 1, } } vec![-1, -1] } } struct Example { input: (Vec<i32>, i32), output: Vec<i32>, } #[test] pub fn test() { let examples = vec![ Example { input: (vec![2, 7, 11, 15], 9), output: vec![1, 2], }, Example { input: (vec![2, 3, 4], 6), output: vec![1, 3], }, Example { input: (vec![-1, 0], -1), output: vec![1, 2], }, Example { input: (vec![-5, -4, -3, -2, -1], -8), output: vec![1, 3], }, ]; for example in examples { assert_eq!( Solution::two_sum(example.input.0, example.input.1), example.output ); } }
23.36
83
0.411815
1c15d38a50ac526a4a5d5ff56154c9a5a9abc3bf
692
fn main() { const MAX_NUMBERS: usize = 2020; let input = "6,13,1,15,2,0"; // "0,3,6"; let mut spoken_numbers = Vec::with_capacity(MAX_NUMBERS); spoken_numbers.extend(input.split(',').map(|n| n.parse::<u32>().unwrap())); for _ in 0..MAX_NUMBERS - spoken_numbers.len() { let last_num = *spoken_numbers.last().unwrap(); spoken_numbers.push( spoken_numbers .iter() .rev() .skip(1) .position(|&n| n == last_num) .map(|diff| (diff + 1) as _) .unwrap_or(0), ); } let answer = *spoken_numbers.last().unwrap(); println!("{}", answer); }
32.952381
79
0.504335
f960f02e61032eef694c09a0da65251ea5f4a109
1,897
use crate::checks::Check; use crate::common::*; pub(crate) struct LowercaseKeyChecker<'a> { name: &'a str, template: &'a str, } impl Default for LowercaseKeyChecker<'_> { fn default() -> Self { Self { name: "LowercaseKey", template: "The {} key should be in uppercase", } } } impl Check for LowercaseKeyChecker<'_> { fn run(&mut self, line: &LineEntry) -> Option<Warning> { let key = line.get_key()?; if key.to_uppercase() == key { None } else { Some(Warning::new(line.clone(), self.name(), self.message(&key))) } } fn name(&self) -> &str { self.name } } impl LowercaseKeyChecker<'_> { fn message(&self, key: &str) -> String { self.template.replace("{}", key) } } #[cfg(test)] mod tests { use super::*; use crate::common::tests::*; #[test] fn working_run() { let mut checker = LowercaseKeyChecker::default(); let line = line_entry(1, 1, "FOO=BAR"); assert_eq!(None, checker.run(&line)); } #[test] fn failing_run_with_lowercase_key() { let mut checker = LowercaseKeyChecker::default(); let line = line_entry(1, 1, "foo_bar=FOOBAR"); let expected = Some(Warning::new( line.clone(), "LowercaseKey", String::from("The foo_bar key should be in uppercase"), )); assert_eq!(expected, checker.run(&line)); } #[test] fn failing_run_with_lowercase_letter() { let mut checker = LowercaseKeyChecker::default(); let line = line_entry(1, 1, "FOo_BAR=FOOBAR"); let expected = Some(Warning::new( line.clone(), "LowercaseKey", String::from("The FOo_BAR key should be in uppercase"), )); assert_eq!(expected, checker.run(&line)); } }
25.293333
77
0.550343
899a4b6c97cfce25ba8a7e4fc785179017e30d3c
4,643
//! An implementation of HKDF, the [HMAC-based Extract-and-Expand Key Derivation Function][1]. //! //! # Usage //! //! ```rust //! # extern crate hex; //! # extern crate hkdf; //! # extern crate sha2; //! //! # use sha2::Sha256; //! # use hkdf::Hkdf; //! //! # fn main() { //! let ikm = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(); //! let salt = hex::decode("000102030405060708090a0b0c").unwrap(); //! let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap(); //! //! let h = Hkdf::<Sha256>::new(Some(&salt[..]), &ikm); //! let mut okm = [0u8; 42]; //! h.expand(&info, &mut okm).unwrap(); //! println!("OKM is {}", hex::encode(&okm[..])); //! # } //! ``` //! //! [1]: https://tools.ietf.org/html/rfc5869 #![no_std] extern crate digest; extern crate hmac; #[cfg(feature = "std")] extern crate std; use core::fmt; use digest::generic_array::{self, ArrayLength, GenericArray}; use digest::{BlockInput, FixedOutput, Input, Reset}; use hmac::{Hmac, Mac}; /// Error that is returned when supplied pseudorandom key (PRK) is not long enough. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct InvalidPrkLength; /// Structure for InvalidLength, used for output error handling. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct InvalidLength; /// Structure representing the HKDF, capable of HKDF-Expand and HKDF-extract operations. #[derive(Clone)] pub struct Hkdf<D> where D: Input + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength<u8>, D::OutputSize: ArrayLength<u8>, { hmac: Hmac<D>, } impl<D> Hkdf<D> where D: Input + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength<u8>, D::OutputSize: ArrayLength<u8>, { /// Convenience method for [`extract`] when the generated pseudorandom /// key can be ignored and only HKDF-Expand operation is needed. This is /// the most common constructor. pub fn new(salt: Option<&[u8]>, ikm: &[u8]) -> Hkdf<D> { let (_, hkdf) = Hkdf::extract(salt, ikm); hkdf } /// Create `Hkdf` from an already cryptographically strong pseudorandom key /// as per section 3.3 from RFC5869. pub fn from_prk(prk: &[u8]) -> Result<Hkdf<D>, InvalidPrkLength> { use generic_array::typenum::Unsigned; // section 2.3 specifies that prk must be "at least HashLen octets" if prk.len() < D::OutputSize::to_usize() { return Err(InvalidPrkLength); } Ok(Hkdf { hmac: Hmac::new_varkey(prk).expect("HMAC can take a key of any size"), }) } /// The RFC5869 HKDF-Extract operation returning both the generated /// pseudorandom key and `Hkdf` struct for expanding. pub fn extract(salt: Option<&[u8]>, ikm: &[u8]) -> (GenericArray<u8, D::OutputSize>, Hkdf<D>) { let mut hmac = match salt { Some(s) => Hmac::<D>::new_varkey(s).expect("HMAC can take a key of any size"), None => Hmac::<D>::new(&Default::default()), }; hmac.input(ikm); let prk = hmac.result().code(); let hkdf = Hkdf::from_prk(&prk).expect("PRK size is correct"); (prk, hkdf) } /// The RFC5869 HKDF-Expand operation pub fn expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength> { use generic_array::typenum::Unsigned; let mut prev: Option<GenericArray<u8, <D as digest::FixedOutput>::OutputSize>> = None; let hmac_output_bytes = D::OutputSize::to_usize(); if okm.len() > hmac_output_bytes * 255 { return Err(InvalidLength); } let mut hmac = self.hmac.clone(); for (blocknum, okm_block) in okm.chunks_mut(hmac_output_bytes).enumerate() { let block_len = okm_block.len(); if let Some(ref prev) = prev { hmac.input(prev) }; hmac.input(info); hmac.input(&[blocknum as u8 + 1]); let output = hmac.result_reset().code(); okm_block.copy_from_slice(&output[..block_len]); prev = Some(output); } Ok(()) } } impl fmt::Display for InvalidPrkLength { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_str("invalid pseudorandom key length, too short") } } #[cfg(feature = "std")] impl ::std::error::Error for InvalidPrkLength {} impl fmt::Display for InvalidLength { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_str("invalid number of blocks, too large output") } } #[cfg(feature = "std")] impl ::std::error::Error for InvalidLength {}
31.161074
99
0.610381
e94635b959424c8b7ca0fcd20db170fe4af78287
40,731
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. // // @generated SignedSource<<14b42234f61d10165227c877456579ab>> // // To regenerate this file, run: // hphp/hack/src/oxidized_regen.sh use arena_trait::TrivialDrop; use no_pos_hash::NoPosHash; use ocamlrep_derive::FromOcamlRep; use ocamlrep_derive::FromOcamlRepIn; use ocamlrep_derive::ToOcamlRep; use serde::Deserialize; use serde::Serialize; #[allow(unused_imports)] use crate::*; pub use aast_defs::*; pub use doc_comment::DocComment; /// Aast.program represents the top-level definitions in a Hack program. /// ex: Expression annotation type (when typechecking, the inferred type) /// fb: Function body tag (e.g. has naming occurred) /// en: Environment (tracking state inside functions and classes) /// hi: Hint annotation (when typechecking it will be the localized type hint or the /// inferred missing type if the hint is missing) pub type Program<Ex, Fb, En, Hi> = Vec<Def<Ex, Fb, En, Hi>>; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Stmt<Ex, Fb, En, Hi>(pub Pos, pub Stmt_<Ex, Fb, En, Hi>); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Stmt_<Ex, Fb, En, Hi> { /// Marker for a switch statement that falls through. /// /// // FALLTHROUGH Fallthrough, /// Standalone expression. /// /// 1 + 2; Expr(Box<Expr<Ex, Fb, En, Hi>>), /// Break inside a loop or switch statement. /// /// break; Break, /// Continue inside a loop or switch statement. /// /// continue; Continue, /// Throw an exception. /// /// throw $foo; Throw(Box<Expr<Ex, Fb, En, Hi>>), /// Return, with an optional value. /// /// return; /// return $foo; Return(Box<Option<Expr<Ex, Fb, En, Hi>>>), /// Yield break, terminating the current generator. This behaves like /// return; but is more explicit, and ensures the function is treated /// as a generator. /// /// yield break; YieldBreak, /// Concurrent block. All the await expressions are awaited at the /// same time, similar to genva(). /// /// We store the desugared form. In the below example, the list is: /// [('__tmp$1', f()), (__tmp$2, g()), (None, h())] /// and the block assigns the temporary variables back to the locals. /// { $foo = __tmp$1; $bar = __tmp$2; } /// /// concurrent { /// $foo = await f(); /// $bar = await g(); /// await h(); /// } Awaitall( Box<( Vec<(Option<Lid>, Expr<Ex, Fb, En, Hi>)>, Block<Ex, Fb, En, Hi>, )>, ), /// If statement. /// /// if ($foo) { ... } else { ... } If( Box<( Expr<Ex, Fb, En, Hi>, Block<Ex, Fb, En, Hi>, Block<Ex, Fb, En, Hi>, )>, ), /// Do-while loop. /// /// do { /// bar(); /// } while($foo) Do(Box<(Block<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>)>), /// While loop. /// /// while ($foo) { /// bar(); /// } While(Box<(Expr<Ex, Fb, En, Hi>, Block<Ex, Fb, En, Hi>)>), /// Initialize a value that is automatically disposed of. /// /// using $foo = bar(); // disposed at the end of the function /// using ($foo = bar(), $baz = quux()) {} // disposed after the block Using(Box<UsingStmt<Ex, Fb, En, Hi>>), /// For loop. The initializer and increment parts can include /// multiple comma-separated statements. The termination condition is /// optional. /// /// for ($i = 0; $i < 100; $i++) { ... } /// for ($x = 0, $y = 0; ; $x++, $y++) { ... } For( Box<( Vec<Expr<Ex, Fb, En, Hi>>, Option<Expr<Ex, Fb, En, Hi>>, Vec<Expr<Ex, Fb, En, Hi>>, Block<Ex, Fb, En, Hi>, )>, ), /// Switch statement. /// /// switch ($foo) { /// case X: /// bar(); /// break; /// default: /// baz(); /// break; /// } Switch(Box<(Expr<Ex, Fb, En, Hi>, Vec<Case<Ex, Fb, En, Hi>>)>), /// For-each loop. /// /// foreach ($items as $item) { ... } /// foreach ($items as $key => value) { ... } /// foreach ($items await as $item) { ... } // AsyncIterator<_> /// foreach ($items await as $key => value) { ... } // AsyncKeyedIterator<_> Foreach( Box<( Expr<Ex, Fb, En, Hi>, AsExpr<Ex, Fb, En, Hi>, Block<Ex, Fb, En, Hi>, )>, ), /// Try statement, with catch blocks and a finally block. /// /// try { /// foo(); /// } catch (SomeException $e) { /// bar(); /// } finally { /// baz(); /// } Try( Box<( Block<Ex, Fb, En, Hi>, Vec<Catch<Ex, Fb, En, Hi>>, Block<Ex, Fb, En, Hi>, )>, ), /// No-op, the empty statement. /// /// {} /// while (true) ; /// if ($foo) {} // the else is Noop here Noop, /// Block, a list of statements in curly braces. /// /// { $foo = 42; } Block(Block<Ex, Fb, En, Hi>), /// The mode tag at the beginning of a file. /// TODO: this really belongs in def. /// /// <?hh Markup(Box<Pstring>), /// Used in IFC to track type inference environments. Not user /// denotable. AssertEnv(Box<(EnvAnnot, LocalIdMap<Ex>)>), } #[derive( Clone, Copy, Debug, Deserialize, Eq, FromOcamlRep, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum EnvAnnot { Join, Refinement, } impl TrivialDrop for EnvAnnot {} arena_deserializer::impl_deserialize_in_arena!(EnvAnnot); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct UsingStmt<Ex, Fb, En, Hi> { pub is_block_scoped: bool, pub has_await: bool, pub exprs: (Pos, Vec<Expr<Ex, Fb, En, Hi>>), pub block: Block<Ex, Fb, En, Hi>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum AsExpr<Ex, Fb, En, Hi> { AsV(Expr<Ex, Fb, En, Hi>), AsKv(Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>), AwaitAsV(Pos, Expr<Ex, Fb, En, Hi>), AwaitAsKv(Pos, Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>), } pub type Block<Ex, Fb, En, Hi> = Vec<Stmt<Ex, Fb, En, Hi>>; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassId<Ex, Fb, En, Hi>(pub Ex, pub ClassId_<Ex, Fb, En, Hi>); /// Class ID, used in things like instantiation and static property access. #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassId_<Ex, Fb, En, Hi> { /// The class ID of the parent of the lexically scoped class. /// /// In a trait, it is the parent class ID of the using class. /// /// parent::some_meth() /// parent::$prop = 1; /// new parent(); CIparent, /// The class ID of the lexically scoped class. /// /// In a trait, it is the class ID of the using class. /// /// self::some_meth() /// self::$prop = 1; /// new self(); CIself, /// The class ID of the late static bound class. /// /// https://www.php.net/manual/en/language.oop5.late-static-bindings.php /// /// In a trait, it is the late static bound class ID of the using class. /// /// static::some_meth() /// static::$prop = 1; /// new static(); CIstatic, /// Dynamic class name. /// /// TODO: Syntactically this can only be an Lvar/This/Lplacehodller. /// We should use lid rather than expr. /// /// // Assume $d has type dynamic. /// $d::some_meth(); /// $d::$prop = 1; /// new $d(); CIexpr(Expr<Ex, Fb, En, Hi>), /// Explicit class name. This is the common case. /// /// Foop::some_meth() /// Foo::$prop = 1; /// new Foo(); CI(Sid), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Expr<Ex, Fb, En, Hi>(pub Ex, pub Expr_<Ex, Fb, En, Hi>); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum CollectionTarg<Hi> { CollectionTV(Targ<Hi>), CollectionTKV(Targ<Hi>, Targ<Hi>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum FunctionPtrId<Ex, Fb, En, Hi> { FPId(Sid), FPClassConst(ClassId<Ex, Fb, En, Hi>, Pstring), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ExpressionTree<Ex, Fb, En, Hi> { pub hint: Hint, pub splices: Block<Ex, Fb, En, Hi>, pub virtualized_expr: Expr<Ex, Fb, En, Hi>, pub runtime_expr: Expr<Ex, Fb, En, Hi>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Expr_<Ex, Fb, En, Hi> { /// darray literal. /// /// darray['x' => 0, 'y' => 1] /// darray<string, int>['x' => 0, 'y' => 1] Darray( Box<( Option<(Targ<Hi>, Targ<Hi>)>, Vec<(Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>)>, )>, ), /// varray literal. /// /// varray['hello', 'world'] /// varray<string>['hello', 'world'] Varray(Box<(Option<Targ<Hi>>, Vec<Expr<Ex, Fb, En, Hi>>)>), /// Shape literal. /// /// shape('x' => 1, 'y' => 2) Shape(Vec<(ast_defs::ShapeFieldName, Expr<Ex, Fb, En, Hi>)>), /// Collection literal for indexable structures. /// /// Vector {1, 2} /// ImmVector {} /// Set<string> {'foo', 'bar'} /// vec[1, 2] /// keyset[] ValCollection(Box<(VcKind, Option<Targ<Hi>>, Vec<Expr<Ex, Fb, En, Hi>>)>), /// Collection literal for key-value structures. /// /// dict['x' => 1, 'y' => 2] /// Map<int, string> {} /// ImmMap {} KeyValCollection( Box<( KvcKind, Option<(Targ<Hi>, Targ<Hi>)>, Vec<Field<Ex, Fb, En, Hi>>, )>, ), /// Null literal. /// /// null Null, /// The local variable representing the current class instance. /// /// $this This, /// Boolean literal. /// /// true True, /// Boolean literal. /// /// false False, /// The empty expression. /// /// list(, $y) = vec[1, 2] // Omitted is the first expression inside list() Omitted, /// An identifier. Used for method names and global constants. /// /// SOME_CONST /// $x->foo() // id: "foo" Id(Box<Sid>), /// Local variable. /// /// $foo Lvar(Box<Lid>), /// The extra variable in a pipe expression. /// /// $$ Dollardollar(Box<Lid>), /// Clone expression. /// /// clone $foo Clone(Box<Expr<Ex, Fb, En, Hi>>), /// Array indexing. /// /// $foo[] /// $foo[$bar] ArrayGet(Box<(Expr<Ex, Fb, En, Hi>, Option<Expr<Ex, Fb, En, Hi>>)>), /// Instance property or method access. is_prop_call is always /// false, except when inside a call is accessing a property. /// /// $foo->bar // (Obj_get false) property access /// $foo->bar() // (Call (Obj_get false)) method call /// ($foo->bar)() // (Call (Obj_get true)) call lambda stored in property /// $foo?->bar // nullsafe access ObjGet( Box<( Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>, OgNullFlavor, bool, )>, ), /// Static property access. /// /// Foo::$bar /// $some_classname::$bar /// Foo::${$bar} // only in partial mode ClassGet(Box<(ClassId<Ex, Fb, En, Hi>, ClassGetExpr<Ex, Fb, En, Hi>, bool)>), /// Class constant or static method call. As a standalone expression, /// this is a class constant. Inside a Call node, this is a static /// method call. /// /// This is not ambiguous, because constants are not allowed to /// contain functions. /// /// Foo::some_const // Class_const /// Foo::someStaticMeth() // Call (Class_const) /// /// This syntax is used for both static and instance methods when /// calling the implementation on the superclass. /// /// parent::someStaticMeth() /// parent::someInstanceMeth() ClassConst(Box<(ClassId<Ex, Fb, En, Hi>, Pstring)>), /// Function or method call. /// /// foo() /// $x() /// foo<int>(1, 2, ...$rest) /// $x->foo() /// /// async { return 1; } /// // lowered to: /// (async () ==> { return 1; })() Call( Box<( Expr<Ex, Fb, En, Hi>, Vec<Targ<Hi>>, Vec<Expr<Ex, Fb, En, Hi>>, Option<Expr<Ex, Fb, En, Hi>>, )>, ), /// A reference to a function or method. /// /// foo_fun<> /// FooCls::meth<int> FunctionPointer(Box<(FunctionPtrId<Ex, Fb, En, Hi>, Vec<Targ<Hi>>)>), /// Integer literal. /// /// 42 /// 0123 // octal /// 0xBEEF // hexadecimal /// 0b11111111 // binary Int(String), /// Float literal. /// /// 1.0 /// 1.2e3 /// 7E-10 Float(String), /// String literal. /// /// "foo" /// 'foo' /// /// <<<DOC /// foo /// DOC /// /// <<<'DOC' /// foo /// DOC String(bstr::BString), /// Interpolated string literal. /// /// "hello $foo $bar" /// /// <<<DOC /// hello $foo $bar /// DOC String2(Vec<Expr<Ex, Fb, En, Hi>>), /// Prefixed string literal. Only used for regular expressions. /// /// re"foo" PrefixedString(Box<(String, Expr<Ex, Fb, En, Hi>)>), /// Yield expression. The enclosing function should have an Iterator /// return type. /// /// yield $foo // enclosing function returns an Iterator /// yield $foo => $bar // enclosing function returns a KeyedIterator Yield(Box<Afield<Ex, Fb, En, Hi>>), /// Await expression. /// /// await $foo Await(Box<Expr<Ex, Fb, En, Hi>>), /// Readonly expression. /// /// readonly $foo ReadonlyExpr(Box<Expr<Ex, Fb, En, Hi>>), /// Tuple expression. /// /// tuple("a", 1, $foo) Tuple(Vec<Expr<Ex, Fb, En, Hi>>), /// List expression, only used in destructuring. Allows any arbitrary /// lvalue as a subexpression. May also nest. /// /// list($x, $y) = vec[1, 2]; /// list(, $y) = vec[1, 2]; // skipping items /// list(list($x)) = vec[vec[1]]; // nesting /// list($v[0], $x[], $y->foo) = $blah; List(Vec<Expr<Ex, Fb, En, Hi>>), /// Cast expression, converting a value to a different type. Only /// primitive types are supported in the hint position. /// /// (int)$foo /// (string)$foo Cast(Box<(Hint, Expr<Ex, Fb, En, Hi>)>), /// Unary operator. /// /// !$foo /// -$foo /// +$foo Unop(Box<(ast_defs::Uop, Expr<Ex, Fb, En, Hi>)>), /// Binary operator. /// /// $foo + $bar Binop(Box<(ast_defs::Bop, Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>)>), /// Pipe expression. The lid is the ID of the $$ that is implicitly /// declared by this pipe. /// /// See also Dollardollar. /// /// $foo |> bar() // equivalent: bar($foo) /// $foo |> bar(1, $$) // equivalent: bar(1, $foo) Pipe(Box<(Lid, Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>)>), /// Ternary operator, or elvis operator. /// /// $foo ? $bar : $baz // ternary /// $foo ?: $baz // elvis Eif( Box<( Expr<Ex, Fb, En, Hi>, Option<Expr<Ex, Fb, En, Hi>>, Expr<Ex, Fb, En, Hi>, )>, ), /// Is operator. /// /// $foo is SomeType Is(Box<(Expr<Ex, Fb, En, Hi>, Hint)>), /// As operator. /// /// $foo as int /// $foo ?as int As(Box<(Expr<Ex, Fb, En, Hi>, Hint, bool)>), /// Instantiation. /// /// new Foo(1, 2); /// new Foo<int, T>(); /// new Foo('blah', ...$rest); New( Box<( ClassId<Ex, Fb, En, Hi>, Vec<Targ<Hi>>, Vec<Expr<Ex, Fb, En, Hi>>, Option<Expr<Ex, Fb, En, Hi>>, Ex, )>, ), /// Record literal. /// /// MyRecord['x' => $foo, 'y' => $bar] Record(Box<(Sid, Vec<(Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>)>)>), /// PHP-style lambda. Does not capture variables unless explicitly /// specified. /// /// Mnemonic: 'expanded lambda', since we can desugar Lfun to Efun. /// /// function($x) { return $x; } /// function(int $x): int { return $x; } /// function($x) use ($y) { return $y; } /// function($x): int use ($y, $z) { return $x + $y + $z; } Efun(Box<(Fun_<Ex, Fb, En, Hi>, Vec<Lid>)>), /// Hack lambda. Captures variables automatically. /// /// $x ==> $x /// (int $x): int ==> $x + $other /// ($x, $y) ==> { return $x + $y; } Lfun(Box<(Fun_<Ex, Fb, En, Hi>, Vec<Lid>)>), /// XHP expression. May contain interpolated expressions. /// /// <foo x="hello" y={$foo}>hello {$bar}</foo> Xml( Box<( Sid, Vec<XhpAttribute<Ex, Fb, En, Hi>>, Vec<Expr<Ex, Fb, En, Hi>>, )>, ), /// Explicit calling convention, used for inout. Inout supports any lvalue. /// /// TODO: This could be a flag on parameters in Call. /// /// foo(inout $x[0]) Callconv(Box<(ast_defs::ParamKind, Expr<Ex, Fb, En, Hi>)>), /// Include or require expression. /// /// require('foo.php') /// require_once('foo.php') /// include('foo.php') /// include_once('foo.php') Import(Box<(ImportFlavor, Expr<Ex, Fb, En, Hi>)>), /// Collection literal. /// /// TODO: T38184446 this is redundant with ValCollection/KeyValCollection. /// /// Vector {} Collection(Box<(Sid, Option<CollectionTarg<Hi>>, Vec<Afield<Ex, Fb, En, Hi>>)>), /// Expression tree literal. Expression trees are not evaluated at /// runtime, but desugared to an expression representing the code. /// /// Foo`1 + bar()` /// Foo`$x ==> $x * ${$value}` // splicing $value ExpressionTree(Box<ExpressionTree<Ex, Fb, En, Hi>>), /// Placeholder local variable. /// /// $_ Lplaceholder(Box<Pos>), /// Global function reference. /// /// fun('foo') FunId(Box<Sid>), /// Instance method reference on a specific instance. /// /// TODO: This is only created in naming, and ought to happen in /// lowering or be removed. The emitter just sees a normal Call. /// /// inst_meth($f, 'some_meth') // equivalent: $f->some_meth<> MethodId(Box<(Expr<Ex, Fb, En, Hi>, Pstring)>), /// Instance method reference that can be called with an instance. /// /// meth_caller(FooClass::class, 'some_meth') /// meth_caller('FooClass', 'some_meth') /// /// These examples are equivalent to: /// /// (FooClass $f, ...$args) ==> $f->some_meth(...$args) MethodCaller(Box<(Sid, Pstring)>), /// Static method reference. /// /// class_meth('FooClass', 'some_static_meth') /// // equivalent: FooClass::some_static_meth<> SmethodId(Box<(ClassId<Ex, Fb, En, Hi>, Pstring)>), /// Pair literal. /// /// Pair {$foo, $bar} Pair( Box<( Option<(Targ<Hi>, Targ<Hi>)>, Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>, )>, ), /// Expression tree splice expression. Only valid inside an /// expression tree literal (backticks). /// /// ${$foo} ETSplice(Box<Expr<Ex, Fb, En, Hi>>), /// Label used for enum classes. /// /// enum_name#label_name or #label_name EnumClassLabel(Box<(Option<Sid>, String)>), /// Annotation used to record failure in subtyping or coercion of an /// expression and calls to [unsafe_cast] or [enforced_cast]. /// /// The [hole_source] indicates whether this came from an /// explicit call to [unsafe_cast] or [enforced_cast] or was /// generated during typing. /// /// Given a call to [unsafe_cast]: /// ``` /// function f(int $x): void { /* ... */ } /// /// function g(float $x): void { /// f(unsafe_cast<float,int>($x)); /// } /// ``` /// After typing, this is represented by the following TAST fragment /// ``` /// Call /// ( ( (..., function(int $x): void), Id (..., "\f")) /// , [] /// , [ ( (..., int) /// , Hole /// ( ((..., float), Lvar (..., $x)) /// , float /// , int /// , UnsafeCast /// ) /// ) /// ] /// , None /// ) /// ``` Hole(Box<(Expr<Ex, Fb, En, Hi>, Hi, Hi, HoleSource)>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassGetExpr<Ex, Fb, En, Hi> { CGstring(Pstring), CGexpr(Expr<Ex, Fb, En, Hi>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Case<Ex, Fb, En, Hi> { Default(Pos, Block<Ex, Fb, En, Hi>), Case(Expr<Ex, Fb, En, Hi>, Block<Ex, Fb, En, Hi>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Catch<Ex, Fb, En, Hi>(pub Sid, pub Lid, pub Block<Ex, Fb, En, Hi>); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Field<Ex, Fb, En, Hi>(pub Expr<Ex, Fb, En, Hi>, pub Expr<Ex, Fb, En, Hi>); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Afield<Ex, Fb, En, Hi> { AFvalue(Expr<Ex, Fb, En, Hi>), AFkvalue(Expr<Ex, Fb, En, Hi>, Expr<Ex, Fb, En, Hi>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct XhpSimple<Ex, Fb, En, Hi> { pub name: Pstring, pub type_: Hi, pub expr: Expr<Ex, Fb, En, Hi>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum XhpAttribute<Ex, Fb, En, Hi> { XhpSimple(XhpSimple<Ex, Fb, En, Hi>), XhpSpread(Expr<Ex, Fb, En, Hi>), } pub type IsVariadic = bool; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FunParam<Ex, Fb, En, Hi> { pub annotation: Ex, pub type_hint: TypeHint<Hi>, pub is_variadic: IsVariadic, pub pos: Pos, pub name: String, pub expr: Option<Expr<Ex, Fb, En, Hi>>, pub readonly: Option<ast_defs::ReadonlyKind>, pub callconv: Option<ast_defs::ParamKind>, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub visibility: Option<Visibility>, } /// Does this function/method take a variable number of arguments? #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum FunVariadicity<Ex, Fb, En, Hi> { /// Named variadic argument. /// /// function foo(int ...$args): void {} FVvariadicArg(FunParam<Ex, Fb, En, Hi>), /// Unnamed variaidic argument. Partial mode only. /// /// function foo(...): void {} FVellipsis(Pos), /// Function is not variadic, takes an exact number of arguments. FVnonVariadic, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Fun_<Ex, Fb, En, Hi> { pub span: Pos, pub readonly_this: Option<ast_defs::ReadonlyKind>, pub annotation: En, pub readonly_ret: Option<ast_defs::ReadonlyKind>, pub ret: TypeHint<Hi>, pub name: Sid, pub tparams: Vec<Tparam<Ex, Fb, En, Hi>>, pub where_constraints: Vec<WhereConstraintHint>, pub variadic: FunVariadicity<Ex, Fb, En, Hi>, pub params: Vec<FunParam<Ex, Fb, En, Hi>>, pub ctxs: Option<Contexts>, pub unsafe_ctxs: Option<Contexts>, pub body: FuncBody<Ex, Fb, En, Hi>, pub fun_kind: ast_defs::FunKind, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, /// true if this declaration has no body because it is an /// external function declaration (e.g. from an HHI file) pub external: bool, pub doc_comment: Option<DocComment>, } /// Naming has two phases and the annotation helps to indicate the phase. /// In the first pass, it will perform naming on everything except for function /// and method bodies and collect information needed. Then, another round of /// naming is performed where function bodies are named. Thus, naming will /// have named and unnamed variants of the annotation. /// See BodyNamingAnnotation in nast.ml and the comment in naming.ml #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FuncBody<Ex, Fb, En, Hi> { pub ast: Block<Ex, Fb, En, Hi>, pub annotation: Fb, } /// A type annotation is two things: /// - the localized hint, or if the hint is missing, the inferred type /// - The typehint associated to this expression if it exists #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct TypeHint<Hi>(pub Hi, pub TypeHint_); /// Explicit type argument to function, constructor, or collection literal. /// 'hi = unit in NAST /// 'hi = Typing_defs.(locl ty) in TAST, /// and is used to record inferred type arguments, with wildcard hint. #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Targ<Hi>(pub Hi, pub Hint); pub type TypeHint_ = Option<Hint>; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct UserAttribute<Ex, Fb, En, Hi> { pub name: Sid, /// user attributes are restricted to scalar values pub params: Vec<Expr<Ex, Fb, En, Hi>>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FileAttribute<Ex, Fb, En, Hi> { pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub namespace: Nsenv, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Tparam<Ex, Fb, En, Hi> { pub variance: ast_defs::Variance, pub name: Sid, pub parameters: Vec<Tparam<Ex, Fb, En, Hi>>, pub constraints: Vec<(ast_defs::ConstraintKind, Hint)>, pub reified: ReifyKind, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct UseAsAlias( pub Option<Sid>, pub Pstring, pub Option<Sid>, pub Vec<UseAsVisibility>, ); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct InsteadofAlias(pub Sid, pub Pstring, pub Vec<Sid>); pub type IsExtends = bool; #[derive( Clone, Copy, Debug, Deserialize, Eq, FromOcamlRep, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum EmitId { EmitId(isize), Anonymous, } arena_deserializer::impl_deserialize_in_arena!(EmitId); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Class_<Ex, Fb, En, Hi> { pub span: Pos, pub annotation: En, pub mode: file_info::Mode, pub final_: bool, pub is_xhp: bool, pub has_xhp_keyword: bool, pub kind: ast_defs::ClassKind, pub name: Sid, /// The type parameters of a class A<T> (T is the parameter) pub tparams: Vec<Tparam<Ex, Fb, En, Hi>>, pub extends: Vec<ClassHint>, pub uses: Vec<TraitHint>, /// PHP feature not supported in hack but required /// because we have runtime support. pub use_as_alias: Vec<UseAsAlias>, /// PHP feature not supported in hack but required /// because we have runtime support. pub insteadof_alias: Vec<InsteadofAlias>, pub xhp_attr_uses: Vec<XhpAttrHint>, pub xhp_category: Option<(Pos, Vec<Pstring>)>, pub reqs: Vec<(ClassHint, IsExtends)>, pub implements: Vec<ClassHint>, pub support_dynamic_type: bool, pub where_constraints: Vec<WhereConstraintHint>, pub consts: Vec<ClassConst<Ex, Fb, En, Hi>>, pub typeconsts: Vec<ClassTypeconstDef<Ex, Fb, En, Hi>>, pub vars: Vec<ClassVar<Ex, Fb, En, Hi>>, pub methods: Vec<Method_<Ex, Fb, En, Hi>>, pub attributes: Vec<ClassAttr<Ex, Fb, En, Hi>>, pub xhp_children: Vec<(Pos, XhpChild)>, pub xhp_attrs: Vec<XhpAttr<Ex, Fb, En, Hi>>, pub namespace: Nsenv, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub file_attributes: Vec<FileAttribute<Ex, Fb, En, Hi>>, pub enum_: Option<Enum_>, pub doc_comment: Option<DocComment>, pub emit_id: Option<EmitId>, } pub type ClassHint = Hint; pub type TraitHint = Hint; pub type XhpAttrHint = Hint; #[derive( Clone, Copy, Debug, Deserialize, Eq, FromOcamlRep, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum XhpAttrTag { Required, LateInit, } impl TrivialDrop for XhpAttrTag {} arena_deserializer::impl_deserialize_in_arena!(XhpAttrTag); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct XhpAttr<Ex, Fb, En, Hi>( pub TypeHint<Hi>, pub ClassVar<Ex, Fb, En, Hi>, pub Option<XhpAttrTag>, pub Option<(Pos, Vec<Expr<Ex, Fb, En, Hi>>)>, ); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassAttr<Ex, Fb, En, Hi> { CAName(Sid), CAField(CaField<Ex, Fb, En, Hi>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct CaField<Ex, Fb, En, Hi> { pub type_: CaType, pub id: Sid, pub value: Option<Expr<Ex, Fb, En, Hi>>, pub required: bool, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum CaType { CAHint(Hint), CAEnum(Vec<String>), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassConst<Ex, Fb, En, Hi> { pub type_: Option<Hint>, pub id: Sid, /// expr = None indicates an abstract const pub expr: Option<Expr<Ex, Fb, En, Hi>>, pub doc_comment: Option<DocComment>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassAbstractTypeconst { pub as_constraint: Option<Hint>, pub super_constraint: Option<Hint>, pub default: Option<Hint>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassConcreteTypeconst { pub c_tc_type: Hint, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassPartiallyAbstractTypeconst { pub constraint: Hint, pub type_: Hint, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassTypeconst { TCAbstract(ClassAbstractTypeconst), TCConcrete(ClassConcreteTypeconst), TCPartiallyAbstract(ClassPartiallyAbstractTypeconst), } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassTypeconstDef<Ex, Fb, En, Hi> { pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub name: Sid, pub kind: ClassTypeconst, pub span: Pos, pub doc_comment: Option<DocComment>, pub is_ctx: bool, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct XhpAttrInfo { pub tag: Option<XhpAttrTag>, pub enum_values: Vec<ast_defs::XhpEnumValue>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassVar<Ex, Fb, En, Hi> { pub final_: bool, pub xhp_attr: Option<XhpAttrInfo>, pub abstract_: bool, pub readonly: bool, pub visibility: Visibility, pub type_: TypeHint<Hi>, pub id: Sid, pub expr: Option<Expr<Ex, Fb, En, Hi>>, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub doc_comment: Option<DocComment>, pub is_promoted_variadic: bool, pub is_static: bool, pub span: Pos, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Method_<Ex, Fb, En, Hi> { pub span: Pos, pub annotation: En, pub final_: bool, pub abstract_: bool, pub static_: bool, pub readonly_this: bool, pub visibility: Visibility, pub name: Sid, pub tparams: Vec<Tparam<Ex, Fb, En, Hi>>, pub where_constraints: Vec<WhereConstraintHint>, pub variadic: FunVariadicity<Ex, Fb, En, Hi>, pub params: Vec<FunParam<Ex, Fb, En, Hi>>, pub ctxs: Option<Contexts>, pub unsafe_ctxs: Option<Contexts>, pub body: FuncBody<Ex, Fb, En, Hi>, pub fun_kind: ast_defs::FunKind, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub readonly_ret: Option<ast_defs::ReadonlyKind>, pub ret: TypeHint<Hi>, /// true if this declaration has no body because it is an external method /// declaration (e.g. from an HHI file) pub external: bool, pub doc_comment: Option<DocComment>, } pub type Nsenv = ocamlrep::rc::RcOc<namespace_env::Env>; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Typedef<Ex, Fb, En, Hi> { pub annotation: En, pub name: Sid, pub tparams: Vec<Tparam<Ex, Fb, En, Hi>>, pub constraint: Option<Hint>, pub kind: Hint, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub mode: file_info::Mode, pub vis: TypedefVisibility, pub namespace: Nsenv, pub span: Pos, pub emit_id: Option<EmitId>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Gconst<Ex, Fb, En, Hi> { pub annotation: En, pub mode: file_info::Mode, pub name: Sid, pub type_: Option<Hint>, pub value: Expr<Ex, Fb, En, Hi>, pub namespace: Nsenv, pub span: Pos, pub emit_id: Option<EmitId>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct RecordDef<Ex, Fb, En, Hi> { pub annotation: En, pub name: Sid, pub extends: Option<RecordHint>, pub abstract_: bool, pub fields: Vec<(Sid, Hint, Option<Expr<Ex, Fb, En, Hi>>)>, pub user_attributes: Vec<UserAttribute<Ex, Fb, En, Hi>>, pub namespace: Nsenv, pub span: Pos, pub doc_comment: Option<DocComment>, pub emit_id: Option<EmitId>, } pub type RecordHint = Hint; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FunDef<Ex, Fb, En, Hi> { pub namespace: Nsenv, pub file_attributes: Vec<FileAttribute<Ex, Fb, En, Hi>>, pub mode: file_info::Mode, pub fun: Fun_<Ex, Fb, En, Hi>, } #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Def<Ex, Fb, En, Hi> { Fun(Box<FunDef<Ex, Fb, En, Hi>>), Class(Box<Class_<Ex, Fb, En, Hi>>), RecordDef(Box<RecordDef<Ex, Fb, En, Hi>>), Stmt(Box<Stmt<Ex, Fb, En, Hi>>), Typedef(Box<Typedef<Ex, Fb, En, Hi>>), Constant(Box<Gconst<Ex, Fb, En, Hi>>), Namespace(Box<(Sid, Program<Ex, Fb, En, Hi>)>), NamespaceUse(Vec<(NsKind, Sid, Sid)>), SetNamespaceEnv(Box<Nsenv>), FileAttributes(Box<FileAttribute<Ex, Fb, En, Hi>>), } #[derive( Clone, Copy, Debug, Deserialize, Eq, FromOcamlRep, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum NsKind { NSNamespace, NSClass, NSClassAndNamespace, NSFun, NSConst, } impl TrivialDrop for NsKind {} arena_deserializer::impl_deserialize_in_arena!(NsKind); #[derive( Clone, Copy, Debug, Deserialize, Eq, FromOcamlRep, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum HoleSource { Typing, UnsafeCast, EnforcedCast, } impl TrivialDrop for HoleSource {} arena_deserializer::impl_deserialize_in_arena!(HoleSource); #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum BreakContinueLevel { LevelOk(Option<isize>), LevelNonLiteral, LevelNonPositive, }
22.208833
85
0.562937
69b116166e06581a67375a7b59467a2d47555aaa
16,274
//! This module contains some shared code for encoding and decoding various //! things from the `ty` module, and in particular implements support for //! "shorthands" which allow to have pointers back into the already encoded //! stream instead of re-encoding the same thing twice. //! //! The functionality in here is shared between persisting to crate metadata and //! persisting to incr. comp. caches. use crate::arena::ArenaAllocatable; use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos}; use crate::mir::{ self, interpret::{AllocId, Allocation}, }; use crate::thir; use crate::traits; use crate::ty::subst::SubstsRef; use crate::ty::{self, Ty, TyCtxt}; use rustc_data_structures::fx::FxHashMap; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_span::Span; use std::hash::Hash; use std::intrinsics; use std::marker::DiscriminantKind; /// The shorthand encoding uses an enum's variant index `usize` /// and is offset by this value so it never matches a real variant. /// This offset is also chosen so that the first byte is never < 0x80. pub const SHORTHAND_OFFSET: usize = 0x80; pub trait EncodableWithShorthand<'tcx, E: TyEncoder<'tcx>>: Copy + Eq + Hash { type Variant: Encodable<E>; fn variant(&self) -> &Self::Variant; } #[allow(rustc::usage_of_ty_tykind)] impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> { type Variant = ty::TyKind<'tcx>; #[inline] fn variant(&self) -> &Self::Variant { self.kind() } } impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::PredicateKind<'tcx> { type Variant = ty::PredicateKind<'tcx>; #[inline] fn variant(&self) -> &Self::Variant { self } } pub trait TyEncoder<'tcx>: Encoder { const CLEAR_CROSS_CRATE: bool; fn position(&self) -> usize; fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>; fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize>; fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>; } /// Trait for decoding to a reference. /// /// This is a separate trait from `Decodable` so that we can implement it for /// upstream types, such as `FxHashSet`. /// /// The `TyDecodable` derive macro will use this trait for fields that are /// references (and don't use a type alias to hide that). /// /// `Decodable` can still be implemented in cases where `Decodable` is required /// by a trait bound. pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> { fn decode(d: &mut D) -> &'tcx Self; } /// Encode the given value or a previously cached shorthand. pub fn encode_with_shorthand<'tcx, E, T, M>( encoder: &mut E, value: &T, cache: M, ) -> Result<(), E::Error> where E: TyEncoder<'tcx>, M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>, T: EncodableWithShorthand<'tcx, E>, // The discriminant and shorthand must have the same size. T::Variant: DiscriminantKind<Discriminant = isize>, { let existing_shorthand = cache(encoder).get(value).copied(); if let Some(shorthand) = existing_shorthand { return encoder.emit_usize(shorthand); } let variant = value.variant(); let start = encoder.position(); variant.encode(encoder)?; let len = encoder.position() - start; // The shorthand encoding uses the same usize as the // discriminant, with an offset so they can't conflict. let discriminant = intrinsics::discriminant_value(variant); assert!(SHORTHAND_OFFSET > discriminant as usize); let shorthand = start + SHORTHAND_OFFSET; // Get the number of bits that leb128 could fit // in the same space as the fully encoded type. let leb128_bits = len * 7; // Check that the shorthand is a not longer than the // full encoding itself, i.e., it's an obvious win. if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) { cache(encoder).insert(*value, shorthand); } Ok(()) } impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { encode_with_shorthand(e, self, TyEncoder::type_shorthands) } } impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.bound_vars().encode(e)?; encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands) } } impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.kind().encode(e) } } impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId { fn encode(&self, e: &mut E) -> Result<(), E::Error> { e.encode_alloc_id(self) } } macro_rules! encodable_via_deref { ($($t:ty),+) => { $(impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for $t { fn encode(&self, e: &mut E) -> Result<(), E::Error> { (**self).encode(e) } })* } } encodable_via_deref! { &'tcx ty::TypeckResults<'tcx>, ty::Region<'tcx>, &'tcx traits::ImplSource<'tcx, ()>, &'tcx mir::Body<'tcx>, &'tcx mir::UnsafetyCheckResult, &'tcx mir::BorrowCheckResult<'tcx>, &'tcx mir::coverage::CodeRegion, &'tcx ty::AdtDef } pub trait TyDecoder<'tcx>: Decoder { const CLEAR_CROSS_CRATE: bool; fn tcx(&self) -> TyCtxt<'tcx>; fn peek_byte(&self) -> u8; fn position(&self) -> usize; fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> where F: FnOnce(&mut Self) -> Ty<'tcx>; fn with_position<F, R>(&mut self, pos: usize, f: F) -> R where F: FnOnce(&mut Self) -> R; fn positioned_at_shorthand(&self) -> bool { (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0 } fn decode_alloc_id(&mut self) -> AllocId; } #[inline] fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>( decoder: &mut D, ) -> &'tcx T where D: TyDecoder<'tcx>, { decoder.tcx().arena.alloc(Decodable::decode(decoder)) } #[inline] fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable<D>>( decoder: &mut D, ) -> &'tcx [T] where D: TyDecoder<'tcx>, { decoder.tcx().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)) } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> { #[allow(rustc::usage_of_ty_tykind)] fn decode(decoder: &mut D) -> Ty<'tcx> { // Handle shorthands first, if we have a usize > 0x80. if decoder.positioned_at_shorthand() { let pos = decoder.read_usize(); assert!(pos >= SHORTHAND_OFFSET); let shorthand = pos - SHORTHAND_OFFSET; decoder.cached_ty_for_shorthand(shorthand, |decoder| { decoder.with_position(shorthand, Ty::decode) }) } else { let tcx = decoder.tcx(); tcx.mk_ty(ty::TyKind::decode(decoder)) } } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> { let bound_vars = Decodable::decode(decoder); // Handle shorthands first, if we have a usize > 0x80. ty::Binder::bind_with_vars( if decoder.positioned_at_shorthand() { let pos = decoder.read_usize(); assert!(pos >= SHORTHAND_OFFSET); let shorthand = pos - SHORTHAND_OFFSET; decoder.with_position(shorthand, ty::PredicateKind::decode) } else { ty::PredicateKind::decode(decoder) }, bound_vars, ) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> { fn decode(decoder: &mut D) -> ty::Predicate<'tcx> { let predicate_kind = Decodable::decode(decoder); decoder.tcx().mk_predicate(predicate_kind) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for SubstsRef<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let tcx = decoder.tcx(); tcx.mk_substs( (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)), ) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> { fn decode(decoder: &mut D) -> Self { let local: mir::Local = Decodable::decode(decoder); let len = decoder.read_usize(); let projection = decoder.tcx().mk_place_elems( (0..len).map::<mir::PlaceElem<'tcx>, _>(|_| Decodable::decode(decoder)), ); mir::Place { local, projection } } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> { fn decode(decoder: &mut D) -> Self { decoder.tcx().mk_region(Decodable::decode(decoder)) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let interned: Vec<CanonicalVarInfo<'tcx>> = (0..len).map(|_| Decodable::decode(decoder)).collect(); decoder.tcx().intern_canonical_var_infos(interned.as_slice()) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId { fn decode(decoder: &mut D) -> Self { decoder.decode_alloc_id() } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> { fn decode(decoder: &mut D) -> Self { ty::SymbolName::new(decoder.tcx(), &decoder.read_str()) } } macro_rules! impl_decodable_via_ref { ($($t:ty),+) => { $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t { fn decode(decoder: &mut D) -> Self { RefDecodable::decode(decoder) } })* } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.tcx().mk_type_list((0..len).map::<Ty<'tcx>, _>(|_| Decodable::decode(decoder))) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.tcx().mk_poly_existential_predicates( (0..len).map::<ty::Binder<'tcx, _>, _>(|_| Decodable::decode(decoder)), ) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::Const<'tcx> { fn decode(decoder: &mut D) -> &'tcx Self { decoder.tcx().mk_const(Decodable::decode(decoder)) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] { fn decode(decoder: &mut D) -> &'tcx Self { decoder.tcx().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(), ) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for Allocation { fn decode(decoder: &mut D) -> &'tcx Self { decoder.tcx().intern_const_alloc(Decodable::decode(decoder)) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] { fn decode(decoder: &mut D) -> &'tcx Self { decoder.tcx().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(), ) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] { fn decode(decoder: &mut D) -> &'tcx Self { decoder.tcx().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(), ) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] { fn decode(decoder: &mut D) -> &'tcx Self { decoder.tcx().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(), ) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.tcx().mk_bound_variable_kinds( (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)), ) } } impl_decodable_via_ref! { &'tcx ty::TypeckResults<'tcx>, &'tcx ty::List<Ty<'tcx>>, &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, &'tcx traits::ImplSource<'tcx, ()>, &'tcx Allocation, &'tcx mir::Body<'tcx>, &'tcx mir::UnsafetyCheckResult, &'tcx mir::BorrowCheckResult<'tcx>, &'tcx mir::coverage::CodeRegion, &'tcx ty::List<ty::BoundVariableKind>, &'tcx ty::AdtDef } #[macro_export] macro_rules! __impl_decoder_methods { ($($name:ident -> $ty:ty;)*) => { $( #[inline] fn $name(&mut self) -> $ty { self.opaque.$name() } )* } } macro_rules! impl_arena_allocatable_decoder { ([]$args:tt) => {}; ([decode $(, $attrs:ident)*] [$name:ident: $ty:ty]) => { impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable(decoder) } } impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable_slice(decoder) } } }; ([$ignore:ident $(, $attrs:ident)*]$args:tt) => { impl_arena_allocatable_decoder!([$($attrs),*]$args); }; } macro_rules! impl_arena_allocatable_decoders { ([$($a:tt $name:ident: $ty:ty,)*]) => { $( impl_arena_allocatable_decoder!($a [$name: $ty]); )* } } rustc_hir::arena_types!(impl_arena_allocatable_decoders); arena_types!(impl_arena_allocatable_decoders); #[macro_export] macro_rules! implement_ty_decoder { ($DecoderName:ident <$($typaram:tt),*>) => { mod __ty_decoder_impl { use std::borrow::Cow; use rustc_serialize::Decoder; use super::$DecoderName; impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> { $crate::__impl_decoder_methods! { read_unit -> (); read_u128 -> u128; read_u64 -> u64; read_u32 -> u32; read_u16 -> u16; read_u8 -> u8; read_usize -> usize; read_i128 -> i128; read_i64 -> i64; read_i32 -> i32; read_i16 -> i16; read_i8 -> i8; read_isize -> isize; read_bool -> bool; read_f64 -> f64; read_f32 -> f32; read_char -> char; read_str -> Cow<'_, str>; } #[inline] fn read_raw_bytes_into(&mut self, bytes: &mut [u8]) { self.opaque.read_raw_bytes_into(bytes) } } } } } macro_rules! impl_binder_encode_decode { ($($t:ty),+ $(,)?) => { $( impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Binder<'tcx, $t> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.bound_vars().encode(e)?; self.as_ref().skip_binder().encode(e) } } impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Binder<'tcx, $t> { fn decode(decoder: &mut D) -> Self { let bound_vars = Decodable::decode(decoder); ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars) } } )* } } impl_binder_encode_decode! { &'tcx ty::List<Ty<'tcx>>, ty::FnSig<'tcx>, ty::ExistentialPredicate<'tcx>, ty::TraitRef<'tcx>, Vec<ty::GeneratorInteriorTypeCause<'tcx>>, }
31.6
95
0.580128
ffc2a60172b1e5113ab50f118e025048df91ac71
6,495
//! Our parser is generic over the source of tokens it parses. //! //! This module defines tokens sourced from declarative macros. use parser::{Token, TokenSource}; use syntax::{lex_single_syntax_kind, SmolStr, SyntaxKind, SyntaxKind::*, T}; use tt::buffer::TokenBuffer; #[derive(Debug, Clone, Eq, PartialEq)] struct TtToken { tt: Token, text: SmolStr, } pub(crate) struct SubtreeTokenSource { cached: Vec<TtToken>, curr: (Token, usize), } impl<'a> SubtreeTokenSource { // Helper function used in test #[cfg(test)] pub(crate) fn text(&self) -> SmolStr { match self.cached.get(self.curr.1) { Some(tt) => tt.text.clone(), _ => SmolStr::new(""), } } } impl<'a> SubtreeTokenSource { pub(crate) fn new(buffer: &TokenBuffer) -> SubtreeTokenSource { let mut current = buffer.begin(); let mut cached = Vec::with_capacity(100); while !current.eof() { let cursor = current; let tt = cursor.token_tree(); // Check if it is lifetime if let Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Punct(punct), _)) = tt { if punct.char == '\'' { let next = cursor.bump(); if let Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Ident(ident), _)) = next.token_tree() { let text = SmolStr::new("'".to_string() + &ident.text); cached.push(TtToken { tt: Token { kind: LIFETIME_IDENT, is_jointed_to_next: false }, text, }); current = next.bump(); continue; } else { panic!("Next token must be ident : {:#?}", next.token_tree()); } } } current = match tt { Some(tt::buffer::TokenTreeRef::Leaf(leaf, _)) => { cached.push(convert_leaf(leaf)); cursor.bump() } Some(tt::buffer::TokenTreeRef::Subtree(subtree, _)) => { cached.push(convert_delim(subtree.delimiter_kind(), false)); cursor.subtree().unwrap() } None => { if let Some(subtree) = cursor.end() { cached.push(convert_delim(subtree.delimiter_kind(), true)); cursor.bump() } else { continue; } } }; } let mut res = SubtreeTokenSource { curr: (Token { kind: EOF, is_jointed_to_next: false }, 0), cached, }; res.curr = (res.token(0), 0); res } fn token(&self, pos: usize) -> Token { match self.cached.get(pos) { Some(it) => it.tt, None => Token { kind: EOF, is_jointed_to_next: false }, } } } impl<'a> TokenSource for SubtreeTokenSource { fn current(&self) -> Token { self.curr.0 } /// Lookahead n token fn lookahead_nth(&self, n: usize) -> Token { self.token(self.curr.1 + n) } /// bump cursor to next token fn bump(&mut self) { if self.current().kind == EOF { return; } self.curr = (self.token(self.curr.1 + 1), self.curr.1 + 1); } /// Is the current token a specified keyword? fn is_keyword(&self, kw: &str) -> bool { match self.cached.get(self.curr.1) { Some(t) => t.text == *kw, None => false, } } } fn convert_delim(d: Option<tt::DelimiterKind>, closing: bool) -> TtToken { let (kinds, texts) = match d { Some(tt::DelimiterKind::Parenthesis) => ([T!['('], T![')']], "()"), Some(tt::DelimiterKind::Brace) => ([T!['{'], T!['}']], "{}"), Some(tt::DelimiterKind::Bracket) => ([T!['['], T![']']], "[]"), None => ([L_DOLLAR, R_DOLLAR], ""), }; let idx = closing as usize; let kind = kinds[idx]; let text = if !texts.is_empty() { &texts[idx..texts.len() - (1 - idx)] } else { "" }; TtToken { tt: Token { kind, is_jointed_to_next: false }, text: SmolStr::new(text) } } fn convert_literal(l: &tt::Literal) -> TtToken { let is_negated = l.text.starts_with('-'); let inner_text = &l.text[if is_negated { 1 } else { 0 }..]; let kind = lex_single_syntax_kind(inner_text) .map(|(kind, _error)| kind) .filter(|kind| { kind.is_literal() && (!is_negated || matches!(kind, FLOAT_NUMBER | INT_NUMBER)) }) .unwrap_or_else(|| panic!("Fail to convert given literal {:#?}", &l)); TtToken { tt: Token { kind, is_jointed_to_next: false }, text: l.text.clone() } } fn convert_ident(ident: &tt::Ident) -> TtToken { let kind = match ident.text.as_ref() { "true" => T![true], "false" => T![false], "_" => UNDERSCORE, i if i.starts_with('\'') => LIFETIME_IDENT, _ => SyntaxKind::from_keyword(ident.text.as_str()).unwrap_or(IDENT), }; TtToken { tt: Token { kind, is_jointed_to_next: false }, text: ident.text.clone() } } fn convert_punct(p: tt::Punct) -> TtToken { let kind = match SyntaxKind::from_char(p.char) { None => panic!("{:#?} is not a valid punct", p), Some(kind) => kind, }; let text = { let mut buf = [0u8; 4]; let s: &str = p.char.encode_utf8(&mut buf); SmolStr::new(s) }; TtToken { tt: Token { kind, is_jointed_to_next: p.spacing == tt::Spacing::Joint }, text } } fn convert_leaf(leaf: &tt::Leaf) -> TtToken { match leaf { tt::Leaf::Literal(l) => convert_literal(l), tt::Leaf::Ident(ident) => convert_ident(ident), tt::Leaf::Punct(punct) => convert_punct(*punct), } } #[cfg(test)] mod tests { use super::{convert_literal, TtToken}; use parser::Token; use syntax::{SmolStr, SyntaxKind}; #[test] fn test_negative_literal() { assert_eq!( convert_literal(&tt::Literal { id: tt::TokenId::unspecified(), text: SmolStr::new("-42.0") }), TtToken { tt: Token { kind: SyntaxKind::FLOAT_NUMBER, is_jointed_to_next: false }, text: SmolStr::new("-42.0") } ); } }
31.682927
93
0.50485
180135b6760e9e2c7c961091c57fa51859282e34
1,665
// errors2.rs // Say we're writing a game where you can buy items with tokens. All items cost // 5 tokens, and whenever you purchase items there is a processing fee of 1 // token. A player of the game will type in how many items they want to buy, // and the `total_cost` function will calculate the total number of tokens. // Since the player typed in the quantity, though, we get it as a string-- and // they might have typed anything, not just numbers! // Right now, this function isn't handling the error case at all (and isn't // handling the success case properly either). What we want to do is: // if we call the `parse` function on a string that is not a number, that // function will return a `ParseIntError`, and in that case, we want to // immediately return that error from our function and not try to multiply // and add. // There are at least two ways to implement this that are both correct-- but // one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways. use std::num::ParseIntError; pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { let processing_fee = 1; let cost_per_item = 5; let res = item_quantity.parse::<i32>(); match res { Ok(num) => Ok(num * cost_per_item + processing_fee), Err(e) => Err(e), } } #[cfg(test)] mod tests { use super::*; #[test] fn item_quantity_is_a_valid_number() { assert_eq!(total_cost("34"), Ok(171)); } #[test] fn item_quantity_is_an_invalid_number() { assert_eq!( total_cost("beep boop").unwrap_err().to_string(), "invalid digit found in string" ); } }
33.979592
81
0.675676
5bfa61f7d99c72b27a0e9d20fa2b30b97de08353
470
use direnv::DirenvValue; use direnvtestcase::DirenvTestCase; use std::env; #[test] fn bug23_shell_hook() { env::set_var("EXAMPLE", "my-neat-path"); let mut testcase = DirenvTestCase::new("bug23_setuphook"); testcase.evaluate().expect("Failed to build the first time"); let env = testcase.get_direnv_variables(); println!("{:?}", env); assert_eq!( env.get_env("EXAMPLE"), DirenvValue::Value("my-neat-path:/tmp/foo/bar") ); }
26.111111
65
0.653191
f5b6fece83a846c6e575459e2cb59f20196d78dd
12,653
use anyhow::{anyhow, bail, Context}; use argh::FromArgs; use bootloader::disk_image::create_disk_image; use std::{ convert::TryFrom, fs::{self, File}, io::{self, Seek}, path::{Path, PathBuf}, process::Command, str::FromStr, }; type ExitCode = i32; #[derive(FromArgs)] /// Build the bootloader struct BuildArguments { /// path to the `Cargo.toml` of the kernel #[argh(option)] kernel_manifest: PathBuf, /// path to the kernel ELF binary #[argh(option)] kernel_binary: PathBuf, /// which firmware interface to build #[argh(option, default = "Firmware::All")] firmware: Firmware, /// whether to run the resulting binary in QEMU #[argh(switch)] run: bool, /// suppress stdout output #[argh(switch)] quiet: bool, /// build the bootloader with the given cargo features #[argh(option)] features: Vec<String>, /// use the given path as target directory #[argh(option)] target_dir: Option<PathBuf>, /// place the output binaries at the given path #[argh(option)] out_dir: Option<PathBuf>, } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Firmware { Bios, Uefi, All, } impl FromStr for Firmware { type Err = FirmwareParseError; fn from_str(s: &str) -> Result<Self, FirmwareParseError> { match s.to_ascii_lowercase().as_str() { "bios" => Ok(Firmware::Bios), "uefi" => Ok(Firmware::Uefi), "all" => Ok(Firmware::All), _other => Err(FirmwareParseError), } } } impl Firmware { fn uefi(&self) -> bool { match self { Firmware::Bios => false, Firmware::Uefi | Firmware::All => true, } } fn bios(&self) -> bool { match self { Firmware::Bios | Firmware::All => true, Firmware::Uefi => false, } } } /// Firmware must be one of `uefi`, `bios`, or `all`. #[derive(Debug, displaydoc::Display, Eq, PartialEq, Copy, Clone)] struct FirmwareParseError; fn main() -> anyhow::Result<()> { let args: BuildArguments = argh::from_env(); if args.firmware.uefi() { let build_or_run = if args.run { "run" } else { "build" }; let mut cmd = Command::new(env!("CARGO")); cmd.arg(build_or_run).arg("--bin").arg("uefi"); cmd.arg("--release"); cmd.arg("--target").arg("x86_64-unknown-uefi"); cmd.arg("--features") .arg(args.features.join(" ") + " uefi_bin"); cmd.arg("-Zbuild-std=core"); cmd.arg("-Zbuild-std-features=compiler-builtins-mem"); if let Some(target_dir) = &args.target_dir { cmd.arg("--target-dir").arg(target_dir); } if args.quiet { cmd.arg("--quiet"); } cmd.env("KERNEL", &args.kernel_binary); cmd.env("KERNEL_MANIFEST", &args.kernel_manifest); assert!(cmd.status()?.success()); // Retrieve binary paths cmd.arg("--message-format").arg("json"); let output = cmd .output() .context("failed to execute kernel build with json output")?; if !output.status.success() { return Err(anyhow!("{}", String::from_utf8_lossy(&output.stderr))); } let mut executables = Vec::new(); for line in String::from_utf8(output.stdout) .context("build JSON output is not valid UTF-8")? .lines() { let mut artifact = json::parse(line).context("build JSON output is not valid JSON")?; if let Some(executable) = artifact["executable"].take_string() { executables.push(PathBuf::from(executable)); } } assert_eq!(executables.len(), 1); let executable_path = executables.pop().unwrap(); let executable_name = executable_path .file_stem() .and_then(|stem| stem.to_str()) .ok_or_else(|| { anyhow!( "executable path `{}` has invalid file stem", executable_path.display() ) })?; let kernel_name = args .kernel_binary .file_name() .and_then(|name| name.to_str()) .ok_or_else(|| { anyhow!( "kernel binary path `{}` has invalid file name", args.kernel_binary.display() ) })?; if let Some(out_dir) = &args.out_dir { let efi_file = out_dir.join(format!("boot-{}-{}.efi", executable_name, kernel_name)); create_uefi_disk_image(&executable_path, &efi_file) .context("failed to create UEFI disk image")?; } } if args.firmware.bios() { let mut cmd = Command::new(env!("CARGO")); cmd.arg("build").arg("--bin").arg("bios"); cmd.arg("--profile").arg("release"); cmd.arg("-Z").arg("unstable-options"); cmd.arg("--target").arg("x86_64-bootloader.json"); cmd.arg("--features") .arg(args.features.join(" ") + " bios_bin"); cmd.arg("-Zbuild-std=core"); cmd.arg("-Zbuild-std-features=compiler-builtins-mem"); if let Some(target_dir) = &args.target_dir { cmd.arg("--target-dir").arg(target_dir); } if args.quiet { cmd.arg("--quiet"); } cmd.env("KERNEL", &args.kernel_binary); cmd.env("KERNEL_MANIFEST", &args.kernel_manifest); cmd.env("RUSTFLAGS", "-C opt-level=s"); assert!(cmd.status()?.success()); // Retrieve binary paths cmd.arg("--message-format").arg("json"); let output = cmd .output() .context("failed to execute kernel build with json output")?; if !output.status.success() { return Err(anyhow!("{}", String::from_utf8_lossy(&output.stderr))); } let mut executables = Vec::new(); for line in String::from_utf8(output.stdout) .context("build JSON output is not valid UTF-8")? .lines() { let mut artifact = json::parse(line).context("build JSON output is not valid JSON")?; if let Some(executable) = artifact["executable"].take_string() { executables.push(PathBuf::from(executable)); } } assert_eq!(executables.len(), 1); let executable_path = executables.pop().unwrap(); let executable_name = executable_path.file_name().unwrap().to_str().unwrap(); let kernel_name = args.kernel_binary.file_name().unwrap().to_str().unwrap(); let mut output_bin_path = executable_path .parent() .unwrap() .join(format!("boot-{}-{}.img", executable_name, kernel_name)); create_disk_image(&executable_path, &output_bin_path) .context("Failed to create bootable disk image")?; if let Some(out_dir) = &args.out_dir { let file = out_dir.join(output_bin_path.file_name().unwrap()); fs::copy(output_bin_path, &file)?; output_bin_path = file; } if !args.quiet { println!( "Created bootable disk image at {}", output_bin_path.display() ); } if args.run { bios_run(&output_bin_path)?; } } Ok(()) } fn create_uefi_disk_image(executable_path: &Path, efi_file: &Path) -> anyhow::Result<()> { fs::copy(&executable_path, &efi_file).context("failed to copy efi file to out dir")?; let efi_size = fs::metadata(&efi_file) .context("failed to read metadata of efi file")? .len(); // create fat partition let fat_file_path = { const MB: u64 = 1024 * 1024; let fat_path = efi_file.with_extension("fat"); let fat_file = fs::OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(&fat_path) .context("Failed to create UEFI FAT file")?; let efi_size_padded_and_rounded = ((efi_size + 1024 * 64 - 1) / MB + 1) * MB; fat_file .set_len(efi_size_padded_and_rounded) .context("failed to set UEFI FAT file length")?; // create new FAT partition let format_options = fatfs::FormatVolumeOptions::new().volume_label(*b"FOOO "); fatfs::format_volume(&fat_file, format_options) .context("Failed to format UEFI FAT file")?; // copy EFI file to FAT filesystem let partition = fatfs::FileSystem::new(&fat_file, fatfs::FsOptions::new()) .context("Failed to open FAT file system of UEFI FAT file")?; let root_dir = partition.root_dir(); root_dir.create_dir("efi")?; root_dir.create_dir("efi/boot")?; let mut bootx64 = root_dir.create_file("efi/boot/bootx64.efi")?; bootx64.truncate()?; io::copy(&mut fs::File::open(&executable_path)?, &mut bootx64)?; fat_path }; // create gpt disk { let image_path = efi_file.with_extension("img"); let mut image = fs::OpenOptions::new() .create(true) .truncate(true) .read(true) .write(true) .open(&image_path) .context("failed to create UEFI disk image")?; let partition_size: u64 = fs::metadata(&fat_file_path) .context("failed to read metadata of UEFI FAT partition")? .len(); let image_size = partition_size + 1024 * 64; image .set_len(image_size) .context("failed to set length of UEFI disk image")?; // Create a protective MBR at LBA0 let mbr = gpt::mbr::ProtectiveMBR::with_lb_size( u32::try_from((image_size / 512) - 1).unwrap_or(0xFF_FF_FF_FF), ); mbr.overwrite_lba0(&mut image) .context("failed to write protective MBR")?; // create new GPT in image file let block_size = gpt::disk::LogicalBlockSize::Lb512; let block_size_bytes: u64 = block_size.into(); let mut disk = gpt::GptConfig::new() .writable(true) .initialized(false) .logical_block_size(block_size) .create_from_device(Box::new(&mut image), None) .context("failed to open UEFI disk image")?; disk.update_partitions(Default::default()) .context("failed to initialize GPT partition table")?; // add add EFI system partition let partition_id = disk .add_partition("boot", partition_size, gpt::partition_types::EFI, 0) .context("failed to add boot partition")?; let partition = disk .partitions() .get(&partition_id) .ok_or_else(|| anyhow!("Partition doesn't exist after adding it"))?; let created_partition_size: u64 = (partition.last_lba - partition.first_lba + 1u64) * block_size_bytes; if created_partition_size != partition_size { bail!( "Created partition has invalid size (size is {:?}, expected {})", created_partition_size, partition_size ); } let start_offset = partition .bytes_start(block_size) .context("failed to retrieve partition start offset")?; // Write the partition table disk.write() .context("failed to write GPT partition table to UEFI image file")?; image .seek(io::SeekFrom::Start(start_offset)) .context("failed to seek to boot partiiton start")?; let bytes_written = io::copy( &mut File::open(&fat_file_path).context("failed to open fat image")?, &mut image, ) .context("failed to write boot partition content")?; if bytes_written != partition_size { bail!( "Invalid number of partition bytes written (expected {}, got {})", partition_size, bytes_written ); } } Ok(()) } fn bios_run(bin_path: &Path) -> anyhow::Result<Option<ExitCode>> { let mut qemu = Command::new("qemu-system-x86_64"); qemu.arg("-drive") .arg(format!("format=raw,file={}", bin_path.display())); qemu.arg("-s"); qemu.arg("--no-reboot"); println!("{:?}", qemu); let exit_status = qemu.status()?; let ret = if exit_status.success() { None } else { exit_status.code() }; Ok(ret) }
33.562334
97
0.557417
d78de4b5071d0490e0f050bc2f51384fcecbf9bb
1,033
use pairing::bls12_381::Fr; use pairing::Engine; use crate::hasher::{Blake2sHasher, Hasher}; /// Key derivation function, based on pedersen hashing. pub fn kdf<E: Engine>(data: &[u8], m: usize) -> Fr { Blake2sHasher::kdf(&data, m).into() } #[cfg(test)] mod tests { use super::kdf; use crate::fr32::bytes_into_fr; use pairing::bls12_381::Bls12; #[test] fn kdf_valid_block_len() { let m = 1; let size = 32 * (1 + m); let data = vec![1u8; size]; let expected = bytes_into_fr::<Bls12>( &mut vec![ 220, 60, 76, 126, 119, 247, 67, 162, 98, 94, 119, 28, 247, 18, 71, 208, 167, 72, 33, 85, 59, 56, 96, 13, 9, 67, 49, 109, 95, 246, 152, 63, ] .as_slice(), ) .unwrap(); let res = kdf::<Bls12>(&data, m); assert_eq!(res, expected); } #[test] #[should_panic] fn kdf_invalid_block_len() { let data = vec![2u8; 1234]; kdf::<Bls12>(&data, 44); } }
23.477273
96
0.515973
1413936313974c675491ea15abe754934dfca570
702
use language::operations::{make_param_doc, Operation, ParamInfo}; pub struct PlayerGetScoreOp; const DOC: &str = ""; pub const OP_CODE: u32 = 431; pub const IDENT: &str = "player_get_score"; impl Operation for PlayerGetScoreOp { fn op_code(&self) -> u32 { OP_CODE } fn documentation(&self) -> &'static str { DOC } fn identifier(&self) -> &'static str { IDENT } fn param_info(&self) -> ParamInfo { ParamInfo { num_required: 2, num_optional: 0, param_docs: vec![ make_param_doc("<destination>", ""), make_param_doc("<player_id>", ""), ], } } }
20.057143
65
0.539886
5d6afc55a5973189326d76c45944b4df70dbe1f1
875,748
#![doc = r" This file is automatically generated by executing `cargo build --features generate`."] #![doc = r""] #![doc = r" **Make adjustments in `build.rs`, not in this file!**"] #![allow(clippy::many_single_char_names)] #![allow(clippy::too_many_arguments)] #![allow(clippy::type_complexity)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use crate::{bindings::root, PluginContext}; #[doc = r" This is the low-level API access point to all REAPER functions."] #[doc = r""] #[doc = r" In order to use it, you first must obtain an instance of this struct by invoking [`load()`]."] #[doc = r""] #[doc = r" `Default::default()` will give you an instance which panics on each function call. It's"] #[doc = r" intended to be used for example code only."] #[doc = r""] #[doc = r" # Panics"] #[doc = r""] #[doc = r" Please note that it's possible that functions are *not available*. This can be the case if"] #[doc = r" the user runs your plug-in in an older version of REAPER which doesn't have that function yet."] #[doc = r" The availability of a function can be checked by inspecting the respective function pointer"] #[doc = r" option accessible via the [`pointers()`] method. The actual methods in this structs are just"] #[doc = r" convenience methods which unwrap the function pointers and panic if they are not available."] #[doc = r""] #[doc = r" [`load()`]: #method.load"] #[doc = r" [`pointers()`]: #method.pointers"] #[derive(Copy, Clone, Debug, Default)] pub struct Reaper { pub(crate) pointers: ReaperFunctionPointers, pub(crate) plugin_context: Option<PluginContext>, } impl Reaper { #[doc = r" Loads all available REAPER functions from the given plug-in context."] #[doc = r""] #[doc = r" Returns a low-level `Reaper` instance which allows you to call these functions."] pub fn load(plugin_context: PluginContext) -> Reaper { let mut loaded_count = 0; let mut pointers = unsafe { ReaperFunctionPointers { loaded_count: 0, __mergesort: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(__mergesort)).as_ptr()), ), AddCustomizableMenu: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddCustomizableMenu)).as_ptr()), ), AddExtensionsMainMenu: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddExtensionsMainMenu)).as_ptr()), ), AddMediaItemToTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddMediaItemToTrack)).as_ptr()), ), AddProjectMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddProjectMarker)).as_ptr()), ), AddProjectMarker2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddProjectMarker2)).as_ptr()), ), AddRemoveReaScript: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddRemoveReaScript)).as_ptr()), ), AddTakeToMediaItem: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddTakeToMediaItem)).as_ptr()), ), AddTempoTimeSigMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AddTempoTimeSigMarker)).as_ptr()), ), adjustZoom: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(adjustZoom)).as_ptr()), ), AnyTrackSolo: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(AnyTrackSolo)).as_ptr()), ), APIExists: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(APIExists)).as_ptr()), ), APITest: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(APITest)).as_ptr()), ), ApplyNudge: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ApplyNudge)).as_ptr()), ), ArmCommand: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ArmCommand)).as_ptr()), ), Audio_Init: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Audio_Init)).as_ptr()), ), Audio_IsPreBuffer: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Audio_IsPreBuffer)).as_ptr()), ), Audio_IsRunning: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Audio_IsRunning)).as_ptr()), ), Audio_Quit: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Audio_Quit)).as_ptr()), ), Audio_RegHardwareHook: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Audio_RegHardwareHook)).as_ptr()), ), AudioAccessorStateChanged: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(AudioAccessorStateChanged)).as_ptr(), ), ), AudioAccessorUpdate: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(AudioAccessorUpdate)).as_ptr()), ), AudioAccessorValidateState: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(AudioAccessorValidateState)).as_ptr(), ), ), BypassFxAllTracks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(BypassFxAllTracks)).as_ptr()), ), CalculatePeaks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CalculatePeaks)).as_ptr()), ), CalculatePeaksFloatSrcPtr: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CalculatePeaksFloatSrcPtr)).as_ptr(), ), ), ClearAllRecArmed: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ClearAllRecArmed)).as_ptr()), ), ClearConsole: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ClearConsole)).as_ptr()), ), ClearPeakCache: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ClearPeakCache)).as_ptr()), ), ColorFromNative: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ColorFromNative)).as_ptr()), ), ColorToNative: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ColorToNative)).as_ptr()), ), CountActionShortcuts: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountActionShortcuts)).as_ptr()), ), CountAutomationItems: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountAutomationItems)).as_ptr()), ), CountEnvelopePoints: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountEnvelopePoints)).as_ptr()), ), CountEnvelopePointsEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountEnvelopePointsEx)).as_ptr()), ), CountMediaItems: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountMediaItems)).as_ptr()), ), CountProjectMarkers: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountProjectMarkers)).as_ptr()), ), CountSelectedMediaItems: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountSelectedMediaItems)).as_ptr()), ), CountSelectedTracks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountSelectedTracks)).as_ptr()), ), CountSelectedTracks2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountSelectedTracks2)).as_ptr()), ), CountTakeEnvelopes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountTakeEnvelopes)).as_ptr()), ), CountTakes: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CountTakes)).as_ptr()), ), CountTCPFXParms: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountTCPFXParms)).as_ptr()), ), CountTempoTimeSigMarkers: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CountTempoTimeSigMarkers)).as_ptr(), ), ), CountTrackEnvelopes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountTrackEnvelopes)).as_ptr()), ), CountTrackMediaItems: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CountTrackMediaItems)).as_ptr()), ), CountTracks: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CountTracks)).as_ptr()), ), CreateLocalOscHandler: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CreateLocalOscHandler)).as_ptr()), ), CreateMIDIInput: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CreateMIDIInput)).as_ptr()), ), CreateMIDIOutput: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CreateMIDIOutput)).as_ptr()), ), CreateNewMIDIItemInProj: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CreateNewMIDIItemInProj)).as_ptr()), ), CreateTakeAudioAccessor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CreateTakeAudioAccessor)).as_ptr()), ), CreateTrackAudioAccessor: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CreateTrackAudioAccessor)).as_ptr(), ), ), CreateTrackSend: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CreateTrackSend)).as_ptr()), ), CSurf_FlushUndo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_FlushUndo)).as_ptr()), ), CSurf_GetTouchState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_GetTouchState)).as_ptr()), ), CSurf_GoEnd: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_GoEnd)).as_ptr()), ), CSurf_GoStart: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_GoStart)).as_ptr()), ), CSurf_NumTracks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_NumTracks)).as_ptr()), ), CSurf_OnArrow: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnArrow)).as_ptr()), ), CSurf_OnFwd: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnFwd)).as_ptr()), ), CSurf_OnFXChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnFXChange)).as_ptr()), ), CSurf_OnInputMonitorChange: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_OnInputMonitorChange)).as_ptr(), ), ), CSurf_OnInputMonitorChangeEx: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_OnInputMonitorChangeEx)).as_ptr(), )), CSurf_OnMuteChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnMuteChange)).as_ptr()), ), CSurf_OnMuteChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnMuteChangeEx)).as_ptr()), ), CSurf_OnOscControlMessage: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_OnOscControlMessage)).as_ptr(), ), ), CSurf_OnPanChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnPanChange)).as_ptr()), ), CSurf_OnPanChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnPanChangeEx)).as_ptr()), ), CSurf_OnPause: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnPause)).as_ptr()), ), CSurf_OnPlay: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnPlay)).as_ptr()), ), CSurf_OnPlayRateChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnPlayRateChange)).as_ptr()), ), CSurf_OnRecArmChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnRecArmChange)).as_ptr()), ), CSurf_OnRecArmChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnRecArmChangeEx)).as_ptr()), ), CSurf_OnRecord: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnRecord)).as_ptr()), ), CSurf_OnRecvPanChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnRecvPanChange)).as_ptr()), ), CSurf_OnRecvVolumeChange: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_OnRecvVolumeChange)).as_ptr(), ), ), CSurf_OnRew: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnRew)).as_ptr()), ), CSurf_OnRewFwd: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnRewFwd)).as_ptr()), ), CSurf_OnScroll: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnScroll)).as_ptr()), ), CSurf_OnSelectedChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnSelectedChange)).as_ptr()), ), CSurf_OnSendPanChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnSendPanChange)).as_ptr()), ), CSurf_OnSendVolumeChange: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_OnSendVolumeChange)).as_ptr(), ), ), CSurf_OnSoloChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnSoloChange)).as_ptr()), ), CSurf_OnSoloChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnSoloChangeEx)).as_ptr()), ), CSurf_OnStop: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnStop)).as_ptr()), ), CSurf_OnTempoChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnTempoChange)).as_ptr()), ), CSurf_OnTrackSelection: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnTrackSelection)).as_ptr()), ), CSurf_OnVolumeChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnVolumeChange)).as_ptr()), ), CSurf_OnVolumeChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnVolumeChangeEx)).as_ptr()), ), CSurf_OnWidthChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnWidthChange)).as_ptr()), ), CSurf_OnWidthChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnWidthChangeEx)).as_ptr()), ), CSurf_OnZoom: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(CSurf_OnZoom)).as_ptr()), ), CSurf_ResetAllCachedVolPanStates: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_ResetAllCachedVolPanStates)).as_ptr(), )), CSurf_ScrubAmt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_ScrubAmt)).as_ptr()), ), CSurf_SetAutoMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetAutoMode)).as_ptr()), ), CSurf_SetPlayState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetPlayState)).as_ptr()), ), CSurf_SetRepeatState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetRepeatState)).as_ptr()), ), CSurf_SetSurfaceMute: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetSurfaceMute)).as_ptr()), ), CSurf_SetSurfacePan: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetSurfacePan)).as_ptr()), ), CSurf_SetSurfaceRecArm: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetSurfaceRecArm)).as_ptr()), ), CSurf_SetSurfaceSelected: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_SetSurfaceSelected)).as_ptr(), ), ), CSurf_SetSurfaceSolo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetSurfaceSolo)).as_ptr()), ), CSurf_SetSurfaceVolume: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_SetSurfaceVolume)).as_ptr()), ), CSurf_SetTrackListChange: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(CSurf_SetTrackListChange)).as_ptr(), ), ), CSurf_TrackFromID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_TrackFromID)).as_ptr()), ), CSurf_TrackToID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CSurf_TrackToID)).as_ptr()), ), DB2SLIDER: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(DB2SLIDER)).as_ptr()), ), DeleteActionShortcut: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DeleteActionShortcut)).as_ptr()), ), DeleteEnvelopePointEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DeleteEnvelopePointEx)).as_ptr()), ), DeleteEnvelopePointRange: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DeleteEnvelopePointRange)).as_ptr(), ), ), DeleteEnvelopePointRangeEx: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DeleteEnvelopePointRangeEx)).as_ptr(), ), ), DeleteExtState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DeleteExtState)).as_ptr()), ), DeleteProjectMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DeleteProjectMarker)).as_ptr()), ), DeleteProjectMarkerByIndex: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DeleteProjectMarkerByIndex)).as_ptr(), ), ), DeleteTakeMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DeleteTakeMarker)).as_ptr()), ), DeleteTakeStretchMarkers: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DeleteTakeStretchMarkers)).as_ptr(), ), ), DeleteTempoTimeSigMarker: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DeleteTempoTimeSigMarker)).as_ptr(), ), ), DeleteTrack: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(DeleteTrack)).as_ptr()), ), DeleteTrackMediaItem: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DeleteTrackMediaItem)).as_ptr()), ), DestroyAudioAccessor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DestroyAudioAccessor)).as_ptr()), ), DestroyLocalOscHandler: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DestroyLocalOscHandler)).as_ptr()), ), DoActionShortcutDialog: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DoActionShortcutDialog)).as_ptr()), ), Dock_UpdateDockID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Dock_UpdateDockID)).as_ptr()), ), DockGetPosition: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DockGetPosition)).as_ptr()), ), DockIsChildOfDock: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DockIsChildOfDock)).as_ptr()), ), DockWindowActivate: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DockWindowActivate)).as_ptr()), ), DockWindowAdd: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(DockWindowAdd)).as_ptr()), ), DockWindowAddEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DockWindowAddEx)).as_ptr()), ), DockWindowRefresh: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DockWindowRefresh)).as_ptr()), ), DockWindowRefreshForHWND: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DockWindowRefreshForHWND)).as_ptr(), ), ), DockWindowRemove: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(DockWindowRemove)).as_ptr()), ), DuplicateCustomizableMenu: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(DuplicateCustomizableMenu)).as_ptr(), ), ), EditTempoTimeSigMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EditTempoTimeSigMarker)).as_ptr()), ), EnsureNotCompletelyOffscreen: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(EnsureNotCompletelyOffscreen)).as_ptr(), )), EnumerateFiles: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumerateFiles)).as_ptr()), ), EnumerateSubdirectories: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumerateSubdirectories)).as_ptr()), ), EnumPitchShiftModes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumPitchShiftModes)).as_ptr()), ), EnumPitchShiftSubModes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumPitchShiftSubModes)).as_ptr()), ), EnumProjectMarkers: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumProjectMarkers)).as_ptr()), ), EnumProjectMarkers2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumProjectMarkers2)).as_ptr()), ), EnumProjectMarkers3: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumProjectMarkers3)).as_ptr()), ), EnumProjects: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(EnumProjects)).as_ptr()), ), EnumProjExtState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumProjExtState)).as_ptr()), ), EnumRegionRenderMatrix: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(EnumRegionRenderMatrix)).as_ptr()), ), EnumTrackMIDIProgramNames: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(EnumTrackMIDIProgramNames)).as_ptr(), ), ), EnumTrackMIDIProgramNamesEx: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(EnumTrackMIDIProgramNamesEx)).as_ptr(), )), Envelope_Evaluate: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Envelope_Evaluate)).as_ptr()), ), Envelope_FormatValue: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Envelope_FormatValue)).as_ptr()), ), Envelope_GetParentTake: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Envelope_GetParentTake)).as_ptr()), ), Envelope_GetParentTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Envelope_GetParentTrack)).as_ptr()), ), Envelope_SortPoints: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Envelope_SortPoints)).as_ptr()), ), Envelope_SortPointsEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Envelope_SortPointsEx)).as_ptr()), ), ExecProcess: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ExecProcess)).as_ptr()), ), file_exists: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(file_exists)).as_ptr()), ), FindTempoTimeSigMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(FindTempoTimeSigMarker)).as_ptr()), ), format_timestr: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(format_timestr)).as_ptr()), ), format_timestr_len: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(format_timestr_len)).as_ptr()), ), format_timestr_pos: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(format_timestr_pos)).as_ptr()), ), FreeHeapPtr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(FreeHeapPtr)).as_ptr()), ), genGuid: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(genGuid)).as_ptr()), ), get_config_var: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(get_config_var)).as_ptr()), ), get_config_var_string: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(get_config_var_string)).as_ptr()), ), get_ini_file: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(get_ini_file)).as_ptr()), ), get_midi_config_var: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(get_midi_config_var)).as_ptr()), ), GetActionShortcutDesc: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetActionShortcutDesc)).as_ptr()), ), GetActiveTake: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetActiveTake)).as_ptr()), ), GetAllProjectPlayStates: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetAllProjectPlayStates)).as_ptr()), ), GetAppVersion: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetAppVersion)).as_ptr()), ), GetArmedCommand: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetArmedCommand)).as_ptr()), ), GetAudioAccessorEndTime: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetAudioAccessorEndTime)).as_ptr()), ), GetAudioAccessorHash: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetAudioAccessorHash)).as_ptr()), ), GetAudioAccessorSamples: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetAudioAccessorSamples)).as_ptr()), ), GetAudioAccessorStartTime: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetAudioAccessorStartTime)).as_ptr(), ), ), GetAudioDeviceInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetAudioDeviceInfo)).as_ptr()), ), GetColorTheme: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetColorTheme)).as_ptr()), ), GetColorThemeStruct: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetColorThemeStruct)).as_ptr()), ), GetConfigWantsDock: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetConfigWantsDock)).as_ptr()), ), GetContextMenu: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetContextMenu)).as_ptr()), ), GetCurrentProjectInLoadSave: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetCurrentProjectInLoadSave)).as_ptr(), )), GetCursorContext: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetCursorContext)).as_ptr()), ), GetCursorContext2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetCursorContext2)).as_ptr()), ), GetCursorPosition: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetCursorPosition)).as_ptr()), ), GetCursorPositionEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetCursorPositionEx)).as_ptr()), ), GetDisplayedMediaItemColor: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetDisplayedMediaItemColor)).as_ptr(), ), ), GetDisplayedMediaItemColor2: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetDisplayedMediaItemColor2)).as_ptr(), )), GetEnvelopeInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopeInfo_Value)).as_ptr()), ), GetEnvelopeName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopeName)).as_ptr()), ), GetEnvelopePoint: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopePoint)).as_ptr()), ), GetEnvelopePointByTime: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopePointByTime)).as_ptr()), ), GetEnvelopePointByTimeEx: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetEnvelopePointByTimeEx)).as_ptr(), ), ), GetEnvelopePointEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopePointEx)).as_ptr()), ), GetEnvelopeScalingMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopeScalingMode)).as_ptr()), ), GetEnvelopeStateChunk: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetEnvelopeStateChunk)).as_ptr()), ), GetExePath: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetExePath)).as_ptr()), ), GetExtState: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetExtState)).as_ptr()), ), GetFocusedFX: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetFocusedFX)).as_ptr()), ), GetFocusedFX2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetFocusedFX2)).as_ptr()), ), GetFreeDiskSpaceForRecordPath: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetFreeDiskSpaceForRecordPath)).as_ptr(), )), GetFXEnvelope: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetFXEnvelope)).as_ptr()), ), GetGlobalAutomationOverride: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetGlobalAutomationOverride)).as_ptr(), )), GetHZoomLevel: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetHZoomLevel)).as_ptr()), ), GetIconThemePointer: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetIconThemePointer)).as_ptr()), ), GetIconThemePointerForDPI: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetIconThemePointerForDPI)).as_ptr(), ), ), GetIconThemeStruct: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetIconThemeStruct)).as_ptr()), ), GetInputChannelName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetInputChannelName)).as_ptr()), ), GetInputOutputLatency: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetInputOutputLatency)).as_ptr()), ), GetItemEditingTime2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetItemEditingTime2)).as_ptr()), ), GetItemFromPoint: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetItemFromPoint)).as_ptr()), ), GetItemProjectContext: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetItemProjectContext)).as_ptr()), ), GetItemStateChunk: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetItemStateChunk)).as_ptr()), ), GetLastColorThemeFile: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetLastColorThemeFile)).as_ptr()), ), GetLastMarkerAndCurRegion: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetLastMarkerAndCurRegion)).as_ptr(), ), ), GetLastTouchedFX: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetLastTouchedFX)).as_ptr()), ), GetLastTouchedTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetLastTouchedTrack)).as_ptr()), ), GetMainHwnd: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetMainHwnd)).as_ptr()), ), GetMasterMuteSoloFlags: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMasterMuteSoloFlags)).as_ptr()), ), GetMasterTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMasterTrack)).as_ptr()), ), GetMasterTrackVisibility: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetMasterTrackVisibility)).as_ptr(), ), ), GetMaxMidiInputs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMaxMidiInputs)).as_ptr()), ), GetMaxMidiOutputs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMaxMidiOutputs)).as_ptr()), ), GetMediaFileMetadata: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaFileMetadata)).as_ptr()), ), GetMediaItem: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetMediaItem)).as_ptr()), ), GetMediaItem_Track: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItem_Track)).as_ptr()), ), GetMediaItemInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemInfo_Value)).as_ptr()), ), GetMediaItemNumTakes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemNumTakes)).as_ptr()), ), GetMediaItemTake: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTake)).as_ptr()), ), GetMediaItemTake_Item: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTake_Item)).as_ptr()), ), GetMediaItemTake_Peaks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTake_Peaks)).as_ptr()), ), GetMediaItemTake_Source: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTake_Source)).as_ptr()), ), GetMediaItemTake_Track: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTake_Track)).as_ptr()), ), GetMediaItemTakeByGUID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTakeByGUID)).as_ptr()), ), GetMediaItemTakeInfo_Value: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetMediaItemTakeInfo_Value)).as_ptr(), ), ), GetMediaItemTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaItemTrack)).as_ptr()), ), GetMediaSourceFileName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaSourceFileName)).as_ptr()), ), GetMediaSourceLength: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaSourceLength)).as_ptr()), ), GetMediaSourceNumChannels: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetMediaSourceNumChannels)).as_ptr(), ), ), GetMediaSourceParent: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaSourceParent)).as_ptr()), ), GetMediaSourceSampleRate: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetMediaSourceSampleRate)).as_ptr(), ), ), GetMediaSourceType: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaSourceType)).as_ptr()), ), GetMediaTrackInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMediaTrackInfo_Value)).as_ptr()), ), GetMIDIInputName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMIDIInputName)).as_ptr()), ), GetMIDIOutputName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMIDIOutputName)).as_ptr()), ), GetMixerScroll: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMixerScroll)).as_ptr()), ), GetMouseModifier: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMouseModifier)).as_ptr()), ), GetMousePosition: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetMousePosition)).as_ptr()), ), GetNumAudioInputs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetNumAudioInputs)).as_ptr()), ), GetNumAudioOutputs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetNumAudioOutputs)).as_ptr()), ), GetNumMIDIInputs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetNumMIDIInputs)).as_ptr()), ), GetNumMIDIOutputs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetNumMIDIOutputs)).as_ptr()), ), GetNumTakeMarkers: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetNumTakeMarkers)).as_ptr()), ), GetNumTracks: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetNumTracks)).as_ptr()), ), GetOS: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetOS)).as_ptr()), ), GetOutputChannelName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetOutputChannelName)).as_ptr()), ), GetOutputLatency: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetOutputLatency)).as_ptr()), ), GetParentTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetParentTrack)).as_ptr()), ), GetPeakFileName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPeakFileName)).as_ptr()), ), GetPeakFileNameEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPeakFileNameEx)).as_ptr()), ), GetPeakFileNameEx2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPeakFileNameEx2)).as_ptr()), ), GetPeaksBitmap: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPeaksBitmap)).as_ptr()), ), GetPlayPosition: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPlayPosition)).as_ptr()), ), GetPlayPosition2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPlayPosition2)).as_ptr()), ), GetPlayPosition2Ex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPlayPosition2Ex)).as_ptr()), ), GetPlayPositionEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPlayPositionEx)).as_ptr()), ), GetPlayState: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetPlayState)).as_ptr()), ), GetPlayStateEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetPlayStateEx)).as_ptr()), ), GetPreferredDiskReadMode: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetPreferredDiskReadMode)).as_ptr(), ), ), GetPreferredDiskReadModePeak: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetPreferredDiskReadModePeak)).as_ptr(), )), GetPreferredDiskWriteMode: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetPreferredDiskWriteMode)).as_ptr(), ), ), GetProjectLength: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjectLength)).as_ptr()), ), GetProjectName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjectName)).as_ptr()), ), GetProjectPath: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjectPath)).as_ptr()), ), GetProjectPathEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjectPathEx)).as_ptr()), ), GetProjectStateChangeCount: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetProjectStateChangeCount)).as_ptr(), ), ), GetProjectTimeOffset: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjectTimeOffset)).as_ptr()), ), GetProjectTimeSignature: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjectTimeSignature)).as_ptr()), ), GetProjectTimeSignature2: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetProjectTimeSignature2)).as_ptr(), ), ), GetProjExtState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetProjExtState)).as_ptr()), ), GetResourcePath: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetResourcePath)).as_ptr()), ), GetSelectedEnvelope: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSelectedEnvelope)).as_ptr()), ), GetSelectedMediaItem: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSelectedMediaItem)).as_ptr()), ), GetSelectedTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSelectedTrack)).as_ptr()), ), GetSelectedTrack2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSelectedTrack2)).as_ptr()), ), GetSelectedTrackEnvelope: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSelectedTrackEnvelope)).as_ptr(), ), ), GetSet_ArrangeView2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSet_ArrangeView2)).as_ptr()), ), GetSet_LoopTimeRange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSet_LoopTimeRange)).as_ptr()), ), GetSet_LoopTimeRange2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSet_LoopTimeRange2)).as_ptr()), ), GetSetAutomationItemInfo: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetAutomationItemInfo)).as_ptr(), ), ), GetSetAutomationItemInfo_String: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetAutomationItemInfo_String)).as_ptr(), )), GetSetEnvelopeInfo_String: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetEnvelopeInfo_String)).as_ptr(), ), ), GetSetEnvelopeState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetEnvelopeState)).as_ptr()), ), GetSetEnvelopeState2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetEnvelopeState2)).as_ptr()), ), GetSetItemState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetItemState)).as_ptr()), ), GetSetItemState2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetItemState2)).as_ptr()), ), GetSetMediaItemInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetMediaItemInfo)).as_ptr()), ), GetSetMediaItemInfo_String: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetMediaItemInfo_String)).as_ptr(), ), ), GetSetMediaItemTakeInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetMediaItemTakeInfo)).as_ptr()), ), GetSetMediaItemTakeInfo_String: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetMediaItemTakeInfo_String)).as_ptr(), )), GetSetMediaTrackInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetMediaTrackInfo)).as_ptr()), ), GetSetMediaTrackInfo_String: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetMediaTrackInfo_String)).as_ptr(), )), GetSetObjectState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetObjectState)).as_ptr()), ), GetSetObjectState2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetObjectState2)).as_ptr()), ), GetSetProjectAuthor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetProjectAuthor)).as_ptr()), ), GetSetProjectGrid: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetProjectGrid)).as_ptr()), ), GetSetProjectInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetProjectInfo)).as_ptr()), ), GetSetProjectInfo_String: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetProjectInfo_String)).as_ptr(), ), ), GetSetProjectNotes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetProjectNotes)).as_ptr()), ), GetSetRepeat: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetSetRepeat)).as_ptr()), ), GetSetRepeatEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetRepeatEx)).as_ptr()), ), GetSetTrackGroupMembership: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetTrackGroupMembership)).as_ptr(), ), ), GetSetTrackGroupMembershipHigh: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetTrackGroupMembershipHigh)).as_ptr(), )), GetSetTrackMIDISupportFile: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetTrackMIDISupportFile)).as_ptr(), ), ), GetSetTrackSendInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetTrackSendInfo)).as_ptr()), ), GetSetTrackSendInfo_String: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetSetTrackSendInfo_String)).as_ptr(), ), ), GetSetTrackState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetTrackState)).as_ptr()), ), GetSetTrackState2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSetTrackState2)).as_ptr()), ), GetSubProjectFromSource: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetSubProjectFromSource)).as_ptr()), ), GetTake: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTake)).as_ptr()), ), GetTakeEnvelope: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTakeEnvelope)).as_ptr()), ), GetTakeEnvelopeByName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTakeEnvelopeByName)).as_ptr()), ), GetTakeMarker: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTakeMarker)).as_ptr()), ), GetTakeName: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTakeName)).as_ptr()), ), GetTakeNumStretchMarkers: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetTakeNumStretchMarkers)).as_ptr(), ), ), GetTakeStretchMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTakeStretchMarker)).as_ptr()), ), GetTakeStretchMarkerSlope: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetTakeStretchMarkerSlope)).as_ptr(), ), ), GetTCPFXParm: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTCPFXParm)).as_ptr()), ), GetTempoMatchPlayRate: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTempoMatchPlayRate)).as_ptr()), ), GetTempoTimeSigMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTempoTimeSigMarker)).as_ptr()), ), GetThemeColor: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetThemeColor)).as_ptr()), ), GetThingFromPoint: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetThingFromPoint)).as_ptr()), ), GetToggleCommandState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetToggleCommandState)).as_ptr()), ), GetToggleCommandState2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetToggleCommandState2)).as_ptr()), ), GetToggleCommandStateEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetToggleCommandStateEx)).as_ptr()), ), GetToggleCommandStateThroughHooks: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetToggleCommandStateThroughHooks)).as_ptr(), )), GetTooltipWindow: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTooltipWindow)).as_ptr()), ), GetTrack: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrack)).as_ptr()), ), GetTrackAutomationMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackAutomationMode)).as_ptr()), ), GetTrackColor: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackColor)).as_ptr()), ), GetTrackDepth: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackDepth)).as_ptr()), ), GetTrackEnvelope: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackEnvelope)).as_ptr()), ), GetTrackEnvelopeByChunkName: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(GetTrackEnvelopeByChunkName)).as_ptr(), )), GetTrackEnvelopeByName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackEnvelopeByName)).as_ptr()), ), GetTrackFromPoint: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackFromPoint)).as_ptr()), ), GetTrackGUID: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackGUID)).as_ptr()), ), GetTrackInfo: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackInfo)).as_ptr()), ), GetTrackMediaItem: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackMediaItem)).as_ptr()), ), GetTrackMIDILyrics: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackMIDILyrics)).as_ptr()), ), GetTrackMIDINoteName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackMIDINoteName)).as_ptr()), ), GetTrackMIDINoteNameEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackMIDINoteNameEx)).as_ptr()), ), GetTrackMIDINoteRange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackMIDINoteRange)).as_ptr()), ), GetTrackName: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackName)).as_ptr()), ), GetTrackNumMediaItems: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackNumMediaItems)).as_ptr()), ), GetTrackNumSends: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackNumSends)).as_ptr()), ), GetTrackReceiveName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackReceiveName)).as_ptr()), ), GetTrackReceiveUIMute: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackReceiveUIMute)).as_ptr()), ), GetTrackReceiveUIVolPan: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackReceiveUIVolPan)).as_ptr()), ), GetTrackSendInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackSendInfo_Value)).as_ptr()), ), GetTrackSendName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackSendName)).as_ptr()), ), GetTrackSendUIMute: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackSendUIMute)).as_ptr()), ), GetTrackSendUIVolPan: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackSendUIVolPan)).as_ptr()), ), GetTrackState: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackState)).as_ptr()), ), GetTrackStateChunk: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackStateChunk)).as_ptr()), ), GetTrackUIMute: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackUIMute)).as_ptr()), ), GetTrackUIPan: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetTrackUIPan)).as_ptr()), ), GetTrackUIVolPan: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetTrackUIVolPan)).as_ptr()), ), GetUnderrunTime: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetUnderrunTime)).as_ptr()), ), GetUserFileNameForRead: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GetUserFileNameForRead)).as_ptr()), ), GetUserInputs: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetUserInputs)).as_ptr()), ), GoToMarker: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GoToMarker)).as_ptr()), ), GoToRegion: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GoToRegion)).as_ptr()), ), GR_SelectColor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(GR_SelectColor)).as_ptr()), ), GSC_mainwnd: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GSC_mainwnd)).as_ptr()), ), guidToString: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(guidToString)).as_ptr()), ), HasExtState: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(HasExtState)).as_ptr()), ), HasTrackMIDIPrograms: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(HasTrackMIDIPrograms)).as_ptr()), ), HasTrackMIDIProgramsEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(HasTrackMIDIProgramsEx)).as_ptr()), ), Help_Set: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Help_Set)).as_ptr()), ), HiresPeaksFromSource: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(HiresPeaksFromSource)).as_ptr()), ), image_resolve_fn: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(image_resolve_fn)).as_ptr()), ), InsertAutomationItem: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(InsertAutomationItem)).as_ptr()), ), InsertEnvelopePoint: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(InsertEnvelopePoint)).as_ptr()), ), InsertEnvelopePointEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(InsertEnvelopePointEx)).as_ptr()), ), InsertMedia: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(InsertMedia)).as_ptr()), ), InsertMediaSection: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(InsertMediaSection)).as_ptr()), ), InsertTrackAtIndex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(InsertTrackAtIndex)).as_ptr()), ), IsInRealTimeAudio: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(IsInRealTimeAudio)).as_ptr()), ), IsItemTakeActiveForPlayback: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(IsItemTakeActiveForPlayback)).as_ptr(), )), IsMediaExtension: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(IsMediaExtension)).as_ptr()), ), IsMediaItemSelected: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(IsMediaItemSelected)).as_ptr()), ), IsProjectDirty: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(IsProjectDirty)).as_ptr()), ), IsREAPER: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(IsREAPER)).as_ptr()), ), IsTrackSelected: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(IsTrackSelected)).as_ptr()), ), IsTrackVisible: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(IsTrackVisible)).as_ptr()), ), joystick_create: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_create)).as_ptr()), ), joystick_destroy: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_destroy)).as_ptr()), ), joystick_enum: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(joystick_enum)).as_ptr()), ), joystick_getaxis: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_getaxis)).as_ptr()), ), joystick_getbuttonmask: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_getbuttonmask)).as_ptr()), ), joystick_getinfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_getinfo)).as_ptr()), ), joystick_getpov: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_getpov)).as_ptr()), ), joystick_update: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(joystick_update)).as_ptr()), ), kbd_enumerateActions: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_enumerateActions)).as_ptr()), ), kbd_formatKeyName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_formatKeyName)).as_ptr()), ), kbd_getCommandName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_getCommandName)).as_ptr()), ), kbd_getTextFromCmd: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_getTextFromCmd)).as_ptr()), ), KBD_OnMainActionEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(KBD_OnMainActionEx)).as_ptr()), ), kbd_OnMidiEvent: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_OnMidiEvent)).as_ptr()), ), kbd_OnMidiList: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_OnMidiList)).as_ptr()), ), kbd_ProcessActionsMenu: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_ProcessActionsMenu)).as_ptr()), ), kbd_processMidiEventActionEx: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(kbd_processMidiEventActionEx)).as_ptr(), )), kbd_reprocessMenu: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_reprocessMenu)).as_ptr()), ), kbd_RunCommandThroughHooks: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(kbd_RunCommandThroughHooks)).as_ptr(), ), ), kbd_translateAccelerator: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(kbd_translateAccelerator)).as_ptr(), ), ), kbd_translateMouse: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(kbd_translateMouse)).as_ptr()), ), LICE__Destroy: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE__Destroy)).as_ptr()), ), LICE__DestroyFont: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__DestroyFont)).as_ptr()), ), LICE__DrawText: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__DrawText)).as_ptr()), ), LICE__GetBits: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE__GetBits)).as_ptr()), ), LICE__GetDC: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE__GetDC)).as_ptr()), ), LICE__GetHeight: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__GetHeight)).as_ptr()), ), LICE__GetRowSpan: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__GetRowSpan)).as_ptr()), ), LICE__GetWidth: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__GetWidth)).as_ptr()), ), LICE__IsFlipped: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__IsFlipped)).as_ptr()), ), LICE__resize: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE__resize)).as_ptr()), ), LICE__SetBkColor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__SetBkColor)).as_ptr()), ), LICE__SetFromHFont: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__SetFromHFont)).as_ptr()), ), LICE__SetTextColor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE__SetTextColor)).as_ptr()), ), LICE__SetTextCombineMode: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(LICE__SetTextCombineMode)).as_ptr(), ), ), LICE_Arc: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Arc)).as_ptr()), ), LICE_Blit: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Blit)).as_ptr()), ), LICE_Blur: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Blur)).as_ptr()), ), LICE_BorderedRect: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_BorderedRect)).as_ptr()), ), LICE_Circle: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Circle)).as_ptr()), ), LICE_Clear: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Clear)).as_ptr()), ), LICE_ClearRect: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_ClearRect)).as_ptr()), ), LICE_ClipLine: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_ClipLine)).as_ptr()), ), LICE_Copy: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Copy)).as_ptr()), ), LICE_CreateBitmap: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_CreateBitmap)).as_ptr()), ), LICE_CreateFont: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_CreateFont)).as_ptr()), ), LICE_DrawCBezier: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_DrawCBezier)).as_ptr()), ), LICE_DrawChar: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_DrawChar)).as_ptr()), ), LICE_DrawGlyph: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_DrawGlyph)).as_ptr()), ), LICE_DrawRect: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_DrawRect)).as_ptr()), ), LICE_DrawText: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_DrawText)).as_ptr()), ), LICE_FillCBezier: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_FillCBezier)).as_ptr()), ), LICE_FillCircle: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_FillCircle)).as_ptr()), ), LICE_FillConvexPolygon: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_FillConvexPolygon)).as_ptr()), ), LICE_FillRect: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_FillRect)).as_ptr()), ), LICE_FillTrapezoid: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_FillTrapezoid)).as_ptr()), ), LICE_FillTriangle: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_FillTriangle)).as_ptr()), ), LICE_GetPixel: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_GetPixel)).as_ptr()), ), LICE_GradRect: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_GradRect)).as_ptr()), ), LICE_Line: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_Line)).as_ptr()), ), LICE_LineInt: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_LineInt)).as_ptr()), ), LICE_LoadPNG: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_LoadPNG)).as_ptr()), ), LICE_LoadPNGFromResource: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(LICE_LoadPNGFromResource)).as_ptr(), ), ), LICE_MeasureText: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_MeasureText)).as_ptr()), ), LICE_MultiplyAddRect: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_MultiplyAddRect)).as_ptr()), ), LICE_PutPixel: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(LICE_PutPixel)).as_ptr()), ), LICE_RotatedBlit: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_RotatedBlit)).as_ptr()), ), LICE_RoundRect: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_RoundRect)).as_ptr()), ), LICE_ScaledBlit: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_ScaledBlit)).as_ptr()), ), LICE_SimpleFill: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LICE_SimpleFill)).as_ptr()), ), LocalizeString: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(LocalizeString)).as_ptr()), ), Loop_OnArrow: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Loop_OnArrow)).as_ptr()), ), Main_OnCommand: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Main_OnCommand)).as_ptr()), ), Main_OnCommandEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Main_OnCommandEx)).as_ptr()), ), Main_openProject: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Main_openProject)).as_ptr()), ), Main_SaveProject: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Main_SaveProject)).as_ptr()), ), Main_UpdateLoopInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Main_UpdateLoopInfo)).as_ptr()), ), MarkProjectDirty: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MarkProjectDirty)).as_ptr()), ), MarkTrackItemsDirty: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MarkTrackItemsDirty)).as_ptr()), ), Master_GetPlayRate: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Master_GetPlayRate)).as_ptr()), ), Master_GetPlayRateAtTime: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(Master_GetPlayRateAtTime)).as_ptr(), ), ), Master_GetTempo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Master_GetTempo)).as_ptr()), ), Master_NormalizePlayRate: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(Master_NormalizePlayRate)).as_ptr(), ), ), Master_NormalizeTempo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Master_NormalizeTempo)).as_ptr()), ), MB: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MB)).as_ptr()), ), MediaItemDescendsFromTrack: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MediaItemDescendsFromTrack)).as_ptr(), ), ), MIDI_CountEvts: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_CountEvts)).as_ptr()), ), MIDI_DeleteCC: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_DeleteCC)).as_ptr()), ), MIDI_DeleteEvt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_DeleteEvt)).as_ptr()), ), MIDI_DeleteNote: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_DeleteNote)).as_ptr()), ), MIDI_DeleteTextSysexEvt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_DeleteTextSysexEvt)).as_ptr()), ), MIDI_DisableSort: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_DisableSort)).as_ptr()), ), MIDI_EnumSelCC: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_EnumSelCC)).as_ptr()), ), MIDI_EnumSelEvts: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_EnumSelEvts)).as_ptr()), ), MIDI_EnumSelNotes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_EnumSelNotes)).as_ptr()), ), MIDI_EnumSelTextSysexEvts: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_EnumSelTextSysexEvts)).as_ptr(), ), ), MIDI_eventlist_Create: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_eventlist_Create)).as_ptr()), ), MIDI_eventlist_Destroy: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_eventlist_Destroy)).as_ptr()), ), MIDI_GetAllEvts: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetAllEvts)).as_ptr()), ), MIDI_GetCC: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetCC)).as_ptr()), ), MIDI_GetCCShape: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetCCShape)).as_ptr()), ), MIDI_GetEvt: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetEvt)).as_ptr()), ), MIDI_GetGrid: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetGrid)).as_ptr()), ), MIDI_GetHash: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetHash)).as_ptr()), ), MIDI_GetNote: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetNote)).as_ptr()), ), MIDI_GetPPQPos_EndOfMeasure: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_GetPPQPos_EndOfMeasure)).as_ptr(), )), MIDI_GetPPQPos_StartOfMeasure: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_GetPPQPos_StartOfMeasure)).as_ptr(), )), MIDI_GetPPQPosFromProjQN: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_GetPPQPosFromProjQN)).as_ptr(), ), ), MIDI_GetPPQPosFromProjTime: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_GetPPQPosFromProjTime)).as_ptr(), ), ), MIDI_GetProjQNFromPPQPos: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_GetProjQNFromPPQPos)).as_ptr(), ), ), MIDI_GetProjTimeFromPPQPos: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDI_GetProjTimeFromPPQPos)).as_ptr(), ), ), MIDI_GetScale: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetScale)).as_ptr()), ), MIDI_GetTextSysexEvt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetTextSysexEvt)).as_ptr()), ), MIDI_GetTrackHash: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_GetTrackHash)).as_ptr()), ), MIDI_InsertCC: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_InsertCC)).as_ptr()), ), MIDI_InsertEvt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_InsertEvt)).as_ptr()), ), MIDI_InsertNote: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_InsertNote)).as_ptr()), ), MIDI_InsertTextSysexEvt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_InsertTextSysexEvt)).as_ptr()), ), midi_reinit: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(midi_reinit)).as_ptr()), ), MIDI_SelectAll: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_SelectAll)).as_ptr()), ), MIDI_SetAllEvts: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetAllEvts)).as_ptr()), ), MIDI_SetCC: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetCC)).as_ptr()), ), MIDI_SetCCShape: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetCCShape)).as_ptr()), ), MIDI_SetEvt: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetEvt)).as_ptr()), ), MIDI_SetItemExtents: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetItemExtents)).as_ptr()), ), MIDI_SetNote: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetNote)).as_ptr()), ), MIDI_SetTextSysexEvt: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDI_SetTextSysexEvt)).as_ptr()), ), MIDI_Sort: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MIDI_Sort)).as_ptr()), ), MIDIEditor_EnumTakes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDIEditor_EnumTakes)).as_ptr()), ), MIDIEditor_GetActive: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDIEditor_GetActive)).as_ptr()), ), MIDIEditor_GetMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDIEditor_GetMode)).as_ptr()), ), MIDIEditor_GetSetting_int: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDIEditor_GetSetting_int)).as_ptr(), ), ), MIDIEditor_GetSetting_str: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDIEditor_GetSetting_str)).as_ptr(), ), ), MIDIEditor_GetTake: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDIEditor_GetTake)).as_ptr()), ), MIDIEditor_LastFocused_OnCommand: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDIEditor_LastFocused_OnCommand)).as_ptr(), )), MIDIEditor_OnCommand: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MIDIEditor_OnCommand)).as_ptr()), ), MIDIEditor_SetSetting_int: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(MIDIEditor_SetSetting_int)).as_ptr(), ), ), mkpanstr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(mkpanstr)).as_ptr()), ), mkvolpanstr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(mkvolpanstr)).as_ptr()), ), mkvolstr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(mkvolstr)).as_ptr()), ), MoveEditCursor: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MoveEditCursor)).as_ptr()), ), MoveMediaItemToTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(MoveMediaItemToTrack)).as_ptr()), ), MuteAllTracks: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(MuteAllTracks)).as_ptr()), ), my_getViewport: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(my_getViewport)).as_ptr()), ), NamedCommandLookup: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(NamedCommandLookup)).as_ptr()), ), OnPauseButton: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(OnPauseButton)).as_ptr()), ), OnPauseButtonEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(OnPauseButtonEx)).as_ptr()), ), OnPlayButton: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(OnPlayButton)).as_ptr()), ), OnPlayButtonEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(OnPlayButtonEx)).as_ptr()), ), OnStopButton: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(OnStopButton)).as_ptr()), ), OnStopButtonEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(OnStopButtonEx)).as_ptr()), ), OpenColorThemeFile: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(OpenColorThemeFile)).as_ptr()), ), OpenMediaExplorer: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(OpenMediaExplorer)).as_ptr()), ), OscLocalMessageToHost: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(OscLocalMessageToHost)).as_ptr()), ), parse_timestr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(parse_timestr)).as_ptr()), ), parse_timestr_len: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(parse_timestr_len)).as_ptr()), ), parse_timestr_pos: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(parse_timestr_pos)).as_ptr()), ), parsepanstr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(parsepanstr)).as_ptr()), ), PCM_Sink_Create: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Sink_Create)).as_ptr()), ), PCM_Sink_CreateEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Sink_CreateEx)).as_ptr()), ), PCM_Sink_CreateMIDIFile: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Sink_CreateMIDIFile)).as_ptr()), ), PCM_Sink_CreateMIDIFileEx: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(PCM_Sink_CreateMIDIFileEx)).as_ptr(), ), ), PCM_Sink_Enum: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(PCM_Sink_Enum)).as_ptr()), ), PCM_Sink_GetExtension: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Sink_GetExtension)).as_ptr()), ), PCM_Sink_ShowConfig: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Sink_ShowConfig)).as_ptr()), ), PCM_Source_BuildPeaks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Source_BuildPeaks)).as_ptr()), ), PCM_Source_CreateFromFile: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(PCM_Source_CreateFromFile)).as_ptr(), ), ), PCM_Source_CreateFromFileEx: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(PCM_Source_CreateFromFileEx)).as_ptr(), )), PCM_Source_CreateFromSimple: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(PCM_Source_CreateFromSimple)).as_ptr(), )), PCM_Source_CreateFromType: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(PCM_Source_CreateFromType)).as_ptr(), ), ), PCM_Source_Destroy: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Source_Destroy)).as_ptr()), ), PCM_Source_GetPeaks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PCM_Source_GetPeaks)).as_ptr()), ), PCM_Source_GetSectionInfo: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(PCM_Source_GetSectionInfo)).as_ptr(), ), ), PeakBuild_Create: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PeakBuild_Create)).as_ptr()), ), PeakBuild_CreateEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PeakBuild_CreateEx)).as_ptr()), ), PeakGet_Create: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PeakGet_Create)).as_ptr()), ), PitchShiftSubModeMenu: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PitchShiftSubModeMenu)).as_ptr()), ), PlayPreview: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(PlayPreview)).as_ptr()), ), PlayPreviewEx: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(PlayPreviewEx)).as_ptr()), ), PlayTrackPreview: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PlayTrackPreview)).as_ptr()), ), PlayTrackPreview2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PlayTrackPreview2)).as_ptr()), ), PlayTrackPreview2Ex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PlayTrackPreview2Ex)).as_ptr()), ), plugin_getapi: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(plugin_getapi)).as_ptr()), ), plugin_getFilterList: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(plugin_getFilterList)).as_ptr()), ), plugin_getImportableProjectFilterList: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(plugin_getImportableProjectFilterList)).as_ptr(), )), plugin_register: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(plugin_register)).as_ptr()), ), PluginWantsAlwaysRunFx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PluginWantsAlwaysRunFx)).as_ptr()), ), PreventUIRefresh: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PreventUIRefresh)).as_ptr()), ), projectconfig_var_addr: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(projectconfig_var_addr)).as_ptr()), ), projectconfig_var_getoffs: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(projectconfig_var_getoffs)).as_ptr(), ), ), PromptForAction: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(PromptForAction)).as_ptr()), ), realloc_cmd_ptr: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(realloc_cmd_ptr)).as_ptr()), ), ReaperGetPitchShiftAPI: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ReaperGetPitchShiftAPI)).as_ptr()), ), ReaScriptError: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ReaScriptError)).as_ptr()), ), RecursiveCreateDirectory: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(RecursiveCreateDirectory)).as_ptr(), ), ), reduce_open_files: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(reduce_open_files)).as_ptr()), ), RefreshToolbar: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(RefreshToolbar)).as_ptr()), ), RefreshToolbar2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(RefreshToolbar2)).as_ptr()), ), relative_fn: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(relative_fn)).as_ptr()), ), RemoveTrackSend: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(RemoveTrackSend)).as_ptr()), ), RenderFileSection: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(RenderFileSection)).as_ptr()), ), ReorderSelectedTracks: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ReorderSelectedTracks)).as_ptr()), ), Resample_EnumModes: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Resample_EnumModes)).as_ptr()), ), Resampler_Create: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Resampler_Create)).as_ptr()), ), resolve_fn: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(resolve_fn)).as_ptr()), ), resolve_fn2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(resolve_fn2)).as_ptr()), ), ResolveRenderPattern: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ResolveRenderPattern)).as_ptr()), ), ReverseNamedCommandLookup: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(ReverseNamedCommandLookup)).as_ptr(), ), ), ScaleFromEnvelopeMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ScaleFromEnvelopeMode)).as_ptr()), ), ScaleToEnvelopeMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ScaleToEnvelopeMode)).as_ptr()), ), screenset_register: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(screenset_register)).as_ptr()), ), screenset_registerNew: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(screenset_registerNew)).as_ptr()), ), screenset_unregister: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(screenset_unregister)).as_ptr()), ), screenset_unregisterByParam: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(screenset_unregisterByParam)).as_ptr(), )), screenset_updateLastFocus: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(screenset_updateLastFocus)).as_ptr(), ), ), SectionFromUniqueID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SectionFromUniqueID)).as_ptr()), ), SelectAllMediaItems: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SelectAllMediaItems)).as_ptr()), ), SelectProjectInstance: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SelectProjectInstance)).as_ptr()), ), SendLocalOscMessage: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SendLocalOscMessage)).as_ptr()), ), SetActiveTake: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetActiveTake)).as_ptr()), ), SetAutomationMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetAutomationMode)).as_ptr()), ), SetCurrentBPM: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetCurrentBPM)).as_ptr()), ), SetCursorContext: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetCursorContext)).as_ptr()), ), SetEditCurPos: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetEditCurPos)).as_ptr()), ), SetEditCurPos2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetEditCurPos2)).as_ptr()), ), SetEnvelopePoint: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetEnvelopePoint)).as_ptr()), ), SetEnvelopePointEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetEnvelopePointEx)).as_ptr()), ), SetEnvelopeStateChunk: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetEnvelopeStateChunk)).as_ptr()), ), SetExtState: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetExtState)).as_ptr()), ), SetGlobalAutomationOverride: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(SetGlobalAutomationOverride)).as_ptr(), )), SetItemStateChunk: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetItemStateChunk)).as_ptr()), ), SetMasterTrackVisibility: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(SetMasterTrackVisibility)).as_ptr(), ), ), SetMediaItemInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMediaItemInfo_Value)).as_ptr()), ), SetMediaItemLength: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMediaItemLength)).as_ptr()), ), SetMediaItemPosition: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMediaItemPosition)).as_ptr()), ), SetMediaItemSelected: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMediaItemSelected)).as_ptr()), ), SetMediaItemTake_Source: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMediaItemTake_Source)).as_ptr()), ), SetMediaItemTakeInfo_Value: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(SetMediaItemTakeInfo_Value)).as_ptr(), ), ), SetMediaTrackInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMediaTrackInfo_Value)).as_ptr()), ), SetMIDIEditorGrid: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMIDIEditorGrid)).as_ptr()), ), SetMixerScroll: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMixerScroll)).as_ptr()), ), SetMouseModifier: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetMouseModifier)).as_ptr()), ), SetOnlyTrackSelected: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetOnlyTrackSelected)).as_ptr()), ), SetProjectGrid: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjectGrid)).as_ptr()), ), SetProjectMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjectMarker)).as_ptr()), ), SetProjectMarker2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjectMarker2)).as_ptr()), ), SetProjectMarker3: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjectMarker3)).as_ptr()), ), SetProjectMarker4: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjectMarker4)).as_ptr()), ), SetProjectMarkerByIndex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjectMarkerByIndex)).as_ptr()), ), SetProjectMarkerByIndex2: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(SetProjectMarkerByIndex2)).as_ptr(), ), ), SetProjExtState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetProjExtState)).as_ptr()), ), SetRegionRenderMatrix: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetRegionRenderMatrix)).as_ptr()), ), SetRenderLastError: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetRenderLastError)).as_ptr()), ), SetTakeMarker: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetTakeMarker)).as_ptr()), ), SetTakeStretchMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTakeStretchMarker)).as_ptr()), ), SetTakeStretchMarkerSlope: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(SetTakeStretchMarkerSlope)).as_ptr(), ), ), SetTempoTimeSigMarker: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTempoTimeSigMarker)).as_ptr()), ), SetThemeColor: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetThemeColor)).as_ptr()), ), SetToggleCommandState: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetToggleCommandState)).as_ptr()), ), SetTrackAutomationMode: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackAutomationMode)).as_ptr()), ), SetTrackColor: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SetTrackColor)).as_ptr()), ), SetTrackMIDILyrics: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackMIDILyrics)).as_ptr()), ), SetTrackMIDINoteName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackMIDINoteName)).as_ptr()), ), SetTrackMIDINoteNameEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackMIDINoteNameEx)).as_ptr()), ), SetTrackSelected: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackSelected)).as_ptr()), ), SetTrackSendInfo_Value: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackSendInfo_Value)).as_ptr()), ), SetTrackSendUIPan: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackSendUIPan)).as_ptr()), ), SetTrackSendUIVol: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackSendUIVol)).as_ptr()), ), SetTrackStateChunk: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SetTrackStateChunk)).as_ptr()), ), ShowActionList: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ShowActionList)).as_ptr()), ), ShowConsoleMsg: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ShowConsoleMsg)).as_ptr()), ), ShowMessageBox: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ShowMessageBox)).as_ptr()), ), ShowPopupMenu: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ShowPopupMenu)).as_ptr()), ), SLIDER2DB: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SLIDER2DB)).as_ptr()), ), SnapToGrid: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SnapToGrid)).as_ptr()), ), SoloAllTracks: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(SoloAllTracks)).as_ptr()), ), Splash_GetWnd: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Splash_GetWnd)).as_ptr()), ), SplitMediaItem: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(SplitMediaItem)).as_ptr()), ), StopPreview: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(StopPreview)).as_ptr()), ), StopTrackPreview: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(StopTrackPreview)).as_ptr()), ), StopTrackPreview2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(StopTrackPreview2)).as_ptr()), ), stringToGuid: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(stringToGuid)).as_ptr()), ), StuffMIDIMessage: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(StuffMIDIMessage)).as_ptr()), ), TakeFX_AddByName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_AddByName)).as_ptr()), ), TakeFX_CopyToTake: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_CopyToTake)).as_ptr()), ), TakeFX_CopyToTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_CopyToTrack)).as_ptr()), ), TakeFX_Delete: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(TakeFX_Delete)).as_ptr()), ), TakeFX_EndParamEdit: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_EndParamEdit)).as_ptr()), ), TakeFX_FormatParamValue: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_FormatParamValue)).as_ptr()), ), TakeFX_FormatParamValueNormalized: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_FormatParamValueNormalized)).as_ptr(), )), TakeFX_GetChainVisible: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetChainVisible)).as_ptr()), ), TakeFX_GetCount: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetCount)).as_ptr()), ), TakeFX_GetEnabled: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetEnabled)).as_ptr()), ), TakeFX_GetEnvelope: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetEnvelope)).as_ptr()), ), TakeFX_GetFloatingWindow: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetFloatingWindow)).as_ptr(), ), ), TakeFX_GetFormattedParamValue: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetFormattedParamValue)).as_ptr(), )), TakeFX_GetFXGUID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetFXGUID)).as_ptr()), ), TakeFX_GetFXName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetFXName)).as_ptr()), ), TakeFX_GetIOSize: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetIOSize)).as_ptr()), ), TakeFX_GetNamedConfigParm: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetNamedConfigParm)).as_ptr(), ), ), TakeFX_GetNumParams: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetNumParams)).as_ptr()), ), TakeFX_GetOffline: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetOffline)).as_ptr()), ), TakeFX_GetOpen: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetOpen)).as_ptr()), ), TakeFX_GetParam: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetParam)).as_ptr()), ), TakeFX_GetParameterStepSizes: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetParameterStepSizes)).as_ptr(), )), TakeFX_GetParamEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetParamEx)).as_ptr()), ), TakeFX_GetParamFromIdent: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetParamFromIdent)).as_ptr(), ), ), TakeFX_GetParamIdent: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetParamIdent)).as_ptr()), ), TakeFX_GetParamName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetParamName)).as_ptr()), ), TakeFX_GetParamNormalized: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetParamNormalized)).as_ptr(), ), ), TakeFX_GetPinMappings: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetPinMappings)).as_ptr()), ), TakeFX_GetPreset: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetPreset)).as_ptr()), ), TakeFX_GetPresetIndex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_GetPresetIndex)).as_ptr()), ), TakeFX_GetUserPresetFilename: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_GetUserPresetFilename)).as_ptr(), )), TakeFX_NavigatePresets: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_NavigatePresets)).as_ptr()), ), TakeFX_SetEnabled: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetEnabled)).as_ptr()), ), TakeFX_SetNamedConfigParm: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_SetNamedConfigParm)).as_ptr(), ), ), TakeFX_SetOffline: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetOffline)).as_ptr()), ), TakeFX_SetOpen: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetOpen)).as_ptr()), ), TakeFX_SetParam: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetParam)).as_ptr()), ), TakeFX_SetParamNormalized: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TakeFX_SetParamNormalized)).as_ptr(), ), ), TakeFX_SetPinMappings: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetPinMappings)).as_ptr()), ), TakeFX_SetPreset: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetPreset)).as_ptr()), ), TakeFX_SetPresetByIndex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TakeFX_SetPresetByIndex)).as_ptr()), ), TakeFX_Show: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(TakeFX_Show)).as_ptr()), ), TakeIsMIDI: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(TakeIsMIDI)).as_ptr()), ), ThemeLayout_GetLayout: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ThemeLayout_GetLayout)).as_ptr()), ), ThemeLayout_GetParameter: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(ThemeLayout_GetParameter)).as_ptr(), ), ), ThemeLayout_RefreshAll: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ThemeLayout_RefreshAll)).as_ptr()), ), ThemeLayout_SetLayout: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ThemeLayout_SetLayout)).as_ptr()), ), ThemeLayout_SetParameter: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(ThemeLayout_SetParameter)).as_ptr(), ), ), time_precise: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(time_precise)).as_ptr()), ), TimeMap2_beatsToTime: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap2_beatsToTime)).as_ptr()), ), TimeMap2_GetDividedBpmAtTime: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TimeMap2_GetDividedBpmAtTime)).as_ptr(), )), TimeMap2_GetNextChangeTime: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TimeMap2_GetNextChangeTime)).as_ptr(), ), ), TimeMap2_QNToTime: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap2_QNToTime)).as_ptr()), ), TimeMap2_timeToBeats: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap2_timeToBeats)).as_ptr()), ), TimeMap2_timeToQN: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap2_timeToQN)).as_ptr()), ), TimeMap_curFrameRate: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_curFrameRate)).as_ptr()), ), TimeMap_GetDividedBpmAtTime: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TimeMap_GetDividedBpmAtTime)).as_ptr(), )), TimeMap_GetMeasureInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_GetMeasureInfo)).as_ptr()), ), TimeMap_GetMetronomePattern: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TimeMap_GetMetronomePattern)).as_ptr(), )), TimeMap_GetTimeSigAtTime: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TimeMap_GetTimeSigAtTime)).as_ptr(), ), ), TimeMap_QNToMeasures: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_QNToMeasures)).as_ptr()), ), TimeMap_QNToTime: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_QNToTime)).as_ptr()), ), TimeMap_QNToTime_abs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_QNToTime_abs)).as_ptr()), ), TimeMap_timeToQN: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_timeToQN)).as_ptr()), ), TimeMap_timeToQN_abs: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TimeMap_timeToQN_abs)).as_ptr()), ), ToggleTrackSendUIMute: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(ToggleTrackSendUIMute)).as_ptr()), ), Track_GetPeakHoldDB: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Track_GetPeakHoldDB)).as_ptr()), ), Track_GetPeakInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Track_GetPeakInfo)).as_ptr()), ), TrackCtl_SetToolTip: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackCtl_SetToolTip)).as_ptr()), ), TrackFX_AddByName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_AddByName)).as_ptr()), ), TrackFX_CopyToTake: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_CopyToTake)).as_ptr()), ), TrackFX_CopyToTrack: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_CopyToTrack)).as_ptr()), ), TrackFX_Delete: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_Delete)).as_ptr()), ), TrackFX_EndParamEdit: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_EndParamEdit)).as_ptr()), ), TrackFX_FormatParamValue: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_FormatParamValue)).as_ptr(), ), ), TrackFX_FormatParamValueNormalized: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_FormatParamValueNormalized)).as_ptr(), )), TrackFX_GetByName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetByName)).as_ptr()), ), TrackFX_GetChainVisible: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetChainVisible)).as_ptr()), ), TrackFX_GetCount: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetCount)).as_ptr()), ), TrackFX_GetEnabled: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetEnabled)).as_ptr()), ), TrackFX_GetEQ: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetEQ)).as_ptr()), ), TrackFX_GetEQBandEnabled: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetEQBandEnabled)).as_ptr(), ), ), TrackFX_GetEQParam: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetEQParam)).as_ptr()), ), TrackFX_GetFloatingWindow: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetFloatingWindow)).as_ptr(), ), ), TrackFX_GetFormattedParamValue: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetFormattedParamValue)).as_ptr(), )), TrackFX_GetFXGUID: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetFXGUID)).as_ptr()), ), TrackFX_GetFXName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetFXName)).as_ptr()), ), TrackFX_GetInstrument: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetInstrument)).as_ptr()), ), TrackFX_GetIOSize: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetIOSize)).as_ptr()), ), TrackFX_GetNamedConfigParm: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetNamedConfigParm)).as_ptr(), ), ), TrackFX_GetNumParams: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetNumParams)).as_ptr()), ), TrackFX_GetOffline: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetOffline)).as_ptr()), ), TrackFX_GetOpen: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetOpen)).as_ptr()), ), TrackFX_GetParam: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetParam)).as_ptr()), ), TrackFX_GetParameterStepSizes: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetParameterStepSizes)).as_ptr(), )), TrackFX_GetParamEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetParamEx)).as_ptr()), ), TrackFX_GetParamFromIdent: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetParamFromIdent)).as_ptr(), ), ), TrackFX_GetParamIdent: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetParamIdent)).as_ptr()), ), TrackFX_GetParamName: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetParamName)).as_ptr()), ), TrackFX_GetParamNormalized: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetParamNormalized)).as_ptr(), ), ), TrackFX_GetPinMappings: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetPinMappings)).as_ptr()), ), TrackFX_GetPreset: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetPreset)).as_ptr()), ), TrackFX_GetPresetIndex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetPresetIndex)).as_ptr()), ), TrackFX_GetRecChainVisible: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetRecChainVisible)).as_ptr(), ), ), TrackFX_GetRecCount: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_GetRecCount)).as_ptr()), ), TrackFX_GetUserPresetFilename: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_GetUserPresetFilename)).as_ptr(), )), TrackFX_NavigatePresets: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_NavigatePresets)).as_ptr()), ), TrackFX_SetEnabled: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetEnabled)).as_ptr()), ), TrackFX_SetEQBandEnabled: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_SetEQBandEnabled)).as_ptr(), ), ), TrackFX_SetEQParam: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetEQParam)).as_ptr()), ), TrackFX_SetNamedConfigParm: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_SetNamedConfigParm)).as_ptr(), ), ), TrackFX_SetOffline: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetOffline)).as_ptr()), ), TrackFX_SetOpen: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetOpen)).as_ptr()), ), TrackFX_SetParam: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetParam)).as_ptr()), ), TrackFX_SetParamNormalized: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_SetParamNormalized)).as_ptr(), ), ), TrackFX_SetPinMappings: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetPinMappings)).as_ptr()), ), TrackFX_SetPreset: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackFX_SetPreset)).as_ptr()), ), TrackFX_SetPresetByIndex: std::mem::transmute( plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackFX_SetPresetByIndex)).as_ptr(), ), ), TrackFX_Show: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(TrackFX_Show)).as_ptr()), ), TrackList_AdjustWindows: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(TrackList_AdjustWindows)).as_ptr()), ), TrackList_UpdateAllExternalSurfaces: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(TrackList_UpdateAllExternalSurfaces)).as_ptr(), )), Undo_BeginBlock: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_BeginBlock)).as_ptr()), ), Undo_BeginBlock2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_BeginBlock2)).as_ptr()), ), Undo_CanRedo2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Undo_CanRedo2)).as_ptr()), ), Undo_CanUndo2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Undo_CanUndo2)).as_ptr()), ), Undo_DoRedo2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Undo_DoRedo2)).as_ptr()), ), Undo_DoUndo2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Undo_DoUndo2)).as_ptr()), ), Undo_EndBlock: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(Undo_EndBlock)).as_ptr()), ), Undo_EndBlock2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_EndBlock2)).as_ptr()), ), Undo_OnStateChange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_OnStateChange)).as_ptr()), ), Undo_OnStateChange2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_OnStateChange2)).as_ptr()), ), Undo_OnStateChange_Item: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_OnStateChange_Item)).as_ptr()), ), Undo_OnStateChangeEx: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_OnStateChangeEx)).as_ptr()), ), Undo_OnStateChangeEx2: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(Undo_OnStateChangeEx2)).as_ptr()), ), update_disk_counters: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(update_disk_counters)).as_ptr()), ), UpdateArrange: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(UpdateArrange)).as_ptr()), ), UpdateItemInProject: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(UpdateItemInProject)).as_ptr()), ), UpdateTimeline: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(UpdateTimeline)).as_ptr()), ), ValidatePtr: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ValidatePtr)).as_ptr()), ), ValidatePtr2: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ValidatePtr2)).as_ptr()), ), ViewPrefs: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(ViewPrefs)).as_ptr()), ), WDL_VirtualWnd_ScaledBlitBG: std::mem::transmute(plugin_context.GetFunc( c_str_macro::c_str!(stringify!(WDL_VirtualWnd_ScaledBlitBG)).as_ptr(), )), GetMidiInput: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetMidiInput)).as_ptr()), ), GetMidiOutput: std::mem::transmute( plugin_context.GetFunc(c_str_macro::c_str!(stringify!(GetMidiOutput)).as_ptr()), ), InitializeCoolSB: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(InitializeCoolSB)).as_ptr()), ), UninitializeCoolSB: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(UninitializeCoolSB)).as_ptr()), ), CoolSB_SetMinThumbSize: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_SetMinThumbSize)).as_ptr()), ), CoolSB_GetScrollInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_GetScrollInfo)).as_ptr()), ), CoolSB_SetScrollInfo: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_SetScrollInfo)).as_ptr()), ), CoolSB_SetScrollPos: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_SetScrollPos)).as_ptr()), ), CoolSB_SetScrollRange: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_SetScrollRange)).as_ptr()), ), CoolSB_ShowScrollBar: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_ShowScrollBar)).as_ptr()), ), CoolSB_SetResizingThumb: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_SetResizingThumb)).as_ptr()), ), CoolSB_SetThemeIndex: std::mem::transmute( plugin_context .GetFunc(c_str_macro::c_str!(stringify!(CoolSB_SetThemeIndex)).as_ptr()), ), } }; if pointers.__mergesort.is_some() { loaded_count += 1; } if pointers.AddCustomizableMenu.is_some() { loaded_count += 1; } if pointers.AddExtensionsMainMenu.is_some() { loaded_count += 1; } if pointers.AddMediaItemToTrack.is_some() { loaded_count += 1; } if pointers.AddProjectMarker.is_some() { loaded_count += 1; } if pointers.AddProjectMarker2.is_some() { loaded_count += 1; } if pointers.AddRemoveReaScript.is_some() { loaded_count += 1; } if pointers.AddTakeToMediaItem.is_some() { loaded_count += 1; } if pointers.AddTempoTimeSigMarker.is_some() { loaded_count += 1; } if pointers.adjustZoom.is_some() { loaded_count += 1; } if pointers.AnyTrackSolo.is_some() { loaded_count += 1; } if pointers.APIExists.is_some() { loaded_count += 1; } if pointers.APITest.is_some() { loaded_count += 1; } if pointers.ApplyNudge.is_some() { loaded_count += 1; } if pointers.ArmCommand.is_some() { loaded_count += 1; } if pointers.Audio_Init.is_some() { loaded_count += 1; } if pointers.Audio_IsPreBuffer.is_some() { loaded_count += 1; } if pointers.Audio_IsRunning.is_some() { loaded_count += 1; } if pointers.Audio_Quit.is_some() { loaded_count += 1; } if pointers.Audio_RegHardwareHook.is_some() { loaded_count += 1; } if pointers.AudioAccessorStateChanged.is_some() { loaded_count += 1; } if pointers.AudioAccessorUpdate.is_some() { loaded_count += 1; } if pointers.AudioAccessorValidateState.is_some() { loaded_count += 1; } if pointers.BypassFxAllTracks.is_some() { loaded_count += 1; } if pointers.CalculatePeaks.is_some() { loaded_count += 1; } if pointers.CalculatePeaksFloatSrcPtr.is_some() { loaded_count += 1; } if pointers.ClearAllRecArmed.is_some() { loaded_count += 1; } if pointers.ClearConsole.is_some() { loaded_count += 1; } if pointers.ClearPeakCache.is_some() { loaded_count += 1; } if pointers.ColorFromNative.is_some() { loaded_count += 1; } if pointers.ColorToNative.is_some() { loaded_count += 1; } if pointers.CountActionShortcuts.is_some() { loaded_count += 1; } if pointers.CountAutomationItems.is_some() { loaded_count += 1; } if pointers.CountEnvelopePoints.is_some() { loaded_count += 1; } if pointers.CountEnvelopePointsEx.is_some() { loaded_count += 1; } if pointers.CountMediaItems.is_some() { loaded_count += 1; } if pointers.CountProjectMarkers.is_some() { loaded_count += 1; } if pointers.CountSelectedMediaItems.is_some() { loaded_count += 1; } if pointers.CountSelectedTracks.is_some() { loaded_count += 1; } if pointers.CountSelectedTracks2.is_some() { loaded_count += 1; } if pointers.CountTakeEnvelopes.is_some() { loaded_count += 1; } if pointers.CountTakes.is_some() { loaded_count += 1; } if pointers.CountTCPFXParms.is_some() { loaded_count += 1; } if pointers.CountTempoTimeSigMarkers.is_some() { loaded_count += 1; } if pointers.CountTrackEnvelopes.is_some() { loaded_count += 1; } if pointers.CountTrackMediaItems.is_some() { loaded_count += 1; } if pointers.CountTracks.is_some() { loaded_count += 1; } if pointers.CreateLocalOscHandler.is_some() { loaded_count += 1; } if pointers.CreateMIDIInput.is_some() { loaded_count += 1; } if pointers.CreateMIDIOutput.is_some() { loaded_count += 1; } if pointers.CreateNewMIDIItemInProj.is_some() { loaded_count += 1; } if pointers.CreateTakeAudioAccessor.is_some() { loaded_count += 1; } if pointers.CreateTrackAudioAccessor.is_some() { loaded_count += 1; } if pointers.CreateTrackSend.is_some() { loaded_count += 1; } if pointers.CSurf_FlushUndo.is_some() { loaded_count += 1; } if pointers.CSurf_GetTouchState.is_some() { loaded_count += 1; } if pointers.CSurf_GoEnd.is_some() { loaded_count += 1; } if pointers.CSurf_GoStart.is_some() { loaded_count += 1; } if pointers.CSurf_NumTracks.is_some() { loaded_count += 1; } if pointers.CSurf_OnArrow.is_some() { loaded_count += 1; } if pointers.CSurf_OnFwd.is_some() { loaded_count += 1; } if pointers.CSurf_OnFXChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnInputMonitorChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnInputMonitorChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnMuteChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnMuteChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnOscControlMessage.is_some() { loaded_count += 1; } if pointers.CSurf_OnPanChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnPanChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnPause.is_some() { loaded_count += 1; } if pointers.CSurf_OnPlay.is_some() { loaded_count += 1; } if pointers.CSurf_OnPlayRateChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnRecArmChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnRecArmChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnRecord.is_some() { loaded_count += 1; } if pointers.CSurf_OnRecvPanChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnRecvVolumeChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnRew.is_some() { loaded_count += 1; } if pointers.CSurf_OnRewFwd.is_some() { loaded_count += 1; } if pointers.CSurf_OnScroll.is_some() { loaded_count += 1; } if pointers.CSurf_OnSelectedChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnSendPanChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnSendVolumeChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnSoloChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnSoloChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnStop.is_some() { loaded_count += 1; } if pointers.CSurf_OnTempoChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnTrackSelection.is_some() { loaded_count += 1; } if pointers.CSurf_OnVolumeChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnVolumeChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnWidthChange.is_some() { loaded_count += 1; } if pointers.CSurf_OnWidthChangeEx.is_some() { loaded_count += 1; } if pointers.CSurf_OnZoom.is_some() { loaded_count += 1; } if pointers.CSurf_ResetAllCachedVolPanStates.is_some() { loaded_count += 1; } if pointers.CSurf_ScrubAmt.is_some() { loaded_count += 1; } if pointers.CSurf_SetAutoMode.is_some() { loaded_count += 1; } if pointers.CSurf_SetPlayState.is_some() { loaded_count += 1; } if pointers.CSurf_SetRepeatState.is_some() { loaded_count += 1; } if pointers.CSurf_SetSurfaceMute.is_some() { loaded_count += 1; } if pointers.CSurf_SetSurfacePan.is_some() { loaded_count += 1; } if pointers.CSurf_SetSurfaceRecArm.is_some() { loaded_count += 1; } if pointers.CSurf_SetSurfaceSelected.is_some() { loaded_count += 1; } if pointers.CSurf_SetSurfaceSolo.is_some() { loaded_count += 1; } if pointers.CSurf_SetSurfaceVolume.is_some() { loaded_count += 1; } if pointers.CSurf_SetTrackListChange.is_some() { loaded_count += 1; } if pointers.CSurf_TrackFromID.is_some() { loaded_count += 1; } if pointers.CSurf_TrackToID.is_some() { loaded_count += 1; } if pointers.DB2SLIDER.is_some() { loaded_count += 1; } if pointers.DeleteActionShortcut.is_some() { loaded_count += 1; } if pointers.DeleteEnvelopePointEx.is_some() { loaded_count += 1; } if pointers.DeleteEnvelopePointRange.is_some() { loaded_count += 1; } if pointers.DeleteEnvelopePointRangeEx.is_some() { loaded_count += 1; } if pointers.DeleteExtState.is_some() { loaded_count += 1; } if pointers.DeleteProjectMarker.is_some() { loaded_count += 1; } if pointers.DeleteProjectMarkerByIndex.is_some() { loaded_count += 1; } if pointers.DeleteTakeMarker.is_some() { loaded_count += 1; } if pointers.DeleteTakeStretchMarkers.is_some() { loaded_count += 1; } if pointers.DeleteTempoTimeSigMarker.is_some() { loaded_count += 1; } if pointers.DeleteTrack.is_some() { loaded_count += 1; } if pointers.DeleteTrackMediaItem.is_some() { loaded_count += 1; } if pointers.DestroyAudioAccessor.is_some() { loaded_count += 1; } if pointers.DestroyLocalOscHandler.is_some() { loaded_count += 1; } if pointers.DoActionShortcutDialog.is_some() { loaded_count += 1; } if pointers.Dock_UpdateDockID.is_some() { loaded_count += 1; } if pointers.DockGetPosition.is_some() { loaded_count += 1; } if pointers.DockIsChildOfDock.is_some() { loaded_count += 1; } if pointers.DockWindowActivate.is_some() { loaded_count += 1; } if pointers.DockWindowAdd.is_some() { loaded_count += 1; } if pointers.DockWindowAddEx.is_some() { loaded_count += 1; } if pointers.DockWindowRefresh.is_some() { loaded_count += 1; } if pointers.DockWindowRefreshForHWND.is_some() { loaded_count += 1; } if pointers.DockWindowRemove.is_some() { loaded_count += 1; } if pointers.DuplicateCustomizableMenu.is_some() { loaded_count += 1; } if pointers.EditTempoTimeSigMarker.is_some() { loaded_count += 1; } if pointers.EnsureNotCompletelyOffscreen.is_some() { loaded_count += 1; } if pointers.EnumerateFiles.is_some() { loaded_count += 1; } if pointers.EnumerateSubdirectories.is_some() { loaded_count += 1; } if pointers.EnumPitchShiftModes.is_some() { loaded_count += 1; } if pointers.EnumPitchShiftSubModes.is_some() { loaded_count += 1; } if pointers.EnumProjectMarkers.is_some() { loaded_count += 1; } if pointers.EnumProjectMarkers2.is_some() { loaded_count += 1; } if pointers.EnumProjectMarkers3.is_some() { loaded_count += 1; } if pointers.EnumProjects.is_some() { loaded_count += 1; } if pointers.EnumProjExtState.is_some() { loaded_count += 1; } if pointers.EnumRegionRenderMatrix.is_some() { loaded_count += 1; } if pointers.EnumTrackMIDIProgramNames.is_some() { loaded_count += 1; } if pointers.EnumTrackMIDIProgramNamesEx.is_some() { loaded_count += 1; } if pointers.Envelope_Evaluate.is_some() { loaded_count += 1; } if pointers.Envelope_FormatValue.is_some() { loaded_count += 1; } if pointers.Envelope_GetParentTake.is_some() { loaded_count += 1; } if pointers.Envelope_GetParentTrack.is_some() { loaded_count += 1; } if pointers.Envelope_SortPoints.is_some() { loaded_count += 1; } if pointers.Envelope_SortPointsEx.is_some() { loaded_count += 1; } if pointers.ExecProcess.is_some() { loaded_count += 1; } if pointers.file_exists.is_some() { loaded_count += 1; } if pointers.FindTempoTimeSigMarker.is_some() { loaded_count += 1; } if pointers.format_timestr.is_some() { loaded_count += 1; } if pointers.format_timestr_len.is_some() { loaded_count += 1; } if pointers.format_timestr_pos.is_some() { loaded_count += 1; } if pointers.FreeHeapPtr.is_some() { loaded_count += 1; } if pointers.genGuid.is_some() { loaded_count += 1; } if pointers.get_config_var.is_some() { loaded_count += 1; } if pointers.get_config_var_string.is_some() { loaded_count += 1; } if pointers.get_ini_file.is_some() { loaded_count += 1; } if pointers.get_midi_config_var.is_some() { loaded_count += 1; } if pointers.GetActionShortcutDesc.is_some() { loaded_count += 1; } if pointers.GetActiveTake.is_some() { loaded_count += 1; } if pointers.GetAllProjectPlayStates.is_some() { loaded_count += 1; } if pointers.GetAppVersion.is_some() { loaded_count += 1; } if pointers.GetArmedCommand.is_some() { loaded_count += 1; } if pointers.GetAudioAccessorEndTime.is_some() { loaded_count += 1; } if pointers.GetAudioAccessorHash.is_some() { loaded_count += 1; } if pointers.GetAudioAccessorSamples.is_some() { loaded_count += 1; } if pointers.GetAudioAccessorStartTime.is_some() { loaded_count += 1; } if pointers.GetAudioDeviceInfo.is_some() { loaded_count += 1; } if pointers.GetColorTheme.is_some() { loaded_count += 1; } if pointers.GetColorThemeStruct.is_some() { loaded_count += 1; } if pointers.GetConfigWantsDock.is_some() { loaded_count += 1; } if pointers.GetContextMenu.is_some() { loaded_count += 1; } if pointers.GetCurrentProjectInLoadSave.is_some() { loaded_count += 1; } if pointers.GetCursorContext.is_some() { loaded_count += 1; } if pointers.GetCursorContext2.is_some() { loaded_count += 1; } if pointers.GetCursorPosition.is_some() { loaded_count += 1; } if pointers.GetCursorPositionEx.is_some() { loaded_count += 1; } if pointers.GetDisplayedMediaItemColor.is_some() { loaded_count += 1; } if pointers.GetDisplayedMediaItemColor2.is_some() { loaded_count += 1; } if pointers.GetEnvelopeInfo_Value.is_some() { loaded_count += 1; } if pointers.GetEnvelopeName.is_some() { loaded_count += 1; } if pointers.GetEnvelopePoint.is_some() { loaded_count += 1; } if pointers.GetEnvelopePointByTime.is_some() { loaded_count += 1; } if pointers.GetEnvelopePointByTimeEx.is_some() { loaded_count += 1; } if pointers.GetEnvelopePointEx.is_some() { loaded_count += 1; } if pointers.GetEnvelopeScalingMode.is_some() { loaded_count += 1; } if pointers.GetEnvelopeStateChunk.is_some() { loaded_count += 1; } if pointers.GetExePath.is_some() { loaded_count += 1; } if pointers.GetExtState.is_some() { loaded_count += 1; } if pointers.GetFocusedFX.is_some() { loaded_count += 1; } if pointers.GetFocusedFX2.is_some() { loaded_count += 1; } if pointers.GetFreeDiskSpaceForRecordPath.is_some() { loaded_count += 1; } if pointers.GetFXEnvelope.is_some() { loaded_count += 1; } if pointers.GetGlobalAutomationOverride.is_some() { loaded_count += 1; } if pointers.GetHZoomLevel.is_some() { loaded_count += 1; } if pointers.GetIconThemePointer.is_some() { loaded_count += 1; } if pointers.GetIconThemePointerForDPI.is_some() { loaded_count += 1; } if pointers.GetIconThemeStruct.is_some() { loaded_count += 1; } if pointers.GetInputChannelName.is_some() { loaded_count += 1; } if pointers.GetInputOutputLatency.is_some() { loaded_count += 1; } if pointers.GetItemEditingTime2.is_some() { loaded_count += 1; } if pointers.GetItemFromPoint.is_some() { loaded_count += 1; } if pointers.GetItemProjectContext.is_some() { loaded_count += 1; } if pointers.GetItemStateChunk.is_some() { loaded_count += 1; } if pointers.GetLastColorThemeFile.is_some() { loaded_count += 1; } if pointers.GetLastMarkerAndCurRegion.is_some() { loaded_count += 1; } if pointers.GetLastTouchedFX.is_some() { loaded_count += 1; } if pointers.GetLastTouchedTrack.is_some() { loaded_count += 1; } if pointers.GetMainHwnd.is_some() { loaded_count += 1; } if pointers.GetMasterMuteSoloFlags.is_some() { loaded_count += 1; } if pointers.GetMasterTrack.is_some() { loaded_count += 1; } if pointers.GetMasterTrackVisibility.is_some() { loaded_count += 1; } if pointers.GetMaxMidiInputs.is_some() { loaded_count += 1; } if pointers.GetMaxMidiOutputs.is_some() { loaded_count += 1; } if pointers.GetMediaFileMetadata.is_some() { loaded_count += 1; } if pointers.GetMediaItem.is_some() { loaded_count += 1; } if pointers.GetMediaItem_Track.is_some() { loaded_count += 1; } if pointers.GetMediaItemInfo_Value.is_some() { loaded_count += 1; } if pointers.GetMediaItemNumTakes.is_some() { loaded_count += 1; } if pointers.GetMediaItemTake.is_some() { loaded_count += 1; } if pointers.GetMediaItemTake_Item.is_some() { loaded_count += 1; } if pointers.GetMediaItemTake_Peaks.is_some() { loaded_count += 1; } if pointers.GetMediaItemTake_Source.is_some() { loaded_count += 1; } if pointers.GetMediaItemTake_Track.is_some() { loaded_count += 1; } if pointers.GetMediaItemTakeByGUID.is_some() { loaded_count += 1; } if pointers.GetMediaItemTakeInfo_Value.is_some() { loaded_count += 1; } if pointers.GetMediaItemTrack.is_some() { loaded_count += 1; } if pointers.GetMediaSourceFileName.is_some() { loaded_count += 1; } if pointers.GetMediaSourceLength.is_some() { loaded_count += 1; } if pointers.GetMediaSourceNumChannels.is_some() { loaded_count += 1; } if pointers.GetMediaSourceParent.is_some() { loaded_count += 1; } if pointers.GetMediaSourceSampleRate.is_some() { loaded_count += 1; } if pointers.GetMediaSourceType.is_some() { loaded_count += 1; } if pointers.GetMediaTrackInfo_Value.is_some() { loaded_count += 1; } if pointers.GetMIDIInputName.is_some() { loaded_count += 1; } if pointers.GetMIDIOutputName.is_some() { loaded_count += 1; } if pointers.GetMixerScroll.is_some() { loaded_count += 1; } if pointers.GetMouseModifier.is_some() { loaded_count += 1; } if pointers.GetMousePosition.is_some() { loaded_count += 1; } if pointers.GetNumAudioInputs.is_some() { loaded_count += 1; } if pointers.GetNumAudioOutputs.is_some() { loaded_count += 1; } if pointers.GetNumMIDIInputs.is_some() { loaded_count += 1; } if pointers.GetNumMIDIOutputs.is_some() { loaded_count += 1; } if pointers.GetNumTakeMarkers.is_some() { loaded_count += 1; } if pointers.GetNumTracks.is_some() { loaded_count += 1; } if pointers.GetOS.is_some() { loaded_count += 1; } if pointers.GetOutputChannelName.is_some() { loaded_count += 1; } if pointers.GetOutputLatency.is_some() { loaded_count += 1; } if pointers.GetParentTrack.is_some() { loaded_count += 1; } if pointers.GetPeakFileName.is_some() { loaded_count += 1; } if pointers.GetPeakFileNameEx.is_some() { loaded_count += 1; } if pointers.GetPeakFileNameEx2.is_some() { loaded_count += 1; } if pointers.GetPeaksBitmap.is_some() { loaded_count += 1; } if pointers.GetPlayPosition.is_some() { loaded_count += 1; } if pointers.GetPlayPosition2.is_some() { loaded_count += 1; } if pointers.GetPlayPosition2Ex.is_some() { loaded_count += 1; } if pointers.GetPlayPositionEx.is_some() { loaded_count += 1; } if pointers.GetPlayState.is_some() { loaded_count += 1; } if pointers.GetPlayStateEx.is_some() { loaded_count += 1; } if pointers.GetPreferredDiskReadMode.is_some() { loaded_count += 1; } if pointers.GetPreferredDiskReadModePeak.is_some() { loaded_count += 1; } if pointers.GetPreferredDiskWriteMode.is_some() { loaded_count += 1; } if pointers.GetProjectLength.is_some() { loaded_count += 1; } if pointers.GetProjectName.is_some() { loaded_count += 1; } if pointers.GetProjectPath.is_some() { loaded_count += 1; } if pointers.GetProjectPathEx.is_some() { loaded_count += 1; } if pointers.GetProjectStateChangeCount.is_some() { loaded_count += 1; } if pointers.GetProjectTimeOffset.is_some() { loaded_count += 1; } if pointers.GetProjectTimeSignature.is_some() { loaded_count += 1; } if pointers.GetProjectTimeSignature2.is_some() { loaded_count += 1; } if pointers.GetProjExtState.is_some() { loaded_count += 1; } if pointers.GetResourcePath.is_some() { loaded_count += 1; } if pointers.GetSelectedEnvelope.is_some() { loaded_count += 1; } if pointers.GetSelectedMediaItem.is_some() { loaded_count += 1; } if pointers.GetSelectedTrack.is_some() { loaded_count += 1; } if pointers.GetSelectedTrack2.is_some() { loaded_count += 1; } if pointers.GetSelectedTrackEnvelope.is_some() { loaded_count += 1; } if pointers.GetSet_ArrangeView2.is_some() { loaded_count += 1; } if pointers.GetSet_LoopTimeRange.is_some() { loaded_count += 1; } if pointers.GetSet_LoopTimeRange2.is_some() { loaded_count += 1; } if pointers.GetSetAutomationItemInfo.is_some() { loaded_count += 1; } if pointers.GetSetAutomationItemInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetEnvelopeInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetEnvelopeState.is_some() { loaded_count += 1; } if pointers.GetSetEnvelopeState2.is_some() { loaded_count += 1; } if pointers.GetSetItemState.is_some() { loaded_count += 1; } if pointers.GetSetItemState2.is_some() { loaded_count += 1; } if pointers.GetSetMediaItemInfo.is_some() { loaded_count += 1; } if pointers.GetSetMediaItemInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetMediaItemTakeInfo.is_some() { loaded_count += 1; } if pointers.GetSetMediaItemTakeInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetMediaTrackInfo.is_some() { loaded_count += 1; } if pointers.GetSetMediaTrackInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetObjectState.is_some() { loaded_count += 1; } if pointers.GetSetObjectState2.is_some() { loaded_count += 1; } if pointers.GetSetProjectAuthor.is_some() { loaded_count += 1; } if pointers.GetSetProjectGrid.is_some() { loaded_count += 1; } if pointers.GetSetProjectInfo.is_some() { loaded_count += 1; } if pointers.GetSetProjectInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetProjectNotes.is_some() { loaded_count += 1; } if pointers.GetSetRepeat.is_some() { loaded_count += 1; } if pointers.GetSetRepeatEx.is_some() { loaded_count += 1; } if pointers.GetSetTrackGroupMembership.is_some() { loaded_count += 1; } if pointers.GetSetTrackGroupMembershipHigh.is_some() { loaded_count += 1; } if pointers.GetSetTrackMIDISupportFile.is_some() { loaded_count += 1; } if pointers.GetSetTrackSendInfo.is_some() { loaded_count += 1; } if pointers.GetSetTrackSendInfo_String.is_some() { loaded_count += 1; } if pointers.GetSetTrackState.is_some() { loaded_count += 1; } if pointers.GetSetTrackState2.is_some() { loaded_count += 1; } if pointers.GetSubProjectFromSource.is_some() { loaded_count += 1; } if pointers.GetTake.is_some() { loaded_count += 1; } if pointers.GetTakeEnvelope.is_some() { loaded_count += 1; } if pointers.GetTakeEnvelopeByName.is_some() { loaded_count += 1; } if pointers.GetTakeMarker.is_some() { loaded_count += 1; } if pointers.GetTakeName.is_some() { loaded_count += 1; } if pointers.GetTakeNumStretchMarkers.is_some() { loaded_count += 1; } if pointers.GetTakeStretchMarker.is_some() { loaded_count += 1; } if pointers.GetTakeStretchMarkerSlope.is_some() { loaded_count += 1; } if pointers.GetTCPFXParm.is_some() { loaded_count += 1; } if pointers.GetTempoMatchPlayRate.is_some() { loaded_count += 1; } if pointers.GetTempoTimeSigMarker.is_some() { loaded_count += 1; } if pointers.GetThemeColor.is_some() { loaded_count += 1; } if pointers.GetThingFromPoint.is_some() { loaded_count += 1; } if pointers.GetToggleCommandState.is_some() { loaded_count += 1; } if pointers.GetToggleCommandState2.is_some() { loaded_count += 1; } if pointers.GetToggleCommandStateEx.is_some() { loaded_count += 1; } if pointers.GetToggleCommandStateThroughHooks.is_some() { loaded_count += 1; } if pointers.GetTooltipWindow.is_some() { loaded_count += 1; } if pointers.GetTrack.is_some() { loaded_count += 1; } if pointers.GetTrackAutomationMode.is_some() { loaded_count += 1; } if pointers.GetTrackColor.is_some() { loaded_count += 1; } if pointers.GetTrackDepth.is_some() { loaded_count += 1; } if pointers.GetTrackEnvelope.is_some() { loaded_count += 1; } if pointers.GetTrackEnvelopeByChunkName.is_some() { loaded_count += 1; } if pointers.GetTrackEnvelopeByName.is_some() { loaded_count += 1; } if pointers.GetTrackFromPoint.is_some() { loaded_count += 1; } if pointers.GetTrackGUID.is_some() { loaded_count += 1; } if pointers.GetTrackInfo.is_some() { loaded_count += 1; } if pointers.GetTrackMediaItem.is_some() { loaded_count += 1; } if pointers.GetTrackMIDILyrics.is_some() { loaded_count += 1; } if pointers.GetTrackMIDINoteName.is_some() { loaded_count += 1; } if pointers.GetTrackMIDINoteNameEx.is_some() { loaded_count += 1; } if pointers.GetTrackMIDINoteRange.is_some() { loaded_count += 1; } if pointers.GetTrackName.is_some() { loaded_count += 1; } if pointers.GetTrackNumMediaItems.is_some() { loaded_count += 1; } if pointers.GetTrackNumSends.is_some() { loaded_count += 1; } if pointers.GetTrackReceiveName.is_some() { loaded_count += 1; } if pointers.GetTrackReceiveUIMute.is_some() { loaded_count += 1; } if pointers.GetTrackReceiveUIVolPan.is_some() { loaded_count += 1; } if pointers.GetTrackSendInfo_Value.is_some() { loaded_count += 1; } if pointers.GetTrackSendName.is_some() { loaded_count += 1; } if pointers.GetTrackSendUIMute.is_some() { loaded_count += 1; } if pointers.GetTrackSendUIVolPan.is_some() { loaded_count += 1; } if pointers.GetTrackState.is_some() { loaded_count += 1; } if pointers.GetTrackStateChunk.is_some() { loaded_count += 1; } if pointers.GetTrackUIMute.is_some() { loaded_count += 1; } if pointers.GetTrackUIPan.is_some() { loaded_count += 1; } if pointers.GetTrackUIVolPan.is_some() { loaded_count += 1; } if pointers.GetUnderrunTime.is_some() { loaded_count += 1; } if pointers.GetUserFileNameForRead.is_some() { loaded_count += 1; } if pointers.GetUserInputs.is_some() { loaded_count += 1; } if pointers.GoToMarker.is_some() { loaded_count += 1; } if pointers.GoToRegion.is_some() { loaded_count += 1; } if pointers.GR_SelectColor.is_some() { loaded_count += 1; } if pointers.GSC_mainwnd.is_some() { loaded_count += 1; } if pointers.guidToString.is_some() { loaded_count += 1; } if pointers.HasExtState.is_some() { loaded_count += 1; } if pointers.HasTrackMIDIPrograms.is_some() { loaded_count += 1; } if pointers.HasTrackMIDIProgramsEx.is_some() { loaded_count += 1; } if pointers.Help_Set.is_some() { loaded_count += 1; } if pointers.HiresPeaksFromSource.is_some() { loaded_count += 1; } if pointers.image_resolve_fn.is_some() { loaded_count += 1; } if pointers.InsertAutomationItem.is_some() { loaded_count += 1; } if pointers.InsertEnvelopePoint.is_some() { loaded_count += 1; } if pointers.InsertEnvelopePointEx.is_some() { loaded_count += 1; } if pointers.InsertMedia.is_some() { loaded_count += 1; } if pointers.InsertMediaSection.is_some() { loaded_count += 1; } if pointers.InsertTrackAtIndex.is_some() { loaded_count += 1; } if pointers.IsInRealTimeAudio.is_some() { loaded_count += 1; } if pointers.IsItemTakeActiveForPlayback.is_some() { loaded_count += 1; } if pointers.IsMediaExtension.is_some() { loaded_count += 1; } if pointers.IsMediaItemSelected.is_some() { loaded_count += 1; } if pointers.IsProjectDirty.is_some() { loaded_count += 1; } if pointers.IsREAPER.is_some() { loaded_count += 1; } if pointers.IsTrackSelected.is_some() { loaded_count += 1; } if pointers.IsTrackVisible.is_some() { loaded_count += 1; } if pointers.joystick_create.is_some() { loaded_count += 1; } if pointers.joystick_destroy.is_some() { loaded_count += 1; } if pointers.joystick_enum.is_some() { loaded_count += 1; } if pointers.joystick_getaxis.is_some() { loaded_count += 1; } if pointers.joystick_getbuttonmask.is_some() { loaded_count += 1; } if pointers.joystick_getinfo.is_some() { loaded_count += 1; } if pointers.joystick_getpov.is_some() { loaded_count += 1; } if pointers.joystick_update.is_some() { loaded_count += 1; } if pointers.kbd_enumerateActions.is_some() { loaded_count += 1; } if pointers.kbd_formatKeyName.is_some() { loaded_count += 1; } if pointers.kbd_getCommandName.is_some() { loaded_count += 1; } if pointers.kbd_getTextFromCmd.is_some() { loaded_count += 1; } if pointers.KBD_OnMainActionEx.is_some() { loaded_count += 1; } if pointers.kbd_OnMidiEvent.is_some() { loaded_count += 1; } if pointers.kbd_OnMidiList.is_some() { loaded_count += 1; } if pointers.kbd_ProcessActionsMenu.is_some() { loaded_count += 1; } if pointers.kbd_processMidiEventActionEx.is_some() { loaded_count += 1; } if pointers.kbd_reprocessMenu.is_some() { loaded_count += 1; } if pointers.kbd_RunCommandThroughHooks.is_some() { loaded_count += 1; } if pointers.kbd_translateAccelerator.is_some() { loaded_count += 1; } if pointers.kbd_translateMouse.is_some() { loaded_count += 1; } if pointers.LICE__Destroy.is_some() { loaded_count += 1; } if pointers.LICE__DestroyFont.is_some() { loaded_count += 1; } if pointers.LICE__DrawText.is_some() { loaded_count += 1; } if pointers.LICE__GetBits.is_some() { loaded_count += 1; } if pointers.LICE__GetDC.is_some() { loaded_count += 1; } if pointers.LICE__GetHeight.is_some() { loaded_count += 1; } if pointers.LICE__GetRowSpan.is_some() { loaded_count += 1; } if pointers.LICE__GetWidth.is_some() { loaded_count += 1; } if pointers.LICE__IsFlipped.is_some() { loaded_count += 1; } if pointers.LICE__resize.is_some() { loaded_count += 1; } if pointers.LICE__SetBkColor.is_some() { loaded_count += 1; } if pointers.LICE__SetFromHFont.is_some() { loaded_count += 1; } if pointers.LICE__SetTextColor.is_some() { loaded_count += 1; } if pointers.LICE__SetTextCombineMode.is_some() { loaded_count += 1; } if pointers.LICE_Arc.is_some() { loaded_count += 1; } if pointers.LICE_Blit.is_some() { loaded_count += 1; } if pointers.LICE_Blur.is_some() { loaded_count += 1; } if pointers.LICE_BorderedRect.is_some() { loaded_count += 1; } if pointers.LICE_Circle.is_some() { loaded_count += 1; } if pointers.LICE_Clear.is_some() { loaded_count += 1; } if pointers.LICE_ClearRect.is_some() { loaded_count += 1; } if pointers.LICE_ClipLine.is_some() { loaded_count += 1; } if pointers.LICE_Copy.is_some() { loaded_count += 1; } if pointers.LICE_CreateBitmap.is_some() { loaded_count += 1; } if pointers.LICE_CreateFont.is_some() { loaded_count += 1; } if pointers.LICE_DrawCBezier.is_some() { loaded_count += 1; } if pointers.LICE_DrawChar.is_some() { loaded_count += 1; } if pointers.LICE_DrawGlyph.is_some() { loaded_count += 1; } if pointers.LICE_DrawRect.is_some() { loaded_count += 1; } if pointers.LICE_DrawText.is_some() { loaded_count += 1; } if pointers.LICE_FillCBezier.is_some() { loaded_count += 1; } if pointers.LICE_FillCircle.is_some() { loaded_count += 1; } if pointers.LICE_FillConvexPolygon.is_some() { loaded_count += 1; } if pointers.LICE_FillRect.is_some() { loaded_count += 1; } if pointers.LICE_FillTrapezoid.is_some() { loaded_count += 1; } if pointers.LICE_FillTriangle.is_some() { loaded_count += 1; } if pointers.LICE_GetPixel.is_some() { loaded_count += 1; } if pointers.LICE_GradRect.is_some() { loaded_count += 1; } if pointers.LICE_Line.is_some() { loaded_count += 1; } if pointers.LICE_LineInt.is_some() { loaded_count += 1; } if pointers.LICE_LoadPNG.is_some() { loaded_count += 1; } if pointers.LICE_LoadPNGFromResource.is_some() { loaded_count += 1; } if pointers.LICE_MeasureText.is_some() { loaded_count += 1; } if pointers.LICE_MultiplyAddRect.is_some() { loaded_count += 1; } if pointers.LICE_PutPixel.is_some() { loaded_count += 1; } if pointers.LICE_RotatedBlit.is_some() { loaded_count += 1; } if pointers.LICE_RoundRect.is_some() { loaded_count += 1; } if pointers.LICE_ScaledBlit.is_some() { loaded_count += 1; } if pointers.LICE_SimpleFill.is_some() { loaded_count += 1; } if pointers.LocalizeString.is_some() { loaded_count += 1; } if pointers.Loop_OnArrow.is_some() { loaded_count += 1; } if pointers.Main_OnCommand.is_some() { loaded_count += 1; } if pointers.Main_OnCommandEx.is_some() { loaded_count += 1; } if pointers.Main_openProject.is_some() { loaded_count += 1; } if pointers.Main_SaveProject.is_some() { loaded_count += 1; } if pointers.Main_UpdateLoopInfo.is_some() { loaded_count += 1; } if pointers.MarkProjectDirty.is_some() { loaded_count += 1; } if pointers.MarkTrackItemsDirty.is_some() { loaded_count += 1; } if pointers.Master_GetPlayRate.is_some() { loaded_count += 1; } if pointers.Master_GetPlayRateAtTime.is_some() { loaded_count += 1; } if pointers.Master_GetTempo.is_some() { loaded_count += 1; } if pointers.Master_NormalizePlayRate.is_some() { loaded_count += 1; } if pointers.Master_NormalizeTempo.is_some() { loaded_count += 1; } if pointers.MB.is_some() { loaded_count += 1; } if pointers.MediaItemDescendsFromTrack.is_some() { loaded_count += 1; } if pointers.MIDI_CountEvts.is_some() { loaded_count += 1; } if pointers.MIDI_DeleteCC.is_some() { loaded_count += 1; } if pointers.MIDI_DeleteEvt.is_some() { loaded_count += 1; } if pointers.MIDI_DeleteNote.is_some() { loaded_count += 1; } if pointers.MIDI_DeleteTextSysexEvt.is_some() { loaded_count += 1; } if pointers.MIDI_DisableSort.is_some() { loaded_count += 1; } if pointers.MIDI_EnumSelCC.is_some() { loaded_count += 1; } if pointers.MIDI_EnumSelEvts.is_some() { loaded_count += 1; } if pointers.MIDI_EnumSelNotes.is_some() { loaded_count += 1; } if pointers.MIDI_EnumSelTextSysexEvts.is_some() { loaded_count += 1; } if pointers.MIDI_eventlist_Create.is_some() { loaded_count += 1; } if pointers.MIDI_eventlist_Destroy.is_some() { loaded_count += 1; } if pointers.MIDI_GetAllEvts.is_some() { loaded_count += 1; } if pointers.MIDI_GetCC.is_some() { loaded_count += 1; } if pointers.MIDI_GetCCShape.is_some() { loaded_count += 1; } if pointers.MIDI_GetEvt.is_some() { loaded_count += 1; } if pointers.MIDI_GetGrid.is_some() { loaded_count += 1; } if pointers.MIDI_GetHash.is_some() { loaded_count += 1; } if pointers.MIDI_GetNote.is_some() { loaded_count += 1; } if pointers.MIDI_GetPPQPos_EndOfMeasure.is_some() { loaded_count += 1; } if pointers.MIDI_GetPPQPos_StartOfMeasure.is_some() { loaded_count += 1; } if pointers.MIDI_GetPPQPosFromProjQN.is_some() { loaded_count += 1; } if pointers.MIDI_GetPPQPosFromProjTime.is_some() { loaded_count += 1; } if pointers.MIDI_GetProjQNFromPPQPos.is_some() { loaded_count += 1; } if pointers.MIDI_GetProjTimeFromPPQPos.is_some() { loaded_count += 1; } if pointers.MIDI_GetScale.is_some() { loaded_count += 1; } if pointers.MIDI_GetTextSysexEvt.is_some() { loaded_count += 1; } if pointers.MIDI_GetTrackHash.is_some() { loaded_count += 1; } if pointers.MIDI_InsertCC.is_some() { loaded_count += 1; } if pointers.MIDI_InsertEvt.is_some() { loaded_count += 1; } if pointers.MIDI_InsertNote.is_some() { loaded_count += 1; } if pointers.MIDI_InsertTextSysexEvt.is_some() { loaded_count += 1; } if pointers.midi_reinit.is_some() { loaded_count += 1; } if pointers.MIDI_SelectAll.is_some() { loaded_count += 1; } if pointers.MIDI_SetAllEvts.is_some() { loaded_count += 1; } if pointers.MIDI_SetCC.is_some() { loaded_count += 1; } if pointers.MIDI_SetCCShape.is_some() { loaded_count += 1; } if pointers.MIDI_SetEvt.is_some() { loaded_count += 1; } if pointers.MIDI_SetItemExtents.is_some() { loaded_count += 1; } if pointers.MIDI_SetNote.is_some() { loaded_count += 1; } if pointers.MIDI_SetTextSysexEvt.is_some() { loaded_count += 1; } if pointers.MIDI_Sort.is_some() { loaded_count += 1; } if pointers.MIDIEditor_EnumTakes.is_some() { loaded_count += 1; } if pointers.MIDIEditor_GetActive.is_some() { loaded_count += 1; } if pointers.MIDIEditor_GetMode.is_some() { loaded_count += 1; } if pointers.MIDIEditor_GetSetting_int.is_some() { loaded_count += 1; } if pointers.MIDIEditor_GetSetting_str.is_some() { loaded_count += 1; } if pointers.MIDIEditor_GetTake.is_some() { loaded_count += 1; } if pointers.MIDIEditor_LastFocused_OnCommand.is_some() { loaded_count += 1; } if pointers.MIDIEditor_OnCommand.is_some() { loaded_count += 1; } if pointers.MIDIEditor_SetSetting_int.is_some() { loaded_count += 1; } if pointers.mkpanstr.is_some() { loaded_count += 1; } if pointers.mkvolpanstr.is_some() { loaded_count += 1; } if pointers.mkvolstr.is_some() { loaded_count += 1; } if pointers.MoveEditCursor.is_some() { loaded_count += 1; } if pointers.MoveMediaItemToTrack.is_some() { loaded_count += 1; } if pointers.MuteAllTracks.is_some() { loaded_count += 1; } if pointers.my_getViewport.is_some() { loaded_count += 1; } if pointers.NamedCommandLookup.is_some() { loaded_count += 1; } if pointers.OnPauseButton.is_some() { loaded_count += 1; } if pointers.OnPauseButtonEx.is_some() { loaded_count += 1; } if pointers.OnPlayButton.is_some() { loaded_count += 1; } if pointers.OnPlayButtonEx.is_some() { loaded_count += 1; } if pointers.OnStopButton.is_some() { loaded_count += 1; } if pointers.OnStopButtonEx.is_some() { loaded_count += 1; } if pointers.OpenColorThemeFile.is_some() { loaded_count += 1; } if pointers.OpenMediaExplorer.is_some() { loaded_count += 1; } if pointers.OscLocalMessageToHost.is_some() { loaded_count += 1; } if pointers.parse_timestr.is_some() { loaded_count += 1; } if pointers.parse_timestr_len.is_some() { loaded_count += 1; } if pointers.parse_timestr_pos.is_some() { loaded_count += 1; } if pointers.parsepanstr.is_some() { loaded_count += 1; } if pointers.PCM_Sink_Create.is_some() { loaded_count += 1; } if pointers.PCM_Sink_CreateEx.is_some() { loaded_count += 1; } if pointers.PCM_Sink_CreateMIDIFile.is_some() { loaded_count += 1; } if pointers.PCM_Sink_CreateMIDIFileEx.is_some() { loaded_count += 1; } if pointers.PCM_Sink_Enum.is_some() { loaded_count += 1; } if pointers.PCM_Sink_GetExtension.is_some() { loaded_count += 1; } if pointers.PCM_Sink_ShowConfig.is_some() { loaded_count += 1; } if pointers.PCM_Source_BuildPeaks.is_some() { loaded_count += 1; } if pointers.PCM_Source_CreateFromFile.is_some() { loaded_count += 1; } if pointers.PCM_Source_CreateFromFileEx.is_some() { loaded_count += 1; } if pointers.PCM_Source_CreateFromSimple.is_some() { loaded_count += 1; } if pointers.PCM_Source_CreateFromType.is_some() { loaded_count += 1; } if pointers.PCM_Source_Destroy.is_some() { loaded_count += 1; } if pointers.PCM_Source_GetPeaks.is_some() { loaded_count += 1; } if pointers.PCM_Source_GetSectionInfo.is_some() { loaded_count += 1; } if pointers.PeakBuild_Create.is_some() { loaded_count += 1; } if pointers.PeakBuild_CreateEx.is_some() { loaded_count += 1; } if pointers.PeakGet_Create.is_some() { loaded_count += 1; } if pointers.PitchShiftSubModeMenu.is_some() { loaded_count += 1; } if pointers.PlayPreview.is_some() { loaded_count += 1; } if pointers.PlayPreviewEx.is_some() { loaded_count += 1; } if pointers.PlayTrackPreview.is_some() { loaded_count += 1; } if pointers.PlayTrackPreview2.is_some() { loaded_count += 1; } if pointers.PlayTrackPreview2Ex.is_some() { loaded_count += 1; } if pointers.plugin_getapi.is_some() { loaded_count += 1; } if pointers.plugin_getFilterList.is_some() { loaded_count += 1; } if pointers.plugin_getImportableProjectFilterList.is_some() { loaded_count += 1; } if pointers.plugin_register.is_some() { loaded_count += 1; } if pointers.PluginWantsAlwaysRunFx.is_some() { loaded_count += 1; } if pointers.PreventUIRefresh.is_some() { loaded_count += 1; } if pointers.projectconfig_var_addr.is_some() { loaded_count += 1; } if pointers.projectconfig_var_getoffs.is_some() { loaded_count += 1; } if pointers.PromptForAction.is_some() { loaded_count += 1; } if pointers.realloc_cmd_ptr.is_some() { loaded_count += 1; } if pointers.ReaperGetPitchShiftAPI.is_some() { loaded_count += 1; } if pointers.ReaScriptError.is_some() { loaded_count += 1; } if pointers.RecursiveCreateDirectory.is_some() { loaded_count += 1; } if pointers.reduce_open_files.is_some() { loaded_count += 1; } if pointers.RefreshToolbar.is_some() { loaded_count += 1; } if pointers.RefreshToolbar2.is_some() { loaded_count += 1; } if pointers.relative_fn.is_some() { loaded_count += 1; } if pointers.RemoveTrackSend.is_some() { loaded_count += 1; } if pointers.RenderFileSection.is_some() { loaded_count += 1; } if pointers.ReorderSelectedTracks.is_some() { loaded_count += 1; } if pointers.Resample_EnumModes.is_some() { loaded_count += 1; } if pointers.Resampler_Create.is_some() { loaded_count += 1; } if pointers.resolve_fn.is_some() { loaded_count += 1; } if pointers.resolve_fn2.is_some() { loaded_count += 1; } if pointers.ResolveRenderPattern.is_some() { loaded_count += 1; } if pointers.ReverseNamedCommandLookup.is_some() { loaded_count += 1; } if pointers.ScaleFromEnvelopeMode.is_some() { loaded_count += 1; } if pointers.ScaleToEnvelopeMode.is_some() { loaded_count += 1; } if pointers.screenset_register.is_some() { loaded_count += 1; } if pointers.screenset_registerNew.is_some() { loaded_count += 1; } if pointers.screenset_unregister.is_some() { loaded_count += 1; } if pointers.screenset_unregisterByParam.is_some() { loaded_count += 1; } if pointers.screenset_updateLastFocus.is_some() { loaded_count += 1; } if pointers.SectionFromUniqueID.is_some() { loaded_count += 1; } if pointers.SelectAllMediaItems.is_some() { loaded_count += 1; } if pointers.SelectProjectInstance.is_some() { loaded_count += 1; } if pointers.SendLocalOscMessage.is_some() { loaded_count += 1; } if pointers.SetActiveTake.is_some() { loaded_count += 1; } if pointers.SetAutomationMode.is_some() { loaded_count += 1; } if pointers.SetCurrentBPM.is_some() { loaded_count += 1; } if pointers.SetCursorContext.is_some() { loaded_count += 1; } if pointers.SetEditCurPos.is_some() { loaded_count += 1; } if pointers.SetEditCurPos2.is_some() { loaded_count += 1; } if pointers.SetEnvelopePoint.is_some() { loaded_count += 1; } if pointers.SetEnvelopePointEx.is_some() { loaded_count += 1; } if pointers.SetEnvelopeStateChunk.is_some() { loaded_count += 1; } if pointers.SetExtState.is_some() { loaded_count += 1; } if pointers.SetGlobalAutomationOverride.is_some() { loaded_count += 1; } if pointers.SetItemStateChunk.is_some() { loaded_count += 1; } if pointers.SetMasterTrackVisibility.is_some() { loaded_count += 1; } if pointers.SetMediaItemInfo_Value.is_some() { loaded_count += 1; } if pointers.SetMediaItemLength.is_some() { loaded_count += 1; } if pointers.SetMediaItemPosition.is_some() { loaded_count += 1; } if pointers.SetMediaItemSelected.is_some() { loaded_count += 1; } if pointers.SetMediaItemTake_Source.is_some() { loaded_count += 1; } if pointers.SetMediaItemTakeInfo_Value.is_some() { loaded_count += 1; } if pointers.SetMediaTrackInfo_Value.is_some() { loaded_count += 1; } if pointers.SetMIDIEditorGrid.is_some() { loaded_count += 1; } if pointers.SetMixerScroll.is_some() { loaded_count += 1; } if pointers.SetMouseModifier.is_some() { loaded_count += 1; } if pointers.SetOnlyTrackSelected.is_some() { loaded_count += 1; } if pointers.SetProjectGrid.is_some() { loaded_count += 1; } if pointers.SetProjectMarker.is_some() { loaded_count += 1; } if pointers.SetProjectMarker2.is_some() { loaded_count += 1; } if pointers.SetProjectMarker3.is_some() { loaded_count += 1; } if pointers.SetProjectMarker4.is_some() { loaded_count += 1; } if pointers.SetProjectMarkerByIndex.is_some() { loaded_count += 1; } if pointers.SetProjectMarkerByIndex2.is_some() { loaded_count += 1; } if pointers.SetProjExtState.is_some() { loaded_count += 1; } if pointers.SetRegionRenderMatrix.is_some() { loaded_count += 1; } if pointers.SetRenderLastError.is_some() { loaded_count += 1; } if pointers.SetTakeMarker.is_some() { loaded_count += 1; } if pointers.SetTakeStretchMarker.is_some() { loaded_count += 1; } if pointers.SetTakeStretchMarkerSlope.is_some() { loaded_count += 1; } if pointers.SetTempoTimeSigMarker.is_some() { loaded_count += 1; } if pointers.SetThemeColor.is_some() { loaded_count += 1; } if pointers.SetToggleCommandState.is_some() { loaded_count += 1; } if pointers.SetTrackAutomationMode.is_some() { loaded_count += 1; } if pointers.SetTrackColor.is_some() { loaded_count += 1; } if pointers.SetTrackMIDILyrics.is_some() { loaded_count += 1; } if pointers.SetTrackMIDINoteName.is_some() { loaded_count += 1; } if pointers.SetTrackMIDINoteNameEx.is_some() { loaded_count += 1; } if pointers.SetTrackSelected.is_some() { loaded_count += 1; } if pointers.SetTrackSendInfo_Value.is_some() { loaded_count += 1; } if pointers.SetTrackSendUIPan.is_some() { loaded_count += 1; } if pointers.SetTrackSendUIVol.is_some() { loaded_count += 1; } if pointers.SetTrackStateChunk.is_some() { loaded_count += 1; } if pointers.ShowActionList.is_some() { loaded_count += 1; } if pointers.ShowConsoleMsg.is_some() { loaded_count += 1; } if pointers.ShowMessageBox.is_some() { loaded_count += 1; } if pointers.ShowPopupMenu.is_some() { loaded_count += 1; } if pointers.SLIDER2DB.is_some() { loaded_count += 1; } if pointers.SnapToGrid.is_some() { loaded_count += 1; } if pointers.SoloAllTracks.is_some() { loaded_count += 1; } if pointers.Splash_GetWnd.is_some() { loaded_count += 1; } if pointers.SplitMediaItem.is_some() { loaded_count += 1; } if pointers.StopPreview.is_some() { loaded_count += 1; } if pointers.StopTrackPreview.is_some() { loaded_count += 1; } if pointers.StopTrackPreview2.is_some() { loaded_count += 1; } if pointers.stringToGuid.is_some() { loaded_count += 1; } if pointers.StuffMIDIMessage.is_some() { loaded_count += 1; } if pointers.TakeFX_AddByName.is_some() { loaded_count += 1; } if pointers.TakeFX_CopyToTake.is_some() { loaded_count += 1; } if pointers.TakeFX_CopyToTrack.is_some() { loaded_count += 1; } if pointers.TakeFX_Delete.is_some() { loaded_count += 1; } if pointers.TakeFX_EndParamEdit.is_some() { loaded_count += 1; } if pointers.TakeFX_FormatParamValue.is_some() { loaded_count += 1; } if pointers.TakeFX_FormatParamValueNormalized.is_some() { loaded_count += 1; } if pointers.TakeFX_GetChainVisible.is_some() { loaded_count += 1; } if pointers.TakeFX_GetCount.is_some() { loaded_count += 1; } if pointers.TakeFX_GetEnabled.is_some() { loaded_count += 1; } if pointers.TakeFX_GetEnvelope.is_some() { loaded_count += 1; } if pointers.TakeFX_GetFloatingWindow.is_some() { loaded_count += 1; } if pointers.TakeFX_GetFormattedParamValue.is_some() { loaded_count += 1; } if pointers.TakeFX_GetFXGUID.is_some() { loaded_count += 1; } if pointers.TakeFX_GetFXName.is_some() { loaded_count += 1; } if pointers.TakeFX_GetIOSize.is_some() { loaded_count += 1; } if pointers.TakeFX_GetNamedConfigParm.is_some() { loaded_count += 1; } if pointers.TakeFX_GetNumParams.is_some() { loaded_count += 1; } if pointers.TakeFX_GetOffline.is_some() { loaded_count += 1; } if pointers.TakeFX_GetOpen.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParam.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParameterStepSizes.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParamEx.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParamFromIdent.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParamIdent.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParamName.is_some() { loaded_count += 1; } if pointers.TakeFX_GetParamNormalized.is_some() { loaded_count += 1; } if pointers.TakeFX_GetPinMappings.is_some() { loaded_count += 1; } if pointers.TakeFX_GetPreset.is_some() { loaded_count += 1; } if pointers.TakeFX_GetPresetIndex.is_some() { loaded_count += 1; } if pointers.TakeFX_GetUserPresetFilename.is_some() { loaded_count += 1; } if pointers.TakeFX_NavigatePresets.is_some() { loaded_count += 1; } if pointers.TakeFX_SetEnabled.is_some() { loaded_count += 1; } if pointers.TakeFX_SetNamedConfigParm.is_some() { loaded_count += 1; } if pointers.TakeFX_SetOffline.is_some() { loaded_count += 1; } if pointers.TakeFX_SetOpen.is_some() { loaded_count += 1; } if pointers.TakeFX_SetParam.is_some() { loaded_count += 1; } if pointers.TakeFX_SetParamNormalized.is_some() { loaded_count += 1; } if pointers.TakeFX_SetPinMappings.is_some() { loaded_count += 1; } if pointers.TakeFX_SetPreset.is_some() { loaded_count += 1; } if pointers.TakeFX_SetPresetByIndex.is_some() { loaded_count += 1; } if pointers.TakeFX_Show.is_some() { loaded_count += 1; } if pointers.TakeIsMIDI.is_some() { loaded_count += 1; } if pointers.ThemeLayout_GetLayout.is_some() { loaded_count += 1; } if pointers.ThemeLayout_GetParameter.is_some() { loaded_count += 1; } if pointers.ThemeLayout_RefreshAll.is_some() { loaded_count += 1; } if pointers.ThemeLayout_SetLayout.is_some() { loaded_count += 1; } if pointers.ThemeLayout_SetParameter.is_some() { loaded_count += 1; } if pointers.time_precise.is_some() { loaded_count += 1; } if pointers.TimeMap2_beatsToTime.is_some() { loaded_count += 1; } if pointers.TimeMap2_GetDividedBpmAtTime.is_some() { loaded_count += 1; } if pointers.TimeMap2_GetNextChangeTime.is_some() { loaded_count += 1; } if pointers.TimeMap2_QNToTime.is_some() { loaded_count += 1; } if pointers.TimeMap2_timeToBeats.is_some() { loaded_count += 1; } if pointers.TimeMap2_timeToQN.is_some() { loaded_count += 1; } if pointers.TimeMap_curFrameRate.is_some() { loaded_count += 1; } if pointers.TimeMap_GetDividedBpmAtTime.is_some() { loaded_count += 1; } if pointers.TimeMap_GetMeasureInfo.is_some() { loaded_count += 1; } if pointers.TimeMap_GetMetronomePattern.is_some() { loaded_count += 1; } if pointers.TimeMap_GetTimeSigAtTime.is_some() { loaded_count += 1; } if pointers.TimeMap_QNToMeasures.is_some() { loaded_count += 1; } if pointers.TimeMap_QNToTime.is_some() { loaded_count += 1; } if pointers.TimeMap_QNToTime_abs.is_some() { loaded_count += 1; } if pointers.TimeMap_timeToQN.is_some() { loaded_count += 1; } if pointers.TimeMap_timeToQN_abs.is_some() { loaded_count += 1; } if pointers.ToggleTrackSendUIMute.is_some() { loaded_count += 1; } if pointers.Track_GetPeakHoldDB.is_some() { loaded_count += 1; } if pointers.Track_GetPeakInfo.is_some() { loaded_count += 1; } if pointers.TrackCtl_SetToolTip.is_some() { loaded_count += 1; } if pointers.TrackFX_AddByName.is_some() { loaded_count += 1; } if pointers.TrackFX_CopyToTake.is_some() { loaded_count += 1; } if pointers.TrackFX_CopyToTrack.is_some() { loaded_count += 1; } if pointers.TrackFX_Delete.is_some() { loaded_count += 1; } if pointers.TrackFX_EndParamEdit.is_some() { loaded_count += 1; } if pointers.TrackFX_FormatParamValue.is_some() { loaded_count += 1; } if pointers.TrackFX_FormatParamValueNormalized.is_some() { loaded_count += 1; } if pointers.TrackFX_GetByName.is_some() { loaded_count += 1; } if pointers.TrackFX_GetChainVisible.is_some() { loaded_count += 1; } if pointers.TrackFX_GetCount.is_some() { loaded_count += 1; } if pointers.TrackFX_GetEnabled.is_some() { loaded_count += 1; } if pointers.TrackFX_GetEQ.is_some() { loaded_count += 1; } if pointers.TrackFX_GetEQBandEnabled.is_some() { loaded_count += 1; } if pointers.TrackFX_GetEQParam.is_some() { loaded_count += 1; } if pointers.TrackFX_GetFloatingWindow.is_some() { loaded_count += 1; } if pointers.TrackFX_GetFormattedParamValue.is_some() { loaded_count += 1; } if pointers.TrackFX_GetFXGUID.is_some() { loaded_count += 1; } if pointers.TrackFX_GetFXName.is_some() { loaded_count += 1; } if pointers.TrackFX_GetInstrument.is_some() { loaded_count += 1; } if pointers.TrackFX_GetIOSize.is_some() { loaded_count += 1; } if pointers.TrackFX_GetNamedConfigParm.is_some() { loaded_count += 1; } if pointers.TrackFX_GetNumParams.is_some() { loaded_count += 1; } if pointers.TrackFX_GetOffline.is_some() { loaded_count += 1; } if pointers.TrackFX_GetOpen.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParam.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParameterStepSizes.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParamEx.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParamFromIdent.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParamIdent.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParamName.is_some() { loaded_count += 1; } if pointers.TrackFX_GetParamNormalized.is_some() { loaded_count += 1; } if pointers.TrackFX_GetPinMappings.is_some() { loaded_count += 1; } if pointers.TrackFX_GetPreset.is_some() { loaded_count += 1; } if pointers.TrackFX_GetPresetIndex.is_some() { loaded_count += 1; } if pointers.TrackFX_GetRecChainVisible.is_some() { loaded_count += 1; } if pointers.TrackFX_GetRecCount.is_some() { loaded_count += 1; } if pointers.TrackFX_GetUserPresetFilename.is_some() { loaded_count += 1; } if pointers.TrackFX_NavigatePresets.is_some() { loaded_count += 1; } if pointers.TrackFX_SetEnabled.is_some() { loaded_count += 1; } if pointers.TrackFX_SetEQBandEnabled.is_some() { loaded_count += 1; } if pointers.TrackFX_SetEQParam.is_some() { loaded_count += 1; } if pointers.TrackFX_SetNamedConfigParm.is_some() { loaded_count += 1; } if pointers.TrackFX_SetOffline.is_some() { loaded_count += 1; } if pointers.TrackFX_SetOpen.is_some() { loaded_count += 1; } if pointers.TrackFX_SetParam.is_some() { loaded_count += 1; } if pointers.TrackFX_SetParamNormalized.is_some() { loaded_count += 1; } if pointers.TrackFX_SetPinMappings.is_some() { loaded_count += 1; } if pointers.TrackFX_SetPreset.is_some() { loaded_count += 1; } if pointers.TrackFX_SetPresetByIndex.is_some() { loaded_count += 1; } if pointers.TrackFX_Show.is_some() { loaded_count += 1; } if pointers.TrackList_AdjustWindows.is_some() { loaded_count += 1; } if pointers.TrackList_UpdateAllExternalSurfaces.is_some() { loaded_count += 1; } if pointers.Undo_BeginBlock.is_some() { loaded_count += 1; } if pointers.Undo_BeginBlock2.is_some() { loaded_count += 1; } if pointers.Undo_CanRedo2.is_some() { loaded_count += 1; } if pointers.Undo_CanUndo2.is_some() { loaded_count += 1; } if pointers.Undo_DoRedo2.is_some() { loaded_count += 1; } if pointers.Undo_DoUndo2.is_some() { loaded_count += 1; } if pointers.Undo_EndBlock.is_some() { loaded_count += 1; } if pointers.Undo_EndBlock2.is_some() { loaded_count += 1; } if pointers.Undo_OnStateChange.is_some() { loaded_count += 1; } if pointers.Undo_OnStateChange2.is_some() { loaded_count += 1; } if pointers.Undo_OnStateChange_Item.is_some() { loaded_count += 1; } if pointers.Undo_OnStateChangeEx.is_some() { loaded_count += 1; } if pointers.Undo_OnStateChangeEx2.is_some() { loaded_count += 1; } if pointers.update_disk_counters.is_some() { loaded_count += 1; } if pointers.UpdateArrange.is_some() { loaded_count += 1; } if pointers.UpdateItemInProject.is_some() { loaded_count += 1; } if pointers.UpdateTimeline.is_some() { loaded_count += 1; } if pointers.ValidatePtr.is_some() { loaded_count += 1; } if pointers.ValidatePtr2.is_some() { loaded_count += 1; } if pointers.ViewPrefs.is_some() { loaded_count += 1; } if pointers.WDL_VirtualWnd_ScaledBlitBG.is_some() { loaded_count += 1; } if pointers.GetMidiInput.is_some() { loaded_count += 1; } if pointers.GetMidiOutput.is_some() { loaded_count += 1; } if pointers.InitializeCoolSB.is_some() { loaded_count += 1; } if pointers.UninitializeCoolSB.is_some() { loaded_count += 1; } if pointers.CoolSB_SetMinThumbSize.is_some() { loaded_count += 1; } if pointers.CoolSB_GetScrollInfo.is_some() { loaded_count += 1; } if pointers.CoolSB_SetScrollInfo.is_some() { loaded_count += 1; } if pointers.CoolSB_SetScrollPos.is_some() { loaded_count += 1; } if pointers.CoolSB_SetScrollRange.is_some() { loaded_count += 1; } if pointers.CoolSB_ShowScrollBar.is_some() { loaded_count += 1; } if pointers.CoolSB_SetResizingThumb.is_some() { loaded_count += 1; } if pointers.CoolSB_SetThemeIndex.is_some() { loaded_count += 1; } pointers.loaded_count = loaded_count; Reaper { pointers, plugin_context: Some(plugin_context), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn __mergesort( &self, base: *mut ::std::os::raw::c_void, nmemb: usize, size: usize, cmpfunc: ::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, >, tmpspace: *mut ::std::os::raw::c_void, ) { match self.pointers.__mergesort { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(__mergesort) ), Some(f) => f(base, nmemb, size, cmpfunc, tmpspace), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddCustomizableMenu( &self, menuidstr: *const ::std::os::raw::c_char, menuname: *const ::std::os::raw::c_char, kbdsecname: *const ::std::os::raw::c_char, addtomainmenu: bool, ) -> bool { match self.pointers.AddCustomizableMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddCustomizableMenu) ), Some(f) => f(menuidstr, menuname, kbdsecname, addtomainmenu), } } pub fn AddExtensionsMainMenu(&self) -> bool { match self.pointers.AddExtensionsMainMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddExtensionsMainMenu) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddMediaItemToTrack(&self, tr: *mut root::MediaTrack) -> *mut root::MediaItem { match self.pointers.AddMediaItemToTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddMediaItemToTrack) ), Some(f) => f(tr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddProjectMarker( &self, proj: *mut root::ReaProject, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, wantidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.AddProjectMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddProjectMarker) ), Some(f) => f(proj, isrgn, pos, rgnend, name, wantidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddProjectMarker2( &self, proj: *mut root::ReaProject, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, wantidx: ::std::os::raw::c_int, color: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.AddProjectMarker2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddProjectMarker2) ), Some(f) => f(proj, isrgn, pos, rgnend, name, wantidx, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddRemoveReaScript( &self, add: bool, sectionID: ::std::os::raw::c_int, scriptfn: *const ::std::os::raw::c_char, commit: bool, ) -> ::std::os::raw::c_int { match self.pointers.AddRemoveReaScript { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddRemoveReaScript) ), Some(f) => f(add, sectionID, scriptfn, commit), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddTakeToMediaItem( &self, item: *mut root::MediaItem, ) -> *mut root::MediaItem_Take { match self.pointers.AddTakeToMediaItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddTakeToMediaItem) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AddTempoTimeSigMarker( &self, proj: *mut root::ReaProject, timepos: f64, bpm: f64, timesig_num: ::std::os::raw::c_int, timesig_denom: ::std::os::raw::c_int, lineartempochange: bool, ) -> bool { match self.pointers.AddTempoTimeSigMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AddTempoTimeSigMarker) ), Some(f) => f( proj, timepos, bpm, timesig_num, timesig_denom, lineartempochange, ), } } pub fn adjustZoom( &self, amt: f64, forceset: ::std::os::raw::c_int, doupd: bool, centermode: ::std::os::raw::c_int, ) { match self.pointers.adjustZoom { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(adjustZoom) ), Some(f) => f(amt, forceset, doupd, centermode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AnyTrackSolo(&self, proj: *mut root::ReaProject) -> bool { match self.pointers.AnyTrackSolo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AnyTrackSolo) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn APIExists(&self, function_name: *const ::std::os::raw::c_char) -> bool { match self.pointers.APIExists { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(APIExists) ), Some(f) => f(function_name), } } pub fn APITest(&self) { match self.pointers.APITest { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(APITest) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ApplyNudge( &self, project: *mut root::ReaProject, nudgeflag: ::std::os::raw::c_int, nudgewhat: ::std::os::raw::c_int, nudgeunits: ::std::os::raw::c_int, value: f64, reverse: bool, copies: ::std::os::raw::c_int, ) -> bool { match self.pointers.ApplyNudge { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ApplyNudge) ), Some(f) => f( project, nudgeflag, nudgewhat, nudgeunits, value, reverse, copies, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ArmCommand( &self, cmd: ::std::os::raw::c_int, sectionname: *const ::std::os::raw::c_char, ) { match self.pointers.ArmCommand { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ArmCommand) ), Some(f) => f(cmd, sectionname), } } pub fn Audio_Init(&self) { match self.pointers.Audio_Init { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Audio_Init) ), Some(f) => f(), } } pub fn Audio_IsPreBuffer(&self) -> ::std::os::raw::c_int { match self.pointers.Audio_IsPreBuffer { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Audio_IsPreBuffer) ), Some(f) => f(), } } pub fn Audio_IsRunning(&self) -> ::std::os::raw::c_int { match self.pointers.Audio_IsRunning { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Audio_IsRunning) ), Some(f) => f(), } } pub fn Audio_Quit(&self) { match self.pointers.Audio_Quit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Audio_Quit) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Audio_RegHardwareHook( &self, isAdd: bool, reg: *mut root::audio_hook_register_t, ) -> ::std::os::raw::c_int { match self.pointers.Audio_RegHardwareHook { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Audio_RegHardwareHook) ), Some(f) => f(isAdd, reg), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AudioAccessorStateChanged( &self, accessor: *mut root::reaper_functions::AudioAccessor, ) -> bool { match self.pointers.AudioAccessorStateChanged { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AudioAccessorStateChanged) ), Some(f) => f(accessor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AudioAccessorUpdate(&self, accessor: *mut root::reaper_functions::AudioAccessor) { match self.pointers.AudioAccessorUpdate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AudioAccessorUpdate) ), Some(f) => f(accessor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn AudioAccessorValidateState( &self, accessor: *mut root::reaper_functions::AudioAccessor, ) -> bool { match self.pointers.AudioAccessorValidateState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(AudioAccessorValidateState) ), Some(f) => f(accessor), } } pub fn BypassFxAllTracks(&self, bypass: ::std::os::raw::c_int) { match self.pointers.BypassFxAllTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(BypassFxAllTracks) ), Some(f) => f(bypass), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CalculatePeaks( &self, srcBlock: *mut root::PCM_source_transfer_t, pksBlock: *mut root::PCM_source_peaktransfer_t, ) -> ::std::os::raw::c_int { match self.pointers.CalculatePeaks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CalculatePeaks) ), Some(f) => f(srcBlock, pksBlock), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CalculatePeaksFloatSrcPtr( &self, srcBlock: *mut root::PCM_source_transfer_t, pksBlock: *mut root::PCM_source_peaktransfer_t, ) -> ::std::os::raw::c_int { match self.pointers.CalculatePeaksFloatSrcPtr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CalculatePeaksFloatSrcPtr) ), Some(f) => f(srcBlock, pksBlock), } } pub fn ClearAllRecArmed(&self) { match self.pointers.ClearAllRecArmed { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ClearAllRecArmed) ), Some(f) => f(), } } pub fn ClearConsole(&self) { match self.pointers.ClearConsole { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ClearConsole) ), Some(f) => f(), } } pub fn ClearPeakCache(&self) { match self.pointers.ClearPeakCache { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ClearPeakCache) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ColorFromNative( &self, col: ::std::os::raw::c_int, rOut: *mut ::std::os::raw::c_int, gOut: *mut ::std::os::raw::c_int, bOut: *mut ::std::os::raw::c_int, ) { match self.pointers.ColorFromNative { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ColorFromNative) ), Some(f) => f(col, rOut, gOut, bOut), } } pub fn ColorToNative( &self, r: ::std::os::raw::c_int, g: ::std::os::raw::c_int, b: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.ColorToNative { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ColorToNative) ), Some(f) => f(r, g, b), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountActionShortcuts( &self, section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.CountActionShortcuts { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountActionShortcuts) ), Some(f) => f(section, cmdID), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountAutomationItems( &self, env: *mut root::TrackEnvelope, ) -> ::std::os::raw::c_int { match self.pointers.CountAutomationItems { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountAutomationItems) ), Some(f) => f(env), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountEnvelopePoints( &self, envelope: *mut root::TrackEnvelope, ) -> ::std::os::raw::c_int { match self.pointers.CountEnvelopePoints { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountEnvelopePoints) ), Some(f) => f(envelope), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountEnvelopePointsEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.CountEnvelopePointsEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountEnvelopePointsEx) ), Some(f) => f(envelope, autoitem_idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountMediaItems(&self, proj: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.CountMediaItems { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountMediaItems) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountProjectMarkers( &self, proj: *mut root::ReaProject, num_markersOut: *mut ::std::os::raw::c_int, num_regionsOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.CountProjectMarkers { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountProjectMarkers) ), Some(f) => f(proj, num_markersOut, num_regionsOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountSelectedMediaItems( &self, proj: *mut root::ReaProject, ) -> ::std::os::raw::c_int { match self.pointers.CountSelectedMediaItems { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountSelectedMediaItems) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountSelectedTracks(&self, proj: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.CountSelectedTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountSelectedTracks) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountSelectedTracks2( &self, proj: *mut root::ReaProject, wantmaster: bool, ) -> ::std::os::raw::c_int { match self.pointers.CountSelectedTracks2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountSelectedTracks2) ), Some(f) => f(proj, wantmaster), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTakeEnvelopes( &self, take: *mut root::MediaItem_Take, ) -> ::std::os::raw::c_int { match self.pointers.CountTakeEnvelopes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTakeEnvelopes) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTakes(&self, item: *mut root::MediaItem) -> ::std::os::raw::c_int { match self.pointers.CountTakes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTakes) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTCPFXParms( &self, project: *mut root::ReaProject, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.CountTCPFXParms { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTCPFXParms) ), Some(f) => f(project, track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTempoTimeSigMarkers( &self, proj: *mut root::ReaProject, ) -> ::std::os::raw::c_int { match self.pointers.CountTempoTimeSigMarkers { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTempoTimeSigMarkers) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTrackEnvelopes( &self, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.CountTrackEnvelopes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTrackEnvelopes) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTrackMediaItems( &self, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.CountTrackMediaItems { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTrackMediaItems) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CountTracks(&self, projOptional: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.CountTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CountTracks) ), Some(f) => f(projOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CreateLocalOscHandler( &self, obj: *mut ::std::os::raw::c_void, callback: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void { match self.pointers.CreateLocalOscHandler { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateLocalOscHandler) ), Some(f) => f(obj, callback), } } pub fn CreateMIDIInput(&self, dev: ::std::os::raw::c_int) -> *mut root::midi_Input { match self.pointers.CreateMIDIInput { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateMIDIInput) ), Some(f) => f(dev), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CreateMIDIOutput( &self, dev: ::std::os::raw::c_int, streamMode: bool, msoffset100: *mut ::std::os::raw::c_int, ) -> *mut root::midi_Output { match self.pointers.CreateMIDIOutput { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateMIDIOutput) ), Some(f) => f(dev, streamMode, msoffset100), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CreateNewMIDIItemInProj( &self, track: *mut root::MediaTrack, starttime: f64, endtime: f64, qnInOptional: *const bool, ) -> *mut root::MediaItem { match self.pointers.CreateNewMIDIItemInProj { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateNewMIDIItemInProj) ), Some(f) => f(track, starttime, endtime, qnInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CreateTakeAudioAccessor( &self, take: *mut root::MediaItem_Take, ) -> *mut root::reaper_functions::AudioAccessor { match self.pointers.CreateTakeAudioAccessor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateTakeAudioAccessor) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CreateTrackAudioAccessor( &self, track: *mut root::MediaTrack, ) -> *mut root::reaper_functions::AudioAccessor { match self.pointers.CreateTrackAudioAccessor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateTrackAudioAccessor) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CreateTrackSend( &self, tr: *mut root::MediaTrack, desttrInOptional: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.CreateTrackSend { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CreateTrackSend) ), Some(f) => f(tr, desttrInOptional), } } pub fn CSurf_FlushUndo(&self, force: bool) { match self.pointers.CSurf_FlushUndo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_FlushUndo) ), Some(f) => f(force), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_GetTouchState( &self, trackid: *mut root::MediaTrack, isPan: ::std::os::raw::c_int, ) -> bool { match self.pointers.CSurf_GetTouchState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_GetTouchState) ), Some(f) => f(trackid, isPan), } } pub fn CSurf_GoEnd(&self) { match self.pointers.CSurf_GoEnd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_GoEnd) ), Some(f) => f(), } } pub fn CSurf_GoStart(&self) { match self.pointers.CSurf_GoStart { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_GoStart) ), Some(f) => f(), } } pub fn CSurf_NumTracks(&self, mcpView: bool) -> ::std::os::raw::c_int { match self.pointers.CSurf_NumTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_NumTracks) ), Some(f) => f(mcpView), } } pub fn CSurf_OnArrow(&self, whichdir: ::std::os::raw::c_int, wantzoom: bool) { match self.pointers.CSurf_OnArrow { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnArrow) ), Some(f) => f(whichdir, wantzoom), } } pub fn CSurf_OnFwd(&self, seekplay: ::std::os::raw::c_int) { match self.pointers.CSurf_OnFwd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnFwd) ), Some(f) => f(seekplay), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnFXChange( &self, trackid: *mut root::MediaTrack, en: ::std::os::raw::c_int, ) -> bool { match self.pointers.CSurf_OnFXChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnFXChange) ), Some(f) => f(trackid, en), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnInputMonitorChange( &self, trackid: *mut root::MediaTrack, monitor: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.CSurf_OnInputMonitorChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnInputMonitorChange) ), Some(f) => f(trackid, monitor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnInputMonitorChangeEx( &self, trackid: *mut root::MediaTrack, monitor: ::std::os::raw::c_int, allowgang: bool, ) -> ::std::os::raw::c_int { match self.pointers.CSurf_OnInputMonitorChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnInputMonitorChangeEx) ), Some(f) => f(trackid, monitor, allowgang), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnMuteChange( &self, trackid: *mut root::MediaTrack, mute: ::std::os::raw::c_int, ) -> bool { match self.pointers.CSurf_OnMuteChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnMuteChange) ), Some(f) => f(trackid, mute), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnMuteChangeEx( &self, trackid: *mut root::MediaTrack, mute: ::std::os::raw::c_int, allowgang: bool, ) -> bool { match self.pointers.CSurf_OnMuteChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnMuteChangeEx) ), Some(f) => f(trackid, mute, allowgang), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnOscControlMessage( &self, msg: *const ::std::os::raw::c_char, arg: *const f32, ) { match self.pointers.CSurf_OnOscControlMessage { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnOscControlMessage) ), Some(f) => f(msg, arg), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnPanChange( &self, trackid: *mut root::MediaTrack, pan: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnPanChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnPanChange) ), Some(f) => f(trackid, pan, relative), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnPanChangeEx( &self, trackid: *mut root::MediaTrack, pan: f64, relative: bool, allowGang: bool, ) -> f64 { match self.pointers.CSurf_OnPanChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnPanChangeEx) ), Some(f) => f(trackid, pan, relative, allowGang), } } pub fn CSurf_OnPause(&self) { match self.pointers.CSurf_OnPause { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnPause) ), Some(f) => f(), } } pub fn CSurf_OnPlay(&self) { match self.pointers.CSurf_OnPlay { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnPlay) ), Some(f) => f(), } } pub fn CSurf_OnPlayRateChange(&self, playrate: f64) { match self.pointers.CSurf_OnPlayRateChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnPlayRateChange) ), Some(f) => f(playrate), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnRecArmChange( &self, trackid: *mut root::MediaTrack, recarm: ::std::os::raw::c_int, ) -> bool { match self.pointers.CSurf_OnRecArmChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRecArmChange) ), Some(f) => f(trackid, recarm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnRecArmChangeEx( &self, trackid: *mut root::MediaTrack, recarm: ::std::os::raw::c_int, allowgang: bool, ) -> bool { match self.pointers.CSurf_OnRecArmChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRecArmChangeEx) ), Some(f) => f(trackid, recarm, allowgang), } } pub fn CSurf_OnRecord(&self) { match self.pointers.CSurf_OnRecord { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRecord) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnRecvPanChange( &self, trackid: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, pan: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnRecvPanChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRecvPanChange) ), Some(f) => f(trackid, recv_index, pan, relative), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnRecvVolumeChange( &self, trackid: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, volume: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnRecvVolumeChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRecvVolumeChange) ), Some(f) => f(trackid, recv_index, volume, relative), } } pub fn CSurf_OnRew(&self, seekplay: ::std::os::raw::c_int) { match self.pointers.CSurf_OnRew { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRew) ), Some(f) => f(seekplay), } } pub fn CSurf_OnRewFwd(&self, seekplay: ::std::os::raw::c_int, dir: ::std::os::raw::c_int) { match self.pointers.CSurf_OnRewFwd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnRewFwd) ), Some(f) => f(seekplay, dir), } } pub fn CSurf_OnScroll(&self, xdir: ::std::os::raw::c_int, ydir: ::std::os::raw::c_int) { match self.pointers.CSurf_OnScroll { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnScroll) ), Some(f) => f(xdir, ydir), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnSelectedChange( &self, trackid: *mut root::MediaTrack, selected: ::std::os::raw::c_int, ) -> bool { match self.pointers.CSurf_OnSelectedChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnSelectedChange) ), Some(f) => f(trackid, selected), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnSendPanChange( &self, trackid: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, pan: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnSendPanChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnSendPanChange) ), Some(f) => f(trackid, send_index, pan, relative), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnSendVolumeChange( &self, trackid: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, volume: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnSendVolumeChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnSendVolumeChange) ), Some(f) => f(trackid, send_index, volume, relative), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnSoloChange( &self, trackid: *mut root::MediaTrack, solo: ::std::os::raw::c_int, ) -> bool { match self.pointers.CSurf_OnSoloChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnSoloChange) ), Some(f) => f(trackid, solo), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnSoloChangeEx( &self, trackid: *mut root::MediaTrack, solo: ::std::os::raw::c_int, allowgang: bool, ) -> bool { match self.pointers.CSurf_OnSoloChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnSoloChangeEx) ), Some(f) => f(trackid, solo, allowgang), } } pub fn CSurf_OnStop(&self) { match self.pointers.CSurf_OnStop { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnStop) ), Some(f) => f(), } } pub fn CSurf_OnTempoChange(&self, bpm: f64) { match self.pointers.CSurf_OnTempoChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnTempoChange) ), Some(f) => f(bpm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnTrackSelection(&self, trackid: *mut root::MediaTrack) { match self.pointers.CSurf_OnTrackSelection { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnTrackSelection) ), Some(f) => f(trackid), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnVolumeChange( &self, trackid: *mut root::MediaTrack, volume: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnVolumeChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnVolumeChange) ), Some(f) => f(trackid, volume, relative), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnVolumeChangeEx( &self, trackid: *mut root::MediaTrack, volume: f64, relative: bool, allowGang: bool, ) -> f64 { match self.pointers.CSurf_OnVolumeChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnVolumeChangeEx) ), Some(f) => f(trackid, volume, relative, allowGang), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnWidthChange( &self, trackid: *mut root::MediaTrack, width: f64, relative: bool, ) -> f64 { match self.pointers.CSurf_OnWidthChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnWidthChange) ), Some(f) => f(trackid, width, relative), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_OnWidthChangeEx( &self, trackid: *mut root::MediaTrack, width: f64, relative: bool, allowGang: bool, ) -> f64 { match self.pointers.CSurf_OnWidthChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnWidthChangeEx) ), Some(f) => f(trackid, width, relative, allowGang), } } pub fn CSurf_OnZoom(&self, xdir: ::std::os::raw::c_int, ydir: ::std::os::raw::c_int) { match self.pointers.CSurf_OnZoom { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_OnZoom) ), Some(f) => f(xdir, ydir), } } pub fn CSurf_ResetAllCachedVolPanStates(&self) { match self.pointers.CSurf_ResetAllCachedVolPanStates { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_ResetAllCachedVolPanStates) ), Some(f) => f(), } } pub fn CSurf_ScrubAmt(&self, amt: f64) { match self.pointers.CSurf_ScrubAmt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_ScrubAmt) ), Some(f) => f(amt), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetAutoMode( &self, mode: ::std::os::raw::c_int, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetAutoMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetAutoMode) ), Some(f) => f(mode, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetPlayState( &self, play: bool, pause: bool, rec: bool, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetPlayState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetPlayState) ), Some(f) => f(play, pause, rec, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetRepeatState( &self, rep: bool, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetRepeatState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetRepeatState) ), Some(f) => f(rep, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetSurfaceMute( &self, trackid: *mut root::MediaTrack, mute: bool, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetSurfaceMute { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetSurfaceMute) ), Some(f) => f(trackid, mute, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetSurfacePan( &self, trackid: *mut root::MediaTrack, pan: f64, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetSurfacePan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetSurfacePan) ), Some(f) => f(trackid, pan, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetSurfaceRecArm( &self, trackid: *mut root::MediaTrack, recarm: bool, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetSurfaceRecArm { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetSurfaceRecArm) ), Some(f) => f(trackid, recarm, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetSurfaceSelected( &self, trackid: *mut root::MediaTrack, selected: bool, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetSurfaceSelected { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetSurfaceSelected) ), Some(f) => f(trackid, selected, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetSurfaceSolo( &self, trackid: *mut root::MediaTrack, solo: bool, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetSurfaceSolo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetSurfaceSolo) ), Some(f) => f(trackid, solo, ignoresurf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_SetSurfaceVolume( &self, trackid: *mut root::MediaTrack, volume: f64, ignoresurf: *mut root::IReaperControlSurface, ) { match self.pointers.CSurf_SetSurfaceVolume { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetSurfaceVolume) ), Some(f) => f(trackid, volume, ignoresurf), } } pub fn CSurf_SetTrackListChange(&self) { match self.pointers.CSurf_SetTrackListChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_SetTrackListChange) ), Some(f) => f(), } } pub fn CSurf_TrackFromID( &self, idx: ::std::os::raw::c_int, mcpView: bool, ) -> *mut root::MediaTrack { match self.pointers.CSurf_TrackFromID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_TrackFromID) ), Some(f) => f(idx, mcpView), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CSurf_TrackToID( &self, track: *mut root::MediaTrack, mcpView: bool, ) -> ::std::os::raw::c_int { match self.pointers.CSurf_TrackToID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CSurf_TrackToID) ), Some(f) => f(track, mcpView), } } pub fn DB2SLIDER(&self, x: f64) -> f64 { match self.pointers.DB2SLIDER { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DB2SLIDER) ), Some(f) => f(x), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteActionShortcut( &self, section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, shortcutidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.DeleteActionShortcut { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteActionShortcut) ), Some(f) => f(section, cmdID, shortcutidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteEnvelopePointEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ptidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.DeleteEnvelopePointEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteEnvelopePointEx) ), Some(f) => f(envelope, autoitem_idx, ptidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteEnvelopePointRange( &self, envelope: *mut root::TrackEnvelope, time_start: f64, time_end: f64, ) -> bool { match self.pointers.DeleteEnvelopePointRange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteEnvelopePointRange) ), Some(f) => f(envelope, time_start, time_end), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteEnvelopePointRangeEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, time_start: f64, time_end: f64, ) -> bool { match self.pointers.DeleteEnvelopePointRangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteEnvelopePointRangeEx) ), Some(f) => f(envelope, autoitem_idx, time_start, time_end), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteExtState( &self, section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, persist: bool, ) { match self.pointers.DeleteExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteExtState) ), Some(f) => f(section, key, persist), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteProjectMarker( &self, proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, ) -> bool { match self.pointers.DeleteProjectMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteProjectMarker) ), Some(f) => f(proj, markrgnindexnumber, isrgn), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteProjectMarkerByIndex( &self, proj: *mut root::ReaProject, markrgnidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.DeleteProjectMarkerByIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteProjectMarkerByIndex) ), Some(f) => f(proj, markrgnidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteTakeMarker( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, ) -> bool { match self.pointers.DeleteTakeMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteTakeMarker) ), Some(f) => f(take, idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteTakeStretchMarkers( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, countInOptional: *const ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.DeleteTakeStretchMarkers { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteTakeStretchMarkers) ), Some(f) => f(take, idx, countInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteTempoTimeSigMarker( &self, project: *mut root::ReaProject, markerindex: ::std::os::raw::c_int, ) -> bool { match self.pointers.DeleteTempoTimeSigMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteTempoTimeSigMarker) ), Some(f) => f(project, markerindex), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteTrack(&self, tr: *mut root::MediaTrack) { match self.pointers.DeleteTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteTrack) ), Some(f) => f(tr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DeleteTrackMediaItem( &self, tr: *mut root::MediaTrack, it: *mut root::MediaItem, ) -> bool { match self.pointers.DeleteTrackMediaItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DeleteTrackMediaItem) ), Some(f) => f(tr, it), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DestroyAudioAccessor( &self, accessor: *mut root::reaper_functions::AudioAccessor, ) { match self.pointers.DestroyAudioAccessor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DestroyAudioAccessor) ), Some(f) => f(accessor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DestroyLocalOscHandler(&self, local_osc_handler: *mut ::std::os::raw::c_void) { match self.pointers.DestroyLocalOscHandler { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DestroyLocalOscHandler) ), Some(f) => f(local_osc_handler), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DoActionShortcutDialog( &self, hwnd: root::HWND, section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, shortcutidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.DoActionShortcutDialog { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DoActionShortcutDialog) ), Some(f) => f(hwnd, section, cmdID, shortcutidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Dock_UpdateDockID( &self, ident_str: *const ::std::os::raw::c_char, whichDock: ::std::os::raw::c_int, ) { match self.pointers.Dock_UpdateDockID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Dock_UpdateDockID) ), Some(f) => f(ident_str, whichDock), } } pub fn DockGetPosition(&self, whichDock: ::std::os::raw::c_int) -> ::std::os::raw::c_int { match self.pointers.DockGetPosition { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockGetPosition) ), Some(f) => f(whichDock), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DockIsChildOfDock( &self, hwnd: root::HWND, isFloatingDockerOut: *mut bool, ) -> ::std::os::raw::c_int { match self.pointers.DockIsChildOfDock { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockIsChildOfDock) ), Some(f) => f(hwnd, isFloatingDockerOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DockWindowActivate(&self, hwnd: root::HWND) { match self.pointers.DockWindowActivate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockWindowActivate) ), Some(f) => f(hwnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DockWindowAdd( &self, hwnd: root::HWND, name: *const ::std::os::raw::c_char, pos: ::std::os::raw::c_int, allowShow: bool, ) { match self.pointers.DockWindowAdd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockWindowAdd) ), Some(f) => f(hwnd, name, pos, allowShow), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DockWindowAddEx( &self, hwnd: root::HWND, name: *const ::std::os::raw::c_char, identstr: *const ::std::os::raw::c_char, allowShow: bool, ) { match self.pointers.DockWindowAddEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockWindowAddEx) ), Some(f) => f(hwnd, name, identstr, allowShow), } } pub fn DockWindowRefresh(&self) { match self.pointers.DockWindowRefresh { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockWindowRefresh) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DockWindowRefreshForHWND(&self, hwnd: root::HWND) { match self.pointers.DockWindowRefreshForHWND { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockWindowRefreshForHWND) ), Some(f) => f(hwnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DockWindowRemove(&self, hwnd: root::HWND) { match self.pointers.DockWindowRemove { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DockWindowRemove) ), Some(f) => f(hwnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn DuplicateCustomizableMenu( &self, srcmenu: *mut ::std::os::raw::c_void, destmenu: *mut ::std::os::raw::c_void, ) -> bool { match self.pointers.DuplicateCustomizableMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(DuplicateCustomizableMenu) ), Some(f) => f(srcmenu, destmenu), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EditTempoTimeSigMarker( &self, project: *mut root::ReaProject, markerindex: ::std::os::raw::c_int, ) -> bool { match self.pointers.EditTempoTimeSigMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EditTempoTimeSigMarker) ), Some(f) => f(project, markerindex), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnsureNotCompletelyOffscreen(&self, rInOut: *mut root::RECT) { match self.pointers.EnsureNotCompletelyOffscreen { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnsureNotCompletelyOffscreen) ), Some(f) => f(rInOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumerateFiles( &self, path: *const ::std::os::raw::c_char, fileindex: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.EnumerateFiles { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumerateFiles) ), Some(f) => f(path, fileindex), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumerateSubdirectories( &self, path: *const ::std::os::raw::c_char, subdirindex: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.EnumerateSubdirectories { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumerateSubdirectories) ), Some(f) => f(path, subdirindex), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumPitchShiftModes( &self, mode: ::std::os::raw::c_int, strOut: *mut *const ::std::os::raw::c_char, ) -> bool { match self.pointers.EnumPitchShiftModes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumPitchShiftModes) ), Some(f) => f(mode, strOut), } } pub fn EnumPitchShiftSubModes( &self, mode: ::std::os::raw::c_int, submode: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.EnumPitchShiftSubModes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumPitchShiftSubModes) ), Some(f) => f(mode, submode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumProjectMarkers( &self, idx: ::std::os::raw::c_int, isrgnOut: *mut bool, posOut: *mut f64, rgnendOut: *mut f64, nameOut: *mut *const ::std::os::raw::c_char, markrgnindexnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.EnumProjectMarkers { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumProjectMarkers) ), Some(f) => f( idx, isrgnOut, posOut, rgnendOut, nameOut, markrgnindexnumberOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumProjectMarkers2( &self, proj: *mut root::ReaProject, idx: ::std::os::raw::c_int, isrgnOut: *mut bool, posOut: *mut f64, rgnendOut: *mut f64, nameOut: *mut *const ::std::os::raw::c_char, markrgnindexnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.EnumProjectMarkers2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumProjectMarkers2) ), Some(f) => f( proj, idx, isrgnOut, posOut, rgnendOut, nameOut, markrgnindexnumberOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumProjectMarkers3( &self, proj: *mut root::ReaProject, idx: ::std::os::raw::c_int, isrgnOut: *mut bool, posOut: *mut f64, rgnendOut: *mut f64, nameOut: *mut *const ::std::os::raw::c_char, markrgnindexnumberOut: *mut ::std::os::raw::c_int, colorOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.EnumProjectMarkers3 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumProjectMarkers3) ), Some(f) => f( proj, idx, isrgnOut, posOut, rgnendOut, nameOut, markrgnindexnumberOut, colorOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumProjects( &self, idx: ::std::os::raw::c_int, projfnOutOptional: *mut ::std::os::raw::c_char, projfnOutOptional_sz: ::std::os::raw::c_int, ) -> *mut root::ReaProject { match self.pointers.EnumProjects { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumProjects) ), Some(f) => f(idx, projfnOutOptional, projfnOutOptional_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumProjExtState( &self, proj: *mut root::ReaProject, extname: *const ::std::os::raw::c_char, idx: ::std::os::raw::c_int, keyOutOptional: *mut ::std::os::raw::c_char, keyOutOptional_sz: ::std::os::raw::c_int, valOutOptional: *mut ::std::os::raw::c_char, valOutOptional_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.EnumProjExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumProjExtState) ), Some(f) => f( proj, extname, idx, keyOutOptional, keyOutOptional_sz, valOutOptional, valOutOptional_sz, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumRegionRenderMatrix( &self, proj: *mut root::ReaProject, regionindex: ::std::os::raw::c_int, rendertrack: ::std::os::raw::c_int, ) -> *mut root::MediaTrack { match self.pointers.EnumRegionRenderMatrix { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumRegionRenderMatrix) ), Some(f) => f(proj, regionindex, rendertrack), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumTrackMIDIProgramNames( &self, track: ::std::os::raw::c_int, programNumber: ::std::os::raw::c_int, programName: *mut ::std::os::raw::c_char, programName_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.EnumTrackMIDIProgramNames { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumTrackMIDIProgramNames) ), Some(f) => f(track, programNumber, programName, programName_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn EnumTrackMIDIProgramNamesEx( &self, proj: *mut root::ReaProject, track: *mut root::MediaTrack, programNumber: ::std::os::raw::c_int, programName: *mut ::std::os::raw::c_char, programName_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.EnumTrackMIDIProgramNamesEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(EnumTrackMIDIProgramNamesEx) ), Some(f) => f(proj, track, programNumber, programName, programName_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Envelope_Evaluate( &self, envelope: *mut root::TrackEnvelope, time: f64, samplerate: f64, samplesRequested: ::std::os::raw::c_int, valueOutOptional: *mut f64, dVdSOutOptional: *mut f64, ddVdSOutOptional: *mut f64, dddVdSOutOptional: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.Envelope_Evaluate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Envelope_Evaluate) ), Some(f) => f( envelope, time, samplerate, samplesRequested, valueOutOptional, dVdSOutOptional, ddVdSOutOptional, dddVdSOutOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Envelope_FormatValue( &self, env: *mut root::TrackEnvelope, value: f64, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.Envelope_FormatValue { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Envelope_FormatValue) ), Some(f) => f(env, value, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Envelope_GetParentTake( &self, env: *mut root::TrackEnvelope, indexOutOptional: *mut ::std::os::raw::c_int, index2OutOptional: *mut ::std::os::raw::c_int, ) -> *mut root::MediaItem_Take { match self.pointers.Envelope_GetParentTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Envelope_GetParentTake) ), Some(f) => f(env, indexOutOptional, index2OutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Envelope_GetParentTrack( &self, env: *mut root::TrackEnvelope, indexOutOptional: *mut ::std::os::raw::c_int, index2OutOptional: *mut ::std::os::raw::c_int, ) -> *mut root::MediaTrack { match self.pointers.Envelope_GetParentTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Envelope_GetParentTrack) ), Some(f) => f(env, indexOutOptional, index2OutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Envelope_SortPoints(&self, envelope: *mut root::TrackEnvelope) -> bool { match self.pointers.Envelope_SortPoints { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Envelope_SortPoints) ), Some(f) => f(envelope), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Envelope_SortPointsEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ) -> bool { match self.pointers.Envelope_SortPointsEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Envelope_SortPointsEx) ), Some(f) => f(envelope, autoitem_idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ExecProcess( &self, cmdline: *const ::std::os::raw::c_char, timeoutmsec: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.ExecProcess { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ExecProcess) ), Some(f) => f(cmdline, timeoutmsec), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn file_exists(&self, path: *const ::std::os::raw::c_char) -> bool { match self.pointers.file_exists { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(file_exists) ), Some(f) => f(path), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn FindTempoTimeSigMarker( &self, project: *mut root::ReaProject, time: f64, ) -> ::std::os::raw::c_int { match self.pointers.FindTempoTimeSigMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(FindTempoTimeSigMarker) ), Some(f) => f(project, time), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn format_timestr( &self, tpos: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) { match self.pointers.format_timestr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(format_timestr) ), Some(f) => f(tpos, buf, buf_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn format_timestr_len( &self, tpos: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, offset: f64, modeoverride: ::std::os::raw::c_int, ) { match self.pointers.format_timestr_len { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(format_timestr_len) ), Some(f) => f(tpos, buf, buf_sz, offset, modeoverride), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn format_timestr_pos( &self, tpos: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, modeoverride: ::std::os::raw::c_int, ) { match self.pointers.format_timestr_pos { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(format_timestr_pos) ), Some(f) => f(tpos, buf, buf_sz, modeoverride), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn FreeHeapPtr(&self, ptr: *mut ::std::os::raw::c_void) { match self.pointers.FreeHeapPtr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(FreeHeapPtr) ), Some(f) => f(ptr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn genGuid(&self, g: *mut root::GUID) { match self.pointers.genGuid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(genGuid) ), Some(f) => f(g), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn get_config_var( &self, name: *const ::std::os::raw::c_char, szOut: *mut ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void { match self.pointers.get_config_var { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(get_config_var) ), Some(f) => f(name, szOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn get_config_var_string( &self, name: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.get_config_var_string { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(get_config_var_string) ), Some(f) => f(name, bufOut, bufOut_sz), } } pub fn get_ini_file(&self) -> *const ::std::os::raw::c_char { match self.pointers.get_ini_file { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(get_ini_file) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn get_midi_config_var( &self, name: *const ::std::os::raw::c_char, szOut: *mut ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void { match self.pointers.get_midi_config_var { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(get_midi_config_var) ), Some(f) => f(name, szOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetActionShortcutDesc( &self, section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, shortcutidx: ::std::os::raw::c_int, desc: *mut ::std::os::raw::c_char, desclen: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetActionShortcutDesc { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetActionShortcutDesc) ), Some(f) => f(section, cmdID, shortcutidx, desc, desclen), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetActiveTake(&self, item: *mut root::MediaItem) -> *mut root::MediaItem_Take { match self.pointers.GetActiveTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetActiveTake) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetAllProjectPlayStates( &self, ignoreProject: *mut root::ReaProject, ) -> ::std::os::raw::c_int { match self.pointers.GetAllProjectPlayStates { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAllProjectPlayStates) ), Some(f) => f(ignoreProject), } } pub fn GetAppVersion(&self) -> *const ::std::os::raw::c_char { match self.pointers.GetAppVersion { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAppVersion) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetArmedCommand( &self, secOut: *mut ::std::os::raw::c_char, secOut_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetArmedCommand { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetArmedCommand) ), Some(f) => f(secOut, secOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetAudioAccessorEndTime( &self, accessor: *mut root::reaper_functions::AudioAccessor, ) -> f64 { match self.pointers.GetAudioAccessorEndTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAudioAccessorEndTime) ), Some(f) => f(accessor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetAudioAccessorHash( &self, accessor: *mut root::reaper_functions::AudioAccessor, hashNeed128: *mut ::std::os::raw::c_char, ) { match self.pointers.GetAudioAccessorHash { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAudioAccessorHash) ), Some(f) => f(accessor, hashNeed128), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetAudioAccessorSamples( &self, accessor: *mut root::reaper_functions::AudioAccessor, samplerate: ::std::os::raw::c_int, numchannels: ::std::os::raw::c_int, starttime_sec: f64, numsamplesperchannel: ::std::os::raw::c_int, samplebuffer: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.GetAudioAccessorSamples { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAudioAccessorSamples) ), Some(f) => f( accessor, samplerate, numchannels, starttime_sec, numsamplesperchannel, samplebuffer, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetAudioAccessorStartTime( &self, accessor: *mut root::reaper_functions::AudioAccessor, ) -> f64 { match self.pointers.GetAudioAccessorStartTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAudioAccessorStartTime) ), Some(f) => f(accessor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetAudioDeviceInfo( &self, attribute: *const ::std::os::raw::c_char, descOut: *mut ::std::os::raw::c_char, descOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetAudioDeviceInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetAudioDeviceInfo) ), Some(f) => f(attribute, descOut, descOut_sz), } } pub fn GetColorTheme( &self, idx: ::std::os::raw::c_int, defval: ::std::os::raw::c_int, ) -> root::INT_PTR { match self.pointers.GetColorTheme { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetColorTheme) ), Some(f) => f(idx, defval), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetColorThemeStruct( &self, szOut: *mut ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetColorThemeStruct { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetColorThemeStruct) ), Some(f) => f(szOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetConfigWantsDock( &self, ident_str: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.GetConfigWantsDock { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetConfigWantsDock) ), Some(f) => f(ident_str), } } pub fn GetContextMenu(&self, idx: ::std::os::raw::c_int) -> root::HMENU { match self.pointers.GetContextMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetContextMenu) ), Some(f) => f(idx), } } pub fn GetCurrentProjectInLoadSave(&self) -> *mut root::ReaProject { match self.pointers.GetCurrentProjectInLoadSave { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetCurrentProjectInLoadSave) ), Some(f) => f(), } } pub fn GetCursorContext(&self) -> ::std::os::raw::c_int { match self.pointers.GetCursorContext { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetCursorContext) ), Some(f) => f(), } } pub fn GetCursorContext2(&self, want_last_valid: bool) -> ::std::os::raw::c_int { match self.pointers.GetCursorContext2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetCursorContext2) ), Some(f) => f(want_last_valid), } } pub fn GetCursorPosition(&self) -> f64 { match self.pointers.GetCursorPosition { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetCursorPosition) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetCursorPositionEx(&self, proj: *mut root::ReaProject) -> f64 { match self.pointers.GetCursorPositionEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetCursorPositionEx) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetDisplayedMediaItemColor( &self, item: *mut root::MediaItem, ) -> ::std::os::raw::c_int { match self.pointers.GetDisplayedMediaItemColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetDisplayedMediaItemColor) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetDisplayedMediaItemColor2( &self, item: *mut root::MediaItem, take: *mut root::MediaItem_Take, ) -> ::std::os::raw::c_int { match self.pointers.GetDisplayedMediaItemColor2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetDisplayedMediaItemColor2) ), Some(f) => f(item, take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopeInfo_Value( &self, env: *mut root::TrackEnvelope, parmname: *const ::std::os::raw::c_char, ) -> f64 { match self.pointers.GetEnvelopeInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopeInfo_Value) ), Some(f) => f(env, parmname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopeName( &self, env: *mut root::TrackEnvelope, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetEnvelopeName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopeName) ), Some(f) => f(env, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopePoint( &self, envelope: *mut root::TrackEnvelope, ptidx: ::std::os::raw::c_int, timeOutOptional: *mut f64, valueOutOptional: *mut f64, shapeOutOptional: *mut ::std::os::raw::c_int, tensionOutOptional: *mut f64, selectedOutOptional: *mut bool, ) -> bool { match self.pointers.GetEnvelopePoint { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopePoint) ), Some(f) => f( envelope, ptidx, timeOutOptional, valueOutOptional, shapeOutOptional, tensionOutOptional, selectedOutOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopePointByTime( &self, envelope: *mut root::TrackEnvelope, time: f64, ) -> ::std::os::raw::c_int { match self.pointers.GetEnvelopePointByTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopePointByTime) ), Some(f) => f(envelope, time), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopePointByTimeEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, time: f64, ) -> ::std::os::raw::c_int { match self.pointers.GetEnvelopePointByTimeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopePointByTimeEx) ), Some(f) => f(envelope, autoitem_idx, time), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopePointEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ptidx: ::std::os::raw::c_int, timeOutOptional: *mut f64, valueOutOptional: *mut f64, shapeOutOptional: *mut ::std::os::raw::c_int, tensionOutOptional: *mut f64, selectedOutOptional: *mut bool, ) -> bool { match self.pointers.GetEnvelopePointEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopePointEx) ), Some(f) => f( envelope, autoitem_idx, ptidx, timeOutOptional, valueOutOptional, shapeOutOptional, tensionOutOptional, selectedOutOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopeScalingMode( &self, env: *mut root::TrackEnvelope, ) -> ::std::os::raw::c_int { match self.pointers.GetEnvelopeScalingMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopeScalingMode) ), Some(f) => f(env), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetEnvelopeStateChunk( &self, env: *mut root::TrackEnvelope, strNeedBig: *mut ::std::os::raw::c_char, strNeedBig_sz: ::std::os::raw::c_int, isundoOptional: bool, ) -> bool { match self.pointers.GetEnvelopeStateChunk { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetEnvelopeStateChunk) ), Some(f) => f(env, strNeedBig, strNeedBig_sz, isundoOptional), } } pub fn GetExePath(&self) -> *const ::std::os::raw::c_char { match self.pointers.GetExePath { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetExePath) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetExtState( &self, section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, ) -> *const ::std::os::raw::c_char { match self.pointers.GetExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetExtState) ), Some(f) => f(section, key), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetFocusedFX( &self, tracknumberOut: *mut ::std::os::raw::c_int, itemnumberOut: *mut ::std::os::raw::c_int, fxnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetFocusedFX { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetFocusedFX) ), Some(f) => f(tracknumberOut, itemnumberOut, fxnumberOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetFocusedFX2( &self, tracknumberOut: *mut ::std::os::raw::c_int, itemnumberOut: *mut ::std::os::raw::c_int, fxnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetFocusedFX2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetFocusedFX2) ), Some(f) => f(tracknumberOut, itemnumberOut, fxnumberOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetFreeDiskSpaceForRecordPath( &self, proj: *mut root::ReaProject, pathidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetFreeDiskSpaceForRecordPath { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetFreeDiskSpaceForRecordPath) ), Some(f) => f(proj, pathidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetFXEnvelope( &self, track: *mut root::MediaTrack, fxindex: ::std::os::raw::c_int, parameterindex: ::std::os::raw::c_int, create: bool, ) -> *mut root::TrackEnvelope { match self.pointers.GetFXEnvelope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetFXEnvelope) ), Some(f) => f(track, fxindex, parameterindex, create), } } pub fn GetGlobalAutomationOverride(&self) -> ::std::os::raw::c_int { match self.pointers.GetGlobalAutomationOverride { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetGlobalAutomationOverride) ), Some(f) => f(), } } pub fn GetHZoomLevel(&self) -> f64 { match self.pointers.GetHZoomLevel { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetHZoomLevel) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetIconThemePointer( &self, name: *const ::std::os::raw::c_char, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetIconThemePointer { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetIconThemePointer) ), Some(f) => f(name), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetIconThemePointerForDPI( &self, name: *const ::std::os::raw::c_char, dpisc: ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetIconThemePointerForDPI { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetIconThemePointerForDPI) ), Some(f) => f(name, dpisc), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetIconThemeStruct( &self, szOut: *mut ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetIconThemeStruct { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetIconThemeStruct) ), Some(f) => f(szOut), } } pub fn GetInputChannelName( &self, channelIndex: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.GetInputChannelName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetInputChannelName) ), Some(f) => f(channelIndex), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetInputOutputLatency( &self, inputlatencyOut: *mut ::std::os::raw::c_int, outputLatencyOut: *mut ::std::os::raw::c_int, ) { match self.pointers.GetInputOutputLatency { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetInputOutputLatency) ), Some(f) => f(inputlatencyOut, outputLatencyOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetItemEditingTime2( &self, which_itemOut: *mut *mut root::PCM_source, flagsOut: *mut ::std::os::raw::c_int, ) -> f64 { match self.pointers.GetItemEditingTime2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetItemEditingTime2) ), Some(f) => f(which_itemOut, flagsOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetItemFromPoint( &self, screen_x: ::std::os::raw::c_int, screen_y: ::std::os::raw::c_int, allow_locked: bool, takeOutOptional: *mut *mut root::MediaItem_Take, ) -> *mut root::MediaItem { match self.pointers.GetItemFromPoint { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetItemFromPoint) ), Some(f) => f(screen_x, screen_y, allow_locked, takeOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetItemProjectContext( &self, item: *mut root::MediaItem, ) -> *mut root::ReaProject { match self.pointers.GetItemProjectContext { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetItemProjectContext) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetItemStateChunk( &self, item: *mut root::MediaItem, strNeedBig: *mut ::std::os::raw::c_char, strNeedBig_sz: ::std::os::raw::c_int, isundoOptional: bool, ) -> bool { match self.pointers.GetItemStateChunk { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetItemStateChunk) ), Some(f) => f(item, strNeedBig, strNeedBig_sz, isundoOptional), } } pub fn GetLastColorThemeFile(&self) -> *const ::std::os::raw::c_char { match self.pointers.GetLastColorThemeFile { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetLastColorThemeFile) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetLastMarkerAndCurRegion( &self, proj: *mut root::ReaProject, time: f64, markeridxOut: *mut ::std::os::raw::c_int, regionidxOut: *mut ::std::os::raw::c_int, ) { match self.pointers.GetLastMarkerAndCurRegion { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetLastMarkerAndCurRegion) ), Some(f) => f(proj, time, markeridxOut, regionidxOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetLastTouchedFX( &self, tracknumberOut: *mut ::std::os::raw::c_int, fxnumberOut: *mut ::std::os::raw::c_int, paramnumberOut: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.GetLastTouchedFX { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetLastTouchedFX) ), Some(f) => f(tracknumberOut, fxnumberOut, paramnumberOut), } } pub fn GetLastTouchedTrack(&self) -> *mut root::MediaTrack { match self.pointers.GetLastTouchedTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetLastTouchedTrack) ), Some(f) => f(), } } pub fn GetMainHwnd(&self) -> root::HWND { match self.pointers.GetMainHwnd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMainHwnd) ), Some(f) => f(), } } pub fn GetMasterMuteSoloFlags(&self) -> ::std::os::raw::c_int { match self.pointers.GetMasterMuteSoloFlags { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMasterMuteSoloFlags) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMasterTrack(&self, proj: *mut root::ReaProject) -> *mut root::MediaTrack { match self.pointers.GetMasterTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMasterTrack) ), Some(f) => f(proj), } } pub fn GetMasterTrackVisibility(&self) -> ::std::os::raw::c_int { match self.pointers.GetMasterTrackVisibility { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMasterTrackVisibility) ), Some(f) => f(), } } pub fn GetMaxMidiInputs(&self) -> ::std::os::raw::c_int { match self.pointers.GetMaxMidiInputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMaxMidiInputs) ), Some(f) => f(), } } pub fn GetMaxMidiOutputs(&self) -> ::std::os::raw::c_int { match self.pointers.GetMaxMidiOutputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMaxMidiOutputs) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaFileMetadata( &self, mediaSource: *mut root::PCM_source, identifier: *const ::std::os::raw::c_char, bufOutNeedBig: *mut ::std::os::raw::c_char, bufOutNeedBig_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetMediaFileMetadata { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaFileMetadata) ), Some(f) => f(mediaSource, identifier, bufOutNeedBig, bufOutNeedBig_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItem( &self, proj: *mut root::ReaProject, itemidx: ::std::os::raw::c_int, ) -> *mut root::MediaItem { match self.pointers.GetMediaItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItem) ), Some(f) => f(proj, itemidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItem_Track(&self, item: *mut root::MediaItem) -> *mut root::MediaTrack { match self.pointers.GetMediaItem_Track { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItem_Track) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemInfo_Value( &self, item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, ) -> f64 { match self.pointers.GetMediaItemInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemInfo_Value) ), Some(f) => f(item, parmname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemNumTakes(&self, item: *mut root::MediaItem) -> ::std::os::raw::c_int { match self.pointers.GetMediaItemNumTakes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemNumTakes) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTake( &self, item: *mut root::MediaItem, tk: ::std::os::raw::c_int, ) -> *mut root::MediaItem_Take { match self.pointers.GetMediaItemTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTake) ), Some(f) => f(item, tk), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTake_Item( &self, take: *mut root::MediaItem_Take, ) -> *mut root::MediaItem { match self.pointers.GetMediaItemTake_Item { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTake_Item) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTake_Peaks( &self, take: *mut root::MediaItem_Take, peakrate: f64, starttime: f64, numchannels: ::std::os::raw::c_int, numsamplesperchannel: ::std::os::raw::c_int, want_extra_type: ::std::os::raw::c_int, buf: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.GetMediaItemTake_Peaks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTake_Peaks) ), Some(f) => f( take, peakrate, starttime, numchannels, numsamplesperchannel, want_extra_type, buf, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTake_Source( &self, take: *mut root::MediaItem_Take, ) -> *mut root::PCM_source { match self.pointers.GetMediaItemTake_Source { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTake_Source) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTake_Track( &self, take: *mut root::MediaItem_Take, ) -> *mut root::MediaTrack { match self.pointers.GetMediaItemTake_Track { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTake_Track) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTakeByGUID( &self, project: *mut root::ReaProject, guid: *const root::GUID, ) -> *mut root::MediaItem_Take { match self.pointers.GetMediaItemTakeByGUID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTakeByGUID) ), Some(f) => f(project, guid), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTakeInfo_Value( &self, take: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, ) -> f64 { match self.pointers.GetMediaItemTakeInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTakeInfo_Value) ), Some(f) => f(take, parmname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaItemTrack(&self, item: *mut root::MediaItem) -> *mut root::MediaTrack { match self.pointers.GetMediaItemTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaItemTrack) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaSourceFileName( &self, source: *mut root::PCM_source, filenamebufOut: *mut ::std::os::raw::c_char, filenamebufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetMediaSourceFileName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaSourceFileName) ), Some(f) => f(source, filenamebufOut, filenamebufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaSourceLength( &self, source: *mut root::PCM_source, lengthIsQNOut: *mut bool, ) -> f64 { match self.pointers.GetMediaSourceLength { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaSourceLength) ), Some(f) => f(source, lengthIsQNOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaSourceNumChannels( &self, source: *mut root::PCM_source, ) -> ::std::os::raw::c_int { match self.pointers.GetMediaSourceNumChannels { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaSourceNumChannels) ), Some(f) => f(source), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaSourceParent(&self, src: *mut root::PCM_source) -> *mut root::PCM_source { match self.pointers.GetMediaSourceParent { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaSourceParent) ), Some(f) => f(src), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaSourceSampleRate( &self, source: *mut root::PCM_source, ) -> ::std::os::raw::c_int { match self.pointers.GetMediaSourceSampleRate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaSourceSampleRate) ), Some(f) => f(source), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaSourceType( &self, source: *mut root::PCM_source, typebufOut: *mut ::std::os::raw::c_char, typebufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetMediaSourceType { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaSourceType) ), Some(f) => f(source, typebufOut, typebufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMediaTrackInfo_Value( &self, tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, ) -> f64 { match self.pointers.GetMediaTrackInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMediaTrackInfo_Value) ), Some(f) => f(tr, parmname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMIDIInputName( &self, dev: ::std::os::raw::c_int, nameout: *mut ::std::os::raw::c_char, nameout_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetMIDIInputName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMIDIInputName) ), Some(f) => f(dev, nameout, nameout_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMIDIOutputName( &self, dev: ::std::os::raw::c_int, nameout: *mut ::std::os::raw::c_char, nameout_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetMIDIOutputName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMIDIOutputName) ), Some(f) => f(dev, nameout, nameout_sz), } } pub fn GetMixerScroll(&self) -> *mut root::MediaTrack { match self.pointers.GetMixerScroll { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMixerScroll) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMouseModifier( &self, context: *const ::std::os::raw::c_char, modifier_flag: ::std::os::raw::c_int, actionOut: *mut ::std::os::raw::c_char, actionOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetMouseModifier { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMouseModifier) ), Some(f) => f(context, modifier_flag, actionOut, actionOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetMousePosition( &self, xOut: *mut ::std::os::raw::c_int, yOut: *mut ::std::os::raw::c_int, ) { match self.pointers.GetMousePosition { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMousePosition) ), Some(f) => f(xOut, yOut), } } pub fn GetNumAudioInputs(&self) -> ::std::os::raw::c_int { match self.pointers.GetNumAudioInputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetNumAudioInputs) ), Some(f) => f(), } } pub fn GetNumAudioOutputs(&self) -> ::std::os::raw::c_int { match self.pointers.GetNumAudioOutputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetNumAudioOutputs) ), Some(f) => f(), } } pub fn GetNumMIDIInputs(&self) -> ::std::os::raw::c_int { match self.pointers.GetNumMIDIInputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetNumMIDIInputs) ), Some(f) => f(), } } pub fn GetNumMIDIOutputs(&self) -> ::std::os::raw::c_int { match self.pointers.GetNumMIDIOutputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetNumMIDIOutputs) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetNumTakeMarkers( &self, take: *mut root::MediaItem_Take, ) -> ::std::os::raw::c_int { match self.pointers.GetNumTakeMarkers { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetNumTakeMarkers) ), Some(f) => f(take), } } pub fn GetNumTracks(&self) -> ::std::os::raw::c_int { match self.pointers.GetNumTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetNumTracks) ), Some(f) => f(), } } pub fn GetOS(&self) -> *const ::std::os::raw::c_char { match self.pointers.GetOS { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetOS) ), Some(f) => f(), } } pub fn GetOutputChannelName( &self, channelIndex: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.GetOutputChannelName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetOutputChannelName) ), Some(f) => f(channelIndex), } } pub fn GetOutputLatency(&self) -> f64 { match self.pointers.GetOutputLatency { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetOutputLatency) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetParentTrack(&self, track: *mut root::MediaTrack) -> *mut root::MediaTrack { match self.pointers.GetParentTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetParentTrack) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPeakFileName( &self, fn_: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetPeakFileName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPeakFileName) ), Some(f) => f(fn_, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPeakFileNameEx( &self, fn_: *const ::std::os::raw::c_char, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, forWrite: bool, ) { match self.pointers.GetPeakFileNameEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPeakFileNameEx) ), Some(f) => f(fn_, buf, buf_sz, forWrite), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPeakFileNameEx2( &self, fn_: *const ::std::os::raw::c_char, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, forWrite: bool, peaksfileextension: *const ::std::os::raw::c_char, ) { match self.pointers.GetPeakFileNameEx2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPeakFileNameEx2) ), Some(f) => f(fn_, buf, buf_sz, forWrite, peaksfileextension), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPeaksBitmap( &self, pks: *mut root::PCM_source_peaktransfer_t, maxamp: f64, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, bmp: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetPeaksBitmap { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPeaksBitmap) ), Some(f) => f(pks, maxamp, w, h, bmp), } } pub fn GetPlayPosition(&self) -> f64 { match self.pointers.GetPlayPosition { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPlayPosition) ), Some(f) => f(), } } pub fn GetPlayPosition2(&self) -> f64 { match self.pointers.GetPlayPosition2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPlayPosition2) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPlayPosition2Ex(&self, proj: *mut root::ReaProject) -> f64 { match self.pointers.GetPlayPosition2Ex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPlayPosition2Ex) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPlayPositionEx(&self, proj: *mut root::ReaProject) -> f64 { match self.pointers.GetPlayPositionEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPlayPositionEx) ), Some(f) => f(proj), } } pub fn GetPlayState(&self) -> ::std::os::raw::c_int { match self.pointers.GetPlayState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPlayState) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPlayStateEx(&self, proj: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.GetPlayStateEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPlayStateEx) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPreferredDiskReadMode( &self, mode: *mut ::std::os::raw::c_int, nb: *mut ::std::os::raw::c_int, bs: *mut ::std::os::raw::c_int, ) { match self.pointers.GetPreferredDiskReadMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPreferredDiskReadMode) ), Some(f) => f(mode, nb, bs), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPreferredDiskReadModePeak( &self, mode: *mut ::std::os::raw::c_int, nb: *mut ::std::os::raw::c_int, bs: *mut ::std::os::raw::c_int, ) { match self.pointers.GetPreferredDiskReadModePeak { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPreferredDiskReadModePeak) ), Some(f) => f(mode, nb, bs), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetPreferredDiskWriteMode( &self, mode: *mut ::std::os::raw::c_int, nb: *mut ::std::os::raw::c_int, bs: *mut ::std::os::raw::c_int, ) { match self.pointers.GetPreferredDiskWriteMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetPreferredDiskWriteMode) ), Some(f) => f(mode, nb, bs), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectLength(&self, proj: *mut root::ReaProject) -> f64 { match self.pointers.GetProjectLength { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectLength) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectName( &self, proj: *mut root::ReaProject, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetProjectName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectName) ), Some(f) => f(proj, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectPath( &self, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetProjectPath { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectPath) ), Some(f) => f(bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectPathEx( &self, proj: *mut root::ReaProject, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) { match self.pointers.GetProjectPathEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectPathEx) ), Some(f) => f(proj, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectStateChangeCount( &self, proj: *mut root::ReaProject, ) -> ::std::os::raw::c_int { match self.pointers.GetProjectStateChangeCount { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectStateChangeCount) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectTimeOffset(&self, proj: *mut root::ReaProject, rndframe: bool) -> f64 { match self.pointers.GetProjectTimeOffset { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectTimeOffset) ), Some(f) => f(proj, rndframe), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectTimeSignature(&self, bpmOut: *mut f64, bpiOut: *mut f64) { match self.pointers.GetProjectTimeSignature { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectTimeSignature) ), Some(f) => f(bpmOut, bpiOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjectTimeSignature2( &self, proj: *mut root::ReaProject, bpmOut: *mut f64, bpiOut: *mut f64, ) { match self.pointers.GetProjectTimeSignature2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjectTimeSignature2) ), Some(f) => f(proj, bpmOut, bpiOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetProjExtState( &self, proj: *mut root::ReaProject, extname: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, valOutNeedBig: *mut ::std::os::raw::c_char, valOutNeedBig_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetProjExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetProjExtState) ), Some(f) => f(proj, extname, key, valOutNeedBig, valOutNeedBig_sz), } } pub fn GetResourcePath(&self) -> *const ::std::os::raw::c_char { match self.pointers.GetResourcePath { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetResourcePath) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSelectedEnvelope( &self, proj: *mut root::ReaProject, ) -> *mut root::TrackEnvelope { match self.pointers.GetSelectedEnvelope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSelectedEnvelope) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSelectedMediaItem( &self, proj: *mut root::ReaProject, selitem: ::std::os::raw::c_int, ) -> *mut root::MediaItem { match self.pointers.GetSelectedMediaItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSelectedMediaItem) ), Some(f) => f(proj, selitem), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSelectedTrack( &self, proj: *mut root::ReaProject, seltrackidx: ::std::os::raw::c_int, ) -> *mut root::MediaTrack { match self.pointers.GetSelectedTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSelectedTrack) ), Some(f) => f(proj, seltrackidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSelectedTrack2( &self, proj: *mut root::ReaProject, seltrackidx: ::std::os::raw::c_int, wantmaster: bool, ) -> *mut root::MediaTrack { match self.pointers.GetSelectedTrack2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSelectedTrack2) ), Some(f) => f(proj, seltrackidx, wantmaster), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSelectedTrackEnvelope( &self, proj: *mut root::ReaProject, ) -> *mut root::TrackEnvelope { match self.pointers.GetSelectedTrackEnvelope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSelectedTrackEnvelope) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSet_ArrangeView2( &self, proj: *mut root::ReaProject, isSet: bool, screen_x_start: ::std::os::raw::c_int, screen_x_end: ::std::os::raw::c_int, start_timeOut: *mut f64, end_timeOut: *mut f64, ) { match self.pointers.GetSet_ArrangeView2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSet_ArrangeView2) ), Some(f) => f( proj, isSet, screen_x_start, screen_x_end, start_timeOut, end_timeOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSet_LoopTimeRange( &self, isSet: bool, isLoop: bool, startOut: *mut f64, endOut: *mut f64, allowautoseek: bool, ) { match self.pointers.GetSet_LoopTimeRange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSet_LoopTimeRange) ), Some(f) => f(isSet, isLoop, startOut, endOut, allowautoseek), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSet_LoopTimeRange2( &self, proj: *mut root::ReaProject, isSet: bool, isLoop: bool, startOut: *mut f64, endOut: *mut f64, allowautoseek: bool, ) { match self.pointers.GetSet_LoopTimeRange2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSet_LoopTimeRange2) ), Some(f) => f(proj, isSet, isLoop, startOut, endOut, allowautoseek), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetAutomationItemInfo( &self, env: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, desc: *const ::std::os::raw::c_char, value: f64, is_set: bool, ) -> f64 { match self.pointers.GetSetAutomationItemInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetAutomationItemInfo) ), Some(f) => f(env, autoitem_idx, desc, value, is_set), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetAutomationItemInfo_String( &self, env: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, desc: *const ::std::os::raw::c_char, valuestrNeedBig: *mut ::std::os::raw::c_char, is_set: bool, ) -> bool { match self.pointers.GetSetAutomationItemInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetAutomationItemInfo_String) ), Some(f) => f(env, autoitem_idx, desc, valuestrNeedBig, is_set), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetEnvelopeInfo_String( &self, env: *mut root::TrackEnvelope, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool { match self.pointers.GetSetEnvelopeInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetEnvelopeInfo_String) ), Some(f) => f(env, parmname, stringNeedBig, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetEnvelopeState( &self, env: *mut root::TrackEnvelope, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetSetEnvelopeState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetEnvelopeState) ), Some(f) => f(env, str, str_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetEnvelopeState2( &self, env: *mut root::TrackEnvelope, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, isundo: bool, ) -> bool { match self.pointers.GetSetEnvelopeState2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetEnvelopeState2) ), Some(f) => f(env, str, str_sz, isundo), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetItemState( &self, item: *mut root::MediaItem, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetSetItemState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetItemState) ), Some(f) => f(item, str, str_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetItemState2( &self, item: *mut root::MediaItem, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, isundo: bool, ) -> bool { match self.pointers.GetSetItemState2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetItemState2) ), Some(f) => f(item, str, str_sz, isundo), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetMediaItemInfo( &self, item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetSetMediaItemInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetMediaItemInfo) ), Some(f) => f(item, parmname, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetMediaItemInfo_String( &self, item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool { match self.pointers.GetSetMediaItemInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetMediaItemInfo_String) ), Some(f) => f(item, parmname, stringNeedBig, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetMediaItemTakeInfo( &self, tk: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetSetMediaItemTakeInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetMediaItemTakeInfo) ), Some(f) => f(tk, parmname, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetMediaItemTakeInfo_String( &self, tk: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool { match self.pointers.GetSetMediaItemTakeInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetMediaItemTakeInfo_String) ), Some(f) => f(tk, parmname, stringNeedBig, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetMediaTrackInfo( &self, tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetSetMediaTrackInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetMediaTrackInfo) ), Some(f) => f(tr, parmname, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetMediaTrackInfo_String( &self, tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool { match self.pointers.GetSetMediaTrackInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetMediaTrackInfo_String) ), Some(f) => f(tr, parmname, stringNeedBig, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetObjectState( &self, obj: *mut ::std::os::raw::c_void, str: *const ::std::os::raw::c_char, ) -> *mut ::std::os::raw::c_char { match self.pointers.GetSetObjectState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetObjectState) ), Some(f) => f(obj, str), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetObjectState2( &self, obj: *mut ::std::os::raw::c_void, str: *const ::std::os::raw::c_char, isundo: bool, ) -> *mut ::std::os::raw::c_char { match self.pointers.GetSetObjectState2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetObjectState2) ), Some(f) => f(obj, str, isundo), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetProjectAuthor( &self, proj: *mut root::ReaProject, set: bool, author: *mut ::std::os::raw::c_char, author_sz: ::std::os::raw::c_int, ) { match self.pointers.GetSetProjectAuthor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetProjectAuthor) ), Some(f) => f(proj, set, author, author_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetProjectGrid( &self, project: *mut root::ReaProject, set: bool, divisionInOutOptional: *mut f64, swingmodeInOutOptional: *mut ::std::os::raw::c_int, swingamtInOutOptional: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.GetSetProjectGrid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetProjectGrid) ), Some(f) => f( project, set, divisionInOutOptional, swingmodeInOutOptional, swingamtInOutOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetProjectInfo( &self, project: *mut root::ReaProject, desc: *const ::std::os::raw::c_char, value: f64, is_set: bool, ) -> f64 { match self.pointers.GetSetProjectInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetProjectInfo) ), Some(f) => f(project, desc, value, is_set), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetProjectInfo_String( &self, project: *mut root::ReaProject, desc: *const ::std::os::raw::c_char, valuestrNeedBig: *mut ::std::os::raw::c_char, is_set: bool, ) -> bool { match self.pointers.GetSetProjectInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetProjectInfo_String) ), Some(f) => f(project, desc, valuestrNeedBig, is_set), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetProjectNotes( &self, proj: *mut root::ReaProject, set: bool, notesNeedBig: *mut ::std::os::raw::c_char, notesNeedBig_sz: ::std::os::raw::c_int, ) { match self.pointers.GetSetProjectNotes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetProjectNotes) ), Some(f) => f(proj, set, notesNeedBig, notesNeedBig_sz), } } pub fn GetSetRepeat(&self, val: ::std::os::raw::c_int) -> ::std::os::raw::c_int { match self.pointers.GetSetRepeat { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetRepeat) ), Some(f) => f(val), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetRepeatEx( &self, proj: *mut root::ReaProject, val: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetSetRepeatEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetRepeatEx) ), Some(f) => f(proj, val), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackGroupMembership( &self, tr: *mut root::MediaTrack, groupname: *const ::std::os::raw::c_char, setmask: ::std::os::raw::c_uint, setvalue: ::std::os::raw::c_uint, ) -> ::std::os::raw::c_uint { match self.pointers.GetSetTrackGroupMembership { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackGroupMembership) ), Some(f) => f(tr, groupname, setmask, setvalue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackGroupMembershipHigh( &self, tr: *mut root::MediaTrack, groupname: *const ::std::os::raw::c_char, setmask: ::std::os::raw::c_uint, setvalue: ::std::os::raw::c_uint, ) -> ::std::os::raw::c_uint { match self.pointers.GetSetTrackGroupMembershipHigh { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackGroupMembershipHigh) ), Some(f) => f(tr, groupname, setmask, setvalue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackMIDISupportFile( &self, proj: *mut root::ReaProject, track: *mut root::MediaTrack, which: ::std::os::raw::c_int, filename: *const ::std::os::raw::c_char, ) -> *const ::std::os::raw::c_char { match self.pointers.GetSetTrackMIDISupportFile { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackMIDISupportFile) ), Some(f) => f(proj, track, which, filename), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackSendInfo( &self, tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void { match self.pointers.GetSetTrackSendInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackSendInfo) ), Some(f) => f(tr, category, sendidx, parmname, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackSendInfo_String( &self, tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool { match self.pointers.GetSetTrackSendInfo_String { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackSendInfo_String) ), Some(f) => f(tr, category, sendidx, parmname, stringNeedBig, setNewValue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackState( &self, track: *mut root::MediaTrack, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetSetTrackState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackState) ), Some(f) => f(track, str, str_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSetTrackState2( &self, track: *mut root::MediaTrack, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, isundo: bool, ) -> bool { match self.pointers.GetSetTrackState2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSetTrackState2) ), Some(f) => f(track, str, str_sz, isundo), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetSubProjectFromSource( &self, src: *mut root::PCM_source, ) -> *mut root::ReaProject { match self.pointers.GetSubProjectFromSource { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetSubProjectFromSource) ), Some(f) => f(src), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTake( &self, item: *mut root::MediaItem, takeidx: ::std::os::raw::c_int, ) -> *mut root::MediaItem_Take { match self.pointers.GetTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTake) ), Some(f) => f(item, takeidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeEnvelope( &self, take: *mut root::MediaItem_Take, envidx: ::std::os::raw::c_int, ) -> *mut root::TrackEnvelope { match self.pointers.GetTakeEnvelope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeEnvelope) ), Some(f) => f(take, envidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeEnvelopeByName( &self, take: *mut root::MediaItem_Take, envname: *const ::std::os::raw::c_char, ) -> *mut root::TrackEnvelope { match self.pointers.GetTakeEnvelopeByName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeEnvelopeByName) ), Some(f) => f(take, envname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeMarker( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, nameOut: *mut ::std::os::raw::c_char, nameOut_sz: ::std::os::raw::c_int, colorOutOptional: *mut ::std::os::raw::c_int, ) -> f64 { match self.pointers.GetTakeMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeMarker) ), Some(f) => f(take, idx, nameOut, nameOut_sz, colorOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeName( &self, take: *mut root::MediaItem_Take, ) -> *const ::std::os::raw::c_char { match self.pointers.GetTakeName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeName) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeNumStretchMarkers( &self, take: *mut root::MediaItem_Take, ) -> ::std::os::raw::c_int { match self.pointers.GetTakeNumStretchMarkers { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeNumStretchMarkers) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeStretchMarker( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, posOut: *mut f64, srcposOutOptional: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.GetTakeStretchMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeStretchMarker) ), Some(f) => f(take, idx, posOut, srcposOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTakeStretchMarkerSlope( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, ) -> f64 { match self.pointers.GetTakeStretchMarkerSlope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTakeStretchMarkerSlope) ), Some(f) => f(take, idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTCPFXParm( &self, project: *mut root::ReaProject, track: *mut root::MediaTrack, index: ::std::os::raw::c_int, fxindexOut: *mut ::std::os::raw::c_int, parmidxOut: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.GetTCPFXParm { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTCPFXParm) ), Some(f) => f(project, track, index, fxindexOut, parmidxOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTempoMatchPlayRate( &self, source: *mut root::PCM_source, srcscale: f64, position: f64, mult: f64, rateOut: *mut f64, targetlenOut: *mut f64, ) -> bool { match self.pointers.GetTempoMatchPlayRate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTempoMatchPlayRate) ), Some(f) => f(source, srcscale, position, mult, rateOut, targetlenOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTempoTimeSigMarker( &self, proj: *mut root::ReaProject, ptidx: ::std::os::raw::c_int, timeposOut: *mut f64, measureposOut: *mut ::std::os::raw::c_int, beatposOut: *mut f64, bpmOut: *mut f64, timesig_numOut: *mut ::std::os::raw::c_int, timesig_denomOut: *mut ::std::os::raw::c_int, lineartempoOut: *mut bool, ) -> bool { match self.pointers.GetTempoTimeSigMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTempoTimeSigMarker) ), Some(f) => f( proj, ptidx, timeposOut, measureposOut, beatposOut, bpmOut, timesig_numOut, timesig_denomOut, lineartempoOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetThemeColor( &self, ini_key: *const ::std::os::raw::c_char, flagsOptional: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetThemeColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetThemeColor) ), Some(f) => f(ini_key, flagsOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetThingFromPoint( &self, screen_x: ::std::os::raw::c_int, screen_y: ::std::os::raw::c_int, infoOut: *mut ::std::os::raw::c_char, infoOut_sz: ::std::os::raw::c_int, ) -> *mut root::MediaTrack { match self.pointers.GetThingFromPoint { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetThingFromPoint) ), Some(f) => f(screen_x, screen_y, infoOut, infoOut_sz), } } pub fn GetToggleCommandState( &self, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetToggleCommandState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetToggleCommandState) ), Some(f) => f(command_id), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetToggleCommandState2( &self, section: *mut root::KbdSectionInfo, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetToggleCommandState2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetToggleCommandState2) ), Some(f) => f(section, command_id), } } pub fn GetToggleCommandStateEx( &self, section_id: ::std::os::raw::c_int, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetToggleCommandStateEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetToggleCommandStateEx) ), Some(f) => f(section_id, command_id), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetToggleCommandStateThroughHooks( &self, section: *mut root::KbdSectionInfo, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetToggleCommandStateThroughHooks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetToggleCommandStateThroughHooks) ), Some(f) => f(section, command_id), } } pub fn GetTooltipWindow(&self) -> root::HWND { match self.pointers.GetTooltipWindow { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTooltipWindow) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrack( &self, proj: *mut root::ReaProject, trackidx: ::std::os::raw::c_int, ) -> *mut root::MediaTrack { match self.pointers.GetTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrack) ), Some(f) => f(proj, trackidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackAutomationMode( &self, tr: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.GetTrackAutomationMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackAutomationMode) ), Some(f) => f(tr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackColor(&self, track: *mut root::MediaTrack) -> ::std::os::raw::c_int { match self.pointers.GetTrackColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackColor) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackDepth(&self, track: *mut root::MediaTrack) -> ::std::os::raw::c_int { match self.pointers.GetTrackDepth { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackDepth) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackEnvelope( &self, track: *mut root::MediaTrack, envidx: ::std::os::raw::c_int, ) -> *mut root::TrackEnvelope { match self.pointers.GetTrackEnvelope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackEnvelope) ), Some(f) => f(track, envidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackEnvelopeByChunkName( &self, tr: *mut root::MediaTrack, cfgchunkname_or_guid: *const ::std::os::raw::c_char, ) -> *mut root::TrackEnvelope { match self.pointers.GetTrackEnvelopeByChunkName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackEnvelopeByChunkName) ), Some(f) => f(tr, cfgchunkname_or_guid), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackEnvelopeByName( &self, track: *mut root::MediaTrack, envname: *const ::std::os::raw::c_char, ) -> *mut root::TrackEnvelope { match self.pointers.GetTrackEnvelopeByName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackEnvelopeByName) ), Some(f) => f(track, envname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackFromPoint( &self, screen_x: ::std::os::raw::c_int, screen_y: ::std::os::raw::c_int, infoOutOptional: *mut ::std::os::raw::c_int, ) -> *mut root::MediaTrack { match self.pointers.GetTrackFromPoint { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackFromPoint) ), Some(f) => f(screen_x, screen_y, infoOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackGUID(&self, tr: *mut root::MediaTrack) -> *mut root::GUID { match self.pointers.GetTrackGUID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackGUID) ), Some(f) => f(tr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackInfo( &self, track: root::INT_PTR, flags: *mut ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.GetTrackInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackInfo) ), Some(f) => f(track, flags), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackMediaItem( &self, tr: *mut root::MediaTrack, itemidx: ::std::os::raw::c_int, ) -> *mut root::MediaItem { match self.pointers.GetTrackMediaItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackMediaItem) ), Some(f) => f(tr, itemidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackMIDILyrics( &self, track: *mut root::MediaTrack, flag: ::std::os::raw::c_int, bufOutWantNeedBig: *mut ::std::os::raw::c_char, bufOutWantNeedBig_sz: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.GetTrackMIDILyrics { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackMIDILyrics) ), Some(f) => f(track, flag, bufOutWantNeedBig, bufOutWantNeedBig_sz), } } pub fn GetTrackMIDINoteName( &self, track: ::std::os::raw::c_int, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.GetTrackMIDINoteName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackMIDINoteName) ), Some(f) => f(track, pitch, chan), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackMIDINoteNameEx( &self, proj: *mut root::ReaProject, track: *mut root::MediaTrack, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.GetTrackMIDINoteNameEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackMIDINoteNameEx) ), Some(f) => f(proj, track, pitch, chan), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackMIDINoteRange( &self, proj: *mut root::ReaProject, track: *mut root::MediaTrack, note_loOut: *mut ::std::os::raw::c_int, note_hiOut: *mut ::std::os::raw::c_int, ) { match self.pointers.GetTrackMIDINoteRange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackMIDINoteRange) ), Some(f) => f(proj, track, note_loOut, note_hiOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackName( &self, track: *mut root::MediaTrack, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetTrackName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackName) ), Some(f) => f(track, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackNumMediaItems(&self, tr: *mut root::MediaTrack) -> ::std::os::raw::c_int { match self.pointers.GetTrackNumMediaItems { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackNumMediaItems) ), Some(f) => f(tr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackNumSends( &self, tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GetTrackNumSends { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackNumSends) ), Some(f) => f(tr, category), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackReceiveName( &self, track: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetTrackReceiveName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackReceiveName) ), Some(f) => f(track, recv_index, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackReceiveUIMute( &self, track: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, muteOut: *mut bool, ) -> bool { match self.pointers.GetTrackReceiveUIMute { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackReceiveUIMute) ), Some(f) => f(track, recv_index, muteOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackReceiveUIVolPan( &self, track: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, volumeOut: *mut f64, panOut: *mut f64, ) -> bool { match self.pointers.GetTrackReceiveUIVolPan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackReceiveUIVolPan) ), Some(f) => f(track, recv_index, volumeOut, panOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackSendInfo_Value( &self, tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, ) -> f64 { match self.pointers.GetTrackSendInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackSendInfo_Value) ), Some(f) => f(tr, category, sendidx, parmname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackSendName( &self, track: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetTrackSendName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackSendName) ), Some(f) => f(track, send_index, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackSendUIMute( &self, track: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, muteOut: *mut bool, ) -> bool { match self.pointers.GetTrackSendUIMute { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackSendUIMute) ), Some(f) => f(track, send_index, muteOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackSendUIVolPan( &self, track: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, volumeOut: *mut f64, panOut: *mut f64, ) -> bool { match self.pointers.GetTrackSendUIVolPan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackSendUIVolPan) ), Some(f) => f(track, send_index, volumeOut, panOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackState( &self, track: *mut root::MediaTrack, flagsOut: *mut ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.GetTrackState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackState) ), Some(f) => f(track, flagsOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackStateChunk( &self, track: *mut root::MediaTrack, strNeedBig: *mut ::std::os::raw::c_char, strNeedBig_sz: ::std::os::raw::c_int, isundoOptional: bool, ) -> bool { match self.pointers.GetTrackStateChunk { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackStateChunk) ), Some(f) => f(track, strNeedBig, strNeedBig_sz, isundoOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackUIMute(&self, track: *mut root::MediaTrack, muteOut: *mut bool) -> bool { match self.pointers.GetTrackUIMute { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackUIMute) ), Some(f) => f(track, muteOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackUIPan( &self, track: *mut root::MediaTrack, pan1Out: *mut f64, pan2Out: *mut f64, panmodeOut: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.GetTrackUIPan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackUIPan) ), Some(f) => f(track, pan1Out, pan2Out, panmodeOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetTrackUIVolPan( &self, track: *mut root::MediaTrack, volumeOut: *mut f64, panOut: *mut f64, ) -> bool { match self.pointers.GetTrackUIVolPan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetTrackUIVolPan) ), Some(f) => f(track, volumeOut, panOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetUnderrunTime( &self, audio_xrunOutOptional: *mut ::std::os::raw::c_uint, media_xrunOutOptional: *mut ::std::os::raw::c_uint, curtimeOutOptional: *mut ::std::os::raw::c_uint, ) { match self.pointers.GetUnderrunTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetUnderrunTime) ), Some(f) => f( audio_xrunOutOptional, media_xrunOutOptional, curtimeOutOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetUserFileNameForRead( &self, filenameNeed4096: *mut ::std::os::raw::c_char, title: *const ::std::os::raw::c_char, defext: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.GetUserFileNameForRead { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetUserFileNameForRead) ), Some(f) => f(filenameNeed4096, title, defext), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GetUserInputs( &self, title: *const ::std::os::raw::c_char, num_inputs: ::std::os::raw::c_int, captions_csv: *const ::std::os::raw::c_char, retvals_csv: *mut ::std::os::raw::c_char, retvals_csv_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.GetUserInputs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetUserInputs) ), Some(f) => f(title, num_inputs, captions_csv, retvals_csv, retvals_csv_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GoToMarker( &self, proj: *mut root::ReaProject, marker_index: ::std::os::raw::c_int, use_timeline_order: bool, ) { match self.pointers.GoToMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GoToMarker) ), Some(f) => f(proj, marker_index, use_timeline_order), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GoToRegion( &self, proj: *mut root::ReaProject, region_index: ::std::os::raw::c_int, use_timeline_order: bool, ) { match self.pointers.GoToRegion { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GoToRegion) ), Some(f) => f(proj, region_index, use_timeline_order), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn GR_SelectColor( &self, hwnd: root::HWND, colorOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.GR_SelectColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GR_SelectColor) ), Some(f) => f(hwnd, colorOut), } } pub fn GSC_mainwnd(&self, t: ::std::os::raw::c_int) -> ::std::os::raw::c_int { match self.pointers.GSC_mainwnd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GSC_mainwnd) ), Some(f) => f(t), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn guidToString( &self, g: *const root::GUID, destNeed64: *mut ::std::os::raw::c_char, ) { match self.pointers.guidToString { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(guidToString) ), Some(f) => f(g, destNeed64), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn HasExtState( &self, section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.HasExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(HasExtState) ), Some(f) => f(section, key), } } pub fn HasTrackMIDIPrograms( &self, track: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.HasTrackMIDIPrograms { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(HasTrackMIDIPrograms) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn HasTrackMIDIProgramsEx( &self, proj: *mut root::ReaProject, track: *mut root::MediaTrack, ) -> *const ::std::os::raw::c_char { match self.pointers.HasTrackMIDIProgramsEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(HasTrackMIDIProgramsEx) ), Some(f) => f(proj, track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Help_Set( &self, helpstring: *const ::std::os::raw::c_char, is_temporary_help: bool, ) { match self.pointers.Help_Set { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Help_Set) ), Some(f) => f(helpstring, is_temporary_help), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn HiresPeaksFromSource( &self, src: *mut root::PCM_source, block: *mut root::PCM_source_peaktransfer_t, ) { match self.pointers.HiresPeaksFromSource { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(HiresPeaksFromSource) ), Some(f) => f(src, block), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn image_resolve_fn( &self, in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, ) { match self.pointers.image_resolve_fn { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(image_resolve_fn) ), Some(f) => f(in_, out, out_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn InsertAutomationItem( &self, env: *mut root::TrackEnvelope, pool_id: ::std::os::raw::c_int, position: f64, length: f64, ) -> ::std::os::raw::c_int { match self.pointers.InsertAutomationItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InsertAutomationItem) ), Some(f) => f(env, pool_id, position, length), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn InsertEnvelopePoint( &self, envelope: *mut root::TrackEnvelope, time: f64, value: f64, shape: ::std::os::raw::c_int, tension: f64, selected: bool, noSortInOptional: *mut bool, ) -> bool { match self.pointers.InsertEnvelopePoint { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InsertEnvelopePoint) ), Some(f) => f( envelope, time, value, shape, tension, selected, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn InsertEnvelopePointEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, time: f64, value: f64, shape: ::std::os::raw::c_int, tension: f64, selected: bool, noSortInOptional: *mut bool, ) -> bool { match self.pointers.InsertEnvelopePointEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InsertEnvelopePointEx) ), Some(f) => f( envelope, autoitem_idx, time, value, shape, tension, selected, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn InsertMedia( &self, file: *const ::std::os::raw::c_char, mode: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.InsertMedia { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InsertMedia) ), Some(f) => f(file, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn InsertMediaSection( &self, file: *const ::std::os::raw::c_char, mode: ::std::os::raw::c_int, startpct: f64, endpct: f64, pitchshift: f64, ) -> ::std::os::raw::c_int { match self.pointers.InsertMediaSection { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InsertMediaSection) ), Some(f) => f(file, mode, startpct, endpct, pitchshift), } } pub fn InsertTrackAtIndex(&self, idx: ::std::os::raw::c_int, wantDefaults: bool) { match self.pointers.InsertTrackAtIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InsertTrackAtIndex) ), Some(f) => f(idx, wantDefaults), } } pub fn IsInRealTimeAudio(&self) -> ::std::os::raw::c_int { match self.pointers.IsInRealTimeAudio { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsInRealTimeAudio) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn IsItemTakeActiveForPlayback( &self, item: *mut root::MediaItem, take: *mut root::MediaItem_Take, ) -> bool { match self.pointers.IsItemTakeActiveForPlayback { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsItemTakeActiveForPlayback) ), Some(f) => f(item, take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn IsMediaExtension( &self, ext: *const ::std::os::raw::c_char, wantOthers: bool, ) -> bool { match self.pointers.IsMediaExtension { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsMediaExtension) ), Some(f) => f(ext, wantOthers), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn IsMediaItemSelected(&self, item: *mut root::MediaItem) -> bool { match self.pointers.IsMediaItemSelected { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsMediaItemSelected) ), Some(f) => f(item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn IsProjectDirty(&self, proj: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.IsProjectDirty { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsProjectDirty) ), Some(f) => f(proj), } } pub fn IsREAPER(&self) -> bool { match self.pointers.IsREAPER { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsREAPER) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn IsTrackSelected(&self, track: *mut root::MediaTrack) -> bool { match self.pointers.IsTrackSelected { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsTrackSelected) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn IsTrackVisible(&self, track: *mut root::MediaTrack, mixer: bool) -> bool { match self.pointers.IsTrackVisible { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(IsTrackVisible) ), Some(f) => f(track, mixer), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_create( &self, guid: *const root::GUID, ) -> *mut root::reaper_functions::joystick_device { match self.pointers.joystick_create { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_create) ), Some(f) => f(guid), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_destroy(&self, device: *mut root::reaper_functions::joystick_device) { match self.pointers.joystick_destroy { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_destroy) ), Some(f) => f(device), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_enum( &self, index: ::std::os::raw::c_int, namestrOutOptional: *mut *const ::std::os::raw::c_char, ) -> *const ::std::os::raw::c_char { match self.pointers.joystick_enum { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_enum) ), Some(f) => f(index, namestrOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_getaxis( &self, dev: *mut root::reaper_functions::joystick_device, axis: ::std::os::raw::c_int, ) -> f64 { match self.pointers.joystick_getaxis { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_getaxis) ), Some(f) => f(dev, axis), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_getbuttonmask( &self, dev: *mut root::reaper_functions::joystick_device, ) -> ::std::os::raw::c_uint { match self.pointers.joystick_getbuttonmask { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_getbuttonmask) ), Some(f) => f(dev), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_getinfo( &self, dev: *mut root::reaper_functions::joystick_device, axesOutOptional: *mut ::std::os::raw::c_int, povsOutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.joystick_getinfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_getinfo) ), Some(f) => f(dev, axesOutOptional, povsOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_getpov( &self, dev: *mut root::reaper_functions::joystick_device, pov: ::std::os::raw::c_int, ) -> f64 { match self.pointers.joystick_getpov { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_getpov) ), Some(f) => f(dev, pov), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn joystick_update( &self, dev: *mut root::reaper_functions::joystick_device, ) -> bool { match self.pointers.joystick_update { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(joystick_update) ), Some(f) => f(dev), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_enumerateActions( &self, section: *mut root::KbdSectionInfo, idx: ::std::os::raw::c_int, nameOut: *mut *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.kbd_enumerateActions { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_enumerateActions) ), Some(f) => f(section, idx, nameOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_formatKeyName(&self, ac: *mut root::ACCEL, s: *mut ::std::os::raw::c_char) { match self.pointers.kbd_formatKeyName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_formatKeyName) ), Some(f) => f(ac, s), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_getCommandName( &self, cmd: ::std::os::raw::c_int, s: *mut ::std::os::raw::c_char, section: *mut root::KbdSectionInfo, ) { match self.pointers.kbd_getCommandName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_getCommandName) ), Some(f) => f(cmd, s, section), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_getTextFromCmd( &self, cmd: root::DWORD, section: *mut root::KbdSectionInfo, ) -> *const ::std::os::raw::c_char { match self.pointers.kbd_getTextFromCmd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_getTextFromCmd) ), Some(f) => f(cmd, section), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn KBD_OnMainActionEx( &self, cmd: ::std::os::raw::c_int, val: ::std::os::raw::c_int, valhw: ::std::os::raw::c_int, relmode: ::std::os::raw::c_int, hwnd: root::HWND, proj: *mut root::ReaProject, ) -> ::std::os::raw::c_int { match self.pointers.KBD_OnMainActionEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(KBD_OnMainActionEx) ), Some(f) => f(cmd, val, valhw, relmode, hwnd, proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_OnMidiEvent( &self, evt: *mut root::MIDI_event_t, dev_index: ::std::os::raw::c_int, ) { match self.pointers.kbd_OnMidiEvent { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_OnMidiEvent) ), Some(f) => f(evt, dev_index), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_OnMidiList( &self, list: *mut root::MIDI_eventlist, dev_index: ::std::os::raw::c_int, ) { match self.pointers.kbd_OnMidiList { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_OnMidiList) ), Some(f) => f(list, dev_index), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_ProcessActionsMenu( &self, menu: root::HMENU, section: *mut root::KbdSectionInfo, ) { match self.pointers.kbd_ProcessActionsMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_ProcessActionsMenu) ), Some(f) => f(menu, section), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_processMidiEventActionEx( &self, evt: *mut root::MIDI_event_t, section: *mut root::KbdSectionInfo, hwndCtx: root::HWND, ) -> bool { match self.pointers.kbd_processMidiEventActionEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_processMidiEventActionEx) ), Some(f) => f(evt, section, hwndCtx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_reprocessMenu(&self, menu: root::HMENU, section: *mut root::KbdSectionInfo) { match self.pointers.kbd_reprocessMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_reprocessMenu) ), Some(f) => f(menu, section), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_RunCommandThroughHooks( &self, section: *mut root::KbdSectionInfo, actionCommandID: *mut ::std::os::raw::c_int, val: *mut ::std::os::raw::c_int, valhw: *mut ::std::os::raw::c_int, relmode: *mut ::std::os::raw::c_int, hwnd: root::HWND, ) -> bool { match self.pointers.kbd_RunCommandThroughHooks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_RunCommandThroughHooks) ), Some(f) => f(section, actionCommandID, val, valhw, relmode, hwnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_translateAccelerator( &self, hwnd: root::HWND, msg: *mut root::MSG, section: *mut root::KbdSectionInfo, ) -> ::std::os::raw::c_int { match self.pointers.kbd_translateAccelerator { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_translateAccelerator) ), Some(f) => f(hwnd, msg, section), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn kbd_translateMouse( &self, winmsg: *mut ::std::os::raw::c_void, midimsg: *mut ::std::os::raw::c_uchar, ) -> bool { match self.pointers.kbd_translateMouse { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(kbd_translateMouse) ), Some(f) => f(winmsg, midimsg), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__Destroy(&self, bm: *mut root::reaper_functions::LICE_IBitmap) { match self.pointers.LICE__Destroy { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__Destroy) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__DestroyFont(&self, font: *mut root::reaper_functions::LICE_IFont) { match self.pointers.LICE__DestroyFont { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__DestroyFont) ), Some(f) => f(font), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__DrawText( &self, font: *mut root::reaper_functions::LICE_IFont, bm: *mut root::reaper_functions::LICE_IBitmap, str: *const ::std::os::raw::c_char, strcnt: ::std::os::raw::c_int, rect: *mut root::RECT, dtFlags: root::UINT, ) -> ::std::os::raw::c_int { match self.pointers.LICE__DrawText { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__DrawText) ), Some(f) => f(font, bm, str, strcnt, rect, dtFlags), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__GetBits( &self, bm: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut ::std::os::raw::c_void { match self.pointers.LICE__GetBits { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__GetBits) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__GetDC(&self, bm: *mut root::reaper_functions::LICE_IBitmap) -> root::HDC { match self.pointers.LICE__GetDC { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__GetDC) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__GetHeight( &self, bm: *mut root::reaper_functions::LICE_IBitmap, ) -> ::std::os::raw::c_int { match self.pointers.LICE__GetHeight { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__GetHeight) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__GetRowSpan( &self, bm: *mut root::reaper_functions::LICE_IBitmap, ) -> ::std::os::raw::c_int { match self.pointers.LICE__GetRowSpan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__GetRowSpan) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__GetWidth( &self, bm: *mut root::reaper_functions::LICE_IBitmap, ) -> ::std::os::raw::c_int { match self.pointers.LICE__GetWidth { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__GetWidth) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__IsFlipped(&self, bm: *mut root::reaper_functions::LICE_IBitmap) -> bool { match self.pointers.LICE__IsFlipped { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__IsFlipped) ), Some(f) => f(bm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__resize( &self, bm: *mut root::reaper_functions::LICE_IBitmap, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, ) -> bool { match self.pointers.LICE__resize { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__resize) ), Some(f) => f(bm, w, h), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__SetBkColor( &self, font: *mut root::reaper_functions::LICE_IFont, color: root::reaper_functions::LICE_pixel, ) -> root::reaper_functions::LICE_pixel { match self.pointers.LICE__SetBkColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__SetBkColor) ), Some(f) => f(font, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__SetFromHFont( &self, font: *mut root::reaper_functions::LICE_IFont, hfont: root::HFONT, flags: ::std::os::raw::c_int, ) { match self.pointers.LICE__SetFromHFont { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__SetFromHFont) ), Some(f) => f(font, hfont, flags), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__SetTextColor( &self, font: *mut root::reaper_functions::LICE_IFont, color: root::reaper_functions::LICE_pixel, ) -> root::reaper_functions::LICE_pixel { match self.pointers.LICE__SetTextColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__SetTextColor) ), Some(f) => f(font, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE__SetTextCombineMode( &self, ifont: *mut root::reaper_functions::LICE_IFont, mode: ::std::os::raw::c_int, alpha: f32, ) { match self.pointers.LICE__SetTextCombineMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE__SetTextCombineMode) ), Some(f) => f(ifont, mode, alpha), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Arc( &self, dest: *mut root::reaper_functions::LICE_IBitmap, cx: f32, cy: f32, r: f32, minAngle: f32, maxAngle: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ) { match self.pointers.LICE_Arc { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Arc) ), Some(f) => f(dest, cx, cy, r, minAngle, maxAngle, color, alpha, mode, aa), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Blit( &self, dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, srcx: ::std::os::raw::c_int, srcy: ::std::os::raw::c_int, srcw: ::std::os::raw::c_int, srch: ::std::os::raw::c_int, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_Blit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Blit) ), Some(f) => f(dest, src, dstx, dsty, srcx, srcy, srcw, srch, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Blur( &self, dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, srcx: ::std::os::raw::c_int, srcy: ::std::os::raw::c_int, srcw: ::std::os::raw::c_int, srch: ::std::os::raw::c_int, ) { match self.pointers.LICE_Blur { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Blur) ), Some(f) => f(dest, src, dstx, dsty, srcx, srcy, srcw, srch), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_BorderedRect( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, bgcolor: root::reaper_functions::LICE_pixel, fgcolor: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_BorderedRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_BorderedRect) ), Some(f) => f(dest, x, y, w, h, bgcolor, fgcolor, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Circle( &self, dest: *mut root::reaper_functions::LICE_IBitmap, cx: f32, cy: f32, r: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ) { match self.pointers.LICE_Circle { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Circle) ), Some(f) => f(dest, cx, cy, r, color, alpha, mode, aa), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Clear( &self, dest: *mut root::reaper_functions::LICE_IBitmap, color: root::reaper_functions::LICE_pixel, ) { match self.pointers.LICE_Clear { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Clear) ), Some(f) => f(dest, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_ClearRect( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, mask: root::reaper_functions::LICE_pixel, orbits: root::reaper_functions::LICE_pixel, ) { match self.pointers.LICE_ClearRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_ClearRect) ), Some(f) => f(dest, x, y, w, h, mask, orbits), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_ClipLine( &self, pX1Out: *mut ::std::os::raw::c_int, pY1Out: *mut ::std::os::raw::c_int, pX2Out: *mut ::std::os::raw::c_int, pY2Out: *mut ::std::os::raw::c_int, xLo: ::std::os::raw::c_int, yLo: ::std::os::raw::c_int, xHi: ::std::os::raw::c_int, yHi: ::std::os::raw::c_int, ) -> bool { match self.pointers.LICE_ClipLine { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_ClipLine) ), Some(f) => f(pX1Out, pY1Out, pX2Out, pY2Out, xLo, yLo, xHi, yHi), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Copy( &self, dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, ) { match self.pointers.LICE_Copy { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Copy) ), Some(f) => f(dest, src), } } pub fn LICE_CreateBitmap( &self, mode: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, ) -> *mut root::reaper_functions::LICE_IBitmap { match self.pointers.LICE_CreateBitmap { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_CreateBitmap) ), Some(f) => f(mode, w, h), } } pub fn LICE_CreateFont(&self) -> *mut root::reaper_functions::LICE_IFont { match self.pointers.LICE_CreateFont { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_CreateFont) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_DrawCBezier( &self, dest: *mut root::reaper_functions::LICE_IBitmap, xstart: f64, ystart: f64, xctl1: f64, yctl1: f64, xctl2: f64, yctl2: f64, xend: f64, yend: f64, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, tol: f64, ) { match self.pointers.LICE_DrawCBezier { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_DrawCBezier) ), Some(f) => f( dest, xstart, ystart, xctl1, yctl1, xctl2, yctl2, xend, yend, color, alpha, mode, aa, tol, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_DrawChar( &self, bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, c: ::std::os::raw::c_char, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_DrawChar { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_DrawChar) ), Some(f) => f(bm, x, y, c, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_DrawGlyph( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alphas: *mut root::reaper_functions::LICE_pixel_chan, glyph_w: ::std::os::raw::c_int, glyph_h: ::std::os::raw::c_int, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_DrawGlyph { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_DrawGlyph) ), Some(f) => f(dest, x, y, color, alphas, glyph_w, glyph_h, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_DrawRect( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_DrawRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_DrawRect) ), Some(f) => f(dest, x, y, w, h, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_DrawText( &self, bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, string: *const ::std::os::raw::c_char, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_DrawText { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_DrawText) ), Some(f) => f(bm, x, y, string, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_FillCBezier( &self, dest: *mut root::reaper_functions::LICE_IBitmap, xstart: f64, ystart: f64, xctl1: f64, yctl1: f64, xctl2: f64, yctl2: f64, xend: f64, yend: f64, yfill: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, tol: f64, ) { match self.pointers.LICE_FillCBezier { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_FillCBezier) ), Some(f) => f( dest, xstart, ystart, xctl1, yctl1, xctl2, yctl2, xend, yend, yfill, color, alpha, mode, aa, tol, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_FillCircle( &self, dest: *mut root::reaper_functions::LICE_IBitmap, cx: f32, cy: f32, r: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ) { match self.pointers.LICE_FillCircle { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_FillCircle) ), Some(f) => f(dest, cx, cy, r, color, alpha, mode, aa), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_FillConvexPolygon( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: *mut ::std::os::raw::c_int, y: *mut ::std::os::raw::c_int, npoints: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_FillConvexPolygon { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_FillConvexPolygon) ), Some(f) => f(dest, x, y, npoints, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_FillRect( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_FillRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_FillRect) ), Some(f) => f(dest, x, y, w, h, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_FillTrapezoid( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x1a: ::std::os::raw::c_int, x1b: ::std::os::raw::c_int, y1: ::std::os::raw::c_int, x2a: ::std::os::raw::c_int, x2b: ::std::os::raw::c_int, y2: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_FillTrapezoid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_FillTrapezoid) ), Some(f) => f(dest, x1a, x1b, y1, x2a, x2b, y2, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_FillTriangle( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x1: ::std::os::raw::c_int, y1: ::std::os::raw::c_int, x2: ::std::os::raw::c_int, y2: ::std::os::raw::c_int, x3: ::std::os::raw::c_int, y3: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_FillTriangle { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_FillTriangle) ), Some(f) => f(dest, x1, y1, x2, y2, x3, y3, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_GetPixel( &self, bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, ) -> root::reaper_functions::LICE_pixel { match self.pointers.LICE_GetPixel { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_GetPixel) ), Some(f) => f(bm, x, y), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_GradRect( &self, dest: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, dstw: ::std::os::raw::c_int, dsth: ::std::os::raw::c_int, ir: f32, ig: f32, ib: f32, ia: f32, drdx: f32, dgdx: f32, dbdx: f32, dadx: f32, drdy: f32, dgdy: f32, dbdy: f32, dady: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_GradRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_GradRect) ), Some(f) => f( dest, dstx, dsty, dstw, dsth, ir, ig, ib, ia, drdx, dgdx, dbdx, dadx, drdy, dgdy, dbdy, dady, mode, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_Line( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x1: f32, y1: f32, x2: f32, y2: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ) { match self.pointers.LICE_Line { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_Line) ), Some(f) => f(dest, x1, y1, x2, y2, color, alpha, mode, aa), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_LineInt( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x1: ::std::os::raw::c_int, y1: ::std::os::raw::c_int, x2: ::std::os::raw::c_int, y2: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ) { match self.pointers.LICE_LineInt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_LineInt) ), Some(f) => f(dest, x1, y1, x2, y2, color, alpha, mode, aa), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_LoadPNG( &self, filename: *const ::std::os::raw::c_char, bmp: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut root::reaper_functions::LICE_IBitmap { match self.pointers.LICE_LoadPNG { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_LoadPNG) ), Some(f) => f(filename, bmp), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_LoadPNGFromResource( &self, hInst: root::HINSTANCE, resid: *const ::std::os::raw::c_char, bmp: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut root::reaper_functions::LICE_IBitmap { match self.pointers.LICE_LoadPNGFromResource { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_LoadPNGFromResource) ), Some(f) => f(hInst, resid, bmp), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_MeasureText( &self, string: *const ::std::os::raw::c_char, w: *mut ::std::os::raw::c_int, h: *mut ::std::os::raw::c_int, ) { match self.pointers.LICE_MeasureText { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_MeasureText) ), Some(f) => f(string, w, h), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_MultiplyAddRect( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, rsc: f32, gsc: f32, bsc: f32, asc: f32, radd: f32, gadd: f32, badd: f32, aadd: f32, ) { match self.pointers.LICE_MultiplyAddRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_MultiplyAddRect) ), Some(f) => f(dest, x, y, w, h, rsc, gsc, bsc, asc, radd, gadd, badd, aadd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_PutPixel( &self, bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_PutPixel { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_PutPixel) ), Some(f) => f(bm, x, y, color, alpha, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_RotatedBlit( &self, dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, dstw: ::std::os::raw::c_int, dsth: ::std::os::raw::c_int, srcx: f32, srcy: f32, srcw: f32, srch: f32, angle: f32, cliptosourcerect: bool, alpha: f32, mode: ::std::os::raw::c_int, rotxcent: f32, rotycent: f32, ) { match self.pointers.LICE_RotatedBlit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_RotatedBlit) ), Some(f) => f( dest, src, dstx, dsty, dstw, dsth, srcx, srcy, srcw, srch, angle, cliptosourcerect, alpha, mode, rotxcent, rotycent, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_RoundRect( &self, drawbm: *mut root::reaper_functions::LICE_IBitmap, xpos: f32, ypos: f32, w: f32, h: f32, cornerradius: ::std::os::raw::c_int, col: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ) { match self.pointers.LICE_RoundRect { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_RoundRect) ), Some(f) => f(drawbm, xpos, ypos, w, h, cornerradius, col, alpha, mode, aa), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_ScaledBlit( &self, dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, dstw: ::std::os::raw::c_int, dsth: ::std::os::raw::c_int, srcx: f32, srcy: f32, srcw: f32, srch: f32, alpha: f32, mode: ::std::os::raw::c_int, ) { match self.pointers.LICE_ScaledBlit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_ScaledBlit) ), Some(f) => f( dest, src, dstx, dsty, dstw, dsth, srcx, srcy, srcw, srch, alpha, mode, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LICE_SimpleFill( &self, dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, newcolor: root::reaper_functions::LICE_pixel, comparemask: root::reaper_functions::LICE_pixel, keepmask: root::reaper_functions::LICE_pixel, ) { match self.pointers.LICE_SimpleFill { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LICE_SimpleFill) ), Some(f) => f(dest, x, y, newcolor, comparemask, keepmask), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn LocalizeString( &self, src_string: *const ::std::os::raw::c_char, section: *const ::std::os::raw::c_char, flagsOptional: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.LocalizeString { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(LocalizeString) ), Some(f) => f(src_string, section, flagsOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Loop_OnArrow( &self, project: *mut root::ReaProject, direction: ::std::os::raw::c_int, ) -> bool { match self.pointers.Loop_OnArrow { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Loop_OnArrow) ), Some(f) => f(project, direction), } } pub fn Main_OnCommand(&self, command: ::std::os::raw::c_int, flag: ::std::os::raw::c_int) { match self.pointers.Main_OnCommand { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Main_OnCommand) ), Some(f) => f(command, flag), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Main_OnCommandEx( &self, command: ::std::os::raw::c_int, flag: ::std::os::raw::c_int, proj: *mut root::ReaProject, ) { match self.pointers.Main_OnCommandEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Main_OnCommandEx) ), Some(f) => f(command, flag, proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Main_openProject(&self, name: *const ::std::os::raw::c_char) { match self.pointers.Main_openProject { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Main_openProject) ), Some(f) => f(name), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Main_SaveProject( &self, proj: *mut root::ReaProject, forceSaveAsInOptional: bool, ) { match self.pointers.Main_SaveProject { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Main_SaveProject) ), Some(f) => f(proj, forceSaveAsInOptional), } } pub fn Main_UpdateLoopInfo(&self, ignoremask: ::std::os::raw::c_int) { match self.pointers.Main_UpdateLoopInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Main_UpdateLoopInfo) ), Some(f) => f(ignoremask), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MarkProjectDirty(&self, proj: *mut root::ReaProject) { match self.pointers.MarkProjectDirty { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MarkProjectDirty) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MarkTrackItemsDirty( &self, track: *mut root::MediaTrack, item: *mut root::MediaItem, ) { match self.pointers.MarkTrackItemsDirty { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MarkTrackItemsDirty) ), Some(f) => f(track, item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Master_GetPlayRate(&self, project: *mut root::ReaProject) -> f64 { match self.pointers.Master_GetPlayRate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Master_GetPlayRate) ), Some(f) => f(project), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Master_GetPlayRateAtTime(&self, time_s: f64, proj: *mut root::ReaProject) -> f64 { match self.pointers.Master_GetPlayRateAtTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Master_GetPlayRateAtTime) ), Some(f) => f(time_s, proj), } } pub fn Master_GetTempo(&self) -> f64 { match self.pointers.Master_GetTempo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Master_GetTempo) ), Some(f) => f(), } } pub fn Master_NormalizePlayRate(&self, playrate: f64, isnormalized: bool) -> f64 { match self.pointers.Master_NormalizePlayRate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Master_NormalizePlayRate) ), Some(f) => f(playrate, isnormalized), } } pub fn Master_NormalizeTempo(&self, bpm: f64, isnormalized: bool) -> f64 { match self.pointers.Master_NormalizeTempo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Master_NormalizeTempo) ), Some(f) => f(bpm, isnormalized), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MB( &self, msg: *const ::std::os::raw::c_char, title: *const ::std::os::raw::c_char, type_: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.MB { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MB) ), Some(f) => f(msg, title, type_), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MediaItemDescendsFromTrack( &self, item: *mut root::MediaItem, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.MediaItemDescendsFromTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MediaItemDescendsFromTrack) ), Some(f) => f(item, track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_CountEvts( &self, take: *mut root::MediaItem_Take, notecntOut: *mut ::std::os::raw::c_int, ccevtcntOut: *mut ::std::os::raw::c_int, textsyxevtcntOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.MIDI_CountEvts { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_CountEvts) ), Some(f) => f(take, notecntOut, ccevtcntOut, textsyxevtcntOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_DeleteCC( &self, take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_DeleteCC { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_DeleteCC) ), Some(f) => f(take, ccidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_DeleteEvt( &self, take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_DeleteEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_DeleteEvt) ), Some(f) => f(take, evtidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_DeleteNote( &self, take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_DeleteNote { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_DeleteNote) ), Some(f) => f(take, noteidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_DeleteTextSysexEvt( &self, take: *mut root::MediaItem_Take, textsyxevtidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_DeleteTextSysexEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_DeleteTextSysexEvt) ), Some(f) => f(take, textsyxevtidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_DisableSort(&self, take: *mut root::MediaItem_Take) { match self.pointers.MIDI_DisableSort { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_DisableSort) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_EnumSelCC( &self, take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.MIDI_EnumSelCC { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_EnumSelCC) ), Some(f) => f(take, ccidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_EnumSelEvts( &self, take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.MIDI_EnumSelEvts { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_EnumSelEvts) ), Some(f) => f(take, evtidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_EnumSelNotes( &self, take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.MIDI_EnumSelNotes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_EnumSelNotes) ), Some(f) => f(take, noteidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_EnumSelTextSysexEvts( &self, take: *mut root::MediaItem_Take, textsyxidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.MIDI_EnumSelTextSysexEvts { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_EnumSelTextSysexEvts) ), Some(f) => f(take, textsyxidx), } } pub fn MIDI_eventlist_Create(&self) -> *mut root::MIDI_eventlist { match self.pointers.MIDI_eventlist_Create { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_eventlist_Create) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_eventlist_Destroy(&self, evtlist: *mut root::MIDI_eventlist) { match self.pointers.MIDI_eventlist_Destroy { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_eventlist_Destroy) ), Some(f) => f(evtlist), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetAllEvts( &self, take: *mut root::MediaItem_Take, bufOutNeedBig: *mut ::std::os::raw::c_char, bufOutNeedBig_sz: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetAllEvts { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetAllEvts) ), Some(f) => f(take, bufOutNeedBig, bufOutNeedBig_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetCC( &self, take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, selectedOut: *mut bool, mutedOut: *mut bool, ppqposOut: *mut f64, chanmsgOut: *mut ::std::os::raw::c_int, chanOut: *mut ::std::os::raw::c_int, msg2Out: *mut ::std::os::raw::c_int, msg3Out: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetCC { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetCC) ), Some(f) => f( take, ccidx, selectedOut, mutedOut, ppqposOut, chanmsgOut, chanOut, msg2Out, msg3Out, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetCCShape( &self, take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, shapeOut: *mut ::std::os::raw::c_int, beztensionOut: *mut f64, ) -> bool { match self.pointers.MIDI_GetCCShape { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetCCShape) ), Some(f) => f(take, ccidx, shapeOut, beztensionOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetEvt( &self, take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, selectedOut: *mut bool, mutedOut: *mut bool, ppqposOut: *mut f64, msgOut: *mut ::std::os::raw::c_char, msgOut_sz: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetEvt) ), Some(f) => f( take, evtidx, selectedOut, mutedOut, ppqposOut, msgOut, msgOut_sz, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetGrid( &self, take: *mut root::MediaItem_Take, swingOutOptional: *mut f64, noteLenOutOptional: *mut f64, ) -> f64 { match self.pointers.MIDI_GetGrid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetGrid) ), Some(f) => f(take, swingOutOptional, noteLenOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetHash( &self, take: *mut root::MediaItem_Take, notesonly: bool, hashOut: *mut ::std::os::raw::c_char, hashOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetHash { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetHash) ), Some(f) => f(take, notesonly, hashOut, hashOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetNote( &self, take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, selectedOut: *mut bool, mutedOut: *mut bool, startppqposOut: *mut f64, endppqposOut: *mut f64, chanOut: *mut ::std::os::raw::c_int, pitchOut: *mut ::std::os::raw::c_int, velOut: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetNote { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetNote) ), Some(f) => f( take, noteidx, selectedOut, mutedOut, startppqposOut, endppqposOut, chanOut, pitchOut, velOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetPPQPos_EndOfMeasure( &self, take: *mut root::MediaItem_Take, ppqpos: f64, ) -> f64 { match self.pointers.MIDI_GetPPQPos_EndOfMeasure { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetPPQPos_EndOfMeasure) ), Some(f) => f(take, ppqpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetPPQPos_StartOfMeasure( &self, take: *mut root::MediaItem_Take, ppqpos: f64, ) -> f64 { match self.pointers.MIDI_GetPPQPos_StartOfMeasure { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetPPQPos_StartOfMeasure) ), Some(f) => f(take, ppqpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetPPQPosFromProjQN( &self, take: *mut root::MediaItem_Take, projqn: f64, ) -> f64 { match self.pointers.MIDI_GetPPQPosFromProjQN { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetPPQPosFromProjQN) ), Some(f) => f(take, projqn), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetPPQPosFromProjTime( &self, take: *mut root::MediaItem_Take, projtime: f64, ) -> f64 { match self.pointers.MIDI_GetPPQPosFromProjTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetPPQPosFromProjTime) ), Some(f) => f(take, projtime), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetProjQNFromPPQPos( &self, take: *mut root::MediaItem_Take, ppqpos: f64, ) -> f64 { match self.pointers.MIDI_GetProjQNFromPPQPos { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetProjQNFromPPQPos) ), Some(f) => f(take, ppqpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetProjTimeFromPPQPos( &self, take: *mut root::MediaItem_Take, ppqpos: f64, ) -> f64 { match self.pointers.MIDI_GetProjTimeFromPPQPos { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetProjTimeFromPPQPos) ), Some(f) => f(take, ppqpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetScale( &self, take: *mut root::MediaItem_Take, rootOut: *mut ::std::os::raw::c_int, scaleOut: *mut ::std::os::raw::c_int, nameOut: *mut ::std::os::raw::c_char, nameOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetScale { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetScale) ), Some(f) => f(take, rootOut, scaleOut, nameOut, nameOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetTextSysexEvt( &self, take: *mut root::MediaItem_Take, textsyxevtidx: ::std::os::raw::c_int, selectedOutOptional: *mut bool, mutedOutOptional: *mut bool, ppqposOutOptional: *mut f64, typeOutOptional: *mut ::std::os::raw::c_int, msgOptional: *mut ::std::os::raw::c_char, msgOptional_sz: *mut ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetTextSysexEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetTextSysexEvt) ), Some(f) => f( take, textsyxevtidx, selectedOutOptional, mutedOutOptional, ppqposOutOptional, typeOutOptional, msgOptional, msgOptional_sz, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_GetTrackHash( &self, track: *mut root::MediaTrack, notesonly: bool, hashOut: *mut ::std::os::raw::c_char, hashOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_GetTrackHash { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_GetTrackHash) ), Some(f) => f(track, notesonly, hashOut, hashOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_InsertCC( &self, take: *mut root::MediaItem_Take, selected: bool, muted: bool, ppqpos: f64, chanmsg: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, msg2: ::std::os::raw::c_int, msg3: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_InsertCC { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_InsertCC) ), Some(f) => f(take, selected, muted, ppqpos, chanmsg, chan, msg2, msg3), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_InsertEvt( &self, take: *mut root::MediaItem_Take, selected: bool, muted: bool, ppqpos: f64, bytestr: *const ::std::os::raw::c_char, bytestr_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_InsertEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_InsertEvt) ), Some(f) => f(take, selected, muted, ppqpos, bytestr, bytestr_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_InsertNote( &self, take: *mut root::MediaItem_Take, selected: bool, muted: bool, startppqpos: f64, endppqpos: f64, chan: ::std::os::raw::c_int, pitch: ::std::os::raw::c_int, vel: ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool { match self.pointers.MIDI_InsertNote { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_InsertNote) ), Some(f) => f( take, selected, muted, startppqpos, endppqpos, chan, pitch, vel, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_InsertTextSysexEvt( &self, take: *mut root::MediaItem_Take, selected: bool, muted: bool, ppqpos: f64, type_: ::std::os::raw::c_int, bytestr: *const ::std::os::raw::c_char, bytestr_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_InsertTextSysexEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_InsertTextSysexEvt) ), Some(f) => f(take, selected, muted, ppqpos, type_, bytestr, bytestr_sz), } } pub fn midi_reinit(&self) { match self.pointers.midi_reinit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(midi_reinit) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SelectAll(&self, take: *mut root::MediaItem_Take, select: bool) { match self.pointers.MIDI_SelectAll { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SelectAll) ), Some(f) => f(take, select), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetAllEvts( &self, take: *mut root::MediaItem_Take, buf: *const ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDI_SetAllEvts { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetAllEvts) ), Some(f) => f(take, buf, buf_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetCC( &self, take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, ppqposInOptional: *const f64, chanmsgInOptional: *const ::std::os::raw::c_int, chanInOptional: *const ::std::os::raw::c_int, msg2InOptional: *const ::std::os::raw::c_int, msg3InOptional: *const ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool { match self.pointers.MIDI_SetCC { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetCC) ), Some(f) => f( take, ccidx, selectedInOptional, mutedInOptional, ppqposInOptional, chanmsgInOptional, chanInOptional, msg2InOptional, msg3InOptional, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetCCShape( &self, take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, shape: ::std::os::raw::c_int, beztension: f64, noSortInOptional: *const bool, ) -> bool { match self.pointers.MIDI_SetCCShape { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetCCShape) ), Some(f) => f(take, ccidx, shape, beztension, noSortInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetEvt( &self, take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, ppqposInOptional: *const f64, msgOptional: *const ::std::os::raw::c_char, msgOptional_sz: ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool { match self.pointers.MIDI_SetEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetEvt) ), Some(f) => f( take, evtidx, selectedInOptional, mutedInOptional, ppqposInOptional, msgOptional, msgOptional_sz, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetItemExtents( &self, item: *mut root::MediaItem, startQN: f64, endQN: f64, ) -> bool { match self.pointers.MIDI_SetItemExtents { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetItemExtents) ), Some(f) => f(item, startQN, endQN), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetNote( &self, take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, startppqposInOptional: *const f64, endppqposInOptional: *const f64, chanInOptional: *const ::std::os::raw::c_int, pitchInOptional: *const ::std::os::raw::c_int, velInOptional: *const ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool { match self.pointers.MIDI_SetNote { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetNote) ), Some(f) => f( take, noteidx, selectedInOptional, mutedInOptional, startppqposInOptional, endppqposInOptional, chanInOptional, pitchInOptional, velInOptional, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_SetTextSysexEvt( &self, take: *mut root::MediaItem_Take, textsyxevtidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, ppqposInOptional: *const f64, typeInOptional: *const ::std::os::raw::c_int, msgOptional: *const ::std::os::raw::c_char, msgOptional_sz: ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool { match self.pointers.MIDI_SetTextSysexEvt { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_SetTextSysexEvt) ), Some(f) => f( take, textsyxevtidx, selectedInOptional, mutedInOptional, ppqposInOptional, typeInOptional, msgOptional, msgOptional_sz, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDI_Sort(&self, take: *mut root::MediaItem_Take) { match self.pointers.MIDI_Sort { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDI_Sort) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_EnumTakes( &self, midieditor: root::HWND, takeindex: ::std::os::raw::c_int, editable_only: bool, ) -> *mut root::MediaItem_Take { match self.pointers.MIDIEditor_EnumTakes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_EnumTakes) ), Some(f) => f(midieditor, takeindex, editable_only), } } pub fn MIDIEditor_GetActive(&self) -> root::HWND { match self.pointers.MIDIEditor_GetActive { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_GetActive) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_GetMode(&self, midieditor: root::HWND) -> ::std::os::raw::c_int { match self.pointers.MIDIEditor_GetMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_GetMode) ), Some(f) => f(midieditor), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_GetSetting_int( &self, midieditor: root::HWND, setting_desc: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.MIDIEditor_GetSetting_int { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_GetSetting_int) ), Some(f) => f(midieditor, setting_desc), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_GetSetting_str( &self, midieditor: root::HWND, setting_desc: *const ::std::os::raw::c_char, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDIEditor_GetSetting_str { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_GetSetting_str) ), Some(f) => f(midieditor, setting_desc, buf, buf_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_GetTake(&self, midieditor: root::HWND) -> *mut root::MediaItem_Take { match self.pointers.MIDIEditor_GetTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_GetTake) ), Some(f) => f(midieditor), } } pub fn MIDIEditor_LastFocused_OnCommand( &self, command_id: ::std::os::raw::c_int, islistviewcommand: bool, ) -> bool { match self.pointers.MIDIEditor_LastFocused_OnCommand { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_LastFocused_OnCommand) ), Some(f) => f(command_id, islistviewcommand), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_OnCommand( &self, midieditor: root::HWND, command_id: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDIEditor_OnCommand { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_OnCommand) ), Some(f) => f(midieditor, command_id), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MIDIEditor_SetSetting_int( &self, midieditor: root::HWND, setting_desc: *const ::std::os::raw::c_char, setting: ::std::os::raw::c_int, ) -> bool { match self.pointers.MIDIEditor_SetSetting_int { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MIDIEditor_SetSetting_int) ), Some(f) => f(midieditor, setting_desc, setting), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn mkpanstr(&self, strNeed64: *mut ::std::os::raw::c_char, pan: f64) { match self.pointers.mkpanstr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(mkpanstr) ), Some(f) => f(strNeed64, pan), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn mkvolpanstr(&self, strNeed64: *mut ::std::os::raw::c_char, vol: f64, pan: f64) { match self.pointers.mkvolpanstr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(mkvolpanstr) ), Some(f) => f(strNeed64, vol, pan), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn mkvolstr(&self, strNeed64: *mut ::std::os::raw::c_char, vol: f64) { match self.pointers.mkvolstr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(mkvolstr) ), Some(f) => f(strNeed64, vol), } } pub fn MoveEditCursor(&self, adjamt: f64, dosel: bool) { match self.pointers.MoveEditCursor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MoveEditCursor) ), Some(f) => f(adjamt, dosel), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn MoveMediaItemToTrack( &self, item: *mut root::MediaItem, desttr: *mut root::MediaTrack, ) -> bool { match self.pointers.MoveMediaItemToTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MoveMediaItemToTrack) ), Some(f) => f(item, desttr), } } pub fn MuteAllTracks(&self, mute: bool) { match self.pointers.MuteAllTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(MuteAllTracks) ), Some(f) => f(mute), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn my_getViewport( &self, r: *mut root::RECT, sr: *const root::RECT, wantWorkArea: bool, ) { match self.pointers.my_getViewport { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(my_getViewport) ), Some(f) => f(r, sr, wantWorkArea), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn NamedCommandLookup( &self, command_name: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.NamedCommandLookup { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(NamedCommandLookup) ), Some(f) => f(command_name), } } pub fn OnPauseButton(&self) { match self.pointers.OnPauseButton { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OnPauseButton) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn OnPauseButtonEx(&self, proj: *mut root::ReaProject) { match self.pointers.OnPauseButtonEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OnPauseButtonEx) ), Some(f) => f(proj), } } pub fn OnPlayButton(&self) { match self.pointers.OnPlayButton { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OnPlayButton) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn OnPlayButtonEx(&self, proj: *mut root::ReaProject) { match self.pointers.OnPlayButtonEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OnPlayButtonEx) ), Some(f) => f(proj), } } pub fn OnStopButton(&self) { match self.pointers.OnStopButton { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OnStopButton) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn OnStopButtonEx(&self, proj: *mut root::ReaProject) { match self.pointers.OnStopButtonEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OnStopButtonEx) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn OpenColorThemeFile(&self, fn_: *const ::std::os::raw::c_char) -> bool { match self.pointers.OpenColorThemeFile { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OpenColorThemeFile) ), Some(f) => f(fn_), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn OpenMediaExplorer( &self, mediafn: *const ::std::os::raw::c_char, play: bool, ) -> root::HWND { match self.pointers.OpenMediaExplorer { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OpenMediaExplorer) ), Some(f) => f(mediafn, play), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn OscLocalMessageToHost( &self, message: *const ::std::os::raw::c_char, valueInOptional: *const f64, ) { match self.pointers.OscLocalMessageToHost { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(OscLocalMessageToHost) ), Some(f) => f(message, valueInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn parse_timestr(&self, buf: *const ::std::os::raw::c_char) -> f64 { match self.pointers.parse_timestr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(parse_timestr) ), Some(f) => f(buf), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn parse_timestr_len( &self, buf: *const ::std::os::raw::c_char, offset: f64, modeoverride: ::std::os::raw::c_int, ) -> f64 { match self.pointers.parse_timestr_len { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(parse_timestr_len) ), Some(f) => f(buf, offset, modeoverride), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn parse_timestr_pos( &self, buf: *const ::std::os::raw::c_char, modeoverride: ::std::os::raw::c_int, ) -> f64 { match self.pointers.parse_timestr_pos { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(parse_timestr_pos) ), Some(f) => f(buf, modeoverride), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn parsepanstr(&self, str: *const ::std::os::raw::c_char) -> f64 { match self.pointers.parsepanstr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(parsepanstr) ), Some(f) => f(str), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_Create( &self, filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, srate: ::std::os::raw::c_int, buildpeaks: bool, ) -> *mut root::PCM_sink { match self.pointers.PCM_Sink_Create { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_Create) ), Some(f) => f(filename, cfg, cfg_sz, nch, srate, buildpeaks), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_CreateEx( &self, proj: *mut root::ReaProject, filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, srate: ::std::os::raw::c_int, buildpeaks: bool, ) -> *mut root::PCM_sink { match self.pointers.PCM_Sink_CreateEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_CreateEx) ), Some(f) => f(proj, filename, cfg, cfg_sz, nch, srate, buildpeaks), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_CreateMIDIFile( &self, filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, bpm: f64, div: ::std::os::raw::c_int, ) -> *mut root::PCM_sink { match self.pointers.PCM_Sink_CreateMIDIFile { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_CreateMIDIFile) ), Some(f) => f(filename, cfg, cfg_sz, bpm, div), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_CreateMIDIFileEx( &self, proj: *mut root::ReaProject, filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, bpm: f64, div: ::std::os::raw::c_int, ) -> *mut root::PCM_sink { match self.pointers.PCM_Sink_CreateMIDIFileEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_CreateMIDIFileEx) ), Some(f) => f(proj, filename, cfg, cfg_sz, bpm, div), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_Enum( &self, idx: ::std::os::raw::c_int, descstrOut: *mut *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_uint { match self.pointers.PCM_Sink_Enum { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_Enum) ), Some(f) => f(idx, descstrOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_GetExtension( &self, data: *const ::std::os::raw::c_char, data_sz: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.PCM_Sink_GetExtension { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_GetExtension) ), Some(f) => f(data, data_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Sink_ShowConfig( &self, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, hwndParent: root::HWND, ) -> root::HWND { match self.pointers.PCM_Sink_ShowConfig { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Sink_ShowConfig) ), Some(f) => f(cfg, cfg_sz, hwndParent), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_BuildPeaks( &self, src: *mut root::PCM_source, mode: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.PCM_Source_BuildPeaks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_BuildPeaks) ), Some(f) => f(src, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_CreateFromFile( &self, filename: *const ::std::os::raw::c_char, ) -> *mut root::PCM_source { match self.pointers.PCM_Source_CreateFromFile { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_CreateFromFile) ), Some(f) => f(filename), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_CreateFromFileEx( &self, filename: *const ::std::os::raw::c_char, forcenoMidiImp: bool, ) -> *mut root::PCM_source { match self.pointers.PCM_Source_CreateFromFileEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_CreateFromFileEx) ), Some(f) => f(filename, forcenoMidiImp), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_CreateFromSimple( &self, dec: *mut root::ISimpleMediaDecoder, fn_: *const ::std::os::raw::c_char, ) -> *mut root::PCM_source { match self.pointers.PCM_Source_CreateFromSimple { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_CreateFromSimple) ), Some(f) => f(dec, fn_), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_CreateFromType( &self, sourcetype: *const ::std::os::raw::c_char, ) -> *mut root::PCM_source { match self.pointers.PCM_Source_CreateFromType { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_CreateFromType) ), Some(f) => f(sourcetype), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_Destroy(&self, src: *mut root::PCM_source) { match self.pointers.PCM_Source_Destroy { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_Destroy) ), Some(f) => f(src), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_GetPeaks( &self, src: *mut root::PCM_source, peakrate: f64, starttime: f64, numchannels: ::std::os::raw::c_int, numsamplesperchannel: ::std::os::raw::c_int, want_extra_type: ::std::os::raw::c_int, buf: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.PCM_Source_GetPeaks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_GetPeaks) ), Some(f) => f( src, peakrate, starttime, numchannels, numsamplesperchannel, want_extra_type, buf, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PCM_Source_GetSectionInfo( &self, src: *mut root::PCM_source, offsOut: *mut f64, lenOut: *mut f64, revOut: *mut bool, ) -> bool { match self.pointers.PCM_Source_GetSectionInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PCM_Source_GetSectionInfo) ), Some(f) => f(src, offsOut, lenOut, revOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PeakBuild_Create( &self, src: *mut root::PCM_source, fn_: *const ::std::os::raw::c_char, srate: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, ) -> *mut root::REAPER_PeakBuild_Interface { match self.pointers.PeakBuild_Create { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PeakBuild_Create) ), Some(f) => f(src, fn_, srate, nch), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PeakBuild_CreateEx( &self, src: *mut root::PCM_source, fn_: *const ::std::os::raw::c_char, srate: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, ) -> *mut root::REAPER_PeakBuild_Interface { match self.pointers.PeakBuild_CreateEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PeakBuild_CreateEx) ), Some(f) => f(src, fn_, srate, nch, flags), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PeakGet_Create( &self, fn_: *const ::std::os::raw::c_char, srate: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, ) -> *mut root::REAPER_PeakGet_Interface { match self.pointers.PeakGet_Create { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PeakGet_Create) ), Some(f) => f(fn_, srate, nch), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PitchShiftSubModeMenu( &self, hwnd: root::HWND, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, mode: ::std::os::raw::c_int, submode_sel: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.PitchShiftSubModeMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PitchShiftSubModeMenu) ), Some(f) => f(hwnd, x, y, mode, submode_sel), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PlayPreview( &self, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int { match self.pointers.PlayPreview { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PlayPreview) ), Some(f) => f(preview), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PlayPreviewEx( &self, preview: *mut root::preview_register_t, bufflags: ::std::os::raw::c_int, measure_align: f64, ) -> ::std::os::raw::c_int { match self.pointers.PlayPreviewEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PlayPreviewEx) ), Some(f) => f(preview, bufflags, measure_align), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PlayTrackPreview( &self, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int { match self.pointers.PlayTrackPreview { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PlayTrackPreview) ), Some(f) => f(preview), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PlayTrackPreview2( &self, proj: *mut root::ReaProject, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int { match self.pointers.PlayTrackPreview2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PlayTrackPreview2) ), Some(f) => f(proj, preview), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn PlayTrackPreview2Ex( &self, proj: *mut root::ReaProject, preview: *mut root::preview_register_t, flags: ::std::os::raw::c_int, measure_align: f64, ) -> ::std::os::raw::c_int { match self.pointers.PlayTrackPreview2Ex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PlayTrackPreview2Ex) ), Some(f) => f(proj, preview, flags, measure_align), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn plugin_getapi( &self, name: *const ::std::os::raw::c_char, ) -> *mut ::std::os::raw::c_void { match self.pointers.plugin_getapi { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(plugin_getapi) ), Some(f) => f(name), } } pub fn plugin_getFilterList(&self) -> *const ::std::os::raw::c_char { match self.pointers.plugin_getFilterList { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(plugin_getFilterList) ), Some(f) => f(), } } pub fn plugin_getImportableProjectFilterList(&self) -> *const ::std::os::raw::c_char { match self.pointers.plugin_getImportableProjectFilterList { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(plugin_getImportableProjectFilterList) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn plugin_register( &self, name: *const ::std::os::raw::c_char, infostruct: *mut ::std::os::raw::c_void, ) -> ::std::os::raw::c_int { match self.pointers.plugin_register { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(plugin_register) ), Some(f) => f(name, infostruct), } } pub fn PluginWantsAlwaysRunFx(&self, amt: ::std::os::raw::c_int) { match self.pointers.PluginWantsAlwaysRunFx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PluginWantsAlwaysRunFx) ), Some(f) => f(amt), } } pub fn PreventUIRefresh(&self, prevent_count: ::std::os::raw::c_int) { match self.pointers.PreventUIRefresh { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PreventUIRefresh) ), Some(f) => f(prevent_count), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn projectconfig_var_addr( &self, proj: *mut root::ReaProject, idx: ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void { match self.pointers.projectconfig_var_addr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(projectconfig_var_addr) ), Some(f) => f(proj, idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn projectconfig_var_getoffs( &self, name: *const ::std::os::raw::c_char, szOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.projectconfig_var_getoffs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(projectconfig_var_getoffs) ), Some(f) => f(name, szOut), } } pub fn PromptForAction( &self, session_mode: ::std::os::raw::c_int, init_id: ::std::os::raw::c_int, section_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.PromptForAction { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(PromptForAction) ), Some(f) => f(session_mode, init_id, section_id), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn realloc_cmd_ptr( &self, ptr: *mut *mut ::std::os::raw::c_char, ptr_size: *mut ::std::os::raw::c_int, new_size: ::std::os::raw::c_int, ) -> bool { match self.pointers.realloc_cmd_ptr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(realloc_cmd_ptr) ), Some(f) => f(ptr, ptr_size, new_size), } } pub fn ReaperGetPitchShiftAPI( &self, version: ::std::os::raw::c_int, ) -> *mut root::IReaperPitchShift { match self.pointers.ReaperGetPitchShiftAPI { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ReaperGetPitchShiftAPI) ), Some(f) => f(version), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ReaScriptError(&self, errmsg: *const ::std::os::raw::c_char) { match self.pointers.ReaScriptError { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ReaScriptError) ), Some(f) => f(errmsg), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn RecursiveCreateDirectory( &self, path: *const ::std::os::raw::c_char, ignored: usize, ) -> ::std::os::raw::c_int { match self.pointers.RecursiveCreateDirectory { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(RecursiveCreateDirectory) ), Some(f) => f(path, ignored), } } pub fn reduce_open_files(&self, flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int { match self.pointers.reduce_open_files { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(reduce_open_files) ), Some(f) => f(flags), } } pub fn RefreshToolbar(&self, command_id: ::std::os::raw::c_int) { match self.pointers.RefreshToolbar { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(RefreshToolbar) ), Some(f) => f(command_id), } } pub fn RefreshToolbar2( &self, section_id: ::std::os::raw::c_int, command_id: ::std::os::raw::c_int, ) { match self.pointers.RefreshToolbar2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(RefreshToolbar2) ), Some(f) => f(section_id, command_id), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn relative_fn( &self, in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, ) { match self.pointers.relative_fn { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(relative_fn) ), Some(f) => f(in_, out, out_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn RemoveTrackSend( &self, tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.RemoveTrackSend { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(RemoveTrackSend) ), Some(f) => f(tr, category, sendidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn RenderFileSection( &self, source_filename: *const ::std::os::raw::c_char, target_filename: *const ::std::os::raw::c_char, start_percent: f64, end_percent: f64, playrate: f64, ) -> bool { match self.pointers.RenderFileSection { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(RenderFileSection) ), Some(f) => f( source_filename, target_filename, start_percent, end_percent, playrate, ), } } pub fn ReorderSelectedTracks( &self, beforeTrackIdx: ::std::os::raw::c_int, makePrevFolder: ::std::os::raw::c_int, ) -> bool { match self.pointers.ReorderSelectedTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ReorderSelectedTracks) ), Some(f) => f(beforeTrackIdx, makePrevFolder), } } pub fn Resample_EnumModes(&self, mode: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char { match self.pointers.Resample_EnumModes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Resample_EnumModes) ), Some(f) => f(mode), } } pub fn Resampler_Create(&self) -> *mut root::REAPER_Resample_Interface { match self.pointers.Resampler_Create { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Resampler_Create) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn resolve_fn( &self, in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, ) { match self.pointers.resolve_fn { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(resolve_fn) ), Some(f) => f(in_, out, out_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn resolve_fn2( &self, in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, checkSubDirOptional: *const ::std::os::raw::c_char, ) { match self.pointers.resolve_fn2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(resolve_fn2) ), Some(f) => f(in_, out, out_sz, checkSubDirOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ResolveRenderPattern( &self, project: *mut root::ReaProject, path: *const ::std::os::raw::c_char, pattern: *const ::std::os::raw::c_char, targets: *mut ::std::os::raw::c_char, targets_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.ResolveRenderPattern { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ResolveRenderPattern) ), Some(f) => f(project, path, pattern, targets, targets_sz), } } pub fn ReverseNamedCommandLookup( &self, command_id: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.ReverseNamedCommandLookup { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ReverseNamedCommandLookup) ), Some(f) => f(command_id), } } pub fn ScaleFromEnvelopeMode(&self, scaling_mode: ::std::os::raw::c_int, val: f64) -> f64 { match self.pointers.ScaleFromEnvelopeMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ScaleFromEnvelopeMode) ), Some(f) => f(scaling_mode, val), } } pub fn ScaleToEnvelopeMode(&self, scaling_mode: ::std::os::raw::c_int, val: f64) -> f64 { match self.pointers.ScaleToEnvelopeMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ScaleToEnvelopeMode) ), Some(f) => f(scaling_mode, val), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn screenset_register( &self, id: *mut ::std::os::raw::c_char, callbackFunc: *mut ::std::os::raw::c_void, param: *mut ::std::os::raw::c_void, ) { match self.pointers.screenset_register { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(screenset_register) ), Some(f) => f(id, callbackFunc, param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn screenset_registerNew( &self, id: *mut ::std::os::raw::c_char, callbackFunc: root::screensetNewCallbackFunc, param: *mut ::std::os::raw::c_void, ) { match self.pointers.screenset_registerNew { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(screenset_registerNew) ), Some(f) => f(id, callbackFunc, param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn screenset_unregister(&self, id: *mut ::std::os::raw::c_char) { match self.pointers.screenset_unregister { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(screenset_unregister) ), Some(f) => f(id), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn screenset_unregisterByParam(&self, param: *mut ::std::os::raw::c_void) { match self.pointers.screenset_unregisterByParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(screenset_unregisterByParam) ), Some(f) => f(param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn screenset_updateLastFocus(&self, prevWin: root::HWND) { match self.pointers.screenset_updateLastFocus { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(screenset_updateLastFocus) ), Some(f) => f(prevWin), } } pub fn SectionFromUniqueID( &self, uniqueID: ::std::os::raw::c_int, ) -> *mut root::KbdSectionInfo { match self.pointers.SectionFromUniqueID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SectionFromUniqueID) ), Some(f) => f(uniqueID), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SelectAllMediaItems(&self, proj: *mut root::ReaProject, selected: bool) { match self.pointers.SelectAllMediaItems { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SelectAllMediaItems) ), Some(f) => f(proj, selected), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SelectProjectInstance(&self, proj: *mut root::ReaProject) { match self.pointers.SelectProjectInstance { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SelectProjectInstance) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SendLocalOscMessage( &self, local_osc_handler: *mut ::std::os::raw::c_void, msg: *const ::std::os::raw::c_char, msglen: ::std::os::raw::c_int, ) { match self.pointers.SendLocalOscMessage { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SendLocalOscMessage) ), Some(f) => f(local_osc_handler, msg, msglen), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetActiveTake(&self, take: *mut root::MediaItem_Take) { match self.pointers.SetActiveTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetActiveTake) ), Some(f) => f(take), } } pub fn SetAutomationMode(&self, mode: ::std::os::raw::c_int, onlySel: bool) { match self.pointers.SetAutomationMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetAutomationMode) ), Some(f) => f(mode, onlySel), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetCurrentBPM(&self, __proj: *mut root::ReaProject, bpm: f64, wantUndo: bool) { match self.pointers.SetCurrentBPM { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetCurrentBPM) ), Some(f) => f(__proj, bpm, wantUndo), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetCursorContext( &self, mode: ::std::os::raw::c_int, envInOptional: *mut root::TrackEnvelope, ) { match self.pointers.SetCursorContext { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetCursorContext) ), Some(f) => f(mode, envInOptional), } } pub fn SetEditCurPos(&self, time: f64, moveview: bool, seekplay: bool) { match self.pointers.SetEditCurPos { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetEditCurPos) ), Some(f) => f(time, moveview, seekplay), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetEditCurPos2( &self, proj: *mut root::ReaProject, time: f64, moveview: bool, seekplay: bool, ) { match self.pointers.SetEditCurPos2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetEditCurPos2) ), Some(f) => f(proj, time, moveview, seekplay), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetEnvelopePoint( &self, envelope: *mut root::TrackEnvelope, ptidx: ::std::os::raw::c_int, timeInOptional: *mut f64, valueInOptional: *mut f64, shapeInOptional: *mut ::std::os::raw::c_int, tensionInOptional: *mut f64, selectedInOptional: *mut bool, noSortInOptional: *mut bool, ) -> bool { match self.pointers.SetEnvelopePoint { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetEnvelopePoint) ), Some(f) => f( envelope, ptidx, timeInOptional, valueInOptional, shapeInOptional, tensionInOptional, selectedInOptional, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetEnvelopePointEx( &self, envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ptidx: ::std::os::raw::c_int, timeInOptional: *mut f64, valueInOptional: *mut f64, shapeInOptional: *mut ::std::os::raw::c_int, tensionInOptional: *mut f64, selectedInOptional: *mut bool, noSortInOptional: *mut bool, ) -> bool { match self.pointers.SetEnvelopePointEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetEnvelopePointEx) ), Some(f) => f( envelope, autoitem_idx, ptidx, timeInOptional, valueInOptional, shapeInOptional, tensionInOptional, selectedInOptional, noSortInOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetEnvelopeStateChunk( &self, env: *mut root::TrackEnvelope, str: *const ::std::os::raw::c_char, isundoOptional: bool, ) -> bool { match self.pointers.SetEnvelopeStateChunk { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetEnvelopeStateChunk) ), Some(f) => f(env, str, isundoOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetExtState( &self, section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, persist: bool, ) { match self.pointers.SetExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetExtState) ), Some(f) => f(section, key, value, persist), } } pub fn SetGlobalAutomationOverride(&self, mode: ::std::os::raw::c_int) { match self.pointers.SetGlobalAutomationOverride { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetGlobalAutomationOverride) ), Some(f) => f(mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetItemStateChunk( &self, item: *mut root::MediaItem, str: *const ::std::os::raw::c_char, isundoOptional: bool, ) -> bool { match self.pointers.SetItemStateChunk { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetItemStateChunk) ), Some(f) => f(item, str, isundoOptional), } } pub fn SetMasterTrackVisibility(&self, flag: ::std::os::raw::c_int) -> ::std::os::raw::c_int { match self.pointers.SetMasterTrackVisibility { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMasterTrackVisibility) ), Some(f) => f(flag), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaItemInfo_Value( &self, item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool { match self.pointers.SetMediaItemInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaItemInfo_Value) ), Some(f) => f(item, parmname, newvalue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaItemLength( &self, item: *mut root::MediaItem, length: f64, refreshUI: bool, ) -> bool { match self.pointers.SetMediaItemLength { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaItemLength) ), Some(f) => f(item, length, refreshUI), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaItemPosition( &self, item: *mut root::MediaItem, position: f64, refreshUI: bool, ) -> bool { match self.pointers.SetMediaItemPosition { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaItemPosition) ), Some(f) => f(item, position, refreshUI), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaItemSelected(&self, item: *mut root::MediaItem, selected: bool) { match self.pointers.SetMediaItemSelected { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaItemSelected) ), Some(f) => f(item, selected), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaItemTake_Source( &self, take: *mut root::MediaItem_Take, source: *mut root::PCM_source, ) -> bool { match self.pointers.SetMediaItemTake_Source { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaItemTake_Source) ), Some(f) => f(take, source), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaItemTakeInfo_Value( &self, take: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool { match self.pointers.SetMediaItemTakeInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaItemTakeInfo_Value) ), Some(f) => f(take, parmname, newvalue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMediaTrackInfo_Value( &self, tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool { match self.pointers.SetMediaTrackInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMediaTrackInfo_Value) ), Some(f) => f(tr, parmname, newvalue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMIDIEditorGrid(&self, project: *mut root::ReaProject, division: f64) { match self.pointers.SetMIDIEditorGrid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMIDIEditorGrid) ), Some(f) => f(project, division), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMixerScroll( &self, leftmosttrack: *mut root::MediaTrack, ) -> *mut root::MediaTrack { match self.pointers.SetMixerScroll { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMixerScroll) ), Some(f) => f(leftmosttrack), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetMouseModifier( &self, context: *const ::std::os::raw::c_char, modifier_flag: ::std::os::raw::c_int, action: *const ::std::os::raw::c_char, ) { match self.pointers.SetMouseModifier { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetMouseModifier) ), Some(f) => f(context, modifier_flag, action), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetOnlyTrackSelected(&self, track: *mut root::MediaTrack) { match self.pointers.SetOnlyTrackSelected { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetOnlyTrackSelected) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectGrid(&self, project: *mut root::ReaProject, division: f64) { match self.pointers.SetProjectGrid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectGrid) ), Some(f) => f(project, division), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectMarker( &self, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.SetProjectMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectMarker) ), Some(f) => f(markrgnindexnumber, isrgn, pos, rgnend, name), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectMarker2( &self, proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.SetProjectMarker2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectMarker2) ), Some(f) => f(proj, markrgnindexnumber, isrgn, pos, rgnend, name), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectMarker3( &self, proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetProjectMarker3 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectMarker3) ), Some(f) => f(proj, markrgnindexnumber, isrgn, pos, rgnend, name, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectMarker4( &self, proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetProjectMarker4 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectMarker4) ), Some(f) => f( proj, markrgnindexnumber, isrgn, pos, rgnend, name, color, flags, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectMarkerByIndex( &self, proj: *mut root::ReaProject, markrgnidx: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, IDnumber: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetProjectMarkerByIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectMarkerByIndex) ), Some(f) => f(proj, markrgnidx, isrgn, pos, rgnend, IDnumber, name, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjectMarkerByIndex2( &self, proj: *mut root::ReaProject, markrgnidx: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, IDnumber: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetProjectMarkerByIndex2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjectMarkerByIndex2) ), Some(f) => f( proj, markrgnidx, isrgn, pos, rgnend, IDnumber, name, color, flags, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetProjExtState( &self, proj: *mut root::ReaProject, extname: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.SetProjExtState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetProjExtState) ), Some(f) => f(proj, extname, key, value), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetRegionRenderMatrix( &self, proj: *mut root::ReaProject, regionindex: ::std::os::raw::c_int, track: *mut root::MediaTrack, addorremove: ::std::os::raw::c_int, ) { match self.pointers.SetRegionRenderMatrix { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetRegionRenderMatrix) ), Some(f) => f(proj, regionindex, track, addorremove), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetRenderLastError(&self, errorstr: *const ::std::os::raw::c_char) { match self.pointers.SetRenderLastError { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetRenderLastError) ), Some(f) => f(errorstr), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTakeMarker( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, nameIn: *const ::std::os::raw::c_char, srcposInOptional: *mut f64, colorInOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.SetTakeMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTakeMarker) ), Some(f) => f(take, idx, nameIn, srcposInOptional, colorInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTakeStretchMarker( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, pos: f64, srcposInOptional: *const f64, ) -> ::std::os::raw::c_int { match self.pointers.SetTakeStretchMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTakeStretchMarker) ), Some(f) => f(take, idx, pos, srcposInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTakeStretchMarkerSlope( &self, take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, slope: f64, ) -> bool { match self.pointers.SetTakeStretchMarkerSlope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTakeStretchMarkerSlope) ), Some(f) => f(take, idx, slope), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTempoTimeSigMarker( &self, proj: *mut root::ReaProject, ptidx: ::std::os::raw::c_int, timepos: f64, measurepos: ::std::os::raw::c_int, beatpos: f64, bpm: f64, timesig_num: ::std::os::raw::c_int, timesig_denom: ::std::os::raw::c_int, lineartempo: bool, ) -> bool { match self.pointers.SetTempoTimeSigMarker { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTempoTimeSigMarker) ), Some(f) => f( proj, ptidx, timepos, measurepos, beatpos, bpm, timesig_num, timesig_denom, lineartempo, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetThemeColor( &self, ini_key: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, flagsOptional: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.SetThemeColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetThemeColor) ), Some(f) => f(ini_key, color, flagsOptional), } } pub fn SetToggleCommandState( &self, section_id: ::std::os::raw::c_int, command_id: ::std::os::raw::c_int, state: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetToggleCommandState { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetToggleCommandState) ), Some(f) => f(section_id, command_id, state), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackAutomationMode( &self, tr: *mut root::MediaTrack, mode: ::std::os::raw::c_int, ) { match self.pointers.SetTrackAutomationMode { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackAutomationMode) ), Some(f) => f(tr, mode), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackColor(&self, track: *mut root::MediaTrack, color: ::std::os::raw::c_int) { match self.pointers.SetTrackColor { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackColor) ), Some(f) => f(track, color), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackMIDILyrics( &self, track: *mut root::MediaTrack, flag: ::std::os::raw::c_int, str: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.SetTrackMIDILyrics { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackMIDILyrics) ), Some(f) => f(track, flag, str), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackMIDINoteName( &self, track: ::std::os::raw::c_int, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.SetTrackMIDINoteName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackMIDINoteName) ), Some(f) => f(track, pitch, chan, name), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackMIDINoteNameEx( &self, proj: *mut root::ReaProject, track: *mut root::MediaTrack, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.SetTrackMIDINoteNameEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackMIDINoteNameEx) ), Some(f) => f(proj, track, pitch, chan, name), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackSelected(&self, track: *mut root::MediaTrack, selected: bool) { match self.pointers.SetTrackSelected { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackSelected) ), Some(f) => f(track, selected), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackSendInfo_Value( &self, tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool { match self.pointers.SetTrackSendInfo_Value { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackSendInfo_Value) ), Some(f) => f(tr, category, sendidx, parmname, newvalue), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackSendUIPan( &self, track: *mut root::MediaTrack, send_idx: ::std::os::raw::c_int, pan: f64, isend: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetTrackSendUIPan { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackSendUIPan) ), Some(f) => f(track, send_idx, pan, isend), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackSendUIVol( &self, track: *mut root::MediaTrack, send_idx: ::std::os::raw::c_int, vol: f64, isend: ::std::os::raw::c_int, ) -> bool { match self.pointers.SetTrackSendUIVol { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackSendUIVol) ), Some(f) => f(track, send_idx, vol, isend), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SetTrackStateChunk( &self, track: *mut root::MediaTrack, str: *const ::std::os::raw::c_char, isundoOptional: bool, ) -> bool { match self.pointers.SetTrackStateChunk { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SetTrackStateChunk) ), Some(f) => f(track, str, isundoOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ShowActionList(&self, caller: *mut root::KbdSectionInfo, callerWnd: root::HWND) { match self.pointers.ShowActionList { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ShowActionList) ), Some(f) => f(caller, callerWnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ShowConsoleMsg(&self, msg: *const ::std::os::raw::c_char) { match self.pointers.ShowConsoleMsg { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ShowConsoleMsg) ), Some(f) => f(msg), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ShowMessageBox( &self, msg: *const ::std::os::raw::c_char, title: *const ::std::os::raw::c_char, type_: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.ShowMessageBox { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ShowMessageBox) ), Some(f) => f(msg, title, type_), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ShowPopupMenu( &self, name: *const ::std::os::raw::c_char, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, hwndParentOptional: root::HWND, ctxOptional: *mut ::std::os::raw::c_void, ctx2Optional: ::std::os::raw::c_int, ctx3Optional: ::std::os::raw::c_int, ) { match self.pointers.ShowPopupMenu { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ShowPopupMenu) ), Some(f) => f( name, x, y, hwndParentOptional, ctxOptional, ctx2Optional, ctx3Optional, ), } } pub fn SLIDER2DB(&self, y: f64) -> f64 { match self.pointers.SLIDER2DB { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SLIDER2DB) ), Some(f) => f(y), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SnapToGrid(&self, project: *mut root::ReaProject, time_pos: f64) -> f64 { match self.pointers.SnapToGrid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SnapToGrid) ), Some(f) => f(project, time_pos), } } pub fn SoloAllTracks(&self, solo: ::std::os::raw::c_int) { match self.pointers.SoloAllTracks { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SoloAllTracks) ), Some(f) => f(solo), } } pub fn Splash_GetWnd(&self) -> root::HWND { match self.pointers.Splash_GetWnd { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Splash_GetWnd) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn SplitMediaItem( &self, item: *mut root::MediaItem, position: f64, ) -> *mut root::MediaItem { match self.pointers.SplitMediaItem { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(SplitMediaItem) ), Some(f) => f(item, position), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn StopPreview( &self, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int { match self.pointers.StopPreview { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(StopPreview) ), Some(f) => f(preview), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn StopTrackPreview( &self, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int { match self.pointers.StopTrackPreview { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(StopTrackPreview) ), Some(f) => f(preview), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn StopTrackPreview2( &self, proj: *mut ::std::os::raw::c_void, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int { match self.pointers.StopTrackPreview2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(StopTrackPreview2) ), Some(f) => f(proj, preview), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn stringToGuid(&self, str: *const ::std::os::raw::c_char, g: *mut root::GUID) { match self.pointers.stringToGuid { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(stringToGuid) ), Some(f) => f(str, g), } } pub fn StuffMIDIMessage( &self, mode: ::std::os::raw::c_int, msg1: ::std::os::raw::c_int, msg2: ::std::os::raw::c_int, msg3: ::std::os::raw::c_int, ) { match self.pointers.StuffMIDIMessage { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(StuffMIDIMessage) ), Some(f) => f(mode, msg1, msg2, msg3), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_AddByName( &self, take: *mut root::MediaItem_Take, fxname: *const ::std::os::raw::c_char, instantiate: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_AddByName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_AddByName) ), Some(f) => f(take, fxname, instantiate), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_CopyToTake( &self, src_take: *mut root::MediaItem_Take, src_fx: ::std::os::raw::c_int, dest_take: *mut root::MediaItem_Take, dest_fx: ::std::os::raw::c_int, is_move: bool, ) { match self.pointers.TakeFX_CopyToTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_CopyToTake) ), Some(f) => f(src_take, src_fx, dest_take, dest_fx, is_move), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_CopyToTrack( &self, src_take: *mut root::MediaItem_Take, src_fx: ::std::os::raw::c_int, dest_track: *mut root::MediaTrack, dest_fx: ::std::os::raw::c_int, is_move: bool, ) { match self.pointers.TakeFX_CopyToTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_CopyToTrack) ), Some(f) => f(src_take, src_fx, dest_track, dest_fx, is_move), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_Delete( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_Delete { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_Delete) ), Some(f) => f(take, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_EndParamEdit( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_EndParamEdit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_EndParamEdit) ), Some(f) => f(take, fx, param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_FormatParamValue( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_FormatParamValue { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_FormatParamValue) ), Some(f) => f(take, fx, param, val, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_FormatParamValueNormalized( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_FormatParamValueNormalized { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_FormatParamValueNormalized) ), Some(f) => f(take, fx, param, value, buf, buf_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetChainVisible( &self, take: *mut root::MediaItem_Take, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetChainVisible { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetChainVisible) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetCount(&self, take: *mut root::MediaItem_Take) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetCount { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetCount) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetEnabled( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetEnabled { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetEnabled) ), Some(f) => f(take, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetEnvelope( &self, take: *mut root::MediaItem_Take, fxindex: ::std::os::raw::c_int, parameterindex: ::std::os::raw::c_int, create: bool, ) -> *mut root::TrackEnvelope { match self.pointers.TakeFX_GetEnvelope { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetEnvelope) ), Some(f) => f(take, fxindex, parameterindex, create), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetFloatingWindow( &self, take: *mut root::MediaItem_Take, index: ::std::os::raw::c_int, ) -> root::HWND { match self.pointers.TakeFX_GetFloatingWindow { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetFloatingWindow) ), Some(f) => f(take, index), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetFormattedParamValue( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetFormattedParamValue { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetFormattedParamValue) ), Some(f) => f(take, fx, param, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetFXGUID( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> *mut root::GUID { match self.pointers.TakeFX_GetFXGUID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetFXGUID) ), Some(f) => f(take, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetFXName( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetFXName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetFXName) ), Some(f) => f(take, fx, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetIOSize( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, inputPinsOutOptional: *mut ::std::os::raw::c_int, outputPinsOutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetIOSize { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetIOSize) ), Some(f) => f(take, fx, inputPinsOutOptional, outputPinsOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetNamedConfigParm( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetNamedConfigParm { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetNamedConfigParm) ), Some(f) => f(take, fx, parmname, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetNumParams( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetNumParams { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetNumParams) ), Some(f) => f(take, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetOffline( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetOffline { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetOffline) ), Some(f) => f(take, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetOpen( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetOpen { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetOpen) ), Some(f) => f(take, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParam( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, ) -> f64 { match self.pointers.TakeFX_GetParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParam) ), Some(f) => f(take, fx, param, minvalOut, maxvalOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParameterStepSizes( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, stepOut: *mut f64, smallstepOut: *mut f64, largestepOut: *mut f64, istoggleOut: *mut bool, ) -> bool { match self.pointers.TakeFX_GetParameterStepSizes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParameterStepSizes) ), Some(f) => f( take, fx, param, stepOut, smallstepOut, largestepOut, istoggleOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParamEx( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, midvalOut: *mut f64, ) -> f64 { match self.pointers.TakeFX_GetParamEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParamEx) ), Some(f) => f(take, fx, param, minvalOut, maxvalOut, midvalOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParamFromIdent( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ident_str: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetParamFromIdent { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParamFromIdent) ), Some(f) => f(take, fx, ident_str), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParamIdent( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetParamIdent { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParamIdent) ), Some(f) => f(take, fx, param, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParamName( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetParamName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParamName) ), Some(f) => f(take, fx, param, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetParamNormalized( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> f64 { match self.pointers.TakeFX_GetParamNormalized { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetParamNormalized) ), Some(f) => f(take, fx, param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetPinMappings( &self, tr: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, high32OutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetPinMappings { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetPinMappings) ), Some(f) => f(tr, fx, isoutput, pin, high32OutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetPreset( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, presetnameOut: *mut ::std::os::raw::c_char, presetnameOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_GetPreset { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetPreset) ), Some(f) => f(take, fx, presetnameOut, presetnameOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetPresetIndex( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, numberOfPresetsOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TakeFX_GetPresetIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetPresetIndex) ), Some(f) => f(take, fx, numberOfPresetsOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_GetUserPresetFilename( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, fnOut: *mut ::std::os::raw::c_char, fnOut_sz: ::std::os::raw::c_int, ) { match self.pointers.TakeFX_GetUserPresetFilename { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_GetUserPresetFilename) ), Some(f) => f(take, fx, fnOut, fnOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_NavigatePresets( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, presetmove: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_NavigatePresets { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_NavigatePresets) ), Some(f) => f(take, fx, presetmove), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetEnabled( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, enabled: bool, ) { match self.pointers.TakeFX_SetEnabled { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetEnabled) ), Some(f) => f(take, fx, enabled), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetNamedConfigParm( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.TakeFX_SetNamedConfigParm { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetNamedConfigParm) ), Some(f) => f(take, fx, parmname, value), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetOffline( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, offline: bool, ) { match self.pointers.TakeFX_SetOffline { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetOffline) ), Some(f) => f(take, fx, offline), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetOpen( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, open: bool, ) { match self.pointers.TakeFX_SetOpen { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetOpen) ), Some(f) => f(take, fx, open), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetParam( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, ) -> bool { match self.pointers.TakeFX_SetParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetParam) ), Some(f) => f(take, fx, param, val), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetParamNormalized( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, ) -> bool { match self.pointers.TakeFX_SetParamNormalized { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetParamNormalized) ), Some(f) => f(take, fx, param, value), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetPinMappings( &self, tr: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, low32bits: ::std::os::raw::c_int, hi32bits: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_SetPinMappings { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetPinMappings) ), Some(f) => f(tr, fx, isoutput, pin, low32bits, hi32bits), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetPreset( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, presetname: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.TakeFX_SetPreset { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetPreset) ), Some(f) => f(take, fx, presetname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_SetPresetByIndex( &self, take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, idx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TakeFX_SetPresetByIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_SetPresetByIndex) ), Some(f) => f(take, fx, idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeFX_Show( &self, take: *mut root::MediaItem_Take, index: ::std::os::raw::c_int, showFlag: ::std::os::raw::c_int, ) { match self.pointers.TakeFX_Show { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeFX_Show) ), Some(f) => f(take, index, showFlag), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TakeIsMIDI(&self, take: *mut root::MediaItem_Take) -> bool { match self.pointers.TakeIsMIDI { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TakeIsMIDI) ), Some(f) => f(take), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ThemeLayout_GetLayout( &self, section: *const ::std::os::raw::c_char, idx: ::std::os::raw::c_int, nameOut: *mut ::std::os::raw::c_char, nameOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.ThemeLayout_GetLayout { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ThemeLayout_GetLayout) ), Some(f) => f(section, idx, nameOut, nameOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ThemeLayout_GetParameter( &self, wp: ::std::os::raw::c_int, descOutOptional: *mut *const ::std::os::raw::c_char, valueOutOptional: *mut ::std::os::raw::c_int, defValueOutOptional: *mut ::std::os::raw::c_int, minValueOutOptional: *mut ::std::os::raw::c_int, maxValueOutOptional: *mut ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char { match self.pointers.ThemeLayout_GetParameter { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ThemeLayout_GetParameter) ), Some(f) => f( wp, descOutOptional, valueOutOptional, defValueOutOptional, minValueOutOptional, maxValueOutOptional, ), } } pub fn ThemeLayout_RefreshAll(&self) { match self.pointers.ThemeLayout_RefreshAll { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ThemeLayout_RefreshAll) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ThemeLayout_SetLayout( &self, section: *const ::std::os::raw::c_char, layout: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.ThemeLayout_SetLayout { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ThemeLayout_SetLayout) ), Some(f) => f(section, layout), } } pub fn ThemeLayout_SetParameter( &self, wp: ::std::os::raw::c_int, value: ::std::os::raw::c_int, persist: bool, ) -> bool { match self.pointers.ThemeLayout_SetParameter { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ThemeLayout_SetParameter) ), Some(f) => f(wp, value, persist), } } pub fn time_precise(&self) -> f64 { match self.pointers.time_precise { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(time_precise) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap2_beatsToTime( &self, proj: *mut root::ReaProject, tpos: f64, measuresInOptional: *const ::std::os::raw::c_int, ) -> f64 { match self.pointers.TimeMap2_beatsToTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap2_beatsToTime) ), Some(f) => f(proj, tpos, measuresInOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap2_GetDividedBpmAtTime( &self, proj: *mut root::ReaProject, time: f64, ) -> f64 { match self.pointers.TimeMap2_GetDividedBpmAtTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap2_GetDividedBpmAtTime) ), Some(f) => f(proj, time), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap2_GetNextChangeTime(&self, proj: *mut root::ReaProject, time: f64) -> f64 { match self.pointers.TimeMap2_GetNextChangeTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap2_GetNextChangeTime) ), Some(f) => f(proj, time), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap2_QNToTime(&self, proj: *mut root::ReaProject, qn: f64) -> f64 { match self.pointers.TimeMap2_QNToTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap2_QNToTime) ), Some(f) => f(proj, qn), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap2_timeToBeats( &self, proj: *mut root::ReaProject, tpos: f64, measuresOutOptional: *mut ::std::os::raw::c_int, cmlOutOptional: *mut ::std::os::raw::c_int, fullbeatsOutOptional: *mut f64, cdenomOutOptional: *mut ::std::os::raw::c_int, ) -> f64 { match self.pointers.TimeMap2_timeToBeats { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap2_timeToBeats) ), Some(f) => f( proj, tpos, measuresOutOptional, cmlOutOptional, fullbeatsOutOptional, cdenomOutOptional, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap2_timeToQN(&self, proj: *mut root::ReaProject, tpos: f64) -> f64 { match self.pointers.TimeMap2_timeToQN { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap2_timeToQN) ), Some(f) => f(proj, tpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_curFrameRate( &self, proj: *mut root::ReaProject, dropFrameOutOptional: *mut bool, ) -> f64 { match self.pointers.TimeMap_curFrameRate { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_curFrameRate) ), Some(f) => f(proj, dropFrameOutOptional), } } pub fn TimeMap_GetDividedBpmAtTime(&self, time: f64) -> f64 { match self.pointers.TimeMap_GetDividedBpmAtTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_GetDividedBpmAtTime) ), Some(f) => f(time), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_GetMeasureInfo( &self, proj: *mut root::ReaProject, measure: ::std::os::raw::c_int, qn_startOut: *mut f64, qn_endOut: *mut f64, timesig_numOut: *mut ::std::os::raw::c_int, timesig_denomOut: *mut ::std::os::raw::c_int, tempoOut: *mut f64, ) -> f64 { match self.pointers.TimeMap_GetMeasureInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_GetMeasureInfo) ), Some(f) => f( proj, measure, qn_startOut, qn_endOut, timesig_numOut, timesig_denomOut, tempoOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_GetMetronomePattern( &self, proj: *mut root::ReaProject, time: f64, pattern: *mut ::std::os::raw::c_char, pattern_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TimeMap_GetMetronomePattern { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_GetMetronomePattern) ), Some(f) => f(proj, time, pattern, pattern_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_GetTimeSigAtTime( &self, proj: *mut root::ReaProject, time: f64, timesig_numOut: *mut ::std::os::raw::c_int, timesig_denomOut: *mut ::std::os::raw::c_int, tempoOut: *mut f64, ) { match self.pointers.TimeMap_GetTimeSigAtTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_GetTimeSigAtTime) ), Some(f) => f(proj, time, timesig_numOut, timesig_denomOut, tempoOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_QNToMeasures( &self, proj: *mut root::ReaProject, qn: f64, qnMeasureStartOutOptional: *mut f64, qnMeasureEndOutOptional: *mut f64, ) -> ::std::os::raw::c_int { match self.pointers.TimeMap_QNToMeasures { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_QNToMeasures) ), Some(f) => f(proj, qn, qnMeasureStartOutOptional, qnMeasureEndOutOptional), } } pub fn TimeMap_QNToTime(&self, qn: f64) -> f64 { match self.pointers.TimeMap_QNToTime { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_QNToTime) ), Some(f) => f(qn), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_QNToTime_abs(&self, proj: *mut root::ReaProject, qn: f64) -> f64 { match self.pointers.TimeMap_QNToTime_abs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_QNToTime_abs) ), Some(f) => f(proj, qn), } } pub fn TimeMap_timeToQN(&self, tpos: f64) -> f64 { match self.pointers.TimeMap_timeToQN { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_timeToQN) ), Some(f) => f(tpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TimeMap_timeToQN_abs(&self, proj: *mut root::ReaProject, tpos: f64) -> f64 { match self.pointers.TimeMap_timeToQN_abs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TimeMap_timeToQN_abs) ), Some(f) => f(proj, tpos), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ToggleTrackSendUIMute( &self, track: *mut root::MediaTrack, send_idx: ::std::os::raw::c_int, ) -> bool { match self.pointers.ToggleTrackSendUIMute { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ToggleTrackSendUIMute) ), Some(f) => f(track, send_idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Track_GetPeakHoldDB( &self, track: *mut root::MediaTrack, channel: ::std::os::raw::c_int, clear: bool, ) -> f64 { match self.pointers.Track_GetPeakHoldDB { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Track_GetPeakHoldDB) ), Some(f) => f(track, channel, clear), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Track_GetPeakInfo( &self, track: *mut root::MediaTrack, channel: ::std::os::raw::c_int, ) -> f64 { match self.pointers.Track_GetPeakInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Track_GetPeakInfo) ), Some(f) => f(track, channel), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackCtl_SetToolTip( &self, fmt: *const ::std::os::raw::c_char, xpos: ::std::os::raw::c_int, ypos: ::std::os::raw::c_int, topmost: bool, ) { match self.pointers.TrackCtl_SetToolTip { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackCtl_SetToolTip) ), Some(f) => f(fmt, xpos, ypos, topmost), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_AddByName( &self, track: *mut root::MediaTrack, fxname: *const ::std::os::raw::c_char, recFX: bool, instantiate: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_AddByName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_AddByName) ), Some(f) => f(track, fxname, recFX, instantiate), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_CopyToTake( &self, src_track: *mut root::MediaTrack, src_fx: ::std::os::raw::c_int, dest_take: *mut root::MediaItem_Take, dest_fx: ::std::os::raw::c_int, is_move: bool, ) { match self.pointers.TrackFX_CopyToTake { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_CopyToTake) ), Some(f) => f(src_track, src_fx, dest_take, dest_fx, is_move), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_CopyToTrack( &self, src_track: *mut root::MediaTrack, src_fx: ::std::os::raw::c_int, dest_track: *mut root::MediaTrack, dest_fx: ::std::os::raw::c_int, is_move: bool, ) { match self.pointers.TrackFX_CopyToTrack { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_CopyToTrack) ), Some(f) => f(src_track, src_fx, dest_track, dest_fx, is_move), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_Delete( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_Delete { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_Delete) ), Some(f) => f(track, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_EndParamEdit( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_EndParamEdit { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_EndParamEdit) ), Some(f) => f(track, fx, param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_FormatParamValue( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_FormatParamValue { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_FormatParamValue) ), Some(f) => f(track, fx, param, val, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_FormatParamValueNormalized( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_FormatParamValueNormalized { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_FormatParamValueNormalized) ), Some(f) => f(track, fx, param, value, buf, buf_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetByName( &self, track: *mut root::MediaTrack, fxname: *const ::std::os::raw::c_char, instantiate: bool, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetByName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetByName) ), Some(f) => f(track, fxname, instantiate), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetChainVisible( &self, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetChainVisible { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetChainVisible) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetCount(&self, track: *mut root::MediaTrack) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetCount { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetCount) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetEnabled( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetEnabled { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetEnabled) ), Some(f) => f(track, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetEQ( &self, track: *mut root::MediaTrack, instantiate: bool, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetEQ { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetEQ) ), Some(f) => f(track, instantiate), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetEQBandEnabled( &self, track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, bandtype: ::std::os::raw::c_int, bandidx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetEQBandEnabled { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetEQBandEnabled) ), Some(f) => f(track, fxidx, bandtype, bandidx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetEQParam( &self, track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, paramidx: ::std::os::raw::c_int, bandtypeOut: *mut ::std::os::raw::c_int, bandidxOut: *mut ::std::os::raw::c_int, paramtypeOut: *mut ::std::os::raw::c_int, normvalOut: *mut f64, ) -> bool { match self.pointers.TrackFX_GetEQParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetEQParam) ), Some(f) => f( track, fxidx, paramidx, bandtypeOut, bandidxOut, paramtypeOut, normvalOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetFloatingWindow( &self, track: *mut root::MediaTrack, index: ::std::os::raw::c_int, ) -> root::HWND { match self.pointers.TrackFX_GetFloatingWindow { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetFloatingWindow) ), Some(f) => f(track, index), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetFormattedParamValue( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetFormattedParamValue { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetFormattedParamValue) ), Some(f) => f(track, fx, param, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetFXGUID( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> *mut root::GUID { match self.pointers.TrackFX_GetFXGUID { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetFXGUID) ), Some(f) => f(track, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetFXName( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetFXName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetFXName) ), Some(f) => f(track, fx, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetInstrument( &self, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetInstrument { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetInstrument) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetIOSize( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, inputPinsOutOptional: *mut ::std::os::raw::c_int, outputPinsOutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetIOSize { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetIOSize) ), Some(f) => f(track, fx, inputPinsOutOptional, outputPinsOutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetNamedConfigParm( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetNamedConfigParm { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetNamedConfigParm) ), Some(f) => f(track, fx, parmname, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetNumParams( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetNumParams { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetNumParams) ), Some(f) => f(track, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetOffline( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetOffline { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetOffline) ), Some(f) => f(track, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetOpen( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetOpen { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetOpen) ), Some(f) => f(track, fx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParam( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, ) -> f64 { match self.pointers.TrackFX_GetParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParam) ), Some(f) => f(track, fx, param, minvalOut, maxvalOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParameterStepSizes( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, stepOut: *mut f64, smallstepOut: *mut f64, largestepOut: *mut f64, istoggleOut: *mut bool, ) -> bool { match self.pointers.TrackFX_GetParameterStepSizes { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParameterStepSizes) ), Some(f) => f( track, fx, param, stepOut, smallstepOut, largestepOut, istoggleOut, ), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParamEx( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, midvalOut: *mut f64, ) -> f64 { match self.pointers.TrackFX_GetParamEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParamEx) ), Some(f) => f(track, fx, param, minvalOut, maxvalOut, midvalOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParamFromIdent( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ident_str: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetParamFromIdent { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParamFromIdent) ), Some(f) => f(track, fx, ident_str), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParamIdent( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetParamIdent { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParamIdent) ), Some(f) => f(track, fx, param, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParamName( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetParamName { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParamName) ), Some(f) => f(track, fx, param, bufOut, bufOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetParamNormalized( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> f64 { match self.pointers.TrackFX_GetParamNormalized { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetParamNormalized) ), Some(f) => f(track, fx, param), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetPinMappings( &self, tr: *mut root::MediaTrack, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, high32OutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetPinMappings { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetPinMappings) ), Some(f) => f(tr, fx, isoutput, pin, high32OutOptional), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetPreset( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, presetnameOut: *mut ::std::os::raw::c_char, presetnameOut_sz: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_GetPreset { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetPreset) ), Some(f) => f(track, fx, presetnameOut, presetnameOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetPresetIndex( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, numberOfPresetsOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetPresetIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetPresetIndex) ), Some(f) => f(track, fx, numberOfPresetsOut), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetRecChainVisible( &self, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetRecChainVisible { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetRecChainVisible) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetRecCount( &self, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int { match self.pointers.TrackFX_GetRecCount { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetRecCount) ), Some(f) => f(track), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_GetUserPresetFilename( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, fnOut: *mut ::std::os::raw::c_char, fnOut_sz: ::std::os::raw::c_int, ) { match self.pointers.TrackFX_GetUserPresetFilename { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_GetUserPresetFilename) ), Some(f) => f(track, fx, fnOut, fnOut_sz), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_NavigatePresets( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, presetmove: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_NavigatePresets { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_NavigatePresets) ), Some(f) => f(track, fx, presetmove), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetEnabled( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, enabled: bool, ) { match self.pointers.TrackFX_SetEnabled { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetEnabled) ), Some(f) => f(track, fx, enabled), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetEQBandEnabled( &self, track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, bandtype: ::std::os::raw::c_int, bandidx: ::std::os::raw::c_int, enable: bool, ) -> bool { match self.pointers.TrackFX_SetEQBandEnabled { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetEQBandEnabled) ), Some(f) => f(track, fxidx, bandtype, bandidx, enable), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetEQParam( &self, track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, bandtype: ::std::os::raw::c_int, bandidx: ::std::os::raw::c_int, paramtype: ::std::os::raw::c_int, val: f64, isnorm: bool, ) -> bool { match self.pointers.TrackFX_SetEQParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetEQParam) ), Some(f) => f(track, fxidx, bandtype, bandidx, paramtype, val, isnorm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetNamedConfigParm( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.TrackFX_SetNamedConfigParm { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetNamedConfigParm) ), Some(f) => f(track, fx, parmname, value), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetOffline( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, offline: bool, ) { match self.pointers.TrackFX_SetOffline { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetOffline) ), Some(f) => f(track, fx, offline), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetOpen( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, open: bool, ) { match self.pointers.TrackFX_SetOpen { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetOpen) ), Some(f) => f(track, fx, open), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetParam( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, ) -> bool { match self.pointers.TrackFX_SetParam { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetParam) ), Some(f) => f(track, fx, param, val), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetParamNormalized( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, ) -> bool { match self.pointers.TrackFX_SetParamNormalized { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetParamNormalized) ), Some(f) => f(track, fx, param, value), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetPinMappings( &self, tr: *mut root::MediaTrack, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, low32bits: ::std::os::raw::c_int, hi32bits: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_SetPinMappings { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetPinMappings) ), Some(f) => f(tr, fx, isoutput, pin, low32bits, hi32bits), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetPreset( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, presetname: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.TrackFX_SetPreset { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetPreset) ), Some(f) => f(track, fx, presetname), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_SetPresetByIndex( &self, track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, idx: ::std::os::raw::c_int, ) -> bool { match self.pointers.TrackFX_SetPresetByIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_SetPresetByIndex) ), Some(f) => f(track, fx, idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn TrackFX_Show( &self, track: *mut root::MediaTrack, index: ::std::os::raw::c_int, showFlag: ::std::os::raw::c_int, ) { match self.pointers.TrackFX_Show { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackFX_Show) ), Some(f) => f(track, index, showFlag), } } pub fn TrackList_AdjustWindows(&self, isMinor: bool) { match self.pointers.TrackList_AdjustWindows { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackList_AdjustWindows) ), Some(f) => f(isMinor), } } pub fn TrackList_UpdateAllExternalSurfaces(&self) { match self.pointers.TrackList_UpdateAllExternalSurfaces { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(TrackList_UpdateAllExternalSurfaces) ), Some(f) => f(), } } pub fn Undo_BeginBlock(&self) { match self.pointers.Undo_BeginBlock { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_BeginBlock) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_BeginBlock2(&self, proj: *mut root::ReaProject) { match self.pointers.Undo_BeginBlock2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_BeginBlock2) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_CanRedo2( &self, proj: *mut root::ReaProject, ) -> *const ::std::os::raw::c_char { match self.pointers.Undo_CanRedo2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_CanRedo2) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_CanUndo2( &self, proj: *mut root::ReaProject, ) -> *const ::std::os::raw::c_char { match self.pointers.Undo_CanUndo2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_CanUndo2) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_DoRedo2(&self, proj: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.Undo_DoRedo2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_DoRedo2) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_DoUndo2(&self, proj: *mut root::ReaProject) -> ::std::os::raw::c_int { match self.pointers.Undo_DoUndo2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_DoUndo2) ), Some(f) => f(proj), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_EndBlock( &self, descchange: *const ::std::os::raw::c_char, extraflags: ::std::os::raw::c_int, ) { match self.pointers.Undo_EndBlock { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_EndBlock) ), Some(f) => f(descchange, extraflags), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_EndBlock2( &self, proj: *mut root::ReaProject, descchange: *const ::std::os::raw::c_char, extraflags: ::std::os::raw::c_int, ) { match self.pointers.Undo_EndBlock2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_EndBlock2) ), Some(f) => f(proj, descchange, extraflags), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_OnStateChange(&self, descchange: *const ::std::os::raw::c_char) { match self.pointers.Undo_OnStateChange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_OnStateChange) ), Some(f) => f(descchange), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_OnStateChange2( &self, proj: *mut root::ReaProject, descchange: *const ::std::os::raw::c_char, ) { match self.pointers.Undo_OnStateChange2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_OnStateChange2) ), Some(f) => f(proj, descchange), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_OnStateChange_Item( &self, proj: *mut root::ReaProject, name: *const ::std::os::raw::c_char, item: *mut root::MediaItem, ) { match self.pointers.Undo_OnStateChange_Item { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_OnStateChange_Item) ), Some(f) => f(proj, name, item), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_OnStateChangeEx( &self, descchange: *const ::std::os::raw::c_char, whichStates: ::std::os::raw::c_int, trackparm: ::std::os::raw::c_int, ) { match self.pointers.Undo_OnStateChangeEx { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_OnStateChangeEx) ), Some(f) => f(descchange, whichStates, trackparm), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn Undo_OnStateChangeEx2( &self, proj: *mut root::ReaProject, descchange: *const ::std::os::raw::c_char, whichStates: ::std::os::raw::c_int, trackparm: ::std::os::raw::c_int, ) { match self.pointers.Undo_OnStateChangeEx2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(Undo_OnStateChangeEx2) ), Some(f) => f(proj, descchange, whichStates, trackparm), } } pub fn update_disk_counters( &self, readamt: ::std::os::raw::c_int, writeamt: ::std::os::raw::c_int, ) { match self.pointers.update_disk_counters { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(update_disk_counters) ), Some(f) => f(readamt, writeamt), } } pub fn UpdateArrange(&self) { match self.pointers.UpdateArrange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(UpdateArrange) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn UpdateItemInProject(&self, item: *mut root::MediaItem) { match self.pointers.UpdateItemInProject { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(UpdateItemInProject) ), Some(f) => f(item), } } pub fn UpdateTimeline(&self) { match self.pointers.UpdateTimeline { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(UpdateTimeline) ), Some(f) => f(), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ValidatePtr( &self, pointer: *mut ::std::os::raw::c_void, ctypename: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.ValidatePtr { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ValidatePtr) ), Some(f) => f(pointer, ctypename), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ValidatePtr2( &self, proj: *mut root::ReaProject, pointer: *mut ::std::os::raw::c_void, ctypename: *const ::std::os::raw::c_char, ) -> bool { match self.pointers.ValidatePtr2 { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ValidatePtr2) ), Some(f) => f(proj, pointer, ctypename), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn ViewPrefs( &self, page: ::std::os::raw::c_int, pageByName: *const ::std::os::raw::c_char, ) { match self.pointers.ViewPrefs { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(ViewPrefs) ), Some(f) => f(page, pageByName), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn WDL_VirtualWnd_ScaledBlitBG( &self, dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::WDL_VirtualWnd_BGCfg, destx: ::std::os::raw::c_int, desty: ::std::os::raw::c_int, destw: ::std::os::raw::c_int, desth: ::std::os::raw::c_int, clipx: ::std::os::raw::c_int, clipy: ::std::os::raw::c_int, clipw: ::std::os::raw::c_int, cliph: ::std::os::raw::c_int, alpha: f32, mode: ::std::os::raw::c_int, ) -> bool { match self.pointers.WDL_VirtualWnd_ScaledBlitBG { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(WDL_VirtualWnd_ScaledBlitBG) ), Some(f) => f( dest, src, destx, desty, destw, desth, clipx, clipy, clipw, cliph, alpha, mode, ), } } pub fn GetMidiInput(&self, idx: ::std::os::raw::c_int) -> *mut root::midi_Input { match self.pointers.GetMidiInput { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMidiInput) ), Some(f) => f(idx), } } pub fn GetMidiOutput(&self, idx: ::std::os::raw::c_int) -> *mut root::midi_Output { match self.pointers.GetMidiOutput { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(GetMidiOutput) ), Some(f) => f(idx), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn InitializeCoolSB(&self, hwnd: root::HWND) -> root::BOOL { match self.pointers.InitializeCoolSB { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(InitializeCoolSB) ), Some(f) => f(hwnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn UninitializeCoolSB(&self, hwnd: root::HWND) -> root::HRESULT { match self.pointers.UninitializeCoolSB { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(UninitializeCoolSB) ), Some(f) => f(hwnd), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_SetMinThumbSize( &self, hwnd: root::HWND, wBar: root::UINT, size: root::UINT, ) -> root::BOOL { match self.pointers.CoolSB_SetMinThumbSize { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_SetMinThumbSize) ), Some(f) => f(hwnd, wBar, size), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_GetScrollInfo( &self, hwnd: root::HWND, fnBar: ::std::os::raw::c_int, lpsi: root::LPSCROLLINFO, ) -> root::BOOL { match self.pointers.CoolSB_GetScrollInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_GetScrollInfo) ), Some(f) => f(hwnd, fnBar, lpsi), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_SetScrollInfo( &self, hwnd: root::HWND, fnBar: ::std::os::raw::c_int, lpsi: root::LPSCROLLINFO, fRedraw: root::BOOL, ) -> ::std::os::raw::c_int { match self.pointers.CoolSB_SetScrollInfo { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_SetScrollInfo) ), Some(f) => f(hwnd, fnBar, lpsi, fRedraw), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_SetScrollPos( &self, hwnd: root::HWND, nBar: ::std::os::raw::c_int, nPos: ::std::os::raw::c_int, fRedraw: root::BOOL, ) -> ::std::os::raw::c_int { match self.pointers.CoolSB_SetScrollPos { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_SetScrollPos) ), Some(f) => f(hwnd, nBar, nPos, fRedraw), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_SetScrollRange( &self, hwnd: root::HWND, nBar: ::std::os::raw::c_int, nMinPos: ::std::os::raw::c_int, nMaxPos: ::std::os::raw::c_int, fRedraw: root::BOOL, ) -> ::std::os::raw::c_int { match self.pointers.CoolSB_SetScrollRange { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_SetScrollRange) ), Some(f) => f(hwnd, nBar, nMinPos, nMaxPos, fRedraw), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_ShowScrollBar( &self, hwnd: root::HWND, wBar: ::std::os::raw::c_int, fShow: root::BOOL, ) -> root::BOOL { match self.pointers.CoolSB_ShowScrollBar { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_ShowScrollBar) ), Some(f) => f(hwnd, wBar, fShow), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_SetResizingThumb( &self, hwnd: root::HWND, active: root::BOOL, ) -> root::BOOL { match self.pointers.CoolSB_SetResizingThumb { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_SetResizingThumb) ), Some(f) => f(hwnd, active), } } #[doc = r" # Safety"] #[doc = r""] #[doc = r" REAPER can crash if you pass an invalid pointer."] pub unsafe fn CoolSB_SetThemeIndex( &self, hwnd: root::HWND, idx: ::std::os::raw::c_int, ) -> root::BOOL { match self.pointers.CoolSB_SetThemeIndex { None => panic!( "Attempt to use a function that has not been loaded: {}", stringify!(CoolSB_SetThemeIndex) ), Some(f) => f(hwnd, idx), } } } #[doc = r" Container for the REAPER function pointers."] #[derive(Copy, Clone, Default)] pub struct ReaperFunctionPointers { pub(crate) loaded_count: u32, pub __mergesort: Option< unsafe extern "C" fn( base: *mut ::std::os::raw::c_void, nmemb: usize, size: usize, cmpfunc: ::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, >, tmpspace: *mut ::std::os::raw::c_void, ), >, pub AddCustomizableMenu: Option< unsafe extern "C" fn( menuidstr: *const ::std::os::raw::c_char, menuname: *const ::std::os::raw::c_char, kbdsecname: *const ::std::os::raw::c_char, addtomainmenu: bool, ) -> bool, >, pub AddExtensionsMainMenu: Option<extern "C" fn() -> bool>, pub AddMediaItemToTrack: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack) -> *mut root::MediaItem>, pub AddProjectMarker: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, wantidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub AddProjectMarker2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, wantidx: ::std::os::raw::c_int, color: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub AddRemoveReaScript: Option< unsafe extern "C" fn( add: bool, sectionID: ::std::os::raw::c_int, scriptfn: *const ::std::os::raw::c_char, commit: bool, ) -> ::std::os::raw::c_int, >, pub AddTakeToMediaItem: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> *mut root::MediaItem_Take>, pub AddTempoTimeSigMarker: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, timepos: f64, bpm: f64, timesig_num: ::std::os::raw::c_int, timesig_denom: ::std::os::raw::c_int, lineartempochange: bool, ) -> bool, >, pub adjustZoom: Option< extern "C" fn( amt: f64, forceset: ::std::os::raw::c_int, doupd: bool, centermode: ::std::os::raw::c_int, ), >, pub AnyTrackSolo: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> bool>, pub APIExists: Option<unsafe extern "C" fn(function_name: *const ::std::os::raw::c_char) -> bool>, pub APITest: Option<extern "C" fn()>, pub ApplyNudge: Option< unsafe extern "C" fn( project: *mut root::ReaProject, nudgeflag: ::std::os::raw::c_int, nudgewhat: ::std::os::raw::c_int, nudgeunits: ::std::os::raw::c_int, value: f64, reverse: bool, copies: ::std::os::raw::c_int, ) -> bool, >, pub ArmCommand: Option< unsafe extern "C" fn( cmd: ::std::os::raw::c_int, sectionname: *const ::std::os::raw::c_char, ), >, pub Audio_Init: Option<extern "C" fn()>, pub Audio_IsPreBuffer: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub Audio_IsRunning: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub Audio_Quit: Option<extern "C" fn()>, pub Audio_RegHardwareHook: Option< unsafe extern "C" fn( isAdd: bool, reg: *mut root::audio_hook_register_t, ) -> ::std::os::raw::c_int, >, pub AudioAccessorStateChanged: Option<unsafe extern "C" fn(accessor: *mut root::reaper_functions::AudioAccessor) -> bool>, pub AudioAccessorUpdate: Option<unsafe extern "C" fn(accessor: *mut root::reaper_functions::AudioAccessor)>, pub AudioAccessorValidateState: Option<unsafe extern "C" fn(accessor: *mut root::reaper_functions::AudioAccessor) -> bool>, pub BypassFxAllTracks: Option<extern "C" fn(bypass: ::std::os::raw::c_int)>, pub CalculatePeaks: Option< unsafe extern "C" fn( srcBlock: *mut root::PCM_source_transfer_t, pksBlock: *mut root::PCM_source_peaktransfer_t, ) -> ::std::os::raw::c_int, >, pub CalculatePeaksFloatSrcPtr: Option< unsafe extern "C" fn( srcBlock: *mut root::PCM_source_transfer_t, pksBlock: *mut root::PCM_source_peaktransfer_t, ) -> ::std::os::raw::c_int, >, pub ClearAllRecArmed: Option<extern "C" fn()>, pub ClearConsole: Option<extern "C" fn()>, pub ClearPeakCache: Option<extern "C" fn()>, pub ColorFromNative: Option< unsafe extern "C" fn( col: ::std::os::raw::c_int, rOut: *mut ::std::os::raw::c_int, gOut: *mut ::std::os::raw::c_int, bOut: *mut ::std::os::raw::c_int, ), >, pub ColorToNative: Option< extern "C" fn( r: ::std::os::raw::c_int, g: ::std::os::raw::c_int, b: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub CountActionShortcuts: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub CountAutomationItems: Option<unsafe extern "C" fn(env: *mut root::TrackEnvelope) -> ::std::os::raw::c_int>, pub CountEnvelopePoints: Option<unsafe extern "C" fn(envelope: *mut root::TrackEnvelope) -> ::std::os::raw::c_int>, pub CountEnvelopePointsEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub CountMediaItems: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub CountProjectMarkers: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, num_markersOut: *mut ::std::os::raw::c_int, num_regionsOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub CountSelectedMediaItems: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub CountSelectedTracks: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub CountSelectedTracks2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, wantmaster: bool, ) -> ::std::os::raw::c_int, >, pub CountTakeEnvelopes: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> ::std::os::raw::c_int>, pub CountTakes: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> ::std::os::raw::c_int>, pub CountTCPFXParms: Option< unsafe extern "C" fn( project: *mut root::ReaProject, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int, >, pub CountTempoTimeSigMarkers: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub CountTrackEnvelopes: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub CountTrackMediaItems: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub CountTracks: Option<unsafe extern "C" fn(projOptional: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub CreateLocalOscHandler: Option< unsafe extern "C" fn( obj: *mut ::std::os::raw::c_void, callback: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void, >, pub CreateMIDIInput: Option<extern "C" fn(dev: ::std::os::raw::c_int) -> *mut root::midi_Input>, pub CreateMIDIOutput: Option< unsafe extern "C" fn( dev: ::std::os::raw::c_int, streamMode: bool, msoffset100: *mut ::std::os::raw::c_int, ) -> *mut root::midi_Output, >, pub CreateNewMIDIItemInProj: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, starttime: f64, endtime: f64, qnInOptional: *const bool, ) -> *mut root::MediaItem, >, pub CreateTakeAudioAccessor: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, ) -> *mut root::reaper_functions::AudioAccessor, >, pub CreateTrackAudioAccessor: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, ) -> *mut root::reaper_functions::AudioAccessor, >, pub CreateTrackSend: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, desttrInOptional: *mut root::MediaTrack, ) -> ::std::os::raw::c_int, >, pub CSurf_FlushUndo: Option<extern "C" fn(force: bool)>, pub CSurf_GetTouchState: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, isPan: ::std::os::raw::c_int) -> bool, >, pub CSurf_GoEnd: Option<extern "C" fn()>, pub CSurf_GoStart: Option<extern "C" fn()>, pub CSurf_NumTracks: Option<extern "C" fn(mcpView: bool) -> ::std::os::raw::c_int>, pub CSurf_OnArrow: Option<extern "C" fn(whichdir: ::std::os::raw::c_int, wantzoom: bool)>, pub CSurf_OnFwd: Option<extern "C" fn(seekplay: ::std::os::raw::c_int)>, pub CSurf_OnFXChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, en: ::std::os::raw::c_int) -> bool, >, pub CSurf_OnInputMonitorChange: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, monitor: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub CSurf_OnInputMonitorChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, monitor: ::std::os::raw::c_int, allowgang: bool, ) -> ::std::os::raw::c_int, >, pub CSurf_OnMuteChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, mute: ::std::os::raw::c_int) -> bool, >, pub CSurf_OnMuteChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, mute: ::std::os::raw::c_int, allowgang: bool, ) -> bool, >, pub CSurf_OnOscControlMessage: Option<unsafe extern "C" fn(msg: *const ::std::os::raw::c_char, arg: *const f32)>, pub CSurf_OnPanChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, pan: f64, relative: bool) -> f64, >, pub CSurf_OnPanChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, pan: f64, relative: bool, allowGang: bool, ) -> f64, >, pub CSurf_OnPause: Option<extern "C" fn()>, pub CSurf_OnPlay: Option<extern "C" fn()>, pub CSurf_OnPlayRateChange: Option<extern "C" fn(playrate: f64)>, pub CSurf_OnRecArmChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, recarm: ::std::os::raw::c_int) -> bool, >, pub CSurf_OnRecArmChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, recarm: ::std::os::raw::c_int, allowgang: bool, ) -> bool, >, pub CSurf_OnRecord: Option<extern "C" fn()>, pub CSurf_OnRecvPanChange: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, pan: f64, relative: bool, ) -> f64, >, pub CSurf_OnRecvVolumeChange: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, volume: f64, relative: bool, ) -> f64, >, pub CSurf_OnRew: Option<extern "C" fn(seekplay: ::std::os::raw::c_int)>, pub CSurf_OnRewFwd: Option<extern "C" fn(seekplay: ::std::os::raw::c_int, dir: ::std::os::raw::c_int)>, pub CSurf_OnScroll: Option<extern "C" fn(xdir: ::std::os::raw::c_int, ydir: ::std::os::raw::c_int)>, pub CSurf_OnSelectedChange: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, selected: ::std::os::raw::c_int, ) -> bool, >, pub CSurf_OnSendPanChange: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, pan: f64, relative: bool, ) -> f64, >, pub CSurf_OnSendVolumeChange: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, volume: f64, relative: bool, ) -> f64, >, pub CSurf_OnSoloChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, solo: ::std::os::raw::c_int) -> bool, >, pub CSurf_OnSoloChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, solo: ::std::os::raw::c_int, allowgang: bool, ) -> bool, >, pub CSurf_OnStop: Option<extern "C" fn()>, pub CSurf_OnTempoChange: Option<extern "C" fn(bpm: f64)>, pub CSurf_OnTrackSelection: Option<unsafe extern "C" fn(trackid: *mut root::MediaTrack)>, pub CSurf_OnVolumeChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, volume: f64, relative: bool) -> f64, >, pub CSurf_OnVolumeChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, volume: f64, relative: bool, allowGang: bool, ) -> f64, >, pub CSurf_OnWidthChange: Option< unsafe extern "C" fn(trackid: *mut root::MediaTrack, width: f64, relative: bool) -> f64, >, pub CSurf_OnWidthChangeEx: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, width: f64, relative: bool, allowGang: bool, ) -> f64, >, pub CSurf_OnZoom: Option<extern "C" fn(xdir: ::std::os::raw::c_int, ydir: ::std::os::raw::c_int)>, pub CSurf_ResetAllCachedVolPanStates: Option<extern "C" fn()>, pub CSurf_ScrubAmt: Option<extern "C" fn(amt: f64)>, pub CSurf_SetAutoMode: Option< unsafe extern "C" fn( mode: ::std::os::raw::c_int, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetPlayState: Option< unsafe extern "C" fn( play: bool, pause: bool, rec: bool, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetRepeatState: Option<unsafe extern "C" fn(rep: bool, ignoresurf: *mut root::IReaperControlSurface)>, pub CSurf_SetSurfaceMute: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, mute: bool, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetSurfacePan: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, pan: f64, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetSurfaceRecArm: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, recarm: bool, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetSurfaceSelected: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, selected: bool, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetSurfaceSolo: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, solo: bool, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetSurfaceVolume: Option< unsafe extern "C" fn( trackid: *mut root::MediaTrack, volume: f64, ignoresurf: *mut root::IReaperControlSurface, ), >, pub CSurf_SetTrackListChange: Option<extern "C" fn()>, pub CSurf_TrackFromID: Option<extern "C" fn(idx: ::std::os::raw::c_int, mcpView: bool) -> *mut root::MediaTrack>, pub CSurf_TrackToID: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, mcpView: bool) -> ::std::os::raw::c_int, >, pub DB2SLIDER: Option<extern "C" fn(x: f64) -> f64>, pub DeleteActionShortcut: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, shortcutidx: ::std::os::raw::c_int, ) -> bool, >, pub DeleteEnvelopePointEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ptidx: ::std::os::raw::c_int, ) -> bool, >, pub DeleteEnvelopePointRange: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, time_start: f64, time_end: f64, ) -> bool, >, pub DeleteEnvelopePointRangeEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, time_start: f64, time_end: f64, ) -> bool, >, pub DeleteExtState: Option< unsafe extern "C" fn( section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, persist: bool, ), >, pub DeleteProjectMarker: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, ) -> bool, >, pub DeleteProjectMarkerByIndex: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnidx: ::std::os::raw::c_int, ) -> bool, >, pub DeleteTakeMarker: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int) -> bool, >, pub DeleteTakeStretchMarkers: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, countInOptional: *const ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub DeleteTempoTimeSigMarker: Option< unsafe extern "C" fn( project: *mut root::ReaProject, markerindex: ::std::os::raw::c_int, ) -> bool, >, pub DeleteTrack: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack)>, pub DeleteTrackMediaItem: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack, it: *mut root::MediaItem) -> bool>, pub DestroyAudioAccessor: Option<unsafe extern "C" fn(accessor: *mut root::reaper_functions::AudioAccessor)>, pub DestroyLocalOscHandler: Option<unsafe extern "C" fn(local_osc_handler: *mut ::std::os::raw::c_void)>, pub DoActionShortcutDialog: Option< unsafe extern "C" fn( hwnd: root::HWND, section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, shortcutidx: ::std::os::raw::c_int, ) -> bool, >, pub Dock_UpdateDockID: Option< unsafe extern "C" fn( ident_str: *const ::std::os::raw::c_char, whichDock: ::std::os::raw::c_int, ), >, pub DockGetPosition: Option<extern "C" fn(whichDock: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub DockIsChildOfDock: Option< unsafe extern "C" fn( hwnd: root::HWND, isFloatingDockerOut: *mut bool, ) -> ::std::os::raw::c_int, >, pub DockWindowActivate: Option<unsafe extern "C" fn(hwnd: root::HWND)>, pub DockWindowAdd: Option< unsafe extern "C" fn( hwnd: root::HWND, name: *const ::std::os::raw::c_char, pos: ::std::os::raw::c_int, allowShow: bool, ), >, pub DockWindowAddEx: Option< unsafe extern "C" fn( hwnd: root::HWND, name: *const ::std::os::raw::c_char, identstr: *const ::std::os::raw::c_char, allowShow: bool, ), >, pub DockWindowRefresh: Option<extern "C" fn()>, pub DockWindowRefreshForHWND: Option<unsafe extern "C" fn(hwnd: root::HWND)>, pub DockWindowRemove: Option<unsafe extern "C" fn(hwnd: root::HWND)>, pub DuplicateCustomizableMenu: Option< unsafe extern "C" fn( srcmenu: *mut ::std::os::raw::c_void, destmenu: *mut ::std::os::raw::c_void, ) -> bool, >, pub EditTempoTimeSigMarker: Option< unsafe extern "C" fn( project: *mut root::ReaProject, markerindex: ::std::os::raw::c_int, ) -> bool, >, pub EnsureNotCompletelyOffscreen: Option<unsafe extern "C" fn(rInOut: *mut root::RECT)>, pub EnumerateFiles: Option< unsafe extern "C" fn( path: *const ::std::os::raw::c_char, fileindex: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub EnumerateSubdirectories: Option< unsafe extern "C" fn( path: *const ::std::os::raw::c_char, subdirindex: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub EnumPitchShiftModes: Option< unsafe extern "C" fn( mode: ::std::os::raw::c_int, strOut: *mut *const ::std::os::raw::c_char, ) -> bool, >, pub EnumPitchShiftSubModes: Option< extern "C" fn( mode: ::std::os::raw::c_int, submode: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub EnumProjectMarkers: Option< unsafe extern "C" fn( idx: ::std::os::raw::c_int, isrgnOut: *mut bool, posOut: *mut f64, rgnendOut: *mut f64, nameOut: *mut *const ::std::os::raw::c_char, markrgnindexnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub EnumProjectMarkers2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, idx: ::std::os::raw::c_int, isrgnOut: *mut bool, posOut: *mut f64, rgnendOut: *mut f64, nameOut: *mut *const ::std::os::raw::c_char, markrgnindexnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub EnumProjectMarkers3: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, idx: ::std::os::raw::c_int, isrgnOut: *mut bool, posOut: *mut f64, rgnendOut: *mut f64, nameOut: *mut *const ::std::os::raw::c_char, markrgnindexnumberOut: *mut ::std::os::raw::c_int, colorOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub EnumProjects: Option< unsafe extern "C" fn( idx: ::std::os::raw::c_int, projfnOutOptional: *mut ::std::os::raw::c_char, projfnOutOptional_sz: ::std::os::raw::c_int, ) -> *mut root::ReaProject, >, pub EnumProjExtState: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, extname: *const ::std::os::raw::c_char, idx: ::std::os::raw::c_int, keyOutOptional: *mut ::std::os::raw::c_char, keyOutOptional_sz: ::std::os::raw::c_int, valOutOptional: *mut ::std::os::raw::c_char, valOutOptional_sz: ::std::os::raw::c_int, ) -> bool, >, pub EnumRegionRenderMatrix: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, regionindex: ::std::os::raw::c_int, rendertrack: ::std::os::raw::c_int, ) -> *mut root::MediaTrack, >, pub EnumTrackMIDIProgramNames: Option< unsafe extern "C" fn( track: ::std::os::raw::c_int, programNumber: ::std::os::raw::c_int, programName: *mut ::std::os::raw::c_char, programName_sz: ::std::os::raw::c_int, ) -> bool, >, pub EnumTrackMIDIProgramNamesEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, track: *mut root::MediaTrack, programNumber: ::std::os::raw::c_int, programName: *mut ::std::os::raw::c_char, programName_sz: ::std::os::raw::c_int, ) -> bool, >, pub Envelope_Evaluate: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, time: f64, samplerate: f64, samplesRequested: ::std::os::raw::c_int, valueOutOptional: *mut f64, dVdSOutOptional: *mut f64, ddVdSOutOptional: *mut f64, dddVdSOutOptional: *mut f64, ) -> ::std::os::raw::c_int, >, pub Envelope_FormatValue: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, value: f64, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ), >, pub Envelope_GetParentTake: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, indexOutOptional: *mut ::std::os::raw::c_int, index2OutOptional: *mut ::std::os::raw::c_int, ) -> *mut root::MediaItem_Take, >, pub Envelope_GetParentTrack: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, indexOutOptional: *mut ::std::os::raw::c_int, index2OutOptional: *mut ::std::os::raw::c_int, ) -> *mut root::MediaTrack, >, pub Envelope_SortPoints: Option<unsafe extern "C" fn(envelope: *mut root::TrackEnvelope) -> bool>, pub Envelope_SortPointsEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ) -> bool, >, pub ExecProcess: Option< unsafe extern "C" fn( cmdline: *const ::std::os::raw::c_char, timeoutmsec: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub file_exists: Option<unsafe extern "C" fn(path: *const ::std::os::raw::c_char) -> bool>, pub FindTempoTimeSigMarker: Option< unsafe extern "C" fn(project: *mut root::ReaProject, time: f64) -> ::std::os::raw::c_int, >, pub format_timestr: Option< unsafe extern "C" fn( tpos: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ), >, pub format_timestr_len: Option< unsafe extern "C" fn( tpos: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, offset: f64, modeoverride: ::std::os::raw::c_int, ), >, pub format_timestr_pos: Option< unsafe extern "C" fn( tpos: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, modeoverride: ::std::os::raw::c_int, ), >, pub FreeHeapPtr: Option<unsafe extern "C" fn(ptr: *mut ::std::os::raw::c_void)>, pub genGuid: Option<unsafe extern "C" fn(g: *mut root::GUID)>, pub get_config_var: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, szOut: *mut ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void, >, pub get_config_var_string: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub get_ini_file: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub get_midi_config_var: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, szOut: *mut ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void, >, pub GetActionShortcutDesc: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, cmdID: ::std::os::raw::c_int, shortcutidx: ::std::os::raw::c_int, desc: *mut ::std::os::raw::c_char, desclen: ::std::os::raw::c_int, ) -> bool, >, pub GetActiveTake: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> *mut root::MediaItem_Take>, pub GetAllProjectPlayStates: Option<unsafe extern "C" fn(ignoreProject: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub GetAppVersion: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub GetArmedCommand: Option< unsafe extern "C" fn( secOut: *mut ::std::os::raw::c_char, secOut_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetAudioAccessorEndTime: Option<unsafe extern "C" fn(accessor: *mut root::reaper_functions::AudioAccessor) -> f64>, pub GetAudioAccessorHash: Option< unsafe extern "C" fn( accessor: *mut root::reaper_functions::AudioAccessor, hashNeed128: *mut ::std::os::raw::c_char, ), >, pub GetAudioAccessorSamples: Option< unsafe extern "C" fn( accessor: *mut root::reaper_functions::AudioAccessor, samplerate: ::std::os::raw::c_int, numchannels: ::std::os::raw::c_int, starttime_sec: f64, numsamplesperchannel: ::std::os::raw::c_int, samplebuffer: *mut f64, ) -> ::std::os::raw::c_int, >, pub GetAudioAccessorStartTime: Option<unsafe extern "C" fn(accessor: *mut root::reaper_functions::AudioAccessor) -> f64>, pub GetAudioDeviceInfo: Option< unsafe extern "C" fn( attribute: *const ::std::os::raw::c_char, descOut: *mut ::std::os::raw::c_char, descOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetColorTheme: Option< extern "C" fn(idx: ::std::os::raw::c_int, defval: ::std::os::raw::c_int) -> root::INT_PTR, >, pub GetColorThemeStruct: Option< unsafe extern "C" fn(szOut: *mut ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void, >, pub GetConfigWantsDock: Option< unsafe extern "C" fn(ident_str: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int, >, pub GetContextMenu: Option<extern "C" fn(idx: ::std::os::raw::c_int) -> root::HMENU>, pub GetCurrentProjectInLoadSave: Option<extern "C" fn() -> *mut root::ReaProject>, pub GetCursorContext: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetCursorContext2: Option<extern "C" fn(want_last_valid: bool) -> ::std::os::raw::c_int>, pub GetCursorPosition: Option<extern "C" fn() -> f64>, pub GetCursorPositionEx: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> f64>, pub GetDisplayedMediaItemColor: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> ::std::os::raw::c_int>, pub GetDisplayedMediaItemColor2: Option< unsafe extern "C" fn( item: *mut root::MediaItem, take: *mut root::MediaItem_Take, ) -> ::std::os::raw::c_int, >, pub GetEnvelopeInfo_Value: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, parmname: *const ::std::os::raw::c_char, ) -> f64, >, pub GetEnvelopeName: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetEnvelopePoint: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, ptidx: ::std::os::raw::c_int, timeOutOptional: *mut f64, valueOutOptional: *mut f64, shapeOutOptional: *mut ::std::os::raw::c_int, tensionOutOptional: *mut f64, selectedOutOptional: *mut bool, ) -> bool, >, pub GetEnvelopePointByTime: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, time: f64, ) -> ::std::os::raw::c_int, >, pub GetEnvelopePointByTimeEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, time: f64, ) -> ::std::os::raw::c_int, >, pub GetEnvelopePointEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ptidx: ::std::os::raw::c_int, timeOutOptional: *mut f64, valueOutOptional: *mut f64, shapeOutOptional: *mut ::std::os::raw::c_int, tensionOutOptional: *mut f64, selectedOutOptional: *mut bool, ) -> bool, >, pub GetEnvelopeScalingMode: Option<unsafe extern "C" fn(env: *mut root::TrackEnvelope) -> ::std::os::raw::c_int>, pub GetEnvelopeStateChunk: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, strNeedBig: *mut ::std::os::raw::c_char, strNeedBig_sz: ::std::os::raw::c_int, isundoOptional: bool, ) -> bool, >, pub GetExePath: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub GetExtState: Option< unsafe extern "C" fn( section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, ) -> *const ::std::os::raw::c_char, >, pub GetFocusedFX: Option< unsafe extern "C" fn( tracknumberOut: *mut ::std::os::raw::c_int, itemnumberOut: *mut ::std::os::raw::c_int, fxnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetFocusedFX2: Option< unsafe extern "C" fn( tracknumberOut: *mut ::std::os::raw::c_int, itemnumberOut: *mut ::std::os::raw::c_int, fxnumberOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetFreeDiskSpaceForRecordPath: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, pathidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetFXEnvelope: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxindex: ::std::os::raw::c_int, parameterindex: ::std::os::raw::c_int, create: bool, ) -> *mut root::TrackEnvelope, >, pub GetGlobalAutomationOverride: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetHZoomLevel: Option<extern "C" fn() -> f64>, pub GetIconThemePointer: Option< unsafe extern "C" fn(name: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_void, >, pub GetIconThemePointerForDPI: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, dpisc: ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void, >, pub GetIconThemeStruct: Option< unsafe extern "C" fn(szOut: *mut ::std::os::raw::c_int) -> *mut ::std::os::raw::c_void, >, pub GetInputChannelName: Option<extern "C" fn(channelIndex: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char>, pub GetInputOutputLatency: Option< unsafe extern "C" fn( inputlatencyOut: *mut ::std::os::raw::c_int, outputLatencyOut: *mut ::std::os::raw::c_int, ), >, pub GetItemEditingTime2: Option< unsafe extern "C" fn( which_itemOut: *mut *mut root::PCM_source, flagsOut: *mut ::std::os::raw::c_int, ) -> f64, >, pub GetItemFromPoint: Option< unsafe extern "C" fn( screen_x: ::std::os::raw::c_int, screen_y: ::std::os::raw::c_int, allow_locked: bool, takeOutOptional: *mut *mut root::MediaItem_Take, ) -> *mut root::MediaItem, >, pub GetItemProjectContext: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> *mut root::ReaProject>, pub GetItemStateChunk: Option< unsafe extern "C" fn( item: *mut root::MediaItem, strNeedBig: *mut ::std::os::raw::c_char, strNeedBig_sz: ::std::os::raw::c_int, isundoOptional: bool, ) -> bool, >, pub GetLastColorThemeFile: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub GetLastMarkerAndCurRegion: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, time: f64, markeridxOut: *mut ::std::os::raw::c_int, regionidxOut: *mut ::std::os::raw::c_int, ), >, pub GetLastTouchedFX: Option< unsafe extern "C" fn( tracknumberOut: *mut ::std::os::raw::c_int, fxnumberOut: *mut ::std::os::raw::c_int, paramnumberOut: *mut ::std::os::raw::c_int, ) -> bool, >, pub GetLastTouchedTrack: Option<extern "C" fn() -> *mut root::MediaTrack>, pub GetMainHwnd: Option<extern "C" fn() -> root::HWND>, pub GetMasterMuteSoloFlags: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetMasterTrack: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> *mut root::MediaTrack>, pub GetMasterTrackVisibility: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetMaxMidiInputs: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetMaxMidiOutputs: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetMediaFileMetadata: Option< unsafe extern "C" fn( mediaSource: *mut root::PCM_source, identifier: *const ::std::os::raw::c_char, bufOutNeedBig: *mut ::std::os::raw::c_char, bufOutNeedBig_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetMediaItem: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, itemidx: ::std::os::raw::c_int, ) -> *mut root::MediaItem, >, pub GetMediaItem_Track: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> *mut root::MediaTrack>, pub GetMediaItemInfo_Value: Option< unsafe extern "C" fn( item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, ) -> f64, >, pub GetMediaItemNumTakes: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> ::std::os::raw::c_int>, pub GetMediaItemTake: Option< unsafe extern "C" fn( item: *mut root::MediaItem, tk: ::std::os::raw::c_int, ) -> *mut root::MediaItem_Take, >, pub GetMediaItemTake_Item: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> *mut root::MediaItem>, pub GetMediaItemTake_Peaks: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, peakrate: f64, starttime: f64, numchannels: ::std::os::raw::c_int, numsamplesperchannel: ::std::os::raw::c_int, want_extra_type: ::std::os::raw::c_int, buf: *mut f64, ) -> ::std::os::raw::c_int, >, pub GetMediaItemTake_Source: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> *mut root::PCM_source>, pub GetMediaItemTake_Track: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> *mut root::MediaTrack>, pub GetMediaItemTakeByGUID: Option< unsafe extern "C" fn( project: *mut root::ReaProject, guid: *const root::GUID, ) -> *mut root::MediaItem_Take, >, pub GetMediaItemTakeInfo_Value: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, ) -> f64, >, pub GetMediaItemTrack: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> *mut root::MediaTrack>, pub GetMediaSourceFileName: Option< unsafe extern "C" fn( source: *mut root::PCM_source, filenamebufOut: *mut ::std::os::raw::c_char, filenamebufOut_sz: ::std::os::raw::c_int, ), >, pub GetMediaSourceLength: Option< unsafe extern "C" fn(source: *mut root::PCM_source, lengthIsQNOut: *mut bool) -> f64, >, pub GetMediaSourceNumChannels: Option<unsafe extern "C" fn(source: *mut root::PCM_source) -> ::std::os::raw::c_int>, pub GetMediaSourceParent: Option<unsafe extern "C" fn(src: *mut root::PCM_source) -> *mut root::PCM_source>, pub GetMediaSourceSampleRate: Option<unsafe extern "C" fn(source: *mut root::PCM_source) -> ::std::os::raw::c_int>, pub GetMediaSourceType: Option< unsafe extern "C" fn( source: *mut root::PCM_source, typebufOut: *mut ::std::os::raw::c_char, typebufOut_sz: ::std::os::raw::c_int, ), >, pub GetMediaTrackInfo_Value: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, ) -> f64, >, pub GetMIDIInputName: Option< unsafe extern "C" fn( dev: ::std::os::raw::c_int, nameout: *mut ::std::os::raw::c_char, nameout_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetMIDIOutputName: Option< unsafe extern "C" fn( dev: ::std::os::raw::c_int, nameout: *mut ::std::os::raw::c_char, nameout_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetMixerScroll: Option<extern "C" fn() -> *mut root::MediaTrack>, pub GetMouseModifier: Option< unsafe extern "C" fn( context: *const ::std::os::raw::c_char, modifier_flag: ::std::os::raw::c_int, actionOut: *mut ::std::os::raw::c_char, actionOut_sz: ::std::os::raw::c_int, ), >, pub GetMousePosition: Option< unsafe extern "C" fn(xOut: *mut ::std::os::raw::c_int, yOut: *mut ::std::os::raw::c_int), >, pub GetNumAudioInputs: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetNumAudioOutputs: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetNumMIDIInputs: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetNumMIDIOutputs: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetNumTakeMarkers: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> ::std::os::raw::c_int>, pub GetNumTracks: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetOS: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub GetOutputChannelName: Option<extern "C" fn(channelIndex: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char>, pub GetOutputLatency: Option<extern "C" fn() -> f64>, pub GetParentTrack: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> *mut root::MediaTrack>, pub GetPeakFileName: Option< unsafe extern "C" fn( fn_: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ), >, pub GetPeakFileNameEx: Option< unsafe extern "C" fn( fn_: *const ::std::os::raw::c_char, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, forWrite: bool, ), >, pub GetPeakFileNameEx2: Option< unsafe extern "C" fn( fn_: *const ::std::os::raw::c_char, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, forWrite: bool, peaksfileextension: *const ::std::os::raw::c_char, ), >, pub GetPeaksBitmap: Option< unsafe extern "C" fn( pks: *mut root::PCM_source_peaktransfer_t, maxamp: f64, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, bmp: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut ::std::os::raw::c_void, >, pub GetPlayPosition: Option<extern "C" fn() -> f64>, pub GetPlayPosition2: Option<extern "C" fn() -> f64>, pub GetPlayPosition2Ex: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> f64>, pub GetPlayPositionEx: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> f64>, pub GetPlayState: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub GetPlayStateEx: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub GetPreferredDiskReadMode: Option< unsafe extern "C" fn( mode: *mut ::std::os::raw::c_int, nb: *mut ::std::os::raw::c_int, bs: *mut ::std::os::raw::c_int, ), >, pub GetPreferredDiskReadModePeak: Option< unsafe extern "C" fn( mode: *mut ::std::os::raw::c_int, nb: *mut ::std::os::raw::c_int, bs: *mut ::std::os::raw::c_int, ), >, pub GetPreferredDiskWriteMode: Option< unsafe extern "C" fn( mode: *mut ::std::os::raw::c_int, nb: *mut ::std::os::raw::c_int, bs: *mut ::std::os::raw::c_int, ), >, pub GetProjectLength: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> f64>, pub GetProjectName: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ), >, pub GetProjectPath: Option< unsafe extern "C" fn(bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int), >, pub GetProjectPathEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ), >, pub GetProjectStateChangeCount: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub GetProjectTimeOffset: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, rndframe: bool) -> f64>, pub GetProjectTimeSignature: Option<unsafe extern "C" fn(bpmOut: *mut f64, bpiOut: *mut f64)>, pub GetProjectTimeSignature2: Option< unsafe extern "C" fn(proj: *mut root::ReaProject, bpmOut: *mut f64, bpiOut: *mut f64), >, pub GetProjExtState: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, extname: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, valOutNeedBig: *mut ::std::os::raw::c_char, valOutNeedBig_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetResourcePath: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub GetSelectedEnvelope: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> *mut root::TrackEnvelope>, pub GetSelectedMediaItem: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, selitem: ::std::os::raw::c_int, ) -> *mut root::MediaItem, >, pub GetSelectedTrack: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, seltrackidx: ::std::os::raw::c_int, ) -> *mut root::MediaTrack, >, pub GetSelectedTrack2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, seltrackidx: ::std::os::raw::c_int, wantmaster: bool, ) -> *mut root::MediaTrack, >, pub GetSelectedTrackEnvelope: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> *mut root::TrackEnvelope>, pub GetSet_ArrangeView2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, isSet: bool, screen_x_start: ::std::os::raw::c_int, screen_x_end: ::std::os::raw::c_int, start_timeOut: *mut f64, end_timeOut: *mut f64, ), >, pub GetSet_LoopTimeRange: Option< unsafe extern "C" fn( isSet: bool, isLoop: bool, startOut: *mut f64, endOut: *mut f64, allowautoseek: bool, ), >, pub GetSet_LoopTimeRange2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, isSet: bool, isLoop: bool, startOut: *mut f64, endOut: *mut f64, allowautoseek: bool, ), >, pub GetSetAutomationItemInfo: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, desc: *const ::std::os::raw::c_char, value: f64, is_set: bool, ) -> f64, >, pub GetSetAutomationItemInfo_String: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, desc: *const ::std::os::raw::c_char, valuestrNeedBig: *mut ::std::os::raw::c_char, is_set: bool, ) -> bool, >, pub GetSetEnvelopeInfo_String: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool, >, pub GetSetEnvelopeState: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetSetEnvelopeState2: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, isundo: bool, ) -> bool, >, pub GetSetItemState: Option< unsafe extern "C" fn( item: *mut root::MediaItem, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetSetItemState2: Option< unsafe extern "C" fn( item: *mut root::MediaItem, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, isundo: bool, ) -> bool, >, pub GetSetMediaItemInfo: Option< unsafe extern "C" fn( item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void, >, pub GetSetMediaItemInfo_String: Option< unsafe extern "C" fn( item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool, >, pub GetSetMediaItemTakeInfo: Option< unsafe extern "C" fn( tk: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void, >, pub GetSetMediaItemTakeInfo_String: Option< unsafe extern "C" fn( tk: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool, >, pub GetSetMediaTrackInfo: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void, >, pub GetSetMediaTrackInfo_String: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool, >, pub GetSetObjectState: Option< unsafe extern "C" fn( obj: *mut ::std::os::raw::c_void, str: *const ::std::os::raw::c_char, ) -> *mut ::std::os::raw::c_char, >, pub GetSetObjectState2: Option< unsafe extern "C" fn( obj: *mut ::std::os::raw::c_void, str: *const ::std::os::raw::c_char, isundo: bool, ) -> *mut ::std::os::raw::c_char, >, pub GetSetProjectAuthor: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, set: bool, author: *mut ::std::os::raw::c_char, author_sz: ::std::os::raw::c_int, ), >, pub GetSetProjectGrid: Option< unsafe extern "C" fn( project: *mut root::ReaProject, set: bool, divisionInOutOptional: *mut f64, swingmodeInOutOptional: *mut ::std::os::raw::c_int, swingamtInOutOptional: *mut f64, ) -> ::std::os::raw::c_int, >, pub GetSetProjectInfo: Option< unsafe extern "C" fn( project: *mut root::ReaProject, desc: *const ::std::os::raw::c_char, value: f64, is_set: bool, ) -> f64, >, pub GetSetProjectInfo_String: Option< unsafe extern "C" fn( project: *mut root::ReaProject, desc: *const ::std::os::raw::c_char, valuestrNeedBig: *mut ::std::os::raw::c_char, is_set: bool, ) -> bool, >, pub GetSetProjectNotes: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, set: bool, notesNeedBig: *mut ::std::os::raw::c_char, notesNeedBig_sz: ::std::os::raw::c_int, ), >, pub GetSetRepeat: Option<extern "C" fn(val: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub GetSetRepeatEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, val: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetSetTrackGroupMembership: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, groupname: *const ::std::os::raw::c_char, setmask: ::std::os::raw::c_uint, setvalue: ::std::os::raw::c_uint, ) -> ::std::os::raw::c_uint, >, pub GetSetTrackGroupMembershipHigh: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, groupname: *const ::std::os::raw::c_char, setmask: ::std::os::raw::c_uint, setvalue: ::std::os::raw::c_uint, ) -> ::std::os::raw::c_uint, >, pub GetSetTrackMIDISupportFile: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, track: *mut root::MediaTrack, which: ::std::os::raw::c_int, filename: *const ::std::os::raw::c_char, ) -> *const ::std::os::raw::c_char, >, pub GetSetTrackSendInfo: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, setNewValue: *mut ::std::os::raw::c_void, ) -> *mut ::std::os::raw::c_void, >, pub GetSetTrackSendInfo_String: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, stringNeedBig: *mut ::std::os::raw::c_char, setNewValue: bool, ) -> bool, >, pub GetSetTrackState: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetSetTrackState2: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, str: *mut ::std::os::raw::c_char, str_sz: ::std::os::raw::c_int, isundo: bool, ) -> bool, >, pub GetSubProjectFromSource: Option<unsafe extern "C" fn(src: *mut root::PCM_source) -> *mut root::ReaProject>, pub GetTake: Option< unsafe extern "C" fn( item: *mut root::MediaItem, takeidx: ::std::os::raw::c_int, ) -> *mut root::MediaItem_Take, >, pub GetTakeEnvelope: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, envidx: ::std::os::raw::c_int, ) -> *mut root::TrackEnvelope, >, pub GetTakeEnvelopeByName: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, envname: *const ::std::os::raw::c_char, ) -> *mut root::TrackEnvelope, >, pub GetTakeMarker: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, nameOut: *mut ::std::os::raw::c_char, nameOut_sz: ::std::os::raw::c_int, colorOutOptional: *mut ::std::os::raw::c_int, ) -> f64, >, pub GetTakeName: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> *const ::std::os::raw::c_char, >, pub GetTakeNumStretchMarkers: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> ::std::os::raw::c_int>, pub GetTakeStretchMarker: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, posOut: *mut f64, srcposOutOptional: *mut f64, ) -> ::std::os::raw::c_int, >, pub GetTakeStretchMarkerSlope: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int) -> f64, >, pub GetTCPFXParm: Option< unsafe extern "C" fn( project: *mut root::ReaProject, track: *mut root::MediaTrack, index: ::std::os::raw::c_int, fxindexOut: *mut ::std::os::raw::c_int, parmidxOut: *mut ::std::os::raw::c_int, ) -> bool, >, pub GetTempoMatchPlayRate: Option< unsafe extern "C" fn( source: *mut root::PCM_source, srcscale: f64, position: f64, mult: f64, rateOut: *mut f64, targetlenOut: *mut f64, ) -> bool, >, pub GetTempoTimeSigMarker: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, ptidx: ::std::os::raw::c_int, timeposOut: *mut f64, measureposOut: *mut ::std::os::raw::c_int, beatposOut: *mut f64, bpmOut: *mut f64, timesig_numOut: *mut ::std::os::raw::c_int, timesig_denomOut: *mut ::std::os::raw::c_int, lineartempoOut: *mut bool, ) -> bool, >, pub GetThemeColor: Option< unsafe extern "C" fn( ini_key: *const ::std::os::raw::c_char, flagsOptional: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetThingFromPoint: Option< unsafe extern "C" fn( screen_x: ::std::os::raw::c_int, screen_y: ::std::os::raw::c_int, infoOut: *mut ::std::os::raw::c_char, infoOut_sz: ::std::os::raw::c_int, ) -> *mut root::MediaTrack, >, pub GetToggleCommandState: Option<extern "C" fn(command_id: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub GetToggleCommandState2: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetToggleCommandStateEx: Option< extern "C" fn( section_id: ::std::os::raw::c_int, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetToggleCommandStateThroughHooks: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, command_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetTooltipWindow: Option<extern "C" fn() -> root::HWND>, pub GetTrack: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, trackidx: ::std::os::raw::c_int, ) -> *mut root::MediaTrack, >, pub GetTrackAutomationMode: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub GetTrackColor: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub GetTrackDepth: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub GetTrackEnvelope: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, envidx: ::std::os::raw::c_int, ) -> *mut root::TrackEnvelope, >, pub GetTrackEnvelopeByChunkName: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, cfgchunkname_or_guid: *const ::std::os::raw::c_char, ) -> *mut root::TrackEnvelope, >, pub GetTrackEnvelopeByName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, envname: *const ::std::os::raw::c_char, ) -> *mut root::TrackEnvelope, >, pub GetTrackFromPoint: Option< unsafe extern "C" fn( screen_x: ::std::os::raw::c_int, screen_y: ::std::os::raw::c_int, infoOutOptional: *mut ::std::os::raw::c_int, ) -> *mut root::MediaTrack, >, pub GetTrackGUID: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack) -> *mut root::GUID>, pub GetTrackInfo: Option< unsafe extern "C" fn( track: root::INT_PTR, flags: *mut ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub GetTrackMediaItem: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, itemidx: ::std::os::raw::c_int, ) -> *mut root::MediaItem, >, pub GetTrackMIDILyrics: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, flag: ::std::os::raw::c_int, bufOutWantNeedBig: *mut ::std::os::raw::c_char, bufOutWantNeedBig_sz: *mut ::std::os::raw::c_int, ) -> bool, >, pub GetTrackMIDINoteName: Option< extern "C" fn( track: ::std::os::raw::c_int, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub GetTrackMIDINoteNameEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, track: *mut root::MediaTrack, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub GetTrackMIDINoteRange: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, track: *mut root::MediaTrack, note_loOut: *mut ::std::os::raw::c_int, note_hiOut: *mut ::std::os::raw::c_int, ), >, pub GetTrackName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetTrackNumMediaItems: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub GetTrackNumSends: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GetTrackReceiveName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetTrackReceiveUIMute: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, muteOut: *mut bool, ) -> bool, >, pub GetTrackReceiveUIVolPan: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, recv_index: ::std::os::raw::c_int, volumeOut: *mut f64, panOut: *mut f64, ) -> bool, >, pub GetTrackSendInfo_Value: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, ) -> f64, >, pub GetTrackSendName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub GetTrackSendUIMute: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, muteOut: *mut bool, ) -> bool, >, pub GetTrackSendUIVolPan: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, send_index: ::std::os::raw::c_int, volumeOut: *mut f64, panOut: *mut f64, ) -> bool, >, pub GetTrackState: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, flagsOut: *mut ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub GetTrackStateChunk: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, strNeedBig: *mut ::std::os::raw::c_char, strNeedBig_sz: ::std::os::raw::c_int, isundoOptional: bool, ) -> bool, >, pub GetTrackUIMute: Option<unsafe extern "C" fn(track: *mut root::MediaTrack, muteOut: *mut bool) -> bool>, pub GetTrackUIPan: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, pan1Out: *mut f64, pan2Out: *mut f64, panmodeOut: *mut ::std::os::raw::c_int, ) -> bool, >, pub GetTrackUIVolPan: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, volumeOut: *mut f64, panOut: *mut f64, ) -> bool, >, pub GetUnderrunTime: Option< unsafe extern "C" fn( audio_xrunOutOptional: *mut ::std::os::raw::c_uint, media_xrunOutOptional: *mut ::std::os::raw::c_uint, curtimeOutOptional: *mut ::std::os::raw::c_uint, ), >, pub GetUserFileNameForRead: Option< unsafe extern "C" fn( filenameNeed4096: *mut ::std::os::raw::c_char, title: *const ::std::os::raw::c_char, defext: *const ::std::os::raw::c_char, ) -> bool, >, pub GetUserInputs: Option< unsafe extern "C" fn( title: *const ::std::os::raw::c_char, num_inputs: ::std::os::raw::c_int, captions_csv: *const ::std::os::raw::c_char, retvals_csv: *mut ::std::os::raw::c_char, retvals_csv_sz: ::std::os::raw::c_int, ) -> bool, >, pub GoToMarker: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, marker_index: ::std::os::raw::c_int, use_timeline_order: bool, ), >, pub GoToRegion: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, region_index: ::std::os::raw::c_int, use_timeline_order: bool, ), >, pub GR_SelectColor: Option< unsafe extern "C" fn( hwnd: root::HWND, colorOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub GSC_mainwnd: Option<extern "C" fn(t: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub guidToString: Option<unsafe extern "C" fn(g: *const root::GUID, destNeed64: *mut ::std::os::raw::c_char)>, pub HasExtState: Option< unsafe extern "C" fn( section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, ) -> bool, >, pub HasTrackMIDIPrograms: Option<extern "C" fn(track: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char>, pub HasTrackMIDIProgramsEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, track: *mut root::MediaTrack, ) -> *const ::std::os::raw::c_char, >, pub Help_Set: Option< unsafe extern "C" fn(helpstring: *const ::std::os::raw::c_char, is_temporary_help: bool), >, pub HiresPeaksFromSource: Option< unsafe extern "C" fn( src: *mut root::PCM_source, block: *mut root::PCM_source_peaktransfer_t, ), >, pub image_resolve_fn: Option< unsafe extern "C" fn( in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, ), >, pub InsertAutomationItem: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, pool_id: ::std::os::raw::c_int, position: f64, length: f64, ) -> ::std::os::raw::c_int, >, pub InsertEnvelopePoint: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, time: f64, value: f64, shape: ::std::os::raw::c_int, tension: f64, selected: bool, noSortInOptional: *mut bool, ) -> bool, >, pub InsertEnvelopePointEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, time: f64, value: f64, shape: ::std::os::raw::c_int, tension: f64, selected: bool, noSortInOptional: *mut bool, ) -> bool, >, pub InsertMedia: Option< unsafe extern "C" fn( file: *const ::std::os::raw::c_char, mode: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub InsertMediaSection: Option< unsafe extern "C" fn( file: *const ::std::os::raw::c_char, mode: ::std::os::raw::c_int, startpct: f64, endpct: f64, pitchshift: f64, ) -> ::std::os::raw::c_int, >, pub InsertTrackAtIndex: Option<extern "C" fn(idx: ::std::os::raw::c_int, wantDefaults: bool)>, pub IsInRealTimeAudio: Option<extern "C" fn() -> ::std::os::raw::c_int>, pub IsItemTakeActiveForPlayback: Option< unsafe extern "C" fn(item: *mut root::MediaItem, take: *mut root::MediaItem_Take) -> bool, >, pub IsMediaExtension: Option<unsafe extern "C" fn(ext: *const ::std::os::raw::c_char, wantOthers: bool) -> bool>, pub IsMediaItemSelected: Option<unsafe extern "C" fn(item: *mut root::MediaItem) -> bool>, pub IsProjectDirty: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub IsREAPER: Option<extern "C" fn() -> bool>, pub IsTrackSelected: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> bool>, pub IsTrackVisible: Option<unsafe extern "C" fn(track: *mut root::MediaTrack, mixer: bool) -> bool>, pub joystick_create: Option< unsafe extern "C" fn( guid: *const root::GUID, ) -> *mut root::reaper_functions::joystick_device, >, pub joystick_destroy: Option<unsafe extern "C" fn(device: *mut root::reaper_functions::joystick_device)>, pub joystick_enum: Option< unsafe extern "C" fn( index: ::std::os::raw::c_int, namestrOutOptional: *mut *const ::std::os::raw::c_char, ) -> *const ::std::os::raw::c_char, >, pub joystick_getaxis: Option< unsafe extern "C" fn( dev: *mut root::reaper_functions::joystick_device, axis: ::std::os::raw::c_int, ) -> f64, >, pub joystick_getbuttonmask: Option< unsafe extern "C" fn( dev: *mut root::reaper_functions::joystick_device, ) -> ::std::os::raw::c_uint, >, pub joystick_getinfo: Option< unsafe extern "C" fn( dev: *mut root::reaper_functions::joystick_device, axesOutOptional: *mut ::std::os::raw::c_int, povsOutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub joystick_getpov: Option< unsafe extern "C" fn( dev: *mut root::reaper_functions::joystick_device, pov: ::std::os::raw::c_int, ) -> f64, >, pub joystick_update: Option<unsafe extern "C" fn(dev: *mut root::reaper_functions::joystick_device) -> bool>, pub kbd_enumerateActions: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, idx: ::std::os::raw::c_int, nameOut: *mut *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int, >, pub kbd_formatKeyName: Option<unsafe extern "C" fn(ac: *mut root::ACCEL, s: *mut ::std::os::raw::c_char)>, pub kbd_getCommandName: Option< unsafe extern "C" fn( cmd: ::std::os::raw::c_int, s: *mut ::std::os::raw::c_char, section: *mut root::KbdSectionInfo, ), >, pub kbd_getTextFromCmd: Option< unsafe extern "C" fn( cmd: root::DWORD, section: *mut root::KbdSectionInfo, ) -> *const ::std::os::raw::c_char, >, pub KBD_OnMainActionEx: Option< unsafe extern "C" fn( cmd: ::std::os::raw::c_int, val: ::std::os::raw::c_int, valhw: ::std::os::raw::c_int, relmode: ::std::os::raw::c_int, hwnd: root::HWND, proj: *mut root::ReaProject, ) -> ::std::os::raw::c_int, >, pub kbd_OnMidiEvent: Option< unsafe extern "C" fn(evt: *mut root::MIDI_event_t, dev_index: ::std::os::raw::c_int), >, pub kbd_OnMidiList: Option< unsafe extern "C" fn(list: *mut root::MIDI_eventlist, dev_index: ::std::os::raw::c_int), >, pub kbd_ProcessActionsMenu: Option<unsafe extern "C" fn(menu: root::HMENU, section: *mut root::KbdSectionInfo)>, pub kbd_processMidiEventActionEx: Option< unsafe extern "C" fn( evt: *mut root::MIDI_event_t, section: *mut root::KbdSectionInfo, hwndCtx: root::HWND, ) -> bool, >, pub kbd_reprocessMenu: Option<unsafe extern "C" fn(menu: root::HMENU, section: *mut root::KbdSectionInfo)>, pub kbd_RunCommandThroughHooks: Option< unsafe extern "C" fn( section: *mut root::KbdSectionInfo, actionCommandID: *mut ::std::os::raw::c_int, val: *mut ::std::os::raw::c_int, valhw: *mut ::std::os::raw::c_int, relmode: *mut ::std::os::raw::c_int, hwnd: root::HWND, ) -> bool, >, pub kbd_translateAccelerator: Option< unsafe extern "C" fn( hwnd: root::HWND, msg: *mut root::MSG, section: *mut root::KbdSectionInfo, ) -> ::std::os::raw::c_int, >, pub kbd_translateMouse: Option< unsafe extern "C" fn( winmsg: *mut ::std::os::raw::c_void, midimsg: *mut ::std::os::raw::c_uchar, ) -> bool, >, pub LICE__Destroy: Option<unsafe extern "C" fn(bm: *mut root::reaper_functions::LICE_IBitmap)>, pub LICE__DestroyFont: Option<unsafe extern "C" fn(font: *mut root::reaper_functions::LICE_IFont)>, pub LICE__DrawText: Option< unsafe extern "C" fn( font: *mut root::reaper_functions::LICE_IFont, bm: *mut root::reaper_functions::LICE_IBitmap, str: *const ::std::os::raw::c_char, strcnt: ::std::os::raw::c_int, rect: *mut root::RECT, dtFlags: root::UINT, ) -> ::std::os::raw::c_int, >, pub LICE__GetBits: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut ::std::os::raw::c_void, >, pub LICE__GetDC: Option<unsafe extern "C" fn(bm: *mut root::reaper_functions::LICE_IBitmap) -> root::HDC>, pub LICE__GetHeight: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, ) -> ::std::os::raw::c_int, >, pub LICE__GetRowSpan: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, ) -> ::std::os::raw::c_int, >, pub LICE__GetWidth: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, ) -> ::std::os::raw::c_int, >, pub LICE__IsFlipped: Option<unsafe extern "C" fn(bm: *mut root::reaper_functions::LICE_IBitmap) -> bool>, pub LICE__resize: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, ) -> bool, >, pub LICE__SetBkColor: Option< unsafe extern "C" fn( font: *mut root::reaper_functions::LICE_IFont, color: root::reaper_functions::LICE_pixel, ) -> root::reaper_functions::LICE_pixel, >, pub LICE__SetFromHFont: Option< unsafe extern "C" fn( font: *mut root::reaper_functions::LICE_IFont, hfont: root::HFONT, flags: ::std::os::raw::c_int, ), >, pub LICE__SetTextColor: Option< unsafe extern "C" fn( font: *mut root::reaper_functions::LICE_IFont, color: root::reaper_functions::LICE_pixel, ) -> root::reaper_functions::LICE_pixel, >, pub LICE__SetTextCombineMode: Option< unsafe extern "C" fn( ifont: *mut root::reaper_functions::LICE_IFont, mode: ::std::os::raw::c_int, alpha: f32, ), >, pub LICE_Arc: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, cx: f32, cy: f32, r: f32, minAngle: f32, maxAngle: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ), >, pub LICE_Blit: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, srcx: ::std::os::raw::c_int, srcy: ::std::os::raw::c_int, srcw: ::std::os::raw::c_int, srch: ::std::os::raw::c_int, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_Blur: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, srcx: ::std::os::raw::c_int, srcy: ::std::os::raw::c_int, srcw: ::std::os::raw::c_int, srch: ::std::os::raw::c_int, ), >, pub LICE_BorderedRect: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, bgcolor: root::reaper_functions::LICE_pixel, fgcolor: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_Circle: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, cx: f32, cy: f32, r: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ), >, pub LICE_Clear: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, color: root::reaper_functions::LICE_pixel, ), >, pub LICE_ClearRect: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, mask: root::reaper_functions::LICE_pixel, orbits: root::reaper_functions::LICE_pixel, ), >, pub LICE_ClipLine: Option< unsafe extern "C" fn( pX1Out: *mut ::std::os::raw::c_int, pY1Out: *mut ::std::os::raw::c_int, pX2Out: *mut ::std::os::raw::c_int, pY2Out: *mut ::std::os::raw::c_int, xLo: ::std::os::raw::c_int, yLo: ::std::os::raw::c_int, xHi: ::std::os::raw::c_int, yHi: ::std::os::raw::c_int, ) -> bool, >, pub LICE_Copy: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, ), >, pub LICE_CreateBitmap: Option< extern "C" fn( mode: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, ) -> *mut root::reaper_functions::LICE_IBitmap, >, pub LICE_CreateFont: Option<extern "C" fn() -> *mut root::reaper_functions::LICE_IFont>, pub LICE_DrawCBezier: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, xstart: f64, ystart: f64, xctl1: f64, yctl1: f64, xctl2: f64, yctl2: f64, xend: f64, yend: f64, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, tol: f64, ), >, pub LICE_DrawChar: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, c: ::std::os::raw::c_char, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_DrawGlyph: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alphas: *mut root::reaper_functions::LICE_pixel_chan, glyph_w: ::std::os::raw::c_int, glyph_h: ::std::os::raw::c_int, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_DrawRect: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_DrawText: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, string: *const ::std::os::raw::c_char, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_FillCBezier: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, xstart: f64, ystart: f64, xctl1: f64, yctl1: f64, xctl2: f64, yctl2: f64, xend: f64, yend: f64, yfill: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, tol: f64, ), >, pub LICE_FillCircle: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, cx: f32, cy: f32, r: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ), >, pub LICE_FillConvexPolygon: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: *mut ::std::os::raw::c_int, y: *mut ::std::os::raw::c_int, npoints: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_FillRect: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_FillTrapezoid: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x1a: ::std::os::raw::c_int, x1b: ::std::os::raw::c_int, y1: ::std::os::raw::c_int, x2a: ::std::os::raw::c_int, x2b: ::std::os::raw::c_int, y2: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_FillTriangle: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x1: ::std::os::raw::c_int, y1: ::std::os::raw::c_int, x2: ::std::os::raw::c_int, y2: ::std::os::raw::c_int, x3: ::std::os::raw::c_int, y3: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_GetPixel: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, ) -> root::reaper_functions::LICE_pixel, >, pub LICE_GradRect: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, dstw: ::std::os::raw::c_int, dsth: ::std::os::raw::c_int, ir: f32, ig: f32, ib: f32, ia: f32, drdx: f32, dgdx: f32, dbdx: f32, dadx: f32, drdy: f32, dgdy: f32, dbdy: f32, dady: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_Line: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x1: f32, y1: f32, x2: f32, y2: f32, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ), >, pub LICE_LineInt: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x1: ::std::os::raw::c_int, y1: ::std::os::raw::c_int, x2: ::std::os::raw::c_int, y2: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ), >, pub LICE_LoadPNG: Option< unsafe extern "C" fn( filename: *const ::std::os::raw::c_char, bmp: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut root::reaper_functions::LICE_IBitmap, >, pub LICE_LoadPNGFromResource: Option< unsafe extern "C" fn( hInst: root::HINSTANCE, resid: *const ::std::os::raw::c_char, bmp: *mut root::reaper_functions::LICE_IBitmap, ) -> *mut root::reaper_functions::LICE_IBitmap, >, pub LICE_MeasureText: Option< unsafe extern "C" fn( string: *const ::std::os::raw::c_char, w: *mut ::std::os::raw::c_int, h: *mut ::std::os::raw::c_int, ), >, pub LICE_MultiplyAddRect: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, w: ::std::os::raw::c_int, h: ::std::os::raw::c_int, rsc: f32, gsc: f32, bsc: f32, asc: f32, radd: f32, gadd: f32, badd: f32, aadd: f32, ), >, pub LICE_PutPixel: Option< unsafe extern "C" fn( bm: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, color: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_RotatedBlit: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, dstw: ::std::os::raw::c_int, dsth: ::std::os::raw::c_int, srcx: f32, srcy: f32, srcw: f32, srch: f32, angle: f32, cliptosourcerect: bool, alpha: f32, mode: ::std::os::raw::c_int, rotxcent: f32, rotycent: f32, ), >, pub LICE_RoundRect: Option< unsafe extern "C" fn( drawbm: *mut root::reaper_functions::LICE_IBitmap, xpos: f32, ypos: f32, w: f32, h: f32, cornerradius: ::std::os::raw::c_int, col: root::reaper_functions::LICE_pixel, alpha: f32, mode: ::std::os::raw::c_int, aa: bool, ), >, pub LICE_ScaledBlit: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::LICE_IBitmap, dstx: ::std::os::raw::c_int, dsty: ::std::os::raw::c_int, dstw: ::std::os::raw::c_int, dsth: ::std::os::raw::c_int, srcx: f32, srcy: f32, srcw: f32, srch: f32, alpha: f32, mode: ::std::os::raw::c_int, ), >, pub LICE_SimpleFill: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, newcolor: root::reaper_functions::LICE_pixel, comparemask: root::reaper_functions::LICE_pixel, keepmask: root::reaper_functions::LICE_pixel, ), >, pub LocalizeString: Option< unsafe extern "C" fn( src_string: *const ::std::os::raw::c_char, section: *const ::std::os::raw::c_char, flagsOptional: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub Loop_OnArrow: Option< unsafe extern "C" fn( project: *mut root::ReaProject, direction: ::std::os::raw::c_int, ) -> bool, >, pub Main_OnCommand: Option<extern "C" fn(command: ::std::os::raw::c_int, flag: ::std::os::raw::c_int)>, pub Main_OnCommandEx: Option< unsafe extern "C" fn( command: ::std::os::raw::c_int, flag: ::std::os::raw::c_int, proj: *mut root::ReaProject, ), >, pub Main_openProject: Option<unsafe extern "C" fn(name: *const ::std::os::raw::c_char)>, pub Main_SaveProject: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, forceSaveAsInOptional: bool)>, pub Main_UpdateLoopInfo: Option<extern "C" fn(ignoremask: ::std::os::raw::c_int)>, pub MarkProjectDirty: Option<unsafe extern "C" fn(proj: *mut root::ReaProject)>, pub MarkTrackItemsDirty: Option<unsafe extern "C" fn(track: *mut root::MediaTrack, item: *mut root::MediaItem)>, pub Master_GetPlayRate: Option<unsafe extern "C" fn(project: *mut root::ReaProject) -> f64>, pub Master_GetPlayRateAtTime: Option<unsafe extern "C" fn(time_s: f64, proj: *mut root::ReaProject) -> f64>, pub Master_GetTempo: Option<extern "C" fn() -> f64>, pub Master_NormalizePlayRate: Option<extern "C" fn(playrate: f64, isnormalized: bool) -> f64>, pub Master_NormalizeTempo: Option<extern "C" fn(bpm: f64, isnormalized: bool) -> f64>, pub MB: Option< unsafe extern "C" fn( msg: *const ::std::os::raw::c_char, title: *const ::std::os::raw::c_char, type_: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub MediaItemDescendsFromTrack: Option< unsafe extern "C" fn( item: *mut root::MediaItem, track: *mut root::MediaTrack, ) -> ::std::os::raw::c_int, >, pub MIDI_CountEvts: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, notecntOut: *mut ::std::os::raw::c_int, ccevtcntOut: *mut ::std::os::raw::c_int, textsyxevtcntOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub MIDI_DeleteCC: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int) -> bool, >, pub MIDI_DeleteEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_DeleteNote: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_DeleteTextSysexEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, textsyxevtidx: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_DisableSort: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take)>, pub MIDI_EnumSelCC: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub MIDI_EnumSelEvts: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub MIDI_EnumSelNotes: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub MIDI_EnumSelTextSysexEvts: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, textsyxidx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub MIDI_eventlist_Create: Option<extern "C" fn() -> *mut root::MIDI_eventlist>, pub MIDI_eventlist_Destroy: Option<unsafe extern "C" fn(evtlist: *mut root::MIDI_eventlist)>, pub MIDI_GetAllEvts: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, bufOutNeedBig: *mut ::std::os::raw::c_char, bufOutNeedBig_sz: *mut ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetCC: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, selectedOut: *mut bool, mutedOut: *mut bool, ppqposOut: *mut f64, chanmsgOut: *mut ::std::os::raw::c_int, chanOut: *mut ::std::os::raw::c_int, msg2Out: *mut ::std::os::raw::c_int, msg3Out: *mut ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetCCShape: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, shapeOut: *mut ::std::os::raw::c_int, beztensionOut: *mut f64, ) -> bool, >, pub MIDI_GetEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, selectedOut: *mut bool, mutedOut: *mut bool, ppqposOut: *mut f64, msgOut: *mut ::std::os::raw::c_char, msgOut_sz: *mut ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetGrid: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, swingOutOptional: *mut f64, noteLenOutOptional: *mut f64, ) -> f64, >, pub MIDI_GetHash: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, notesonly: bool, hashOut: *mut ::std::os::raw::c_char, hashOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetNote: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, selectedOut: *mut bool, mutedOut: *mut bool, startppqposOut: *mut f64, endppqposOut: *mut f64, chanOut: *mut ::std::os::raw::c_int, pitchOut: *mut ::std::os::raw::c_int, velOut: *mut ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetPPQPos_EndOfMeasure: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, ppqpos: f64) -> f64>, pub MIDI_GetPPQPos_StartOfMeasure: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, ppqpos: f64) -> f64>, pub MIDI_GetPPQPosFromProjQN: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, projqn: f64) -> f64>, pub MIDI_GetPPQPosFromProjTime: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, projtime: f64) -> f64>, pub MIDI_GetProjQNFromPPQPos: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, ppqpos: f64) -> f64>, pub MIDI_GetProjTimeFromPPQPos: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, ppqpos: f64) -> f64>, pub MIDI_GetScale: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, rootOut: *mut ::std::os::raw::c_int, scaleOut: *mut ::std::os::raw::c_int, nameOut: *mut ::std::os::raw::c_char, nameOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetTextSysexEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, textsyxevtidx: ::std::os::raw::c_int, selectedOutOptional: *mut bool, mutedOutOptional: *mut bool, ppqposOutOptional: *mut f64, typeOutOptional: *mut ::std::os::raw::c_int, msgOptional: *mut ::std::os::raw::c_char, msgOptional_sz: *mut ::std::os::raw::c_int, ) -> bool, >, pub MIDI_GetTrackHash: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, notesonly: bool, hashOut: *mut ::std::os::raw::c_char, hashOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_InsertCC: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, selected: bool, muted: bool, ppqpos: f64, chanmsg: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, msg2: ::std::os::raw::c_int, msg3: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_InsertEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, selected: bool, muted: bool, ppqpos: f64, bytestr: *const ::std::os::raw::c_char, bytestr_sz: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_InsertNote: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, selected: bool, muted: bool, startppqpos: f64, endppqpos: f64, chan: ::std::os::raw::c_int, pitch: ::std::os::raw::c_int, vel: ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool, >, pub MIDI_InsertTextSysexEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, selected: bool, muted: bool, ppqpos: f64, type_: ::std::os::raw::c_int, bytestr: *const ::std::os::raw::c_char, bytestr_sz: ::std::os::raw::c_int, ) -> bool, >, pub midi_reinit: Option<extern "C" fn()>, pub MIDI_SelectAll: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take, select: bool)>, pub MIDI_SetAllEvts: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, buf: *const ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool, >, pub MIDI_SetCC: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, ppqposInOptional: *const f64, chanmsgInOptional: *const ::std::os::raw::c_int, chanInOptional: *const ::std::os::raw::c_int, msg2InOptional: *const ::std::os::raw::c_int, msg3InOptional: *const ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool, >, pub MIDI_SetCCShape: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, ccidx: ::std::os::raw::c_int, shape: ::std::os::raw::c_int, beztension: f64, noSortInOptional: *const bool, ) -> bool, >, pub MIDI_SetEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, evtidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, ppqposInOptional: *const f64, msgOptional: *const ::std::os::raw::c_char, msgOptional_sz: ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool, >, pub MIDI_SetItemExtents: Option<unsafe extern "C" fn(item: *mut root::MediaItem, startQN: f64, endQN: f64) -> bool>, pub MIDI_SetNote: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, noteidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, startppqposInOptional: *const f64, endppqposInOptional: *const f64, chanInOptional: *const ::std::os::raw::c_int, pitchInOptional: *const ::std::os::raw::c_int, velInOptional: *const ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool, >, pub MIDI_SetTextSysexEvt: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, textsyxevtidx: ::std::os::raw::c_int, selectedInOptional: *const bool, mutedInOptional: *const bool, ppqposInOptional: *const f64, typeInOptional: *const ::std::os::raw::c_int, msgOptional: *const ::std::os::raw::c_char, msgOptional_sz: ::std::os::raw::c_int, noSortInOptional: *const bool, ) -> bool, >, pub MIDI_Sort: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take)>, pub MIDIEditor_EnumTakes: Option< unsafe extern "C" fn( midieditor: root::HWND, takeindex: ::std::os::raw::c_int, editable_only: bool, ) -> *mut root::MediaItem_Take, >, pub MIDIEditor_GetActive: Option<extern "C" fn() -> root::HWND>, pub MIDIEditor_GetMode: Option<unsafe extern "C" fn(midieditor: root::HWND) -> ::std::os::raw::c_int>, pub MIDIEditor_GetSetting_int: Option< unsafe extern "C" fn( midieditor: root::HWND, setting_desc: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int, >, pub MIDIEditor_GetSetting_str: Option< unsafe extern "C" fn( midieditor: root::HWND, setting_desc: *const ::std::os::raw::c_char, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool, >, pub MIDIEditor_GetTake: Option<unsafe extern "C" fn(midieditor: root::HWND) -> *mut root::MediaItem_Take>, pub MIDIEditor_LastFocused_OnCommand: Option<extern "C" fn(command_id: ::std::os::raw::c_int, islistviewcommand: bool) -> bool>, pub MIDIEditor_OnCommand: Option< unsafe extern "C" fn(midieditor: root::HWND, command_id: ::std::os::raw::c_int) -> bool, >, pub MIDIEditor_SetSetting_int: Option< unsafe extern "C" fn( midieditor: root::HWND, setting_desc: *const ::std::os::raw::c_char, setting: ::std::os::raw::c_int, ) -> bool, >, pub mkpanstr: Option<unsafe extern "C" fn(strNeed64: *mut ::std::os::raw::c_char, pan: f64)>, pub mkvolpanstr: Option<unsafe extern "C" fn(strNeed64: *mut ::std::os::raw::c_char, vol: f64, pan: f64)>, pub mkvolstr: Option<unsafe extern "C" fn(strNeed64: *mut ::std::os::raw::c_char, vol: f64)>, pub MoveEditCursor: Option<extern "C" fn(adjamt: f64, dosel: bool)>, pub MoveMediaItemToTrack: Option< unsafe extern "C" fn(item: *mut root::MediaItem, desttr: *mut root::MediaTrack) -> bool, >, pub MuteAllTracks: Option<extern "C" fn(mute: bool)>, pub my_getViewport: Option<unsafe extern "C" fn(r: *mut root::RECT, sr: *const root::RECT, wantWorkArea: bool)>, pub NamedCommandLookup: Option< unsafe extern "C" fn(command_name: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int, >, pub OnPauseButton: Option<extern "C" fn()>, pub OnPauseButtonEx: Option<unsafe extern "C" fn(proj: *mut root::ReaProject)>, pub OnPlayButton: Option<extern "C" fn()>, pub OnPlayButtonEx: Option<unsafe extern "C" fn(proj: *mut root::ReaProject)>, pub OnStopButton: Option<extern "C" fn()>, pub OnStopButtonEx: Option<unsafe extern "C" fn(proj: *mut root::ReaProject)>, pub OpenColorThemeFile: Option<unsafe extern "C" fn(fn_: *const ::std::os::raw::c_char) -> bool>, pub OpenMediaExplorer: Option< unsafe extern "C" fn(mediafn: *const ::std::os::raw::c_char, play: bool) -> root::HWND, >, pub OscLocalMessageToHost: Option< unsafe extern "C" fn(message: *const ::std::os::raw::c_char, valueInOptional: *const f64), >, pub parse_timestr: Option<unsafe extern "C" fn(buf: *const ::std::os::raw::c_char) -> f64>, pub parse_timestr_len: Option< unsafe extern "C" fn( buf: *const ::std::os::raw::c_char, offset: f64, modeoverride: ::std::os::raw::c_int, ) -> f64, >, pub parse_timestr_pos: Option< unsafe extern "C" fn( buf: *const ::std::os::raw::c_char, modeoverride: ::std::os::raw::c_int, ) -> f64, >, pub parsepanstr: Option<unsafe extern "C" fn(str: *const ::std::os::raw::c_char) -> f64>, pub PCM_Sink_Create: Option< unsafe extern "C" fn( filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, srate: ::std::os::raw::c_int, buildpeaks: bool, ) -> *mut root::PCM_sink, >, pub PCM_Sink_CreateEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, srate: ::std::os::raw::c_int, buildpeaks: bool, ) -> *mut root::PCM_sink, >, pub PCM_Sink_CreateMIDIFile: Option< unsafe extern "C" fn( filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, bpm: f64, div: ::std::os::raw::c_int, ) -> *mut root::PCM_sink, >, pub PCM_Sink_CreateMIDIFileEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, filename: *const ::std::os::raw::c_char, cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, bpm: f64, div: ::std::os::raw::c_int, ) -> *mut root::PCM_sink, >, pub PCM_Sink_Enum: Option< unsafe extern "C" fn( idx: ::std::os::raw::c_int, descstrOut: *mut *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_uint, >, pub PCM_Sink_GetExtension: Option< unsafe extern "C" fn( data: *const ::std::os::raw::c_char, data_sz: ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub PCM_Sink_ShowConfig: Option< unsafe extern "C" fn( cfg: *const ::std::os::raw::c_char, cfg_sz: ::std::os::raw::c_int, hwndParent: root::HWND, ) -> root::HWND, >, pub PCM_Source_BuildPeaks: Option< unsafe extern "C" fn( src: *mut root::PCM_source, mode: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub PCM_Source_CreateFromFile: Option< unsafe extern "C" fn(filename: *const ::std::os::raw::c_char) -> *mut root::PCM_source, >, pub PCM_Source_CreateFromFileEx: Option< unsafe extern "C" fn( filename: *const ::std::os::raw::c_char, forcenoMidiImp: bool, ) -> *mut root::PCM_source, >, pub PCM_Source_CreateFromSimple: Option< unsafe extern "C" fn( dec: *mut root::ISimpleMediaDecoder, fn_: *const ::std::os::raw::c_char, ) -> *mut root::PCM_source, >, pub PCM_Source_CreateFromType: Option< unsafe extern "C" fn(sourcetype: *const ::std::os::raw::c_char) -> *mut root::PCM_source, >, pub PCM_Source_Destroy: Option<unsafe extern "C" fn(src: *mut root::PCM_source)>, pub PCM_Source_GetPeaks: Option< unsafe extern "C" fn( src: *mut root::PCM_source, peakrate: f64, starttime: f64, numchannels: ::std::os::raw::c_int, numsamplesperchannel: ::std::os::raw::c_int, want_extra_type: ::std::os::raw::c_int, buf: *mut f64, ) -> ::std::os::raw::c_int, >, pub PCM_Source_GetSectionInfo: Option< unsafe extern "C" fn( src: *mut root::PCM_source, offsOut: *mut f64, lenOut: *mut f64, revOut: *mut bool, ) -> bool, >, pub PeakBuild_Create: Option< unsafe extern "C" fn( src: *mut root::PCM_source, fn_: *const ::std::os::raw::c_char, srate: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, ) -> *mut root::REAPER_PeakBuild_Interface, >, pub PeakBuild_CreateEx: Option< unsafe extern "C" fn( src: *mut root::PCM_source, fn_: *const ::std::os::raw::c_char, srate: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, ) -> *mut root::REAPER_PeakBuild_Interface, >, pub PeakGet_Create: Option< unsafe extern "C" fn( fn_: *const ::std::os::raw::c_char, srate: ::std::os::raw::c_int, nch: ::std::os::raw::c_int, ) -> *mut root::REAPER_PeakGet_Interface, >, pub PitchShiftSubModeMenu: Option< unsafe extern "C" fn( hwnd: root::HWND, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, mode: ::std::os::raw::c_int, submode_sel: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub PlayPreview: Option< unsafe extern "C" fn(preview: *mut root::preview_register_t) -> ::std::os::raw::c_int, >, pub PlayPreviewEx: Option< unsafe extern "C" fn( preview: *mut root::preview_register_t, bufflags: ::std::os::raw::c_int, measure_align: f64, ) -> ::std::os::raw::c_int, >, pub PlayTrackPreview: Option< unsafe extern "C" fn(preview: *mut root::preview_register_t) -> ::std::os::raw::c_int, >, pub PlayTrackPreview2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int, >, pub PlayTrackPreview2Ex: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, preview: *mut root::preview_register_t, flags: ::std::os::raw::c_int, measure_align: f64, ) -> ::std::os::raw::c_int, >, pub plugin_getapi: Option< unsafe extern "C" fn(name: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_void, >, pub plugin_getFilterList: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub plugin_getImportableProjectFilterList: Option<extern "C" fn() -> *const ::std::os::raw::c_char>, pub plugin_register: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, infostruct: *mut ::std::os::raw::c_void, ) -> ::std::os::raw::c_int, >, pub PluginWantsAlwaysRunFx: Option<extern "C" fn(amt: ::std::os::raw::c_int)>, pub PreventUIRefresh: Option<extern "C" fn(prevent_count: ::std::os::raw::c_int)>, pub projectconfig_var_addr: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, idx: ::std::os::raw::c_int, ) -> *mut ::std::os::raw::c_void, >, pub projectconfig_var_getoffs: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, szOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub PromptForAction: Option< extern "C" fn( session_mode: ::std::os::raw::c_int, init_id: ::std::os::raw::c_int, section_id: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub realloc_cmd_ptr: Option< unsafe extern "C" fn( ptr: *mut *mut ::std::os::raw::c_char, ptr_size: *mut ::std::os::raw::c_int, new_size: ::std::os::raw::c_int, ) -> bool, >, pub ReaperGetPitchShiftAPI: Option<extern "C" fn(version: ::std::os::raw::c_int) -> *mut root::IReaperPitchShift>, pub ReaScriptError: Option<unsafe extern "C" fn(errmsg: *const ::std::os::raw::c_char)>, pub RecursiveCreateDirectory: Option< unsafe extern "C" fn( path: *const ::std::os::raw::c_char, ignored: usize, ) -> ::std::os::raw::c_int, >, pub reduce_open_files: Option<extern "C" fn(flags: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub RefreshToolbar: Option<extern "C" fn(command_id: ::std::os::raw::c_int)>, pub RefreshToolbar2: Option<extern "C" fn(section_id: ::std::os::raw::c_int, command_id: ::std::os::raw::c_int)>, pub relative_fn: Option< unsafe extern "C" fn( in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, ), >, pub RemoveTrackSend: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, ) -> bool, >, pub RenderFileSection: Option< unsafe extern "C" fn( source_filename: *const ::std::os::raw::c_char, target_filename: *const ::std::os::raw::c_char, start_percent: f64, end_percent: f64, playrate: f64, ) -> bool, >, pub ReorderSelectedTracks: Option< extern "C" fn( beforeTrackIdx: ::std::os::raw::c_int, makePrevFolder: ::std::os::raw::c_int, ) -> bool, >, pub Resample_EnumModes: Option<extern "C" fn(mode: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char>, pub Resampler_Create: Option<extern "C" fn() -> *mut root::REAPER_Resample_Interface>, pub resolve_fn: Option< unsafe extern "C" fn( in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, ), >, pub resolve_fn2: Option< unsafe extern "C" fn( in_: *const ::std::os::raw::c_char, out: *mut ::std::os::raw::c_char, out_sz: ::std::os::raw::c_int, checkSubDirOptional: *const ::std::os::raw::c_char, ), >, pub ResolveRenderPattern: Option< unsafe extern "C" fn( project: *mut root::ReaProject, path: *const ::std::os::raw::c_char, pattern: *const ::std::os::raw::c_char, targets: *mut ::std::os::raw::c_char, targets_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub ReverseNamedCommandLookup: Option<extern "C" fn(command_id: ::std::os::raw::c_int) -> *const ::std::os::raw::c_char>, pub ScaleFromEnvelopeMode: Option<extern "C" fn(scaling_mode: ::std::os::raw::c_int, val: f64) -> f64>, pub ScaleToEnvelopeMode: Option<extern "C" fn(scaling_mode: ::std::os::raw::c_int, val: f64) -> f64>, pub screenset_register: Option< unsafe extern "C" fn( id: *mut ::std::os::raw::c_char, callbackFunc: *mut ::std::os::raw::c_void, param: *mut ::std::os::raw::c_void, ), >, pub screenset_registerNew: Option< unsafe extern "C" fn( id: *mut ::std::os::raw::c_char, callbackFunc: root::screensetNewCallbackFunc, param: *mut ::std::os::raw::c_void, ), >, pub screenset_unregister: Option<unsafe extern "C" fn(id: *mut ::std::os::raw::c_char)>, pub screenset_unregisterByParam: Option<unsafe extern "C" fn(param: *mut ::std::os::raw::c_void)>, pub screenset_updateLastFocus: Option<unsafe extern "C" fn(prevWin: root::HWND)>, pub SectionFromUniqueID: Option<extern "C" fn(uniqueID: ::std::os::raw::c_int) -> *mut root::KbdSectionInfo>, pub SelectAllMediaItems: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, selected: bool)>, pub SelectProjectInstance: Option<unsafe extern "C" fn(proj: *mut root::ReaProject)>, pub SendLocalOscMessage: Option< unsafe extern "C" fn( local_osc_handler: *mut ::std::os::raw::c_void, msg: *const ::std::os::raw::c_char, msglen: ::std::os::raw::c_int, ), >, pub SetActiveTake: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take)>, pub SetAutomationMode: Option<extern "C" fn(mode: ::std::os::raw::c_int, onlySel: bool)>, pub SetCurrentBPM: Option<unsafe extern "C" fn(__proj: *mut root::ReaProject, bpm: f64, wantUndo: bool)>, pub SetCursorContext: Option< unsafe extern "C" fn(mode: ::std::os::raw::c_int, envInOptional: *mut root::TrackEnvelope), >, pub SetEditCurPos: Option<extern "C" fn(time: f64, moveview: bool, seekplay: bool)>, pub SetEditCurPos2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, time: f64, moveview: bool, seekplay: bool, ), >, pub SetEnvelopePoint: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, ptidx: ::std::os::raw::c_int, timeInOptional: *mut f64, valueInOptional: *mut f64, shapeInOptional: *mut ::std::os::raw::c_int, tensionInOptional: *mut f64, selectedInOptional: *mut bool, noSortInOptional: *mut bool, ) -> bool, >, pub SetEnvelopePointEx: Option< unsafe extern "C" fn( envelope: *mut root::TrackEnvelope, autoitem_idx: ::std::os::raw::c_int, ptidx: ::std::os::raw::c_int, timeInOptional: *mut f64, valueInOptional: *mut f64, shapeInOptional: *mut ::std::os::raw::c_int, tensionInOptional: *mut f64, selectedInOptional: *mut bool, noSortInOptional: *mut bool, ) -> bool, >, pub SetEnvelopeStateChunk: Option< unsafe extern "C" fn( env: *mut root::TrackEnvelope, str: *const ::std::os::raw::c_char, isundoOptional: bool, ) -> bool, >, pub SetExtState: Option< unsafe extern "C" fn( section: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, persist: bool, ), >, pub SetGlobalAutomationOverride: Option<extern "C" fn(mode: ::std::os::raw::c_int)>, pub SetItemStateChunk: Option< unsafe extern "C" fn( item: *mut root::MediaItem, str: *const ::std::os::raw::c_char, isundoOptional: bool, ) -> bool, >, pub SetMasterTrackVisibility: Option<extern "C" fn(flag: ::std::os::raw::c_int) -> ::std::os::raw::c_int>, pub SetMediaItemInfo_Value: Option< unsafe extern "C" fn( item: *mut root::MediaItem, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool, >, pub SetMediaItemLength: Option< unsafe extern "C" fn(item: *mut root::MediaItem, length: f64, refreshUI: bool) -> bool, >, pub SetMediaItemPosition: Option< unsafe extern "C" fn(item: *mut root::MediaItem, position: f64, refreshUI: bool) -> bool, >, pub SetMediaItemSelected: Option<unsafe extern "C" fn(item: *mut root::MediaItem, selected: bool)>, pub SetMediaItemTake_Source: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, source: *mut root::PCM_source, ) -> bool, >, pub SetMediaItemTakeInfo_Value: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool, >, pub SetMediaTrackInfo_Value: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool, >, pub SetMIDIEditorGrid: Option<unsafe extern "C" fn(project: *mut root::ReaProject, division: f64)>, pub SetMixerScroll: Option<unsafe extern "C" fn(leftmosttrack: *mut root::MediaTrack) -> *mut root::MediaTrack>, pub SetMouseModifier: Option< unsafe extern "C" fn( context: *const ::std::os::raw::c_char, modifier_flag: ::std::os::raw::c_int, action: *const ::std::os::raw::c_char, ), >, pub SetOnlyTrackSelected: Option<unsafe extern "C" fn(track: *mut root::MediaTrack)>, pub SetProjectGrid: Option<unsafe extern "C" fn(project: *mut root::ReaProject, division: f64)>, pub SetProjectMarker: Option< unsafe extern "C" fn( markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, ) -> bool, >, pub SetProjectMarker2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, ) -> bool, >, pub SetProjectMarker3: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, ) -> bool, >, pub SetProjectMarker4: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnindexnumber: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, ) -> bool, >, pub SetProjectMarkerByIndex: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnidx: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, IDnumber: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, ) -> bool, >, pub SetProjectMarkerByIndex2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, markrgnidx: ::std::os::raw::c_int, isrgn: bool, pos: f64, rgnend: f64, IDnumber: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, flags: ::std::os::raw::c_int, ) -> bool, >, pub SetProjExtState: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, extname: *const ::std::os::raw::c_char, key: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int, >, pub SetRegionRenderMatrix: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, regionindex: ::std::os::raw::c_int, track: *mut root::MediaTrack, addorremove: ::std::os::raw::c_int, ), >, pub SetRenderLastError: Option<unsafe extern "C" fn(errorstr: *const ::std::os::raw::c_char)>, pub SetTakeMarker: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, nameIn: *const ::std::os::raw::c_char, srcposInOptional: *mut f64, colorInOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub SetTakeStretchMarker: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, pos: f64, srcposInOptional: *const f64, ) -> ::std::os::raw::c_int, >, pub SetTakeStretchMarkerSlope: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, idx: ::std::os::raw::c_int, slope: f64, ) -> bool, >, pub SetTempoTimeSigMarker: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, ptidx: ::std::os::raw::c_int, timepos: f64, measurepos: ::std::os::raw::c_int, beatpos: f64, bpm: f64, timesig_num: ::std::os::raw::c_int, timesig_denom: ::std::os::raw::c_int, lineartempo: bool, ) -> bool, >, pub SetThemeColor: Option< unsafe extern "C" fn( ini_key: *const ::std::os::raw::c_char, color: ::std::os::raw::c_int, flagsOptional: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub SetToggleCommandState: Option< extern "C" fn( section_id: ::std::os::raw::c_int, command_id: ::std::os::raw::c_int, state: ::std::os::raw::c_int, ) -> bool, >, pub SetTrackAutomationMode: Option<unsafe extern "C" fn(tr: *mut root::MediaTrack, mode: ::std::os::raw::c_int)>, pub SetTrackColor: Option<unsafe extern "C" fn(track: *mut root::MediaTrack, color: ::std::os::raw::c_int)>, pub SetTrackMIDILyrics: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, flag: ::std::os::raw::c_int, str: *const ::std::os::raw::c_char, ) -> bool, >, pub SetTrackMIDINoteName: Option< unsafe extern "C" fn( track: ::std::os::raw::c_int, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, ) -> bool, >, pub SetTrackMIDINoteNameEx: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, track: *mut root::MediaTrack, pitch: ::std::os::raw::c_int, chan: ::std::os::raw::c_int, name: *const ::std::os::raw::c_char, ) -> bool, >, pub SetTrackSelected: Option<unsafe extern "C" fn(track: *mut root::MediaTrack, selected: bool)>, pub SetTrackSendInfo_Value: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, category: ::std::os::raw::c_int, sendidx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, newvalue: f64, ) -> bool, >, pub SetTrackSendUIPan: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, send_idx: ::std::os::raw::c_int, pan: f64, isend: ::std::os::raw::c_int, ) -> bool, >, pub SetTrackSendUIVol: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, send_idx: ::std::os::raw::c_int, vol: f64, isend: ::std::os::raw::c_int, ) -> bool, >, pub SetTrackStateChunk: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, str: *const ::std::os::raw::c_char, isundoOptional: bool, ) -> bool, >, pub ShowActionList: Option<unsafe extern "C" fn(caller: *mut root::KbdSectionInfo, callerWnd: root::HWND)>, pub ShowConsoleMsg: Option<unsafe extern "C" fn(msg: *const ::std::os::raw::c_char)>, pub ShowMessageBox: Option< unsafe extern "C" fn( msg: *const ::std::os::raw::c_char, title: *const ::std::os::raw::c_char, type_: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub ShowPopupMenu: Option< unsafe extern "C" fn( name: *const ::std::os::raw::c_char, x: ::std::os::raw::c_int, y: ::std::os::raw::c_int, hwndParentOptional: root::HWND, ctxOptional: *mut ::std::os::raw::c_void, ctx2Optional: ::std::os::raw::c_int, ctx3Optional: ::std::os::raw::c_int, ), >, pub SLIDER2DB: Option<extern "C" fn(y: f64) -> f64>, pub SnapToGrid: Option<unsafe extern "C" fn(project: *mut root::ReaProject, time_pos: f64) -> f64>, pub SoloAllTracks: Option<extern "C" fn(solo: ::std::os::raw::c_int)>, pub Splash_GetWnd: Option<extern "C" fn() -> root::HWND>, pub SplitMediaItem: Option< unsafe extern "C" fn(item: *mut root::MediaItem, position: f64) -> *mut root::MediaItem, >, pub StopPreview: Option< unsafe extern "C" fn(preview: *mut root::preview_register_t) -> ::std::os::raw::c_int, >, pub StopTrackPreview: Option< unsafe extern "C" fn(preview: *mut root::preview_register_t) -> ::std::os::raw::c_int, >, pub StopTrackPreview2: Option< unsafe extern "C" fn( proj: *mut ::std::os::raw::c_void, preview: *mut root::preview_register_t, ) -> ::std::os::raw::c_int, >, pub stringToGuid: Option<unsafe extern "C" fn(str: *const ::std::os::raw::c_char, g: *mut root::GUID)>, pub StuffMIDIMessage: Option< extern "C" fn( mode: ::std::os::raw::c_int, msg1: ::std::os::raw::c_int, msg2: ::std::os::raw::c_int, msg3: ::std::os::raw::c_int, ), >, pub TakeFX_AddByName: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fxname: *const ::std::os::raw::c_char, instantiate: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TakeFX_CopyToTake: Option< unsafe extern "C" fn( src_take: *mut root::MediaItem_Take, src_fx: ::std::os::raw::c_int, dest_take: *mut root::MediaItem_Take, dest_fx: ::std::os::raw::c_int, is_move: bool, ), >, pub TakeFX_CopyToTrack: Option< unsafe extern "C" fn( src_take: *mut root::MediaItem_Take, src_fx: ::std::os::raw::c_int, dest_track: *mut root::MediaTrack, dest_fx: ::std::os::raw::c_int, is_move: bool, ), >, pub TakeFX_Delete: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int) -> bool, >, pub TakeFX_EndParamEdit: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_FormatParamValue: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_FormatParamValueNormalized: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetChainVisible: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> ::std::os::raw::c_int>, pub TakeFX_GetCount: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> ::std::os::raw::c_int>, pub TakeFX_GetEnabled: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int) -> bool, >, pub TakeFX_GetEnvelope: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fxindex: ::std::os::raw::c_int, parameterindex: ::std::os::raw::c_int, create: bool, ) -> *mut root::TrackEnvelope, >, pub TakeFX_GetFloatingWindow: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, index: ::std::os::raw::c_int, ) -> root::HWND, >, pub TakeFX_GetFormattedParamValue: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetFXGUID: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> *mut root::GUID, >, pub TakeFX_GetFXName: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetIOSize: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, inputPinsOutOptional: *mut ::std::os::raw::c_int, outputPinsOutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TakeFX_GetNamedConfigParm: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetNumParams: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TakeFX_GetOffline: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int) -> bool, >, pub TakeFX_GetOpen: Option< unsafe extern "C" fn(take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int) -> bool, >, pub TakeFX_GetParam: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, ) -> f64, >, pub TakeFX_GetParameterStepSizes: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, stepOut: *mut f64, smallstepOut: *mut f64, largestepOut: *mut f64, istoggleOut: *mut bool, ) -> bool, >, pub TakeFX_GetParamEx: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, midvalOut: *mut f64, ) -> f64, >, pub TakeFX_GetParamFromIdent: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, ident_str: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int, >, pub TakeFX_GetParamIdent: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetParamName: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetParamNormalized: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> f64, >, pub TakeFX_GetPinMappings: Option< unsafe extern "C" fn( tr: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, high32OutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TakeFX_GetPreset: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, presetnameOut: *mut ::std::os::raw::c_char, presetnameOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_GetPresetIndex: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, numberOfPresetsOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TakeFX_GetUserPresetFilename: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, fnOut: *mut ::std::os::raw::c_char, fnOut_sz: ::std::os::raw::c_int, ), >, pub TakeFX_NavigatePresets: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, presetmove: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_SetEnabled: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, enabled: bool, ), >, pub TakeFX_SetNamedConfigParm: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, ) -> bool, >, pub TakeFX_SetOffline: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, offline: bool, ), >, pub TakeFX_SetOpen: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, open: bool, ), >, pub TakeFX_SetParam: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, ) -> bool, >, pub TakeFX_SetParamNormalized: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, ) -> bool, >, pub TakeFX_SetPinMappings: Option< unsafe extern "C" fn( tr: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, low32bits: ::std::os::raw::c_int, hi32bits: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_SetPreset: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, presetname: *const ::std::os::raw::c_char, ) -> bool, >, pub TakeFX_SetPresetByIndex: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, fx: ::std::os::raw::c_int, idx: ::std::os::raw::c_int, ) -> bool, >, pub TakeFX_Show: Option< unsafe extern "C" fn( take: *mut root::MediaItem_Take, index: ::std::os::raw::c_int, showFlag: ::std::os::raw::c_int, ), >, pub TakeIsMIDI: Option<unsafe extern "C" fn(take: *mut root::MediaItem_Take) -> bool>, pub ThemeLayout_GetLayout: Option< unsafe extern "C" fn( section: *const ::std::os::raw::c_char, idx: ::std::os::raw::c_int, nameOut: *mut ::std::os::raw::c_char, nameOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub ThemeLayout_GetParameter: Option< unsafe extern "C" fn( wp: ::std::os::raw::c_int, descOutOptional: *mut *const ::std::os::raw::c_char, valueOutOptional: *mut ::std::os::raw::c_int, defValueOutOptional: *mut ::std::os::raw::c_int, minValueOutOptional: *mut ::std::os::raw::c_int, maxValueOutOptional: *mut ::std::os::raw::c_int, ) -> *const ::std::os::raw::c_char, >, pub ThemeLayout_RefreshAll: Option<extern "C" fn()>, pub ThemeLayout_SetLayout: Option< unsafe extern "C" fn( section: *const ::std::os::raw::c_char, layout: *const ::std::os::raw::c_char, ) -> bool, >, pub ThemeLayout_SetParameter: Option< extern "C" fn( wp: ::std::os::raw::c_int, value: ::std::os::raw::c_int, persist: bool, ) -> bool, >, pub time_precise: Option<extern "C" fn() -> f64>, pub TimeMap2_beatsToTime: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, tpos: f64, measuresInOptional: *const ::std::os::raw::c_int, ) -> f64, >, pub TimeMap2_GetDividedBpmAtTime: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, time: f64) -> f64>, pub TimeMap2_GetNextChangeTime: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, time: f64) -> f64>, pub TimeMap2_QNToTime: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, qn: f64) -> f64>, pub TimeMap2_timeToBeats: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, tpos: f64, measuresOutOptional: *mut ::std::os::raw::c_int, cmlOutOptional: *mut ::std::os::raw::c_int, fullbeatsOutOptional: *mut f64, cdenomOutOptional: *mut ::std::os::raw::c_int, ) -> f64, >, pub TimeMap2_timeToQN: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, tpos: f64) -> f64>, pub TimeMap_curFrameRate: Option< unsafe extern "C" fn(proj: *mut root::ReaProject, dropFrameOutOptional: *mut bool) -> f64, >, pub TimeMap_GetDividedBpmAtTime: Option<extern "C" fn(time: f64) -> f64>, pub TimeMap_GetMeasureInfo: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, measure: ::std::os::raw::c_int, qn_startOut: *mut f64, qn_endOut: *mut f64, timesig_numOut: *mut ::std::os::raw::c_int, timesig_denomOut: *mut ::std::os::raw::c_int, tempoOut: *mut f64, ) -> f64, >, pub TimeMap_GetMetronomePattern: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, time: f64, pattern: *mut ::std::os::raw::c_char, pattern_sz: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TimeMap_GetTimeSigAtTime: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, time: f64, timesig_numOut: *mut ::std::os::raw::c_int, timesig_denomOut: *mut ::std::os::raw::c_int, tempoOut: *mut f64, ), >, pub TimeMap_QNToMeasures: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, qn: f64, qnMeasureStartOutOptional: *mut f64, qnMeasureEndOutOptional: *mut f64, ) -> ::std::os::raw::c_int, >, pub TimeMap_QNToTime: Option<extern "C" fn(qn: f64) -> f64>, pub TimeMap_QNToTime_abs: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, qn: f64) -> f64>, pub TimeMap_timeToQN: Option<extern "C" fn(tpos: f64) -> f64>, pub TimeMap_timeToQN_abs: Option<unsafe extern "C" fn(proj: *mut root::ReaProject, tpos: f64) -> f64>, pub ToggleTrackSendUIMute: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, send_idx: ::std::os::raw::c_int) -> bool, >, pub Track_GetPeakHoldDB: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, channel: ::std::os::raw::c_int, clear: bool, ) -> f64, >, pub Track_GetPeakInfo: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, channel: ::std::os::raw::c_int) -> f64, >, pub TrackCtl_SetToolTip: Option< unsafe extern "C" fn( fmt: *const ::std::os::raw::c_char, xpos: ::std::os::raw::c_int, ypos: ::std::os::raw::c_int, topmost: bool, ), >, pub TrackFX_AddByName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxname: *const ::std::os::raw::c_char, recFX: bool, instantiate: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TrackFX_CopyToTake: Option< unsafe extern "C" fn( src_track: *mut root::MediaTrack, src_fx: ::std::os::raw::c_int, dest_take: *mut root::MediaItem_Take, dest_fx: ::std::os::raw::c_int, is_move: bool, ), >, pub TrackFX_CopyToTrack: Option< unsafe extern "C" fn( src_track: *mut root::MediaTrack, src_fx: ::std::os::raw::c_int, dest_track: *mut root::MediaTrack, dest_fx: ::std::os::raw::c_int, is_move: bool, ), >, pub TrackFX_Delete: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, fx: ::std::os::raw::c_int) -> bool, >, pub TrackFX_EndParamEdit: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_FormatParamValue: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_FormatParamValueNormalized: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, buf: *mut ::std::os::raw::c_char, buf_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetByName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxname: *const ::std::os::raw::c_char, instantiate: bool, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetChainVisible: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub TrackFX_GetCount: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub TrackFX_GetEnabled: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, fx: ::std::os::raw::c_int) -> bool, >, pub TrackFX_GetEQ: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, instantiate: bool, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetEQBandEnabled: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, bandtype: ::std::os::raw::c_int, bandidx: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetEQParam: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, paramidx: ::std::os::raw::c_int, bandtypeOut: *mut ::std::os::raw::c_int, bandidxOut: *mut ::std::os::raw::c_int, paramtypeOut: *mut ::std::os::raw::c_int, normvalOut: *mut f64, ) -> bool, >, pub TrackFX_GetFloatingWindow: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, index: ::std::os::raw::c_int, ) -> root::HWND, >, pub TrackFX_GetFormattedParamValue: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetFXGUID: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> *mut root::GUID, >, pub TrackFX_GetFXName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetInstrument: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub TrackFX_GetIOSize: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, inputPinsOutOptional: *mut ::std::os::raw::c_int, outputPinsOutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetNamedConfigParm: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetNumParams: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetOffline: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, fx: ::std::os::raw::c_int) -> bool, >, pub TrackFX_GetOpen: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, fx: ::std::os::raw::c_int) -> bool, >, pub TrackFX_GetParam: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, ) -> f64, >, pub TrackFX_GetParameterStepSizes: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, stepOut: *mut f64, smallstepOut: *mut f64, largestepOut: *mut f64, istoggleOut: *mut bool, ) -> bool, >, pub TrackFX_GetParamEx: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, minvalOut: *mut f64, maxvalOut: *mut f64, midvalOut: *mut f64, ) -> f64, >, pub TrackFX_GetParamFromIdent: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, ident_str: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetParamIdent: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetParamName: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, bufOut: *mut ::std::os::raw::c_char, bufOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetParamNormalized: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, ) -> f64, >, pub TrackFX_GetPinMappings: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, high32OutOptional: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetPreset: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, presetnameOut: *mut ::std::os::raw::c_char, presetnameOut_sz: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_GetPresetIndex: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, numberOfPresetsOut: *mut ::std::os::raw::c_int, ) -> ::std::os::raw::c_int, >, pub TrackFX_GetRecChainVisible: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub TrackFX_GetRecCount: Option<unsafe extern "C" fn(track: *mut root::MediaTrack) -> ::std::os::raw::c_int>, pub TrackFX_GetUserPresetFilename: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, fnOut: *mut ::std::os::raw::c_char, fnOut_sz: ::std::os::raw::c_int, ), >, pub TrackFX_NavigatePresets: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, presetmove: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_SetEnabled: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, enabled: bool, ), >, pub TrackFX_SetEQBandEnabled: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, bandtype: ::std::os::raw::c_int, bandidx: ::std::os::raw::c_int, enable: bool, ) -> bool, >, pub TrackFX_SetEQParam: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fxidx: ::std::os::raw::c_int, bandtype: ::std::os::raw::c_int, bandidx: ::std::os::raw::c_int, paramtype: ::std::os::raw::c_int, val: f64, isnorm: bool, ) -> bool, >, pub TrackFX_SetNamedConfigParm: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, parmname: *const ::std::os::raw::c_char, value: *const ::std::os::raw::c_char, ) -> bool, >, pub TrackFX_SetOffline: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, offline: bool, ), >, pub TrackFX_SetOpen: Option< unsafe extern "C" fn(track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, open: bool), >, pub TrackFX_SetParam: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, val: f64, ) -> bool, >, pub TrackFX_SetParamNormalized: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, param: ::std::os::raw::c_int, value: f64, ) -> bool, >, pub TrackFX_SetPinMappings: Option< unsafe extern "C" fn( tr: *mut root::MediaTrack, fx: ::std::os::raw::c_int, isoutput: ::std::os::raw::c_int, pin: ::std::os::raw::c_int, low32bits: ::std::os::raw::c_int, hi32bits: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_SetPreset: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, presetname: *const ::std::os::raw::c_char, ) -> bool, >, pub TrackFX_SetPresetByIndex: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, fx: ::std::os::raw::c_int, idx: ::std::os::raw::c_int, ) -> bool, >, pub TrackFX_Show: Option< unsafe extern "C" fn( track: *mut root::MediaTrack, index: ::std::os::raw::c_int, showFlag: ::std::os::raw::c_int, ), >, pub TrackList_AdjustWindows: Option<extern "C" fn(isMinor: bool)>, pub TrackList_UpdateAllExternalSurfaces: Option<extern "C" fn()>, pub Undo_BeginBlock: Option<extern "C" fn()>, pub Undo_BeginBlock2: Option<unsafe extern "C" fn(proj: *mut root::ReaProject)>, pub Undo_CanRedo2: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> *const ::std::os::raw::c_char>, pub Undo_CanUndo2: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> *const ::std::os::raw::c_char>, pub Undo_DoRedo2: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub Undo_DoUndo2: Option<unsafe extern "C" fn(proj: *mut root::ReaProject) -> ::std::os::raw::c_int>, pub Undo_EndBlock: Option< unsafe extern "C" fn( descchange: *const ::std::os::raw::c_char, extraflags: ::std::os::raw::c_int, ), >, pub Undo_EndBlock2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, descchange: *const ::std::os::raw::c_char, extraflags: ::std::os::raw::c_int, ), >, pub Undo_OnStateChange: Option<unsafe extern "C" fn(descchange: *const ::std::os::raw::c_char)>, pub Undo_OnStateChange2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, descchange: *const ::std::os::raw::c_char, ), >, pub Undo_OnStateChange_Item: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, name: *const ::std::os::raw::c_char, item: *mut root::MediaItem, ), >, pub Undo_OnStateChangeEx: Option< unsafe extern "C" fn( descchange: *const ::std::os::raw::c_char, whichStates: ::std::os::raw::c_int, trackparm: ::std::os::raw::c_int, ), >, pub Undo_OnStateChangeEx2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, descchange: *const ::std::os::raw::c_char, whichStates: ::std::os::raw::c_int, trackparm: ::std::os::raw::c_int, ), >, pub update_disk_counters: Option<extern "C" fn(readamt: ::std::os::raw::c_int, writeamt: ::std::os::raw::c_int)>, pub UpdateArrange: Option<extern "C" fn()>, pub UpdateItemInProject: Option<unsafe extern "C" fn(item: *mut root::MediaItem)>, pub UpdateTimeline: Option<extern "C" fn()>, pub ValidatePtr: Option< unsafe extern "C" fn( pointer: *mut ::std::os::raw::c_void, ctypename: *const ::std::os::raw::c_char, ) -> bool, >, pub ValidatePtr2: Option< unsafe extern "C" fn( proj: *mut root::ReaProject, pointer: *mut ::std::os::raw::c_void, ctypename: *const ::std::os::raw::c_char, ) -> bool, >, pub ViewPrefs: Option< unsafe extern "C" fn( page: ::std::os::raw::c_int, pageByName: *const ::std::os::raw::c_char, ), >, pub WDL_VirtualWnd_ScaledBlitBG: Option< unsafe extern "C" fn( dest: *mut root::reaper_functions::LICE_IBitmap, src: *mut root::reaper_functions::WDL_VirtualWnd_BGCfg, destx: ::std::os::raw::c_int, desty: ::std::os::raw::c_int, destw: ::std::os::raw::c_int, desth: ::std::os::raw::c_int, clipx: ::std::os::raw::c_int, clipy: ::std::os::raw::c_int, clipw: ::std::os::raw::c_int, cliph: ::std::os::raw::c_int, alpha: f32, mode: ::std::os::raw::c_int, ) -> bool, >, pub GetMidiInput: Option<extern "C" fn(idx: ::std::os::raw::c_int) -> *mut root::midi_Input>, pub GetMidiOutput: Option<extern "C" fn(idx: ::std::os::raw::c_int) -> *mut root::midi_Output>, pub InitializeCoolSB: Option<unsafe extern "system" fn(hwnd: root::HWND) -> root::BOOL>, pub UninitializeCoolSB: Option<unsafe extern "system" fn(hwnd: root::HWND) -> root::HRESULT>, pub CoolSB_SetMinThumbSize: Option< unsafe extern "system" fn( hwnd: root::HWND, wBar: root::UINT, size: root::UINT, ) -> root::BOOL, >, pub CoolSB_GetScrollInfo: Option< unsafe extern "system" fn( hwnd: root::HWND, fnBar: ::std::os::raw::c_int, lpsi: root::LPSCROLLINFO, ) -> root::BOOL, >, pub CoolSB_SetScrollInfo: Option< unsafe extern "system" fn( hwnd: root::HWND, fnBar: ::std::os::raw::c_int, lpsi: root::LPSCROLLINFO, fRedraw: root::BOOL, ) -> ::std::os::raw::c_int, >, pub CoolSB_SetScrollPos: Option< unsafe extern "system" fn( hwnd: root::HWND, nBar: ::std::os::raw::c_int, nPos: ::std::os::raw::c_int, fRedraw: root::BOOL, ) -> ::std::os::raw::c_int, >, pub CoolSB_SetScrollRange: Option< unsafe extern "system" fn( hwnd: root::HWND, nBar: ::std::os::raw::c_int, nMinPos: ::std::os::raw::c_int, nMaxPos: ::std::os::raw::c_int, fRedraw: root::BOOL, ) -> ::std::os::raw::c_int, >, pub CoolSB_ShowScrollBar: Option< unsafe extern "system" fn( hwnd: root::HWND, wBar: ::std::os::raw::c_int, fShow: root::BOOL, ) -> root::BOOL, >, pub CoolSB_SetResizingThumb: Option<unsafe extern "system" fn(hwnd: root::HWND, active: root::BOOL) -> root::BOOL>, pub CoolSB_SetThemeIndex: Option< unsafe extern "system" fn(hwnd: root::HWND, idx: ::std::os::raw::c_int) -> root::BOOL, >, } impl ReaperFunctionPointers { pub(crate) const TOTAL_COUNT: u32 = 830u32; }
37.043611
107
0.514392
d5777bafeda76251e5fa5d8efa594beee4cc690b
11,117
// Buttplug Rust Source Code File - See https://buttplug.io for more info. // // Copyright 2016-2020 Nonpolynomial Labs LLC. All rights reserved. // // Licensed under the BSD 3-Clause license. See LICENSE file in the project root // for full license information. //! Handling of websockets using async-tungstenite use super::transport::{ButtplugConnectorTransport, ButtplugTransportIncomingMessage}; use crate::{ connector::{ButtplugConnector, ButtplugConnectorError, ButtplugConnectorResultFuture}, core::messages::{ serializer::{ ButtplugClientJSONSerializer, ButtplugMessageSerializer, ButtplugSerializedMessage, }, ButtplugClientMessage, ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage, ButtplugMessage, ButtplugServerMessage, }, util::async_manager, }; use futures::{future::BoxFuture, FutureExt}; use std::marker::PhantomData; use tokio::sync::mpsc::{channel, Receiver, Sender}; enum ButtplugRemoteConnectorMessage<T> where T: ButtplugMessage + 'static, { Message(T), Close, } enum StreamValue<T> where T: ButtplugMessage + 'static, { NoValue, Incoming(ButtplugTransportIncomingMessage), Outgoing(ButtplugRemoteConnectorMessage<T>), } async fn remote_connector_event_loop< TransportType, SerializerType, OutboundMessageType, InboundMessageType, >( // Takes messages from the client mut connector_outgoing_recv: Receiver<ButtplugRemoteConnectorMessage<OutboundMessageType>>, // Sends messages not matched in the sorter to the client. connector_incoming_sender: Sender<InboundMessageType>, transport: TransportType, // Sends sorter processed messages to the transport. transport_outgoing_sender: Sender<ButtplugSerializedMessage>, // Takes data coming in from the transport. mut transport_incoming_recv: Receiver<ButtplugTransportIncomingMessage>, ) where TransportType: ButtplugConnectorTransport + 'static, SerializerType: ButtplugMessageSerializer<Inbound = InboundMessageType, Outbound = OutboundMessageType> + 'static, OutboundMessageType: ButtplugMessage + 'static, InboundMessageType: ButtplugMessage + 'static, { // Message sorter that receives messages that come in from the client. let serializer = SerializerType::default(); loop { // We use two Options instead of an enum because we may never get anything. // // For the type, we will get back one of two things: Either a serialized // incoming message from the transport for the connector, or an outgoing // message from the connector to go to the transport. let mut stream_return = select! { // Catch messages coming in from the transport. transport = transport_incoming_recv.recv().fuse() => match transport { Some(msg) => StreamValue::Incoming(msg), None => StreamValue::NoValue, }, connector = connector_outgoing_recv.recv().fuse() => match connector { // Catch messages that need to be sent out through the connector. Some(msg) => StreamValue::Outgoing(msg), None => StreamValue::NoValue, } }; match stream_return { // If we get NoValue back, it means one side closed, so the other should // too. StreamValue::NoValue => break, // If we get incoming back, it means we've received something from the // server. See if we have a matching future, else send whatever we got as // an event. StreamValue::Incoming(remote_msg) => { match remote_msg { ButtplugTransportIncomingMessage::Message(serialized_msg) => { match serializer.deserialize(serialized_msg) { Ok(array) => { for smsg in array { // TODO Test validity here. if connector_incoming_sender.send(smsg).await.is_err() { error!("Connector has disconnected, ending remote connector loop."); return; } } } Err(e) => { // TODO Not sure where to relay this. error!( "{}", format!( "Got invalid messages from remote Buttplug connection: {:?}", e ) ); } } } ButtplugTransportIncomingMessage::Close(s) => { info!("Connector closing connection {}", s); break; } // TODO We should probably make connecting an event? ButtplugTransportIncomingMessage::Connected => {} // TODO We should probably figure out what this even does? ButtplugTransportIncomingMessage::Error(_) => {} } } // If we receive something from the client, register it with our sorter // then let the connector figure out what to do with it. StreamValue::Outgoing(ref mut buttplug_msg) => { match buttplug_msg { ButtplugRemoteConnectorMessage::Message(msg) => { // Create future sets our message ID, so make sure this // happens before we send out the message. let serialized_msg = serializer.serialize(vec![msg.clone()]); if transport_outgoing_sender .send(serialized_msg) .await .is_err() { error!("Transport has disconnected, exiting remote connector loop."); return; } } ButtplugRemoteConnectorMessage::Close => { if let Err(e) = transport.disconnect().await { error!("Error disconnecting transport: {:?}", e); } break; } } } } } } pub type ButtplugRemoteClientConnector< TransportType, SerializerType = ButtplugClientJSONSerializer, > = ButtplugRemoteConnector< TransportType, SerializerType, ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage, >; pub type ButtplugRemoteServerConnector<TransportType, SerializerType> = ButtplugRemoteConnector< TransportType, SerializerType, ButtplugServerMessage, ButtplugClientMessage, >; pub struct ButtplugRemoteConnector< TransportType, SerializerType, OutboundMessageType, InboundMessageType, > where TransportType: ButtplugConnectorTransport + 'static, SerializerType: ButtplugMessageSerializer<Inbound = InboundMessageType, Outbound = OutboundMessageType> + 'static, OutboundMessageType: ButtplugMessage + 'static, InboundMessageType: ButtplugMessage + 'static, { /// Transport that the connector will use to communicate with the other /// connector. /// /// This is an option so that, if we connect successfully, we can `.take()` /// the value out of the option and send it to our event loop. This means if /// anyone tries to call connect twice, we'll fail (because we'll have no /// transport to connect to). It also limits the lifetime of the connector to /// the lifetime of the event loop, meaning if for any reason we exit, we make /// sure the transport is dropped. transport: Option<TransportType>, /// Sender for forwarding outgoing messages to the connector event loop. event_loop_sender: Option<Sender<ButtplugRemoteConnectorMessage<OutboundMessageType>>>, dummy_serializer: PhantomData<SerializerType>, } impl<TransportType, SerializerType, OutboundMessageType, InboundMessageType> ButtplugRemoteConnector<TransportType, SerializerType, OutboundMessageType, InboundMessageType> where TransportType: ButtplugConnectorTransport + 'static, SerializerType: ButtplugMessageSerializer<Inbound = InboundMessageType, Outbound = OutboundMessageType> + 'static, OutboundMessageType: ButtplugMessage + 'static, InboundMessageType: ButtplugMessage + 'static, { pub fn new(transport: TransportType) -> Self { Self { transport: Some(transport), event_loop_sender: None, dummy_serializer: PhantomData::default(), } } } impl<TransportType, SerializerType, OutboundMessageType, InboundMessageType> ButtplugConnector<OutboundMessageType, InboundMessageType> for ButtplugRemoteConnector< TransportType, SerializerType, OutboundMessageType, InboundMessageType, > where TransportType: ButtplugConnectorTransport + 'static, SerializerType: ButtplugMessageSerializer<Inbound = InboundMessageType, Outbound = OutboundMessageType> + 'static, OutboundMessageType: ButtplugMessage + 'static, InboundMessageType: ButtplugMessage + 'static, { fn connect( &mut self, connector_incoming_sender: Sender<InboundMessageType>, ) -> BoxFuture<'static, Result<(), ButtplugConnectorError>> { if self.transport.is_some() { // We can unwrap this because we just proved we had it. let transport = self.transport.take().unwrap(); let (connector_outgoing_sender, connector_outgoing_receiver) = channel(256); self.event_loop_sender = Some(connector_outgoing_sender); Box::pin(async move { let (transport_outgoing_sender, transport_outgoing_receiver) = channel(256); let (transport_incoming_sender, transport_incoming_receiver) = channel(256); match transport .connect(transport_outgoing_receiver, transport_incoming_sender) .await { // If we connect successfully, we get back the channel from the transport // to send outgoing messages and receieve incoming events, all serialized. Ok(()) => { async_manager::spawn(async move { remote_connector_event_loop::< TransportType, SerializerType, OutboundMessageType, InboundMessageType, >( connector_outgoing_receiver, connector_incoming_sender, transport, transport_outgoing_sender, transport_incoming_receiver, ) .await }) .unwrap(); Ok(()) } Err(e) => Err(e), } }) } else { ButtplugConnectorError::ConnectorAlreadyConnected.into() } } fn disconnect(&self) -> ButtplugConnectorResultFuture { if let Some(ref sender) = self.event_loop_sender { let sender_clone = sender.clone(); Box::pin(async move { sender_clone .send(ButtplugRemoteConnectorMessage::Close) .await .map_err(|_| ButtplugConnectorError::ConnectorNotConnected) }) } else { ButtplugConnectorError::ConnectorNotConnected.into() } } fn send(&self, msg: OutboundMessageType) -> ButtplugConnectorResultFuture { if let Some(ref sender) = self.event_loop_sender { let sender_clone = sender.clone(); Box::pin(async move { sender_clone .send(ButtplugRemoteConnectorMessage::Message(msg)) .await .map_err(|_| ButtplugConnectorError::ConnectorNotConnected) }) } else { ButtplugConnectorError::ConnectorNotConnected.into() } } }
35.517572
105
0.667356
3a93376a790bb3361cb96464903e4b5ef4e9b059
5,994
use std::error::Error; use std::{cmp, ops}; use ordered_float::NotNan; use serde::{Deserialize, Serialize}; use crate::{trim_f64, Duration}; /// In seconds since midnight. Can't be negative. #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct Time(f64); // By construction, Time is a finite f64 with trimmed precision. impl Eq for Time {} impl Ord for Time { fn cmp(&self, other: &Time) -> cmp::Ordering { self.partial_cmp(other).unwrap() } } impl std::hash::Hash for Time { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { NotNan::new(self.0).unwrap().hash(state); } } impl Time { pub const START_OF_DAY: Time = Time(0.0); // No direct public constructors. Explicitly do Time::START_OF_DAY + duration. fn seconds_since_midnight(value: f64) -> Time { if !value.is_finite() || value < 0.0 { panic!("Bad Time {}", value); } Time(trim_f64(value)) } /// (hours, minutes, seconds, centiseconds) pub fn get_parts(self) -> (usize, usize, usize, usize) { let mut remainder = self.0; let hours = (remainder / 3600.0).floor(); remainder -= hours * 3600.0; let minutes = (remainder / 60.0).floor(); remainder -= minutes * 60.0; let seconds = remainder.floor(); remainder -= seconds; let centis = (remainder / 0.1).floor(); ( hours as usize, minutes as usize, seconds as usize, centis as usize, ) } /// Rounded up pub fn get_hours(self) -> usize { let (hr, min, sec, cs) = self.get_parts(); if min > 0 || sec > 0 || cs > 0 { hr + 1 } else { hr } } pub fn ampm_tostring(self) -> String { let (mut hours, minutes, seconds, _) = self.get_parts(); let next_day = if hours >= 24 { let days = hours / 24; hours = hours % 24; format!(" (+{} days)", days) } else { "".to_string() }; let suffix = if hours < 12 { "AM" } else { "PM" }; if hours == 0 { hours = 12; } else if hours >= 24 { hours -= 24; } else if hours > 12 { hours -= 12; } format!( "{:02}:{:02}:{:02} {}{}", hours, minutes, seconds, suffix, next_day ) } pub fn as_filename(self) -> String { let (hours, minutes, seconds, remainder) = self.get_parts(); format!( "{0:02}h{1:02}m{2:02}.{3:01}s", hours, minutes, seconds, remainder ) } pub fn parse(string: &str) -> Result<Time, Box<dyn Error>> { let parts: Vec<&str> = string.split(':').collect(); if parts.is_empty() { return Err(format!("Time {}: no :'s", string).into()); } let mut seconds: f64 = 0.0; if parts.last().unwrap().contains('.') { let last_parts: Vec<&str> = parts.last().unwrap().split('.').collect(); if last_parts.len() != 2 { return Err(format!("Time {}: no . in last part", string).into()); } seconds += last_parts[1].parse::<f64>()? / 10.0; seconds += last_parts[0].parse::<f64>()?; } else { seconds += parts.last().unwrap().parse::<f64>()?; } match parts.len() { 1 => Ok(Time::seconds_since_midnight(seconds)), 2 => { seconds += 60.0 * parts[0].parse::<f64>()?; Ok(Time::seconds_since_midnight(seconds)) } 3 => { seconds += 60.0 * parts[1].parse::<f64>()?; seconds += 3600.0 * parts[0].parse::<f64>()?; Ok(Time::seconds_since_midnight(seconds)) } _ => Err(format!("Time {}: weird number of parts", string).into()), } } // TODO Why isn't this free given Ord? pub fn min(self, other: Time) -> Time { if self <= other { self } else { other } } pub fn max(self, other: Time) -> Time { if self >= other { self } else { other } } // TODO These are a little weird, so don't operator overload yet pub fn percent_of(self, p: f64) -> Time { if p < 0.0 || p > 1.0 { panic!("Bad percent_of input: {}", p); } Time::seconds_since_midnight(self.0 * p) } pub fn to_percent(self, other: Time) -> f64 { self.0 / other.0 } /// For RNG range generation. Don't abuse. pub fn inner_seconds(self) -> f64 { self.0 } pub fn clamped_sub(self, dt: Duration) -> Time { Time::seconds_since_midnight((self.0 - dt.inner_seconds()).max(0.0)) } pub fn round_seconds(self, s: f64) -> Time { Time::seconds_since_midnight(s * (self.0 / s).round()) } } // 24-hour format by default impl std::fmt::Display for Time { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let (hours, minutes, seconds, remainder) = self.get_parts(); write!( f, "{0:02}:{1:02}:{2:02}.{3:01}", hours, minutes, seconds, remainder ) } } impl ops::Add<Duration> for Time { type Output = Time; fn add(self, other: Duration) -> Time { Time::seconds_since_midnight(self.0 + other.inner_seconds()) } } impl ops::AddAssign<Duration> for Time { fn add_assign(&mut self, other: Duration) { *self = *self + other; } } impl ops::Sub<Duration> for Time { type Output = Time; fn sub(self, other: Duration) -> Time { Time::seconds_since_midnight(self.0 - other.inner_seconds()) } } impl ops::Sub for Time { type Output = Duration; fn sub(self, other: Time) -> Duration { Duration::seconds(self.0 - other.0) } }
27.75
83
0.511011
38a92ea723d98f037ea7c61f9bace402bc6039d2
19,558
use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::ops::Deref; use std::rc::Rc; use crate::HoconLoaderConfig; use super::intermediate::{Child, HoconIntermediate, Node}; use super::value::HoconValue; pub(crate) enum Include<'a> { File(Cow<'a, str>), Url(Cow<'a, str>), } impl<'a> Include<'a> { fn included(&self) -> &Cow<'a, str> { match self { Include::File(s) => s, Include::Url(s) => s, } } } #[derive(Debug, PartialEq, Clone)] pub(crate) struct HoconInternal { pub(crate) internal: Hash, } impl HoconInternal { pub(crate) fn empty() -> Self { Self { internal: vec![] } } pub(crate) fn add(self, mut other: HoconInternal) -> Self { let mut elems = self.internal; elems.append(&mut other.internal); Self { internal: elems } } pub(crate) fn from_properties(properties: HashMap<String, String>) -> Self { Self { internal: properties .into_iter() .map(|(path, value)| { ( path.split('.') .map(|s| HoconValue::String(String::from(s))) .collect(), HoconValue::String(value), ) }) .collect(), } } pub(crate) fn from_value(v: HoconValue) -> Self { Self { internal: vec![(vec![], v)], } } pub(crate) fn from_object(h: Hash) -> Self { if h.is_empty() { Self { internal: vec![(vec![], HoconValue::EmptyObject)], } } else { Self { internal: h .into_iter() .map(|(k, v)| Self::add_root_to_includes(k, v)) .collect(), } } } fn add_root_to_includes(k: Vec<HoconValue>, v: HoconValue) -> (Vec<HoconValue>, HoconValue) { match v { HoconValue::Included { value, original_path, .. } => { let root = k .iter() .take(k.len() - original_path.len()) .cloned() .collect(); ( k, HoconValue::Included { value, include_root: Some(root), original_path, }, ) } HoconValue::ToConcatToArray { value, original_path, item_id, .. } => ( k, HoconValue::ToConcatToArray { value, original_path, item_id, }, ), _ => (k, v), } } pub(crate) fn from_array(a: Vec<HoconInternal>) -> Self { let mut indexer: Box<dyn Fn(i64) -> HoconValue> = Box::new(HoconValue::Integer); if !a.is_empty() && a[0].internal.len() == 1 { if let HoconValue::PathSubstitutionInParent(_) = a[0].internal[0].1 { let index_prefix = uuid::Uuid::new_v4().to_hyphenated().to_string(); indexer = Box::new(move |i| HoconValue::Null(format!("{}-{}", index_prefix, i))); } } if a.is_empty() { Self { internal: vec![(vec![], HoconValue::EmptyArray)], } } else { Self { internal: a .into_iter() .enumerate() .flat_map(|(i, hw)| { Self { internal: hw.internal, } .add_to_path(vec![indexer(i as i64)]) .internal .into_iter() }) .map(|(k, v)| Self::add_root_to_includes(k, v)) .collect(), } } } pub(crate) fn from_include( included: Include, config: &HoconLoaderConfig, ) -> Result<Self, crate::Error> { if config.include_depth > config.max_include_depth { Ok(Self { internal: vec![( vec![HoconValue::String(included.included().to_string())], bad_value_or_err!(config, crate::Error::TooManyIncludes), )], }) } else if config.file_meta.is_none() { Ok(Self { internal: vec![( vec![HoconValue::String(included.included().to_string())], bad_value_or_err!(config, crate::Error::IncludeNotAllowedFromStr), )], }) } else { let included_parsed = match included { Include::File(ref path) => { let include_config = config .included_from() .with_file(std::path::Path::new(path.as_ref()).to_path_buf()); include_config .read_file() .map_err(|_| crate::error::Error::Include { path: path.to_string(), }) .and_then(|s| include_config.parse_str_to_internal(s)) } #[cfg(feature = "url-support")] Include::Url(ref url) => { config .load_url(url) .map_err(|_| crate::error::Error::Include { path: url.to_string(), }) } #[cfg(not(feature = "url-support"))] _ => Err(crate::error::Error::DisabledExternalUrl), }; match included_parsed { Ok(included) => Ok(Self { internal: included .internal .into_iter() .map(|(path, value)| { ( path.clone(), HoconValue::Included { value: Box::new(value), original_path: path, include_root: None, }, ) }) .collect(), }), Err(error) => Ok(Self { internal: vec![( vec![HoconValue::String(included.included().to_string())], bad_value_or_err!(config, error), )], }), } } } pub(crate) fn add_include( &mut self, included: Include, config: &HoconLoaderConfig, ) -> Result<Self, crate::Error> { let mut included = Self::from_include(included, config)?; included.internal.append(&mut self.internal); Ok(included) } pub(crate) fn add_to_path(self, p: Path) -> Self { self.transform(|mut k, v| { let mut new_path = p.clone(); new_path.append(&mut k); (new_path, v) }) } pub(crate) fn transform( self, transform: impl Fn(Vec<HoconValue>, HoconValue) -> (Vec<HoconValue>, HoconValue), ) -> Self { Self { internal: self .internal .into_iter() .map(|(k, v)| (transform(k, v))) .collect(), } } pub(crate) fn merge( self, config: &HoconLoaderConfig, ) -> Result<HoconIntermediate, crate::Error> { let root = Rc::new(Child { key: HoconValue::Temp, value: RefCell::new(Node::Node { children: vec![], key_hint: None, }), }); let mut concatenated_arrays: HashMap<Path, HashMap<HoconValue, i64>> = HashMap::new(); let mut last_path_encoutered = vec![]; for (raw_path, item) in self.internal { if raw_path.is_empty() { continue; } let full_path = raw_path .clone() .into_iter() .flat_map(|path_item| match path_item { HoconValue::UnquotedString(s) => s .trim() .split('.') .map(|s| HoconValue::String(String::from(s))) .collect(), _ => vec![path_item], }) .collect::<Vec<_>>(); let (leaf_value, path) = match item { HoconValue::PathSubstitutionInParent(v) => { let subst = HoconValue::PathSubstitution { target: v, optional: false, original: None, } .substitute(config, &root, &full_path); (subst, full_path.into_iter().rev().skip(1).rev().collect()) } HoconValue::ToConcatToArray { value, original_path, item_id, .. } => { let concat_root: Path = full_path .iter() .rev() .skip(original_path.len()) .rev() .cloned() .collect(); let existing_array = concatenated_arrays .entry(concat_root.clone()) .or_insert_with(HashMap::new); let nb_elems = existing_array.keys().len(); let idx = existing_array .entry(HoconValue::String(item_id.clone())) .or_insert(nb_elems as i64); ( value.substitute(config, &root, &full_path), concat_root .into_iter() .chain(std::iter::once(HoconValue::Integer(*idx))) .chain(original_path.into_iter().flat_map(|path_item| { match path_item { HoconValue::UnquotedString(s) => s .trim() .split('.') .map(|s| HoconValue::String(String::from(s))) .collect(), _ => vec![path_item], } })) .collect(), ) } HoconValue::PathSubstitution { ref target, .. } => { let value = concatenated_arrays .get(&target.to_path()) .cloned() .unwrap_or_else(HashMap::new); concatenated_arrays .entry(full_path.clone()) .or_insert(value); (item.substitute(config, &root, &full_path), full_path) } v => { let mut checked_path: Path = vec![]; for item in full_path.clone() { if let HoconValue::Integer(idx) = item { concatenated_arrays .entry(checked_path.clone()) .or_insert_with(HashMap::new) .entry(HoconValue::Integer(idx)) .or_insert(idx); } checked_path.push(item); } (v.substitute(config, &root, &full_path), full_path) } }; let mut current_path = vec![]; let mut current_node = Rc::clone(&root); let mut old_node_value_for_optional_substitution = None; for path_item in path { current_path.push(path_item.clone()); let (target_child, child_list) = match current_node.value.borrow().deref() { Node::Leaf(old_value) => { let new_child = Rc::new(Child { key: path_item, value: RefCell::new(Node::Leaf(HoconValue::Temp)), }); old_node_value_for_optional_substitution = Some(old_value.clone()); (Rc::clone(&new_child), vec![Rc::clone(&new_child)]) } Node::Node { children, .. } => { let exist = children.iter().find(|child| child.key == path_item); let first_key = children.iter().next().map(|v| Rc::deref(v).key.clone()); match (exist, first_key) { (_, Some(HoconValue::Integer(0))) if path_item == HoconValue::Integer(0) && last_path_encoutered.len() >= current_path.len() && current_path.as_slice() != &last_path_encoutered[0..current_path.len()] => { let mut new_children = vec![]; let new_child = Rc::new(Child { key: path_item.clone(), value: RefCell::new(Node::Leaf(HoconValue::Temp)), }); new_children.push(Rc::clone(&new_child)); (new_child, new_children) } (Some(child), _) => { if let Node::Leaf(old_val) = child.value.borrow().deref() { old_node_value_for_optional_substitution = Some(old_val.clone()); } (Rc::clone(child), children.clone()) } (None, _) => { let new_child = Rc::new(Child { key: path_item.clone(), value: RefCell::new(Node::Leaf(HoconValue::Null( String::from("0"), ))), }); let mut new_children = if children.is_empty() { children.clone() } else { match ( Rc::deref( children.iter().next().expect("got an empty iterator"), ), path_item, ) { (_, HoconValue::Integer(0)) => vec![], ( Child { key: HoconValue::Integer(_), .. }, HoconValue::String(_), ) => vec![], ( Child { key: HoconValue::String(_), .. }, HoconValue::Integer(_), ) => vec![], _ => children.clone(), } }; new_children.push(Rc::clone(&new_child)); (new_child, new_children) } } } }; current_node.value.replace(Node::Node { children: child_list, key_hint: None, }); current_node = target_child; } let mut leaf = current_node.value.borrow_mut(); *leaf = match leaf_value? { Node::Leaf(HoconValue::PathSubstitution { target, optional, original: previously_set_original, }) => Node::Leaf(HoconValue::PathSubstitution { target, optional, original: previously_set_original .or_else(|| old_node_value_for_optional_substitution.map(Box::new)), }), v => v, }; last_path_encoutered = current_path; } Ok(HoconIntermediate { tree: Rc::try_unwrap(root) .expect("error getting Rc") .value .into_inner(), }) } } pub(crate) type Path = Vec<HoconValue>; pub(crate) type Hash = Vec<(Path, HoconValue)>; #[cfg(test)] mod tests { use super::*; #[test] fn max_depth_of_include() { let val = dbg!(HoconInternal::from_include( Include::File(Cow::from("file.conf")), &HoconLoaderConfig { include_depth: 15, file_meta: Some(crate::ConfFileMeta::from_path( std::path::Path::new("file.conf").to_path_buf() )), ..Default::default() } )) .expect("during test"); assert_eq!( val, HoconInternal { internal: vec![( vec![HoconValue::String(String::from("file.conf"))], HoconValue::BadValue(crate::Error::TooManyIncludes) )] } ); } #[test] fn missing_file_included() { let val = dbg!(HoconInternal::from_include( Include::File(Cow::from("file.conf")), &HoconLoaderConfig { include_depth: 5, file_meta: Some(crate::ConfFileMeta::from_path( std::path::Path::new("file.conf").to_path_buf() )), ..Default::default() } )) .expect("during test"); assert_eq!( val, HoconInternal { internal: vec![( vec![HoconValue::String(String::from("file.conf"))], HoconValue::BadValue(crate::Error::Include { path: String::from("file.conf") }) )] } ); } }
36.694184
99
0.37693
0e05cd0bec76c868c29f45b0cb1547044c2f520e
5,849
use crate::canvas::Canvas; use crate::shape::Shape; use crate::Color; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Line2D { x1: i32, y1: i32, x2: i32, y2: i32, } impl Line2D { pub fn new(x1: i32, y1: i32, x2: i32, y2: i32) -> Self { Line2D { x1, y1, x2, y2 } } } impl Shape for Line2D { fn draw(&self, canvas: &mut Canvas, color: &Color, buffer: &mut [u8]) { draw_line2d(self.x1, self.y1, self.x2, self.y2, canvas, color, buffer); } fn draw_filled(&self, canvas: &mut Canvas, color: &Color, buffer: &mut [u8]) { draw_line2d(self.x1, self.y1, self.x2, self.y2, canvas, color, buffer); } fn is_filled(&self) -> bool { false } } /// Draws the line using [Bresenham's line Algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) /// /// It only involves integer calculations hence is fast than DDA pub fn draw_line2d( x1: i32, y1: i32, x2: i32, y2: i32, canvas: &mut Canvas, color: &Color, buffer: &mut [u8], ) { let mut mx1 = x1; let mut mx2 = x2; let mut my1 = y1; let mut my2 = y2; let mut steep = false; if (mx1 - mx2).abs() < (my1 - my2).abs() { std::mem::swap(&mut mx1, &mut my1); std::mem::swap(&mut mx2, &mut my2); steep = true; } if mx1 > mx2 { std::mem::swap(&mut mx1, &mut mx2); std::mem::swap(&mut my1, &mut my2); } let dx = mx2 - mx1; let derror = ((my2 - my1) * 2).abs(); let mut error = 0; let mut y = my1; for x in mx1..(mx2 + 1) { if steep { canvas.draw_point(y, x, color, buffer); } else { canvas.draw_point(x, y, color, buffer); } error += derror; if error > dx { y += if my2 > my1 { 1 } else { -1 }; error -= dx * 2; } } } #[cfg(test)] mod tests { use super::*; use crate::color; const WIDTH: usize = 10; const HEIGHT: usize = 10; const WHITE: [u8; 4] = [255, 255, 255, 255]; #[test] fn test_line_new() { let l = Line2D::new(0, 0, 10, 10); assert_eq!(l.x1, 0); assert_eq!(l.y1, 0); assert_eq!(l.x2, 10); assert_eq!(l.y2, 10); } #[test] fn test_line_slope_less_than_one() { let mut buffer = vec![0u8; 4 * WIDTH * HEIGHT]; let mut canvas = Canvas::new(WIDTH, HEIGHT).unwrap(); draw_line2d(0, 0, 4, 2, &mut canvas, &color::WHITE, &mut buffer[..]); assert_eq!(canvas.get_color(0, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(1, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(2, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(3, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(4, 2, &mut buffer[..]), &WHITE); } #[test] fn test_line_slope_one() { let mut buffer = vec![0u8; 4 * WIDTH * HEIGHT]; let mut canvas = Canvas::new(WIDTH, HEIGHT).unwrap(); draw_line2d(0, 0, 4, 4, &mut canvas, &color::WHITE, &mut buffer[..]); assert_eq!(canvas.get_color(0, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(1, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(2, 2, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(3, 3, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(4, 4, &mut buffer[..]), &WHITE); } #[test] fn test_line_slope_greater_than_one() { let mut buffer = vec![0u8; 4 * WIDTH * HEIGHT]; let mut canvas = Canvas::new(WIDTH, HEIGHT).unwrap(); draw_line2d(0, 0, 2, 4, &mut canvas, &color::WHITE, &mut buffer[..]); assert_eq!(canvas.get_color(0, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(0, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(1, 2, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(1, 3, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(2, 4, &mut buffer[..]), &WHITE); } #[test] fn test_line_slope_infinite() { let mut buffer = vec![0u8; 4 * WIDTH * HEIGHT]; let mut canvas = Canvas::new(WIDTH, HEIGHT).unwrap(); draw_line2d(0, 0, 0, 4, &mut canvas, &color::WHITE, &mut buffer[..]); assert_eq!(canvas.get_color(0, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(0, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(0, 2, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(0, 3, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(0, 4, &mut buffer[..]), &WHITE); } #[test] fn test_line_slope_zero() { let mut buffer = vec![0u8; 4 * WIDTH * HEIGHT]; let mut canvas = Canvas::new(WIDTH, HEIGHT).unwrap(); draw_line2d(0, 0, 4, 0, &mut canvas, &color::WHITE, &mut buffer[..]); assert_eq!(canvas.get_color(0, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(1, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(2, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(3, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(4, 0, &mut buffer[..]), &WHITE); } #[test] fn test_line_point_reorder() { let mut buffer = vec![0u8; 4 * WIDTH * HEIGHT]; let mut canvas = Canvas::new(WIDTH, HEIGHT).unwrap(); draw_line2d(4, 2, 0, 0, &mut canvas, &color::WHITE, &mut buffer[..]); assert_eq!(canvas.get_color(0, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(1, 0, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(2, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(3, 1, &mut buffer[..]), &WHITE); assert_eq!(canvas.get_color(4, 2, &mut buffer[..]), &WHITE); } }
32.494444
113
0.552231
29fab6e0ed8267c810cc31028b99445113c972d0
13,843
use core::marker::PhantomData; use crate::endian::Endian; use crate::macho; use crate::pod::Pod; use crate::read::macho::{MachHeader, SymbolTable}; use crate::read::{Bytes, ReadError, ReadRef, Result, StringTable}; /// An iterator over the load commands of a `MachHeader`. #[derive(Debug, Default, Clone, Copy)] pub struct LoadCommandIterator<'data, E: Endian> { endian: E, data: Bytes<'data>, ncmds: u32, } impl<'data, E: Endian> LoadCommandIterator<'data, E> { pub(super) fn new(endian: E, data: &'data [u8], ncmds: u32) -> Self { LoadCommandIterator { endian, data: Bytes(data), ncmds, } } /// Return the next load command. pub fn next(&mut self) -> Result<Option<LoadCommandData<'data, E>>> { if self.ncmds == 0 { return Ok(None); } let header = self .data .read_at::<macho::LoadCommand<E>>(0) .read_error("Invalid Mach-O load command header")?; let cmd = header.cmd.get(self.endian); let cmdsize = header.cmdsize.get(self.endian) as usize; let data = self .data .read_bytes(cmdsize) .read_error("Invalid Mach-O load command size")?; self.ncmds -= 1; Ok(Some(LoadCommandData { cmd, data, marker: Default::default(), })) } } /// The data for a `LoadCommand`. #[derive(Debug, Clone, Copy)] pub struct LoadCommandData<'data, E: Endian> { cmd: u32, // Includes the header. data: Bytes<'data>, marker: PhantomData<E>, } impl<'data, E: Endian> LoadCommandData<'data, E> { /// Return the `cmd` field of the `LoadCommand`. /// /// This is one of the `LC_` constants. pub fn cmd(&self) -> u32 { self.cmd } /// Return the `cmdsize` field of the `LoadCommand`. pub fn cmdsize(&self) -> u32 { self.data.len() as u32 } /// Parse the data as the given type. #[inline] pub fn data<T: Pod>(&self) -> Result<&'data T> { self.data .read_at(0) .read_error("Invalid Mach-O command size") } /// Parse a load command string value. /// /// Strings used by load commands are specified by offsets that are /// relative to the load command header. pub fn string(&self, endian: E, s: macho::LcStr<E>) -> Result<&'data [u8]> { self.data .read_string_at(s.offset.get(endian) as usize) .read_error("Invalid load command string offset") } /// Parse the command data according to the `cmd` field. pub fn variant(&self) -> Result<LoadCommandVariant<'data, E>> { Ok(match self.cmd { macho::LC_SEGMENT => { let mut data = self.data; let segment = data.read().read_error("Invalid Mach-O command size")?; LoadCommandVariant::Segment32(segment, data.0) } macho::LC_SYMTAB => LoadCommandVariant::Symtab(self.data()?), macho::LC_THREAD | macho::LC_UNIXTHREAD => { let mut data = self.data; let thread = data.read().read_error("Invalid Mach-O command size")?; LoadCommandVariant::Thread(thread, data.0) } macho::LC_DYSYMTAB => LoadCommandVariant::Dysymtab(self.data()?), macho::LC_LOAD_DYLIB | macho::LC_LOAD_WEAK_DYLIB | macho::LC_REEXPORT_DYLIB | macho::LC_LAZY_LOAD_DYLIB | macho::LC_LOAD_UPWARD_DYLIB => LoadCommandVariant::Dylib(self.data()?), macho::LC_ID_DYLIB => LoadCommandVariant::IdDylib(self.data()?), macho::LC_LOAD_DYLINKER => LoadCommandVariant::LoadDylinker(self.data()?), macho::LC_ID_DYLINKER => LoadCommandVariant::IdDylinker(self.data()?), macho::LC_PREBOUND_DYLIB => LoadCommandVariant::PreboundDylib(self.data()?), macho::LC_ROUTINES => LoadCommandVariant::Routines32(self.data()?), macho::LC_SUB_FRAMEWORK => LoadCommandVariant::SubFramework(self.data()?), macho::LC_SUB_UMBRELLA => LoadCommandVariant::SubUmbrella(self.data()?), macho::LC_SUB_CLIENT => LoadCommandVariant::SubClient(self.data()?), macho::LC_SUB_LIBRARY => LoadCommandVariant::SubLibrary(self.data()?), macho::LC_TWOLEVEL_HINTS => LoadCommandVariant::TwolevelHints(self.data()?), macho::LC_PREBIND_CKSUM => LoadCommandVariant::PrebindCksum(self.data()?), macho::LC_SEGMENT_64 => { let mut data = self.data; let segment = data.read().read_error("Invalid Mach-O command size")?; LoadCommandVariant::Segment64(segment, data.0) } macho::LC_ROUTINES_64 => LoadCommandVariant::Routines64(self.data()?), macho::LC_UUID => LoadCommandVariant::Uuid(self.data()?), macho::LC_RPATH => LoadCommandVariant::Rpath(self.data()?), macho::LC_CODE_SIGNATURE | macho::LC_SEGMENT_SPLIT_INFO | macho::LC_FUNCTION_STARTS | macho::LC_DATA_IN_CODE | macho::LC_DYLIB_CODE_SIGN_DRS | macho::LC_LINKER_OPTIMIZATION_HINT | macho::LC_DYLD_EXPORTS_TRIE | macho::LC_DYLD_CHAINED_FIXUPS => LoadCommandVariant::LinkeditData(self.data()?), macho::LC_ENCRYPTION_INFO => LoadCommandVariant::EncryptionInfo32(self.data()?), macho::LC_DYLD_INFO | macho::LC_DYLD_INFO_ONLY => { LoadCommandVariant::DyldInfo(self.data()?) } macho::LC_VERSION_MIN_MACOSX | macho::LC_VERSION_MIN_IPHONEOS | macho::LC_VERSION_MIN_TVOS | macho::LC_VERSION_MIN_WATCHOS => LoadCommandVariant::VersionMin(self.data()?), macho::LC_DYLD_ENVIRONMENT => LoadCommandVariant::DyldEnvironment(self.data()?), macho::LC_MAIN => LoadCommandVariant::EntryPoint(self.data()?), macho::LC_SOURCE_VERSION => LoadCommandVariant::SourceVersion(self.data()?), macho::LC_ENCRYPTION_INFO_64 => LoadCommandVariant::EncryptionInfo64(self.data()?), macho::LC_LINKER_OPTION => LoadCommandVariant::LinkerOption(self.data()?), macho::LC_NOTE => LoadCommandVariant::Note(self.data()?), macho::LC_BUILD_VERSION => LoadCommandVariant::BuildVersion(self.data()?), macho::LC_FILESET_ENTRY => LoadCommandVariant::FilesetEntry(self.data()?), _ => LoadCommandVariant::Other, }) } /// Try to parse this command as a `SegmentCommand32`. /// /// Returns the segment command and the data containing the sections. pub fn segment_32(self) -> Result<Option<(&'data macho::SegmentCommand32<E>, &'data [u8])>> { if self.cmd == macho::LC_SEGMENT { let mut data = self.data; let segment = data.read().read_error("Invalid Mach-O command size")?; Ok(Some((segment, data.0))) } else { Ok(None) } } /// Try to parse this command as a `SymtabCommand`. /// /// Returns the segment command and the data containing the sections. pub fn symtab(self) -> Result<Option<&'data macho::SymtabCommand<E>>> { if self.cmd == macho::LC_SYMTAB { Some(self.data()).transpose() } else { Ok(None) } } /// Try to parse this command as a `DysymtabCommand`. pub fn dysymtab(self) -> Result<Option<&'data macho::DysymtabCommand<E>>> { if self.cmd == macho::LC_DYSYMTAB { Some(self.data()).transpose() } else { Ok(None) } } /// Try to parse this command as a `DylibCommand`. pub fn dylib(self) -> Result<Option<&'data macho::DylibCommand<E>>> { if self.cmd == macho::LC_LOAD_DYLIB || self.cmd == macho::LC_LOAD_WEAK_DYLIB || self.cmd == macho::LC_REEXPORT_DYLIB || self.cmd == macho::LC_LAZY_LOAD_DYLIB || self.cmd == macho::LC_LOAD_UPWARD_DYLIB { Some(self.data()).transpose() } else { Ok(None) } } /// Try to parse this command as a `UuidCommand`. pub fn uuid(self) -> Result<Option<&'data macho::UuidCommand<E>>> { if self.cmd == macho::LC_UUID { Some(self.data()).transpose() } else { Ok(None) } } /// Try to parse this command as a `SegmentCommand64`. pub fn segment_64(self) -> Result<Option<(&'data macho::SegmentCommand64<E>, &'data [u8])>> { if self.cmd == macho::LC_SEGMENT_64 { let mut data = self.data; let command = data.read().read_error("Invalid Mach-O command size")?; Ok(Some((command, data.0))) } else { Ok(None) } } /// Try to parse this command as a `DyldInfoCommand`. pub fn dyld_info(self) -> Result<Option<&'data macho::DyldInfoCommand<E>>> { if self.cmd == macho::LC_DYLD_INFO || self.cmd == macho::LC_DYLD_INFO_ONLY { Some(self.data()).transpose() } else { Ok(None) } } /// Try to parse this command as an `EntryPointCommand`. pub fn entry_point(self) -> Result<Option<&'data macho::EntryPointCommand<E>>> { if self.cmd == macho::LC_MAIN { Some(self.data()).transpose() } else { Ok(None) } } } /// A `LoadCommand` that has been interpreted according to its `cmd` field. #[derive(Debug, Clone, Copy)] #[non_exhaustive] pub enum LoadCommandVariant<'data, E: Endian> { /// `LC_SEGMENT` Segment32(&'data macho::SegmentCommand32<E>, &'data [u8]), /// `LC_SYMTAB` Symtab(&'data macho::SymtabCommand<E>), // obsolete: `LC_SYMSEG` //Symseg(&'data macho::SymsegCommand<E>), /// `LC_THREAD` or `LC_UNIXTHREAD` Thread(&'data macho::ThreadCommand<E>, &'data [u8]), // obsolete: `LC_IDFVMLIB` or `LC_LOADFVMLIB` //Fvmlib(&'data macho::FvmlibCommand<E>), // obsolete: `LC_IDENT` //Ident(&'data macho::IdentCommand<E>), // internal: `LC_FVMFILE` //Fvmfile(&'data macho::FvmfileCommand<E>), // internal: `LC_PREPAGE` /// `LC_DYSYMTAB` Dysymtab(&'data macho::DysymtabCommand<E>), /// `LC_LOAD_DYLIB`, `LC_LOAD_WEAK_DYLIB`, `LC_REEXPORT_DYLIB`, /// `LC_LAZY_LOAD_DYLIB`, or `LC_LOAD_UPWARD_DYLIB` Dylib(&'data macho::DylibCommand<E>), /// `LC_ID_DYLIB` IdDylib(&'data macho::DylibCommand<E>), /// `LC_LOAD_DYLINKER` LoadDylinker(&'data macho::DylinkerCommand<E>), /// `LC_ID_DYLINKER` IdDylinker(&'data macho::DylinkerCommand<E>), /// `LC_PREBOUND_DYLIB` PreboundDylib(&'data macho::PreboundDylibCommand<E>), /// `LC_ROUTINES` Routines32(&'data macho::RoutinesCommand32<E>), /// `LC_SUB_FRAMEWORK` SubFramework(&'data macho::SubFrameworkCommand<E>), /// `LC_SUB_UMBRELLA` SubUmbrella(&'data macho::SubUmbrellaCommand<E>), /// `LC_SUB_CLIENT` SubClient(&'data macho::SubClientCommand<E>), /// `LC_SUB_LIBRARY` SubLibrary(&'data macho::SubLibraryCommand<E>), /// `LC_TWOLEVEL_HINTS` TwolevelHints(&'data macho::TwolevelHintsCommand<E>), /// `LC_PREBIND_CKSUM` PrebindCksum(&'data macho::PrebindCksumCommand<E>), /// `LC_SEGMENT_64` Segment64(&'data macho::SegmentCommand64<E>, &'data [u8]), /// `LC_ROUTINES_64` Routines64(&'data macho::RoutinesCommand64<E>), /// `LC_UUID` Uuid(&'data macho::UuidCommand<E>), /// `LC_RPATH` Rpath(&'data macho::RpathCommand<E>), /// `LC_CODE_SIGNATURE`, `LC_SEGMENT_SPLIT_INFO`, `LC_FUNCTION_STARTS`, /// `LC_DATA_IN_CODE`, `LC_DYLIB_CODE_SIGN_DRS`, `LC_LINKER_OPTIMIZATION_HINT`, /// `LC_DYLD_EXPORTS_TRIE`, or `LC_DYLD_CHAINED_FIXUPS`. LinkeditData(&'data macho::LinkeditDataCommand<E>), /// `LC_ENCRYPTION_INFO` EncryptionInfo32(&'data macho::EncryptionInfoCommand32<E>), /// `LC_DYLD_INFO` or `LC_DYLD_INFO_ONLY` DyldInfo(&'data macho::DyldInfoCommand<E>), /// `LC_VERSION_MIN_MACOSX`, `LC_VERSION_MIN_IPHONEOS`, `LC_VERSION_MIN_WATCHOS`, /// or `LC_VERSION_MIN_TVOS` VersionMin(&'data macho::VersionMinCommand<E>), /// `LC_DYLD_ENVIRONMENT` DyldEnvironment(&'data macho::DylinkerCommand<E>), /// `LC_MAIN` EntryPoint(&'data macho::EntryPointCommand<E>), /// `LC_SOURCE_VERSION` SourceVersion(&'data macho::SourceVersionCommand<E>), /// `LC_ENCRYPTION_INFO_64` EncryptionInfo64(&'data macho::EncryptionInfoCommand64<E>), /// `LC_LINKER_OPTION` LinkerOption(&'data macho::LinkerOptionCommand<E>), /// `LC_NOTE` Note(&'data macho::NoteCommand<E>), /// `LC_BUILD_VERSION` BuildVersion(&'data macho::BuildVersionCommand<E>), /// `LC_FILESET_ENTRY` FilesetEntry(&'data macho::FilesetEntryCommand<E>), /// An unrecognized or obsolete load command. Other, } impl<E: Endian> macho::SymtabCommand<E> { /// Return the symbol table that this command references. pub fn symbols<'data, Mach: MachHeader<Endian = E>, R: ReadRef<'data>>( &self, endian: E, data: R, ) -> Result<SymbolTable<'data, Mach, R>> { let symbols = data .read_slice_at( self.symoff.get(endian).into(), self.nsyms.get(endian) as usize, ) .read_error("Invalid Mach-O symbol table offset or size")?; let str_start: u64 = self.stroff.get(endian).into(); let str_end = str_start .checked_add(self.strsize.get(endian).into()) .read_error("Invalid Mach-O string table length")?; let strings = StringTable::new(data, str_start, str_end); Ok(SymbolTable::new(symbols, strings)) } }
39.664756
97
0.603843
18a2dacfae9ff987713210f1ac42456a35bb766a
1,108
// a:miter use super::super::super::Int32Value; use writer::driver::*; use reader::driver::*; use quick_xml::Reader; use quick_xml::events::{BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Clone, Default, Debug)] pub struct Miter { limit: Int32Value, } impl Miter { pub fn get_limit(&self)-> &i32 { &self.limit.get_value() } pub fn set_limit(&mut self, value:i32)-> &mut Self { self.limit.set_value(value); self } pub(crate) fn set_attributes<R: std::io::BufRead>( &mut self, _reader:&mut Reader<R>, e:&BytesStart ) { match get_attribute(e, b"lim") { Some(v) => {self.limit.set_value_string(v);}, None => {}, } } pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) { // a:miter let mut attributes: Vec<(&str, &str)> = Vec::new(); if &self.limit.has_value() == &true { attributes.push(("lim", &self.limit.get_value_string())); } write_start_tag(writer, "a:miter", attributes, true); } }
25.181818
73
0.565884
dbd8965dcf0d0e94ee857c881ffec1e3f900249f
1,219
#![feature(generators)] #![feature(optin_builtin_traits)] auto trait Foo {} struct No; impl !Foo for No {} struct A<'a, 'b>(&'a mut bool, &'b mut bool, No); impl<'a, 'b: 'a> Foo for A<'a, 'b> {} struct OnlyFooIfStaticRef(No); impl Foo for &'static OnlyFooIfStaticRef {} struct OnlyFooIfRef(No); impl<'a> Foo for &'a OnlyFooIfRef {} fn assert_foo<T: Foo>(f: T) {} fn main() { // Make sure 'static is erased for generator interiors so we can't match it in trait selection let x: &'static _ = &OnlyFooIfStaticRef(No); let gen = || { let x = x; yield; assert_foo(x); }; assert_foo(gen); //~^ ERROR implementation of `Foo` is not general enough //~| ERROR implementation of `Foo` is not general enough // Allow impls which matches any lifetime let x = &OnlyFooIfRef(No); let gen = || { let x = x; yield; assert_foo(x); }; assert_foo(gen); // ok // Disallow impls which relates lifetimes in the generator interior let gen = || { let a = A(&mut true, &mut true, No); yield; assert_foo(a); }; assert_foo(gen); //~^ ERROR not general enough //~| ERROR not general enough }
23
98
0.593109
defbeeb398ff0da50148cc8d59703ea670b87b19
135
extern crate lolbench ; # [ test ] fn end_to_end ( ) { lolbench :: end_to_end_test ( "quickcheck_0_6_1" , "shrink_f64_1_tuple" , ) ; }
45
77
0.681481
d50980d2660ce6e486c0e9584750f5d9c4319376
1,084
// Copyright © Spelldawn 2021-present // 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 // https://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 protos::spelldawn::FontAddress; #[derive(Debug, Clone, Copy)] pub struct Font(&'static str); impl Font { pub fn build(self) -> Option<FontAddress> { Some(FontAddress { address: self.0.to_string() }) } } pub const BUTTON_LABEL: Font = ROBOTO; pub const PROMPT_CONTEXT: Font = ROBOTO; pub const PANEL_TITLE: Font = BLUU_NEXT; pub const SUPPLEMENTAL_INFO_TEXT: Font = ROBOTO; const ROBOTO: Font = Font("Fonts/Roboto"); const BLUU_NEXT: Font = Font("Fonts/BluuNext-Bold");
32.848485
75
0.733395
fca1d482b59ec3fe05d729d5136fdbb822354798
55,551
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::cell::RefCell; use std::f64::INFINITY; use std::fmt; use std::sync::atomic::*; use std::sync::*; use std::time::{SystemTime, UNIX_EPOCH}; use std::{borrow::Cow, time::*}; use concurrency_manager::ConcurrencyManager; use configuration::Configuration; use engine_rocks::raw::DB; use engine_traits::{name_to_cf, CfName, SstCompressionType}; use external_storage_export::{create_storage, ExternalStorage}; use file_system::{IOType, WithIOType}; use futures::channel::mpsc::*; use kvproto::backup::*; use kvproto::kvrpcpb::{Context, IsolationLevel}; use kvproto::metapb::*; use raft::StateRole; use raftstore::coprocessor::RegionInfoProvider; use raftstore::store::util::find_peer; use tikv::config::BackupConfig; use tikv::storage::kv::{CursorBuilder, Engine, ScanMode, SnapContext}; use tikv::storage::mvcc::Error as MvccError; use tikv::storage::txn::{ EntryBatch, Error as TxnError, SnapshotStore, TxnEntryScanner, TxnEntryStore, }; use tikv::storage::Statistics; use tikv_util::time::Limiter; use tikv_util::worker::{Runnable, RunnableWithTimer}; use tikv_util::{ box_err, debug, defer, error, error_unknown, impl_display_as_debug, info, slow_log, thd_name, warn, }; use txn_types::{Key, Lock, TimeStamp}; use yatp::task::callback::{Handle, TaskCell}; use yatp::ThreadPool; use crate::metrics::*; use crate::writer::BackupWriterBuilder; use crate::Error; use crate::*; const BACKUP_BATCH_LIMIT: usize = 1024; // if thread pool has been idle for such long time, we will shutdown it. const IDLE_THREADPOOL_DURATION: u64 = 30 * 60 * 1000; // 30 mins #[derive(Clone)] struct Request { start_key: Vec<u8>, end_key: Vec<u8>, start_ts: TimeStamp, end_ts: TimeStamp, limiter: Limiter, backend: StorageBackend, cancel: Arc<AtomicBool>, is_raw_kv: bool, cf: CfName, compression_type: CompressionType, compression_level: i32, } /// Backup Task. pub struct Task { request: Request, pub(crate) resp: UnboundedSender<BackupResponse>, } impl_display_as_debug!(Task); impl fmt::Debug for Task { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BackupTask") .field("start_ts", &self.request.start_ts) .field("end_ts", &self.request.end_ts) .field( "start_key", &log_wrappers::Value::key(&self.request.start_key), ) .field("end_key", &log_wrappers::Value::key(&self.request.end_key)) .field("is_raw_kv", &self.request.is_raw_kv) .field("cf", &self.request.cf) .finish() } } #[derive(Clone)] struct LimitedStorage { limiter: Limiter, storage: Arc<dyn ExternalStorage>, } impl Task { /// Create a backup task based on the given backup request. pub fn new( req: BackupRequest, resp: UnboundedSender<BackupResponse>, ) -> Result<(Task, Arc<AtomicBool>)> { let cancel = Arc::new(AtomicBool::new(false)); let speed_limit = req.get_rate_limit(); let limiter = Limiter::new(if speed_limit > 0 { speed_limit as f64 } else { INFINITY }); let cf = name_to_cf(req.get_cf()).ok_or_else(|| crate::Error::InvalidCf { cf: req.get_cf().to_owned(), })?; let task = Task { request: Request { start_key: req.get_start_key().to_owned(), end_key: req.get_end_key().to_owned(), start_ts: req.get_start_version().into(), end_ts: req.get_end_version().into(), backend: req.get_storage_backend().clone(), limiter, cancel: cancel.clone(), is_raw_kv: req.get_is_raw_kv(), cf, compression_type: req.get_compression_type(), compression_level: req.get_compression_level(), }, resp, }; Ok((task, cancel)) } /// Check whether the task is canceled. pub fn has_canceled(&self) -> bool { self.request.cancel.load(Ordering::SeqCst) } } #[derive(Debug)] pub struct BackupRange { start_key: Option<Key>, end_key: Option<Key>, region: Region, leader: Peer, is_raw_kv: bool, cf: CfName, } impl BackupRange { /// Get entries from the scanner and save them to storage fn backup<E: Engine>( &self, writer_builder: BackupWriterBuilder, engine: &E, concurrency_manager: ConcurrencyManager, backup_ts: TimeStamp, begin_ts: TimeStamp, storage: &LimitedStorage, ) -> Result<(Vec<File>, Statistics)> { assert!(!self.is_raw_kv); let mut ctx = Context::default(); ctx.set_region_id(self.region.get_id()); ctx.set_region_epoch(self.region.get_region_epoch().to_owned()); ctx.set_peer(self.leader.clone()); // Update max_ts and check the in-memory lock table before getting the snapshot concurrency_manager.update_max_ts(backup_ts); concurrency_manager .read_range_check( self.start_key.as_ref(), self.end_key.as_ref(), |key, lock| { Lock::check_ts_conflict( Cow::Borrowed(lock), &key, backup_ts, &Default::default(), ) }, ) .map_err(MvccError::from) .map_err(TxnError::from)?; // Currently backup always happens on the leader, so we don't need // to set key ranges and start ts to check. assert!(!ctx.get_replica_read()); let snap_ctx = SnapContext { pb_ctx: &ctx, ..Default::default() }; let start_snapshot = Instant::now(); let snapshot = match engine.snapshot(snap_ctx) { Ok(s) => s, Err(e) => { error!(?e; "backup snapshot failed"); return Err(e.into()); } }; BACKUP_RANGE_HISTOGRAM_VEC .with_label_values(&["snapshot"]) .observe(start_snapshot.elapsed().as_secs_f64()); let snap_store = SnapshotStore::new( snapshot, backup_ts, IsolationLevel::Si, false, /* fill_cache */ Default::default(), false, ); let start_key = self.start_key.clone(); let end_key = self.end_key.clone(); // Incremental backup needs to output delete records. let incremental = !begin_ts.is_zero(); let mut scanner = snap_store .entry_scanner(start_key, end_key, begin_ts, incremental) .unwrap(); let start_scan = Instant::now(); let mut files: Vec<File> = Vec::with_capacity(2); let mut batch = EntryBatch::with_capacity(BACKUP_BATCH_LIMIT); let mut last_key = self .start_key .clone() .map_or_else(Vec::new, |k| k.into_raw().unwrap()); let mut cur_key = self .end_key .clone() .map_or_else(Vec::new, |k| k.into_raw().unwrap()); let mut writer = writer_builder.build(last_key.clone())?; loop { if let Err(e) = scanner.scan_entries(&mut batch) { error!(?e; "backup scan entries failed"); return Err(e.into()); }; if batch.is_empty() { break; } debug!("backup scan entries"; "len" => batch.len()); let entries = batch.drain(); if writer.need_split_keys() { let res = { entries.as_slice().get(0).map_or_else( || Err(Error::Other(box_err!("get entry error"))), |x| match x.to_key() { Ok(k) => { cur_key = k.into_raw().unwrap(); writer_builder.build(cur_key.clone()) } Err(e) => { error!(?e; "backup save file failed"); Err(Error::Other(box_err!("Decode error: {:?}", e))) } }, ) }; match writer.save(&storage.storage) { Ok(mut split_files) => { for file in split_files.iter_mut() { file.set_start_key(last_key.clone()); file.set_end_key(cur_key.clone()); } last_key = cur_key.clone(); files.append(&mut split_files); } Err(e) => { error_unknown!(?e; "backup save file failed"); return Err(e); } } match res { Ok(w) => { writer = w; } Err(e) => { error_unknown!(?e; "backup writer failed"); return Err(e); } } } // Build sst files. if let Err(e) = writer.write(entries, true) { error_unknown!(?e; "backup build sst failed"); return Err(e); } } BACKUP_RANGE_HISTOGRAM_VEC .with_label_values(&["scan"]) .observe(start_scan.elapsed().as_secs_f64()); if writer.need_flush_keys() { match writer.save(&storage.storage) { Ok(mut split_files) => { cur_key = self .end_key .clone() .map_or_else(Vec::new, |k| k.into_raw().unwrap()); for file in split_files.iter_mut() { file.set_start_key(last_key.clone()); file.set_end_key(cur_key.clone()); } files.append(&mut split_files); } Err(e) => { error_unknown!(?e; "backup save file failed"); return Err(e); } } } let stat = scanner.take_statistics(); Ok((files, stat)) } fn backup_raw<E: Engine>( &self, writer: &mut BackupRawKVWriter, engine: &E, ) -> Result<Statistics> { assert!(self.is_raw_kv); let mut ctx = Context::default(); ctx.set_region_id(self.region.get_id()); ctx.set_region_epoch(self.region.get_region_epoch().to_owned()); ctx.set_peer(self.leader.clone()); let snap_ctx = SnapContext { pb_ctx: &ctx, ..Default::default() }; let snapshot = match engine.snapshot(snap_ctx) { Ok(s) => s, Err(e) => { error!(?e; "backup raw kv snapshot failed"); return Err(e.into()); } }; let start = Instant::now(); let mut statistics = Statistics::default(); let cfstatistics = statistics.mut_cf_statistics(self.cf); let mut cursor = CursorBuilder::new(&snapshot, self.cf) .range(None, self.end_key.clone()) .scan_mode(ScanMode::Forward) .build()?; if let Some(begin) = self.start_key.clone() { if !cursor.seek(&begin, cfstatistics)? { return Ok(statistics); } } else if !cursor.seek_to_first(cfstatistics) { return Ok(statistics); } let mut batch = vec![]; loop { while cursor.valid()? && batch.len() < BACKUP_BATCH_LIMIT { batch.push(Ok(( cursor.key(cfstatistics).to_owned(), cursor.value(cfstatistics).to_owned(), ))); cursor.next(cfstatistics); } if batch.is_empty() { break; } debug!("backup scan raw kv entries"; "len" => batch.len()); // Build sst files. if let Err(e) = writer.write(batch.drain(..), false) { error_unknown!(?e; "backup raw kv build sst failed"); return Err(e); } } BACKUP_RANGE_HISTOGRAM_VEC .with_label_values(&["raw_scan"]) .observe(start.elapsed().as_secs_f64()); Ok(statistics) } fn backup_raw_kv_to_file<E: Engine>( &self, engine: &E, db: Arc<DB>, storage: &LimitedStorage, file_name: String, cf: CfName, compression_type: Option<SstCompressionType>, compression_level: i32, ) -> Result<(Vec<File>, Statistics)> { let mut writer = match BackupRawKVWriter::new( db, &file_name, cf, storage.limiter.clone(), compression_type, compression_level, ) { Ok(w) => w, Err(e) => { error_unknown!(?e; "backup writer failed"); return Err(e); } }; let stat = match self.backup_raw(&mut writer, engine) { Ok(s) => s, Err(e) => return Err(e), }; // Save sst files to storage. match writer.save(&storage.storage) { Ok(files) => Ok((files, stat)), Err(e) => { error_unknown!(?e; "backup save file failed"); Err(e) } } } } #[derive(Clone)] pub struct ConfigManager(Arc<RwLock<BackupConfig>>); impl configuration::ConfigManager for ConfigManager { fn dispatch(&mut self, change: configuration::ConfigChange) -> configuration::Result<()> { self.0.write().unwrap().update(change); Ok(()) } } #[cfg(test)] impl ConfigManager { fn set_num_threads(&self, num_threads: usize) { self.0.write().unwrap().num_threads = num_threads; } } /// The endpoint of backup. /// /// It coordinates backup tasks and dispatches them to different workers. pub struct Endpoint<E: Engine, R: RegionInfoProvider + Clone + 'static> { store_id: u64, pool: RefCell<ControlThreadPool>, pool_idle_threshold: u64, db: Arc<DB>, config_manager: ConfigManager, concurrency_manager: ConcurrencyManager, pub(crate) engine: E, pub(crate) region_info: R, } /// The progress of a backup task pub struct Progress<R: RegionInfoProvider> { store_id: u64, next_start: Option<Key>, end_key: Option<Key>, region_info: R, finished: bool, is_raw_kv: bool, cf: CfName, } impl<R: RegionInfoProvider> Progress<R> { fn new( store_id: u64, next_start: Option<Key>, end_key: Option<Key>, region_info: R, is_raw_kv: bool, cf: CfName, ) -> Self { Progress { store_id, next_start, end_key, region_info, finished: false, is_raw_kv, cf, } } /// Forward the progress by `ranges` BackupRanges /// /// The size of the returned BackupRanges should <= `ranges` fn forward(&mut self, limit: usize) -> Vec<BackupRange> { if self.finished { return Vec::new(); } let store_id = self.store_id; let (tx, rx) = mpsc::channel(); let start_key_ = self .next_start .clone() .map_or_else(Vec::new, |k| k.into_encoded()); let start_key = self.next_start.clone(); let end_key = self.end_key.clone(); let raw_kv = self.is_raw_kv; let cf_name = self.cf; let res = self.region_info.seek_region( &start_key_, Box::new(move |iter| { let mut count = 0; for info in iter { let region = &info.region; if end_key.is_some() { let end_slice = end_key.as_ref().unwrap().as_encoded().as_slice(); if end_slice <= region.get_start_key() { // We have reached the end. // The range is defined as [start, end) so break if // region start key is greater or equal to end key. break; } } if info.role == StateRole::Leader { let ekey = get_min_end_key(end_key.as_ref(), &region); let skey = get_max_start_key(start_key.as_ref(), &region); assert!(!(skey == ekey && ekey.is_some()), "{:?} {:?}", skey, ekey); let leader = find_peer(region, store_id).unwrap().to_owned(); let backup_range = BackupRange { start_key: skey, end_key: ekey, region: region.clone(), leader, is_raw_kv: raw_kv, cf: cf_name, }; tx.send(backup_range).unwrap(); count += 1; if count >= limit { break; } } } }), ); if let Err(e) = res { // TODO: handle error. error!(?e; "backup seek region failed"); } let branges: Vec<_> = rx.iter().collect(); if let Some(b) = branges.last() { // The region's end key is empty means it is the last // region, we need to set the `finished` flag here in case // we run with `next_start` set to None if b.region.get_end_key().is_empty() || b.end_key == self.end_key { self.finished = true; } self.next_start = b.end_key.clone(); } else { self.finished = true; } branges } } struct ControlThreadPool { size: usize, workers: Option<Arc<ThreadPool<TaskCell>>>, last_active: Instant, } impl ControlThreadPool { fn new() -> Self { ControlThreadPool { size: 0, workers: None, last_active: Instant::now(), } } fn spawn<F>(&mut self, func: F) where F: FnOnce() + Send + 'static, { let workers = self.workers.as_ref().unwrap(); let w = workers.clone(); workers.spawn(move |_: &mut Handle<'_>| { func(); // Debug service requires jobs in the old thread pool continue to run even after // the pool is recreated. So the pool needs to be ref counted and dropped after // task has finished. drop(w); }); } /// Lazily adjust the thread pool's size /// /// Resizing if the thread pool need to expend or there /// are too many idle threads. Otherwise do nothing. fn adjust_with(&mut self, new_size: usize) { if self.size >= new_size && self.size - new_size <= 10 { return; } let workers = Arc::new( yatp::Builder::new(thd_name!("bkwkr")) .max_thread_count(new_size) .build_callback_pool(), ); let _ = self.workers.replace(workers); self.size = new_size; BACKUP_THREAD_POOL_SIZE_GAUGE.set(new_size as i64); } fn heartbeat(&mut self) { self.last_active = Instant::now(); } /// Shutdown the thread pool if it has been idle for a long time. fn check_active(&mut self, idle_threshold: Duration) { if self.last_active.elapsed() >= idle_threshold { self.size = 0; if let Some(w) = self.workers.take() { let start = Instant::now(); drop(w); slow_log!(start.elapsed(), "backup thread pool shutdown too long"); } } } } impl<E: Engine, R: RegionInfoProvider + Clone + 'static> Endpoint<E, R> { pub fn new( store_id: u64, engine: E, region_info: R, db: Arc<DB>, config: BackupConfig, concurrency_manager: ConcurrencyManager, ) -> Endpoint<E, R> { Endpoint { store_id, engine, region_info, pool: RefCell::new(ControlThreadPool::new()), pool_idle_threshold: IDLE_THREADPOOL_DURATION, db, config_manager: ConfigManager(Arc::new(RwLock::new(config))), concurrency_manager, } } pub fn get_config_manager(&self) -> ConfigManager { self.config_manager.clone() } fn spawn_backup_worker( &self, prs: Arc<Mutex<Progress<R>>>, request: Request, tx: UnboundedSender<BackupResponse>, ) { let start_ts = request.start_ts; let end_ts = request.end_ts; let backup_ts = request.end_ts; let engine = self.engine.clone(); let db = self.db.clone(); let store_id = self.store_id; let concurrency_manager = self.concurrency_manager.clone(); let batch_size = self.config_manager.0.read().unwrap().batch_size; let sst_max_size = self.config_manager.0.read().unwrap().sst_max_size.0; // TODO: make it async. self.pool.borrow_mut().spawn(move || { tikv_alloc::add_thread_memory_accessor(); let _with_io_type = WithIOType::new(IOType::Export); defer!({ tikv_alloc::remove_thread_memory_accessor(); }); // Check if we can open external storage. let backend = match create_storage(&request.backend) { Ok(backend) => backend, Err(err) => { error_unknown!(?err; "backup create storage failed"); let mut response = BackupResponse::default(); response.set_error(crate::Error::Io(err).into()); if let Err(err) = tx.unbounded_send(response) { error_unknown!(?err; "backup failed to send response"); } return; } }; let storage = LimitedStorage { limiter: request.limiter, storage: Arc::new(backend), }; loop { let (batch, is_raw_kv, cf) = { // Release lock as soon as possible. // It is critical to speed up backup, otherwise workers are // blocked by each other. let mut progress = prs.lock().unwrap(); let batch = progress.forward(batch_size); if batch.is_empty() { return; } (batch, progress.is_raw_kv, progress.cf) }; for brange in batch { if request.cancel.load(Ordering::SeqCst) { warn!("backup task has canceled"; "range" => ?brange); return; } // TODO: make file_name unique and short let key = brange.start_key.clone().and_then(|k| { // use start_key sha256 instead of start_key to avoid file name too long os error let input = if is_raw_kv { k.into_encoded() } else { k.into_raw().unwrap() }; file_system::sha256(&input).ok().map(hex::encode) }); let name = backup_file_name(store_id, &brange.region, key); let ct = to_sst_compression_type(request.compression_type); let (res, start_key, end_key) = if is_raw_kv { ( brange.backup_raw_kv_to_file( &engine, db.clone(), &storage, name, cf, ct, request.compression_level, ), brange.start_key.map_or_else(Vec::new, |k| k.into_encoded()), brange.end_key.map_or_else(Vec::new, |k| k.into_encoded()), ) } else { let writer_builder = BackupWriterBuilder::new( store_id, storage.limiter.clone(), brange.region.clone(), db.clone(), ct, request.compression_level, sst_max_size, ); ( brange.backup( writer_builder, &engine, concurrency_manager.clone(), backup_ts, start_ts, &storage, ), brange .start_key .map_or_else(Vec::new, |k| k.into_raw().unwrap()), brange .end_key .map_or_else(Vec::new, |k| k.into_raw().unwrap()), ) }; let mut response = BackupResponse::default(); match res { Err(e) => { error_unknown!(?e; "backup region failed"; "region" => ?brange.region, "start_key" => &log_wrappers::Value::key(&start_key), "end_key" => &log_wrappers::Value::key(&end_key), ); response.set_error(e.into()); } Ok((mut files, stat)) => { debug!("backup region finish"; "region" => ?brange.region, "start_key" => &log_wrappers::Value::key(&start_key), "end_key" => &log_wrappers::Value::key(&end_key), "details" => ?stat); for file in files.iter_mut() { if is_raw_kv { file.set_start_key(start_key.clone()); file.set_end_key(end_key.clone()); } file.set_start_version(start_ts.into_inner()); file.set_end_version(end_ts.into_inner()); } response.set_files(files.into()); } } response.set_start_key(start_key); response.set_end_key(end_key); if let Err(e) = tx.unbounded_send(response) { error_unknown!(?e; "backup failed to send response"); return; } } } }); } pub fn handle_backup_task(&self, task: Task) { let Task { request, resp } = task; let is_raw_kv = request.is_raw_kv; let start_key = if request.start_key.is_empty() { None } else { // TODO: if is_raw_kv is written everywhere. It need to be simplified. if is_raw_kv { Some(Key::from_encoded(request.start_key.clone())) } else { Some(Key::from_raw(&request.start_key)) } }; let end_key = if request.end_key.is_empty() { None } else if is_raw_kv { Some(Key::from_encoded(request.end_key.clone())) } else { Some(Key::from_raw(&request.end_key)) }; let prs = Arc::new(Mutex::new(Progress::new( self.store_id, start_key, end_key, self.region_info.clone(), is_raw_kv, request.cf, ))); let concurrency = self.config_manager.0.read().unwrap().num_threads; self.pool.borrow_mut().adjust_with(concurrency); for _ in 0..concurrency { self.spawn_backup_worker(prs.clone(), request.clone(), resp.clone()); } } } impl<E: Engine, R: RegionInfoProvider + Clone + 'static> Runnable for Endpoint<E, R> { type Task = Task; fn run(&mut self, task: Task) { if task.has_canceled() { warn!("backup task has canceled"; "task" => %task); return; } info!("run backup task"; "task" => %task); self.handle_backup_task(task); self.pool.borrow_mut().heartbeat(); } } impl<E: Engine, R: RegionInfoProvider + Clone + 'static> RunnableWithTimer for Endpoint<E, R> { fn on_timeout(&mut self) { let pool_idle_duration = Duration::from_millis(self.pool_idle_threshold); self.pool.borrow_mut().check_active(pool_idle_duration); } fn get_interval(&self) -> Duration { Duration::from_millis(self.pool_idle_threshold) } } /// Get the min end key from the given `end_key` and `Region`'s end key. fn get_min_end_key(end_key: Option<&Key>, region: &Region) -> Option<Key> { let region_end = if region.get_end_key().is_empty() { None } else { Some(Key::from_encoded_slice(region.get_end_key())) }; if region.get_end_key().is_empty() { end_key.cloned() } else if end_key.is_none() { region_end } else { let end_slice = end_key.as_ref().unwrap().as_encoded().as_slice(); if end_slice < region.get_end_key() { end_key.cloned() } else { region_end } } } /// Get the max start key from the given `start_key` and `Region`'s start key. fn get_max_start_key(start_key: Option<&Key>, region: &Region) -> Option<Key> { let region_start = if region.get_start_key().is_empty() { None } else { Some(Key::from_encoded_slice(region.get_start_key())) }; if start_key.is_none() { region_start } else { let start_slice = start_key.as_ref().unwrap().as_encoded().as_slice(); if start_slice < region.get_start_key() { region_start } else { start_key.cloned() } } } /// Construct an backup file name based on the given store id, region, range start key and local unix timestamp. /// A name consists with five parts: store id, region_id, a epoch version, the hash of range start key and timestamp. /// range start key is used to keep the unique file name for file, to handle different tables exists on the same region. /// local unix timestamp is used to keep the unique file name for file, to handle receive the same request after connection reset. pub fn backup_file_name(store_id: u64, region: &Region, key: Option<String>) -> String { let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("Time went backwards"); match key { Some(k) => format!( "{}_{}_{}_{}_{}", store_id, region.get_id(), region.get_region_epoch().get_version(), k, since_the_epoch.as_millis() ), None => format!( "{}_{}_{}", store_id, region.get_id(), region.get_region_epoch().get_version() ), } } // convert BackupCompresionType to rocks db DBCompressionType fn to_sst_compression_type(ct: CompressionType) -> Option<SstCompressionType> { match ct { CompressionType::Lz4 => Some(SstCompressionType::Lz4), CompressionType::Snappy => Some(SstCompressionType::Snappy), CompressionType::Zstd => Some(SstCompressionType::Zstd), CompressionType::Unknown => None, } } #[cfg(test)] pub mod tests { use std::path::{Path, PathBuf}; use std::{fs, thread}; use engine_traits::MiscExt; use external_storage_export::{make_local_backend, make_noop_backend}; use file_system::{IOOp, IORateLimiter}; use futures::executor::block_on; use futures::stream::StreamExt; use kvproto::metapb; use raftstore::coprocessor::RegionCollector; use raftstore::coprocessor::Result as CopResult; use raftstore::coprocessor::SeekRegionCallback; use raftstore::store::util::new_peer; use rand::Rng; use tempfile::TempDir; use tikv::storage::txn::tests::{must_commit, must_prewrite_put}; use tikv::storage::{RocksEngine, TestEngineBuilder}; use tikv_util::config::ReadableSize; use tikv_util::worker::Worker; use txn_types::SHORT_VALUE_MAX_LEN; use super::*; #[derive(Clone)] pub struct MockRegionInfoProvider { regions: Arc<Mutex<RegionCollector>>, cancel: Option<Arc<AtomicBool>>, } impl MockRegionInfoProvider { pub fn new() -> Self { MockRegionInfoProvider { regions: Arc::new(Mutex::new(RegionCollector::new())), cancel: None, } } pub fn set_regions(&self, regions: Vec<(Vec<u8>, Vec<u8>, u64)>) { let mut map = self.regions.lock().unwrap(); for (mut start_key, mut end_key, id) in regions { if !start_key.is_empty() { start_key = Key::from_raw(&start_key).into_encoded(); } if !end_key.is_empty() { end_key = Key::from_raw(&end_key).into_encoded(); } let mut r = metapb::Region::default(); r.set_id(id); r.set_start_key(start_key.clone()); r.set_end_key(end_key); r.mut_peers().push(new_peer(1, 1)); map.create_region(r, StateRole::Leader); } } fn canecl_on_seek(&mut self, cancel: Arc<AtomicBool>) { self.cancel = Some(cancel); } } impl RegionInfoProvider for MockRegionInfoProvider { fn seek_region(&self, from: &[u8], callback: SeekRegionCallback) -> CopResult<()> { let from = from.to_vec(); let regions = self.regions.lock().unwrap(); if let Some(c) = self.cancel.as_ref() { c.store(true, Ordering::SeqCst); } regions.handle_seek_region(from, callback); Ok(()) } } pub fn new_endpoint() -> (TempDir, Endpoint<RocksEngine, MockRegionInfoProvider>) { new_endpoint_with_limiter(None) } pub fn new_endpoint_with_limiter( limiter: Option<Arc<IORateLimiter>>, ) -> (TempDir, Endpoint<RocksEngine, MockRegionInfoProvider>) { let temp = TempDir::new().unwrap(); let rocks = TestEngineBuilder::new() .path(temp.path()) .cfs(&[ engine_traits::CF_DEFAULT, engine_traits::CF_LOCK, engine_traits::CF_WRITE, ]) .io_rate_limiter(limiter) .build() .unwrap(); let concurrency_manager = ConcurrencyManager::new(1.into()); let db = rocks.get_rocksdb().get_sync_db(); ( temp, Endpoint::new( 1, rocks, MockRegionInfoProvider::new(), db, BackupConfig { num_threads: 4, batch_size: 8, sst_max_size: ReadableSize::mb(144), }, concurrency_manager, ), ) } pub fn check_response<F>(rx: UnboundedReceiver<BackupResponse>, check: F) where F: FnOnce(Option<BackupResponse>), { let rx = rx.fuse(); let (resp, rx) = block_on(rx.into_future()); check(resp); let (none, _rx) = block_on(rx.into_future()); assert!(none.is_none(), "{:?}", none); } fn make_unique_dir(path: &Path) -> PathBuf { let uid: u64 = rand::thread_rng().gen(); let tmp_suffix = format!("{:016x}", uid); let unique = path.join(tmp_suffix); fs::create_dir_all(&unique).unwrap(); unique } #[test] fn test_control_thread_pool_adjust_keep_tasks() { use std::thread::sleep; let counter = Arc::new(AtomicU32::new(0)); let mut pool = ControlThreadPool::new(); pool.adjust_with(3); for i in 0..8 { let ctr = counter.clone(); pool.spawn(move || { sleep(Duration::from_millis(100)); ctr.fetch_or(1 << i, Ordering::SeqCst); }); } sleep(Duration::from_millis(150)); pool.adjust_with(4); for i in 8..16 { let ctr = counter.clone(); pool.spawn(move || { sleep(Duration::from_millis(100)); ctr.fetch_or(1 << i, Ordering::SeqCst); }); } sleep(Duration::from_millis(250)); assert_eq!(counter.load(Ordering::SeqCst), 0xffff); } #[test] fn test_seek_range() { let (_tmp, endpoint) = new_endpoint(); endpoint.region_info.set_regions(vec![ (b"".to_vec(), b"1".to_vec(), 1), (b"1".to_vec(), b"2".to_vec(), 2), (b"3".to_vec(), b"4".to_vec(), 3), (b"7".to_vec(), b"9".to_vec(), 4), (b"9".to_vec(), b"".to_vec(), 5), ]); // Test seek backup range. let test_seek_backup_range = |start_key: &[u8], end_key: &[u8], expect: Vec<(&[u8], &[u8])>| { let start_key = if start_key.is_empty() { None } else { Some(Key::from_raw(start_key)) }; let end_key = if end_key.is_empty() { None } else { Some(Key::from_raw(end_key)) }; let mut prs = Progress::new( endpoint.store_id, start_key, end_key, endpoint.region_info.clone(), false, engine_traits::CF_DEFAULT, ); let mut ranges = Vec::with_capacity(expect.len()); while ranges.len() != expect.len() { let n = (rand::random::<usize>() % 3) + 1; let mut r = prs.forward(n); // The returned backup ranges should <= n assert!(r.len() <= n); if r.is_empty() { // if return a empty vec then the progress is finished assert_eq!( ranges.len(), expect.len(), "got {:?}, expect {:?}", ranges, expect ); } ranges.append(&mut r); } for (a, b) in ranges.into_iter().zip(expect) { assert_eq!( a.start_key.map_or_else(Vec::new, |k| k.into_raw().unwrap()), b.0 ); assert_eq!( a.end_key.map_or_else(Vec::new, |k| k.into_raw().unwrap()), b.1 ); } }; // Test whether responses contain correct range. #[allow(clippy::blocks_in_if_conditions)] let test_handle_backup_task_range = |start_key: &[u8], end_key: &[u8], expect: Vec<(&[u8], &[u8])>| { let tmp = TempDir::new().unwrap(); let backend = make_local_backend(tmp.path()); let (tx, rx) = unbounded(); let task = Task { request: Request { start_key: start_key.to_vec(), end_key: end_key.to_vec(), start_ts: 1.into(), end_ts: 1.into(), backend, limiter: Limiter::new(INFINITY), cancel: Arc::default(), is_raw_kv: false, cf: engine_traits::CF_DEFAULT, compression_type: CompressionType::Unknown, compression_level: 0, }, resp: tx, }; endpoint.handle_backup_task(task); let resps: Vec<_> = block_on(rx.collect()); for a in &resps { assert!( expect .iter() .any(|b| { a.get_start_key() == b.0 && a.get_end_key() == b.1 }), "{:?} {:?}", resps, expect ); } assert_eq!(resps.len(), expect.len()); }; // Backup range from case.0 to case.1, // the case.2 is the expected results. type Case<'a> = (&'a [u8], &'a [u8], Vec<(&'a [u8], &'a [u8])>); let case: Vec<Case> = vec![ (b"", b"1", vec![(b"", b"1")]), (b"", b"2", vec![(b"", b"1"), (b"1", b"2")]), (b"1", b"2", vec![(b"1", b"2")]), (b"1", b"3", vec![(b"1", b"2")]), (b"1", b"4", vec![(b"1", b"2"), (b"3", b"4")]), (b"4", b"6", vec![]), (b"4", b"5", vec![]), (b"2", b"7", vec![(b"3", b"4")]), (b"7", b"8", vec![(b"7", b"8")]), (b"3", b"", vec![(b"3", b"4"), (b"7", b"9"), (b"9", b"")]), (b"5", b"", vec![(b"7", b"9"), (b"9", b"")]), (b"7", b"", vec![(b"7", b"9"), (b"9", b"")]), (b"8", b"91", vec![(b"8", b"9"), (b"9", b"91")]), (b"8", b"", vec![(b"8", b"9"), (b"9", b"")]), ( b"", b"", vec![ (b"", b"1"), (b"1", b"2"), (b"3", b"4"), (b"7", b"9"), (b"9", b""), ], ), ]; for (start_key, end_key, ranges) in case { test_seek_backup_range(start_key, end_key, ranges.clone()); test_handle_backup_task_range(start_key, end_key, ranges); } } #[test] fn test_handle_backup_task() { let limiter = Arc::new(IORateLimiter::new_for_test()); let stats = limiter.statistics().unwrap(); let (tmp, endpoint) = new_endpoint_with_limiter(Some(limiter)); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut ts = TimeStamp::new(1); let mut alloc_ts = || *ts.incr(); let mut backup_tss = vec![]; // Multi-versions for key 0..9. for len in &[SHORT_VALUE_MAX_LEN - 1, SHORT_VALUE_MAX_LEN * 2] { for i in 0..10u8 { let start = alloc_ts(); let commit = alloc_ts(); let key = format!("{}", i); must_prewrite_put( &engine, key.as_bytes(), &vec![i; *len], key.as_bytes(), start, ); must_commit(&engine, key.as_bytes(), start, commit); backup_tss.push((alloc_ts(), len)); } } // flush to disk so that read requests can be traced by TiKV limiter. engine .get_rocksdb() .flush_cf(engine_traits::CF_DEFAULT, true /*sync*/) .unwrap(); engine .get_rocksdb() .flush_cf(engine_traits::CF_WRITE, true /*sync*/) .unwrap(); // TODO: check key number for each snapshot. let limiter = Limiter::new(10.0 * 1024.0 * 1024.0 /* 10 MB/s */); for (ts, len) in backup_tss { stats.reset(); let mut req = BackupRequest::default(); req.set_start_key(vec![]); req.set_end_key(vec![b'5']); req.set_start_version(0); req.set_end_version(ts.into_inner()); let (tx, rx) = unbounded(); let tmp1 = make_unique_dir(tmp.path()); req.set_storage_backend(make_local_backend(&tmp1)); if len % 2 == 0 { req.set_rate_limit(10 * 1024 * 1024); } let (mut task, _) = Task::new(req, tx).unwrap(); if len % 2 == 0 { // Make sure the rate limiter is set. assert!(task.request.limiter.speed_limit().is_finite()); // Share the same rate limiter. task.request.limiter = limiter.clone(); } endpoint.handle_backup_task(task); let (resp, rx) = block_on(rx.into_future()); let resp = resp.unwrap(); assert!(!resp.has_error(), "{:?}", resp); let file_len = if *len <= SHORT_VALUE_MAX_LEN { 1 } else { 2 }; let files = resp.get_files(); info!("{:?}", files); assert_eq!( files.len(), file_len, /* default and write */ "{:?}", resp ); let (none, _rx) = block_on(rx.into_future()); assert!(none.is_none(), "{:?}", none); assert_eq!(stats.fetch(IOType::Export, IOOp::Write), 0); assert_ne!(stats.fetch(IOType::Export, IOOp::Read), 0); } } #[test] fn test_scan_error() { let (tmp, endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut ts: TimeStamp = 1.into(); let mut alloc_ts = || *ts.incr(); let start = alloc_ts(); let key = format!("{}", start); must_prewrite_put( &engine, key.as_bytes(), key.as_bytes(), key.as_bytes(), start, ); let now = alloc_ts(); let mut req = BackupRequest::default(); req.set_start_key(vec![]); req.set_end_key(vec![b'5']); req.set_start_version(now.into_inner()); req.set_end_version(now.into_inner()); req.set_concurrency(4); let tmp1 = make_unique_dir(tmp.path()); req.set_storage_backend(make_local_backend(&tmp1)); let (tx, rx) = unbounded(); let (task, _) = Task::new(req.clone(), tx).unwrap(); endpoint.handle_backup_task(task); check_response(rx, |resp| { let resp = resp.unwrap(); assert!(resp.get_error().has_kv_error(), "{:?}", resp); assert!(resp.get_error().get_kv_error().has_locked(), "{:?}", resp); assert_eq!(resp.get_files().len(), 0, "{:?}", resp); }); // Commit the perwrite. let commit = alloc_ts(); must_commit(&engine, key.as_bytes(), start, commit); // Test whether it can correctly convert not leader to region error. engine.trigger_not_leader(); let now = alloc_ts(); req.set_start_version(now.into_inner()); req.set_end_version(now.into_inner()); let tmp2 = make_unique_dir(tmp.path()); req.set_storage_backend(make_local_backend(&tmp2)); let (tx, rx) = unbounded(); let (task, _) = Task::new(req, tx).unwrap(); endpoint.handle_backup_task(task); check_response(rx, |resp| { let resp = resp.unwrap(); assert!(resp.get_error().has_region_error(), "{:?}", resp); assert!( resp.get_error().get_region_error().has_not_leader(), "{:?}", resp ); }); } #[test] fn test_cancel() { let (temp, mut endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut ts: TimeStamp = 1.into(); let mut alloc_ts = || *ts.incr(); let start = alloc_ts(); let key = format!("{}", start); must_prewrite_put( &engine, key.as_bytes(), key.as_bytes(), key.as_bytes(), start, ); // Commit the perwrite. let commit = alloc_ts(); must_commit(&engine, key.as_bytes(), start, commit); let now = alloc_ts(); let mut req = BackupRequest::default(); req.set_start_key(vec![]); req.set_end_key(vec![]); req.set_start_version(now.into_inner()); req.set_end_version(now.into_inner()); req.set_concurrency(4); req.set_storage_backend(make_local_backend(temp.path())); // Cancel the task before starting the task. let (tx, rx) = unbounded(); let (task, cancel) = Task::new(req.clone(), tx).unwrap(); // Cancel the task. cancel.store(true, Ordering::SeqCst); endpoint.handle_backup_task(task); check_response(rx, |resp| { assert!(resp.is_none()); }); // Cancel the task during backup. let (tx, rx) = unbounded(); let (task, cancel) = Task::new(req, tx).unwrap(); endpoint.region_info.canecl_on_seek(cancel); endpoint.handle_backup_task(task); check_response(rx, |resp| { assert!(resp.is_none()); }); } #[test] fn test_busy() { let (_tmp, endpoint) = new_endpoint(); let engine = endpoint.engine.clone(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"5".to_vec(), 1)]); let mut req = BackupRequest::default(); req.set_start_key(vec![]); req.set_end_key(vec![]); req.set_start_version(1); req.set_end_version(1); req.set_concurrency(4); req.set_storage_backend(make_noop_backend()); let (tx, rx) = unbounded(); let (task, _) = Task::new(req, tx).unwrap(); // Pause the engine 6 seconds to trigger Timeout error. // The Timeout error is translated to server is busy. engine.pause(Duration::from_secs(6)); endpoint.handle_backup_task(task); check_response(rx, |resp| { let resp = resp.unwrap(); assert!(resp.get_error().has_region_error(), "{:?}", resp); assert!( resp.get_error().get_region_error().has_server_is_busy(), "{:?}", resp ); }); } #[test] fn test_adjust_thread_pool_size() { let (_tmp, endpoint) = new_endpoint(); endpoint .region_info .set_regions(vec![(b"".to_vec(), b"".to_vec(), 1)]); let mut req = BackupRequest::default(); req.set_start_key(vec![]); req.set_end_key(vec![]); req.set_start_version(1); req.set_end_version(1); req.set_storage_backend(make_noop_backend()); let (tx, _) = unbounded(); // expand thread pool is needed endpoint.get_config_manager().set_num_threads(15); let (task, _) = Task::new(req.clone(), tx.clone()).unwrap(); endpoint.handle_backup_task(task); assert!(endpoint.pool.borrow().size == 15); // shrink thread pool only if there are too many idle threads endpoint.get_config_manager().set_num_threads(10); let (task, _) = Task::new(req.clone(), tx.clone()).unwrap(); endpoint.handle_backup_task(task); assert!(endpoint.pool.borrow().size == 15); endpoint.get_config_manager().set_num_threads(3); let (task, _) = Task::new(req, tx).unwrap(); endpoint.handle_backup_task(task); assert!(endpoint.pool.borrow().size == 3); } pub struct EndpointWrapper<E: Engine, R: RegionInfoProvider + Clone + 'static> { inner: Arc<Mutex<Endpoint<E, R>>>, } impl<E: Engine, R: RegionInfoProvider + Clone + 'static> Runnable for EndpointWrapper<E, R> { type Task = Task; fn run(&mut self, task: Task) { self.inner.lock().unwrap().run(task); } } impl<E: Engine, R: RegionInfoProvider + Clone + 'static> RunnableWithTimer for EndpointWrapper<E, R> { fn on_timeout(&mut self) { self.inner.lock().unwrap().on_timeout(); } fn get_interval(&self) -> Duration { self.inner.lock().unwrap().get_interval() } } #[test] fn test_thread_pool_shutdown_when_idle() { let (_tmp, mut endpoint) = new_endpoint(); // set the idle threshold to 100ms endpoint.pool_idle_threshold = 100; let endpoint = Arc::new(Mutex::new(endpoint)); let worker = Worker::new("endpoint"); let scheduler = { let inner = endpoint.clone(); worker.start_with_timer("endpoint", EndpointWrapper { inner }) }; let mut req = BackupRequest::default(); req.set_start_key(vec![]); req.set_end_key(vec![]); req.set_start_version(1); req.set_end_version(1); req.set_storage_backend(make_noop_backend()); endpoint .lock() .unwrap() .get_config_manager() .set_num_threads(10); let (tx, resp_rx) = unbounded(); let (task, _) = Task::new(req, tx).unwrap(); // if not task arrive after create the thread pool is empty assert_eq!(endpoint.lock().unwrap().pool.borrow().size, 0); scheduler.schedule(task).unwrap(); // wait until the task finish let _ = block_on(resp_rx.into_future()); assert_eq!(endpoint.lock().unwrap().pool.borrow().size, 10); // thread pool not yet shutdown thread::sleep(Duration::from_millis(50)); assert_eq!(endpoint.lock().unwrap().pool.borrow().size, 10); // thread pool shutdown if not task arrive more than 100ms thread::sleep(Duration::from_millis(160)); assert_eq!(endpoint.lock().unwrap().pool.borrow().size, 0); } // TODO: region err in txn(engine(request)) }
35.136622
130
0.495509
5dac94d7b19cd57016db3c2de9594d38a3c70345
3,474
#[doc = "Reader of register DMA_MISC_CONF"] pub type R = crate::R<u32, super::DMA_MISC_CONF>; #[doc = "Writer for register DMA_MISC_CONF"] pub type W = crate::W<u32, super::DMA_MISC_CONF>; #[doc = "Register DMA_MISC_CONF `reset()`'s with value 0"] impl crate::ResetValue for super::DMA_MISC_CONF { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DMA_CLK_EN`"] pub type DMA_CLK_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA_CLK_EN`"] pub struct DMA_CLK_EN_W<'a> { w: &'a mut W, } impl<'a> DMA_CLK_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `DMA_ARB_PRI_DIS`"] pub type DMA_ARB_PRI_DIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA_ARB_PRI_DIS`"] pub struct DMA_ARB_PRI_DIS_W<'a> { w: &'a mut W, } impl<'a> DMA_ARB_PRI_DIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `DMA_AHBM_RST_INTER`"] pub type DMA_AHBM_RST_INTER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA_AHBM_RST_INTER`"] pub struct DMA_AHBM_RST_INTER_W<'a> { w: &'a mut W, } impl<'a> DMA_AHBM_RST_INTER_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 3"] #[inline(always)] pub fn dma_clk_en(&self) -> DMA_CLK_EN_R { DMA_CLK_EN_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2"] #[inline(always)] pub fn dma_arb_pri_dis(&self) -> DMA_ARB_PRI_DIS_R { DMA_ARB_PRI_DIS_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 0"] #[inline(always)] pub fn dma_ahbm_rst_inter(&self) -> DMA_AHBM_RST_INTER_R { DMA_AHBM_RST_INTER_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 3"] #[inline(always)] pub fn dma_clk_en(&mut self) -> DMA_CLK_EN_W { DMA_CLK_EN_W { w: self } } #[doc = "Bit 2"] #[inline(always)] pub fn dma_arb_pri_dis(&mut self) -> DMA_ARB_PRI_DIS_W { DMA_ARB_PRI_DIS_W { w: self } } #[doc = "Bit 0"] #[inline(always)] pub fn dma_ahbm_rst_inter(&mut self) -> DMA_AHBM_RST_INTER_W { DMA_AHBM_RST_INTER_W { w: self } } }
29.193277
84
0.570524
2f3772e5600715c2d179fc6411a6e5be0ba625c0
2,090
use async_trait::async_trait; use crate::rules_parser::rule::Rule; use crate::engine::waf_engine::WafEngine; use hyper::{Response, Request, Body}; use crate::waf_error::WafError; use crate::engine::waf_engine_type::WafEngineType::RuleBased; use crate::engine::waf_engine_type::WafEngineType; use crate::waf_running_mode::WafRunningMode; use crate::waf_running_mode::WafRunningMode::{Off, On}; pub struct RuleBasedEngine { running_mode: WafRunningMode, rules: Vec<Rule>, } #[async_trait] impl WafEngine for RuleBasedEngine { fn running_mode(&self) -> WafRunningMode { self.running_mode.clone() } fn engine_type(&self) -> WafEngineType { RuleBased } async fn inspect_request(&self, request: Request<Body>) -> Result<Request<Body>, WafError> { self.apply_rules(request) .await .map_err(|_err| WafError::new("Could not handle HTTP request")) } async fn inspect_response(&self, response: Response<Body>) -> Result<Response<Body>, WafError> { Ok(response) } } impl RuleBasedEngine { pub fn new(running_mode: WafRunningMode, rules: Vec<Rule>) -> Self { Self { running_mode, rules, } } async fn apply_rules(&self, mut request: Request<Body>) -> Result<Request<Body>, WafError> { if self.running_mode != Off { let mut matched_rules: Vec<Rule> = vec![]; for rule in self.rules.iter() { let (reconstructed_request, is_matched) = rule.matches(request).await; request = reconstructed_request; if is_matched { matched_rules.push(rule.clone()); } } if !matched_rules.is_empty() { log::warn!("Request {:?} matches: {:?}", request, matched_rules); if self.running_mode == On { log::warn!("Blocking request {:?}", request); return Err(WafError::new("Blocked request")); } } } Ok(request) } }
31.19403
100
0.594737
7214addfca68a4cc31a48905e6c5f82ae7aecb43
521
//! Structures related to dynamics: bodies, joints, etc. pub use self::ccd_solver::*; pub use self::impulse_joint_set::*; pub use self::integration_parameters::*; pub use self::island_manager::*; pub use self::joint::*; pub use self::multibody_joint_set::*; pub use self::rigid_body::*; pub use self::rigid_body_set::*; mod ccd_solver; mod impulse_joint; mod impulse_joint_set; mod integration_parameters; mod island_manager; mod joint; mod multibody_joint; mod multibody_joint_set; mod rigid_body; mod rigid_body_set;
23.681818
56
0.771593
5d374a1763cba4e31869540788228d745c25a39f
4,444
use async_std::fs; use async_std::path::Path as AsyncPath; use async_std::prelude::*; use async_std::task; use atty::Stream; use clap::{load_yaml, App}; use colored::{self, Colorize}; use nomino::errors::SourceError; use nomino::input::{Context, Formatter, Source}; use prettytable::{cell, format, row, Table}; use serde_json::map::Map; use serde_json::value::Value; use std::env::{args, set_current_dir}; use std::error::Error; use std::path::Path; use std::process::exit; async fn read_source( regex: Option<&str>, sort: Option<&str>, map: Option<&str>, ) -> Result<Source, Box<dyn Error>> { match (regex, sort, map) { (Some(pattern), _, _) => Source::new_regex(pattern).await, (_, Some(order), _) => Source::new_sort(order).await, (_, _, Some(filename)) => Source::new_map(filename).await, _ => { colored::control::set_override(atty::is(Stream::Stderr)); Err(Box::new(SourceError::new(format!( "one of '{}', '{}' or '{}' options must be set.\n{}: run '{} {}' for more information.", "regex".cyan(), "sort".cyan(), "map".cyan(), "usage".yellow().bold(), args().next().unwrap().cyan(), "--help".cyan(), )))) } } } async fn read_output(output: Option<&str>) -> Result<Option<Formatter>, Box<dyn Error>> { if output.is_none() { return Ok(None); } Ok(Some(Formatter::new(output.unwrap()).await?)) } async fn rename_files( context: Context, test_mode: bool, need_map: bool, ) -> Result<Option<Map<String, Value>>, Box<dyn Error>> { let mut map_iter = context.into_iter().await?; let mut map = if need_map { Some(Map::new()) } else { None }; let mut is_renamed = true; while let Some((input, mut output)) = map_iter.next().await { while AsyncPath::new(output.as_str()).exists().await { output = String::from("_") + output.as_str(); } if !test_mode { is_renamed = fs::rename(input.as_str(), output.as_str()).await.is_ok(); } if is_renamed && need_map { map.as_mut().map(|m| m.insert(output, Value::String(input))); } is_renamed = true; } Ok(map) } async fn print_map_table(map: Map<String, Value>) -> Result<(), Box<dyn Error>> { let mut table = Table::new(); table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE); table.set_titles(row!["Input".cyan(), "Output".cyan()]); map.into_iter() .enumerate() .for_each(|(i, (output, input))| { if let Value::String(input) = input { if i % 2 == 0 { table.add_row(row![input.as_str(), output.as_str()]); } else { table.add_row(row![input.as_str().purple(), output.as_str().purple()]); } } }); table.printstd(); Ok(()) } async fn run_app() -> Result<(), Box<dyn Error>> { let opts_format = load_yaml!("opts.yml"); let opts = App::from_yaml(opts_format).get_matches(); if let Some(cwd) = opts.value_of("directory").map(Path::new) { set_current_dir(cwd)?; } let context = Context::new( read_source( opts.value_of("regex"), opts.value_of("sort"), opts.value_of("map"), ) .await?, read_output(opts.value_of("output")).await?, opts.is_present("extension"), ) .await; let print_map = opts.is_present("print"); let generate_map = opts.value_of("generate"); let test_mode = opts.is_present("test"); let map = rename_files(context, test_mode, print_map || generate_map.is_some()).await?; if let Some(map_file) = generate_map { fs::write( map_file, serde_json::to_vec_pretty(map.as_ref().unwrap())?.as_slice(), ) .await?; } if print_map { colored::control::set_override(atty::is(Stream::Stdout)); print_map_table(map.unwrap()).await?; } Ok(()) } async fn async_main() -> i32 { match run_app().await { Ok(_) => 0, Err(err) => { colored::control::set_override(atty::is(Stream::Stderr)); eprintln!("{}: {}", "error".red().bold(), err.to_string()); 1 } } } fn main() { exit(task::block_on(async_main())); }
31.742857
104
0.55468
38c30a376a92bfe665661deebe31ca611789ee79
1,285
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #![feature(specialization)] #![feature(try_from)] #![feature(box_syntax)] #![feature(maybe_uninit)] #![allow(dead_code)] #![allow(non_camel_case_types)] #[macro_use] pub mod errors; pub mod basic; pub mod data_type; // Exported for external use, such as benchmarks pub use self::encodings::{decoding, encoding}; pub use self::util::memory; #[macro_use] mod util; pub mod column; pub mod compression; mod encodings; pub mod file; // pub mod reader; pub mod record; pub mod schema;
29.883721
63
0.74786
fbdf088278153f7509dee037789e87caf699a44c
4,902
// Copyright 2020 The Vega 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. //! Vega explorer service. //! //! The explorer service does not define transactions, but it has several REST / WebSocket //! endpoints allowing to retrieve information from the blockchain in a structured way. //! Usually, the explorer service should be instantiated at the blockchain start //! with the default identifiers. There may be no more than one explorer service on a blockchain; //! an attempt to create a second service instance will lead to an error in the service //! constructor. //! //! The API types necessary to interact with the service HTTP API are defined in a separate //! crate, [`vega-explorer`]. The base explorer provides Rust language APIs for retrieving info //! from the blockchain, while this crate translates these APIs into REST and WebSocket endpoints //! and packages this logic as an Vega service. Thus, this crate is useful if you want to provide //! the way for external apps to query the blockchain info. //! //! # HTTP API //! //! REST API of the service is documented in the [`api` module](api/index.html), and its //! WebSocket API in the [`api::websocket` module](api/websocket/index.html). //! //! # Examples //! //! ## Use with Testkit //! //! ``` //! use vega_explorer::api::BlocksRange; //! use vega_explorer_service::ExplorerFactory; //! use vega_testkit::{ApiKind, TestKit, TestKitBuilder}; //! //! let mut testkit: TestKit = TestKitBuilder::validator() //! .with_default_rust_service(ExplorerFactory) //! // Add other services here //! .create(); //! // The explorer endpoints can be accessed via `api()`: //! let api = testkit.api(); //! let BlocksRange { blocks, range } = api //! .public(ApiKind::Explorer) //! .get("v1/blocks?count=10") //! .unwrap(); //! ``` //! //! [`vega-explorer`]: https://docs.rs/vega-explorer #![deny( unsafe_code, bare_trait_objects, missing_docs, missing_debug_implementations )] use vega::{ merkledb::ObjectHash, runtime::{ExecutionContext, ExecutionError, ExecutionFail}, }; use vega_derive::*; use vega_rust_runtime::{api::ServiceApiBuilder, AfterCommitContext, DefaultInstance, Service}; pub mod api; use crate::api::{websocket::SharedState, ExplorerApi}; /// Errors that can occur during explorer service operation. #[derive(Debug, Clone, Copy, ExecutionFail)] pub enum Error { /// An explorer service is already instantiated on the blockchain. DuplicateExplorer = 0, } /// Explorer service. #[derive(Debug, Default, ServiceDispatcher)] pub struct ExplorerService { shared_state: SharedState, } impl Service for ExplorerService { fn initialize( &self, context: ExecutionContext<'_>, _params: Vec<u8>, ) -> Result<(), ExecutionError> { // Check that there are no other explorer services. let instances = context.data().for_dispatcher().service_instances(); for instance in instances.values() { if instance.spec.artifact.name == env!("CARGO_PKG_NAME") { let msg = format!( "An explorer service is already instantiated on the blockchain as {}", instance.spec ); return Err(Error::DuplicateExplorer.with_description(msg)); } } Ok(()) } fn after_commit(&self, context: AfterCommitContext<'_>) { let block_hash = context.data().for_core().last_block().object_hash(); self.shared_state.broadcast_block(block_hash); } fn wire_api(&self, builder: &mut ServiceApiBuilder) { let blockchain = builder.blockchain().to_owned(); let scope = builder .with_root_path(ExplorerFactory::INSTANCE_NAME) .public_scope(); ExplorerApi::new(blockchain) .wire_rest(scope) .wire_ws(self.shared_state.get_ref(), scope); } } /// Explorer service factory. #[derive(Debug, Clone, Copy, ServiceFactory)] #[service_factory(service_constructor = "Self::new_instance")] pub struct ExplorerFactory; impl ExplorerFactory { #[allow(clippy::trivially_copy_pass_by_ref)] fn new_instance(&self) -> Box<dyn Service> { Box::new(ExplorerService::default()) } } impl DefaultInstance for ExplorerFactory { const INSTANCE_ID: u32 = 2; const INSTANCE_NAME: &'static str = "explorer"; }
34.765957
97
0.682171
1a2662d37f52d16a2e1a5e9d794c43c93e117fec
15,607
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::ed25519::{ Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature, ED25519_PRIVATE_KEY_LENGTH, ED25519_PUBLIC_KEY_LENGTH, }; use crate::hash::{CryptoHash, CryptoHasher}; use crate::{CryptoMaterialError, Length, PrivateKey, Signature, ValidCryptoMaterial}; use crate::{SigningKey, Uniform}; use anyhow::{anyhow, bail, ensure, Result}; use libra_crypto::multi_ed25519::{MultiEd25519PublicKey, MultiEd25519Signature}; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::fmt; const MAX_NUM_OF_KEYS: usize = 32; const BITMAP_NUM_OF_BYTES: usize = 4; /// Part of private keys in the multi-key Ed25519 structure along with the threshold. /// note: the private keys must be a sequential part of the MultiEd25519PrivateKey #[derive(Eq, PartialEq, Serialize, Deserialize)] pub struct MultiEd25519KeyShard { /// Public keys must contains all public key of the MultiEd25519PrivateKey public_keys: Vec<Ed25519PublicKey>, threshold: u8, private_keys: Vec<Ed25519PrivateKey>, /// The private_key index in MultiEd25519PrivateKey, if has multi private_keys, use the first key index. index: u8, } #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct MultiEd25519SignatureShard { signature: MultiEd25519Signature, threshold: u8, } impl MultiEd25519KeyShard { pub fn new( public_keys: Vec<Ed25519PublicKey>, threshold: u8, private_key: Ed25519PrivateKey, index: u8, ) -> Result<Self, CryptoMaterialError> { Self::new_multi(public_keys, threshold, vec![private_key], index) } pub fn new_multi( public_keys: Vec<Ed25519PublicKey>, threshold: u8, private_keys: Vec<Ed25519PrivateKey>, index: u8, ) -> Result<Self, CryptoMaterialError> { let num_of_public_keys = public_keys.len(); let num_of_private_keys = private_keys.len(); if threshold == 0 || num_of_private_keys == 0 || num_of_public_keys < threshold as usize { Err(CryptoMaterialError::ValidationError) } else if num_of_private_keys > MAX_NUM_OF_KEYS || num_of_public_keys > MAX_NUM_OF_KEYS || (index as usize) >= num_of_public_keys { Err(CryptoMaterialError::WrongLengthError) } else { for (i, private_key) in private_keys.iter().enumerate() { let public_key_idx = (index as usize) + i; let public_key = &public_keys[public_key_idx]; let private_key_public_key = private_key.public_key(); if public_key != &private_key_public_key { return Err(CryptoMaterialError::ValidationError); } } Ok(Self { public_keys, threshold, private_keys, index, }) } } /// Generate `shards` MultiEd25519SignatureShard for test pub fn generate<R>(rng: &mut R, shards: usize, threshold: u8) -> Result<Vec<Self>> where R: ::rand::RngCore + ::rand::CryptoRng, { ensure!( threshold as usize <= shards, "threshold should less than shards" ); let private_keys = (0..shards) .map(|_i| Ed25519PrivateKey::generate(rng)) .collect::<Vec<_>>(); let public_keys = private_keys .iter() .map(|private_key| private_key.public_key()) .collect::<Vec<_>>(); private_keys .into_iter() .enumerate() .map(|(idx, private_key)| { Self::new(public_keys.clone(), threshold, private_key, idx as u8) .map_err(anyhow::Error::new) }) .collect() } pub fn public_key(&self) -> MultiEd25519PublicKey { MultiEd25519PublicKey::new(self.public_keys.clone(), self.threshold) .expect("New MultiEd25519PublicKey should success.") } pub fn private_keys(&self) -> &[Ed25519PrivateKey] { self.private_keys.as_slice() } pub fn threshold(&self) -> u8 { self.threshold } pub fn index(&self) -> u8 { self.index } pub fn len(&self) -> usize { self.private_keys.len() } pub fn is_empty(&self) -> bool { self.private_keys.is_empty() } pub fn sign<T: CryptoHash + Serialize>(&self, message: &T) -> MultiEd25519SignatureShard { let signatures: Vec<(Ed25519Signature, u8)> = self .private_keys .iter() .enumerate() .map(|(i, item)| (item.sign(message), self.index + (i as u8))) .collect(); MultiEd25519SignatureShard::new( MultiEd25519Signature::new(signatures).expect("Init MultiEd25519Signature should ok"), self.threshold, ) } } impl ValidCryptoMaterial for MultiEd25519KeyShard { /// Serialize a MultiEd25519PrivateKeyShard. fn to_bytes(&self) -> Vec<u8> { let mut bytes: Vec<u8> = vec![]; bytes.push(self.public_keys.len() as u8); bytes.push(self.threshold); bytes.push(self.private_keys.len() as u8); bytes.push(self.index); bytes.extend( self.public_keys .iter() .flat_map(ValidCryptoMaterial::to_bytes) .collect::<Vec<u8>>(), ); bytes.extend( self.private_keys .iter() .flat_map(ValidCryptoMaterial::to_bytes) .collect::<Vec<u8>>(), ); bytes } } impl std::fmt::Debug for MultiEd25519KeyShard { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "MultiEd25519PrivateKeyShard(public_keys={}, private_keys={}, threshold={})", self.public_keys.len(), self.private_keys.len(), self.threshold ) } } impl TryFrom<&[u8]> for MultiEd25519KeyShard { type Error = CryptoMaterialError; /// Deserialize an Ed25519PrivateKey. This method will also check for key and threshold validity. fn try_from(bytes: &[u8]) -> Result<MultiEd25519KeyShard, Self::Error> { let bytes_len = bytes.len(); if bytes_len < 4 { return Err(CryptoMaterialError::WrongLengthError); } let public_key_len = bytes[0]; let threshold = bytes[1]; let private_key_len = bytes[2]; let index = bytes[3]; let public_key_bytes_len = public_key_len as usize * ED25519_PUBLIC_KEY_LENGTH; let private_key_bytes_len = private_key_len as usize * ED25519_PRIVATE_KEY_LENGTH; if bytes_len < 4 + public_key_bytes_len + private_key_bytes_len { return Err(CryptoMaterialError::WrongLengthError); } let public_key_bytes = &bytes[4..4 + public_key_bytes_len]; let public_keys: Result<Vec<Ed25519PublicKey>, _> = public_key_bytes .chunks_exact(ED25519_PUBLIC_KEY_LENGTH) .map(Ed25519PublicKey::try_from) .collect(); let private_key_bytes = &bytes[4 + public_key_bytes_len..]; let private_keys: Result<Vec<Ed25519PrivateKey>, _> = private_key_bytes .chunks_exact(ED25519_PRIVATE_KEY_LENGTH) .map(Ed25519PrivateKey::try_from) .collect(); MultiEd25519KeyShard::new_multi(public_keys?, threshold, private_keys?, index) } } impl MultiEd25519SignatureShard { /// This method will also sort signatures based on index. pub fn new(signature: MultiEd25519Signature, threshold: u8) -> Self { Self { signature, threshold, } } pub fn merge(shards: Vec<Self>) -> Result<Self> { if shards.is_empty() { bail!("MultiEd25519SignatureShard shards is empty"); } let threshold = shards[0].threshold; let mut signatures = vec![]; for shard in shards { if shard.threshold != threshold { bail!("MultiEd25519SignatureShard shards threshold not same.") } signatures.extend(shard.signatures()); } Ok(Self::new( MultiEd25519Signature::new(signatures)?, threshold, )) } pub fn threshold(&self) -> u8 { self.threshold } pub fn is_enough(&self) -> bool { self.signature.signatures().len() >= self.threshold as usize } /// Getter signatures and index. pub fn signatures(&self) -> Vec<(Ed25519Signature, u8)> { self.into() } /// Getter bitmap. pub fn bitmap(&self) -> &[u8; BITMAP_NUM_OF_BYTES] { self.signature.bitmap() } /// Serialize a MultiEd25519SignatureShard pub fn to_bytes(&self) -> Vec<u8> { let mut bytes: Vec<u8> = self.signature.to_bytes(); bytes.push(self.threshold); bytes } pub fn verify<T: CryptoHash + Serialize>( &self, message: &T, public_key: &MultiEd25519PublicKey, ) -> Result<()> { let mut bytes = <T as CryptoHash>::Hasher::seed().to_vec(); scs::serialize_into(&mut bytes, &message) .map_err(|_| CryptoMaterialError::SerializationError)?; self.verify_arbitrary_msg(&bytes, public_key) } /// Checks that `self` is valid for an arbitrary &[u8] `message` using `public_key`. /// Outside of this crate, this particular function should only be used for native signature /// verification in Move. fn verify_arbitrary_msg( &self, message: &[u8], public_key: &MultiEd25519PublicKey, ) -> Result<()> { ensure!( self.threshold == *public_key.threshold(), "public_key and signature threshold mismatch." ); let bitmap = *self.bitmap(); match bitmap_last_set_bit(bitmap) { Some(last_bit) if last_bit as usize <= public_key.length() => (), _ => { return Err(anyhow!( "{}", CryptoMaterialError::BitVecError("Signature index is out of range".to_string()) )) } }; let mut bitmap_index = 0; let signatures = self.signature.signatures(); // TODO use deterministic batch verification when gets available. for sig in signatures { while !bitmap_get_bit(bitmap, bitmap_index) { bitmap_index += 1; } sig.verify_arbitrary_msg(message, &public_key.public_keys()[bitmap_index])?; bitmap_index += 1; } Ok(()) } } impl Into<Vec<(Ed25519Signature, u8)>> for &MultiEd25519SignatureShard { fn into(self) -> Vec<(Ed25519Signature, u8)> { let signatures = self.signature.signatures(); let bitmap = *self.signature.bitmap(); let mut result = vec![]; let mut bitmap_index = 0; for sig in signatures { while !bitmap_get_bit(bitmap, bitmap_index) { bitmap_index += 1; } result.push((sig.clone(), (bitmap_index as u8))); bitmap_index += 1; } result } } impl Into<MultiEd25519Signature> for MultiEd25519SignatureShard { fn into(self) -> MultiEd25519Signature { self.signature } } impl TryFrom<Vec<MultiEd25519SignatureShard>> for MultiEd25519SignatureShard { type Error = anyhow::Error; fn try_from(value: Vec<MultiEd25519SignatureShard>) -> Result<Self, Self::Error> { MultiEd25519SignatureShard::merge(value) } } #[allow(clippy::derive_hash_xor_eq)] impl std::hash::Hash for MultiEd25519SignatureShard { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let encoded_signature = self.to_bytes(); state.write(&encoded_signature); } } impl fmt::Display for MultiEd25519SignatureShard { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", hex::encode(&self.to_bytes()[..])) } } impl fmt::Debug for MultiEd25519SignatureShard { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "MultiEd25519SignatureShard({})", self) } } // Helper method to get the input's bit at index. fn bitmap_get_bit(input: [u8; BITMAP_NUM_OF_BYTES], index: usize) -> bool { let bucket = index / 8; // It's always invoked with index < 32, thus there is no need to check range. let bucket_pos = index - (bucket * 8); (input[bucket] & (128 >> bucket_pos as u8)) != 0 } // Find the last set bit. fn bitmap_last_set_bit(input: [u8; BITMAP_NUM_OF_BYTES]) -> Option<u8> { input .iter() .rev() .enumerate() .find(|(_, byte)| byte != &&0u8) .map(|(i, byte)| (8 * (BITMAP_NUM_OF_BYTES - i) - byte.trailing_zeros() as usize - 1) as u8) } #[cfg(test)] mod tests { use super::*; use crate::test_utils::{TestLibraCrypto, TEST_SEED}; use crate::ValidCryptoMaterialStringExt; use once_cell::sync::Lazy; use rand::prelude::*; fn generate_shards(n: usize, threshold: u8) -> Vec<MultiEd25519KeyShard> { let mut rng = StdRng::from_seed(TEST_SEED); MultiEd25519KeyShard::generate(&mut rng, n, threshold).unwrap() } static MESSAGE: Lazy<TestLibraCrypto> = Lazy::new(|| TestLibraCrypto("Test Message".to_string())); fn message() -> &'static TestLibraCrypto { &MESSAGE } #[test] pub fn test_to_string_by_read_seed() { let mut seed_rng = rand::rngs::OsRng; let seed_buf: [u8; 32] = seed_rng.gen(); let mut rng = StdRng::from_seed(seed_buf); let shards = MultiEd25519KeyShard::generate(&mut rng, 3, 2).unwrap(); for shard in shards { let hex_str = shard.to_encoded_string().unwrap(); let shard2 = MultiEd25519KeyShard::from_encoded_string(hex_str.as_str()).unwrap(); assert_eq!(shard, shard2); assert!(shard.to_encoded_string().is_ok()); // println!( // "index: {}\npublic_key:\n{} \nimport_key:\n{}\n", // shard.index, // shard.public_key().to_encoded_string().unwrap(), // shard.to_encoded_string().unwrap(), // ) } } #[test] pub fn test_multi_private_key_shard_serialize() { let shards = generate_shards(3, 2); for shard in shards { let bytes = shard.to_bytes(); let shard2 = MultiEd25519KeyShard::try_from(bytes.as_slice()).unwrap(); assert_eq!(shard, shard2) } } #[test] pub fn test_shard_sign_and_verify() { let shards = generate_shards(3, 2); let msg = message(); let signatures = shards .iter() .map(|shard| shard.sign(msg)) .collect::<Vec<_>>(); let public_key = shards[0].public_key(); for signature in signatures.as_slice() { assert!( signature.verify(msg, &public_key).is_ok(), "verify msg by signature {:?} fail.", signature ); assert!(!signature.is_enough()); } let signature2of3 = MultiEd25519SignatureShard::merge(signatures[..2].to_vec()).unwrap(); assert!(signature2of3.is_enough()); let multi_signature: MultiEd25519Signature = signature2of3.into(); multi_signature.verify(msg, &public_key).unwrap(); } }
33.4197
108
0.596783
5d4dbebd8a2c915d5943a6a42316e08569e3022c
11,229
use crate::codec::{BackendMessage, BackendMessages, FrontendMessage, PostgresCodec}; use crate::copy_in::CopyInReceiver; use crate::error::DbError; use crate::maybe_tls_stream::MaybeTlsStream; use crate::{AsyncMessage, Error, Notification}; use actix_utils::mpsc; use bytes::BytesMut; use fallible_iterator::FallibleIterator; use futures::{ready, Sink, Stream, StreamExt}; use log::trace; use postgres_protocol::message::backend::Message; use postgres_protocol::message::frontend; use std::collections::{HashMap, VecDeque}; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_util::codec::Framed; pub enum RequestMessages { Single(FrontendMessage), CopyIn(CopyInReceiver), } pub struct Request { pub messages: RequestMessages, pub sender: mpsc::Sender<BackendMessages>, } pub struct Response { sender: mpsc::Sender<BackendMessages>, } #[derive(PartialEq, Debug)] enum State { Active, Terminating, Closing, } /// A connection to a PostgreSQL database. /// /// This is one half of what is returned when a new connection is established. It performs the actual IO with the /// server, and should generally be spawned off onto an executor to run in the background. /// /// `Connection` implements `Future`, and only resolves when the connection is closed, either because a fatal error has /// occurred, or because its associated `Client` has dropped and all outstanding work has completed. #[must_use = "futures do nothing unless polled"] pub struct Connection<S, T> { stream: Framed<MaybeTlsStream<S, T>, PostgresCodec>, parameters: HashMap<String, String>, receiver: mpsc::Receiver<Request>, pending_request: Option<RequestMessages>, pending_response: Option<BackendMessage>, responses: VecDeque<Response>, state: State, } impl<S, T> Connection<S, T> where S: AsyncRead + AsyncWrite + Unpin, T: AsyncRead + AsyncWrite + Unpin, { pub(crate) fn new( stream: Framed<MaybeTlsStream<S, T>, PostgresCodec>, parameters: HashMap<String, String>, receiver: mpsc::Receiver<Request>, ) -> Connection<S, T> { Connection { stream, parameters, receiver, pending_request: None, pending_response: None, responses: VecDeque::new(), state: State::Active, } } fn poll_response( &mut self, cx: &mut Context<'_>, ) -> Poll<Option<Result<BackendMessage, Error>>> { if let Some(message) = self.pending_response.take() { trace!("retrying pending response"); return Poll::Ready(Some(Ok(message))); } Pin::new(&mut self.stream) .poll_next(cx) .map(|o| o.map(|r| r.map_err(Error::io))) } fn poll_read(&mut self, cx: &mut Context<'_>) -> Result<Option<AsyncMessage>, Error> { if self.state != State::Active { trace!("poll_read: done"); return Ok(None); } loop { let message = match self.poll_response(cx)? { Poll::Ready(Some(message)) => message, Poll::Ready(None) => return Err(Error::closed()), Poll::Pending => { trace!("poll_read: waiting on response"); return Ok(None); } }; let (mut messages, request_complete) = match message { BackendMessage::Async(Message::NoticeResponse(body)) => { let error = DbError::parse(&mut body.fields()).map_err(Error::parse)?; return Ok(Some(AsyncMessage::Notice(error))); } BackendMessage::Async(Message::NotificationResponse(body)) => { let notification = Notification { process_id: body.process_id(), channel: body.channel().map_err(Error::parse)?.to_string(), payload: body.message().map_err(Error::parse)?.to_string(), }; return Ok(Some(AsyncMessage::Notification(notification))); } BackendMessage::Async(Message::ParameterStatus(body)) => { self.parameters.insert( body.name().map_err(Error::parse)?.to_string(), body.value().map_err(Error::parse)?.to_string(), ); continue; } BackendMessage::Async(_) => unreachable!(), BackendMessage::Normal { messages, request_complete, } => (messages, request_complete), }; let response = match self.responses.pop_front() { Some(response) => response, None => match messages.next().map_err(Error::parse)? { Some(Message::ErrorResponse(error)) => return Err(Error::db(error)), _ => return Err(Error::unexpected_message()), }, }; let _ = response.sender.send(messages); if !request_complete { self.responses.push_front(response); } } } fn poll_request(&mut self, cx: &mut Context<'_>) -> Poll<Option<RequestMessages>> { if let Some(messages) = self.pending_request.take() { trace!("retrying pending request"); return Poll::Ready(Some(messages)); } match self.receiver.poll_next_unpin(cx) { Poll::Ready(Some(request)) => { trace!("polled new request"); self.responses.push_back(Response { sender: request.sender, }); Poll::Ready(Some(request.messages)) } Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, } } fn poll_write(&mut self, cx: &mut Context<'_>) -> Result<bool, Error> { loop { if self.state == State::Closing { trace!("poll_write: done"); return Ok(false); } if let Poll::Pending = Pin::new(&mut self.stream) .poll_ready(cx) .map_err(Error::io)? { trace!("poll_write: waiting on socket"); return Ok(false); } let request = match self.poll_request(cx) { Poll::Ready(Some(request)) => request, Poll::Ready(None) if self.responses.is_empty() && self.state == State::Active => { trace!("poll_write: at eof, terminating"); self.state = State::Terminating; let mut request = BytesMut::new(); frontend::terminate(&mut request); RequestMessages::Single(FrontendMessage::Raw(request.freeze())) } Poll::Ready(None) => { trace!( "poll_write: at eof, pending responses {}", self.responses.len() ); return Ok(true); } Poll::Pending => { trace!("poll_write: waiting on request"); return Ok(true); } }; match request { RequestMessages::Single(request) => { Pin::new(&mut self.stream) .start_send(request) .map_err(Error::io)?; if self.state == State::Terminating { trace!("poll_write: sent eof, closing"); self.state = State::Closing; } } RequestMessages::CopyIn(mut receiver) => { let message = match receiver.poll_next_unpin(cx) { Poll::Ready(Some(message)) => message, Poll::Ready(None) => { trace!("poll_write: finished copy_in request"); continue; } Poll::Pending => { trace!("poll_write: waiting on copy_in stream"); self.pending_request = Some(RequestMessages::CopyIn(receiver)); return Ok(true); } }; Pin::new(&mut self.stream) .start_send(message) .map_err(Error::io)?; self.pending_request = Some(RequestMessages::CopyIn(receiver)); } } } } fn poll_flush(&mut self, cx: &mut Context<'_>) -> Result<(), Error> { match Pin::new(&mut self.stream) .poll_flush(cx) .map_err(Error::io)? { Poll::Ready(()) => trace!("poll_flush: flushed"), Poll::Pending => trace!("poll_flush: waiting on socket"), } Ok(()) } fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Error>> { if self.state != State::Closing { return Poll::Pending; } match Pin::new(&mut self.stream) .poll_close(cx) .map_err(Error::io)? { Poll::Ready(()) => { trace!("poll_shutdown: complete"); Poll::Ready(Ok(())) } Poll::Pending => { trace!("poll_shutdown: waiting on socket"); Poll::Pending } } } /// Returns the value of a runtime parameter for this connection. pub fn parameter(&self, name: &str) -> Option<&str> { self.parameters.get(name).map(|s| &**s) } /// Polls for asynchronous messages from the server. /// /// The server can send notices as well as notifications asynchronously to the client. Applications that wish to /// examine those messages should use this method to drive the connection rather than its `Future` implementation. pub fn poll_message( &mut self, cx: &mut Context<'_>, ) -> Poll<Option<Result<AsyncMessage, Error>>> { let message = self.poll_read(cx)?; let want_flush = self.poll_write(cx)?; if want_flush { self.poll_flush(cx)?; } match message { Some(message) => Poll::Ready(Some(Ok(message))), None => match self.poll_shutdown(cx) { Poll::Ready(Ok(())) => Poll::Ready(None), Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))), Poll::Pending => Poll::Pending, }, } } } impl<S, T> Future for Connection<S, T> where S: AsyncRead + AsyncWrite + Unpin, T: AsyncRead + AsyncWrite + Unpin, { type Output = Result<(), Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> { while let Some(_) = ready!(self.poll_message(cx)?) {} Poll::Ready(Ok(())) } }
35.990385
119
0.51928
ac43e8cb1885be378fdaff5d8bcc5fbe72e41c5c
23,190
#[doc = "Register `CH2CONF1` reader"] pub struct R(crate::R<CH2CONF1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CH2CONF1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CH2CONF1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CH2CONF1_SPEC>) -> Self { R(reader) } } #[doc = "Register `CH2CONF1` writer"] pub struct W(crate::W<CH2CONF1_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CH2CONF1_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<CH2CONF1_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<CH2CONF1_SPEC>) -> Self { W(writer) } } #[doc = "Field `TX_START_CH2` reader - Set this bit to start sending data for channel2."] pub struct TX_START_CH2_R(crate::FieldReader<bool, bool>); impl TX_START_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { TX_START_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TX_START_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `TX_START_CH2` writer - Set this bit to start sending data for channel2."] pub struct TX_START_CH2_W<'a> { w: &'a mut W, } impl<'a> TX_START_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } #[doc = "Field `RX_EN_CH2` reader - Set this bit to enbale receving data for channel2."] pub struct RX_EN_CH2_R(crate::FieldReader<bool, bool>); impl RX_EN_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { RX_EN_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RX_EN_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RX_EN_CH2` writer - Set this bit to enbale receving data for channel2."] pub struct RX_EN_CH2_W<'a> { w: &'a mut W, } impl<'a> RX_EN_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "Field `MEM_WR_RST_CH2` reader - Set this bit to reset write ram address for channel2 by receiver access."] pub struct MEM_WR_RST_CH2_R(crate::FieldReader<bool, bool>); impl MEM_WR_RST_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MEM_WR_RST_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MEM_WR_RST_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MEM_WR_RST_CH2` writer - Set this bit to reset write ram address for channel2 by receiver access."] pub struct MEM_WR_RST_CH2_W<'a> { w: &'a mut W, } impl<'a> MEM_WR_RST_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2); self.w } } #[doc = "Field `MEM_RD_RST_CH2` reader - Set this bit to reset read ram address for channel2 by transmitter access."] pub struct MEM_RD_RST_CH2_R(crate::FieldReader<bool, bool>); impl MEM_RD_RST_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MEM_RD_RST_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MEM_RD_RST_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MEM_RD_RST_CH2` writer - Set this bit to reset read ram address for channel2 by transmitter access."] pub struct MEM_RD_RST_CH2_W<'a> { w: &'a mut W, } impl<'a> MEM_RD_RST_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3); self.w } } #[doc = "Field `APB_MEM_RST_CH2` reader - Set this bit to reset W/R ram address for channel2 by apb fifo access"] pub struct APB_MEM_RST_CH2_R(crate::FieldReader<bool, bool>); impl APB_MEM_RST_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { APB_MEM_RST_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for APB_MEM_RST_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `APB_MEM_RST_CH2` writer - Set this bit to reset W/R ram address for channel2 by apb fifo access"] pub struct APB_MEM_RST_CH2_W<'a> { w: &'a mut W, } impl<'a> APB_MEM_RST_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4); self.w } } #[doc = "Field `MEM_OWNER_CH2` reader - This is the mark of channel2's ram usage right.1'b1:receiver uses the ram 0:transmitter uses the ram"] pub struct MEM_OWNER_CH2_R(crate::FieldReader<bool, bool>); impl MEM_OWNER_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MEM_OWNER_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for MEM_OWNER_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MEM_OWNER_CH2` writer - This is the mark of channel2's ram usage right.1'b1:receiver uses the ram 0:transmitter uses the ram"] pub struct MEM_OWNER_CH2_W<'a> { w: &'a mut W, } impl<'a> MEM_OWNER_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5); self.w } } #[doc = "Field `TX_CONTI_MODE_CH2` reader - Set this bit to continue sending from the first data to the last data in channel2."] pub struct TX_CONTI_MODE_CH2_R(crate::FieldReader<bool, bool>); impl TX_CONTI_MODE_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { TX_CONTI_MODE_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TX_CONTI_MODE_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `TX_CONTI_MODE_CH2` writer - Set this bit to continue sending from the first data to the last data in channel2."] pub struct TX_CONTI_MODE_CH2_W<'a> { w: &'a mut W, } impl<'a> TX_CONTI_MODE_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u32 & 0x01) << 6); self.w } } #[doc = "Field `RX_FILTER_EN_CH2` reader - This is the receive filter enable bit for channel2."] pub struct RX_FILTER_EN_CH2_R(crate::FieldReader<bool, bool>); impl RX_FILTER_EN_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { RX_FILTER_EN_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RX_FILTER_EN_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RX_FILTER_EN_CH2` writer - This is the receive filter enable bit for channel2."] pub struct RX_FILTER_EN_CH2_W<'a> { w: &'a mut W, } impl<'a> RX_FILTER_EN_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7); self.w } } #[doc = "Field `RX_FILTER_THRES_CH2` reader - in receive mode channel2 ignore input pulse when the pulse width is smaller then this value."] pub struct RX_FILTER_THRES_CH2_R(crate::FieldReader<u8, u8>); impl RX_FILTER_THRES_CH2_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { RX_FILTER_THRES_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RX_FILTER_THRES_CH2_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RX_FILTER_THRES_CH2` writer - in receive mode channel2 ignore input pulse when the pulse width is smaller then this value."] pub struct RX_FILTER_THRES_CH2_W<'a> { w: &'a mut W, } impl<'a> RX_FILTER_THRES_CH2_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 & !(0xff << 8)) | ((value as u32 & 0xff) << 8); self.w } } #[doc = "Field `REF_CNT_RST_CH2` reader - This bit is used to reset divider in channel2."] pub struct REF_CNT_RST_CH2_R(crate::FieldReader<bool, bool>); impl REF_CNT_RST_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { REF_CNT_RST_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for REF_CNT_RST_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `REF_CNT_RST_CH2` writer - This bit is used to reset divider in channel2."] pub struct REF_CNT_RST_CH2_W<'a> { w: &'a mut W, } impl<'a> REF_CNT_RST_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16); self.w } } #[doc = "Field `REF_ALWAYS_ON_CH2` reader - This bit is used to select base clock. 1'b1:clk_apb 1'b0:clk_ref"] pub struct REF_ALWAYS_ON_CH2_R(crate::FieldReader<bool, bool>); impl REF_ALWAYS_ON_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { REF_ALWAYS_ON_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for REF_ALWAYS_ON_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `REF_ALWAYS_ON_CH2` writer - This bit is used to select base clock. 1'b1:clk_apb 1'b0:clk_ref"] pub struct REF_ALWAYS_ON_CH2_W<'a> { w: &'a mut W, } impl<'a> REF_ALWAYS_ON_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17); self.w } } #[doc = "Field `IDLE_OUT_LV_CH2` reader - This bit configures the output signal's level for channel2 in IDLE state."] pub struct IDLE_OUT_LV_CH2_R(crate::FieldReader<bool, bool>); impl IDLE_OUT_LV_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { IDLE_OUT_LV_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for IDLE_OUT_LV_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `IDLE_OUT_LV_CH2` writer - This bit configures the output signal's level for channel2 in IDLE state."] pub struct IDLE_OUT_LV_CH2_W<'a> { w: &'a mut W, } impl<'a> IDLE_OUT_LV_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | ((value as u32 & 0x01) << 18); self.w } } #[doc = "Field `IDLE_OUT_EN_CH2` reader - This is the output enable control bit for channel2 in IDLE state."] pub struct IDLE_OUT_EN_CH2_R(crate::FieldReader<bool, bool>); impl IDLE_OUT_EN_CH2_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { IDLE_OUT_EN_CH2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for IDLE_OUT_EN_CH2_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `IDLE_OUT_EN_CH2` writer - This is the output enable control bit for channel2 in IDLE state."] pub struct IDLE_OUT_EN_CH2_W<'a> { w: &'a mut W, } impl<'a> IDLE_OUT_EN_CH2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | ((value as u32 & 0x01) << 19); self.w } } impl R { #[doc = "Bit 0 - Set this bit to start sending data for channel2."] #[inline(always)] pub fn tx_start_ch2(&self) -> TX_START_CH2_R { TX_START_CH2_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Set this bit to enbale receving data for channel2."] #[inline(always)] pub fn rx_en_ch2(&self) -> RX_EN_CH2_R { RX_EN_CH2_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Set this bit to reset write ram address for channel2 by receiver access."] #[inline(always)] pub fn mem_wr_rst_ch2(&self) -> MEM_WR_RST_CH2_R { MEM_WR_RST_CH2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Set this bit to reset read ram address for channel2 by transmitter access."] #[inline(always)] pub fn mem_rd_rst_ch2(&self) -> MEM_RD_RST_CH2_R { MEM_RD_RST_CH2_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Set this bit to reset W/R ram address for channel2 by apb fifo access"] #[inline(always)] pub fn apb_mem_rst_ch2(&self) -> APB_MEM_RST_CH2_R { APB_MEM_RST_CH2_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - This is the mark of channel2's ram usage right.1'b1:receiver uses the ram 0:transmitter uses the ram"] #[inline(always)] pub fn mem_owner_ch2(&self) -> MEM_OWNER_CH2_R { MEM_OWNER_CH2_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Set this bit to continue sending from the first data to the last data in channel2."] #[inline(always)] pub fn tx_conti_mode_ch2(&self) -> TX_CONTI_MODE_CH2_R { TX_CONTI_MODE_CH2_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - This is the receive filter enable bit for channel2."] #[inline(always)] pub fn rx_filter_en_ch2(&self) -> RX_FILTER_EN_CH2_R { RX_FILTER_EN_CH2_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bits 8:15 - in receive mode channel2 ignore input pulse when the pulse width is smaller then this value."] #[inline(always)] pub fn rx_filter_thres_ch2(&self) -> RX_FILTER_THRES_CH2_R { RX_FILTER_THRES_CH2_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bit 16 - This bit is used to reset divider in channel2."] #[inline(always)] pub fn ref_cnt_rst_ch2(&self) -> REF_CNT_RST_CH2_R { REF_CNT_RST_CH2_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - This bit is used to select base clock. 1'b1:clk_apb 1'b0:clk_ref"] #[inline(always)] pub fn ref_always_on_ch2(&self) -> REF_ALWAYS_ON_CH2_R { REF_ALWAYS_ON_CH2_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - This bit configures the output signal's level for channel2 in IDLE state."] #[inline(always)] pub fn idle_out_lv_ch2(&self) -> IDLE_OUT_LV_CH2_R { IDLE_OUT_LV_CH2_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - This is the output enable control bit for channel2 in IDLE state."] #[inline(always)] pub fn idle_out_en_ch2(&self) -> IDLE_OUT_EN_CH2_R { IDLE_OUT_EN_CH2_R::new(((self.bits >> 19) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Set this bit to start sending data for channel2."] #[inline(always)] pub fn tx_start_ch2(&mut self) -> TX_START_CH2_W { TX_START_CH2_W { w: self } } #[doc = "Bit 1 - Set this bit to enbale receving data for channel2."] #[inline(always)] pub fn rx_en_ch2(&mut self) -> RX_EN_CH2_W { RX_EN_CH2_W { w: self } } #[doc = "Bit 2 - Set this bit to reset write ram address for channel2 by receiver access."] #[inline(always)] pub fn mem_wr_rst_ch2(&mut self) -> MEM_WR_RST_CH2_W { MEM_WR_RST_CH2_W { w: self } } #[doc = "Bit 3 - Set this bit to reset read ram address for channel2 by transmitter access."] #[inline(always)] pub fn mem_rd_rst_ch2(&mut self) -> MEM_RD_RST_CH2_W { MEM_RD_RST_CH2_W { w: self } } #[doc = "Bit 4 - Set this bit to reset W/R ram address for channel2 by apb fifo access"] #[inline(always)] pub fn apb_mem_rst_ch2(&mut self) -> APB_MEM_RST_CH2_W { APB_MEM_RST_CH2_W { w: self } } #[doc = "Bit 5 - This is the mark of channel2's ram usage right.1'b1:receiver uses the ram 0:transmitter uses the ram"] #[inline(always)] pub fn mem_owner_ch2(&mut self) -> MEM_OWNER_CH2_W { MEM_OWNER_CH2_W { w: self } } #[doc = "Bit 6 - Set this bit to continue sending from the first data to the last data in channel2."] #[inline(always)] pub fn tx_conti_mode_ch2(&mut self) -> TX_CONTI_MODE_CH2_W { TX_CONTI_MODE_CH2_W { w: self } } #[doc = "Bit 7 - This is the receive filter enable bit for channel2."] #[inline(always)] pub fn rx_filter_en_ch2(&mut self) -> RX_FILTER_EN_CH2_W { RX_FILTER_EN_CH2_W { w: self } } #[doc = "Bits 8:15 - in receive mode channel2 ignore input pulse when the pulse width is smaller then this value."] #[inline(always)] pub fn rx_filter_thres_ch2(&mut self) -> RX_FILTER_THRES_CH2_W { RX_FILTER_THRES_CH2_W { w: self } } #[doc = "Bit 16 - This bit is used to reset divider in channel2."] #[inline(always)] pub fn ref_cnt_rst_ch2(&mut self) -> REF_CNT_RST_CH2_W { REF_CNT_RST_CH2_W { w: self } } #[doc = "Bit 17 - This bit is used to select base clock. 1'b1:clk_apb 1'b0:clk_ref"] #[inline(always)] pub fn ref_always_on_ch2(&mut self) -> REF_ALWAYS_ON_CH2_W { REF_ALWAYS_ON_CH2_W { w: self } } #[doc = "Bit 18 - This bit configures the output signal's level for channel2 in IDLE state."] #[inline(always)] pub fn idle_out_lv_ch2(&mut self) -> IDLE_OUT_LV_CH2_W { IDLE_OUT_LV_CH2_W { w: self } } #[doc = "Bit 19 - This is the output enable control bit for channel2 in IDLE state."] #[inline(always)] pub fn idle_out_en_ch2(&mut self) -> IDLE_OUT_EN_CH2_W { IDLE_OUT_EN_CH2_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 = "\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 [ch2conf1](index.html) module"] pub struct CH2CONF1_SPEC; impl crate::RegisterSpec for CH2CONF1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [ch2conf1::R](R) reader structure"] impl crate::Readable for CH2CONF1_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [ch2conf1::W](W) writer structure"] impl crate::Writable for CH2CONF1_SPEC { type Writer = W; } #[doc = "`reset()` method sets CH2CONF1 to value 0x0f20"] impl crate::Resettable for CH2CONF1_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0x0f20 } }
34.715569
389
0.612937
4868a99dd55dcbe77d7375e6dd3ae32f4f0fda71
238
use std::collections::BTreeMap; use crate::song::{ clips::{audio::AudioClip, ClipIndex}, io::{AudioSink, AudioSource}, }; pub struct AudioTrack { source: AudioSource, sink: AudioSink, clips: BTreeMap<ClipIndex, AudioClip>, }
17
40
0.701681
f4a5da1fe36fa8d0f6d2c9465c9f56f65f6b5784
98,538
use std::collections::VecDeque; use std::rc::Rc; use rustc_data_structures::binary_search_util; use rustc_data_structures::frozen::Frozen; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::graph::scc::Sccs; use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_hir::CRATE_HIR_ID; use rustc_index::vec::IndexVec; use rustc_infer::infer::canonical::QueryOutlivesConstraint; use rustc_infer::infer::region_constraints::{GenericKind, VarInfos, VerifyBound}; use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin}; use rustc_middle::mir::{ Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements, ConstraintCategory, Local, Location, ReturnConstraint, }; use rustc_middle::traits::ObligationCause; use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable}; use rustc_span::Span; use crate::{ constraints::{ graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet, }, diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo}, member_constraints::{MemberConstraintSet, NllMemberConstraintIndex}, nll::{PoloniusOutput, ToRegionVid}, region_infer::reverse_sccs::ReverseSccGraph, region_infer::values::{ LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues, ToElementIndex, }, type_check::{free_region_relations::UniversalRegionRelations, Locations}, universal_regions::UniversalRegions, }; mod dump_mir; mod graphviz; mod opaque_types; mod reverse_sccs; pub mod values; pub struct RegionInferenceContext<'tcx> { /// Contains the definition for every region variable. Region /// variables are identified by their index (`RegionVid`). The /// definition contains information about where the region came /// from as well as its final inferred value. definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>, /// The liveness constraints added to each region. For most /// regions, these start out empty and steadily grow, though for /// each universally quantified region R they start out containing /// the entire CFG and `end(R)`. liveness_constraints: LivenessValues<RegionVid>, /// The outlives constraints computed by the type-check. constraints: Frozen<OutlivesConstraintSet<'tcx>>, /// The constraint-set, but in graph form, making it easy to traverse /// the constraints adjacent to a particular region. Used to construct /// the SCC (see `constraint_sccs`) and for error reporting. constraint_graph: Frozen<NormalConstraintGraph>, /// The SCC computed from `constraints` and the constraint /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to /// compute the values of each region. constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>, /// Reverse of the SCC constraint graph -- i.e., an edge `A -> B` exists if /// `B: A`. This is used to compute the universal regions that are required /// to outlive a given SCC. Computed lazily. rev_scc_graph: Option<Rc<ReverseSccGraph>>, /// The "R0 member of [R1..Rn]" constraints, indexed by SCC. member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>, /// Records the member constraints that we applied to each scc. /// This is useful for error reporting. Once constraint /// propagation is done, this vector is sorted according to /// `member_region_scc`. member_constraints_applied: Vec<AppliedMemberConstraint>, /// Map closure bounds to a `Span` that should be used for error reporting. closure_bounds_mapping: FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>, /// Map universe indexes to information on why we created it. universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>, /// Contains the minimum universe of any variable within the same /// SCC. We will ensure that no SCC contains values that are not /// visible from this index. scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>, /// Contains a "representative" from each SCC. This will be the /// minimal RegionVid belonging to that universe. It is used as a /// kind of hacky way to manage checking outlives relationships, /// since we can 'canonicalize' each region to the representative /// of its SCC and be sure that -- if they have the same repr -- /// they *must* be equal (though not having the same repr does not /// mean they are unequal). scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>, /// The final inferred values of the region variables; we compute /// one value per SCC. To get the value for any given *region*, /// you first find which scc it is a part of. scc_values: RegionValues<ConstraintSccIndex>, /// Type constraints that we check after solving. type_tests: Vec<TypeTest<'tcx>>, /// Information about the universally quantified regions in scope /// on this function. universal_regions: Rc<UniversalRegions<'tcx>>, /// Information about how the universally quantified regions in /// scope on this function relate to one another. universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>, } /// Each time that `apply_member_constraint` is successful, it appends /// one of these structs to the `member_constraints_applied` field. /// This is used in error reporting to trace out what happened. /// /// The way that `apply_member_constraint` works is that it effectively /// adds a new lower bound to the SCC it is analyzing: so you wind up /// with `'R: 'O` where `'R` is the pick-region and `'O` is the /// minimal viable option. #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] pub(crate) struct AppliedMemberConstraint { /// The SCC that was affected. (The "member region".) /// /// The vector if `AppliedMemberConstraint` elements is kept sorted /// by this field. pub(crate) member_region_scc: ConstraintSccIndex, /// The "best option" that `apply_member_constraint` found -- this was /// added as an "ad-hoc" lower-bound to `member_region_scc`. pub(crate) min_choice: ty::RegionVid, /// The "member constraint index" -- we can find out details about /// the constraint from /// `set.member_constraints[member_constraint_index]`. pub(crate) member_constraint_index: NllMemberConstraintIndex, } pub(crate) struct RegionDefinition<'tcx> { /// What kind of variable is this -- a free region? existential /// variable? etc. (See the `NllRegionVariableOrigin` for more /// info.) pub(crate) origin: NllRegionVariableOrigin, /// Which universe is this region variable defined in? This is /// most often `ty::UniverseIndex::ROOT`, but when we encounter /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create /// the variable for `'a` in a fresh universe that extends ROOT. pub(crate) universe: ty::UniverseIndex, /// If this is 'static or an early-bound region, then this is /// `Some(X)` where `X` is the name of the region. pub(crate) external_name: Option<ty::Region<'tcx>>, } /// N.B., the variants in `Cause` are intentionally ordered. Lower /// values are preferred when it comes to error messages. Do not /// reorder willy nilly. #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] pub(crate) enum Cause { /// point inserted because Local was live at the given Location LiveVar(Local, Location), /// point inserted because Local was dropped at the given Location DropVar(Local, Location), } /// A "type test" corresponds to an outlives constraint between a type /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are /// translated from the `Verify` region constraints in the ordinary /// inference context. /// /// These sorts of constraints are handled differently than ordinary /// constraints, at least at present. During type checking, the /// `InferCtxt::process_registered_region_obligations` method will /// attempt to convert a type test like `T: 'x` into an ordinary /// outlives constraint when possible (for example, `&'a T: 'b` will /// be converted into `'a: 'b` and registered as a `Constraint`). /// /// In some cases, however, there are outlives relationships that are /// not converted into a region constraint, but rather into one of /// these "type tests". The distinction is that a type test does not /// influence the inference result, but instead just examines the /// values that we ultimately inferred for each region variable and /// checks that they meet certain extra criteria. If not, an error /// can be issued. /// /// One reason for this is that these type tests typically boil down /// to a check like `'a: 'x` where `'a` is a universally quantified /// region -- and therefore not one whose value is really meant to be /// *inferred*, precisely (this is not always the case: one can have a /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an /// inference variable). Another reason is that these type tests can /// involve *disjunction* -- that is, they can be satisfied in more /// than one way. /// /// For more information about this translation, see /// `InferCtxt::process_registered_region_obligations` and /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`. #[derive(Clone, Debug)] pub struct TypeTest<'tcx> { /// The type `T` that must outlive the region. pub generic_kind: GenericKind<'tcx>, /// The region `'x` that the type must outlive. pub lower_bound: RegionVid, /// Where did this constraint arise and why? pub locations: Locations, /// A test which, if met by the region `'x`, proves that this type /// constraint is satisfied. pub verify_bound: VerifyBound<'tcx>, } /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure /// environment). If we can't, it is an error. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum RegionRelationCheckResult { Ok, Propagated, Error, } #[derive(Clone, PartialEq, Eq, Debug)] enum Trace<'tcx> { StartRegion, FromOutlivesConstraint(OutlivesConstraint<'tcx>), NotVisited, } impl<'tcx> RegionInferenceContext<'tcx> { /// Creates a new region inference context with a total of /// `num_region_variables` valid inference variables; the first N /// of those will be constant regions representing the free /// regions defined in `universal_regions`. /// /// The `outlives_constraints` and `type_tests` are an initial set /// of constraints produced by the MIR type check. pub(crate) fn new( var_infos: VarInfos, universal_regions: Rc<UniversalRegions<'tcx>>, placeholder_indices: Rc<PlaceholderIndices>, universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>, outlives_constraints: OutlivesConstraintSet<'tcx>, member_constraints_in: MemberConstraintSet<'tcx, RegionVid>, closure_bounds_mapping: FxHashMap< Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>, >, universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>, type_tests: Vec<TypeTest<'tcx>>, liveness_constraints: LivenessValues<RegionVid>, elements: &Rc<RegionValueElements>, ) -> Self { // Create a RegionDefinition for each inference variable. let definitions: IndexVec<_, _> = var_infos .into_iter() .map(|info| RegionDefinition::new(info.universe, info.origin)) .collect(); let constraints = Frozen::freeze(outlives_constraints); let constraint_graph = Frozen::freeze(constraints.graph(definitions.len())); let fr_static = universal_regions.fr_static; let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static)); let mut scc_values = RegionValues::new(elements, universal_regions.len(), &placeholder_indices); for region in liveness_constraints.rows() { let scc = constraint_sccs.scc(region); scc_values.merge_liveness(scc, region, &liveness_constraints); } let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions); let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions); let member_constraints = Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r))); let mut result = Self { definitions, liveness_constraints, constraints, constraint_graph, constraint_sccs, rev_scc_graph: None, member_constraints, member_constraints_applied: Vec::new(), closure_bounds_mapping, universe_causes, scc_universes, scc_representatives, scc_values, type_tests, universal_regions, universal_region_relations, }; result.init_free_and_bound_regions(); result } /// Each SCC is the combination of many region variables which /// have been equated. Therefore, we can associate a universe with /// each SCC which is minimum of all the universes of its /// constituent regions -- this is because whatever value the SCC /// takes on must be a value that each of the regions within the /// SCC could have as well. This implies that the SCC must have /// the minimum, or narrowest, universe. fn compute_scc_universes( constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>, definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>, ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> { let num_sccs = constraint_sccs.num_sccs(); let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs); debug!("compute_scc_universes()"); // For each region R in universe U, ensure that the universe for the SCC // that contains R is "no bigger" than U. This effectively sets the universe // for each SCC to be the minimum of the regions within. for (region_vid, region_definition) in definitions.iter_enumerated() { let scc = constraint_sccs.scc(region_vid); let scc_universe = &mut scc_universes[scc]; let scc_min = std::cmp::min(region_definition.universe, *scc_universe); if scc_min != *scc_universe { *scc_universe = scc_min; debug!( "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \ because it contains {region_vid:?} in {region_universe:?}", scc = scc, scc_min = scc_min, region_vid = region_vid, region_universe = region_definition.universe, ); } } // Walk each SCC `A` and `B` such that `A: B` // and ensure that universe(A) can see universe(B). // // This serves to enforce the 'empty/placeholder' hierarchy // (described in more detail on `RegionKind`): // // ``` // static -----+ // | | // empty(U0) placeholder(U1) // | / // empty(U1) // ``` // // In particular, imagine we have variables R0 in U0 and R1 // created in U1, and constraints like this; // // ``` // R1: !1 // R1 outlives the placeholder in U1 // R1: R0 // R1 outlives R0 // ``` // // Here, we wish for R1 to be `'static`, because it // cannot outlive `placeholder(U1)` and `empty(U0)` any other way. // // Thanks to this loop, what happens is that the `R1: R0` // constraint lowers the universe of `R1` to `U0`, which in turn // means that the `R1: !1` constraint will (later) cause // `R1` to become `'static`. for scc_a in constraint_sccs.all_sccs() { for &scc_b in constraint_sccs.successors(scc_a) { let scc_universe_a = scc_universes[scc_a]; let scc_universe_b = scc_universes[scc_b]; let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b); if scc_universe_a != scc_universe_min { scc_universes[scc_a] = scc_universe_min; debug!( "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \ because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}", scc_a = scc_a, scc_b = scc_b, scc_universe_min = scc_universe_min, scc_universe_b = scc_universe_b ); } } } debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes); scc_universes } /// For each SCC, we compute a unique `RegionVid` (in fact, the /// minimal one that belongs to the SCC). See /// `scc_representatives` field of `RegionInferenceContext` for /// more details. fn compute_scc_representatives( constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>, definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>, ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> { let num_sccs = constraints_scc.num_sccs(); let next_region_vid = definitions.next_index(); let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs); for region_vid in definitions.indices() { let scc = constraints_scc.scc(region_vid); let prev_min = scc_representatives[scc]; scc_representatives[scc] = region_vid.min(prev_min); } scc_representatives } /// Initializes the region variables for each universally /// quantified region (lifetime parameter). The first N variables /// always correspond to the regions appearing in the function /// signature (both named and anonymous) and where-clauses. This /// function iterates over those regions and initializes them with /// minimum values. /// /// For example: /// /// fn foo<'a, 'b>(..) where 'a: 'b /// /// would initialize two variables like so: /// /// R0 = { CFG, R0 } // 'a /// R1 = { CFG, R0, R1 } // 'b /// /// Here, R0 represents `'a`, and it contains (a) the entire CFG /// and (b) any universally quantified regions that it outlives, /// which in this case is just itself. R1 (`'b`) in contrast also /// outlives `'a` and hence contains R0 and R1. fn init_free_and_bound_regions(&mut self) { // Update the names (if any) for (external_name, variable) in self.universal_regions.named_universal_regions() { debug!( "init_universal_regions: region {:?} has external name {:?}", variable, external_name ); self.definitions[variable].external_name = Some(external_name); } for variable in self.definitions.indices() { let scc = self.constraint_sccs.scc(variable); match self.definitions[variable].origin { NllRegionVariableOrigin::FreeRegion => { // For each free, universally quantified region X: // Add all nodes in the CFG to liveness constraints self.liveness_constraints.add_all_points(variable); self.scc_values.add_all_points(scc); // Add `end(X)` into the set for X. self.scc_values.add_element(scc, variable); } NllRegionVariableOrigin::Placeholder(placeholder) => { // Each placeholder region is only visible from // its universe `ui` and its extensions. So we // can't just add it into `scc` unless the // universe of the scc can name this region. let scc_universe = self.scc_universes[scc]; if scc_universe.can_name(placeholder.universe) { self.scc_values.add_element(scc, placeholder); } else { debug!( "init_free_and_bound_regions: placeholder {:?} is \ not compatible with universe {:?} of its SCC {:?}", placeholder, scc_universe, scc, ); self.add_incompatible_universe(scc); } } NllRegionVariableOrigin::RootEmptyRegion | NllRegionVariableOrigin::Existential { .. } => { // For existential, regions, nothing to do. } } } } /// Returns an iterator over all the region indices. pub fn regions(&self) -> impl Iterator<Item = RegionVid> + '_ { self.definitions.indices() } /// Given a universal region in scope on the MIR, returns the /// corresponding index. /// /// (Panics if `r` is not a registered universal region.) pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid { self.universal_regions.to_region_vid(r) } /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`. crate fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut rustc_errors::DiagnosticBuilder<'_>) { self.universal_regions.annotate(tcx, err) } /// Returns `true` if the region `r` contains the point `p`. /// /// Panics if called before `solve()` executes, crate fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool { let scc = self.constraint_sccs.scc(r.to_region_vid()); self.scc_values.contains(scc, p) } /// Returns access to the value of `r` for debugging purposes. crate fn region_value_str(&self, r: RegionVid) -> String { let scc = self.constraint_sccs.scc(r.to_region_vid()); self.scc_values.region_value_str(scc) } /// Returns access to the value of `r` for debugging purposes. crate fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex { let scc = self.constraint_sccs.scc(r.to_region_vid()); self.scc_universes[scc] } /// Once region solving has completed, this function will return /// the member constraints that were applied to the value of a given /// region `r`. See `AppliedMemberConstraint`. pub(crate) fn applied_member_constraints( &self, r: impl ToRegionVid, ) -> &[AppliedMemberConstraint] { let scc = self.constraint_sccs.scc(r.to_region_vid()); binary_search_util::binary_search_slice( &self.member_constraints_applied, |applied| applied.member_region_scc, &scc, ) } /// Performs region inference and report errors if we see any /// unsatisfiable constraints. If this is a closure, returns the /// region requirements to propagate to our creator, if any. #[instrument(skip(self, infcx, body, polonius_output), level = "debug")] pub(super) fn solve( &mut self, infcx: &InferCtxt<'_, 'tcx>, body: &Body<'tcx>, polonius_output: Option<Rc<PoloniusOutput>>, ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) { let mir_def_id = body.source.def_id(); self.propagate_constraints(body); let mut errors_buffer = RegionErrors::new(); // If this is a closure, we can propagate unsatisfied // `outlives_requirements` to our creator, so create a vector // to store those. Otherwise, we'll pass in `None` to the // functions below, which will trigger them to report errors // eagerly. let mut outlives_requirements = infcx.tcx.is_closure(mir_def_id).then(Vec::new); self.check_type_tests(infcx, body, outlives_requirements.as_mut(), &mut errors_buffer); // In Polonius mode, the errors about missing universal region relations are in the output // and need to be emitted or propagated. Otherwise, we need to check whether the // constraints were too strong, and if so, emit or propagate those errors. if infcx.tcx.sess.opts.debugging_opts.polonius { self.check_polonius_subset_errors( body, outlives_requirements.as_mut(), &mut errors_buffer, polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"), ); } else { self.check_universal_regions(body, outlives_requirements.as_mut(), &mut errors_buffer); } if errors_buffer.is_empty() { self.check_member_constraints(infcx, &mut errors_buffer); } let outlives_requirements = outlives_requirements.unwrap_or_default(); if outlives_requirements.is_empty() { (None, errors_buffer) } else { let num_external_vids = self.universal_regions.num_global_and_external_regions(); ( Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }), errors_buffer, ) } } /// Propagate the region constraints: this will grow the values /// for each region variable until all the constraints are /// satisfied. Note that some values may grow **too** large to be /// feasible, but we check this later. #[instrument(skip(self, _body), level = "debug")] fn propagate_constraints(&mut self, _body: &Body<'tcx>) { debug!("constraints={:#?}", { let mut constraints: Vec<_> = self.constraints.outlives().iter().collect(); constraints.sort(); constraints .into_iter() .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub))) .collect::<Vec<_>>() }); // To propagate constraints, we walk the DAG induced by the // SCC. For each SCC, we visit its successors and compute // their values, then we union all those values to get our // own. let constraint_sccs = self.constraint_sccs.clone(); for scc in constraint_sccs.all_sccs() { self.compute_value_for_scc(scc); } // Sort the applied member constraints so we can binary search // through them later. self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc); } /// Computes the value of the SCC `scc_a`, which has not yet been /// computed, by unioning the values of its successors. /// Assumes that all successors have been computed already /// (which is assured by iterating over SCCs in dependency order). #[instrument(skip(self), level = "debug")] fn compute_value_for_scc(&mut self, scc_a: ConstraintSccIndex) { let constraint_sccs = self.constraint_sccs.clone(); // Walk each SCC `B` such that `A: B`... for &scc_b in constraint_sccs.successors(scc_a) { debug!(?scc_b); // ...and add elements from `B` into `A`. One complication // arises because of universes: If `B` contains something // that `A` cannot name, then `A` can only contain `B` if // it outlives static. if self.universe_compatible(scc_b, scc_a) { // `A` can name everything that is in `B`, so just // merge the bits. self.scc_values.add_region(scc_a, scc_b); } else { self.add_incompatible_universe(scc_a); } } // Now take member constraints into account. let member_constraints = self.member_constraints.clone(); for m_c_i in member_constraints.indices(scc_a) { self.apply_member_constraint(scc_a, m_c_i, member_constraints.choice_regions(m_c_i)); } debug!(value = ?self.scc_values.region_value_str(scc_a)); } /// Invoked for each `R0 member of [R1..Rn]` constraint. /// /// `scc` is the SCC containing R0, and `choice_regions` are the /// `R1..Rn` regions -- they are always known to be universal /// regions (and if that's not true, we just don't attempt to /// enforce the constraint). /// /// The current value of `scc` at the time the method is invoked /// is considered a *lower bound*. If possible, we will modify /// the constraint to set it equal to one of the option regions. /// If we make any changes, returns true, else false. #[instrument(skip(self, member_constraint_index), level = "debug")] fn apply_member_constraint( &mut self, scc: ConstraintSccIndex, member_constraint_index: NllMemberConstraintIndex, choice_regions: &[ty::RegionVid], ) -> bool { // Create a mutable vector of the options. We'll try to winnow // them down. let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec(); // Convert to the SCC representative: sometimes we have inference // variables in the member constraint that wind up equated with // universal regions. The scc representative is the minimal numbered // one from the corresponding scc so it will be the universal region // if one exists. for c_r in &mut choice_regions { let scc = self.constraint_sccs.scc(*c_r); *c_r = self.scc_representatives[scc]; } // The 'member region' in a member constraint is part of the // hidden type, which must be in the root universe. Therefore, // it cannot have any placeholders in its value. assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT); debug_assert!( self.scc_values.placeholders_contained_in(scc).next().is_none(), "scc {:?} in a member constraint has placeholder value: {:?}", scc, self.scc_values.region_value_str(scc), ); // The existing value for `scc` is a lower-bound. This will // consist of some set `{P} + {LB}` of points `{P}` and // lower-bound free regions `{LB}`. As each choice region `O` // is a free region, it will outlive the points. But we can // only consider the option `O` if `O: LB`. choice_regions.retain(|&o_r| { self.scc_values .universal_regions_outlived_by(scc) .all(|lb| self.universal_region_relations.outlives(o_r, lb)) }); debug!(?choice_regions, "after lb"); // Now find all the *upper bounds* -- that is, each UB is a // free region that must outlive the member region `R0` (`UB: // R0`). Therefore, we need only keep an option `O` if `UB: O` // for all UB. let rev_scc_graph = self.reverse_scc_graph(); let universal_region_relations = &self.universal_region_relations; for ub in rev_scc_graph.upper_bounds(scc) { debug!(?ub); choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r)); } debug!(?choice_regions, "after ub"); // If we ruled everything out, we're done. if choice_regions.is_empty() { return false; } // Otherwise, we need to find the minimum remaining choice, if // any, and take that. debug!("choice_regions remaining are {:#?}", choice_regions); let min = |r1: ty::RegionVid, r2: ty::RegionVid| -> Option<ty::RegionVid> { let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2); let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1); match (r1_outlives_r2, r2_outlives_r1) { (true, true) => Some(r1.min(r2)), (true, false) => Some(r2), (false, true) => Some(r1), (false, false) => None, } }; let mut min_choice = choice_regions[0]; for &other_option in &choice_regions[1..] { debug!(?min_choice, ?other_option,); match min(min_choice, other_option) { Some(m) => min_choice = m, None => { debug!(?min_choice, ?other_option, "incomparable; no min choice",); return false; } } } let min_choice_scc = self.constraint_sccs.scc(min_choice); debug!(?min_choice, ?min_choice_scc); if self.scc_values.add_region(scc, min_choice_scc) { self.member_constraints_applied.push(AppliedMemberConstraint { member_region_scc: scc, min_choice, member_constraint_index, }); true } else { false } } /// Returns `true` if all the elements in the value of `scc_b` are nameable /// in `scc_a`. Used during constraint propagation, and only once /// the value of `scc_b` has been computed. fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool { let universe_a = self.scc_universes[scc_a]; // Quick check: if scc_b's declared universe is a subset of // scc_a's declared univese (typically, both are ROOT), then // it cannot contain any problematic universe elements. if universe_a.can_name(self.scc_universes[scc_b]) { return true; } // Otherwise, we have to iterate over the universe elements in // B's value, and check whether all of them are nameable // from universe_a self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe)) } /// Extend `scc` so that it can outlive some placeholder region /// from a universe it can't name; at present, the only way for /// this to be true is if `scc` outlives `'static`. This is /// actually stricter than necessary: ideally, we'd support bounds /// like `for<'a: 'b`>` that might then allow us to approximate /// `'a` with `'b` and not `'static`. But it will have to do for /// now. fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) { debug!("add_incompatible_universe(scc={:?})", scc); let fr_static = self.universal_regions.fr_static; self.scc_values.add_all_points(scc); self.scc_values.add_element(scc, fr_static); } /// Once regions have been propagated, this method is used to see /// whether the "type tests" produced by typeck were satisfied; /// type tests encode type-outlives relationships like `T: /// 'a`. See `TypeTest` for more details. fn check_type_tests( &self, infcx: &InferCtxt<'_, 'tcx>, body: &Body<'tcx>, mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>, errors_buffer: &mut RegionErrors<'tcx>, ) { let tcx = infcx.tcx; // Sometimes we register equivalent type-tests that would // result in basically the exact same error being reported to // the user. Avoid that. let mut deduplicate_errors = FxHashSet::default(); for type_test in &self.type_tests { debug!("check_type_test: {:?}", type_test); let generic_ty = type_test.generic_kind.to_ty(tcx); if self.eval_verify_bound( tcx, body, generic_ty, type_test.lower_bound, &type_test.verify_bound, ) { continue; } if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements { if self.try_promote_type_test( infcx, body, type_test, propagated_outlives_requirements, ) { continue; } } // Type-test failed. Report the error. let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind); // Skip duplicate-ish errors. if deduplicate_errors.insert(( erased_generic_kind, type_test.lower_bound, type_test.locations, )) { debug!( "check_type_test: reporting error for erased_generic_kind={:?}, \ lower_bound_region={:?}, \ type_test.locations={:?}", erased_generic_kind, type_test.lower_bound, type_test.locations, ); errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() }); } } } /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot /// prove to be satisfied. If this is a closure, we will attempt to /// "promote" this type-test into our `ClosureRegionRequirements` and /// hence pass it up the creator. To do this, we have to phrase the /// type-test in terms of external free regions, as local free /// regions are not nameable by the closure's creator. /// /// Promotion works as follows: we first check that the type `T` /// contains only regions that the creator knows about. If this is /// true, then -- as a consequence -- we know that all regions in /// the type `T` are free regions that outlive the closure body. If /// false, then promotion fails. /// /// Once we've promoted T, we have to "promote" `'X` to some region /// that is "external" to the closure. Generally speaking, a region /// may be the union of some points in the closure body as well as /// various free lifetimes. We can ignore the points in the closure /// body: if the type T can be expressed in terms of external regions, /// we know it outlives the points in the closure body. That /// just leaves the free regions. /// /// The idea then is to lower the `T: 'X` constraint into multiple /// bounds -- e.g., if `'X` is the union of two free lifetimes, /// `'1` and `'2`, then we would create `T: '1` and `T: '2`. fn try_promote_type_test( &self, infcx: &InferCtxt<'_, 'tcx>, body: &Body<'tcx>, type_test: &TypeTest<'tcx>, propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>, ) -> bool { let tcx = infcx.tcx; let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ } = type_test; let generic_ty = generic_kind.to_ty(tcx); let subject = match self.try_promote_type_test_subject(infcx, generic_ty) { Some(s) => s, None => return false, }; // For each region outlived by lower_bound find a non-local, // universal region (it may be the same region) and add it to // `ClosureOutlivesRequirement`. let r_scc = self.constraint_sccs.scc(*lower_bound); for ur in self.scc_values.universal_regions_outlived_by(r_scc) { // Check whether we can already prove that the "subject" outlives `ur`. // If so, we don't have to propagate this requirement to our caller. // // To continue the example from the function, if we are trying to promote // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here // we check whether `T: '1` is something we *can* prove. If so, no need // to propagate that requirement. // // This is needed because -- particularly in the case // where `ur` is a local bound -- we are sometimes in a // position to prove things that our caller cannot. See // #53570 for an example. if self.eval_verify_bound(tcx, body, generic_ty, ur, &type_test.verify_bound) { continue; } debug!("try_promote_type_test: ur={:?}", ur); let non_local_ub = self.universal_region_relations.non_local_upper_bounds(&ur); debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub); // This is slightly too conservative. To show T: '1, given `'2: '1` // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to // avoid potential non-determinism we approximate this by requiring // T: '1 and T: '2. for &upper_bound in non_local_ub { debug_assert!(self.universal_regions.is_universal_region(upper_bound)); debug_assert!(!self.universal_regions.is_local_free_region(upper_bound)); let requirement = ClosureOutlivesRequirement { subject, outlived_free_region: upper_bound, blame_span: locations.span(body), category: ConstraintCategory::Boring, }; debug!("try_promote_type_test: pushing {:#?}", requirement); propagated_outlives_requirements.push(requirement); } } true } /// When we promote a type test `T: 'r`, we have to convert the /// type `T` into something we can store in a query result (so /// something allocated for `'tcx`). This is problematic if `ty` /// contains regions. During the course of NLL region checking, we /// will have replaced all of those regions with fresh inference /// variables. To create a test subject, we want to replace those /// inference variables with some region from the closure /// signature -- this is not always possible, so this is a /// fallible process. Presuming we do find a suitable region, we /// will use it's *external name*, which will be a `RegionKind` /// variant that can be used in query responses such as /// `ReEarlyBound`. fn try_promote_type_test_subject( &self, infcx: &InferCtxt<'_, 'tcx>, ty: Ty<'tcx>, ) -> Option<ClosureOutlivesSubject<'tcx>> { let tcx = infcx.tcx; debug!("try_promote_type_test_subject(ty = {:?})", ty); let ty = tcx.fold_regions(ty, &mut false, |r, _depth| { let region_vid = self.to_region_vid(r); // The challenge if this. We have some region variable `r` // whose value is a set of CFG points and universal // regions. We want to find if that set is *equivalent* to // any of the named regions found in the closure. // // To do so, we compute the // `non_local_universal_upper_bound`. This will be a // non-local, universal region that is greater than `r`. // However, it might not be *contained* within `r`, so // then we further check whether this bound is contained // in `r`. If so, we can say that `r` is equivalent to the // bound. // // Let's work through a few examples. For these, imagine // that we have 3 non-local regions (I'll denote them as // `'static`, `'a`, and `'b`, though of course in the code // they would be represented with indices) where: // // - `'static: 'a` // - `'static: 'b` // // First, let's assume that `r` is some existential // variable with an inferred value `{'a, 'static}` (plus // some CFG nodes). In this case, the non-local upper // bound is `'static`, since that outlives `'a`. `'static` // is also a member of `r` and hence we consider `r` // equivalent to `'static` (and replace it with // `'static`). // // Now let's consider the inferred value `{'a, 'b}`. This // means `r` is effectively `'a | 'b`. I'm not sure if // this can come about, actually, but assuming it did, we // would get a non-local upper bound of `'static`. Since // `'static` is not contained in `r`, we would fail to // find an equivalent. let upper_bound = self.non_local_universal_upper_bound(region_vid); if self.region_contains(region_vid, upper_bound) { self.definitions[upper_bound].external_name.unwrap_or(r) } else { // In the case of a failure, use a `ReVar` result. This will // cause the `needs_infer` later on to return `None`. r } }); debug!("try_promote_type_test_subject: folded ty = {:?}", ty); // `needs_infer` will only be true if we failed to promote some region. if ty.needs_infer() { return None; } Some(ClosureOutlivesSubject::Ty(ty)) } /// Given some universal or existential region `r`, finds a /// non-local, universal region `r+` that outlives `r` at entry to (and /// exit from) the closure. In the worst case, this will be /// `'static`. /// /// This is used for two purposes. First, if we are propagated /// some requirement `T: r`, we can use this method to enlarge `r` /// to something we can encode for our creator (which only knows /// about non-local, universal regions). It is also used when /// encoding `T` as part of `try_promote_type_test_subject` (see /// that fn for details). /// /// This is based on the result `'y` of `universal_upper_bound`, /// except that it converts further takes the non-local upper /// bound of `'y`, so that the final result is non-local. fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid { debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r)); let lub = self.universal_upper_bound(r); // Grow further to get smallest universal region known to // creator. let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub); debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub); non_local_lub } /// Returns a universally quantified region that outlives the /// value of `r` (`r` may be existentially or universally /// quantified). /// /// Since `r` is (potentially) an existential region, it has some /// value which may include (a) any number of points in the CFG /// and (b) any number of `end('x)` elements of universally /// quantified regions. To convert this into a single universal /// region we do as follows: /// /// - Ignore the CFG points in `'r`. All universally quantified regions /// include the CFG anyhow. /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding /// a result `'y`. #[instrument(skip(self), level = "debug")] pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid { debug!(r = %self.region_value_str(r)); // Find the smallest universal region that contains all other // universal regions within `region`. let mut lub = self.universal_regions.fr_fn_body; let r_scc = self.constraint_sccs.scc(r); for ur in self.scc_values.universal_regions_outlived_by(r_scc) { lub = self.universal_region_relations.postdom_upper_bound(lub, ur); } debug!(?lub); lub } /// Like `universal_upper_bound`, but returns an approximation more suitable /// for diagnostics. If `r` contains multiple disjoint universal regions /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region. /// This corresponds to picking named regions over unnamed regions /// (e.g. picking early-bound regions over a closure late-bound region). /// /// This means that the returned value may not be a true upper bound, since /// only 'static is known to outlive disjoint universal regions. /// Therefore, this method should only be used in diagnostic code, /// where displaying *some* named universal region is better than /// falling back to 'static. pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid { debug!("approx_universal_upper_bound(r={:?}={})", r, self.region_value_str(r)); // Find the smallest universal region that contains all other // universal regions within `region`. let mut lub = self.universal_regions.fr_fn_body; let r_scc = self.constraint_sccs.scc(r); let static_r = self.universal_regions.fr_static; for ur in self.scc_values.universal_regions_outlived_by(r_scc) { let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur); debug!("approx_universal_upper_bound: ur={:?} lub={:?} new_lub={:?}", ur, lub, new_lub); // The upper bound of two non-static regions is static: this // means we know nothing about the relationship between these // two regions. Pick a 'better' one to use when constructing // a diagnostic if ur != static_r && lub != static_r && new_lub == static_r { // Prefer the region with an `external_name` - this // indicates that the region is early-bound, so working with // it can produce a nicer error. if self.region_definition(ur).external_name.is_some() { lub = ur; } else if self.region_definition(lub).external_name.is_some() { // Leave lub unchanged } else { // If we get here, we don't have any reason to prefer // one region over the other. Just pick the // one with the lower index for now. lub = std::cmp::min(ur, lub); } } else { lub = new_lub; } } debug!("approx_universal_upper_bound: r={:?} lub={:?}", r, lub); lub } /// Tests if `test` is true when applied to `lower_bound` at /// `point`. fn eval_verify_bound( &self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, generic_ty: Ty<'tcx>, lower_bound: RegionVid, verify_bound: &VerifyBound<'tcx>, ) -> bool { debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound); match verify_bound { VerifyBound::IfEq(test_ty, verify_bound1) => { self.eval_if_eq(tcx, body, generic_ty, lower_bound, test_ty, verify_bound1) } VerifyBound::IsEmpty => { let lower_bound_scc = self.constraint_sccs.scc(lower_bound); self.scc_values.elements_contained_in(lower_bound_scc).next().is_none() } VerifyBound::OutlivedBy(r) => { let r_vid = self.to_region_vid(r); self.eval_outlives(r_vid, lower_bound) } VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| { self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound) }), VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| { self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound) }), } } fn eval_if_eq( &self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, generic_ty: Ty<'tcx>, lower_bound: RegionVid, test_ty: Ty<'tcx>, verify_bound: &VerifyBound<'tcx>, ) -> bool { let generic_ty_normalized = self.normalize_to_scc_representatives(tcx, generic_ty); let test_ty_normalized = self.normalize_to_scc_representatives(tcx, test_ty); if generic_ty_normalized == test_ty_normalized { self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound) } else { false } } /// This is a conservative normalization procedure. It takes every /// free region in `value` and replaces it with the /// "representative" of its SCC (see `scc_representatives` field). /// We are guaranteed that if two values normalize to the same /// thing, then they are equal; this is a conservative check in /// that they could still be equal even if they normalize to /// different results. (For example, there might be two regions /// with the same value that are not in the same SCC). /// /// N.B., this is not an ideal approach and I would like to revisit /// it. However, it works pretty well in practice. In particular, /// this is needed to deal with projection outlives bounds like /// /// ```text /// <T as Foo<'0>>::Item: '1 /// ``` /// /// In particular, this routine winds up being important when /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the /// environment. In this case, if we can show that `'0 == 'a`, /// and that `'b: '1`, then we know that the clause is /// satisfied. In such cases, particularly due to limitations of /// the trait solver =), we usually wind up with a where-clause like /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as /// a constraint, and thus ensures that they are in the same SCC. /// /// So why can't we do a more correct routine? Well, we could /// *almost* use the `relate_tys` code, but the way it is /// currently setup it creates inference variables to deal with /// higher-ranked things and so forth, and right now the inference /// context is not permitted to make more inference variables. So /// we use this kind of hacky solution. fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T where T: TypeFoldable<'tcx>, { tcx.fold_regions(value, &mut false, |r, _db| { let vid = self.to_region_vid(r); let scc = self.constraint_sccs.scc(vid); let repr = self.scc_representatives[scc]; tcx.mk_region(ty::ReVar(repr)) }) } // Evaluate whether `sup_region == sub_region`. fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool { self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1) } // Evaluate whether `sup_region: sub_region`. #[instrument(skip(self), level = "debug")] fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool { debug!( "eval_outlives: sup_region's value = {:?} universal={:?}", self.region_value_str(sup_region), self.universal_regions.is_universal_region(sup_region), ); debug!( "eval_outlives: sub_region's value = {:?} universal={:?}", self.region_value_str(sub_region), self.universal_regions.is_universal_region(sub_region), ); let sub_region_scc = self.constraint_sccs.scc(sub_region); let sup_region_scc = self.constraint_sccs.scc(sup_region); // Both the `sub_region` and `sup_region` consist of the union // of some number of universal regions (along with the union // of various points in the CFG; ignore those points for // now). Therefore, the sup-region outlives the sub-region if, // for each universal region R1 in the sub-region, there // exists some region R2 in the sup-region that outlives R1. let universal_outlives = self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| { self.scc_values .universal_regions_outlived_by(sup_region_scc) .any(|r2| self.universal_region_relations.outlives(r2, r1)) }); if !universal_outlives { return false; } // Now we have to compare all the points in the sub region and make // sure they exist in the sup region. if self.universal_regions.is_universal_region(sup_region) { // Micro-opt: universal regions contain all points. return true; } self.scc_values.contains_points(sup_region_scc, sub_region_scc) } /// Once regions have been propagated, this method is used to see /// whether any of the constraints were too strong. In particular, /// we want to check for a case where a universally quantified /// region exceeded its bounds. Consider: /// /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x } /// /// In this case, returning `x` requires `&'a u32 <: &'b u32` /// and hence we establish (transitively) a constraint that /// `'a: 'b`. The `propagate_constraints` code above will /// therefore add `end('a)` into the region for `'b` -- but we /// have no evidence that `'b` outlives `'a`, so we want to report /// an error. /// /// If `propagated_outlives_requirements` is `Some`, then we will /// push unsatisfied obligations into there. Otherwise, we'll /// report them as errors. fn check_universal_regions( &self, body: &Body<'tcx>, mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>, errors_buffer: &mut RegionErrors<'tcx>, ) { for (fr, fr_definition) in self.definitions.iter_enumerated() { match fr_definition.origin { NllRegionVariableOrigin::FreeRegion => { // Go through each of the universal regions `fr` and check that // they did not grow too large, accumulating any requirements // for our caller into the `outlives_requirements` vector. self.check_universal_region( body, fr, &mut propagated_outlives_requirements, errors_buffer, ); } NllRegionVariableOrigin::Placeholder(placeholder) => { self.check_bound_universal_region(fr, placeholder, errors_buffer); } NllRegionVariableOrigin::RootEmptyRegion | NllRegionVariableOrigin::Existential { .. } => { // nothing to check here } } } } /// Checks if Polonius has found any unexpected free region relations. /// /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a` /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`. /// /// More details can be found in this blog post by Niko: /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/> /// /// In the canonical example /// /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x } /// /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a /// constraint that `'a: 'b`. It is an error that we have no evidence that this /// constraint holds. /// /// If `propagated_outlives_requirements` is `Some`, then we will /// push unsatisfied obligations into there. Otherwise, we'll /// report them as errors. fn check_polonius_subset_errors( &self, body: &Body<'tcx>, mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>, errors_buffer: &mut RegionErrors<'tcx>, polonius_output: Rc<PoloniusOutput>, ) { debug!( "check_polonius_subset_errors: {} subset_errors", polonius_output.subset_errors.len() ); // Similarly to `check_universal_regions`: a free region relation, which was not explicitly // declared ("known") was found by Polonius, so emit an error, or propagate the // requirements for our caller into the `propagated_outlives_requirements` vector. // // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with // the rest of the NLL infrastructure. The "subset origin" is the "longer free region", // and the "superset origin" is the outlived "shorter free region". // // Note: Polonius will produce a subset error at every point where the unexpected // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful // for diagnostics in the future, e.g. to point more precisely at the key locations // requiring this constraint to hold. However, the error and diagnostics code downstream // expects that these errors are not duplicated (and that they are in a certain order). // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or // anonymous lifetimes for example, could give these names differently, while others like // the outlives suggestions or the debug output from `#[rustc_regions]` would be // duplicated. The polonius subset errors are deduplicated here, while keeping the // CFG-location ordering. let mut subset_errors: Vec<_> = polonius_output .subset_errors .iter() .flat_map(|(_location, subset_errors)| subset_errors.iter()) .collect(); subset_errors.sort(); subset_errors.dedup(); for (longer_fr, shorter_fr) in subset_errors.into_iter() { debug!( "check_polonius_subset_errors: subset_error longer_fr={:?},\ shorter_fr={:?}", longer_fr, shorter_fr ); let propagated = self.try_propagate_universal_region_error( *longer_fr, *shorter_fr, body, &mut propagated_outlives_requirements, ); if propagated == RegionRelationCheckResult::Error { errors_buffer.push(RegionErrorKind::RegionError { longer_fr: *longer_fr, shorter_fr: *shorter_fr, fr_origin: NllRegionVariableOrigin::FreeRegion, is_reported: true, }); } } // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has // a more complete picture on how to separate this responsibility. for (fr, fr_definition) in self.definitions.iter_enumerated() { match fr_definition.origin { NllRegionVariableOrigin::FreeRegion => { // handled by polonius above } NllRegionVariableOrigin::Placeholder(placeholder) => { self.check_bound_universal_region(fr, placeholder, errors_buffer); } NllRegionVariableOrigin::RootEmptyRegion | NllRegionVariableOrigin::Existential { .. } => { // nothing to check here } } } } /// Checks the final value for the free region `fr` to see if it /// grew too large. In particular, examine what `end(X)` points /// wound up in `fr`'s final value; for each `end(X)` where `X != /// fr`, we want to check that `fr: X`. If not, that's either an /// error, or something we have to propagate to our creator. /// /// Things that are to be propagated are accumulated into the /// `outlives_requirements` vector. #[instrument( skip(self, body, propagated_outlives_requirements, errors_buffer), level = "debug" )] fn check_universal_region( &self, body: &Body<'tcx>, longer_fr: RegionVid, propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>, errors_buffer: &mut RegionErrors<'tcx>, ) { let longer_fr_scc = self.constraint_sccs.scc(longer_fr); // Because this free region must be in the ROOT universe, we // know it cannot contain any bound universes. assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT); debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none()); // Only check all of the relations for the main representative of each // SCC, otherwise just check that we outlive said representative. This // reduces the number of redundant relations propagated out of // closures. // Note that the representative will be a universal region if there is // one in this SCC, so we will always check the representative here. let representative = self.scc_representatives[longer_fr_scc]; if representative != longer_fr { if let RegionRelationCheckResult::Error = self.check_universal_region_relation( longer_fr, representative, body, propagated_outlives_requirements, ) { errors_buffer.push(RegionErrorKind::RegionError { longer_fr, shorter_fr: representative, fr_origin: NllRegionVariableOrigin::FreeRegion, is_reported: true, }); } return; } // Find every region `o` such that `fr: o` // (because `fr` includes `end(o)`). let mut error_reported = false; for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) { if let RegionRelationCheckResult::Error = self.check_universal_region_relation( longer_fr, shorter_fr, body, propagated_outlives_requirements, ) { // We only report the first region error. Subsequent errors are hidden so as // not to overwhelm the user, but we do record them so as to potentially print // better diagnostics elsewhere... errors_buffer.push(RegionErrorKind::RegionError { longer_fr, shorter_fr, fr_origin: NllRegionVariableOrigin::FreeRegion, is_reported: !error_reported, }); error_reported = true; } } } /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate /// the constraint outward (e.g. to a closure environment), but if that fails, there is an /// error. fn check_universal_region_relation( &self, longer_fr: RegionVid, shorter_fr: RegionVid, body: &Body<'tcx>, propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>, ) -> RegionRelationCheckResult { // If it is known that `fr: o`, carry on. if self.universal_region_relations.outlives(longer_fr, shorter_fr) { RegionRelationCheckResult::Ok } else { // If we are not in a context where we can't propagate errors, or we // could not shrink `fr` to something smaller, then just report an // error. // // Note: in this case, we use the unapproximated regions to report the // error. This gives better error messages in some cases. self.try_propagate_universal_region_error( longer_fr, shorter_fr, body, propagated_outlives_requirements, ) } } /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's /// creator. If we cannot, then the caller should report an error to the user. fn try_propagate_universal_region_error( &self, longer_fr: RegionVid, shorter_fr: RegionVid, body: &Body<'tcx>, propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>, ) -> RegionRelationCheckResult { if let Some(propagated_outlives_requirements) = propagated_outlives_requirements { // Shrink `longer_fr` until we find a non-local region (if we do). // We'll call it `fr-` -- it's ever so slightly smaller than // `longer_fr`. if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr) { debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus); let blame_span_category = self.find_outlives_blame_span( body, longer_fr, NllRegionVariableOrigin::FreeRegion, shorter_fr, ); // Grow `shorter_fr` until we find some non-local regions. (We // always will.) We'll call them `shorter_fr+` -- they're ever // so slightly larger than `shorter_fr`. let shorter_fr_plus = self.universal_region_relations.non_local_upper_bounds(&shorter_fr); debug!( "try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus ); for &&fr in &shorter_fr_plus { // Push the constraint `fr-: shorter_fr+` propagated_outlives_requirements.push(ClosureOutlivesRequirement { subject: ClosureOutlivesSubject::Region(fr_minus), outlived_free_region: fr, blame_span: blame_span_category.1.span, category: blame_span_category.0, }); } return RegionRelationCheckResult::Propagated; } } RegionRelationCheckResult::Error } fn check_bound_universal_region( &self, longer_fr: RegionVid, placeholder: ty::PlaceholderRegion, errors_buffer: &mut RegionErrors<'tcx>, ) { debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,); let longer_fr_scc = self.constraint_sccs.scc(longer_fr); debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,); // If we have some bound universal region `'a`, then the only // elements it can contain is itself -- we don't know anything // else about it! let error_element = match { self.scc_values.elements_contained_in(longer_fr_scc).find(|element| match element { RegionElement::Location(_) => true, RegionElement::RootUniversalRegion(_) => true, RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1, }) } { Some(v) => v, None => return, }; debug!("check_bound_universal_region: error_element = {:?}", error_element); // Find the region that introduced this `error_element`. errors_buffer.push(RegionErrorKind::BoundUniversalRegionError { longer_fr, error_element, placeholder, }); } fn check_member_constraints( &self, infcx: &InferCtxt<'_, 'tcx>, errors_buffer: &mut RegionErrors<'tcx>, ) { let member_constraints = self.member_constraints.clone(); for m_c_i in member_constraints.all_indices() { debug!("check_member_constraint(m_c_i={:?})", m_c_i); let m_c = &member_constraints[m_c_i]; let member_region_vid = m_c.member_region_vid; debug!( "check_member_constraint: member_region_vid={:?} with value {}", member_region_vid, self.region_value_str(member_region_vid), ); let choice_regions = member_constraints.choice_regions(m_c_i); debug!("check_member_constraint: choice_regions={:?}", choice_regions); // Did the member region wind up equal to any of the option regions? if let Some(o) = choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid)) { debug!("check_member_constraint: evaluated as equal to {:?}", o); continue; } // If not, report an error. let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid)); errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion { span: m_c.definition_span, hidden_ty: m_c.hidden_ty, member_region, }); } } /// We have a constraint `fr1: fr2` that is not satisfied, where /// `fr2` represents some universal region. Here, `r` is some /// region where we know that `fr1: r` and this function has the /// job of determining whether `r` is "to blame" for the fact that /// `fr1: fr2` is required. /// /// This is true under two conditions: /// /// - `r == fr2` /// - `fr2` is `'static` and `r` is some placeholder in a universe /// that cannot be named by `fr1`; in that case, we will require /// that `fr1: 'static` because it is the only way to `fr1: r` to /// be satisfied. (See `add_incompatible_universe`.) crate fn provides_universal_region( &self, r: RegionVid, fr1: RegionVid, fr2: RegionVid, ) -> bool { debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2); let result = { r == fr2 || { fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r) } }; debug!("provides_universal_region: result = {:?}", result); result } /// If `r2` represents a placeholder region, then this returns /// `true` if `r1` cannot name that placeholder in its /// value; otherwise, returns `false`. crate fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool { debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2); match self.definitions[r2].origin { NllRegionVariableOrigin::Placeholder(placeholder) => { let universe1 = self.definitions[r1].universe; debug!( "cannot_name_value_of: universe1={:?} placeholder={:?}", universe1, placeholder ); universe1.cannot_name(placeholder.universe) } NllRegionVariableOrigin::RootEmptyRegion | NllRegionVariableOrigin::FreeRegion | NllRegionVariableOrigin::Existential { .. } => false, } } crate fn retrieve_closure_constraint_info( &self, body: &Body<'tcx>, constraint: &OutlivesConstraint<'tcx>, ) -> BlameConstraint<'tcx> { let loc = match constraint.locations { Locations::All(span) => { return BlameConstraint { category: constraint.category, from_closure: false, cause: ObligationCause::dummy_with_span(span), variance_info: constraint.variance_info, }; } Locations::Single(loc) => loc, }; let opt_span_category = self.closure_bounds_mapping[&loc].get(&(constraint.sup, constraint.sub)); opt_span_category .map(|&(category, span)| BlameConstraint { category, from_closure: true, cause: ObligationCause::dummy_with_span(span), variance_info: constraint.variance_info, }) .unwrap_or(BlameConstraint { category: constraint.category, from_closure: false, cause: ObligationCause::dummy_with_span(body.source_info(loc).span), variance_info: constraint.variance_info, }) } /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`. crate fn find_outlives_blame_span( &self, body: &Body<'tcx>, fr1: RegionVid, fr1_origin: NllRegionVariableOrigin, fr2: RegionVid, ) -> (ConstraintCategory, ObligationCause<'tcx>) { let BlameConstraint { category, cause, .. } = self.best_blame_constraint(body, fr1, fr1_origin, |r| { self.provides_universal_region(r, fr1, fr2) }); (category, cause) } /// Walks the graph of constraints (where `'a: 'b` is considered /// an edge `'a -> 'b`) to find all paths from `from_region` to /// `to_region`. The paths are accumulated into the vector /// `results`. The paths are stored as a series of /// `ConstraintIndex` values -- in other words, a list of *edges*. /// /// Returns: a series of constraints as well as the region `R` /// that passed the target test. crate fn find_constraint_paths_between_regions( &self, from_region: RegionVid, target_test: impl Fn(RegionVid) -> bool, ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> { let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions); context[from_region] = Trace::StartRegion; // Use a deque so that we do a breadth-first search. We will // stop at the first match, which ought to be the shortest // path (fewest constraints). let mut deque = VecDeque::new(); deque.push_back(from_region); while let Some(r) = deque.pop_front() { debug!( "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}", from_region, r, self.region_value_str(r), ); // Check if we reached the region we were looking for. If so, // we can reconstruct the path that led to it and return it. if target_test(r) { let mut result = vec![]; let mut p = r; loop { match context[p].clone() { Trace::NotVisited => { bug!("found unvisited region {:?} on path to {:?}", p, r) } Trace::FromOutlivesConstraint(c) => { p = c.sup; result.push(c); } Trace::StartRegion => { result.reverse(); return Some((result, r)); } } } } // Otherwise, walk over the outgoing constraints and // enqueue any regions we find, keeping track of how we // reached them. // A constraint like `'r: 'x` can come from our constraint // graph. let fr_static = self.universal_regions.fr_static; let outgoing_edges_from_graph = self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static); // Always inline this closure because it can be hot. let mut handle_constraint = #[inline(always)] |constraint: OutlivesConstraint<'tcx>| { debug_assert_eq!(constraint.sup, r); let sub_region = constraint.sub; if let Trace::NotVisited = context[sub_region] { context[sub_region] = Trace::FromOutlivesConstraint(constraint); deque.push_back(sub_region); } }; // This loop can be hot. for constraint in outgoing_edges_from_graph { handle_constraint(constraint); } // Member constraints can also give rise to `'r: 'x` edges that // were not part of the graph initially, so watch out for those. // (But they are extremely rare; this loop is very cold.) for constraint in self.applied_member_constraints(r) { let p_c = &self.member_constraints[constraint.member_constraint_index]; let constraint = OutlivesConstraint { sup: r, sub: constraint.min_choice, locations: Locations::All(p_c.definition_span), category: ConstraintCategory::OpaqueType, variance_info: ty::VarianceDiagInfo::default(), }; handle_constraint(constraint); } } None } /// Finds some region R such that `fr1: R` and `R` is live at `elem`. #[instrument(skip(self), level = "trace")] crate fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid { trace!(scc = ?self.constraint_sccs.scc(fr1)); trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]); self.find_constraint_paths_between_regions(fr1, |r| { // First look for some `r` such that `fr1: r` and `r` is live at `elem` trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r)); self.liveness_constraints.contains(r, elem) }) .or_else(|| { // If we fail to find that, we may find some `r` such that // `fr1: r` and `r` is a placeholder from some universe // `fr1` cannot name. This would force `fr1` to be // `'static`. self.find_constraint_paths_between_regions(fr1, |r| { self.cannot_name_placeholder(fr1, r) }) }) .or_else(|| { // If we fail to find THAT, it may be that `fr1` is a // placeholder that cannot "fit" into its SCC. In that // case, there should be some `r` where `fr1: r` and `fr1` is a // placeholder that `r` cannot name. We can blame that // edge. // // Remember that if `R1: R2`, then the universe of R1 // must be able to name the universe of R2, because R2 will // be at least `'empty(Universe(R2))`, and `R1` must be at // larger than that. self.find_constraint_paths_between_regions(fr1, |r| { self.cannot_name_placeholder(r, fr1) }) }) .map(|(_path, r)| r) .unwrap() } /// Get the region outlived by `longer_fr` and live at `element`. crate fn region_from_element( &self, longer_fr: RegionVid, element: &RegionElement, ) -> RegionVid { match *element { RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l), RegionElement::RootUniversalRegion(r) => r, RegionElement::PlaceholderRegion(error_placeholder) => self .definitions .iter_enumerated() .find_map(|(r, definition)| match definition.origin { NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r), _ => None, }) .unwrap(), } } /// Get the region definition of `r`. crate fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> { &self.definitions[r] } /// Check if the SCC of `r` contains `upper`. crate fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool { let r_scc = self.constraint_sccs.scc(r); self.scc_values.contains(r_scc, upper) } crate fn universal_regions(&self) -> &UniversalRegions<'tcx> { self.universal_regions.as_ref() } /// Tries to find the best constraint to blame for the fact that /// `R: from_region`, where `R` is some region that meets /// `target_test`. This works by following the constraint graph, /// creating a constraint path that forces `R` to outlive /// `from_region`, and then finding the best choices within that /// path to blame. crate fn best_blame_constraint( &self, body: &Body<'tcx>, from_region: RegionVid, from_region_origin: NllRegionVariableOrigin, target_test: impl Fn(RegionVid) -> bool, ) -> BlameConstraint<'tcx> { debug!( "best_blame_constraint(from_region={:?}, from_region_origin={:?})", from_region, from_region_origin ); // Find all paths let (path, target_region) = self.find_constraint_paths_between_regions(from_region, target_test).unwrap(); debug!( "best_blame_constraint: path={:#?}", path.iter() .map(|c| format!( "{:?} ({:?}: {:?})", c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub), )) .collect::<Vec<_>>() ); // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint. // Instead, we use it to produce an improved `ObligationCauseCode`. // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate` // constraints. Currently, we just pick the first one. let cause_code = path .iter() .find_map(|constraint| { if let ConstraintCategory::Predicate(predicate_span) = constraint.category { // We currentl'y doesn't store the `DefId` in the `ConstraintCategory` // for perforamnce reasons. The error reporting code used by NLL only // uses the span, so this doesn't cause any problems at the moment. Some(ObligationCauseCode::BindingObligation( CRATE_DEF_ID.to_def_id(), predicate_span, )) } else { None } }) .unwrap_or_else(|| ObligationCauseCode::MiscObligation); // Classify each of the constraints along the path. let mut categorized_path: Vec<BlameConstraint<'tcx>> = path .iter() .map(|constraint| { if constraint.category == ConstraintCategory::ClosureBounds { self.retrieve_closure_constraint_info(body, &constraint) } else { BlameConstraint { category: constraint.category, from_closure: false, cause: ObligationCause::new( constraint.locations.span(body), CRATE_HIR_ID, cause_code.clone(), ), variance_info: constraint.variance_info, } } }) .collect(); debug!("best_blame_constraint: categorized_path={:#?}", categorized_path); // To find the best span to cite, we first try to look for the // final constraint that is interesting and where the `sup` is // not unified with the ultimate target region. The reason // for this is that we have a chain of constraints that lead // from the source to the target region, something like: // // '0: '1 ('0 is the source) // '1: '2 // '2: '3 // '3: '4 // '4: '5 // '5: '6 ('6 is the target) // // Some of those regions are unified with `'6` (in the same // SCC). We want to screen those out. After that point, the // "closest" constraint we have to the end is going to be the // most likely to be the point where the value escapes -- but // we still want to screen for an "interesting" point to // highlight (e.g., a call site or something). let target_scc = self.constraint_sccs.scc(target_region); let mut range = 0..path.len(); // As noted above, when reporting an error, there is typically a chain of constraints // leading from some "source" region which must outlive some "target" region. // In most cases, we prefer to "blame" the constraints closer to the target -- // but there is one exception. When constraints arise from higher-ranked subtyping, // we generally prefer to blame the source value, // as the "target" in this case tends to be some type annotation that the user gave. // Therefore, if we find that the region origin is some instantiation // of a higher-ranked region, we start our search from the "source" point // rather than the "target", and we also tweak a few other things. // // An example might be this bit of Rust code: // // ```rust // let x: fn(&'static ()) = |_| {}; // let y: for<'a> fn(&'a ()) = x; // ``` // // In MIR, this will be converted into a combination of assignments and type ascriptions. // In particular, the 'static is imposed through a type ascription: // // ```rust // x = ...; // AscribeUserType(x, fn(&'static ()) // y = x; // ``` // // We wind up ultimately with constraints like // // ```rust // !a: 'temp1 // from the `y = x` statement // 'temp1: 'temp2 // 'temp2: 'static // from the AscribeUserType // ``` // // and here we prefer to blame the source (the y = x statement). let blame_source = match from_region_origin { NllRegionVariableOrigin::FreeRegion | NllRegionVariableOrigin::Existential { from_forall: false } => true, NllRegionVariableOrigin::RootEmptyRegion | NllRegionVariableOrigin::Placeholder(_) | NllRegionVariableOrigin::Existential { from_forall: true } => false, }; let find_region = |i: &usize| { let constraint = &path[*i]; let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup); if blame_source { match categorized_path[*i].category { ConstraintCategory::OpaqueType | ConstraintCategory::Boring | ConstraintCategory::BoringNoLocation | ConstraintCategory::Internal | ConstraintCategory::Predicate(_) => false, ConstraintCategory::TypeAnnotation | ConstraintCategory::Return(_) | ConstraintCategory::Yield => true, _ => constraint_sup_scc != target_scc, } } else { !matches!( categorized_path[*i].category, ConstraintCategory::OpaqueType | ConstraintCategory::Boring | ConstraintCategory::BoringNoLocation | ConstraintCategory::Internal | ConstraintCategory::Predicate(_) ) } }; let best_choice = if blame_source { range.rev().find(find_region) } else { range.find(find_region) }; debug!( "best_blame_constraint: best_choice={:?} blame_source={}", best_choice, blame_source ); if let Some(i) = best_choice { if let Some(next) = categorized_path.get(i + 1) { if matches!(categorized_path[i].category, ConstraintCategory::Return(_)) && next.category == ConstraintCategory::OpaqueType { // The return expression is being influenced by the return type being // impl Trait, point at the return type and not the return expr. return next.clone(); } } if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal) { let field = categorized_path.iter().find_map(|p| { if let ConstraintCategory::ClosureUpvar(f) = p.category { Some(f) } else { None } }); if let Some(field) = field { categorized_path[i].category = ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field)); } } return categorized_path[i].clone(); } // If that search fails, that is.. unusual. Maybe everything // is in the same SCC or something. In that case, find what // appears to be the most interesting point to report to the // user via an even more ad-hoc guess. categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category)); debug!("best_blame_constraint: sorted_path={:#?}", categorized_path); categorized_path.remove(0) } crate fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> { self.universe_causes[&universe].clone() } } impl<'tcx> RegionDefinition<'tcx> { fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self { // Create a new region definition. Note that, for free // regions, the `external_name` field gets updated later in // `init_universal_regions`. let origin = match rv_origin { RegionVariableOrigin::Nll(origin) => origin, _ => NllRegionVariableOrigin::Existential { from_forall: false }, }; Self { origin, universe, external_name: None } } } pub trait ClosureRegionRequirementsExt<'tcx> { fn apply_requirements( &self, tcx: TyCtxt<'tcx>, closure_def_id: DefId, closure_substs: SubstsRef<'tcx>, ) -> Vec<QueryOutlivesConstraint<'tcx>>; } impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx> { /// Given an instance T of the closure type, this method /// instantiates the "extra" requirements that we computed for the /// closure into the inference context. This has the effect of /// adding new outlives obligations to existing variables. /// /// As described on `ClosureRegionRequirements`, the extra /// requirements are expressed in terms of regionvids that index /// into the free regions that appear on the closure type. So, to /// do this, we first copy those regions out from the type T into /// a vector. Then we can just index into that vector to extract /// out the corresponding region from T and apply the /// requirements. fn apply_requirements( &self, tcx: TyCtxt<'tcx>, closure_def_id: DefId, closure_substs: SubstsRef<'tcx>, ) -> Vec<QueryOutlivesConstraint<'tcx>> { debug!( "apply_requirements(closure_def_id={:?}, closure_substs={:?})", closure_def_id, closure_substs ); // Extract the values of the free regions in `closure_substs` // into a vector. These are the regions that we will be // relating to one another. let closure_mapping = &UniversalRegions::closure_mapping( tcx, closure_substs, self.num_external_vids, tcx.closure_base_def_id(closure_def_id), ); debug!("apply_requirements: closure_mapping={:?}", closure_mapping); // Create the predicates. self.outlives_requirements .iter() .map(|outlives_requirement| { let outlived_region = closure_mapping[outlives_requirement.outlived_free_region]; match outlives_requirement.subject { ClosureOutlivesSubject::Region(region) => { let region = closure_mapping[region]; debug!( "apply_requirements: region={:?} \ outlived_region={:?} \ outlives_requirement={:?}", region, outlived_region, outlives_requirement, ); ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region)) } ClosureOutlivesSubject::Ty(ty) => { debug!( "apply_requirements: ty={:?} \ outlived_region={:?} \ outlives_requirement={:?}", ty, outlived_region, outlives_requirement, ); ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region)) } } }) .collect() } } #[derive(Clone, Debug)] pub struct BlameConstraint<'tcx> { pub category: ConstraintCategory, pub from_closure: bool, pub cause: ObligationCause<'tcx>, pub variance_info: ty::VarianceDiagInfo<'tcx>, }
43.294376
103
0.597394
5b5a615795774d2759a8af2fe39da8d8a68b4030
10,215
use super::{ message::{consensus_message as message, Metadata}, Core, Error, Follower, InvalidTransaction, ViewChange, MAX_TRANSACTIONS_PER_BLOCK, }; use crate::{ consensus::{BlockHash, BlockNumber, Body, LeaderTerm, SignatureList}, transaction_checker::TransactionCheck, }; use pinxit::{verify_signed_batch, Signed}; use prellblock_client_api::Transaction; use std::{ ops::Deref, sync::Arc, time::{Duration, SystemTime}, }; use tokio::time; const BLOCK_GENERATION_TIMEOUT: Duration = Duration::from_millis(400); #[derive(Debug)] pub struct Leader { core: Arc<Core>, follower: Arc<Follower>, view_change: Arc<ViewChange>, leader_term: LeaderTerm, block_number: BlockNumber, last_block_hash: BlockHash, phase: Phase, /// Represents the leader's internal `WorldState`. transaction_check: TransactionCheck, } impl Deref for Leader { type Target = Core; fn deref(&self) -> &Self::Target { &self.core } } #[derive(Debug)] enum Phase { Waiting, Prepare, Append, Commit, } impl Leader { pub fn new(core: Arc<Core>, follower: Arc<Follower>, view_change: Arc<ViewChange>) -> Self { let transaction_check = core.transaction_checker.check(); Self { core, follower, view_change, leader_term: LeaderTerm::default(), block_number: BlockNumber::default(), last_block_hash: BlockHash::default(), phase: Phase::Waiting, transaction_check, } } /// Execute the leader. /// /// This function waits until it is notified of a leader change. pub async fn execute(mut self) { loop { self.synchronize_from_follower().await; // Wait when we are not the leader. while !self.is_current_leader() { log::trace!("I am not the current leader."); // Send new view message. self.handle_new_view().await; self.notify_leader.notified().await; // Update leader state with data from the follower state when we are the new leader. self.synchronize_from_follower().await; } log::info!( "I am the new leader in leader term {} (block: #{}).", self.leader_term, self.block_number ); match self.execute_leader_term().await { Ok(()) => log::info!( "Done with leader term {} (block: #{}).", self.leader_term, self.block_number ), Err(err) => log::error!( "Error during leader term {} (block: #{}, phase: {:?}): {}", self.leader_term, self.block_number, self.phase, err ), } // After we are done with one leader term, // we need to wait until the next time we are elected. // (At least one round later) self.leader_term += 1; } } /// Update the leader state with the state from the follower. async fn synchronize_from_follower(&mut self) { let state = self.follower.state().await; // This `if` is required because we set our `leader_term` to // the next value when an error occurs (`self.leader_term += 1`) // and we dont want to override this with the state of the follower. if self.leader_term <= state.leader_term { self.leader_term = state.leader_term; self.block_number = state.block_number; self.last_block_hash = state.last_block_hash; } // Update the leader's world state. self.transaction_check = self.transaction_checker.check(); } /// Broadcast a `NewView` message of one is available. /// Returns `true` if a `NewView` message was sent. async fn handle_new_view(&mut self) { if let Some(message) = self.view_change.get_new_view_message(self.block_number) { let new_leader_term = message.leader_term; match self.broadcast_until_majority(message, |_| Ok(())).await { Ok(_) => log::trace!( "Succesfully broadcasted NewView Message {}.", new_leader_term, ), Err(err) => { log::warn!( "Error while Broadcasting NewView Message {}: {}", new_leader_term, err ); } } } } /// Execute the leader during a single leader term. /// /// This function waits until it is notified to process transactions. async fn execute_leader_term(&mut self) -> Result<(), Error> { let mut timeout_result = Ok(()); loop { self.phase = Phase::Waiting; let min_block_size = match timeout_result { // No timeout, send only full blocks Ok(()) => MAX_TRANSACTIONS_PER_BLOCK, // Timeout, send all pending transactions Err(_) => 1, }; while self.queue.lock().await.len() >= min_block_size { self.execute_round().await?; } timeout_result = time::timeout(BLOCK_GENERATION_TIMEOUT, self.notify_leader.notified()).await; } } /// Execute the leader during a single round (block number). async fn execute_round(&mut self) -> Result<(), Error> { let mut transactions = Vec::new(); // TODO: Check size of transactions cumulated. while let Some(transaction) = self.queue.lock().await.next() { transactions.push(transaction); if transactions.len() >= MAX_TRANSACTIONS_PER_BLOCK { break; } } // Also applies valid transactions onto the leader's virutal world state. let (valid_transactions, invalid_transactions) = self.stateful_validate(transactions)?; let body = Body { leader_term: self.leader_term, height: self.block_number, prev_block_hash: self.last_block_hash, timestamp: SystemTime::now(), transactions: valid_transactions, }; let block_hash = body.hash(); let ackprepare_signatures = self.prepare(block_hash).await?; log::trace!( "Prepare Phase #{} ended. Got ACKPREPARE signatures: {:?}", self.block_number, ackprepare_signatures, ); let ackappend_signatures = self .append( block_hash, body.transactions, invalid_transactions, ackprepare_signatures, body.timestamp, ) .await?; log::trace!( "Append Phase #{} ended. Got ACKAPPEND signatures: {:?}", self.block_number, ackappend_signatures, ); self.commit(block_hash, ackappend_signatures).await?; log::info!("Comitted block #{} on majority of RPUs.", self.block_number); self.block_number += 1; self.last_block_hash = block_hash; Ok(()) } async fn prepare(&mut self, block_hash: BlockHash) -> Result<SignatureList, Error> { self.phase = Phase::Prepare; let metadata = self.metadata_with(block_hash); let message = message::Prepare { metadata: metadata.clone(), }; self.broadcast_until_majority(message, move |ack| ack.metadata.verify(&metadata)) .await } async fn append( &mut self, block_hash: BlockHash, valid_transactions: Vec<Signed<Transaction>>, invalid_transactions: Vec<(usize, Signed<Transaction>)>, ackprepare_signatures: SignatureList, timestamp: SystemTime, ) -> Result<SignatureList, Error> { self.phase = Phase::Append; let metadata = self.metadata_with(block_hash); let message = message::Append { metadata: metadata.clone(), valid_transactions, invalid_transactions, ackprepare_signatures, timestamp, }; self.broadcast_until_majority(message, move |ack| ack.metadata.verify(&metadata)) .await } async fn commit( &mut self, block_hash: BlockHash, ackappend_signatures: SignatureList, ) -> Result<SignatureList, Error> { self.phase = Phase::Commit; let metadata = self.metadata_with(block_hash); let message = message::Commit { metadata: metadata.clone(), ackappend_signatures, }; self.broadcast_until_majority(message, move |_| Ok(())) .await } fn is_current_leader(&self) -> bool { self.leader(self.leader_term) == *self.identity.id() } const fn metadata_with(&self, block_hash: BlockHash) -> Metadata { Metadata { leader_term: self.leader_term, block_number: self.block_number, block_hash, } } fn stateful_validate( &mut self, transactions: Vec<Signed<Transaction>>, ) -> Result<(Vec<Signed<Transaction>>, Vec<InvalidTransaction>), Error> { let verified_transactions = verify_signed_batch(transactions)?; let mut valid_transactions = Vec::new(); let mut invalid_transactions = Vec::new(); for (index, transaction) in verified_transactions.enumerate() { // This applies valid transaction to the leader's own world state. if self .transaction_check .verify_permissions_and_apply(transaction.borrow()) .is_ok() { valid_transactions.push(transaction.into()); } else { invalid_transactions.push((index, transaction.into())); } } Ok((valid_transactions, invalid_transactions)) } }
32.635783
100
0.564366
69c78e62d5eb302ed6afab83e5cf0a2dba11c920
352
use super::widget::Widget; use utils::shared::{share, Shared}; use std::rc::Rc; pub fn widget_of<T>(child: T) -> Shared<T> where T: Widget + 'static { let shared_ref: Shared<T> = share(child); { let widget_ref: Shared<Widget> = shared_ref.clone() as Shared<Widget>; shared_ref.borrow_mut().set_this(Rc::downgrade(&widget_ref)); } shared_ref }
27.076923
72
0.693182
e958d6dcea4850e30af6512fae9ee1562180387d
905
// Copyright (c) Aptos // SPDX-License-Identifier: Apache-2.0 use crate::account_config::DIEM_ACCOUNT_MODULE_IDENTIFIER; use anyhow::Result; use move_core_types::{ident_str, identifier::IdentStr, move_resource::MoveStructType}; use serde::{Deserialize, Serialize}; /// Struct that represents a AdminEvent. #[derive(Debug, Serialize, Deserialize)] pub struct AdminTransactionEvent { committed_timestamp_secs: u64, } impl AdminTransactionEvent { /// Get the applied writeset. pub fn committed_timestamp_secs(&self) -> u64 { self.committed_timestamp_secs } pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> { bcs::from_bytes(bytes).map_err(Into::into) } } impl MoveStructType for AdminTransactionEvent { const MODULE_NAME: &'static IdentStr = DIEM_ACCOUNT_MODULE_IDENTIFIER; const STRUCT_NAME: &'static IdentStr = ident_str!("AdminTransactionEvent"); }
30.166667
86
0.741436
e6144b0681ee378ac9a9ecfa12498be26d61e8b9
21,919
// 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 gio_sys; use glib; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; #[cfg(any(feature = "v2_60", feature = "dox"))] use glib::GString; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::pin::Pin; use std::ptr; use Cancellable; use IOStream; use TlsCertificate; use TlsCertificateFlags; use TlsDatabase; use TlsInteraction; use TlsRehandshakeMode; glib_wrapper! { pub struct TlsConnection(Object<gio_sys::GTlsConnection, gio_sys::GTlsConnectionClass, TlsConnectionClass>) @extends IOStream; match fn { get_type => || gio_sys::g_tls_connection_get_type(), } } pub const NONE_TLS_CONNECTION: Option<&TlsConnection> = None; pub trait TlsConnectionExt: 'static { fn emit_accept_certificate<P: IsA<TlsCertificate>>( &self, peer_cert: &P, errors: TlsCertificateFlags, ) -> bool; fn get_certificate(&self) -> Option<TlsCertificate>; fn get_database(&self) -> Option<TlsDatabase>; fn get_interaction(&self) -> Option<TlsInteraction>; #[cfg(any(feature = "v2_60", feature = "dox"))] fn get_negotiated_protocol(&self) -> Option<GString>; fn get_peer_certificate(&self) -> Option<TlsCertificate>; fn get_peer_certificate_errors(&self) -> TlsCertificateFlags; #[cfg_attr(feature = "v2_60", deprecated)] fn get_rehandshake_mode(&self) -> TlsRehandshakeMode; fn get_require_close_notify(&self) -> bool; fn handshake<P: IsA<Cancellable>>(&self, cancellable: Option<&P>) -> Result<(), glib::Error>; fn handshake_async<P: IsA<Cancellable>, Q: FnOnce(Result<(), glib::Error>) + Send + 'static>( &self, io_priority: glib::Priority, cancellable: Option<&P>, callback: Q, ); fn handshake_async_future( &self, io_priority: glib::Priority, ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>>; #[cfg(any(feature = "v2_60", feature = "dox"))] fn set_advertised_protocols(&self, protocols: &[&str]); fn set_certificate<P: IsA<TlsCertificate>>(&self, certificate: &P); fn set_database<P: IsA<TlsDatabase>>(&self, database: &P); fn set_interaction<P: IsA<TlsInteraction>>(&self, interaction: Option<&P>); #[cfg_attr(feature = "v2_60", deprecated)] fn set_rehandshake_mode(&self, mode: TlsRehandshakeMode); fn set_require_close_notify(&self, require_close_notify: bool); #[cfg(any(feature = "v2_60", feature = "dox"))] fn get_property_advertised_protocols(&self) -> Vec<GString>; fn get_property_base_io_stream(&self) -> Option<IOStream>; fn connect_accept_certificate< F: Fn(&Self, &TlsCertificate, TlsCertificateFlags) -> bool + 'static, >( &self, f: F, ) -> SignalHandlerId; #[cfg(any(feature = "v2_60", feature = "dox"))] fn connect_property_advertised_protocols_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_certificate_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_database_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_interaction_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_60", feature = "dox"))] fn connect_property_negotiated_protocol_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_peer_certificate_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_peer_certificate_errors_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_rehandshake_mode_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_require_close_notify_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; } impl<O: IsA<TlsConnection>> TlsConnectionExt for O { fn emit_accept_certificate<P: IsA<TlsCertificate>>( &self, peer_cert: &P, errors: TlsCertificateFlags, ) -> bool { unsafe { from_glib(gio_sys::g_tls_connection_emit_accept_certificate( self.as_ref().to_glib_none().0, peer_cert.as_ref().to_glib_none().0, errors.to_glib(), )) } } fn get_certificate(&self) -> Option<TlsCertificate> { unsafe { from_glib_none(gio_sys::g_tls_connection_get_certificate( self.as_ref().to_glib_none().0, )) } } fn get_database(&self) -> Option<TlsDatabase> { unsafe { from_glib_none(gio_sys::g_tls_connection_get_database( self.as_ref().to_glib_none().0, )) } } fn get_interaction(&self) -> Option<TlsInteraction> { unsafe { from_glib_none(gio_sys::g_tls_connection_get_interaction( self.as_ref().to_glib_none().0, )) } } #[cfg(any(feature = "v2_60", feature = "dox"))] fn get_negotiated_protocol(&self) -> Option<GString> { unsafe { from_glib_none(gio_sys::g_tls_connection_get_negotiated_protocol( self.as_ref().to_glib_none().0, )) } } fn get_peer_certificate(&self) -> Option<TlsCertificate> { unsafe { from_glib_none(gio_sys::g_tls_connection_get_peer_certificate( self.as_ref().to_glib_none().0, )) } } fn get_peer_certificate_errors(&self) -> TlsCertificateFlags { unsafe { from_glib(gio_sys::g_tls_connection_get_peer_certificate_errors( self.as_ref().to_glib_none().0, )) } } fn get_rehandshake_mode(&self) -> TlsRehandshakeMode { unsafe { from_glib(gio_sys::g_tls_connection_get_rehandshake_mode( self.as_ref().to_glib_none().0, )) } } fn get_require_close_notify(&self) -> bool { unsafe { from_glib(gio_sys::g_tls_connection_get_require_close_notify( self.as_ref().to_glib_none().0, )) } } fn handshake<P: IsA<Cancellable>>(&self, cancellable: Option<&P>) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = gio_sys::g_tls_connection_handshake( self.as_ref().to_glib_none().0, cancellable.map(|p| p.as_ref()).to_glib_none().0, &mut error, ); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } fn handshake_async<P: IsA<Cancellable>, Q: FnOnce(Result<(), glib::Error>) + Send + 'static>( &self, io_priority: glib::Priority, cancellable: Option<&P>, callback: Q, ) { let user_data: Box_<Q> = Box_::new(callback); unsafe extern "C" fn handshake_async_trampoline< Q: FnOnce(Result<(), glib::Error>) + Send + 'static, >( _source_object: *mut gobject_sys::GObject, res: *mut gio_sys::GAsyncResult, user_data: glib_sys::gpointer, ) { let mut error = ptr::null_mut(); let _ = gio_sys::g_tls_connection_handshake_finish( _source_object as *mut _, res, &mut error, ); let result = if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) }; let callback: Box_<Q> = Box_::from_raw(user_data as *mut _); callback(result); } let callback = handshake_async_trampoline::<Q>; unsafe { gio_sys::g_tls_connection_handshake_async( self.as_ref().to_glib_none().0, io_priority.to_glib(), cancellable.map(|p| p.as_ref()).to_glib_none().0, Some(callback), Box_::into_raw(user_data) as *mut _, ); } } fn handshake_async_future( &self, io_priority: glib::Priority, ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> { Box_::pin(crate::GioFuture::new(self, move |obj, send| { let cancellable = Cancellable::new(); obj.handshake_async(io_priority, Some(&cancellable), move |res| { send.resolve(res); }); cancellable })) } #[cfg(any(feature = "v2_60", feature = "dox"))] fn set_advertised_protocols(&self, protocols: &[&str]) { unsafe { gio_sys::g_tls_connection_set_advertised_protocols( self.as_ref().to_glib_none().0, protocols.to_glib_none().0, ); } } fn set_certificate<P: IsA<TlsCertificate>>(&self, certificate: &P) { unsafe { gio_sys::g_tls_connection_set_certificate( self.as_ref().to_glib_none().0, certificate.as_ref().to_glib_none().0, ); } } fn set_database<P: IsA<TlsDatabase>>(&self, database: &P) { unsafe { gio_sys::g_tls_connection_set_database( self.as_ref().to_glib_none().0, database.as_ref().to_glib_none().0, ); } } fn set_interaction<P: IsA<TlsInteraction>>(&self, interaction: Option<&P>) { unsafe { gio_sys::g_tls_connection_set_interaction( self.as_ref().to_glib_none().0, interaction.map(|p| p.as_ref()).to_glib_none().0, ); } } fn set_rehandshake_mode(&self, mode: TlsRehandshakeMode) { unsafe { gio_sys::g_tls_connection_set_rehandshake_mode( self.as_ref().to_glib_none().0, mode.to_glib(), ); } } fn set_require_close_notify(&self, require_close_notify: bool) { unsafe { gio_sys::g_tls_connection_set_require_close_notify( self.as_ref().to_glib_none().0, require_close_notify.to_glib(), ); } } #[cfg(any(feature = "v2_60", feature = "dox"))] fn get_property_advertised_protocols(&self) -> Vec<GString> { unsafe { let mut value = Value::from_type(<Vec<GString> as StaticType>::static_type()); gobject_sys::g_object_get_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"advertised-protocols\0".as_ptr() as *const _, value.to_glib_none_mut().0, ); value .get() .expect("Return Value for property `advertised-protocols` getter") .unwrap() } } fn get_property_base_io_stream(&self) -> Option<IOStream> { unsafe { let mut value = Value::from_type(<IOStream as StaticType>::static_type()); gobject_sys::g_object_get_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"base-io-stream\0".as_ptr() as *const _, value.to_glib_none_mut().0, ); value .get() .expect("Return Value for property `base-io-stream` getter") } } fn connect_accept_certificate< F: Fn(&Self, &TlsCertificate, TlsCertificateFlags) -> bool + 'static, >( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn accept_certificate_trampoline< P, F: Fn(&P, &TlsCertificate, TlsCertificateFlags) -> bool + 'static, >( this: *mut gio_sys::GTlsConnection, peer_cert: *mut gio_sys::GTlsCertificate, errors: gio_sys::GTlsCertificateFlags, f: glib_sys::gpointer, ) -> glib_sys::gboolean where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f( &TlsConnection::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(peer_cert), from_glib(errors), ) .to_glib() } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"accept-certificate\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( accept_certificate_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } #[cfg(any(feature = "v2_60", feature = "dox"))] fn connect_property_advertised_protocols_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_advertised_protocols_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::advertised-protocols\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_advertised_protocols_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_certificate_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_certificate_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::certificate\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_certificate_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_database_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_database_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::database\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_database_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_interaction_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_interaction_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::interaction\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_interaction_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } #[cfg(any(feature = "v2_60", feature = "dox"))] fn connect_property_negotiated_protocol_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_negotiated_protocol_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::negotiated-protocol\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_negotiated_protocol_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_peer_certificate_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_peer_certificate_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::peer-certificate\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_peer_certificate_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_peer_certificate_errors_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_peer_certificate_errors_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::peer-certificate-errors\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_peer_certificate_errors_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_rehandshake_mode_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_rehandshake_mode_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::rehandshake-mode\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_rehandshake_mode_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_require_close_notify_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_require_close_notify_trampoline<P, F: Fn(&P) + 'static>( this: *mut gio_sys::GTlsConnection, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<TlsConnection>, { let f: &F = &*(f as *const F); f(&TlsConnection::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::require-close-notify\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_require_close_notify_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for TlsConnection { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TlsConnection") } }
33.160363
130
0.538209
ed1235269f98c9f946a91a5dd51ae4d46f6618e2
2,856
//! Default Compute@Edge template program. use fastly::http::{HeaderValue, Method, StatusCode}; use fastly::request::CacheOverride; use fastly::{Body, Error, Request, RequestExt, Response, ResponseExt}; /// The name of a backend server associated with this service. /// /// This should be changed to match the name of your own backend. See the the `Hosts` section of /// the Fastly WASM service UI for more information. const BACKEND_NAME: &str = "backend_name"; /// The name of a second backend associated with this service. const OTHER_BACKEND_NAME: &str = "other_backend_name"; /// The entry point for your application. /// /// This function is triggered when your service receives a client request. It could be used to /// route based on the request properties (such as method or path), send the request to a backend, /// make completely new requests, and/or generate synthetic responses. /// /// If `main` returns an error, a 500 error response will be delivered to the client. #[fastly::main] fn main(mut req: Request<Body>) -> Result<impl ResponseExt, Error> { // Make any desired changes to the client request. req.headers_mut() .insert("Host", HeaderValue::from_static("example.com")); // We can filter requests that have unexpected methods. const VALID_METHODS: [Method; 3] = [Method::HEAD, Method::GET, Method::POST]; if !(VALID_METHODS.contains(req.method())) { return Ok(Response::builder() .status(StatusCode::METHOD_NOT_ALLOWED) .body(Body::from("This method is not allowed"))?); } // Pattern match on the request method and path. match (req.method(), req.uri().path()) { // If request is a `GET` to the `/` path, send a default response. (&Method::GET, "/") => Ok(Response::builder() .status(StatusCode::OK) .body(Body::from("Welcome to Fastly Compute@Edge!"))?), // If request is a `GET` to the `/backend` path, send to a named backend. (&Method::GET, "/backend") => { // Request handling logic could go here... // E.g., send the request to an origin backend and then cache the // response for one minute. *req.cache_override_mut() = CacheOverride::ttl(60); Ok(req.send(BACKEND_NAME)?) } // If request is a `GET` to a path starting with `/other/`. (&Method::GET, path) if path.starts_with("/other/") => { // Send request to a different backend and don't cache response. *req.cache_override_mut() = CacheOverride::Pass; Ok(req.send(OTHER_BACKEND_NAME)?) } // Catch all other requests and return a 404. _ => Ok(Response::builder() .status(StatusCode::NOT_FOUND) .body(Body::from("The page you requested could not be found"))?), } }
43.272727
98
0.643557
f7878dc6c7a19a91642373e4c79de7a79a7de98a
7,193
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use diem_genesis_tool::validator_builder::ValidatorConfig; use diem_types::{account_address::AccountAddress, on_chain_config::VMPublishingOption}; use move_cli::{ package::cli as pkgcli, sandbox, sandbox::utils::{on_disk_state_view::OnDiskStateView, Mode, ModeType}, }; use move_lang::shared::AddressBytes; use move_package::source_package::layout::SourcePackageLayout; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, HashMap}, fs, path::{Path, PathBuf}, }; /// Default blockchain configuration pub const DEFAULT_BLOCKCHAIN: &str = "goodday"; /// Name and directory of starter package for all new shuffle projects. const HELLOBLOCKCHAIN: &str = "helloblockchain"; pub fn handle(blockchain: String, pathbuf: PathBuf) -> Result<()> { let project_path = pathbuf.as_path(); println!("Creating shuffle project in {}", project_path.display()); fs::create_dir_all(project_path)?; // Shuffle projects aspire to be on a Diem Core Framework that // does not include the DPN. ModeType::Diem is not quite there but is a step // towards that goal. Bare and Stdlib do not work as expected but this is a WIP let mode = Mode::new(ModeType::Diem); let build_path = project_path.join(HELLOBLOCKCHAIN).join("build"); let storage_path = project_path.join(HELLOBLOCKCHAIN).join("storage"); let state = mode.prepare_state(build_path.as_path(), storage_path.as_path())?; let config = Config { blockchain, named_addresses: fetch_named_addresses(&state)?, }; write_project_config(project_path, &config)?; write_move_starter_modules(project_path)?; build_move_starter_modules(project_path, &state)?; generate_validator_config(project_path)?; Ok(()) } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "kebab-case")] pub struct Config { pub(crate) blockchain: String, named_addresses: BTreeMap<String, AccountAddress>, } // Fetches the named addresses for a particular project or genesis. // Uses a BTreeMap over HashMap because upstream AddressBytes does as well, // probably because order matters. fn fetch_named_addresses(state: &OnDiskStateView) -> Result<BTreeMap<String, AccountAddress>> { let address_bytes_map = state.get_named_addresses(BTreeMap::new())?; Ok(map_address_bytes_to_account_address(address_bytes_map)) } // map_address_bytes_to_account_address converts BTreeMap<String,AddressBytes> // to BTreeMap<String, AccountAddress> because AddressBytes is not serializable. fn map_address_bytes_to_account_address( original: BTreeMap<String, AddressBytes>, ) -> BTreeMap<String, AccountAddress> { original .iter() .map(|(name, addr)| (name.to_string(), AccountAddress::new(addr.into_bytes()))) .collect() } fn write_project_config(path: &Path, config: &Config) -> Result<()> { let toml_path = PathBuf::from(path).join("Shuffle").with_extension("toml"); let toml_string = toml::to_string(config)?; fs::write(toml_path, toml_string)?; Ok(()) } // Embeds bytes into the binary, keyed off of their file path relative to the // crate sibling path. ie: shuffle/cli/../../$key macro_rules! include_files( ($($key:expr),+) => {{ let mut m = HashMap::new(); $( m.insert($key, include_bytes!(concat!("../../", $key)).as_ref()); )+ m }}; ); /// Embeds .move files used to generate the starter template into the binary /// at compilation time, for reference during project generation. static EMBEDDED_MOVE_STARTER_FILES: Lazy<HashMap<&str, &[u8]>> = Lazy::new(|| { include_files! { "move/src/SampleModule.move" } }); // Writes all the move modules for a new project, including genesis and // starter template. fn write_move_starter_modules(root_path: &Path) -> Result<()> { let pkg_dir = root_path.join(HELLOBLOCKCHAIN); pkgcli::create_move_package(HELLOBLOCKCHAIN, pkg_dir.as_path())?; let sources_path = pkg_dir.join(SourcePackageLayout::Sources.path()); for key in EMBEDDED_MOVE_STARTER_FILES.keys() { let dst = sources_path.join(Path::new(key).file_name().unwrap()); fs::write(dst.as_path(), EMBEDDED_MOVE_STARTER_FILES[key])?; } Ok(()) } // Inspired by https://github.com/diem/diem/blob/e0379458c85d58224798b79194a2871be9a7e655/shuffle/genesis/src/lib.rs#L72 // Reuse publish command from move cli fn build_move_starter_modules(project_path: &Path, state: &OnDiskStateView) -> Result<()> { let src_dir = project_path .join(HELLOBLOCKCHAIN) .join(SourcePackageLayout::Sources.path()); let natives = move_stdlib::natives::all_natives(AccountAddress::from_hex_literal("0x1").unwrap()); sandbox::commands::publish( natives, state, &[src_dir.to_string_lossy().to_string()], true, true, None, state.get_named_addresses(BTreeMap::new())?, true, ) } fn generate_validator_config(project_path: &Path) -> Result<ValidatorConfig> { let publishing_option = VMPublishingOption::open(); // TODO (dimroc): place genesis module deployment/generate validator config // in shuffle node command shuffle_custom_node::generate_validator_config( project_path.join("nodeconfig").as_path(), diem_framework_releases::current_module_blobs().to_vec(), publishing_option, ) } #[cfg(test)] mod test { use super::*; use diem_config::config::NodeConfig; use tempfile::tempdir; #[test] fn test_write_project_config() { let dir = tempdir().unwrap(); let config = Config { blockchain: String::from(DEFAULT_BLOCKCHAIN), named_addresses: map_address_bytes_to_account_address( diem_framework::diem_framework_named_addresses(), ), }; write_project_config(dir.path(), &config).unwrap(); let config_string = fs::read_to_string(dir.path().join("Shuffle").with_extension("toml")).unwrap(); let read_config: Config = toml::from_str(config_string.as_str()).unwrap(); assert_eq!(config, read_config); let actual_std_address = read_config.named_addresses["Std"].short_str_lossless(); assert_eq!(actual_std_address, "1"); } #[test] fn test_handle_e2e() { let dir = tempdir().unwrap(); handle(String::from(DEFAULT_BLOCKCHAIN), PathBuf::from(dir.path())).unwrap(); // spot check move starter files let expected_starter_content = String::from_utf8_lossy(include_bytes!("../../move/src/SampleModule.move")); let actual_starter_content = fs::read_to_string(dir.path().join("helloblockchain/sources/SampleModule.move")) .unwrap(); assert_eq!(expected_starter_content, actual_starter_content); // check if we can load generated node.yaml config file let _node_config = NodeConfig::load(dir.path().join("nodeconfig/0/node.yaml").as_path()).unwrap(); } }
37.26943
120
0.687613
fb096c31957ee61ce18fbeeaee246b1712259720
196
// error-pattern:thread 'main' panicked at 'attempt to subtract with overflow' // compile-flags: -C debug-assertions #![allow(arithmetic_overflow)] fn main() { let _x = 42u8 - (42u8 + 1); }
21.777778
78
0.678571
01ee53731e6149d64cdd162ecb3e458080b733c1
3,320
// Copyright (c) 2019, Arm Limited, All Rights Reserved // SPDX-License-Identifier: Apache-2.0 // // 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(test)] mod tests { use parsec_client_test::TestClient; use parsec_interface::operations::key_attributes::*; use parsec_interface::requests::{ResponseStatus, Result}; const KEY_DATA: [u8; 140] = [ 48, 129, 137, 2, 129, 129, 0, 153, 165, 220, 135, 89, 101, 254, 229, 28, 33, 138, 247, 20, 102, 253, 217, 247, 246, 142, 107, 51, 40, 179, 149, 45, 117, 254, 236, 161, 109, 16, 81, 135, 72, 112, 132, 150, 175, 128, 173, 182, 122, 227, 214, 196, 130, 54, 239, 93, 5, 203, 185, 233, 61, 159, 156, 7, 161, 87, 48, 234, 105, 161, 108, 215, 211, 150, 168, 156, 212, 6, 63, 81, 24, 101, 72, 160, 97, 243, 142, 86, 10, 160, 122, 8, 228, 178, 252, 35, 209, 222, 228, 16, 143, 99, 143, 146, 241, 186, 187, 22, 209, 86, 141, 24, 159, 12, 146, 44, 111, 254, 183, 54, 229, 109, 28, 39, 22, 141, 173, 85, 26, 58, 9, 128, 27, 57, 131, 2, 3, 1, 0, 1, ]; #[test] fn import_key() -> Result<()> { let mut client = TestClient::new(); let key_name = String::from("import_key"); client.import_key( key_name.clone(), KeyType::RsaPublicKey, Algorithm::sign(SignAlgorithm::RsaPkcs1v15Sign, None), KEY_DATA.to_vec(), ) } #[test] fn create_and_import_key() -> Result<()> { let mut client = TestClient::new(); let key_name = String::from("create_and_import_key"); client.create_rsa_sign_key(key_name.clone())?; let status = client .import_key( key_name.clone(), KeyType::RsaPublicKey, Algorithm::sign(SignAlgorithm::RsaPkcs1v15Sign, None), KEY_DATA.to_vec(), ) .expect_err("Key should have already existed"); assert_eq!(status, ResponseStatus::KeyAlreadyExists); Ok(()) } #[test] fn import_key_twice() -> Result<()> { let mut client = TestClient::new(); let key_name = String::from("import_key_twice"); client.import_key( key_name.clone(), KeyType::RsaPublicKey, Algorithm::sign(SignAlgorithm::RsaPkcs1v15Sign, None), KEY_DATA.to_vec(), )?; let status = client .import_key( key_name.clone(), KeyType::RsaPublicKey, Algorithm::sign(SignAlgorithm::RsaPkcs1v15Sign, None), KEY_DATA.to_vec(), ) .expect_err("The key with the same name has already been created."); assert_eq!(status, ResponseStatus::KeyAlreadyExists); Ok(()) } }
37.303371
98
0.581627
d7cb2f975585908172992026e6e36e3e48487b15
46,440
//! Efficiently-updatable double-array trie in Rust (ported from cedar). //! //! Add it to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! cedarwood = "0.4" //! ``` //! //! then you are good to go. If you are using Rust 2015 you have to `extern crate cedarwood` to your crate root as well. //! //! ## Example //! //! ```rust //! use cedarwood::Cedar; //! //! let dict = vec![ //! "a", //! "ab", //! "abc", //! "アルゴリズム", //! "データ", //! "構造", //! "网", //! "网球", //! "网球拍", //! "中", //! "中华", //! "中华人民", //! "中华人民共和国", //! ]; //! let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); //! let mut cedar = Cedar::new(); //! cedar.build(&key_values); //! //! let result: Vec<i32> = cedar.common_prefix_search("abcdefg").unwrap().iter().map(|x| x.0).collect(); //! assert_eq!(vec![0, 1, 2], result); //! //! let result: Vec<i32> = cedar //! .common_prefix_search("网球拍卖会") //! .unwrap() //! .iter() //! .map(|x| x.0) //! .collect(); //! assert_eq!(vec![6, 7, 8], result); //! //! let result: Vec<i32> = cedar //! .common_prefix_search("中华人民共和国") //! .unwrap() //! .iter() //! .map(|x| x.0) //! .collect(); //! assert_eq!(vec![9, 10, 11, 12], result); //! //! let result: Vec<i32> = cedar //! .common_prefix_search("データ構造とアルゴリズム") //! .unwrap() //! .iter() //! .map(|x| x.0) //! .collect(); //! assert_eq!(vec![4], result); //! ``` #![no_std] use std::prelude::v1::*; #[macro_use] extern crate sgx_tstd as std; extern crate sgx_libc as libc; use smallvec::SmallVec; use std::fmt; /// NInfo stores the information about the trie #[derive(Debug, Default, Clone)] struct NInfo { sibling: u8, // the index of right sibling, it is 0 if it doesn't have a sibling. child: u8, // the index of the first child } /// Node contains the array of `base` and `check` as specified in the paper: "An efficient implementation of trie structures" /// https://dl.acm.org/citation.cfm?id=146691 #[derive(Debug, Default, Clone)] struct Node { base_: i32, // if it is a negative value, then it stores the value of previous index that is free. check: i32, // if it is a negative value, then it stores the value of next index that is free. } impl Node { #[inline] fn base(&self) -> i32 { #[cfg(feature = "reduced-trie")] return -(self.base_ + 1); #[cfg(not(feature = "reduced-trie"))] return self.base_; } } /// Block stores the linked-list pointers and the stats info for blocks. #[derive(Debug, Clone)] struct Block { prev: i32, // previous block's index, 3 bytes width next: i32, // next block's index, 3 bytes width num: i16, // the number of slots that is free, the range is 0-256 reject: i16, // a heuristic number to make the search for free space faster, it is the minimum number of iteration in each trie node it has to try before we can conclude that we can reject this block. If the number of kids for the block we are looking for is less than this number then this block is worthy of searching. trial: i32, // the number of times this block has been probed by `find_places` for the free block. e_head: i32, // the index of the first empty elemenet in this block } impl Block { pub fn new() -> Self { Block { prev: 0, next: 0, num: 256, // each of block has 256 free slots at the beginning reject: 257, // initially every block need to be fully iterated through so that we can reject it to be unusable. trial: 0, e_head: 0, } } } /// Blocks are marked as either of three categories, so that we can quickly decide if we can /// allocate it for use or not. enum BlockType { Open, // The block has spaces more than 1. Closed, // The block is only left with one free slot Full, // The block's slots are fully used. } /// `Cedar` holds all of the information about double array trie. #[derive(Clone)] pub struct Cedar { array: Vec<Node>, // storing the `base` and `check` info from the original paper. n_infos: Vec<NInfo>, blocks: Vec<Block>, reject: Vec<i16>, blocks_head_full: i32, // the index of the first 'Full' block, 0 means no 'Full' block blocks_head_closed: i32, // the index of the first 'Closed' block, 0 means no ' Closed' block blocks_head_open: i32, // the index of the first 'Open' block, 0 means no 'Open' block capacity: usize, size: usize, ordered: bool, max_trial: i32, // the parameter for cedar, it could be tuned for more, but the default is 1. } impl fmt::Debug for Cedar { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Cedar(size={}, ordered={})", self.size, self.ordered) } } #[allow(dead_code)] const CEDAR_VALUE_LIMIT: i32 = std::i32::MAX - 1; const CEDAR_NO_VALUE: i32 = -1; /// Iterator for `common_prefix_search` #[derive(Clone)] pub struct PrefixIter<'a> { cedar: &'a Cedar, key: &'a [u8], from: usize, i: usize, } impl<'a> Iterator for PrefixIter<'a> { type Item = (i32, usize); fn size_hint(&self) -> (usize, Option<usize>) { (0, Some(self.key.len())) } fn next(&mut self) -> Option<Self::Item> { while self.i < self.key.len() { if let Some(value) = self.cedar.find(&self.key[self.i..=self.i], &mut self.from) { if value == CEDAR_NO_VALUE { self.i += 1; continue; } else { let result = Some((value, self.i)); self.i += 1; return result; } } else { break; } } None } } /// Iterator for `common_prefix_predict` #[derive(Clone)] pub struct PrefixPredictIter<'a> { cedar: &'a Cedar, key: &'a [u8], from: usize, p: usize, root: usize, value: Option<i32>, } impl<'a> PrefixPredictIter<'a> { fn next_until_none(&mut self) -> Option<(i32, usize)> { #[allow(clippy::never_loop)] while let Some(value) = self.value { let result = (value, self.p); let (v_, from_, p_) = self.cedar.next(self.from, self.p, self.root); self.from = from_; self.p = p_; self.value = v_; return Some(result); } None } } impl<'a> Iterator for PrefixPredictIter<'a> { type Item = (i32, usize); fn next(&mut self) -> Option<Self::Item> { if self.from == 0 && self.p == 0 { // To locate the prefix's position first, if it doesn't exist then that means we // don't have do anything. `from` would serve as the cursor. if self.cedar.find(self.key, &mut self.from).is_some() { self.root = self.from; let (v_, from_, p_) = self.cedar.begin(self.from, self.p); self.from = from_; self.p = p_; self.value = v_; self.next_until_none() } else { None } } else { self.next_until_none() } } } #[allow(clippy::cast_lossless)] impl Cedar { /// Initialize the Cedar for further use. #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut array: Vec<Node> = Vec::with_capacity(256); let n_infos: Vec<NInfo> = (0..256).map(|_| Default::default()).collect(); let mut blocks: Vec<Block> = vec![Block::new(); 1]; let reject: Vec<i16> = (0..=256).map(|i| i + 1).collect(); #[cfg(feature = "reduced-trie")] array.push(Node { base_: -1, check: -1 }); #[cfg(not(feature = "reduced-trie"))] array.push(Node { base_: 0, check: -1 }); for i in 1..256 { // make `base_` point to the previous element, and make `check` point to the next element array.push(Node { base_: -(i - 1), check: -(i + 1), }) } // make them link as a cyclic doubly-linked list array[1].base_ = -255; array[255].check = -1; blocks[0].e_head = 1; Cedar { array, n_infos, blocks, reject, blocks_head_full: 0, blocks_head_closed: 0, blocks_head_open: 0, capacity: 256, size: 256, ordered: true, max_trial: 1, } } /// Build the double array trie from the given key value pairs #[allow(dead_code)] pub fn build(&mut self, key_values: &[(&str, i32)]) { for (key, value) in key_values { self.update(key, *value); } } /// Update the key for the value, it is public interface that works on &str pub fn update(&mut self, key: &str, value: i32) { let from = 0; let pos = 0; self.update_(key.as_bytes(), value, from, pos); } // Update the key for the value, it is internal interface that works on &[u8] and cursor. fn update_(&mut self, key: &[u8], value: i32, mut from: usize, mut pos: usize) -> i32 { if from == 0 && key.is_empty() { panic!("failed to insert zero-length key"); } while pos < key.len() { #[cfg(feature = "reduced-trie")] { let val_ = self.array[from].base_; if val_ >= 0 && val_ != CEDAR_VALUE_LIMIT { let to = self.follow(from, 0); self.array[to as usize].base_ = val_; } } from = self.follow(from, key[pos]) as usize; pos += 1; } #[cfg(feature = "reduced-trie")] let to = if self.array[from].base_ >= 0 { from as i32 } else { self.follow(from, 0) }; #[cfg(feature = "reduced-trie")] { if self.array[to as usize].base_ == CEDAR_VALUE_LIMIT { self.array[to as usize].base_ = 0; } } #[cfg(not(feature = "reduced-trie"))] let to = self.follow(from, 0); self.array[to as usize].base_ = value; self.array[to as usize].base_ } // To move in the trie by following the `label`, and insert the node if the node is not there, // it is used by the `update` to populate the trie. #[inline] fn follow(&mut self, from: usize, label: u8) -> i32 { let base = self.array[from].base(); #[allow(unused_assignments)] let mut to = 0; // the node is not there if base < 0 || self.array[(base ^ (label as i32)) as usize].check < 0 { // allocate a e node to = self.pop_e_node(base, label, from as i32); let branch: i32 = to ^ (label as i32); // maintain the info in ninfo self.push_sibling(from, branch, label, base >= 0); } else { // the node is already there and the ownership is not `from`, therefore a conflict. to = base ^ (label as i32); if self.array[to as usize].check != (from as i32) { // call `resolve` to relocate. to = self.resolve(from, base, label); } } to } // Find key from double array trie, with `from` as the cursor to traverse the nodes. fn find(&self, key: &[u8], from: &mut usize) -> Option<i32> { #[allow(unused_assignments)] let mut to: usize = 0; let mut pos = 0; // recursively matching the key. while pos < key.len() { #[cfg(feature = "reduced-trie")] { if self.array[*from].base_ >= 0 { break; } } to = (self.array[*from].base() ^ (key[pos] as i32)) as usize; if self.array[to as usize].check != (*from as i32) { return None; } *from = to; pos += 1; } #[cfg(feature = "reduced-trie")] { if self.array[*from].base_ >= 0 { if pos == key.len() { return Some(self.array[*from].base_); } else { return None; } } } // return the value of the node if `check` is correctly marked fpr the ownership, otherwise // it means no value is stored. let n = &self.array[(self.array[*from].base()) as usize]; if n.check != (*from as i32) { Some(CEDAR_NO_VALUE) } else { Some(n.base_) } } /// Delete the key from the trie, the public interface that works on &str pub fn erase(&mut self, key: &str) { self.erase_(key.as_bytes()) } // Delete the key from the trie, the internal interface that works on &[u8] fn erase_(&mut self, key: &[u8]) { let mut from = 0; // move the cursor to the right place and use erase__ to delete it. if self.find(&key, &mut from).is_some() { self.erase__(from); } } fn erase__(&mut self, mut from: usize) { #[cfg(feature = "reduced-trie")] let mut e: i32 = if self.array[from].base_ >= 0 { from as i32 } else { self.array[from].base() }; #[cfg(feature = "reduced-trie")] { from = self.array[e as usize].check as usize; } #[cfg(not(feature = "reduced-trie"))] let mut e = self.array[from].base(); #[allow(unused_assignments)] let mut has_sibling = false; loop { let n = self.array[from].clone(); has_sibling = self.n_infos[(n.base() ^ (self.n_infos[from].child as i32)) as usize].sibling != 0; // if the node has siblings, then remove `e` from the sibling. if has_sibling { self.pop_sibling(from as i32, n.base(), (n.base() ^ e) as u8); } // maintain the data structures. self.push_e_node(e); e = from as i32; // traverse to the parent. from = self.array[from].check as usize; // if it has sibling then this layer has more than one nodes, then we are done. if has_sibling { break; } } } /// To check if `key` is in the dictionary. pub fn exact_match_search(&self, key: &str) -> Option<(i32, usize, usize)> { let key = key.as_bytes(); let mut from = 0; if let Some(value) = self.find(&key, &mut from) { if value == CEDAR_NO_VALUE { return None; } Some((value, key.len(), from)) } else { None } } /// To return an iterator to iterate through the common prefix in the dictionary with the `key` passed in. pub fn common_prefix_iter<'a>(&'a self, key: &'a str) -> PrefixIter<'a> { let key = key.as_bytes(); PrefixIter { cedar: self, key, from: 0, i: 0, } } /// To return the collection of the common prefix in the dictionary with the `key` passed in. pub fn common_prefix_search(&self, key: &str) -> Option<Vec<(i32, usize)>> { self.common_prefix_iter(key).map(Some).collect() } /// To return an iterator to iterate through the list of words in the dictionary that has `key` as their prefix. pub fn common_prefix_predict_iter<'a>(&'a self, key: &'a str) -> PrefixPredictIter<'a> { let key = key.as_bytes(); PrefixPredictIter { cedar: self, key, from: 0, p: 0, root: 0, value: None, } } /// To return the list of words in the dictionary that has `key` as their prefix. pub fn common_prefix_predict(&self, key: &str) -> Option<Vec<(i32, usize)>> { self.common_prefix_predict_iter(key).map(Some).collect() } // To get the cursor of the first leaf node starting by `from` fn begin(&self, mut from: usize, mut p: usize) -> (Option<i32>, usize, usize) { let base = self.array[from].base(); let mut c = self.n_infos[from].child; if from == 0 { c = self.n_infos[(base ^ (c as i32)) as usize].sibling; // if no sibling couldn be found from the virtual root, then we are done. if c == 0 { return (None, from, p); } } // recursively traversing down to look for the first leaf. while c != 0 { from = (self.array[from].base() ^ (c as i32)) as usize; c = self.n_infos[from].child; p += 1; } #[cfg(feature = "reduced-trie")] { if self.array[from].base_ >= 0 { return (Some(self.array[from].base_), from, p); } } // To return the value of the leaf. let v = self.array[(self.array[from].base() ^ (c as i32)) as usize].base_; (Some(v), from, p) } // To move the cursor from one leaf to the next for the common_prefix_predict. fn next(&self, mut from: usize, mut p: usize, root: usize) -> (Option<i32>, usize, usize) { #[allow(unused_assignments)] let mut c: u8 = 0; #[cfg(feature = "reduced-trie")] { if self.array[from].base_ < 0 { c = self.n_infos[(self.array[from].base()) as usize].sibling; } } #[cfg(not(feature = "reduced-trie"))] { c = self.n_infos[(self.array[from].base()) as usize].sibling; } // traversing up until there is a sibling or it has reached the root. while c == 0 && from != root { c = self.n_infos[from as usize].sibling; from = self.array[from as usize].check as usize; p -= 1; } if c != 0 { // it has a sibling so we leverage on `begin` to traverse the subtree down again. from = (self.array[from].base() ^ (c as i32)) as usize; let (v_, from_, p_) = self.begin(from, p + 1); (v_, from_, p_) } else { // no more work since we couldn't find anything. (None, from, p) } } // pop a block at idx from the linked-list of type `from`, specially handled if it is the last // one in the linked-list. fn pop_block(&mut self, idx: i32, from: BlockType, last: bool) { let head: &mut i32 = match from { BlockType::Open => &mut self.blocks_head_open, BlockType::Closed => &mut self.blocks_head_closed, BlockType::Full => &mut self.blocks_head_full, }; if last { *head = 0; } else { let b = self.blocks[idx as usize].clone(); self.blocks[b.prev as usize].next = b.next; self.blocks[b.next as usize].prev = b.prev; if idx == *head { *head = b.next; } } } // return the block at idx to the linked-list of `to`, specially handled if the linked-list is // empty fn push_block(&mut self, idx: i32, to: BlockType, empty: bool) { let head: &mut i32 = match to { BlockType::Open => &mut self.blocks_head_open, BlockType::Closed => &mut self.blocks_head_closed, BlockType::Full => &mut self.blocks_head_full, }; if empty { self.blocks[idx as usize].next = idx; self.blocks[idx as usize].prev = idx; *head = idx; } else { self.blocks[idx as usize].prev = self.blocks[*head as usize].prev; self.blocks[idx as usize].next = *head; let t = self.blocks[*head as usize].prev; self.blocks[t as usize].next = idx; self.blocks[*head as usize].prev = idx; *head = idx; } } /// Reallocate more spaces so that we have more free blocks. fn add_block(&mut self) -> i32 { if self.size == self.capacity { self.capacity += self.capacity; self.array.resize(self.capacity, Default::default()); self.n_infos.resize(self.capacity, Default::default()); self.blocks.resize(self.capacity >> 8, Block::new()); } self.blocks[self.size >> 8].e_head = self.size as i32; // make it a doubley linked list self.array[self.size] = Node { base_: -((self.size as i32) + 255), check: -((self.size as i32) + 1), }; for i in (self.size + 1)..(self.size + 255) { self.array[i] = Node { base_: -(i as i32 - 1), check: -(i as i32 + 1), }; } self.array[self.size + 255] = Node { base_: -((self.size as i32) + 254), check: -(self.size as i32), }; let is_empty = self.blocks_head_open == 0; let idx = (self.size >> 8) as i32; debug_assert!(self.blocks[idx as usize].num > 1); self.push_block(idx, BlockType::Open, is_empty); self.size += 256; ((self.size >> 8) - 1) as i32 } // transfer the block at idx from the linked-list of `from` to the linked-list of `to`, // specially handle the case where the destination linked-list is empty. fn transfer_block(&mut self, idx: i32, from: BlockType, to: BlockType, to_block_empty: bool) { let is_last = idx == self.blocks[idx as usize].next; //it's the last one if the next points to itself let is_empty = to_block_empty && (self.blocks[idx as usize].num != 0); self.pop_block(idx, from, is_last); self.push_block(idx, to, is_empty); } /// Mark an edge `e` as used in a trie node. fn pop_e_node(&mut self, base: i32, label: u8, from: i32) -> i32 { let e: i32 = if base < 0 { self.find_place() } else { base ^ (label as i32) }; let idx = e >> 8; let n = self.array[e as usize].clone(); self.blocks[idx as usize].num -= 1; // move the block at idx to the correct linked-list depending the free slots it still have. if self.blocks[idx as usize].num == 0 { if idx != 0 { self.transfer_block(idx, BlockType::Closed, BlockType::Full, self.blocks_head_full == 0); } } else { self.array[(-n.base_) as usize].check = n.check; self.array[(-n.check) as usize].base_ = n.base_; if e == self.blocks[idx as usize].e_head { self.blocks[idx as usize].e_head = -n.check; } if idx != 0 && self.blocks[idx as usize].num == 1 && self.blocks[idx as usize].trial != self.max_trial { self.transfer_block(idx, BlockType::Open, BlockType::Closed, self.blocks_head_closed == 0); } } #[cfg(feature = "reduced-trie")] { self.array[e as usize].base_ = CEDAR_VALUE_LIMIT; self.array[e as usize].check = from; if base < 0 { self.array[from as usize].base_ = -(e ^ (label as i32)) - 1; } } #[cfg(not(feature = "reduced-trie"))] { if label != 0 { self.array[e as usize].base_ = -1; } else { self.array[e as usize].base_ = 0; } self.array[e as usize].check = from; if base < 0 { self.array[from as usize].base_ = e ^ (label as i32); } } e } /// Mark an edge `e` as free in a trie node. fn push_e_node(&mut self, e: i32) { let idx = e >> 8; self.blocks[idx as usize].num += 1; if self.blocks[idx as usize].num == 1 { self.blocks[idx as usize].e_head = e; self.array[e as usize] = Node { base_: -e, check: -e }; if idx != 0 { // Move the block from 'Full' to 'Closed' since it has one free slot now. self.transfer_block(idx, BlockType::Full, BlockType::Closed, self.blocks_head_closed == 0); } } else { let prev = self.blocks[idx as usize].e_head; let next = -self.array[prev as usize].check; // Insert to the edge immediately after the e_head self.array[e as usize] = Node { base_: -prev, check: -next, }; self.array[prev as usize].check = -e; self.array[next as usize].base_ = -e; // Move the block from 'Closed' to 'Open' since it has more than one free slot now. if self.blocks[idx as usize].num == 2 || self.blocks[idx as usize].trial == self.max_trial { debug_assert!(self.blocks[idx as usize].num > 1); if idx != 0 { self.transfer_block(idx, BlockType::Closed, BlockType::Open, self.blocks_head_open == 0); } } // Reset the trial stats self.blocks[idx as usize].trial = 0; } if self.blocks[idx as usize].reject < self.reject[self.blocks[idx as usize].num as usize] { self.blocks[idx as usize].reject = self.reject[self.blocks[idx as usize].num as usize]; } self.n_infos[e as usize] = Default::default(); } // push the `label` into the sibling chain fn push_sibling(&mut self, from: usize, base: i32, label: u8, has_child: bool) { let keep_order: bool = if self.ordered { label > self.n_infos[from].child } else { self.n_infos[from].child == 0 }; let sibling: u8; { let mut c: &mut u8 = &mut self.n_infos[from as usize].child; if has_child && keep_order { loop { let code = *c as i32; c = &mut self.n_infos[(base ^ code) as usize].sibling; if !(self.ordered && (*c != 0) && (*c < label)) { break; } } } sibling = *c; *c = label; } self.n_infos[(base ^ (label as i32)) as usize].sibling = sibling; } // remove the `label` from the sibling chain. #[allow(dead_code)] fn pop_sibling(&mut self, from: i32, base: i32, label: u8) { let mut c: *mut u8 = &mut self.n_infos[from as usize].child; unsafe { while *c != label { let code = *c as i32; c = &mut self.n_infos[(base ^ code) as usize].sibling; } let code = label as i32; *c = self.n_infos[(base ^ code) as usize].sibling; } } // Loop through the siblings to see which one reached the end first, which means it is the one // with smaller in children size, and we should try ti relocate the smaller one. fn consult(&self, base_n: i32, base_p: i32, mut c_n: u8, mut c_p: u8) -> bool { loop { c_n = self.n_infos[(base_n ^ (c_n as i32)) as usize].sibling; c_p = self.n_infos[(base_p ^ (c_p as i32)) as usize].sibling; if !(c_n != 0 && c_p != 0) { break; } } c_p != 0 } // Collect the list of the children, and push the label as well if it is not terminal node. fn set_child(&self, base: i32, mut c: u8, label: u8, not_terminal: bool) -> SmallVec<[u8; 256]> { let mut child: SmallVec<[u8; 256]> = SmallVec::new(); if c == 0 { child.push(c); c = self.n_infos[(base ^ (c as i32)) as usize].sibling; } if self.ordered { while c != 0 && c <= label { child.push(c); c = self.n_infos[(base ^ (c as i32)) as usize].sibling; } } if not_terminal { child.push(label); } while c != 0 { child.push(c); c = self.n_infos[(base ^ (c as i32)) as usize].sibling; } child } // For the case where only one free slot is needed fn find_place(&mut self) -> i32 { if self.blocks_head_closed != 0 { return self.blocks[self.blocks_head_closed as usize].e_head; } if self.blocks_head_open != 0 { return self.blocks[self.blocks_head_open as usize].e_head; } // the block is not enough, resize it and allocate it. self.add_block() << 8 } // For the case where multiple free slots are needed. fn find_places(&mut self, child: &[u8]) -> i32 { let mut idx = self.blocks_head_open; // we still have available 'Open' blocks. if idx != 0 { debug_assert!(self.blocks[idx as usize].num > 1); let bz = self.blocks[self.blocks_head_open as usize].prev; let nc = child.len() as i16; loop { // only proceed if the free slots are more than the number of children. Also, we // save the minimal number of attempts to fail in the `reject`, it only worths to // try out this block if the number of children is less than that number. if self.blocks[idx as usize].num >= nc && nc < self.blocks[idx as usize].reject { let mut e = self.blocks[idx as usize].e_head; loop { let base = e ^ (child[0] as i32); let mut i = 1; // iterate through the children to see if they are available: (check < 0) while self.array[(base ^ (child[i] as i32)) as usize].check < 0 { if i == child.len() - 1 { // we have found the available block. self.blocks[idx as usize].e_head = e; return e; } i += 1; } // we save the next free block's information in `check` e = -self.array[e as usize].check; if e == self.blocks[idx as usize].e_head { break; } } } // we broke out of the loop, that means we failed. We save the information in // `reject` for future pruning. self.blocks[idx as usize].reject = nc; if self.blocks[idx as usize].reject < self.reject[self.blocks[idx as usize].num as usize] { // put this stats into the global array of information as well. self.reject[self.blocks[idx as usize].num as usize] = self.blocks[idx as usize].reject; } let idx_ = self.blocks[idx as usize].next; self.blocks[idx as usize].trial += 1; // move this block to the 'Closed' block list since it has reached the max_trial if self.blocks[idx as usize].trial == self.max_trial { self.transfer_block(idx, BlockType::Open, BlockType::Closed, self.blocks_head_closed == 0); } // we have finsihed one round of this cyclic doubly-linked-list. if idx == bz { break; } // going to the next in this linked list group idx = idx_; } } self.add_block() << 8 } // resolve the conflict by moving one of the the nodes to a free block. fn resolve(&mut self, mut from_n: usize, base_n: i32, label_n: u8) -> i32 { let to_pn = base_n ^ (label_n as i32); // the `base` and `from` for the conflicting one. let from_p = self.array[to_pn as usize].check; let base_p = self.array[from_p as usize].base(); // whether to replace siblings of newly added let flag = self.consult( base_n, base_p, self.n_infos[from_n as usize].child, self.n_infos[from_p as usize].child, ); // collect the list of children for the block that we are going to relocate. let children = if flag { self.set_child(base_n, self.n_infos[from_n as usize].child, label_n, true) } else { self.set_child(base_p, self.n_infos[from_p as usize].child, 255, false) }; // decide which algorithm to allocate free block depending on the number of children we // have. let mut base = if children.len() == 1 { self.find_place() } else { self.find_places(&children) }; base ^= children[0] as i32; let (from, base_) = if flag { (from_n as i32, base_n) } else { (from_p, base_p) }; if flag && children[0] == label_n { self.n_infos[from as usize].child = label_n; } #[cfg(feature = "reduced-trie")] { self.array[from as usize].base_ = -base - 1; } #[cfg(not(feature = "reduced-trie"))] { self.array[from as usize].base_ = base; } // the actual work for relocating the chilren for i in 0..(children.len()) { let to = self.pop_e_node(base, children[i], from); let to_ = base_ ^ (children[i] as i32); if i == children.len() - 1 { self.n_infos[to as usize].sibling = 0; } else { self.n_infos[to as usize].sibling = children[i + 1]; } if flag && to_ == to_pn { continue; } self.array[to as usize].base_ = self.array[to_ as usize].base_; #[cfg(feature = "reduced-trie")] let condition = self.array[to as usize].base_ < 0 && children[i] != 0; #[cfg(not(feature = "reduced-trie"))] let condition = self.array[to as usize].base_ > 0 && children[i] != 0; if condition { let mut c = self.n_infos[to_ as usize].child; self.n_infos[to as usize].child = c; loop { let idx = (self.array[to as usize].base() ^ (c as i32)) as usize; self.array[idx].check = to; c = self.n_infos[idx].sibling; if c == 0 { break; } } } if !flag && to_ == (from_n as i32) { from_n = to as usize; } // clean up the space that was moved away from. if !flag && to_ == to_pn { self.push_sibling(from_n, to_pn ^ (label_n as i32), label_n, true); self.n_infos[to_ as usize].child = 0; #[cfg(feature = "reduced-trie")] { self.array[to_ as usize].base_ = CEDAR_VALUE_LIMIT; } #[cfg(not(feature = "reduced-trie"))] { if label_n != 0 { self.array[to_ as usize].base_ = -1; } else { self.array[to_ as usize].base_ = 0; } } self.array[to_ as usize].check = from_n as i32; } else { self.push_e_node(to_); } } // return the position that is free now. if flag { base ^ (label_n as i32) } else { to_pn } } } #[cfg(test)] mod tests { use super::*; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::iter; #[test] fn test_insert_and_delete() { let dict = vec!["a"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result = cedar.exact_match_search("ab").map(|x| x.0); assert_eq!(None, result); cedar.update("ab", 1); let result = cedar.exact_match_search("ab").map(|x| x.0); assert_eq!(Some(1), result); cedar.erase("ab"); let result = cedar.exact_match_search("ab").map(|x| x.0); assert_eq!(None, result); cedar.update("abc", 2); let result = cedar.exact_match_search("abc").map(|x| x.0); assert_eq!(Some(2), result); cedar.erase("abc"); let result = cedar.exact_match_search("abc").map(|x| x.0); assert_eq!(None, result); } #[test] fn test_common_prefix_search() { let dict = vec![ "a", "ab", "abc", "アルゴリズム", "データ", "構造", "网", "网球", "网球拍", "中", "中华", "中华人民", "中华人民共和国", ]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result: Vec<i32> = cedar .common_prefix_search("abcdefg") .unwrap() .iter() .map(|x| x.0) .collect(); assert_eq!(vec![0, 1, 2], result); let result: Vec<i32> = cedar .common_prefix_search("网球拍卖会") .unwrap() .iter() .map(|x| x.0) .collect(); assert_eq!(vec![6, 7, 8], result); let result: Vec<i32> = cedar .common_prefix_search("中华人民共和国") .unwrap() .iter() .map(|x| x.0) .collect(); assert_eq!(vec![9, 10, 11, 12], result); let result: Vec<i32> = cedar .common_prefix_search("データ構造とアルゴリズム") .unwrap() .iter() .map(|x| x.0) .collect(); assert_eq!(vec![4], result); } #[test] fn test_common_prefix_iter() { let dict = vec![ "a", "ab", "abc", "アルゴリズム", "データ", "構造", "网", "网球", "网球拍", "中", "中华", "中华人民", "中华人民共和国", ]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result: Vec<i32> = cedar.common_prefix_iter("abcdefg").map(|x| x.0).collect(); assert_eq!(vec![0, 1, 2], result); let result: Vec<i32> = cedar.common_prefix_iter("网球拍卖会").map(|x| x.0).collect(); assert_eq!(vec![6, 7, 8], result); let result: Vec<i32> = cedar.common_prefix_iter("中华人民共和国").map(|x| x.0).collect(); assert_eq!(vec![9, 10, 11, 12], result); let result: Vec<i32> = cedar .common_prefix_iter("データ構造とアルゴリズム") .map(|x| x.0) .collect(); assert_eq!(vec![4], result); } #[test] fn test_common_prefix_predict() { let dict = vec!["a", "ab", "abc"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result: Vec<i32> = cedar.common_prefix_predict("a").unwrap().iter().map(|x| x.0).collect(); assert_eq!(vec![0, 1, 2], result); } #[test] fn test_exact_match_search() { let dict = vec!["a", "ab", "abc"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result = cedar.exact_match_search("abc").map(|x| x.0); assert_eq!(Some(2), result); } #[test] fn test_unicode_han_sip() { let dict = vec!["讥䶯䶰", "讥䶯䶰䶱䶲", "讥䶯䶰䶱䶲䶳䶴䶵𦡦"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result: Vec<i32> = cedar.common_prefix_iter("讥䶯䶰䶱䶲䶳䶴䶵𦡦").map(|x| x.0).collect(); assert_eq!(vec![0, 1, 2], result); } #[test] fn test_unicode_grapheme_cluster() { let dict = vec!["a", "abc", "abcde\u{0301}"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); let result: Vec<i32> = cedar .common_prefix_iter("abcde\u{0301}\u{1100}\u{1161}\u{AC00}") .map(|x| x.0) .collect(); assert_eq!(vec![0, 1, 2], result); } #[test] fn test_erase() { let dict = vec!["a", "ab", "abc"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); cedar.erase("abc"); assert!(cedar.exact_match_search("abc").is_none()); assert!(cedar.exact_match_search("ab").is_some()); assert!(cedar.exact_match_search("a").is_some()); cedar.erase("ab"); assert!(cedar.exact_match_search("ab").is_none()); assert!(cedar.exact_match_search("a").is_some()); cedar.erase("a"); assert!(cedar.exact_match_search("a").is_none()); } #[test] fn test_update() { let dict = vec!["a", "ab", "abc"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); cedar.update("abcd", 3); assert!(cedar.exact_match_search("a").is_some()); assert!(cedar.exact_match_search("ab").is_some()); assert!(cedar.exact_match_search("abc").is_some()); assert!(cedar.exact_match_search("abcd").is_some()); assert!(cedar.exact_match_search("abcde").is_none()); let dict = vec!["a", "ab", "abc"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); cedar.update("bachelor", 1); cedar.update("jar", 2); cedar.update("badge", 3); cedar.update("baby", 4); assert!(cedar.exact_match_search("bachelor").is_some()); assert!(cedar.exact_match_search("jar").is_some()); assert!(cedar.exact_match_search("badge").is_some()); assert!(cedar.exact_match_search("baby").is_some()); assert!(cedar.exact_match_search("abcde").is_none()); let dict = vec!["a", "ab", "abc"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); cedar.update("中", 1); cedar.update("中华", 2); cedar.update("中华人民", 3); cedar.update("中华人民共和国", 4); assert!(cedar.exact_match_search("中").is_some()); assert!(cedar.exact_match_search("中华").is_some()); assert!(cedar.exact_match_search("中华人民").is_some()); assert!(cedar.exact_match_search("中华人民共和国").is_some()); } #[test] fn test_quickcheck_like() { let mut rng = thread_rng(); let mut dict: Vec<String> = Vec::with_capacity(1000); for _ in 0..1000 { let chars: String = iter::repeat(()).map(|()| rng.sample(Alphanumeric)).take(30).collect(); dict.push(chars); } let key_values: Vec<(&str, i32)> = dict.iter().enumerate().map(|(k, s)| (s.as_ref(), k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); for (k, s) in dict.iter().enumerate() { assert_eq!(cedar.exact_match_search(s).map(|x| x.0), Some(k as i32)); } } #[test] fn test_quickcheck_like_with_deep_trie() { let mut rng = thread_rng(); let mut dict: Vec<String> = Vec::with_capacity(1000); let mut s = String::new(); for _ in 0..1000 { let c: char = rng.sample(Alphanumeric); s.push(c); dict.push(s.clone()); } let key_values: Vec<(&str, i32)> = dict.iter().enumerate().map(|(k, s)| (s.as_ref(), k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); for (k, s) in dict.iter().enumerate() { assert_eq!(cedar.exact_match_search(s).map(|x| x.0), Some(k as i32)); } } #[test] fn test_mass_erase() { let mut rng = thread_rng(); let mut dict: Vec<String> = Vec::with_capacity(1000); for _ in 0..1000 { let chars: String = iter::repeat(()).map(|()| rng.sample(Alphanumeric)).take(30).collect(); dict.push(chars); } let key_values: Vec<(&str, i32)> = dict.iter().enumerate().map(|(k, s)| (s.as_ref(), k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); for s in dict.iter() { cedar.erase(s); assert!(cedar.exact_match_search(s).is_none()); } } #[test] fn test_duplication() { let dict = vec!["些许端", "些須", "些须", "亜", "亝", "亞", "亞", "亞丁", "亞丁港"]; let key_values: Vec<(&str, i32)> = dict.into_iter().enumerate().map(|(k, s)| (s, k as i32)).collect(); let mut cedar = Cedar::new(); cedar.build(&key_values); assert_eq!(cedar.exact_match_search("亞").map(|t| t.0), Some(6)); assert_eq!(cedar.exact_match_search("亞丁港").map(|t| t.0), Some(8)); assert_eq!(cedar.exact_match_search("亝").map(|t| t.0), Some(4)); assert_eq!(cedar.exact_match_search("些須").map(|t| t.0), Some(1)); } }
33.124108
324
0.512791
2fdce4ba3e81c34fdf2a7ad989ae552f9b380b47
10,318
use crate::loom::sync::atomic::AtomicU64; use crate::sync::AtomicWaker; use crate::time::driver::{Handle, Inner}; use crate::time::{Duration, Error, Instant}; use std::cell::UnsafeCell; use std::ptr; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::{Arc, Weak}; use std::task::{self, Poll}; use std::u64; /// Internal state shared between a `Delay` instance and the timer. /// /// This struct is used as a node in two intrusive data structures: /// /// * An atomic stack used to signal to the timer thread that the entry state /// has changed. The timer thread will observe the entry on this stack and /// perform any actions as necessary. /// /// * A doubly linked list used **only** by the timer thread. Each slot in the /// timer wheel is a head pointer to the list of entries that must be /// processed during that timer tick. #[derive(Debug)] pub(crate) struct Entry { /// Only accessed from `Registration`. time: CachePadded<UnsafeCell<Time>>, /// Timer internals. Using a weak pointer allows the timer to shutdown /// without all `Delay` instances having completed. /// /// When `None`, the entry has not yet been linked with a timer instance. inner: Weak<Inner>, /// Tracks the entry state. This value contains the following information: /// /// * The deadline at which the entry must be "fired". /// * A flag indicating if the entry has already been fired. /// * Whether or not the entry transitioned to the error state. /// /// When an `Entry` is created, `state` is initialized to the instant at /// which the entry must be fired. When a timer is reset to a different /// instant, this value is changed. state: AtomicU64, /// Task to notify once the deadline is reached. waker: AtomicWaker, /// True when the entry is queued in the "process" stack. This value /// is set before pushing the value and unset after popping the value. /// /// TODO: This could possibly be rolled up into `state`. pub(super) queued: AtomicBool, /// Next entry in the "process" linked list. /// /// Access to this field is coordinated by the `queued` flag. /// /// Represents a strong Arc ref. pub(super) next_atomic: UnsafeCell<*mut Entry>, /// When the entry expires, relative to the `start` of the timer /// (Inner::start). This is only used by the timer. /// /// A `Delay` instance can be reset to a different deadline by the thread /// that owns the `Delay` instance. In this case, the timer thread will not /// immediately know that this has happened. The timer thread must know the /// last deadline that it saw as it uses this value to locate the entry in /// its wheel. /// /// Once the timer thread observes that the instant has changed, it updates /// the wheel and sets this value. The idea is that this value eventually /// converges to the value of `state` as the timer thread makes updates. when: UnsafeCell<Option<u64>>, /// Next entry in the State's linked list. /// /// This is only accessed by the timer pub(super) next_stack: UnsafeCell<Option<Arc<Entry>>>, /// Previous entry in the State's linked list. /// /// This is only accessed by the timer and is used to unlink a canceled /// entry. /// /// This is a weak reference. pub(super) prev_stack: UnsafeCell<*const Entry>, } /// Stores the info for `Delay`. #[derive(Debug)] pub(crate) struct Time { pub(crate) deadline: Instant, pub(crate) duration: Duration, } /// Flag indicating a timer entry has elapsed const ELAPSED: u64 = 1 << 63; /// Flag indicating a timer entry has reached an error state const ERROR: u64 = u64::MAX; // ===== impl Entry ===== impl Entry { pub(crate) fn new(handle: &Handle, deadline: Instant, duration: Duration) -> Arc<Entry> { let backtrace = backtrace::Backtrace::new_unresolved(); let _ = crate::ENTRY_BACKTRACE_SENDER.send(backtrace); let inner = handle.inner().unwrap(); let entry: Entry; // Increment the number of active timeouts if inner.increment().is_err() { entry = Entry::new2(deadline, duration, Weak::new(), ERROR) } else { let when = inner.normalize_deadline(deadline); let state = if when <= inner.elapsed() { ELAPSED } else { when }; entry = Entry::new2(deadline, duration, Arc::downgrade(&inner), state); } let entry = Arc::new(entry); if inner.queue(&entry).is_err() { entry.error(); } entry } /// Only called by `Registration` pub(crate) fn time_ref(&self) -> &Time { unsafe { &*self.time.0.get() } } /// Only called by `Registration` #[allow(clippy::mut_from_ref)] // https://github.com/rust-lang/rust-clippy/issues/4281 pub(crate) unsafe fn time_mut(&self) -> &mut Time { &mut *self.time.0.get() } /// The current entry state as known by the timer. This is not the value of /// `state`, but lets the timer know how to converge its state to `state`. pub(crate) fn when_internal(&self) -> Option<u64> { unsafe { *self.when.get() } } pub(crate) fn set_when_internal(&self, when: Option<u64>) { unsafe { *self.when.get() = when; } } /// Called by `Timer` to load the current value of `state` for processing pub(crate) fn load_state(&self) -> Option<u64> { let state = self.state.load(SeqCst); if is_elapsed(state) { None } else { Some(state) } } pub(crate) fn is_elapsed(&self) -> bool { let state = self.state.load(SeqCst); is_elapsed(state) } pub(crate) fn fire(&self, when: u64) { let mut curr = self.state.load(SeqCst); loop { if is_elapsed(curr) || curr > when { return; } let next = ELAPSED | curr; let actual = self.state.compare_and_swap(curr, next, SeqCst); if curr == actual { break; } curr = actual; } self.waker.wake(); } pub(crate) fn error(&self) { // Only transition to the error state if not currently elapsed let mut curr = self.state.load(SeqCst); loop { if is_elapsed(curr) { return; } let next = ERROR; let actual = self.state.compare_and_swap(curr, next, SeqCst); if curr == actual { break; } curr = actual; } self.waker.wake(); } pub(crate) fn cancel(entry: &Arc<Entry>) { let state = entry.state.fetch_or(ELAPSED, SeqCst); if is_elapsed(state) { // Nothing more to do return; } // If registered with a timer instance, try to upgrade the Arc. let inner = match entry.upgrade_inner() { Some(inner) => inner, None => return, }; let _ = inner.queue(entry); } pub(crate) fn poll_elapsed(&self, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> { let mut curr = self.state.load(SeqCst); if is_elapsed(curr) { return Poll::Ready(if curr == ERROR { Err(Error::shutdown()) } else { Ok(()) }); } self.waker.register_by_ref(cx.waker()); curr = self.state.load(SeqCst); if is_elapsed(curr) { return Poll::Ready(if curr == ERROR { Err(Error::shutdown()) } else { Ok(()) }); } Poll::Pending } /// Only called by `Registration` pub(crate) fn reset(entry: &mut Arc<Entry>) { let inner = match entry.upgrade_inner() { Some(inner) => inner, None => return, }; let deadline = entry.time_ref().deadline; let when = inner.normalize_deadline(deadline); let elapsed = inner.elapsed(); let mut curr = entry.state.load(SeqCst); let mut notify; loop { // In these two cases, there is no work to do when resetting the // timer. If the `Entry` is in an error state, then it cannot be // used anymore. If resetting the entry to the current value, then // the reset is a noop. if curr == ERROR || curr == when { return; } let next; if when <= elapsed { next = ELAPSED; notify = !is_elapsed(curr); } else { next = when; notify = true; } let actual = entry.state.compare_and_swap(curr, next, SeqCst); if curr == actual { break; } curr = actual; } if notify { let _ = inner.queue(entry); } } fn new2(deadline: Instant, duration: Duration, inner: Weak<Inner>, state: u64) -> Self { Self { time: CachePadded(UnsafeCell::new(Time { deadline, duration })), inner, waker: AtomicWaker::new(), state: AtomicU64::new(state), queued: AtomicBool::new(false), next_atomic: UnsafeCell::new(ptr::null_mut()), when: UnsafeCell::new(None), next_stack: UnsafeCell::new(None), prev_stack: UnsafeCell::new(ptr::null_mut()), } } fn upgrade_inner(&self) -> Option<Arc<Inner>> { self.inner.upgrade() } } fn is_elapsed(state: u64) -> bool { state & ELAPSED == ELAPSED } impl Drop for Entry { fn drop(&mut self) { let inner = match self.upgrade_inner() { Some(inner) => inner, None => return, }; inner.decrement(); } } unsafe impl Send for Entry {} unsafe impl Sync for Entry {} #[cfg_attr(target_arch = "x86_64", repr(align(128)))] #[cfg_attr(not(target_arch = "x86_64"), repr(align(64)))] #[derive(Debug)] struct CachePadded<T>(T);
29.56447
94
0.567455
79b40b5b2681373156ab3763aa313e3ee078f4de
3,590
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use proc_macro2::TokenStream; use quote::quote; use synstructure::{decl_derive, Structure}; decl_derive!([EqModuloPos] => derive_eq_modulo_pos); fn derive_eq_modulo_pos(mut s: Structure<'_>) -> TokenStream { // By default, if you are deriving an impl of trait Foo for generic type // X<T>, synstructure will add Foo as a bound not only for the type // parameter T, but also for every type which appears as a field in X. This // is not necessary for our use case--we can just require that the type // parameters implement our trait. s.add_bounds(synstructure::AddBounds::Generics); let body = derive_eq_modulo_pos_body(&s); s.gen_impl(quote! { gen impl EqModuloPos for @Self { fn eq_modulo_pos(&self, rhs: &Self) -> bool { match self { #body } } } }) } fn derive_eq_modulo_pos_body(s: &Structure<'_>) -> TokenStream { s.each_variant(|v| { let mut s_rhs = s.clone(); let v_rhs = s_rhs .variants_mut() .iter_mut() .find(|v2| v2.ast().ident == v.ast().ident) .unwrap(); for (i, binding) in v_rhs.bindings_mut().iter_mut().enumerate() { let name = format!("rhs{}", i); binding.binding = proc_macro2::Ident::new(&name, binding.binding.span()); } let arm = v_rhs.pat(); let mut inner = quote! {true}; for (bi, bi_rhs) in v.bindings().iter().zip(v_rhs.bindings().iter()) { inner = quote! { #inner && #bi.eq_modulo_pos(#bi_rhs) } } quote!( match rhs { #arm => { #inner } _ => false, } ) }) } decl_derive!([EqModuloPosAndReason] => derive_eq_modulo_pos_and_reason); fn derive_eq_modulo_pos_and_reason(mut s: Structure<'_>) -> TokenStream { // By default, if you are deriving an impl of trait Foo for generic type // X<T>, synstructure will add Foo as a bound not only for the type // parameter T, but also for every type which appears as a field in X. This // is not necessary for our use case--we can just require that the type // parameters implement our trait. s.add_bounds(synstructure::AddBounds::Generics); let body = derive_eq_modulo_pos_and_reason_body(&s); s.gen_impl(quote! { gen impl EqModuloPosAndReason for @Self { fn eq_modulo_pos_and_reason(&self, rhs: &Self) -> bool { match self { #body } } } }) } fn derive_eq_modulo_pos_and_reason_body(s: &Structure<'_>) -> TokenStream { s.each_variant(|v| { let mut s_rhs = s.clone(); let v_rhs = s_rhs .variants_mut() .iter_mut() .find(|v2| v2.ast().ident == v.ast().ident) .unwrap(); for (i, binding) in v_rhs.bindings_mut().iter_mut().enumerate() { let name = format!("rhs{}", i); binding.binding = proc_macro2::Ident::new(&name, binding.binding.span()); } let arm = v_rhs.pat(); let mut inner = quote! {true}; for (bi, bi_rhs) in v.bindings().iter().zip(v_rhs.bindings().iter()) { inner = quote! { #inner && #bi.eq_modulo_pos_and_reason(#bi_rhs) } } quote!( match rhs { #arm => { #inner } _ => false, } ) }) }
35.544554
85
0.577437
261155aeb2180c15fef4e908b100406df3c0106b
8,036
// Copyright 2017 Parity Technologies (UK) Ltd. // // 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. //! Contains the `listener_select_proto` code, which allows selecting a protocol thanks to //! `multistream-select` for the listener. use futures::{prelude::*, sink, stream::StreamFuture}; use crate::protocol::{ DialerToListenerMessage, Listener, ListenerFuture, ListenerToDialerMessage }; use log::{debug, trace}; use std::mem; use tokio_io::{AsyncRead, AsyncWrite}; use crate::ProtocolChoiceError; /// Helps selecting a protocol amongst the ones supported. /// /// This function expects a socket and an iterator of the list of supported protocols. The iterator /// must be clonable (i.e. iterable multiple times), because the list may need to be accessed /// multiple times. /// /// The iterator must produce tuples of the name of the protocol that is advertised to the remote, /// a function that will check whether a remote protocol matches ours, and an identifier for the /// protocol of type `P` (you decide what `P` is). The parameters of the function are the name /// proposed by the remote, and the protocol name that we passed (so that you don't have to clone /// the name). /// /// On success, returns the socket and the identifier of the chosen protocol (of type `P`). The /// socket now uses this protocol. pub fn listener_select_proto<R, I, X>(inner: R, protocols: I) -> ListenerSelectFuture<R, I, X> where R: AsyncRead + AsyncWrite, for<'r> &'r I: IntoIterator<Item = X>, X: AsRef<[u8]> { ListenerSelectFuture { inner: ListenerSelectState::AwaitListener { listener_fut: Listener::listen(inner), protocols } } } /// Future, returned by `listener_select_proto` which selects a protocol among the ones supported. pub struct ListenerSelectFuture<R, I, X> where R: AsyncRead + AsyncWrite, for<'a> &'a I: IntoIterator<Item = X>, X: AsRef<[u8]> { inner: ListenerSelectState<R, I, X> } enum ListenerSelectState<R, I, X> where R: AsyncRead + AsyncWrite, for<'a> &'a I: IntoIterator<Item = X>, X: AsRef<[u8]> { AwaitListener { listener_fut: ListenerFuture<R, X>, protocols: I }, Incoming { stream: StreamFuture<Listener<R, X>>, protocols: I }, Outgoing { sender: sink::Send<Listener<R, X>>, protocols: I, outcome: Option<X> }, Undefined } impl<R, I, X> Future for ListenerSelectFuture<R, I, X> where R: AsyncRead + AsyncWrite, for<'a> &'a I: IntoIterator<Item = X>, X: AsRef<[u8]> + Clone { type Item = (X, R, I); type Error = ProtocolChoiceError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { match mem::replace(&mut self.inner, ListenerSelectState::Undefined) { ListenerSelectState::AwaitListener { mut listener_fut, protocols } => { let listener = match listener_fut.poll()? { Async::Ready(l) => l, Async::NotReady => { self.inner = ListenerSelectState::AwaitListener { listener_fut, protocols }; return Ok(Async::NotReady) } }; let stream = listener.into_future(); self.inner = ListenerSelectState::Incoming { stream, protocols }; } ListenerSelectState::Incoming { mut stream, protocols } => { let (msg, listener) = match stream.poll() { Ok(Async::Ready(x)) => x, Ok(Async::NotReady) => { self.inner = ListenerSelectState::Incoming { stream, protocols }; return Ok(Async::NotReady) } Err((e, _)) => return Err(ProtocolChoiceError::from(e)) }; match msg { Some(DialerToListenerMessage::ProtocolsListRequest) => { trace!("protocols list response: {:?}", protocols .into_iter() .map(|p| p.as_ref().into()) .collect::<Vec<Vec<u8>>>()); let list = protocols.into_iter().collect(); let msg = ListenerToDialerMessage::ProtocolsListResponse { list }; let sender = listener.send(msg); self.inner = ListenerSelectState::Outgoing { sender, protocols, outcome: None } } Some(DialerToListenerMessage::ProtocolRequest { name }) => { let mut outcome = None; let mut send_back = ListenerToDialerMessage::NotAvailable; for supported in &protocols { if name.as_ref() == supported.as_ref() { send_back = ListenerToDialerMessage::ProtocolAck { name: supported.clone() }; outcome = Some(supported); break; } } trace!("requested: {:?}, supported: {}", name, outcome.is_some()); let sender = listener.send(send_back); self.inner = ListenerSelectState::Outgoing { sender, protocols, outcome } } None => { debug!("no protocol request received"); return Err(ProtocolChoiceError::NoProtocolFound) } } } ListenerSelectState::Outgoing { mut sender, protocols, outcome } => { let listener = match sender.poll()? { Async::Ready(l) => l, Async::NotReady => { self.inner = ListenerSelectState::Outgoing { sender, protocols, outcome }; return Ok(Async::NotReady) } }; if let Some(p) = outcome { return Ok(Async::Ready((p, listener.into_inner(), protocols))) } else { let stream = listener.into_future(); self.inner = ListenerSelectState::Incoming { stream, protocols } } } ListenerSelectState::Undefined => panic!("ListenerSelectState::poll called after completion") } } } }
43.204301
104
0.536834
abc7aa2ad1bdc64f08edaf269f2ab6631ffc6fce
9,238
//! Panic runtime for Miri. //! //! The core pieces of the runtime are: //! - An implementation of `__rust_maybe_catch_panic` that pushes the invoked stack frame with //! some extra metadata derived from the panic-catching arguments of `__rust_maybe_catch_panic`. //! - A hack in `libpanic_unwind` that calls the `miri_start_panic` intrinsic instead of the //! target-native panic runtime. (This lives in the rustc repo.) //! - An implementation of `miri_start_panic` that stores its argument (the panic payload), and then //! immediately returns, but on the *unwind* edge (not the normal return edge), thus initiating unwinding. //! - A hook executed each time a frame is popped, such that if the frame pushed by `__rust_maybe_catch_panic` //! gets popped *during unwinding*, we take the panic payload and store it according to the extra //! metadata we remembered when pushing said frame. use log::trace; use rustc_middle::{mir, ty}; use rustc_target::spec::PanicStrategy; use crate::*; use helpers::check_arg_count; /// Holds all of the relevant data for when unwinding hits a `try` frame. #[derive(Debug)] pub struct CatchUnwindData<'tcx> { /// The `catch_fn` callback to call in case of a panic. catch_fn: Scalar<Tag>, /// The `data` argument for that callback. data: Scalar<Tag>, /// The return place from the original call to `try`. dest: PlaceTy<'tcx, Tag>, /// The return block from the original call to `try`. ret: mir::BasicBlock, } impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { /// Handles the special `miri_start_panic` intrinsic, which is called /// by libpanic_unwind to delegate the actual unwinding process to Miri. fn handle_miri_start_panic( &mut self, args: &[OpTy<'tcx, Tag>], unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); trace!("miri_start_panic: {:?}", this.frame().instance); // Make sure we only start unwinding when this matches our panic strategy. assert_eq!(this.tcx.sess.panic_strategy(), PanicStrategy::Unwind); // Get the raw pointer stored in arg[0] (the panic payload). let &[ref payload] = check_arg_count(args)?; let payload = this.read_scalar(payload)?.check_init()?; let thread = this.active_thread_mut(); assert!( thread.panic_payload.is_none(), "the panic runtime should avoid double-panics" ); thread.panic_payload = Some(payload); // Jump to the unwind block to begin unwinding. this.unwind_to_block(unwind); return Ok(()); } /// Handles the `try` intrinsic, the underlying implementation of `std::panicking::try`. fn handle_try( &mut self, args: &[OpTy<'tcx, Tag>], dest: &PlaceTy<'tcx, Tag>, ret: mir::BasicBlock, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); // Signature: // fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32 // Calls `try_fn` with `data` as argument. If that executes normally, returns 0. // If that unwinds, calls `catch_fn` with the first argument being `data` and // then second argument being a target-dependent `payload` (i.e. it is up to us to define // what that is), and returns 1. // The `payload` is passed (by libstd) to `__rust_panic_cleanup`, which is then expected to // return a `Box<dyn Any + Send + 'static>`. // In Miri, `miri_start_panic` is passed exactly that type, so we make the `payload` simply // a pointer to `Box<dyn Any + Send + 'static>`. // Get all the arguments. let &[ref try_fn, ref data, ref catch_fn] = check_arg_count(args)?; let try_fn = this.read_scalar(try_fn)?.check_init()?; let data = this.read_scalar(data)?.check_init()?; let catch_fn = this.read_scalar(catch_fn)?.check_init()?; // Now we make a function call, and pass `data` as first and only argument. let f_instance = this.memory.get_fn(try_fn)?.as_instance()?; trace!("try_fn: {:?}", f_instance); let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into(); this.call_function( f_instance, &[data.into()], Some(&ret_place), // Directly return to caller. StackPopCleanup::Goto { ret: Some(ret), unwind: None }, )?; // We ourselves will return `0`, eventually (will be overwritten if we catch a panic). this.write_null(dest)?; // In unwind mode, we tag this frame with the extra data needed to catch unwinding. // This lets `handle_stack_pop` (below) know that we should stop unwinding // when we pop this frame. if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind { this.frame_mut().extra.catch_unwind = Some(CatchUnwindData { catch_fn, data, dest: *dest, ret }); } return Ok(()); } fn handle_stack_pop( &mut self, mut extra: FrameData<'tcx>, unwinding: bool, ) -> InterpResult<'tcx, StackPopJump> { let this = self.eval_context_mut(); trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding); if let Some(stacked_borrows) = &this.memory.extra.stacked_borrows { stacked_borrows.borrow_mut().end_call(extra.call_id); } // We only care about `catch_panic` if we're unwinding - if we're doing a normal // return, then we don't need to do anything special. if let (true, Some(catch_unwind)) = (unwinding, extra.catch_unwind.take()) { // We've just popped a frame that was pushed by `try`, // and we are unwinding, so we should catch that. trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().instance); // We set the return value of `try` to 1, since there was a panic. this.write_scalar(Scalar::from_i32(1), &catch_unwind.dest)?; // The Thread's `panic_payload` holds what was passed to `miri_start_panic`. // This is exactly the second argument we need to pass to `catch_fn`. let payload = this.active_thread_mut().panic_payload.take().unwrap(); // Push the `catch_fn` stackframe. let f_instance = this.memory.get_fn(catch_unwind.catch_fn)?.as_instance()?; trace!("catch_fn: {:?}", f_instance); let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into(); this.call_function( f_instance, &[catch_unwind.data.into(), payload.into()], Some(&ret_place), // Directly return to caller of `try`. StackPopCleanup::Goto { ret: Some(catch_unwind.ret), unwind: None }, )?; // We pushed a new stack frame, the engine should not do any jumping now! Ok(StackPopJump::NoJump) } else { Ok(StackPopJump::Normal) } } /// Starta a panic in the interpreter with the given message as payload. fn start_panic( &mut self, msg: &str, unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); // First arg: message. let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into()); // Call the lang item. let panic = this.tcx.lang_items().panic_fn().unwrap(); let panic = ty::Instance::mono(this.tcx.tcx, panic); this.call_function( panic, &[msg.to_ref()], None, StackPopCleanup::Goto { ret: None, unwind }, ) } fn assert_panic( &mut self, msg: &mir::AssertMessage<'tcx>, unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { use rustc_middle::mir::AssertKind::*; let this = self.eval_context_mut(); match msg { BoundsCheck { index, len } => { // Forward to `panic_bounds_check` lang item. // First arg: index. let index = this.read_scalar(&this.eval_operand(index, None)?)?; // Second arg: len. let len = this.read_scalar(&this.eval_operand(len, None)?)?; // Call the lang item. let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap(); let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check); this.call_function( panic_bounds_check, &[index.into(), len.into()], None, StackPopCleanup::Goto { ret: None, unwind }, )?; } _ => { // Forward everything else to `panic` lang item. this.start_panic(msg.description(), unwind)?; } } Ok(()) } }
42.376147
110
0.602078
2176d04e26dbdb042fea25cff2e5c68342888c04
3,687
use crate::prelude::*; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::ShellTypeName; use nu_protocol::{ ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value, }; use nu_source::{Tag, Tagged}; use nu_value_ext::ValueExt; #[derive(Deserialize)] struct Arguments { pattern: Tagged<String>, rest: Vec<ColumnPath>, } pub struct SubCommand; #[async_trait] impl WholeStreamCommand for SubCommand { fn name(&self) -> &str { "str starts-with" } fn signature(&self) -> Signature { Signature::build("str starts-with") .required("pattern", SyntaxShape::String, "the pattern to match") .rest( SyntaxShape::ColumnPath, "optionally matches prefix of text by column paths", ) } fn usage(&self) -> &str { "checks if string starts with pattern" } async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { operate(args).await } fn examples(&self) -> Vec<Example> { vec![Example { description: "Checks if string starts with 'my' pattern", example: "echo 'my_library.rb' | str starts-with 'my'", result: Some(vec![UntaggedValue::boolean(true).into_untagged_value()]), }] } } async fn operate(args: CommandArgs) -> Result<OutputStream, ShellError> { let (Arguments { pattern, rest }, input) = args.process().await?; let column_paths: Vec<_> = rest; Ok(input .map(move |v| { if column_paths.is_empty() { ReturnSuccess::value(action(&v, &pattern, v.tag())?) } else { let mut ret = v; for path in &column_paths { let pattern = pattern.clone(); ret = ret.swap_data_by_column_path( path, Box::new(move |old| action(old, &pattern, old.tag())), )?; } ReturnSuccess::value(ret) } }) .to_output_stream()) } fn action(input: &Value, pattern: &str, tag: impl Into<Tag>) -> Result<Value, ShellError> { match &input.value { UntaggedValue::Primitive(Primitive::String(s)) => { let starts_with = s.starts_with(pattern); Ok(UntaggedValue::boolean(starts_with).into_value(tag)) } other => { let got = format!("got {}", other.type_name()); Err(ShellError::labeled_error( "value is not string", got, tag.into().span, )) } } } #[cfg(test)] mod tests { use super::ShellError; use super::{action, SubCommand}; use nu_protocol::UntaggedValue; use nu_source::Tag; use nu_test_support::value::string; #[test] fn examples_work_as_expected() -> Result<(), ShellError> { use crate::examples::test as test_examples; Ok(test_examples(SubCommand {})?) } #[test] fn str_starts_with_pattern() { let word = string("Cargo.toml"); let pattern = "Car"; let expected = UntaggedValue::boolean(true).into_untagged_value(); let actual = action(&word, &pattern, Tag::unknown()).unwrap(); assert_eq!(actual, expected); } #[test] fn str_does_not_start_with_pattern() { let word = string("Cargo.toml"); let pattern = ".toml"; let expected = UntaggedValue::boolean(false).into_untagged_value(); let actual = action(&word, &pattern, Tag::unknown()).unwrap(); assert_eq!(actual, expected); } }
28.804688
91
0.567941
8716ab468253dada89df03c4fbdd493aaa295b45
3,945
#[macro_use] extern crate nom; /* Italics *italics* or _italics_ Bold **bold** Underline italics __*underline italics*__ Underline bold __**underline bold**__ Bold Italics ***bold italics*** underline bold italics __***underline bold italics***__ Underline __underline__ Strikethrough ~~Strikethrough~~ */ use nom::anychar; use nom::types::CompleteStr; // TODO: Support nested styles #[derive(Debug, PartialEq)] pub enum Style { Text(String), Code(String), Bold(String), Italic(String), BoldItalics(String), Underline(String), UnderlineBold(String), UnderlineItalics(String), UnderlineBoldItalics(String), Strikethrough(String), } use self::Style::*; named!(code<CompleteStr, Style>, map!( delimited!(tag!("`"), take_until!("`"), tag!("`")), |text| Code(text.0.to_owned()) ) ); named!(star_italic<CompleteStr, Style>, map!( delimited!(tag!("*"), take_until!("*"), tag!("*")), |text| Italic(text.0.to_owned()) ) ); named!(underscore_italic<CompleteStr, Style>, map!( delimited!(tag!("_"), take_until!("_"), tag!("_")), |text| Italic(text.0.to_owned()) ) ); named!(italic<CompleteStr, Style>, alt_complete!(star_italic | underscore_italic) ); named!(bold<CompleteStr, Style>, map!( delimited!(tag!("**"), take_until!("**"), tag!("**")), |text| Bold(text.0.to_owned()) ) ); named!(underline<CompleteStr, Style>, map!( delimited!(tag!("__"), take_until!("__"), tag!("__")), |text| Underline(text.0.to_owned()) ) ); named!(strikethrough<CompleteStr, Style>, map!( delimited!(tag!("~~"), take_until!("~~"), tag!("~~")), |text| Strikethrough(text.0.to_owned()) ) ); named!(styled<CompleteStr, Style>, alt!(bold | underline | italic | strikethrough | code)); named!(maybe_style<CompleteStr, Style>, alt!( styled | map!( many_till!(call!(anychar), alt!(recognize!(peek!(styled)) | eof!())), |chars| Text(chars.0.iter().collect()) ) ) ); named!(text<CompleteStr, Vec<Style>>, many0!(maybe_style) ); pub fn parse_msg(msg: &str) -> Option<Vec<Style>> { match text(CompleteStr(msg)) { Ok((_, msg)) => Some(msg), _ => None, } } #[cfg(test)] mod test { use super::*; macro_rules! style { ($style:ident($text:tt)) => { $style($text.to_owned()) }; } macro_rules! parse { ($parser:ident($str:tt)) => { $parser(CompleteStr($str)).unwrap().1 }; } #[test] fn italic_underline() { assert_eq!(parse!(italic("_italic_")), style!(Italic("italic"))); } #[test] fn italic_star() { assert_eq!(parse!(italic("*italic*")), style!(Italic("italic"))); } #[test] fn bold_test() { assert_eq!(parse!(bold("**bold**")), style!(Bold("bold"))); } #[test] fn underline_test() { assert_eq!( parse!(underline("__underline__")), style!(Underline("underline")), ); } #[test] fn strikethrough_test() { assert_eq!( parse!(strikethrough("~~strikethrough~~")), style!(Strikethrough("strikethrough")), ); } #[test] fn variety() { assert_eq!( parse!(text( "_italic_ **bold** *italic* __underline__ ~~strikethrough~~" )), [ style!(Italic("italic")), style!(Text(" ")), style!(Bold("bold")), style!(Text(" ")), style!(Italic("italic")), style!(Text(" ")), style!(Underline("underline")), style!(Text(" ")), style!(Strikethrough("strikethrough")), ] ); } }
23.070175
91
0.52294
508bfa02c76094067947d5ea4a8f66f2331a615a
5,538
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use common_tracing::tracing; use headers::authorization::Basic; use headers::authorization::Bearer; use headers::authorization::Credentials; use http::header::AUTHORIZATION; use poem::error::Error as PoemError; use poem::error::Result as PoemResult; use poem::http::StatusCode; use poem::Addr; use poem::Endpoint; use poem::Middleware; use poem::Request; use super::v1::HttpQueryContext; use crate::servers::HttpHandlerKind; use crate::sessions::SessionManager; use crate::sessions::SessionType; use crate::users::auth::auth_mgr::Credential; pub struct HTTPSessionMiddleware { pub kind: HttpHandlerKind, pub session_manager: Arc<SessionManager>, } fn get_credential(req: &Request, kind: HttpHandlerKind) -> Result<Credential> { let auth_headers: Vec<_> = req.headers().get_all(AUTHORIZATION).iter().collect(); if auth_headers.len() > 1 { let msg = &format!("Multiple {} headers detected", AUTHORIZATION); return Err(ErrorCode::AuthenticateFailure(msg)); } let client_ip = match req.remote_addr().0 { Addr::SocketAddr(addr) => Some(addr.ip().to_string()), Addr::Custom(..) => Some("127.0.0.1".to_string()), _ => None, }; if auth_headers.is_empty() { if let HttpHandlerKind::Clickhouse = kind { let (user, key) = ( req.headers().get("X-CLICKHOUSE-USER"), req.headers().get("X-CLICKHOUSE-KEY"), ); if let (Some(name), Some(password)) = (user, key) { let c = Credential::Password { name: String::from_utf8(name.as_bytes().to_vec()).unwrap(), password: Some(password.as_bytes().to_vec()), hostname: client_ip, }; return Ok(c); } } return Err(ErrorCode::AuthenticateFailure( "No authorization header detected", )); } let value = auth_headers[0]; if value.as_bytes().starts_with(b"Basic ") { match Basic::decode(value) { Some(basic) => { let name = basic.username().to_string(); let password = basic.password().to_owned().as_bytes().to_vec(); let password = (!password.is_empty()).then_some(password); let c = Credential::Password { name, password, hostname: client_ip, }; Ok(c) } None => Err(ErrorCode::AuthenticateFailure("bad Basic auth header")), } } else if value.as_bytes().starts_with(b"Bearer ") { match Bearer::decode(value) { Some(bearer) => Ok(Credential::Jwt { token: bearer.token().to_string(), hostname: client_ip, }), None => Err(ErrorCode::AuthenticateFailure("bad Bearer auth header")), } } else { Err(ErrorCode::AuthenticateFailure("bad auth header")) } } impl<E: Endpoint> Middleware<E> for HTTPSessionMiddleware { type Output = HTTPSessionEndpoint<E>; fn transform(&self, ep: E) -> Self::Output { HTTPSessionEndpoint { kind: self.kind, ep, manager: self.session_manager.clone(), } } } pub struct HTTPSessionEndpoint<E> { pub kind: HttpHandlerKind, ep: E, manager: Arc<SessionManager>, } impl<E> HTTPSessionEndpoint<E> { async fn auth(&self, req: &Request) -> Result<HttpQueryContext> { let credential = get_credential(req, self.kind)?; let session = self.manager.create_session(SessionType::Dummy).await?; let (tenant_id, user_info) = session .create_query_context() .await? .get_auth_manager() .auth(&credential) .await?; session.set_current_user(user_info); if let Some(tenant_id) = tenant_id { session.set_current_tenant(tenant_id); } Ok(HttpQueryContext::new(self.manager.clone(), session)) } } #[poem::async_trait] impl<E: Endpoint> Endpoint for HTTPSessionEndpoint<E> { type Output = E::Output; async fn call(&self, mut req: Request) -> PoemResult<Self::Output> { tracing::debug!("receive http request: {:?},", req); let res = match self.auth(&req).await { Ok(ctx) => { req.extensions_mut().insert(ctx); self.ep.call(req).await } Err(err) => Err(PoemError::from_string( err.message(), StatusCode::UNAUTHORIZED, )), }; if let Err(ref err) = res { tracing::warn!( "http request error: status={}, msg={}", err.as_response().status(), err, ); }; res } }
33.768293
85
0.58541