-------------------------------------------------------------------------------- I1 cache: 65536 B, 64 B, 4-way associative D1 cache: 32768 B, 64 B, 8-way associative LL cache: 67108864 B, 64 B, 64-way associative Command: /usr/home/liquid/.rustup/toolchains/w-profiling/bin/rustc --crate-name pear --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 --cfg feature="color" --cfg feature="default" --cfg feature="yansi" -C metadata=f7f54c2f0c982ff9 -C extra-filename=-f7f54c2f0c982ff9 --out-dir /usr/home/liquid/tmp/.tmpy0OUwB/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpy0OUwB/target/debug/deps --extern inlinable_string=/usr/home/liquid/tmp/.tmpy0OUwB/target/debug/deps/libinlinable_string-24deb41577240876.rmeta --extern pear_codegen=/usr/home/liquid/tmp/.tmpy0OUwB/target/debug/deps/libpear_codegen-4f4b97b7cedd4ecf.so --extern yansi=/usr/home/liquid/tmp/.tmpy0OUwB/target/debug/deps/libyansi-19d320b83db24862.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-pear-0.2.3-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 4,608,626,586 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 158,500,507 ( 3.44%) ./malloc/malloc.c:_int_free 99,560,778 ( 2.16%) ./malloc/malloc.c:_int_malloc 94,862,493 ( 2.06%) ./malloc/malloc.c:malloc 93,057,161 ( 2.02%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 71,697,322 ( 1.56%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 50,547,749 ( 1.10%) ./malloc/malloc.c:free 33,744,486 ( 0.73%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 30,789,660 ( 0.67%) ./elf/../elf/dl-tls.c:_dl_update_slotinfo 30,698,173 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs:> as proc_macro::bridge::server::DispatcherTrait>::dispatch 22,865,333 ( 0.50%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 21,270,348 ( 0.46%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 20,536,482 ( 0.45%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 20,138,921 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 20,071,001 ( 0.44%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 19,868,096 ( 0.43%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 19,289,461 ( 0.42%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 18,007,195 ( 0.39%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 16,763,331 ( 0.36%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 16,543,818 ( 0.36%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 16,348,501 ( 0.35%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 15,547,246 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:core::str::traits::::eq 14,813,590 ( 0.32%) ./malloc/malloc.c:malloc_consolidate 14,045,652 ( 0.30%) ./elf/dl-lookup.c:do_lookup_x 13,070,700 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::decode 13,062,280 ( 0.28%) ./elf/../elf/dl-tls.c:update_get_addr 12,697,322 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 12,445,180 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs:<[A] as core::slice::cmp::SlicePartialEq>::equal 12,390,449 ( 0.27%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 12,365,103 ( 0.27%) ???:llvm::MCExpr::evaluateAsRelocatableImpl(llvm::MCValue&, llvm::MCAssembler const*, llvm::MCAsmLayout const*, llvm::MCFixup const*, llvm::DenseMap, llvm::detail::DenseMapPair > const*, bool) const 12,101,749 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 11,299,019 ( 0.25%) ./malloc/malloc.c:realloc 10,902,003 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 10,797,436 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::iterator::Iterator>::next 10,569,793 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 10,562,350 ( 0.23%) ./malloc/malloc.c:unlink_chunk.constprop.0 10,426,768 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 10,390,732 ( 0.23%) ./elf/../sysdeps/x86_64/tls_get_addr.S:__tls_get_addr 10,324,344 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs: as proc_macro::bridge::rpc::DecodeMut>::decode 10,256,494 ( 0.22%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 10,172,939 ( 0.22%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.86/src/token.rs:syn::token::parsing::peek_punct 9,997,078 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 9,705,212 ( 0.21%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 9,688,786 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:core::cmp::impls:: for &A>::eq 9,479,606 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 9,470,916 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 9,415,854 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::guaranteed_eq 9,275,728 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 9,056,558 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 9,029,094 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 8,891,199 ( 0.19%) ???:(anonymous namespace)::VarLocBasedLDV::process(llvm::MachineInstr&, (anonymous namespace)::VarLocBasedLDV::OpenRangesSet&, (anonymous namespace)::VarLocBasedLDV::VarLocMap&, llvm::SmallVector<(anonymous namespace)::VarLocBasedLDV::TransferDebugPair, 4u>&) 8,743,293 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::is_null 8,418,592 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 8,404,840 ( 0.18%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 8,344,956 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 8,263,428 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 8,242,050 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:alloc::raw_vec::RawVec::current_memory 8,210,482 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::mem::replace 8,079,125 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs:core::ptr::non_null::NonNull::as_ptr 7,868,282 ( 0.17%) ./malloc/malloc.c:_int_realloc 7,861,534 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 7,785,852 ( 0.17%) ???:llvm::TargetRegisterInfo::checkAllSuperRegsMarked(llvm::BitVector const&, llvm::ArrayRef) const 7,764,110 ( 0.17%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 7,599,767 ( 0.16%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 7,438,844 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 7,366,282 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 7,266,180 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs:core::slice::cmp:: for [A]>::eq 7,223,239 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 7,202,754 ( 0.16%) ???:llvm::TargetRegisterInfo::shouldRealignStack(llvm::MachineFunction const&) const 7,098,318 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 7,010,679 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 6,928,119 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter.rs:core::slice::iter::Iter::new 6,905,791 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::read 6,847,243 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs: as core::ops::try_trait::Try>::branch 6,753,753 ( 0.15%) ???:(anonymous namespace)::Verifier::verifyFunctionAttrs(llvm::FunctionType*, llvm::AttributeList, llvm::Value const*, bool) 6,619,357 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/enumerate.rs: as core::iter::traits::iterator::Iterator>::next 6,618,475 ( 0.14%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 6,574,032 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 6,539,353 ( 0.14%) ???:(anonymous namespace)::Verifier::visitCallBase(llvm::CallBase&) 6,511,258 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:core::str::converts::from_utf8 6,476,763 ( 0.14%) ???:llvm::SmallSet >::insert(llvm::Register const&) 6,432,780 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 6,337,054 ( 0.14%) ???:llvm::MCAsmLayout::getSymbolOffset(llvm::MCSymbol const&) const 6,298,348 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs:core::ptr::const_ptr::::guaranteed_eq 6,078,645 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:core::option::Option::map 6,075,550 ( 0.13%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 6,054,612 ( 0.13%) ???:(anonymous namespace)::Verifier::verify(llvm::Function const&) [clone .llvm.4153962086227604281] 6,050,816 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 6,026,372 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.86/src/ident.rs:syn::ident::accept_as_ident 6,019,456 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 5,848,466 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs:core::ptr::const_ptr::::is_null 5,773,915 ( 0.13%) ???:(anonymous namespace)::TwoAddressInstructionPass::runOnMachineFunction(llvm::MachineFunction&) 5,752,570 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.86/src/buffer.rs:syn::buffer::Cursor::punct 5,733,752 ( 0.12%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 5,726,049 ( 0.12%) ???:llvm::MCAsmLayout::getFragmentOffset(llvm::MCFragment const*) const 5,722,886 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::_intern_substs 5,644,419 ( 0.12%) ???:(anonymous namespace)::X86MCCodeEmitter::emitPrefixImpl(unsigned int&, llvm::MCInst const&, llvm::MCSubtargetInfo const&, llvm::raw_ostream&) const 5,575,119 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::fold_ty 5,507,470 ( 0.12%) ???:multikeySort(llvm::MutableArrayRef*>, int) 5,476,848 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 5,393,670 ( 0.12%) ???:llvm::FoldingSetBase::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&, llvm::FoldingSetBase::FoldingSetInfo const&) 5,393,625 ( 0.12%) ./malloc/malloc.c:calloc 5,383,618 ( 0.12%) ???:llvm::FoldingSetNodeID::AddInteger(unsigned int) 5,307,505 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs: as core::ops::try_trait::Try>::branch 5,262,086 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 5,127,928 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>>::insert_recursing 5,109,575 ( 0.11%) ???:??? 5,100,766 ( 0.11%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 5,088,040 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 5,075,476 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 5,055,701 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 5,052,543 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs:core::ptr::non_null::NonNull::new_unchecked 4,990,032 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 4,945,371 ( 0.11%) ???:llvm::MetadataTracking::track(void*, llvm::Metadata&, llvm::PointerUnion) 4,877,072 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 4,854,093 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 4,805,498 ( 0.10%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 4,783,768 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:core::str::traits::::eq 4,735,458 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs: as core::convert::From<&mut _>>::from::call::, proc_macro::bridge::buffer::Buffer, ::run_bridge_and_client proc_macro::TokenStream, proc_macro::bridge::server::Dispatcher>>::{closure#0}> 4,665,100 ( 0.10%) ./elf/../sysdeps/x86_64/dl-tls.c:__tls_get_addr_slow 4,611,625 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:core::cell::Cell::replace -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . . impl<'a, T> $name<'a, T> { . // Helper function for creating a slice from the iterator. . #[inline(always)] . fn make_slice(&self) -> &'a [T] { . // SAFETY: the iterator was created from a slice with pointer . // `self.ptr` and length `len!(self)`. This guarantees that all . // the prerequisites for `from_raw_parts` are fulfilled. 582,381 ( 0.01%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { 1,131,198 ( 0.02%) let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 2,054,480 ( 0.04%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; 188,533 ( 0.00%) old . } 377,066 ( 0.01%) } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 107,901 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; 30,338 ( 0.00%) self.end . } 30,338 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 219,999 ( 0.00%) len!(self) 7,742 ( 0.00%) } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> Iterator for $name<'a, T> { . type Item = $elem; . . #[inline] 690,315 ( 0.01%) fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 1,155,325 ( 0.03%) assume(!self.ptr.as_ptr().is_null()); 1,150,525 ( 0.02%) if mem::size_of::() != 0 { 502,774 ( 0.01%) assume(!self.end.is_null()); . } 49,220,490 ( 1.07%) if is_empty!(self) { 41,572 ( 0.00%) None . } else { 377,078 ( 0.01%) Some(next_unchecked!(self)) . } . } 690,315 ( 0.01%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 1,394,479 ( 0.03%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 24,166 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 4,635 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 10,941 ( 0.00%) while let Some(x) = self.next() { 17,732 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] 40 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 371,142 ( 0.01%) while let Some(x) = self.next() { 606,876 ( 0.01%) if f(x) { . return true; . } . } . false 40 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] 43,256 ( 0.00%) fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 165,619 ( 0.00%) while let Some(x) = self.next() { 63,967 ( 0.00%) if predicate(&x) { 382 ( 0.00%) return Some(x); . } . } 8,422 ( 0.00%) None 27,630 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 63,132 ( 0.00%) while let Some(x) = self.next() { 173,164 ( 0.00%) if let Some(y) = f(x) { 22,762 ( 0.00%) return Some(y); . } . } . None 4,615 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . #[rustc_inherit_overflow_checks] . fn position

(&mut self, mut predicate: P) -> Option where . Self: Sized, . P: FnMut(Self::Item) -> bool, . { . let n = len!(self); . let mut i = 0; . while let Some(x) = self.next() { 174,035 ( 0.00%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 42,541 ( 0.00%) while let Some(x) = self.next_back() { 563,170 ( 0.01%) i -= 1; 462,606 ( 0.01%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 121,842 ( 0.00%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } . } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] 45,723 ( 0.00%) fn next_back(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { 62,951 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); 76,205 ( 0.00%) if mem::size_of::() != 0 { 32,491 ( 0.00%) assume(!self.end.is_null()); . } 1,157,190 ( 0.03%) if is_empty!(self) { 72 ( 0.00%) None . } else { 30,338 ( 0.00%) Some(next_back_unchecked!(self)) . } . } 45,723 ( 0.00%) } . . #[inline] . fn nth_back(&mut self, n: usize) -> Option<$elem> { . if n >= len!(self) { . // This iterator is now empty. . self.end = self.ptr.as_ptr(); . return None; . } -- line 375 ---------------------------------------- 10,109,175 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . /// ``` . /// let mut s = [1, 2, 3]; . /// let ptr: *mut u32 = s.as_mut_ptr(); . /// assert!(!ptr.is_null()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")] . #[inline] 2,690,244 ( 0.06%) pub const fn is_null(self) -> bool { . // Compare via a cast to a thin pointer, so fat pointers are only . // considering their "data" part for null-ness. 2,690,244 ( 0.06%) (self as *mut u8).guaranteed_eq(null_mut()) 2,690,244 ( 0.06%) } . . /// Casts to a pointer of another type. . #[stable(feature = "ptr_cast", since = "1.38.0")] . #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")] . #[inline(always)] . pub const fn cast(self) -> *mut U { . self as _ . } -- line 48 ---------------------------------------- -- line 299 ---------------------------------------- . #[inline(always)] . pub const unsafe fn offset(self, count: isize) -> *mut T . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . // The obtained pointer is valid for writes since the caller must . // guarantee that it points to the same allocated object as `self`. 21,328,493 ( 0.46%) unsafe { intrinsics::offset(self, count) as *mut T } . } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety . /// -- line 315 ---------------------------------------- -- line 360 ---------------------------------------- . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const fn wrapping_offset(self, count: isize) -> *mut T . where . T: Sized, . { . // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called. 642 ( 0.00%) unsafe { intrinsics::arith_offset(self, count) as *mut T } . } . . /// Returns `None` if the pointer is null, or else returns a unique reference to . /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`] . /// must be used instead. . /// . /// For the shared counterpart see [`as_ref`]. . /// -- line 376 ---------------------------------------- -- line 492 ---------------------------------------- . /// affect the outcome, but just the performance. . /// The consequences of using this method to make runtime and compile-time code behave . /// differently have not been explored. This method should not be used to introduce such . /// differences, and it should also not be stabilized before we have a better understanding . /// of this issue. . #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[inline] 2,017,683 ( 0.04%) pub const fn guaranteed_eq(self, other: *mut T) -> bool . where . T: Sized, . { 4,042,474 ( 0.09%) intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _) 2,690,244 ( 0.06%) } . . /// Returns whether two pointers are guaranteed to be unequal. . /// . /// At runtime this function behaves like `self != other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine the inequality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be unequal. . /// But when it returns `true`, the pointers are guaranteed to be unequal. -- line 513 ---------------------------------------- -- line 1055 ---------------------------------------- . /// . /// See [`ptr::drop_in_place`] for safety concerns and examples. . /// . /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place() . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[inline(always)] . pub unsafe fn drop_in_place(self) { . // SAFETY: the caller must uphold the safety contract for `drop_in_place`. 1,066 ( 0.00%) unsafe { drop_in_place(self) } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// See [`ptr::write`] for safety concerns and examples. . /// . /// [`ptr::write`]: crate::ptr::write() -- line 1071 ---------------------------------------- -- line 1072 ---------------------------------------- . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")] . #[inline(always)] . pub const unsafe fn write(self, val: T) . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `write`. 5,061 ( 0.00%) unsafe { write(self, val) } . } . . /// Invokes memset on the specified pointer, setting `count * size_of::()` . /// bytes of memory starting at `self` to `val`. . /// . /// See [`ptr::write_bytes`] for safety concerns and examples. . /// . /// [`ptr::write_bytes`]: crate::ptr::write_bytes() -- line 1088 ---------------------------------------- -- line 1416 ---------------------------------------- . } . } . . // Equality for pointers . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for *mut T { . #[inline(always)] . fn eq(&self, other: &*mut T) -> bool { 36,762 ( 0.00%) *self == *other . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for *mut T {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for *mut T { -- line 1432 ---------------------------------------- 1,639,131 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter.rs -------------------------------------------------------------------------------- Ir -- line 79 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Sync for Iter<'_, T> {} . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Send for Iter<'_, T> {} . . impl<'a, T> Iter<'a, T> { . #[inline] 839,772 ( 0.02%) pub(super) fn new(slice: &'a [T]) -> Self { 629,829 ( 0.01%) let ptr = slice.as_ptr(); . // SAFETY: Similar to `IterMut::new`. . unsafe { 209,943 ( 0.00%) assume(!ptr.is_null()); . 1,049,715 ( 0.02%) let end = if mem::size_of::() == 0 { . (ptr as *const u8).wrapping_add(slice.len()) as *const T . } else { 209,943 ( 0.00%) ptr.add(slice.len()) . }; . 1,503,049 ( 0.03%) Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData } . } 839,772 ( 0.02%) } . . /// Views the underlying data as a subslice of the original data. . /// . /// This has the same lifetime as the original slice, and so the . /// iterator can continue to be used while this exists. . /// . /// # Examples . /// -- line 109 ---------------------------------------- -- line 121 ---------------------------------------- . /// . /// // Next, we move to the second element of the slice: . /// iter.next(); . /// // Now `as_slice` returns "[2, 3]": . /// println!("{:?}", iter.as_slice()); . /// ``` . #[must_use] . #[stable(feature = "iter_to_slice", since = "1.4.0")] 78,088 ( 0.00%) pub fn as_slice(&self) -> &'a [T] { 28,120 ( 0.00%) self.make_slice() 39,044 ( 0.00%) } . } . . iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, { . fn is_sorted_by(self, mut compare: F) -> bool . where . Self: Sized, . F: FnMut(&Self::Item, &Self::Item) -> Option, . { -- line 139 ---------------------------------------- -- line 141 ---------------------------------------- . compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false) . }) . } . }} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Iter<'_, T> { . fn clone(&self) -> Self { 36,341 ( 0.00%) Iter { ptr: self.ptr, end: self.end, _marker: self._marker } . } . } . . #[stable(feature = "slice_iter_as_ref", since = "1.13.0")] . impl AsRef<[T]> for Iter<'_, T> { . fn as_ref(&self) -> &[T] { . self.as_slice() . } -- line 157 ---------------------------------------- -- line 199 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Sync for IterMut<'_, T> {} . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Send for IterMut<'_, T> {} . . impl<'a, T> IterMut<'a, T> { . #[inline] 12,720 ( 0.00%) pub(super) fn new(slice: &'a mut [T]) -> Self { 9,540 ( 0.00%) let ptr = slice.as_mut_ptr(); . // SAFETY: There are several things here: . // . // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid . // reference thus it is non-NUL and safe to use and pass to . // `NonNull::new_unchecked` . . // . // Adding `slice.len()` to the starting pointer gives a pointer . // at the end of `slice`. `end` will never be dereferenced, only checked -- line 216 ---------------------------------------- -- line 218 ---------------------------------------- . // done. . // . // In the case of a ZST, the end pointer is just the start pointer plus . // the length, to also allows for the fast `ptr == end` check. . // . // See the `next_unchecked!` and `is_empty!` macros as well as the . // `post_inc_start` method for more information. . unsafe { 3,180 ( 0.00%) assume(!ptr.is_null()); . 15,900 ( 0.00%) let end = if mem::size_of::() == 0 { . (ptr as *mut u8).wrapping_add(slice.len()) as *mut T . } else { 3,180 ( 0.00%) ptr.add(slice.len()) . }; . 29,274 ( 0.00%) Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData } . } 12,720 ( 0.00%) } . . /// Views the underlying data as a subslice of the original data. . /// . /// To avoid creating `&mut` references that alias, this is forced . /// to consume the iterator. . /// . /// # Examples . /// -- line 244 ---------------------------------------- -- line 1711 ---------------------------------------- . v: &'a [T], . rem: &'a [T], . chunk_size: usize, . } . . impl<'a, T> ChunksExact<'a, T> { . #[inline] . pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self { 34 ( 0.00%) let rem = slice.len() % chunk_size; 51 ( 0.00%) let fst_len = slice.len() - rem; . // SAFETY: 0 <= fst_len <= slice.len() by construction above . let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) }; . Self { v: fst, rem: snd, chunk_size } . } . . /// Returns the remainder of the original slice that is not going to be . /// returned by the iterator. The returned slice has at most `chunk_size-1` . /// elements. -- line 1728 ---------------------------------------- -- line 1742 ---------------------------------------- . } . . #[stable(feature = "chunks_exact", since = "1.31.0")] . impl<'a, T> Iterator for ChunksExact<'a, T> { . type Item = &'a [T]; . . #[inline] . fn next(&mut self) -> Option<&'a [T]> { 2,372 ( 0.00%) if self.v.len() < self.chunk_size { . None . } else { . let (fst, snd) = self.v.split_at(self.chunk_size); . self.v = snd; . Some(fst) . } . } . -- line 1758 ---------------------------------------- -- line 2024 ---------------------------------------- . num: usize, . marker: PhantomData<&'a [T; N]>, . } . . impl<'a, T: 'a, const N: usize> ArrayWindows<'a, T, N> { . #[inline] . pub(super) fn new(slice: &'a [T]) -> Self { . let num_windows = slice.len().saturating_sub(N - 1); 42 ( 0.00%) Self { slice_head: slice.as_ptr(), num: num_windows, marker: PhantomData } . } . } . . #[unstable(feature = "array_windows", issue = "75027")] . impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> { . type Item = &'a [T; N]; . . #[inline] . fn next(&mut self) -> Option { 22,462 ( 0.00%) if self.num == 0 { . return None; . } . // SAFETY: . // This is safe because it's indexing into a slice guaranteed to be length > N. . let ret = unsafe { &*self.slice_head.cast::<[T; N]>() }; . // SAFETY: Guaranteed that there are at least 1 item remaining otherwise . // earlier branch would've been hit . self.slice_head = unsafe { self.slice_head.add(1) }; -- line 2050 ---------------------------------------- 2,115,207 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs -------------------------------------------------------------------------------- Ir -- line 4 ---------------------------------------- . . use super::Utf8Error; . . /// Returns the initial codepoint accumulator for the first byte. . /// The first byte is special, only want bottom 5 bits for width 2, 4 bits . /// for width 3, and 3 bits for width 4. . #[inline] . const fn utf8_first_byte(byte: u8, width: u32) -> u32 { 114 ( 0.00%) (byte & (0x7F >> width)) as u32 . } . . /// Returns the value of `ch` updated with continuation byte `byte`. . #[inline] . const fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { 342 ( 0.00%) (ch << 6) | (byte & CONT_MASK) as u32 . } . . /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the . /// bits `10`). . #[inline] . pub(super) const fn utf8_is_cont_byte(byte: u8) -> bool { . (byte as i8) < -64 . } -- line 26 ---------------------------------------- -- line 28 ---------------------------------------- . /// Reads the next code point out of a byte iterator (assuming a . /// UTF-8-like encoding). . /// . /// # Safety . /// . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[unstable(feature = "str_internals", issue = "none")] . #[inline] 477,609 ( 0.01%) pub unsafe fn next_code_point<'a, I: Iterator>(bytes: &mut I) -> Option { . // Decode UTF-8 2,649,214 ( 0.06%) let x = *bytes.next()?; 1,114,978 ( 0.02%) if x < 128 { 455,316 ( 0.01%) return Some(x as u32); . } . . // Multibyte case follows . // Decode from a byte combination out of: [[[x y] z] w] . // NOTE: Performance is sensitive to the exact formulation here . let init = utf8_first_byte(x, 2); . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let y = unsafe { *bytes.next().unwrap_unchecked() }; . let mut ch = utf8_acc_cont_byte(init, y); 114 ( 0.00%) if x >= 0xE0 { . // [[x y z] w] case . // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let z = unsafe { *bytes.next().unwrap_unchecked() }; . let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z); . ch = init << 12 | y_z; 114 ( 0.00%) if x >= 0xF0 { . // [x y z w] case . // use only the lower 3 bits of `init` . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let w = unsafe { *bytes.next().unwrap_unchecked() }; . ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w); . } . } . . Some(ch) 796,015 ( 0.02%) } . . /// Reads the last code point out of a byte iterator (assuming a . /// UTF-8-like encoding). . /// . /// # Safety . /// . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[inline] 22,524 ( 0.00%) pub(super) unsafe fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option . where . I: DoubleEndedIterator, . { . // Decode UTF-8 90,096 ( 0.00%) let w = match *bytes.next_back()? { 67,069 ( 0.00%) next_byte if next_byte < 128 => return Some(next_byte as u32), . back_byte => back_byte, . }; . . // Multibyte case follows . // Decode from a byte combination out of: [x [y [z w]]] . let mut ch; . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. -- line 93 ---------------------------------------- -- line 105 ---------------------------------------- . ch = utf8_first_byte(x, 4); . ch = utf8_acc_cont_byte(ch, y); . } . ch = utf8_acc_cont_byte(ch, z); . } . ch = utf8_acc_cont_byte(ch, w); . . Some(ch) 37,540 ( 0.00%) } . . // use truncation to fit u64 into usize . const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize; . . /// Returns `true` if any byte in the word `x` is nonascii (>= 128). . #[inline] . const fn contains_nonascii(x: usize) -> bool { 14,179 ( 0.00%) (x & NONASCII_MASK) != 0 . } . . /// Walks through `v` checking that it's a valid UTF-8 sequence, . /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`. . #[inline(always)] . #[rustc_const_unstable(feature = "str_internals", issue = "none")] . pub(super) const fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { . let mut index = 0; . let len = v.len(); . . let usize_bytes = mem::size_of::(); . let ascii_block_size = 2 * usize_bytes; 287,847 ( 0.01%) let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 }; . let align = v.as_ptr().align_offset(usize_bytes); . 977,344 ( 0.02%) while index < len { . let old_offset = index; . macro_rules! err { . ($error_len: expr) => { . return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len }) . }; . } . . macro_rules! next { -- line 145 ---------------------------------------- -- line 148 ---------------------------------------- . // we needed data, but there was none: error! . if index >= len { . err!(None) . } . v[index] . }}; . } . 416,732 ( 0.01%) let first = v[index]; 833,464 ( 0.02%) if first >= 128 { . let w = utf8_char_width(first); . // 2-byte encoding is for codepoints \u{0080} to \u{07ff} . // first C2 80 last DF BF . // 3-byte encoding is for codepoints \u{0800} to \u{ffff} . // first E0 A0 80 last EF BF BF . // excluding surrogates codepoints \u{d800} to \u{dfff} . // ED A0 80 to ED BF BF . // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff -- line 165 ---------------------------------------- -- line 169 ---------------------------------------- . // . // https://tools.ietf.org/html/rfc3629 . // UTF8-1 = %x00-7F . // UTF8-2 = %xC2-DF UTF8-tail . // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / . // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) . // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / . // %xF4 %x80-8F 2( UTF8-tail ) 36 ( 0.00%) match w { . 2 => { . if next!() as i8 >= -64 { . err!(Some(1)) . } . } . 3 => { 72 ( 0.00%) match (first, next!()) { . (0xE0, 0xA0..=0xBF) 63 ( 0.00%) | (0xE1..=0xEC, 0x80..=0xBF) . | (0xED, 0x80..=0x9F) . | (0xEE..=0xEF, 0x80..=0xBF) => {} . _ => err!(Some(1)), . } 45 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(2)) . } . } . 4 => { . match (first, next!()) { . (0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {} . _ => err!(Some(1)), . } -- line 199 ---------------------------------------- -- line 201 ---------------------------------------- . err!(Some(2)) . } . if next!() as i8 >= -64 { . err!(Some(3)) . } . } . _ => err!(Some(1)), . } 27 ( 0.00%) index += 1; . } else { . // Ascii case, try to skip forward quickly. . // When the pointer is aligned, read 2 words of data per iteration . // until we find a word containing a non-ascii byte. 1,274,348 ( 0.03%) if align != usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 { . let ptr = v.as_ptr(); 76,706 ( 0.00%) while index < blocks_end { . // SAFETY: since `align - index` and `ascii_block_size` are . // multiples of `usize_bytes`, `block = ptr.add(index)` is . // always aligned with a `usize` so it's safe to dereference . // both `block` and `block.offset(1)`. . unsafe { . let block = ptr.add(index) as *const usize; . // break if there is a nonascii byte 14,179 ( 0.00%) let zu = contains_nonascii(*block); . let zv = contains_nonascii(*block.offset(1)); 28,358 ( 0.00%) if zu || zv { . break; . } . } 28,348 ( 0.00%) index += ascii_block_size; . } . // step from the point where the wordwise loop stopped 811,237 ( 0.02%) while index < len && v[index] < 128 { 172,708 ( 0.00%) index += 1; . } . } else { 392,544 ( 0.01%) index += 1; . } . } . } . . Ok(()) . } . . // https://tools.ietf.org/html/rfc3629 -- line 245 ---------------------------------------- -- line 263 ---------------------------------------- . 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F . ]; . . /// Given a first byte, determines how many bytes are in this UTF-8 character. . #[unstable(feature = "str_internals", issue = "none")] . #[must_use] . #[inline] . pub const fn utf8_char_width(b: u8) -> usize { 18 ( 0.00%) UTF8_CHAR_WIDTH[b as usize] as usize . } . . /// Mask of the value bits of a continuation byte. . const CONT_MASK: u8 = 0b0011_1111; . . // truncate `&str` to length at most equal to `max` . // return `true` if it were truncated, and the new str. . pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) { -- line 279 ---------------------------------------- 1,789,611 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 7,255,610 ( 0.16%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 5,441,706 ( 0.12%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 192,672 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 289,008 ( 0.01%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 1,862,059 ( 0.04%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 463,328 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 926,656 ( 0.02%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 1,024 ( 0.00%) fn clone(&self) -> Self { 1,773 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 299 ( 0.00%) table: self.table.clone(), . } 1,152 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } -- line 207 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 154,401 ( 0.00%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 331,943 ( 0.01%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 503,252 ( 0.01%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 2 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { 14,820 ( 0.00%) hash_builder.hash_one(val) 4 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 280 ---------------------------------------- . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { 354,372 ( 0.01%) hash_builder.hash_one(val) . } . . #[cfg(feature = "ahash")] . impl HashMap { . /// Creates an empty `HashMap`. . /// . /// The hash map is initially created with a capacity of 0, so it will not allocate until it . /// is first inserted into. -- line 296 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 200,275 ( 0.00%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 61 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 527 ---------------------------------------- . /// map.insert("c", 3); . /// . /// for key in map.keys() { . /// println!("{}", key); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn keys(&self) -> Keys<'_, K, V> { 6 ( 0.00%) Keys { inner: self.iter() } . } . . /// An iterator visiting all values in arbitrary order. . /// The iterator element type is `&'a V`. . /// . /// # Examples . /// . /// ``` -- line 543 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 14,017 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 69,343 ( 0.00%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 528 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 60 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 600 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 660 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 734,370 ( 0.02%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 943,359 ( 0.02%) if self.table.is_empty() { . None . } else { 1 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 438,972 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 552,810 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 179 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 1,761 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 358 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 587 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); 816 ( 0.00%) self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. . /// . /// Returns an array of length `N` with the results of each query. For soundness, at most one . /// mutable reference will be returned to any value. `None` will be returned if any of the . /// keys are duplicates or missing. -- line 1223 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,202,898 ( 0.07%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 2,981 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { 2 ( 0.00%) Some(mem::replace(item, v)) . } else { 1,480,813 ( 0.03%) self.table 1,459,236 ( 0.03%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 158,805 ( 0.00%) None . } 2,939,215 ( 0.06%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 60,337 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 725,509 ( 0.02%) match self.remove_entry(k) { 31,352 ( 0.00%) Some((_, v)) => Some(v), 49,531 ( 0.00%) None => None, . } 135,849 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 247,186 ( 0.01%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 2,753,672 ( 0.06%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 7,204,168 ( 0.16%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 7,737,511 ( 0.17%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 875,176 ( 0.02%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 4,579,644 ( 0.10%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 362,189 ( 0.01%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 1,361,086 ( 0.03%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 1,550,806 ( 0.03%) self.from_hash(hash, equivalent(k)) 2,446,863 ( 0.05%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 2,134,709 ( 0.05%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 595,342 ( 0.01%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,547 ( 0.00%) fn into_iter(self) -> IntoIter { 32,625 ( 0.00%) IntoIter { 16,854 ( 0.00%) inner: self.table.into_iter(), . } 4,641 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 135,178 ( 0.00%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 1,636 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 168 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 3,884 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 156 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 312 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 34 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 35,463 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 29,520 ( 0.00%) let iter = iter.into_iter(); 19,535 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 1,859 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 97,601 ( 0.00%) self.insert(k, v); . }); 23,307 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 2,765,324 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs -------------------------------------------------------------------------------- Ir -- line 221 ---------------------------------------- . NodeRef { height: 0, node: NonNull::from(Box::leak(leaf)), _marker: PhantomData } . } . } . . impl NodeRef { . fn new_internal(child: Root) -> Self { . let mut new_node = unsafe { InternalNode::new() }; . new_node.edges[0].write(child.node); 6,166 ( 0.00%) unsafe { NodeRef::from_new_internal(new_node, child.height + 1) } . } . . /// # Safety . /// `height` must not be zero. . unsafe fn from_new_internal(internal: Box>, height: usize) -> Self { . debug_assert!(height > 0); . let node = NonNull::from(Box::leak(internal)).cast(); . let mut this = NodeRef { height, node, _marker: PhantomData }; -- line 237 ---------------------------------------- -- line 269 ---------------------------------------- . impl NodeRef { . /// Finds the length of the node. This is the number of keys or values. . /// The number of edges is `len() + 1`. . /// Note that, despite being safe, calling this function can have the side effect . /// of invalidating mutable references that unsafe code has created. . pub fn len(&self) -> usize { . // Crucially, we only access the `len` field here. If BorrowType is marker::ValMut, . // there might be outstanding mutable references to values that we must not invalidate. 122,652 ( 0.00%) unsafe { usize::from((*Self::as_leaf_ptr(self)).len) } . } . . /// Returns the number of levels that the node and leaves are apart. Zero . /// height means the node is a leaf itself. If you picture trees with the . /// root on top, the number says at which elevation the node appears. . /// If you picture trees with leaves on top, the number says how high . /// the tree extends above the node. . pub fn height(&self) -> usize { . self.height . } . . /// Temporarily takes out another, immutable reference to the same node. . pub fn reborrow(&self) -> NodeRef, K, V, Type> { 992,136 ( 0.02%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Exposes the leaf portion of any leaf or internal node. . /// . /// Returns a raw ptr to avoid invalidating other references to this node. . fn as_leaf_ptr(this: &Self) -> *mut LeafNode { . // The node must be valid for at least the LeafNode portion. . // This is not a reference in the NodeRef type because we don't know if -- line 299 ---------------------------------------- -- line 314 ---------------------------------------- . /// both, upon success, do nothing. . pub fn ascend( . self, . ) -> Result, marker::Edge>, Self> { . assert!(BorrowType::PERMITS_TRAVERSAL); . // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut, . // there might be outstanding mutable references to values that we must not invalidate. . let leaf_ptr: *const _ = Self::as_leaf_ptr(&self); 153,630 ( 0.00%) unsafe { (*leaf_ptr).parent } . .as_ref() . .map(|parent| Handle { 42,787 ( 0.00%) node: NodeRef::from_internal(*parent, self.height + 1), 18,029 ( 0.00%) idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }, . _marker: PhantomData, . }) . .ok_or(self) . } . . pub fn first_edge(self) -> Handle { . unsafe { Handle::new_edge(self, 0) } . } -- line 334 ---------------------------------------- -- line 373 ---------------------------------------- . // SAFETY: there can be no mutable references into this tree borrowed as `Immut`. . unsafe { &*ptr } . } . . /// Borrows a view into the keys stored in the node. . pub fn keys(&self) -> &[K] { . let leaf = self.into_leaf(); . unsafe { 1,213,924 ( 0.03%) MaybeUninit::slice_assume_init_ref(leaf.keys.get_unchecked(..usize::from(leaf.len))) . } . } . } . . impl NodeRef { . /// Similar to `ascend`, gets a reference to a node's parent node, but also . /// deallocates the current node in the process. This is unsafe because the . /// current node will still be accessible despite being deallocated. -- line 389 ---------------------------------------- -- line 391 ---------------------------------------- . self, . ) -> Option, marker::Edge>> { . let height = self.height; . let node = self.node; . let ret = self.ascend().ok(); . unsafe { . Global.deallocate( . node.cast(), 47,169 ( 0.00%) if height > 0 { . Layout::new::>() . } else { . Layout::new::>() . }, . ); . } . ret . } -- line 407 ---------------------------------------- -- line 435 ---------------------------------------- . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } . } . } . . impl NodeRef { . /// Borrows exclusive access to the leaf portion of a dying leaf or internal node. . fn as_leaf_dying(&mut self) -> &mut LeafNode { 3 ( 0.00%) let ptr = Self::as_leaf_ptr(self); . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } . } . } . . impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { . /// Borrows exclusive access to an element of the key storage area. . /// -- line 451 ---------------------------------------- -- line 467 ---------------------------------------- . /// `index` is in bounds of 0..CAPACITY . unsafe fn val_area_mut(&mut self, index: I) -> &mut Output . where . I: SliceIndex<[MaybeUninit], Output = Output>, . { . // SAFETY: the caller will not be able to call further methods on self . // until the value slice reference is dropped, as we have unique access . // for the lifetime of the borrow. 190,303 ( 0.00%) unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { . /// Borrows exclusive access to an element or slice of the node's storage area for edge contents. . /// . /// # Safety . /// `index` is in bounds of 0..CAPACITY + 1 -- line 483 ---------------------------------------- -- line 534 ---------------------------------------- . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { . /// Sets the node's link to its parent edge, . /// without invalidating other references to the node. . fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) { . let leaf = Self::as_leaf_ptr(self); 11,255 ( 0.00%) unsafe { (*leaf).parent = Some(parent) }; . unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; . } . } . . impl NodeRef { . /// Clears the root's link to its parent edge. . fn clear_parent_link(&mut self) { . let mut root_node = self.borrow_mut(); . let leaf = root_node.as_leaf_mut(); 2,763 ( 0.00%) leaf.parent = None; . } . } . . impl NodeRef { . /// Returns a new owned tree, with its own root node that is initially empty. . pub fn new() -> Self { . NodeRef::new_leaf().forget_type() . } . . /// Adds a new internal node with a single edge pointing to the previous root node, . /// make that new node the root node, and return it. This increases the height by 1 . /// and is the opposite of `pop_internal_level`. 18,498 ( 0.00%) pub fn push_internal_level(&mut self) -> NodeRef, K, V, marker::Internal> { . super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root).forget_type()); . . // `self.borrow_mut()`, except that we just forgot we're internal now: . NodeRef { height: self.height, node: self.node, _marker: PhantomData } 24,664 ( 0.00%) } . . /// Removes the internal root node, using its first child as the new root node. . /// As it is intended only to be called when the root node has only one child, . /// no cleanup is done on any of the keys, values and other children. . /// This decreases the height by 1 and is the opposite of `push_internal_level`. . /// . /// Requires exclusive access to the `NodeRef` object but not to the root node; . /// it will not invalidate other handles or references to the root node. . /// . /// Panics if there is no internal level, i.e., if the root node is a leaf. . pub fn pop_internal_level(&mut self) { 8,155 ( 0.00%) assert!(self.height > 0); . . let top = self.node; . . // SAFETY: we asserted to be internal. . let internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() }; . // SAFETY: we borrowed `self` exclusively and its borrow type is exclusive. . let internal_node = unsafe { &mut *NodeRef::as_internal_ptr(&internal_self) }; . // SAFETY: the first edge is always initialized. 2,763 ( 0.00%) self.node = unsafe { internal_node.edges[0].assume_init_read() }; 5,526 ( 0.00%) self.height -= 1; . self.clear_parent_link(); . . unsafe { . Global.deallocate(top.cast(), Layout::new::>()); . } . } . } . . impl NodeRef { . /// Mutably borrows the owned root node. Unlike `reborrow_mut`, this is safe . /// because the return value cannot be used to destroy the root, and there . /// cannot be other references to the tree. . pub fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { 1,011,590 ( 0.02%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Slightly mutably borrows the owned root node. . pub fn borrow_valmut(&mut self) -> NodeRef, K, V, Type> { . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Irreversibly transitions to a reference that permits traversal and offers -- line 614 ---------------------------------------- -- line 617 ---------------------------------------- . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Leaf> { . /// Adds a key-value pair to the end of the node. . pub fn push(&mut self, key: K, val: V) { . let len = self.len_mut(); 30 ( 0.00%) let idx = usize::from(*len); 15 ( 0.00%) assert!(idx < CAPACITY); 36 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); . } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { . /// Adds a key-value pair, and an edge to go to the right of that pair, . /// to the end of the node. . pub fn push(&mut self, key: K, val: V, edge: Root) { 12,332 ( 0.00%) assert!(edge.height == self.height - 1); . . let len = self.len_mut(); 6,166 ( 0.00%) let idx = usize::from(*len); 3,083 ( 0.00%) assert!(idx < CAPACITY); 6,166 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); 3,083 ( 0.00%) self.edge_area_mut(idx + 1).write(edge.node); . Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); . } . } . } . . impl NodeRef { . /// Removes any static information asserting that this node is a `Leaf` node. . pub fn forget_type(self) -> NodeRef { -- line 656 ---------------------------------------- -- line 668 ---------------------------------------- . impl NodeRef { . /// Checks whether a node is an `Internal` node or a `Leaf` node. . pub fn force( . self, . ) -> ForceResult< . NodeRef, . NodeRef, . > { 1,052,078 ( 0.02%) if self.height == 0 { . ForceResult::Leaf(NodeRef { . height: self.height, . node: self.node, . _marker: PhantomData, . }) . } else { . ForceResult::Internal(NodeRef { . height: self.height, -- line 684 ---------------------------------------- -- line 747 ---------------------------------------- . Handle { node, idx, _marker: PhantomData } . } . . pub fn left_edge(self) -> Handle, marker::Edge> { . unsafe { Handle::new_edge(self.node, self.idx) } . } . . pub fn right_edge(self) -> Handle, marker::Edge> { 94,988 ( 0.00%) unsafe { Handle::new_edge(self.node, self.idx + 1) } . } . } . . impl PartialEq . for Handle, HandleType> . { . fn eq(&self, other: &Self) -> bool { . let Self { node, idx, _marker } = self; -- line 763 ---------------------------------------- -- line 790 ---------------------------------------- . } . . impl Handle, marker::Edge> { . /// Creates a new handle to an edge in `node`. . /// Unsafe because the caller must ensure that `idx <= node.len()`. . pub unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { . debug_assert!(idx <= node.len()); . 195,880 ( 0.00%) Handle { node, idx, _marker: PhantomData } . } . . pub fn left_kv(self) -> Result, marker::KV>, Self> { 3,674 ( 0.00%) if self.idx > 0 { 3,124 ( 0.00%) Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) }) . } else { . Err(self) . } . } . . pub fn right_kv(self) -> Result, marker::KV>, Self> { 157,657 ( 0.00%) if self.idx < self.node.len() { . Ok(unsafe { Handle::new_kv(self.node, self.idx) }) . } else { . Err(self) . } . } . } . . pub enum LeftOrRight { -- line 818 ---------------------------------------- -- line 820 ---------------------------------------- . Right(T), . } . . /// Given an edge index where we want to insert into a node filled to capacity, . /// computes a sensible KV index of a split point and where to perform the insertion. . /// The goal of the split point is for its key and value to end up in a parent node; . /// the keys, values and edges to the left of the split point become the left child; . /// the keys, values and edges to the right of the split point become the right child. 5,604 ( 0.00%) fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) { . debug_assert!(edge_idx <= CAPACITY); . // Rust issue #74834 tries to explain these symmetric rules. 21,624 ( 0.00%) match edge_idx { 11,208 ( 0.00%) 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)), . EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)), . EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)), 15,768 ( 0.00%) _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))), . } 5,604 ( 0.00%) } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method assumes that there is enough space in the node for the new . /// pair to fit. . /// . /// The returned pointer points to the inserted value. 1,543,824 ( 0.03%) fn insert_fit(&mut self, key: K, val: V) -> *mut V { . debug_assert!(self.node.len() < CAPACITY); . let new_len = self.node.len() + 1; . . unsafe { 196,073 ( 0.00%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 181,120 ( 0.00%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); 196,064 ( 0.00%) *self.node.len_mut() = new_len as u16; . . self.node.val_area_mut(self.idx).assume_init_mut() . } 1,568,512 ( 0.03%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method splits the node if there isn't enough room. . /// . /// The returned pointer points to the inserted value. . fn insert(mut self, key: K, val: V) -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) { 588,192 ( 0.01%) if self.node.len() < CAPACITY { 982,855 ( 0.02%) let val_ptr = self.insert_fit(key, val); 381,136 ( 0.01%) let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . (InsertResult::Fit(kv), val_ptr) . } else { 43,968 ( 0.00%) let (middle_kv_idx, insertion) = splitpoint(self.idx); 10,421 ( 0.00%) let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 26,467 ( 0.00%) let mut insertion_edge = match insertion { . LeftOrRight::Left(insert_idx) => unsafe { . Handle::new_edge(result.left.reborrow_mut(), insert_idx) . }, . LeftOrRight::Right(insert_idx) => unsafe { . Handle::new_edge(result.right.borrow_mut(), insert_idx) . }, . }; 25,327 ( 0.00%) let val_ptr = insertion_edge.insert_fit(key, val); 15,566 ( 0.00%) (InsertResult::Split(result), val_ptr) . } . } . } . . impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { . /// Fixes the parent pointer and index in the child node that this edge . /// links to. This is useful when the ordering of edges has been changed, . fn correct_parent_link(self) { -- line 890 ---------------------------------------- -- line 895 ---------------------------------------- . child.set_parent_link(ptr, idx); . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { . /// Inserts a new key-value pair and an edge that will go to the right of that new pair . /// between this edge and the key-value pair to the right of this edge. This method assumes . /// that there is enough space in the node for the new pair to fit. 19,621 ( 0.00%) fn insert_fit(&mut self, key: K, val: V, edge: Root) { . debug_assert!(self.node.len() < CAPACITY); . debug_assert!(edge.height == self.node.height - 1); . let new_len = self.node.len() + 1; . . unsafe { 2,521 ( 0.00%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 4,712 ( 0.00%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); . slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node); 2,521 ( 0.00%) *self.node.len_mut() = new_len as u16; . . self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1); . } 20,168 ( 0.00%) } . . /// Inserts a new key-value pair and an edge that will go to the right of that new pair . /// between this edge and the key-value pair to the right of this edge. This method splits . /// the node if there isn't enough room. . fn insert( . mut self, . key: K, . val: V, . edge: Root, . ) -> InsertResult<'a, K, V, marker::Internal> { 7,563 ( 0.00%) assert!(edge.height == self.node.height - 1); . 5,042 ( 0.00%) if self.node.len() < CAPACITY { 20,095 ( 0.00%) self.insert_fit(key, val, edge); . let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . InsertResult::Fit(kv) . } else { 824 ( 0.00%) let (middle_kv_idx, insertion) = splitpoint(self.idx); . let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 176 ( 0.00%) let mut insertion_edge = match insertion { . LeftOrRight::Left(insert_idx) => unsafe { . Handle::new_edge(result.left.reborrow_mut(), insert_idx) . }, . LeftOrRight::Right(insert_idx) => unsafe { . Handle::new_edge(result.right.borrow_mut(), insert_idx) . }, . }; 926 ( 0.00%) insertion_edge.insert_fit(key, val, edge); 280 ( 0.00%) InsertResult::Split(result) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method splits the node if there isn't enough room, and tries to . /// insert the split off portion into the parent node recursively, until the root is reached. . /// . /// If the returned result is a `Fit`, its handle's node can be this edge's node or an ancestor. . /// If the returned result is a `Split`, the `left` field will be the root node. . /// The returned pointer points to the inserted value. 1,951,708 ( 0.04%) pub fn insert_recursing( . self, . key: K, . value: V, . ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) { 1,099,171 ( 0.02%) let (mut split, val_ptr) = match self.insert(key, value) { . (InsertResult::Fit(handle), ptr) => { 952,840 ( 0.02%) return (InsertResult::Fit(handle.forget_node_type()), ptr); . } . (InsertResult::Split(split), val_ptr) => (split.forget_node_type(), val_ptr), . }; . . loop { 7,480 ( 0.00%) split = match split.left.ascend() { 13,365 ( 0.00%) Ok(parent) => match parent.insert(split.kv.0, split.kv.1, split.right) { . InsertResult::Fit(handle) => { 13,921 ( 0.00%) return (InsertResult::Fit(handle.forget_node_type()), val_ptr); . } . InsertResult::Split(split) => split.forget_node_type(), . }, . Err(root) => { 27,640 ( 0.00%) return (InsertResult::Split(SplitResult { left: root, ..split }), val_ptr); . } . }; . } 1,764,576 ( 0.04%) } . } . . impl . Handle, marker::Edge> . { . /// Finds the node pointed to by this edge. . /// . /// The method name assumes you picture trees with the root node on top. -- line 992 ---------------------------------------- -- line 999 ---------------------------------------- . // marker::ValMut, there might be outstanding mutable references to . // values that we must not invalidate. There's no worry accessing the . // height field because that value is copied. Beware that, once the . // node pointer is dereferenced, we access the edges array with a . // reference (Rust issue #73987) and invalidate any other references . // to or inside the array, should any be around. . let parent_ptr = NodeRef::as_internal_ptr(&self.node); . let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; 9,793 ( 0.00%) NodeRef { node, height: self.node.height - 1, _marker: PhantomData } . } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn into_kv(self) -> (&'a K, &'a V) { . debug_assert!(self.idx < self.node.len()); . let leaf = self.node.into_leaf(); . let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() }; . let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() }; 195,008 ( 0.00%) (k, v) . } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn key_mut(&mut self) -> &mut K { . unsafe { self.node.key_area_mut(self.idx).assume_init_mut() } . } . -- line 1025 ---------------------------------------- -- line 1037 ---------------------------------------- . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn kv_mut(&mut self) -> (&mut K, &mut V) { . debug_assert!(self.idx < self.node.len()); . // We cannot call separate key and value methods, because calling the second one . // invalidates the reference returned by the first. . unsafe { 154 ( 0.00%) let leaf = self.node.as_leaf_mut(); 154 ( 0.00%) let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut(); . let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut(); 631 ( 0.00%) (key, val) . } . } . . /// Replaces the key and value that the KV handle refers to. . pub fn replace_kv(&mut self, k: K, v: V) -> (K, V) { . let (key, val) = self.kv_mut(); . (mem::replace(key, k), mem::replace(val, v)) . } -- line 1056 ---------------------------------------- -- line 1069 ---------------------------------------- . (key, val) . } . } . . /// Drops the key and value that the KV handle refers to. . /// # Safety . /// The node that the handle refers to must not yet have been deallocated. . #[inline] 18 ( 0.00%) pub unsafe fn drop_key_val(mut self) { . debug_assert!(self.idx < self.node.len()); . let leaf = self.node.as_leaf_dying(); . unsafe { 3 ( 0.00%) leaf.keys.get_unchecked_mut(self.idx).assume_init_drop(); 9,804 ( 0.00%) leaf.vals.get_unchecked_mut(self.idx).assume_init_drop(); . } 21 ( 0.00%) } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . /// Helps implementations of `split` for a particular `NodeType`, . /// by taking care of leaf data. . fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { . debug_assert!(self.idx < self.node.len()); . let old_len = self.node.len(); 29,424 ( 0.00%) let new_len = old_len - self.idx - 1; 5,615 ( 0.00%) new_node.len = new_len as u16; . unsafe { 2,835 ( 0.00%) let k = self.node.key_area_mut(self.idx).assume_init_read(); 2,482 ( 0.00%) let v = self.node.val_area_mut(self.idx).assume_init_read(); . . move_to_slice( 16,812 ( 0.00%) self.node.key_area_mut(self.idx + 1..old_len), 5,604 ( 0.00%) &mut new_node.keys[..new_len], . ); . move_to_slice( . self.node.val_area_mut(self.idx + 1..old_len), 5,604 ( 0.00%) &mut new_node.vals[..new_len], . ); . 8,087 ( 0.00%) *self.node.len_mut() = self.idx as u16; 11,955 ( 0.00%) (k, v) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { . /// Splits the underlying node into three parts: . /// . /// - The node is truncated to only contain the key-value pairs to the left of -- line 1117 ---------------------------------------- -- line 1120 ---------------------------------------- . /// - All the key-value pairs to the right of this handle are put into a newly . /// allocated node. . pub fn split(mut self) -> SplitResult<'a, K, V, marker::Leaf> { . let mut new_node = LeafNode::new(); . . let kv = self.split_leaf_data(&mut new_node); . . let right = NodeRef::from_new_leaf(new_node); 46,147 ( 0.00%) SplitResult { left: self.node, kv, right } . } . . /// Removes the key-value pair pointed to by this handle and returns it, along with the edge . /// that the key-value pair collapsed into. . pub fn remove( . mut self, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { . let old_len = self.node.len(); . unsafe { . let k = slice_remove(self.node.key_area_mut(..old_len), self.idx); 127,314 ( 0.00%) let v = slice_remove(self.node.val_area_mut(..old_len), self.idx); 604,929 ( 0.01%) *self.node.len_mut() = (old_len - 1) as u16; 448,081 ( 0.01%) ((k, v), self.left_edge()) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { . /// Splits the underlying node into three parts: . /// . /// - The node is truncated to only contain the edges and key-value pairs to the -- line 1149 ---------------------------------------- -- line 1153 ---------------------------------------- . /// a newly allocated node. . pub fn split(mut self) -> SplitResult<'a, K, V, marker::Internal> { . let old_len = self.node.len(); . unsafe { . let mut new_node = InternalNode::new(); . let kv = self.split_leaf_data(&mut new_node.data); . let new_len = usize::from(new_node.data.len); . move_to_slice( 108 ( 0.00%) self.node.edge_area_mut(self.idx + 1..old_len + 1), 216 ( 0.00%) &mut new_node.edges[..new_len + 1], . ); . . let height = self.node.height; . let right = NodeRef::from_new_internal(new_node, height); . 560 ( 0.00%) SplitResult { left: self.node, kv, right } . } . } . } . . /// Represents a session for evaluating and performing a balancing operation . /// around an internal key-value pair. . pub struct BalancingContext<'a, K, V> { . parent: Handle, K, V, marker::Internal>, marker::KV>, -- line 1176 ---------------------------------------- -- line 1242 ---------------------------------------- . . pub fn into_right_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { . self.right_child . } . . /// Returns whether merging is possible, i.e., whether there is enough room . /// in a node to combine the central KV with both adjacent child nodes. . pub fn can_merge(&self) -> bool { 10,444 ( 0.00%) self.left_child.len() + 1 + self.right_child.len() <= CAPACITY . } . } . . impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { . /// Performs a merge and lets a closure decide what to return. . fn do_merge< . F: FnOnce( . NodeRef, K, V, marker::Internal>, -- line 1258 ---------------------------------------- -- line 1264 ---------------------------------------- . result: F, . ) -> R { . let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; . let old_parent_len = parent_node.len(); . let mut left_node = self.left_child; . let old_left_len = left_node.len(); . let mut right_node = self.right_child; . let right_len = right_node.len(); 6,632 ( 0.00%) let new_left_len = old_left_len + 1 + right_len; . 6,632 ( 0.00%) assert!(new_left_len <= CAPACITY); . . unsafe { 3,316 ( 0.00%) *left_node.len_mut() = new_left_len as u16; . . let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx); . left_node.key_area_mut(old_left_len).write(parent_key); . move_to_slice( . right_node.key_area_mut(..right_len), . left_node.key_area_mut(old_left_len + 1..new_left_len), . ); . . let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx); . left_node.val_area_mut(old_left_len).write(parent_val); . move_to_slice( . right_node.val_area_mut(..right_len), . left_node.val_area_mut(old_left_len + 1..new_left_len), . ); . 3,316 ( 0.00%) slice_remove(&mut parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1); . parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len); 19,903 ( 0.00%) *parent_node.len_mut() -= 1; . 6,632 ( 0.00%) if parent_node.height > 1 { . // SAFETY: the height of the nodes being merged is one below the height . // of the node of this edge, thus above zero, so they are internal. . let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked(); . let mut right_node = right_node.cast_to_internal_unchecked(); . move_to_slice( . right_node.edge_area_mut(..right_len + 1), 7 ( 0.00%) left_node.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); . . Global.deallocate(right_node.node.cast(), Layout::new::>()); . } else { . Global.deallocate(right_node.node.cast(), Layout::new::>()); . } -- line 1312 ---------------------------------------- -- line 1313 ---------------------------------------- . } . result(parent_node, left_node) . } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns the shrunk parent node. . /// . /// Panics unless we `.can_merge()`. 49 ( 0.00%) pub fn merge_tracking_parent(self) -> NodeRef, K, V, marker::Internal> { 14 ( 0.00%) self.do_merge(|parent, _child| parent) 70 ( 0.00%) } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns that child node. . /// . /// Panics unless we `.can_merge()`. . pub fn merge_tracking_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { . self.do_merge(|_parent, child| child) . } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns the edge handle in that child node . /// where the tracked child edge ended up, . /// . /// Panics unless we `.can_merge()`. 23,163 ( 0.00%) pub fn merge_tracking_child_edge( . self, . track_edge_idx: LeftOrRight, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 3,309 ( 0.00%) let old_left_len = self.left_child.len(); 3,309 ( 0.00%) let right_len = self.right_child.len(); 9,927 ( 0.00%) assert!(match track_edge_idx { . LeftOrRight::Left(idx) => idx <= old_left_len, . LeftOrRight::Right(idx) => idx <= right_len, . }); . let child = self.merge_tracking_child(); 3,309 ( 0.00%) let new_idx = match track_edge_idx { . LeftOrRight::Left(idx) => idx, 9,231 ( 0.00%) LeftOrRight::Right(idx) => old_left_len + 1 + idx, . }; . unsafe { Handle::new_edge(child, new_idx) } 26,472 ( 0.00%) } . . /// Removes a key-value pair from the left child and places it in the key-value storage . /// of the parent, while pushing the old parent key-value pair into the right child. . /// Returns a handle to the edge in the right child corresponding to where the original . /// edge specified by `track_right_edge_idx` ended up. . pub fn steal_left( . mut self, . track_right_edge_idx: usize, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 80 ( 0.00%) self.bulk_steal_left(1); . unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) } . } . . /// Removes a key-value pair from the right child and places it in the key-value storage . /// of the parent, while pushing the old parent key-value pair onto the left child. . /// Returns a handle to the edge in the left child specified by `track_left_edge_idx`, . /// which didn't move. . pub fn steal_right( . mut self, . track_left_edge_idx: usize, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 228 ( 0.00%) self.bulk_steal_right(1); . unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) } . } . . /// This does stealing similar to `steal_left` but steals multiple elements at once. 280 ( 0.00%) pub fn bulk_steal_left(&mut self, count: usize) { 80 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; . let old_left_len = left_node.len(); . let right_node = &mut self.right_child; 40 ( 0.00%) let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 200 ( 0.00%) assert!(old_right_len + count <= CAPACITY); 93 ( 0.00%) assert!(old_left_len >= count); . . let new_left_len = old_left_len - count; . let new_right_len = old_right_len + count; 40 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 40 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Make room for stolen elements in the right child. . slice_shr(right_node.key_area_mut(..new_right_len), count); . slice_shr(right_node.val_area_mut(..new_right_len), count); . . // Move elements from the left child to the right one. . move_to_slice( 80 ( 0.00%) left_node.key_area_mut(new_left_len + 1..old_left_len), 40 ( 0.00%) right_node.key_area_mut(..count - 1), . ); . move_to_slice( . left_node.val_area_mut(new_left_len + 1..old_left_len), . right_node.val_area_mut(..count - 1), . ); . . // Move the left-most stolen pair to the parent. 13 ( 0.00%) let k = left_node.key_area_mut(new_left_len).assume_init_read(); . let v = left_node.val_area_mut(new_left_len).assume_init_read(); 335 ( 0.00%) let (k, v) = self.parent.replace_kv(k, v); . . // Move parent's key-value pair to the right child. . right_node.key_area_mut(count - 1).write(k); . right_node.val_area_mut(count - 1).write(v); . } . 200 ( 0.00%) match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { . (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { . // Make room for stolen edges. . slice_shr(right.edge_area_mut(..new_right_len + 1), count); . . // Steal edges. . move_to_slice( . left.edge_area_mut(new_left_len + 1..old_left_len + 1), . right.edge_area_mut(..count), -- line 1432 ---------------------------------------- -- line 1433 ---------------------------------------- . ); . . right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 320 ( 0.00%) } . . /// The symmetric clone of `bulk_steal_left`. 798 ( 0.00%) pub fn bulk_steal_right(&mut self, count: usize) { 228 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; 114 ( 0.00%) let old_left_len = left_node.len(); . let right_node = &mut self.right_child; . let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 570 ( 0.00%) assert!(old_left_len + count <= CAPACITY); 230 ( 0.00%) assert!(old_right_len >= count); . . let new_left_len = old_left_len + count; . let new_right_len = old_right_len - count; 114 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 114 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Move the right-most stolen pair to the parent. 228 ( 0.00%) let k = right_node.key_area_mut(count - 1).assume_init_read(); . let v = right_node.val_area_mut(count - 1).assume_init_read(); 456 ( 0.00%) let (k, v) = self.parent.replace_kv(k, v); . . // Move parent's key-value pair to the left child. . left_node.key_area_mut(old_left_len).write(k); . left_node.val_area_mut(old_left_len).write(v); . . // Move elements from the right child to the left one. . move_to_slice( . right_node.key_area_mut(..count - 1), 114 ( 0.00%) left_node.key_area_mut(old_left_len + 1..new_left_len), . ); . move_to_slice( . right_node.val_area_mut(..count - 1), . left_node.val_area_mut(old_left_len + 1..new_left_len), . ); . . // Fill gap where stolen elements used to be. . slice_shl(right_node.key_area_mut(..old_right_len), count); . slice_shl(right_node.val_area_mut(..old_right_len), count); . } . 570 ( 0.00%) match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { . (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { . // Steal edges. . move_to_slice( . right.edge_area_mut(..count), . left.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . // Fill gap where stolen edges used to be. -- line 1495 ---------------------------------------- -- line 1497 ---------------------------------------- . . left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); . right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 912 ( 0.00%) } . } . . impl Handle, marker::Edge> { . pub fn forget_node_type( . self, . ) -> Handle, marker::Edge> { . unsafe { Handle::new_edge(self.node.forget_type(), self.idx) } . } -- line 1513 ---------------------------------------- -- line 1681 ---------------------------------------- . /// . /// # Safety . /// The slice has more than `idx` elements. . unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) { . unsafe { . let len = slice.len(); . debug_assert!(len > idx); . let slice_ptr = slice.as_mut_ptr(); 1,380,353 ( 0.03%) if len > idx + 1 { 124,180 ( 0.00%) ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1); . } . (*slice_ptr.add(idx)).write(val); . } . } . . /// Removes and returns a value from a slice of all initialized elements, leaving behind one . /// trailing uninitialized element. . /// -- line 1698 ---------------------------------------- -- line 1699 ---------------------------------------- . /// # Safety . /// The slice has more than `idx` elements. . unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T { . unsafe { . let len = slice.len(); . debug_assert!(idx < len); . let slice_ptr = slice.as_mut_ptr(); . let ret = (*slice_ptr.add(idx)).assume_init_read(); 1,326,696 ( 0.03%) ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1); . ret . } . } . . /// Shifts the elements in a slice `distance` positions to the left. . /// . /// # Safety . /// The slice has at least `distance` elements. -- line 1715 ---------------------------------------- -- line 1722 ---------------------------------------- . . /// Shifts the elements in a slice `distance` positions to the right. . /// . /// # Safety . /// The slice has at least `distance` elements. . unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { . unsafe { . let slice_ptr = slice.as_mut_ptr(); 120 ( 0.00%) ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance); . } . } . . /// Moves all values from a slice of initialized elements to a slice . /// of uninitialized elements, leaving behind `src` as all uninitialized. . /// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. . fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { 18,404 ( 0.00%) assert!(src.len() == dst.len()); . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); . } . } . . #[cfg(test)] . mod tests; 3,464,342 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . fn cmp(&self, other: &str) -> Ordering { . self.as_bytes().cmp(other.as_bytes()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for str { . #[inline] 5,381,739 ( 0.12%) fn eq(&self, other: &str) -> bool { 4,783,768 ( 0.10%) self.as_bytes() == other.as_bytes() 2,391,884 ( 0.05%) } . #[inline] . fn ne(&self, other: &str) -> bool { . !(*self).eq(other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for str {} -- line 38 ---------------------------------------- -- line 55 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Index for str . where . I: SliceIndex, . { . type Output = I::Output; . . #[inline] 218,258 ( 0.00%) fn index(&self, index: I) -> &I::Output { 212,088 ( 0.00%) index.index(self) 141,392 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::IndexMut for str . where . I: SliceIndex, . { . #[inline] -- line 73 ---------------------------------------- -- line 110 ---------------------------------------- . unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output { . slice . } . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output { . slice . } . #[inline] 416,772 ( 0.01%) fn index(self, slice: &str) -> &Self::Output { . slice 138,924 ( 0.00%) } . #[inline] . fn index_mut(self, slice: &mut str) -> &mut Self::Output { . slice . } . } . . /// Implements substring slicing with syntax `&self[begin .. end]` or `&mut . /// self[begin .. end]`. -- line 128 ---------------------------------------- -- line 159 ---------------------------------------- . /// // byte 100 is outside the string . /// // &s[3 .. 100]; . /// ``` . #[stable(feature = "str_checked_slicing", since = "1.20.0")] . unsafe impl SliceIndex for ops::Range { . type Output = str; . #[inline] . fn get(self, slice: &str) -> Option<&Self::Output> { 199,660 ( 0.00%) if self.start <= self.end . && slice.is_char_boundary(self.start) . && slice.is_char_boundary(self.end) . { . // SAFETY: just checked that `start` and `end` are on a char boundary, . // and we are passing in a safe reference, so the return value will also be one. . // We also checked char boundaries, so this is valid UTF-8. . Some(unsafe { &*self.get_unchecked(slice) }) . } else { -- line 175 ---------------------------------------- -- line 190 ---------------------------------------- . } . } . #[inline] . unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output { . let slice = slice as *const [u8]; . // SAFETY: the caller guarantees that `self` is in bounds of `slice` . // which satisfies all the conditions for `add`. . let ptr = unsafe { slice.as_ptr().add(self.start) }; 132,622 ( 0.00%) let len = self.end - self.start; . ptr::slice_from_raw_parts(ptr, len) as *const str . } . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output { . let slice = slice as *mut [u8]; . // SAFETY: see comments for `get_unchecked`. . let ptr = unsafe { slice.as_mut_ptr().add(self.start) }; . let len = self.end - self.start; -- line 206 ---------------------------------------- -- line 315 ---------------------------------------- . /// # Panics . /// . /// Panics if `begin` does not point to the starting byte offset of . /// a character (as defined by `is_char_boundary`), or if `begin > len`. . #[stable(feature = "str_checked_slicing", since = "1.20.0")] . unsafe impl SliceIndex for ops::RangeFrom { . type Output = str; . #[inline] 16,042 ( 0.00%) fn get(self, slice: &str) -> Option<&Self::Output> { 24,171 ( 0.00%) if slice.is_char_boundary(self.start) { . // SAFETY: just checked that `start` is on a char boundary, . // and we are passing in a safe reference, so the return value will also be one. 6,170 ( 0.00%) Some(unsafe { &*self.get_unchecked(slice) }) . } else { . None . } 4,936 ( 0.00%) } . #[inline] . fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> { . if slice.is_char_boundary(self.start) { . // SAFETY: just checked that `start` is on a char boundary, . // and we are passing in a safe reference, so the return value will also be one. . Some(unsafe { &mut *self.get_unchecked_mut(slice) }) . } else { . None . } . } . #[inline] 16,042 ( 0.00%) unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output { 2,468 ( 0.00%) let slice = slice as *const [u8]; . // SAFETY: the caller guarantees that `self` is in bounds of `slice` . // which satisfies all the conditions for `add`. 3,702 ( 0.00%) let ptr = unsafe { slice.as_ptr().add(self.start) }; 34,899 ( 0.00%) let len = slice.len() - self.start; 4,936 ( 0.00%) ptr::slice_from_raw_parts(ptr, len) as *const str 2,468 ( 0.00%) } . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output { . let slice = slice as *mut [u8]; . // SAFETY: identical to `get_unchecked`. . let ptr = unsafe { slice.as_mut_ptr().add(self.start) }; . let len = slice.len() - self.start; . ptr::slice_from_raw_parts_mut(ptr, len) as *mut str . } . #[inline] 17,276 ( 0.00%) fn index(self, slice: &str) -> &Self::Output { 12,340 ( 0.00%) let (start, end) = (self.start, slice.len()); 12,340 ( 0.00%) match self.get(slice) { 4,936 ( 0.00%) Some(s) => s, . None => super::slice_error_fail(slice, start, end), . } 2,468 ( 0.00%) } . #[inline] . fn index_mut(self, slice: &mut str) -> &mut Self::Output { . if slice.is_char_boundary(self.start) { . // SAFETY: just checked that `start` is on a char boundary, . // and we are passing in a safe reference, so the return value will also be one. . unsafe { &mut *self.get_unchecked_mut(slice) } . } else { . super::slice_error_fail(slice, self.start, slice.len()) -- line 374 ---------------------------------------- 3,192,279 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs -------------------------------------------------------------------------------- Ir -- line 137 ---------------------------------------- . /// . /// assert_eq!("ƒoo".len(), 4); // fancy f! . /// assert_eq!("ƒoo".chars().count(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")] . #[must_use] . #[inline] 142,690 ( 0.00%) pub const fn len(&self) -> usize { . self.as_bytes().len() 57,076 ( 0.00%) } . . /// Returns `true` if `self` has a length of zero bytes. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 155 ---------------------------------------- -- line 158 ---------------------------------------- . /// . /// let s = "not empty"; . /// assert!(!s.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")] . #[must_use] . #[inline] 216 ( 0.00%) pub const fn is_empty(&self) -> bool { 121,133 ( 0.00%) self.len() == 0 288 ( 0.00%) } . . /// Checks that `index`-th byte is the first byte in a UTF-8 code point . /// sequence or the end of the string. . /// . /// The start and end of the string (when `index == self.len()`) are . /// considered to be boundaries. . /// . /// Returns `false` if `index` is greater than `self.len()`. -- line 176 ---------------------------------------- -- line 188 ---------------------------------------- . /// assert!(!s.is_char_boundary(2)); . /// . /// // third byte of `老` . /// assert!(!s.is_char_boundary(8)); . /// ``` . #[must_use] . #[stable(feature = "is_char_boundary", since = "1.9.0")] . #[inline] 8,638 ( 0.00%) pub fn is_char_boundary(&self, index: usize) -> bool { . // 0 is always ok. . // Test for 0 explicitly so that it can optimize out the check . // easily and skip reading string data for that case. . // Note that optimizing `self.get(..index)` relies on this. 231,541 ( 0.01%) if index == 0 { . return true; . } . 135,895 ( 0.00%) match self.as_bytes().get(index) { . // For `None` we have two options: . // . // - index == self.len() . // Empty strings are valid, so return true . // - index > self.len() . // In this case return false . // . // The check is placed exactly here, because it improves generated . // code on higher opt-levels. See PR #84751 for more details. 43,339 ( 0.00%) None => index == self.len(), . . // This is bit magic equivalent to: b < 128 || b >= 192 101,686 ( 0.00%) Some(&b) => (b as i8) >= -0x40, . } 7,404 ( 0.00%) } . . /// Converts a string slice to a byte slice. To convert the byte slice back . /// into a string slice, use the [`from_utf8`] function. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 228 ---------------------------------------- -- line 232 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")] . #[must_use] . #[inline(always)] . #[allow(unused_attributes)] . pub const fn as_bytes(&self) -> &[u8] { . // SAFETY: const sound because we transmute two types with the same layout 6,081,998 ( 0.13%) unsafe { mem::transmute(self) } . } . . /// Converts a mutable string slice to a mutable byte slice. . /// . /// # Safety . /// . /// The caller must ensure that the content of the slice is valid UTF-8 . /// before the borrow ends and the underlying `str` is used. -- line 248 ---------------------------------------- -- line 306 ---------------------------------------- . /// let s = "Hello"; . /// let ptr = s.as_ptr(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")] . #[must_use] . #[inline] . pub const fn as_ptr(&self) -> *const u8 { 438 ( 0.00%) self as *const str as *const u8 . } . . /// Converts a mutable string slice to a raw pointer. . /// . /// As string slices are a slice of bytes, the raw pointer points to a . /// [`u8`]. This pointer will be pointing to the first byte of the string . /// slice. . /// -- line 322 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// assert_eq!(Some('y'), chars.next()); // not 'y̆' . /// assert_eq!(Some('\u{0306}'), chars.next()); . /// . /// assert_eq!(None, chars.next()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 775,590 ( 0.02%) pub fn chars(&self) -> Chars<'_> { 775,590 ( 0.02%) Chars { iter: self.as_bytes().iter() } 620,472 ( 0.01%) } . . /// Returns an iterator over the [`char`]s of a string slice, and their . /// positions. . /// . /// As a string slice consists of valid UTF-8, we can iterate through a . /// string slice by [`char`]. This method returns an iterator of both . /// these [`char`]s, as well as their byte positions. . /// -- line 698 ---------------------------------------- -- line 808 ---------------------------------------- . /// . /// assert_eq!(None, iter.next()); . /// ``` . #[must_use = "this returns the split string as an iterator, \ . without modifying the original"] . #[stable(feature = "split_whitespace", since = "1.1.0")] . #[inline] . pub fn split_whitespace(&self) -> SplitWhitespace<'_> { 9 ( 0.00%) SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) } . } . . /// Splits a string slice by ASCII whitespace. . /// . /// The iterator returned will return string slices that are sub-slices of . /// the original string slice, separated by any amount of ASCII whitespace. . /// . /// To split by Unicode `Whitespace` instead, use [`split_whitespace`]. -- line 824 ---------------------------------------- -- line 979 ---------------------------------------- . /// . /// ``` . /// let bananas = "bananas"; . /// . /// assert!(bananas.starts_with("bana")); . /// assert!(!bananas.starts_with("nana")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 38,176 ( 0.00%) pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool { 6,988 ( 0.00%) pat.is_prefix_of(self) 13,976 ( 0.00%) } . . /// Returns `true` if the given pattern matches a suffix of this . /// string slice. . /// . /// Returns `false` if it does not. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 997 ---------------------------------------- -- line 1005 ---------------------------------------- . /// . /// ``` . /// let bananas = "bananas"; . /// . /// assert!(bananas.ends_with("anas")); . /// assert!(!bananas.ends_with("nana")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 43,362 ( 0.00%) pub fn ends_with<'a, P>(&'a self, pat: P) -> bool . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { 7,884 ( 0.00%) pat.is_suffix_of(self) 15,768 ( 0.00%) } . . /// Returns the byte index of the first character of this string slice that . /// matches the pattern. . /// . /// Returns [`None`] if the pattern doesn't match. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 1026 ---------------------------------------- -- line 1056 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.find(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6 ( 0.00%) pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { 1 ( 0.00%) pat.into_searcher(self).next_match().map(|(i, _)| i) 2 ( 0.00%) } . . /// Returns the byte index for the first character of the rightmost match of the pattern in . /// this string slice. . /// . /// Returns [`None`] if the pattern doesn't match. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 1074 ---------------------------------------- -- line 1102 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.rfind(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 11,104 ( 0.00%) pub fn rfind<'a, P>(&'a self, pat: P) -> Option . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . pat.into_searcher(self).next_match_back().map(|(i, _)| i) 11,104 ( 0.00%) } . . /// An iterator over substrings of this string slice, separated by . /// characters matched by a pattern. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1123 ---------------------------------------- -- line 1225 ---------------------------------------- . /// ``` . /// . /// Use [`split_whitespace`] for this behavior. . /// . /// [`split_whitespace`]: str::split_whitespace . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> { 6,012 ( 0.00%) Split(SplitInternal { . start: 0, . end: self.len(), . matcher: pat.into_searcher(self), . allow_trailing_empty: true, . finished: false, . }) . } . -- line 1241 ---------------------------------------- -- line 1472 ---------------------------------------- . /// . /// ``` . /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); . /// assert_eq!(v, ["abc", "defXghi"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { 243 ( 0.00%) SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) . } . . /// An iterator over substrings of this string slice, separated by a . /// pattern, starting from the end of the string, restricted to returning . /// at most `n` items. . /// . /// If `n` substrings are returned, the last substring (the `n`th substring) . /// will contain the remainder of the string. -- line 1488 ---------------------------------------- -- line 1540 ---------------------------------------- . /// ``` . /// assert_eq!("cfg".split_once('='), None); . /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo"))); . /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar"))); . /// ``` . #[stable(feature = "str_split_once", since = "1.52.0")] . #[inline] . pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> { 50 ( 0.00%) let (start, end) = delimiter.into_searcher(self).next_match()?; . // SAFETY: `Searcher` is known to return valid indices. . unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } . } . . /// Splits the string on the last occurrence of the specified delimiter and . /// returns prefix before delimiter and suffix after delimiter. . /// . /// # Examples -- line 1556 ---------------------------------------- -- line 1749 ---------------------------------------- . /// . /// assert_eq!("Hello\tworld", s.trim()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn trim(&self) -> &str { 56 ( 0.00%) self.trim_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1765 ---------------------------------------- -- line 1825 ---------------------------------------- . /// let s = " עברית "; . /// assert!(Some('ת') == s.trim_end().chars().rev().next()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] . pub fn trim_end(&self) -> &str { 501 ( 0.00%) self.trim_end_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1841 ---------------------------------------- -- line 1945 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] 16,432 ( 0.00%) pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, . { . let mut i = 0; . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((a, b)) = matcher.next_reject() { . i = a; -- line 1961 ---------------------------------------- -- line 1962 ---------------------------------------- . j = b; // Remember earliest known match, correct it below if . // last match is different . } . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..j) } 16,432 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1978 ---------------------------------------- -- line 1994 ---------------------------------------- . /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); . /// . /// let x: &[_] = &['1', '2']; . /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 10,494 ( 0.00%) pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { . let mut i = self.len(); . let mut matcher = pat.into_searcher(self); . if let Some((a, _)) = matcher.next_reject() { . i = a; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..self.len()) } 10,494 ( 0.00%) } . . /// Returns a string slice with the prefix removed. . /// . /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped . /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once. . /// . /// If the string does not start with `prefix`, returns `None`. . /// -- line 2018 ---------------------------------------- -- line 2098 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 4,509 ( 0.00%) pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(0..j) } 5,010 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 2125 ---------------------------------------- -- line 2240 ---------------------------------------- . /// ``` . /// let nope = "j".parse::(); . /// . /// assert!(nope.is_err()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn parse(&self) -> Result { 18 ( 0.00%) FromStr::from_str(self) . } . . /// Checks if all characters in this string are within the ASCII range. . /// . /// # Examples . /// . /// ``` . /// let ascii = "hello!\n"; -- line 2256 ---------------------------------------- -- line 2420 ---------------------------------------- . /// Using `to_string`: . /// . /// ``` . /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!"); . /// ``` . #[must_use = "this returns the escaped string as an iterator, \ . without modifying the original"] . #[stable(feature = "str_escape", since = "1.34.0")] 85 ( 0.00%) pub fn escape_default(&self) -> EscapeDefault<'_> { 340 ( 0.00%) EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) } 85 ( 0.00%) } . . /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`]. . /// . /// # Examples . /// . /// As an iterator: . /// . /// ``` -- line 2438 ---------------------------------------- -- line 2466 ---------------------------------------- . pub fn escape_unicode(&self) -> EscapeUnicode<'_> { . EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl AsRef<[u8]> for str { . #[inline] 8,040 ( 0.00%) fn as_ref(&self) -> &[u8] { . self.as_bytes() 3,216 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for &str { . /// Creates an empty str . #[inline] . fn default() -> Self { -- line 2484 ---------------------------------------- 791,095 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . impl<'a, 'b, T: LambdaL> Deref for RefMutL<'a, 'b, T> { . type Target = >::Out; . fn deref(&self) -> &Self::Target { . self.0 . } . } . . impl<'a, 'b, T: LambdaL> DerefMut for RefMutL<'a, 'b, T> { 156 ( 0.00%) fn deref_mut(&mut self) -> &mut Self::Target { 78 ( 0.00%) self.0 156 ( 0.00%) } . } . . pub struct ScopedCell(Cell<>::Out>); . . impl ScopedCell { . #[rustc_allow_const_fn_unstable(const_fn)] 3 ( 0.00%) pub const fn new(value: >::Out) -> Self { 10 ( 0.00%) ScopedCell(Cell::new(value)) 2 ( 0.00%) } . . /// Sets the value in `self` to `replacement` while . /// running `f`, which gets the old value, mutably. . /// The old value will be restored after `f` exits, even . /// by panic, including modifications made to it by `f`. 3,907,545 ( 0.08%) pub fn replace<'a, R>( . &self, . replacement: >::Out, . f: impl for<'b, 'c> FnOnce(RefMutL<'b, 'c, T>) -> R, . ) -> R { . /// Wrapper that ensures that the cell always gets filled . /// (with the original state, optionally changed by `f`), . /// even if `f` had panicked. . struct PutBackOnDrop<'a, T: LambdaL> { . cell: &'a ScopedCell, . value: Option<>::Out>, . } . . impl<'a, T: LambdaL> Drop for PutBackOnDrop<'a, T> { 351 ( 0.00%) fn drop(&mut self) { 527,450 ( 0.01%) self.cell.0.set(self.value.take().unwrap()); 234 ( 0.00%) } . } . 1,054,314 ( 0.02%) let mut put_back_on_drop = PutBackOnDrop { . cell: self, 1,170 ( 0.00%) value: Some(self.0.replace(unsafe { 234 ( 0.00%) let erased = mem::transmute_copy(&replacement); 1,404 ( 0.00%) mem::forget(replacement); 1,170 ( 0.00%) erased . })), . }; . 193,493 ( 0.00%) f(RefMutL(put_back_on_drop.value.as_mut().unwrap())) 5,132,035 ( 0.11%) } . . /// Sets the value in `self` to `value` while running `f`. 273 ( 0.00%) pub fn set(&self, value: >::Out, f: impl FnOnce() -> R) -> R { 624 ( 0.00%) self.replace(value, |_| f()) 78 ( 0.00%) } . } 135,640 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs -------------------------------------------------------------------------------- Ir -- line 504 ---------------------------------------- . use crate::panicking::{panic, panic_str}; . use crate::pin::Pin; . use crate::{ . convert, hint, mem, . ops::{self, ControlFlow, Deref, DerefMut}, . }; . . /// The `Option` type. See [the module level documentation](self) for more. 2,702,803 ( 0.06%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. . #[lang = "Some"] . #[stable(feature = "rust1", since = "1.0.0")] 105,960 ( 0.00%) Some(#[stable(feature = "rust1", since = "1.0.0")] T), . } . . ///////////////////////////////////////////////////////////////////////////// . // Type implementation . ///////////////////////////////////////////////////////////////////////////// . . impl Option { . ///////////////////////////////////////////////////////////////////////// -- line 531 ---------------------------------------- -- line 542 ---------------------------------------- . /// . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] 116,960 ( 0.00%) pub const fn is_some(&self) -> bool { 2,579,000 ( 0.06%) matches!(*self, Some(_)) 292,400 ( 0.01%) } . . /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] . /// -- line 560 ---------------------------------------- -- line 585 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_none(), true); . /// ``` . #[must_use = "if you intended to assert that this doesn't have a value, consider \ . `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] 57,704 ( 0.00%) pub const fn is_none(&self) -> bool { 86,556 ( 0.00%) !self.is_some() 115,408 ( 0.00%) } . . ///////////////////////////////////////////////////////////////////////// . // Adapter for working with references . ///////////////////////////////////////////////////////////////////////// . . /// Converts from `&Option` to `Option<&T>`. . /// . /// # Examples -- line 603 ---------------------------------------- -- line 615 ---------------------------------------- . /// // First, cast `Option` to `Option<&String>` with `as_ref`, . /// // then consume *that* with `map`, leaving `text` on the stack. . /// let text_length: Option = text.as_ref().map(|s| s.len()); . /// println!("still can print text: {:?}", text); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] 28,143 ( 0.00%) pub const fn as_ref(&self) -> Option<&T> { 6,415,764 ( 0.14%) match *self { 18,292 ( 0.00%) Some(ref x) => Some(x), 586 ( 0.00%) None => None, . } 28,143 ( 0.00%) } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples . /// . /// ``` . /// let mut x = Some(2); . /// match x.as_mut() { -- line 636 ---------------------------------------- -- line 637 ---------------------------------------- . /// Some(v) => *v = 42, . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 5,439 ( 0.00%) pub const fn as_mut(&mut self) -> Option<&mut T> { 3,734,115 ( 0.08%) match *self { 3,328 ( 0.00%) Some(ref mut x) => Some(x), 298 ( 0.00%) None => None, . } 5,439 ( 0.00%) } . . /// Converts from [Pin]<[&]Option\> to Option<[Pin]<[&]T>>. . /// . /// [&]: reference "shared reference" . #[inline] . #[must_use] . #[stable(feature = "pin", since = "1.33.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] -- line 658 ---------------------------------------- -- line 705 ---------------------------------------- . /// let x: Option<&str> = None; . /// x.expect("fruits are healthy"); // panics with `fruits are healthy` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn expect(self, msg: &str) -> T { 1,530,720 ( 0.03%) match self { 678,048 ( 0.01%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 741 ---------------------------------------- . /// ```should_panic . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 113,381 ( 0.00%) pub const fn unwrap(self) -> T { 5,847,211 ( 0.13%) match self { 727,979 ( 0.02%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } 75,430 ( 0.00%) } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], . /// which is lazily evaluated. . /// . /// [`unwrap_or_else`]: Option::unwrap_or_else -- line 762 ---------------------------------------- -- line 765 ---------------------------------------- . /// . /// ``` . /// assert_eq!(Some("car").unwrap_or("bike"), "car"); . /// assert_eq!(None.unwrap_or("bike"), "bike"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 5,619 ( 0.00%) pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 726,712 ( 0.02%) match self { 3,834 ( 0.00%) Some(x) => x, 2,704 ( 0.00%) None => default, . } 29,782 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); . /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 560 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 927,099 ( 0.02%) match self { 96,000 ( 0.00%) Some(x) => x, 5,260 ( 0.00%) None => f(), . } 2,837 ( 0.00%) } . . /// Returns the contained [`Some`] value or a default. . /// . /// Consumes the `self` argument then, if [`Some`], returns the contained . /// value, otherwise if [`None`], returns the [default value] for that . /// type. . /// . /// # Examples -- line 812 ---------------------------------------- -- line 831 ---------------------------------------- . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_default(self) -> T . where . T: ~const Default, . { 9,291 ( 0.00%) match self { 11,119 ( 0.00%) Some(x) => x, . None => Default::default(), . } 1,524 ( 0.00%) } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety . /// . /// Calling this method on [`None`] is *[undefined behavior]*. . /// -- line 851 ---------------------------------------- -- line 892 ---------------------------------------- . /// // `Option::map` takes self *by value*, consuming `maybe_some_string` . /// let maybe_some_len = maybe_some_string.map(|s| s.len()); . /// . /// assert_eq!(maybe_some_len, Some(13)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 760,688 ( 0.02%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 4,832,832 ( 0.10%) match self { 5,029,972 ( 0.11%) Some(x) => Some(f(x)), 253,532 ( 0.01%) None => None, . } 1,370,141 ( 0.03%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 954 ---------------------------------------- . /// assert_eq!(x.map_or(42, |v| v.len()), 3); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.map_or(42, |v| v.len()), 42); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 41,890 ( 0.00%) pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 741,136 ( 0.02%) match self { 66,214 ( 0.00%) Some(t) => f(t), 70,434 ( 0.00%) None => default, . } 45,546 ( 0.00%) } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples . /// . /// ``` . /// let k = 21; -- line 980 ---------------------------------------- -- line 990 ---------------------------------------- . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 49,364 ( 0.00%) match self { 14,932 ( 0.00%) Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// . /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the -- line 1007 ---------------------------------------- -- line 1020 ---------------------------------------- . /// assert_eq!(x.ok_or(0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or(0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 600,630 ( 0.01%) pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 1,841,578 ( 0.04%) match self { 537,492 ( 0.01%) Some(v) => Ok(v), 1,094 ( 0.00%) None => Err(err), . } 923,006 ( 0.02%) } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// . /// [`Ok(v)`]: Ok . /// [`Err(err())`]: Err . /// [`Some(v)`]: Some . /// -- line 1044 ---------------------------------------- -- line 1049 ---------------------------------------- . /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or_else(|| 0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 6,354 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 60,380 ( 0.00%) match self { 46,651 ( 0.00%) Some(v) => Ok(v), 27,072 ( 0.00%) None => Err(err()), . } 5,295 ( 0.00%) } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// . /// # Examples . /// -- line 1074 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 16,231 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1213 ---------------------------------------- . /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); . /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); . /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); . /// assert_eq!(None.and_then(sq).and_then(sq), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 7,369 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 157,424 ( 0.00%) match self { 30,463 ( 0.00%) Some(x) => f(x), 42 ( 0.00%) None => None, . } 30,630 ( 0.00%) } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped . /// value), and . /// - [`None`] if `predicate` returns `false`. . /// -- line 1238 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 3,137 ( 0.00%) if let Some(x) = self { 2,784 ( 0.00%) if predicate(&x) { 377 ( 0.00%) return Some(x); . } . } . None 3 ( 0.00%) } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. . /// . /// [`or_else`]: Option::or_else -- line 1279 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 6,478 ( 0.00%) match self { 952 ( 0.00%) Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// . /// # Examples -- line 1316 ---------------------------------------- -- line 1321 ---------------------------------------- . /// . /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); . /// assert_eq!(None.or_else(vikings), Some("vikings")); . /// assert_eq!(None.or_else(nobody), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 137,288 ( 0.00%) pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 198,552 ( 0.00%) match self { 74,501 ( 0.00%) Some(x) => Some(x), 77,995 ( 0.00%) None => f(), . } 117,444 ( 0.00%) } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// . /// ``` . /// let x = Some(2); . /// let y: Option = None; -- line 1346 ---------------------------------------- -- line 1431 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert(&mut self, value: T) -> &mut T . where . T: ~const Drop, . { 50,229 ( 0.00%) if let None = *self { 117,097 ( 0.00%) *self = Some(value); . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . /// Inserts the default value into the option if it is [`None`], then -- line 1448 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 1,030,854 ( 0.02%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. 18 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1532 ---------------------------------------- . /// let mut x: Option = None; . /// let y = x.take(); . /// assert_eq!(x, None); . /// assert_eq!(y, None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 305,790 ( 0.01%) pub const fn take(&mut self) -> Option { . // FIXME replace `mem::replace` by `mem::take` when the latter is const ready 324,444 ( 0.01%) mem::replace(self, None) 192,746 ( 0.00%) } . . /// Replaces the actual value in the option by the value given in parameter, . /// returning the old value if present, . /// leaving a [`Some`] in its place without deinitializing either one. . /// . /// # Examples . /// . /// ``` -- line 1551 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 2,732 ( 0.00%) mem::replace(self, Some(value)) . } . . /// Returns `true` if the option is a [`Some`] value containing the given value. . /// . /// # Examples . /// . /// ``` . /// #![feature(option_result_contains)] -- line 1574 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 48,144 ( 0.00%) match self { 719,177 ( 0.02%) Some(&v) => Some(v), 3,329 ( 0.00%) None => None, . } 46 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 16,407 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 155,696 ( 0.00%) match self { 289,701 ( 0.01%) Some(t) => Some(t.clone()), 10,433 ( 0.00%) None => None, . } 40,263 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1842 ---------------------------------------- . . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] 66,353 ( 0.00%) fn clone(&self) -> Self { 2,437,995 ( 0.05%) match self { 157,953 ( 0.00%) Some(x) => Some(x.clone()), 3,540 ( 0.00%) None => None, . } 692,291 ( 0.02%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 1870 ---------------------------------------- . /// . /// # Examples . /// . /// ``` . /// let opt: Option = Option::default(); . /// assert!(opt.is_none()); . /// ``` . #[inline] 20,145 ( 0.00%) fn default() -> Option { 20,145 ( 0.00%) None 60,435 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Option { . type Item = T; . type IntoIter = IntoIter; . . /// Returns a consuming iterator over the possibly contained value. -- line 1888 ---------------------------------------- -- line 1894 ---------------------------------------- . /// let v: Vec<&str> = x.into_iter().collect(); . /// assert_eq!(v, ["string"]); . /// . /// let x = None; . /// let v: Vec<&str> = x.into_iter().collect(); . /// assert!(v.is_empty()); . /// ``` . #[inline] 131,404 ( 0.00%) fn into_iter(self) -> IntoIter { 425,586 ( 0.01%) IntoIter { inner: Item { opt: self } } 107,377 ( 0.00%) } . } . . #[stable(since = "1.4.0", feature = "option_iter")] . impl<'a, T> IntoIterator for &'a Option { . type Item = &'a T; . type IntoIter = Iter<'a, T>; . . fn into_iter(self) -> Iter<'a, T> { -- line 1912 ---------------------------------------- -- line 2000 ---------------------------------------- . struct Item { . opt: Option, . } . . impl Iterator for Item { . type Item = A; . . #[inline] 302,330 ( 0.01%) fn next(&mut self) -> Option { 137,638 ( 0.00%) self.opt.take() 189,520 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 56,489 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2131 ---------------------------------------- . inner: Item, . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = A; . . #[inline] 302,330 ( 0.01%) fn next(&mut self) -> Option { 137,638 ( 0.00%) self.inner.next() 189,520 ( 0.00%) } . #[inline] . fn size_hint(&self) -> (usize, Option) { 94 ( 0.00%) self.inner.size_hint() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . self.inner.next_back() -- line 2152 ---------------------------------------- -- line 2241 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Option { . type Output = T; . type Residual = Option; . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) 3,415 ( 0.00%) } . . #[inline] 746,026 ( 0.02%) fn branch(self) -> ControlFlow { 3,175,987 ( 0.07%) match self { 1,348,701 ( 0.03%) Some(v) => ControlFlow::Continue(v), 35,168 ( 0.00%) None => ControlFlow::Break(None), . } 1,050,126 ( 0.02%) } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] 20,059 ( 0.00%) fn from_residual(residual: Option) -> Self { . match residual { 108,449 ( 0.00%) None => None, . } 65,386 ( 0.00%) } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } . . impl Option> { -- line 2276 ---------------------------------------- 5,816,134 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs -------------------------------------------------------------------------------- Ir -- line 13 ---------------------------------------- . reserve: extern "C" fn(Buffer, usize) -> Buffer, . drop: extern "C" fn(Buffer), . } . . unsafe impl Sync for Buffer {} . unsafe impl Send for Buffer {} . . impl Default for Buffer { 702 ( 0.00%) fn default() -> Self { 936 ( 0.00%) Self::from(vec![]) 468 ( 0.00%) } . } . . impl Deref for Buffer { . type Target = [T]; 117 ( 0.00%) fn deref(&self) -> &[T] { 1,182,612 ( 0.03%) unsafe { slice::from_raw_parts(self.data as *const T, self.len) } 78 ( 0.00%) } . } . . impl DerefMut for Buffer { . fn deref_mut(&mut self) -> &mut [T] { . unsafe { slice::from_raw_parts_mut(self.data, self.len) } . } . } . . impl Buffer { . pub(super) fn new() -> Self { . Self::default() . } . 78 ( 0.00%) pub(super) fn clear(&mut self) { 2,505,783 ( 0.05%) self.len = 0; 78 ( 0.00%) } . 936 ( 0.00%) pub(super) fn take(&mut self) -> Self { 234 ( 0.00%) mem::take(self) 468 ( 0.00%) } . . // We have the array method separate from extending from a slice. This is . // because in the case of small arrays, codegen can be more efficient . // (avoiding a memmove call). With extend_from_slice, LLVM at least . // currently is not able to make that optimization. 195 ( 0.00%) pub(super) fn extend_from_array(&mut self, xs: &[T; N]) { 5,278,982 ( 0.11%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 1,638 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 898,460 ( 0.02%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 2,699,683 ( 0.06%) self.len += xs.len(); . } 78 ( 0.00%) } . 34,008 ( 0.00%) pub(super) fn extend_from_slice(&mut self, xs: &[T]) { 545,826 ( 0.01%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 1,638 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 78 ( 0.00%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 272,913 ( 0.01%) self.len += xs.len(); . } 39,676 ( 0.00%) } . 234 ( 0.00%) pub(super) fn push(&mut self, v: T) { . // The code here is taken from Vec::push, and we know that reserve() . // will panic if we're exceeding isize::MAX bytes and so there's no need . // to check for overflow. 6,178,228 ( 0.13%) if self.len == self.capacity { . let b = self.take(); . *self = (b.reserve)(b, 1); . } . unsafe { 4,181,146 ( 0.09%) *self.data.add(self.len) = v; 3,613,854 ( 0.08%) self.len += 1; . } 78 ( 0.00%) } . } . . impl Write for Buffer { . fn write(&mut self, xs: &[u8]) -> io::Result { . self.extend_from_slice(xs); . Ok(xs.len()) . } . 511,818 ( 0.01%) fn write_all(&mut self, xs: &[u8]) -> io::Result<()> { 17,004 ( 0.00%) self.extend_from_slice(xs); . Ok(()) 767,727 ( 0.02%) } . . fn flush(&mut self) -> io::Result<()> { . Ok(()) . } . } . . impl Drop for Buffer { 351 ( 0.00%) fn drop(&mut self) { 234 ( 0.00%) let b = self.take(); 6,316,167 ( 0.14%) (b.drop)(b); 234 ( 0.00%) } . } . . impl From> for Buffer { 1,404 ( 0.00%) fn from(mut v: Vec) -> Self { 6,084 ( 0.00%) let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity()); 1,872 ( 0.00%) mem::forget(v); . . // This utility function is nested in here because it can *only* . // be safely called on `Buffer`s created by *this* `proc_macro`. 351 ( 0.00%) fn to_vec(b: Buffer) -> Vec { . unsafe { 1,053 ( 0.00%) let Buffer { data, len, capacity, .. } = b; 585 ( 0.00%) mem::forget(b); 117 ( 0.00%) Vec::from_raw_parts(data, len, capacity) . } 234 ( 0.00%) } . 624 ( 0.00%) extern "C" fn reserve(b: Buffer, additional: usize) -> Buffer { 468 ( 0.00%) let mut v = to_vec(b); . v.reserve(additional); 468 ( 0.00%) Buffer::from(v) 624 ( 0.00%) } . 234 ( 0.00%) extern "C" fn drop(b: Buffer) { 527,176 ( 0.01%) mem::drop(to_vec(b)); 526,396 ( 0.01%) } . 3,042 ( 0.00%) Buffer { data, len, capacity, reserve, drop } 468 ( 0.00%) } . } 2,849,723 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs -------------------------------------------------------------------------------- Ir -- line 491 ---------------------------------------- . . use crate::iter::{self, FromIterator, FusedIterator, TrustedLen}; . use crate::ops::{self, ControlFlow, Deref, DerefMut}; . use crate::{convert, fmt, hint}; . . /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]). . /// . /// See the [module documentation](self) for details. 302 ( 0.00%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[must_use = "this `Result` may be an `Err` variant, which should be handled"] . #[rustc_diagnostic_item = "Result"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Result { . /// Contains the success value . #[lang = "Ok"] . #[stable(feature = "rust1", since = "1.0.0")] 63 ( 0.00%) Ok(#[stable(feature = "rust1", since = "1.0.0")] T), . . /// Contains the error value . #[lang = "Err"] . #[stable(feature = "rust1", since = "1.0.0")] . Err(#[stable(feature = "rust1", since = "1.0.0")] E), . } . . ///////////////////////////////////////////////////////////////////////////// -- line 515 ---------------------------------------- -- line 533 ---------------------------------------- . /// . /// let x: Result = Err("Some error message"); . /// assert_eq!(x.is_ok(), false); . /// ``` . #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"] . #[rustc_const_stable(feature = "const_result", since = "1.48.0")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 10,286 ( 0.00%) pub const fn is_ok(&self) -> bool { 19,701 ( 0.00%) matches!(*self, Ok(_)) 25,715 ( 0.00%) } . . /// Returns `true` if the result is [`Ok`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] . /// -- line 551 ---------------------------------------- -- line 627 ---------------------------------------- . /// let x: Result = Ok(2); . /// assert_eq!(x.ok(), Some(2)); . /// . /// let x: Result = Err("Nothing here"); . /// assert_eq!(x.ok(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 4,908 ( 0.00%) pub fn ok(self) -> Option { 60,327 ( 0.00%) match self { 19,236 ( 0.00%) Ok(x) => Some(x), 2,386 ( 0.00%) Err(_) => None, . } 21,951 ( 0.00%) } . . /// Converts from `Result` to [`Option`]. . /// . /// Converts `self` into an [`Option`], consuming `self`, . /// and discarding the success value, if any. . /// . /// # Examples . /// -- line 648 ---------------------------------------- -- line 657 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn err(self) -> Option { . match self { . Ok(_) => None, . Err(x) => Some(x), . } 4 ( 0.00%) } . . ///////////////////////////////////////////////////////////////////////// . // Adapter for working with references . ///////////////////////////////////////////////////////////////////////// . . /// Converts from `&Result` to `Result<&T, &E>`. . /// . /// Produces a new `Result`, containing a reference -- line 673 ---------------------------------------- -- line 683 ---------------------------------------- . /// . /// let x: Result = Err("Error"); . /// assert_eq!(x.as_ref(), Err(&"Error")); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_result", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn as_ref(&self) -> Result<&T, &E> { 62 ( 0.00%) match *self { . Ok(ref x) => Ok(x), . Err(ref x) => Err(x), . } . } . . /// Converts from `&mut Result` to `Result<&mut T, &mut E>`. . /// . /// # Examples -- line 699 ---------------------------------------- -- line 715 ---------------------------------------- . /// let mut x: Result = Err(13); . /// mutate(&mut x); . /// assert_eq!(x.unwrap_err(), 0); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_result", issue = "82814")] . pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> { 2,035 ( 0.00%) match *self { . Ok(ref mut x) => Ok(x), . Err(ref mut x) => Err(x), . } . } . . ///////////////////////////////////////////////////////////////////////// . // Transforming contained values . ///////////////////////////////////////////////////////////////////////// -- line 731 ---------------------------------------- -- line 746 ---------------------------------------- . /// match num.parse::().map(|i| i * 2) { . /// Ok(n) => println!("{}", n), . /// Err(..) => {} . /// } . /// } . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 17,584 ( 0.00%) pub fn map U>(self, op: F) -> Result { 420,998 ( 0.01%) match self { 487,479 ( 0.01%) Ok(t) => Ok(op(t)), 111,799 ( 0.00%) Err(e) => Err(e), . } 22,001 ( 0.00%) } . . /// Returns the provided default (if [`Err`]), or . /// applies a function to the contained value (if [`Ok`]), . /// . /// Arguments passed to `map_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`map_or_else`], . /// which is lazily evaluated. . /// -- line 767 ---------------------------------------- -- line 774 ---------------------------------------- . /// assert_eq!(x.map_or(42, |v| v.len()), 3); . /// . /// let x: Result<&str, _> = Err("bar"); . /// assert_eq!(x.map_or(42, |v| v.len()), 42); . /// ``` . #[inline] . #[stable(feature = "result_map_or", since = "1.41.0")] . pub fn map_or U>(self, default: U, f: F) -> U { 1,565 ( 0.00%) match self { 721 ( 0.00%) Ok(t) => f(t), . Err(_) => default, . } . } . . /// Maps a `Result` to `U` by applying fallback function `default` to . /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value. . /// . /// This function can be used to unpack a successful result -- line 791 ---------------------------------------- -- line 831 ---------------------------------------- . /// let x: Result = Ok(2); . /// assert_eq!(x.map_err(stringify), Ok(2)); . /// . /// let x: Result = Err(13); . /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 605,412 ( 0.01%) pub fn map_err F>(self, op: O) -> Result { 2,924,232 ( 0.06%) match self { 3,313,853 ( 0.07%) Ok(t) => Ok(t), 14,261 ( 0.00%) Err(e) => Err(op(e)), . } 569,819 ( 0.01%) } . . /// Calls the provided closure with a reference to the contained value (if [`Ok`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 852 ---------------------------------------- -- line 1008 ---------------------------------------- . /// . /// ```should_panic . /// let x: Result = Err("emergency failure"); . /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "result_expect", since = "1.4.0")] 255,601 ( 0.01%) pub fn expect(self, msg: &str) -> T . where . E: fmt::Debug, . { 1,025,463 ( 0.02%) match self { 300,665 ( 0.01%) Ok(t) => t, . Err(e) => unwrap_failed(msg, &e), . } 58,986 ( 0.00%) } . . /// Returns the contained [`Ok`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`Err`] . /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or . /// [`unwrap_or_default`]. . /// -- line 1032 ---------------------------------------- -- line 1051 ---------------------------------------- . /// . /// ```should_panic . /// let x: Result = Err("emergency failure"); . /// x.unwrap(); // panics with `emergency failure` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] 1,254 ( 0.00%) pub fn unwrap(self) -> T . where . E: fmt::Debug, . { 405,754 ( 0.01%) match self { 205,471 ( 0.00%) Ok(t) => t, . Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), . } 1,452 ( 0.00%) } . . /// Returns the contained [`Ok`] value or a default . /// . /// Consumes the `self` argument then, if [`Ok`], returns the contained . /// value, otherwise if [`Err`], returns the default value for that . /// type. . /// . /// # Examples -- line 1075 ---------------------------------------- -- line 1092 ---------------------------------------- . /// [`parse`]: str::parse . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "result_unwrap_or_default", since = "1.16.0")] . pub fn unwrap_or_default(self) -> T . where . T: Default, . { 3,359 ( 0.00%) match self { 2,100 ( 0.00%) Ok(x) => x, . Err(_) => Default::default(), . } . } . . /// Returns the contained [`Err`] value, consuming the `self` value. . /// . /// # Panics . /// -- line 1109 ---------------------------------------- -- line 1152 ---------------------------------------- . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn unwrap_err(self) -> E . where . T: fmt::Debug, . { 664 ( 0.00%) match self { . Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t), . Err(e) => e, . } . } . . /// Returns the contained [`Ok`] value, but never panics. . /// . /// Unlike [`unwrap`], this method is known to never panic on the -- line 1168 ---------------------------------------- -- line 1190 ---------------------------------------- . /// ``` . #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] . #[inline] . pub fn into_ok(self) -> T . where . E: Into, . { . match self { 1,557,302 ( 0.03%) Ok(x) => x, . Err(e) => e.into(), . } . } . . /// Returns the contained [`Err`] value, but never panics. . /// . /// Unlike [`unwrap_err`], this method is known to never panic on the . /// result types it is implemented for. Therefore, it can be used -- line 1206 ---------------------------------------- -- line 1290 ---------------------------------------- . /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16)); . /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4)); . /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2)); . /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn and_then Result>(self, op: F) -> Result { 36,897 ( 0.00%) match self { 92,868 ( 0.00%) Ok(t) => op(t), 2,932 ( 0.00%) Err(e) => Err(e), . } . } . . /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. -- line 1308 ---------------------------------------- -- line 1355 ---------------------------------------- . /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); . /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); . /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); . /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn or_else Result>(self, op: O) -> Result { 11,836 ( 0.00%) match self { 30,236 ( 0.00%) Ok(t) => Ok(t), . Err(e) => op(e), . } . } . . /// Returns the contained [`Ok`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 1372 ---------------------------------------- -- line 1384 ---------------------------------------- . /// assert_eq!(x.unwrap_or(default), 9); . /// . /// let x: Result = Err("error"); . /// assert_eq!(x.unwrap_or(default), default); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn unwrap_or(self, default: T) -> T { 7,896 ( 0.00%) match self { 6 ( 0.00%) Ok(t) => t, . Err(_) => default, . } . } . . /// Returns the contained [`Ok`] value or computes it from a closure. . /// . /// . /// # Examples -- line 1401 ---------------------------------------- -- line 1405 ---------------------------------------- . /// ``` . /// fn count(x: &str) -> usize { x.len() } . /// . /// assert_eq!(Ok(2).unwrap_or_else(count), 2); . /// assert_eq!(Err("foo").unwrap_or_else(count), 3); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 156 ( 0.00%) pub fn unwrap_or_else T>(self, op: F) -> T { 1,152,980 ( 0.03%) match self { 506,000 ( 0.01%) Ok(t) => t, . Err(e) => op(e), . } 195 ( 0.00%) } . . /// Returns the contained [`Ok`] value, consuming the `self` value, . /// without checking that the value is not an [`Err`]. . /// . /// # Safety . /// . /// Calling this method on an [`Err`] is *[undefined behavior]*. . /// -- line 1426 ---------------------------------------- -- line 1647 ---------------------------------------- . /// let x: Result, SomeErr> = Ok(Some(5)); . /// let y: Option> = Some(Ok(5)); . /// assert_eq!(x.transpose(), y); . /// ``` . #[inline] . #[stable(feature = "transpose_result", since = "1.33.0")] . #[rustc_const_unstable(feature = "const_result", issue = "82814")] . pub const fn transpose(self) -> Option> { 678 ( 0.00%) match self { . Ok(Some(x)) => Some(Ok(x)), . Ok(None) => None, . Err(e) => Some(Err(e)), . } . } . } . . impl Result, E> { -- line 1663 ---------------------------------------- -- line 1751 ---------------------------------------- . . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Result { . #[inline] 45,743 ( 0.00%) fn clone(&self) -> Self { 369,425 ( 0.01%) match self { 216,805 ( 0.00%) Ok(x) => Ok(x.clone()), 53,412 ( 0.00%) Err(x) => Err(x.clone()), . } 94,314 ( 0.00%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Ok(to), Ok(from)) => to.clone_from(from), . (Err(to), Err(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } -- line 1772 ---------------------------------------- -- line 2011 ---------------------------------------- . /// . /// Since the third element caused an underflow, no further elements were taken, . /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. . #[inline] . fn from_iter>>(iter: I) -> Result { . // FIXME(#11084): This could be replaced with Iterator::scan when this . // performance bug is closed. . 25,657 ( 0.00%) iter::process_results(iter.into_iter(), |i| i.collect()) . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Result { . type Output = T; . type Residual = Result; . . #[inline] . fn from_output(output: Self::Output) -> Self { 2,000 ( 0.00%) Ok(output) . } . . #[inline] 1,270,859 ( 0.03%) fn branch(self) -> ControlFlow { 4,104,354 ( 0.09%) match self { 4,882,655 ( 0.11%) Ok(v) => ControlFlow::Continue(v), 362,400 ( 0.01%) Err(e) => ControlFlow::Break(Err(e)), . } 890,466 ( 0.02%) } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl> const ops::FromResidual> . for Result . { . #[inline] . #[track_caller] 15,642 ( 0.00%) fn from_residual(residual: Result) -> Self { . match residual { 265,432 ( 0.01%) Err(e) => Err(From::from(e)), . } 10,428 ( 0.00%) } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Result { . type TryType = Result; . } 2,854,323 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs -------------------------------------------------------------------------------- Ir -- line 136 ---------------------------------------- . /// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak . /// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw . /// [`mem::drop`]: drop . /// [ub]: ../../reference/behavior-considered-undefined.html . #[inline] . #[rustc_const_stable(feature = "const_forget", since = "1.46.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_forget")] 7,728 ( 0.00%) pub const fn forget(t: T) { 2,457 ( 0.00%) let _ = ManuallyDrop::new(t); 3,762 ( 0.00%) } . . /// Like [`forget`], but also accepts unsized values. . /// . /// This function is just a shim intended to be removed when the `unsized_locals` feature gets . /// stabilized. . #[inline] . #[unstable(feature = "forget_unsized", issue = "none")] . pub fn forget_unsized(t: T) { -- line 154 ---------------------------------------- -- line 324 ---------------------------------------- . /// let y: &[u8] = &x; . /// assert_eq!(13, mem::size_of_val(y)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] 296,945 ( 0.01%) pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 451,336 ( 0.01%) unsafe { intrinsics::size_of_val(val) } 210,888 ( 0.00%) } . . /// Returns the size of the pointed-to value in bytes. . /// . /// This is usually the same as `size_of::()`. However, when `T` *has* no . /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], . /// then `size_of_val_raw` can be used to get the dynamically-known size. . /// . /// # Safety -- line 343 ---------------------------------------- -- line 375 ---------------------------------------- . /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "layout_for_ptr", issue = "69835")] . #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")] . pub const unsafe fn size_of_val_raw(val: *const T) -> usize { . // SAFETY: the caller must provide a valid raw pointer 238 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the [ABI]-required minimum alignment of a type. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. . /// -- line 391 ---------------------------------------- -- line 467 ---------------------------------------- . /// . /// assert_eq!(4, mem::align_of_val(&5i32)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")] . #[allow(deprecated)] 38,774 ( 0.00%) pub const fn align_of_val(val: &T) -> usize { . // SAFETY: val is a reference, so it's a valid raw pointer 58,161 ( 0.00%) unsafe { intrinsics::min_align_of_val(val) } 38,774 ( 0.00%) } . . /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface . /// . /// # Safety -- line 486 ---------------------------------------- -- line 578 ---------------------------------------- . /// } . /// } . /// ``` . #[inline] . #[must_use] . #[stable(feature = "needs_drop", since = "1.21.0")] . #[rustc_const_stable(feature = "const_needs_drop", since = "1.36.0")] . #[rustc_diagnostic_item = "needs_drop"] 1 ( 0.00%) pub const fn needs_drop() -> bool { 3 ( 0.00%) intrinsics::needs_drop::() 4 ( 0.00%) } . . /// Returns the value of type `T` represented by the all-zero byte-pattern. . /// . /// This means that, for example, the padding byte in `(u8, u16)` is not . /// necessarily zeroed. . /// . /// There is no guarantee that an all-zero byte-pattern represents a valid value . /// of some type `T`. For example, the all-zero byte-pattern is not a valid value -- line 596 ---------------------------------------- -- line 759 ---------------------------------------- . /// let mut buffer = Buffer { buf: vec![0, 1] }; . /// assert_eq!(buffer.buf.len(), 2); . /// . /// assert_eq!(buffer.get_and_reset(), vec![0, 1]); . /// assert_eq!(buffer.buf.len(), 0); . /// ``` . #[inline] . #[stable(feature = "mem_take", since = "1.40.0")] 1,170 ( 0.00%) pub fn take(dest: &mut T) -> T { 936 ( 0.00%) replace(dest, T::default()) 468 ( 0.00%) } . . /// Moves `src` into the referenced `dest`, returning the previous `dest` value. . /// . /// Neither value is dropped. . /// . /// * If you want to replace the values of two variables, see [`swap`]. . /// * If you want to replace with a default value, see [`take`]. . /// -- line 777 ---------------------------------------- -- line 826 ---------------------------------------- . /// assert_eq!(buffer.replace_index(0, 2), 0); . /// assert_eq!(buffer.buf[0], 2); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "if you don't need the old value, you can just assign the new value directly"] . #[rustc_const_unstable(feature = "const_replace", issue = "83164")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] 1,843,242 ( 0.04%) pub const fn replace(dest: &mut T, src: T) -> T { . // SAFETY: We read from `dest` but directly write `src` into it afterwards, . // such that the old value is not duplicated. Nothing is dropped and . // nothing here can panic. . unsafe { 2,671,436 ( 0.06%) let result = ptr::read(dest); 21,443,442 ( 0.47%) ptr::write(dest, src); . result . } 797,795 ( 0.02%) } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// . /// This effectively does nothing for types which implement `Copy`, e.g. . /// integers. Such values are copied and _then_ moved into the function, so the . /// value persists after this function call. -- line 851 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 991,588 ( 0.02%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 947 ---------------------------------------- . /// . /// // The contents of 'foo_array' should not have changed . /// assert_eq!(foo_array, [10]); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_transmute_copy", issue = "83165")] 585 ( 0.00%) pub const unsafe fn transmute_copy(src: &T) -> U { . // If U has a higher alignment requirement, src might not be suitably aligned. 234 ( 0.00%) if align_of::() > align_of::() { . // SAFETY: `src` is a reference which is guaranteed to be valid for reads. . // The caller must guarantee that the actual transmutation is safe. . unsafe { ptr::read_unaligned(src as *const T as *const U) } . } else { . // SAFETY: `src` is a reference which is guaranteed to be valid for reads. . // We just checked that `src as *const U` was properly aligned. . // The caller must guarantee that the actual transmutation is safe. 234 ( 0.00%) unsafe { ptr::read(src as *const T as *const U) } . } 234 ( 0.00%) } . . /// Opaque type representing the discriminant of an enum. . /// . /// See the [`discriminant`] function in this module for more information. . #[stable(feature = "discriminant_value", since = "1.21.0")] . pub struct Discriminant(::Discriminant); . . // N.B. These trait implementations cannot be derived because we don't want any bounds on T. -- line 975 ---------------------------------------- -- line 991 ---------------------------------------- . } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl cmp::Eq for Discriminant {} . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl hash::Hash for Discriminant { 1,425 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 2,550 ( 0.00%) } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl fmt::Debug for Discriminant { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt.debug_tuple("Discriminant").field(&self.0).finish() . } . } -- line 1009 ---------------------------------------- -- line 1031 ---------------------------------------- . /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); . /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); . /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3))); . /// ``` . #[stable(feature = "discriminant_value", since = "1.21.0")] . #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")] . pub const fn discriminant(v: &T) -> Discriminant { 22,825 ( 0.00%) Discriminant(intrinsics::discriminant_value(v)) . } . . /// Returns the number of variants in the enum type `T`. . /// . /// If `T` is not an enum, calling this function will not result in undefined behavior, but the . /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` . /// the return value is unspecified. Uninhabited variants will be counted. . /// -- line 1047 ---------------------------------------- 1,222,998 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 408 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 204 ( 0.00%) from_str_radix(src, radix) 612 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 220,335 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 555,389 ( 0.01%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 515,015 ( 0.01%) intrinsics::cttz(self) as u32 . } . . /// Returns the number of leading ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 155 ---------------------------------------- -- line 204 ---------------------------------------- . #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn rotate_left(self, n: u32) -> Self { 15,503,489 ( 0.34%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 429 ---------------------------------------- . )] . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 182,400 ( 0.00%) pub const fn checked_add(self, rhs: Self) -> Option { 146,179 ( 0.00%) let (a, b) = self.overflowing_add(rhs); 364,800 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 145,920 ( 0.00%) } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// . /// This results in undefined behavior when . #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")] -- line 448 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 1,067,729 ( 0.02%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 58,753 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 544 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")] . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 228,972 ( 0.00%) pub const fn checked_mul(self, rhs: Self) -> Option { 152,648 ( 0.00%) let (a, b) = self.overflowing_mul(rhs); 381,620 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 152,648 ( 0.00%) } . . /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// . /// This results in undefined behavior when . #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")] -- line 563 ---------------------------------------- -- line 596 ---------------------------------------- . without modifying the original"] . #[inline] . pub const fn checked_div(self, rhs: Self) -> Option { . if unlikely!(rhs == 0) { . None . } else { . // SAFETY: div by zero has been checked above and unsigned types have no other . // failure modes for division 1,752 ( 0.00%) Some(unsafe { intrinsics::unchecked_div(self, rhs) }) . } . } . . /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` . /// if `rhs == 0`. . /// . /// # Examples . /// -- line 612 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 257,747 ( 0.01%) intrinsics::saturating_add(self, rhs) . } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1051 ---------------------------------------- -- line 1084 ---------------------------------------- . #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_sub(self, rhs: Self) -> Self { 9,491 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 7,186,392 ( 0.16%) intrinsics::wrapping_add(self, rhs) . } . . /// Wrapping (modular) addition with a signed integer. Computes . /// `self + rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_sub(self, rhs: Self) -> Self { 3,254,538 ( 0.07%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 8,496,535 ( 0.18%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 4 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 1491 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")] . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 17 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 1,488,002 ( 0.03%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); 72,960 ( 0.00%) (a as Self, b) 145,954 ( 0.00%) } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. . /// . #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] -- line 1510 ---------------------------------------- -- line 1587 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")] . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 1 ( 0.00%) pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 279,469 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 2 ( 0.00%) } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. . /// . /// # Examples -- line 1606 ---------------------------------------- -- line 1674 ---------------------------------------- . /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 2,509,922 ( 0.05%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); 76,324 ( 0.00%) (a as Self, b) 152,648 ( 0.00%) } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always . /// `false`. . /// -- line 1692 ---------------------------------------- -- line 1701 ---------------------------------------- . /// ``` . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")] . /// ``` . #[inline(always)] . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] 4 ( 0.00%) pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) { 16 ( 0.00%) (self / rhs, false) 12 ( 0.00%) } . . /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always . /// `false`. . /// Since, for the positive integers, all common -- line 1719 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 180 ( 0.00%) self.count_ones() == 1 . } . . // Returns one less than next power of two. . // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) . // . // 8u8.one_less_than_next_power_of_two() == 7 . // 6u8.one_less_than_next_power_of_two() == 7 . // . // This method cannot overflow, as in the `next_power_of_two` . // overflow cases it instead ends up returning the maximum value . // of the type, and can return 0 for 0. . #[inline] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . const fn one_less_than_next_power_of_two(self) -> Self { 22,976 ( 0.00%) if self <= 1 { return 0; } . 110,993 ( 0.00%) let p = self - 1; . // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros. . // That means the shift is always in-bounds, and some processors . // (such as intel pre-haswell) have more efficient ctlz . // intrinsics when the argument is non-zero. 332,325 ( 0.01%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 111,567 ( 0.00%) <$SelfT>::MAX >> z . } . . /// Returns the smallest power of two greater than or equal to `self`. . /// . /// When return value overflows (i.e., `self > (1 << (N-1))` for type . /// `uN`), it panics in debug mode and the return value is wrapped to 0 in . /// release mode (the only situation in which method can return 0). . /// -- line 2171 ---------------------------------------- -- line 2179 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . #[rustc_inherit_overflow_checks] . pub const fn next_power_of_two(self) -> Self { 198,970 ( 0.00%) self.one_less_than_next_power_of_two() + 1 . } . . /// Returns the smallest power of two greater than or equal to `n`. If . /// the next power of two is greater than the type's maximum value, . /// `None` is returned, otherwise the power of two is wrapped in `Some`. . /// . /// # Examples . /// -- line 2195 ---------------------------------------- -- line 2264 ---------------------------------------- . #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")] . #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")] . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 195 ( 0.00%) pub const fn to_le_bytes(self) -> [u8; mem::size_of::()] { 156 ( 0.00%) self.to_le().to_ne_bytes() 117 ( 0.00%) } . . /// Return the memory representation of this integer as a byte array in . /// native byte order. . /// . /// As the target platform's native endianness is used, portable code . /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, . /// instead. . /// -- line 2282 ---------------------------------------- -- line 2300 ---------------------------------------- . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . // SAFETY: const sound because integers are plain old datatypes so we can always . // transmute them to arrays of bytes . #[inline] 78 ( 0.00%) pub const fn to_ne_bytes(self) -> [u8; mem::size_of::()] { . // SAFETY: integers are plain old datatypes so we can always transmute them to . // arrays of bytes 39 ( 0.00%) unsafe { mem::transmute(self) } 117 ( 0.00%) } . . /// Create a native endian integer value from its representation . /// as a byte array in big endian. . /// . #[doc = $from_xe_bytes_doc] . /// . /// # Examples . /// -- line 2320 ---------------------------------------- -- line 2360 ---------------------------------------- . /// *input = rest; . #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")] . /// } . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use] . #[inline] 312 ( 0.00%) pub const fn from_le_bytes(bytes: [u8; mem::size_of::()]) -> Self { 390 ( 0.00%) Self::from_le(Self::from_ne_bytes(bytes)) 156 ( 0.00%) } . . /// Create a native endian integer value from its memory representation . /// as a byte array in native endianness. . /// . /// As the target platform's native endianness is used, portable code . /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as . /// appropriate instead. . /// -- line 2378 ---------------------------------------- -- line 2402 ---------------------------------------- . /// } . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use] . // SAFETY: const sound because integers are plain old datatypes so we can always . // transmute to them . #[inline] 312 ( 0.00%) pub const fn from_ne_bytes(bytes: [u8; mem::size_of::()]) -> Self { . // SAFETY: integers are plain old datatypes so we can always transmute to them 468 ( 0.00%) unsafe { mem::transmute(bytes) } 156 ( 0.00%) } . . /// New code should prefer to use . #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")] . /// . /// Returns the smallest value that can be represented by this integer type. . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_promotable] . #[inline(always)] -- line 2421 ---------------------------------------- 576,073 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// use std::ptr::NonNull; . /// . /// // NEVER DO THAT!!! This is undefined behavior. ⚠️ . /// let ptr = unsafe { NonNull::::new_unchecked(std::ptr::null_mut()) }; . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")] . #[inline] 1,684,181 ( 0.04%) pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { . // SAFETY: the caller must guarantee that `ptr` is non-null. 3,420,292 ( 0.07%) unsafe { NonNull { pointer: ptr as _ } } 2,486,344 ( 0.05%) } . . /// Creates a new `NonNull` if `ptr` is non-null. . /// . /// # Examples . /// . /// ``` . /// use std::ptr::NonNull; . /// -- line 205 ---------------------------------------- -- line 207 ---------------------------------------- . /// let ptr = NonNull::::new(&mut x as *mut _).expect("ptr is null!"); . /// . /// if let Some(ptr) = NonNull::::new(std::ptr::null_mut()) { . /// unreachable!(); . /// } . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[inline] 236,385 ( 0.01%) pub fn new(ptr: *mut T) -> Option { 393,975 ( 0.01%) if !ptr.is_null() { . // SAFETY: The pointer is already checked and is not null 236,385 ( 0.01%) Some(unsafe { Self::new_unchecked(ptr) }) . } else { . None . } 236,385 ( 0.01%) } . . /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a . /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer. . /// . /// See the documentation of [`std::ptr::from_raw_parts`] for more details. . /// . /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts . #[unstable(feature = "ptr_metadata", issue = "81513")] -- line 230 ---------------------------------------- -- line 268 ---------------------------------------- . /// unsafe { *ptr.as_ptr() += 2; } . /// let x_value = unsafe { *ptr.as_ptr() }; . /// assert_eq!(x_value, 2); . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")] . #[must_use] . #[inline] 4,911,359 ( 0.11%) pub const fn as_ptr(self) -> *mut T { . self.pointer as *mut T 3,167,766 ( 0.07%) } . . /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`] . /// must be used instead. . /// . /// For the mutable counterpart see [`as_mut`]. . /// . /// [`as_uninit_ref`]: NonNull::as_uninit_ref . /// [`as_mut`]: NonNull::as_mut -- line 286 ---------------------------------------- -- line 316 ---------------------------------------- . /// println!("{}", ref_x); . /// ``` . /// . /// [the module documentation]: crate::ptr#safety . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] . #[must_use] . #[inline] 421,388 ( 0.01%) pub const unsafe fn as_ref<'a>(&self) -> &'a T { . // SAFETY: the caller must guarantee that `self` meets all the . // requirements for a reference. 632,082 ( 0.01%) unsafe { &*self.as_ptr() } 421,388 ( 0.01%) } . . /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`] . /// must be used instead. . /// . /// For the shared counterpart see [`as_ref`]. . /// . /// [`as_uninit_mut`]: NonNull::as_uninit_mut . /// [`as_ref`]: NonNull::as_ref -- line 336 ---------------------------------------- -- line 391 ---------------------------------------- . /// let casted_ptr = ptr.cast::(); . /// let raw_ptr: *mut i8 = casted_ptr.as_ptr(); . /// ``` . #[stable(feature = "nonnull_cast", since = "1.27.0")] . #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 160,883 ( 0.00%) pub const fn cast(self) -> NonNull { . // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null 240,616 ( 0.01%) unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) } 120,180 ( 0.00%) } . } . . impl NonNull<[T]> { . /// Creates a non-null raw slice from a thin pointer and a length. . /// . /// The `len` argument is the number of **elements**, not the number of bytes. . /// . /// This function is safe, but dereferencing the return value is unsafe. -- line 410 ---------------------------------------- -- line 425 ---------------------------------------- . /// ``` . /// . /// (Note that this example artificially demonstrates a use of this method, . /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.) . #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")] . #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")] . #[must_use] . #[inline] 319,420 ( 0.01%) pub const fn slice_from_raw_parts(data: NonNull, len: usize) -> Self { . // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null 638,840 ( 0.01%) unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) } 159,710 ( 0.00%) } . . /// Returns the length of a non-null raw slice. . /// . /// The returned value is the number of **elements**, not the number of bytes. . /// . /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice . /// because the pointer does not have a valid address. . /// -- line 444 ---------------------------------------- -- line 469 ---------------------------------------- . /// . /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3); . /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap()); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "slice_ptr_get", issue = "74265")] . #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] 117,456 ( 0.00%) pub const fn as_non_null_ptr(self) -> NonNull { . // SAFETY: We know `self` is non-null. 195,760 ( 0.00%) unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) } 78,304 ( 0.00%) } . . /// Returns a raw pointer to the slice's buffer. . /// . /// # Examples . /// . /// ```rust . /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)] . /// use std::ptr::NonNull; -- line 488 ---------------------------------------- -- line 489 ---------------------------------------- . /// . /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3); . /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "slice_ptr_get", issue = "74265")] . #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] 117,456 ( 0.00%) pub const fn as_mut_ptr(self) -> *mut T { 156,608 ( 0.00%) self.as_non_null_ptr().as_ptr() 78,304 ( 0.00%) } . . /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to . /// [`as_ref`], this does not require that the value has to be initialized. . /// . /// For the mutable counterpart see [`as_uninit_slice_mut`]. . /// . /// [`as_ref`]: NonNull::as_ref . /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut -- line 507 ---------------------------------------- -- line 705 ---------------------------------------- . self.as_ptr().hash(state) . } . } . . #[unstable(feature = "ptr_internals", issue = "none")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From> for NonNull { . #[inline] 270,568 ( 0.01%) fn from(unique: Unique) -> Self { . // SAFETY: A Unique pointer cannot be null, so the conditions for . // new_unchecked() are respected. 541,136 ( 0.01%) unsafe { NonNull::new_unchecked(unique.as_ptr()) } 270,568 ( 0.01%) } . } . . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From<&mut T> for NonNull { . #[inline] 46,516 ( 0.00%) fn from(reference: &mut T) -> Self { . // SAFETY: A mutable reference cannot be null. 54,675 ( 0.00%) unsafe { NonNull { pointer: reference as *mut T } } 69,774 ( 0.00%) } . } . . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From<&T> for NonNull { . #[inline] . fn from(reference: &T) -> Self { . // SAFETY: A reference cannot be null, so the conditions for -- line 735 ---------------------------------------- 1,686,695 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . (type SourceFile: 'static + Clone;); . (type MultiSpan) => . (type MultiSpan: 'static;); . (type Diagnostic) => . (type Diagnostic: 'static;); . (type Span) => . (type Span: 'static + Copy + Eq + Hash;); . (fn drop(&mut self, $arg:ident: $arg_ty:ty)) => 48,438 ( 0.00%) (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) }); . (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) => 674 ( 0.00%) (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() }); . ($($item:tt)*) => ($($item)*;) . } . . macro_rules! declare_server_traits { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . pub trait Types { -- line 46 ---------------------------------------- -- line 64 ---------------------------------------- . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . impl Types for MarkedTypes { . $(type $name = Marked;)* . } . . $(impl $name for MarkedTypes { . $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? { 2,056,162 ( 0.04%) <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*)) . })* . })* . } . } . with_api!(Self, self_, define_mark_types_impls); . . struct Dispatcher { . handle_store: HandleStore, -- line 80 ---------------------------------------- -- line 89 ---------------------------------------- . pub trait DispatcherTrait { . // HACK(eddyb) these are here to allow `Self::$name` to work below. . $(type $name;)* . fn dispatch(&mut self, b: Buffer) -> Buffer; . } . . impl DispatcherTrait for Dispatcher> { . $(type $name = as Types>::$name;)* 5,261,620 ( 0.11%) fn dispatch(&mut self, mut b: Buffer) -> Buffer { . let Dispatcher { handle_store, server } = self; . 1,578,486 ( 0.03%) let mut reader = &b[..]; 3,683,134 ( 0.08%) match api_tags::Method::decode(&mut reader, &mut ()) { 2,557,905 ( 0.06%) $(api_tags::Method::$name(m) => match m { . $(api_tags::$name::$method => { . let mut call_method = || { 1,420,117 ( 0.03%) reverse_decode!(reader, handle_store; $($arg: $arg_ty),*); . $name::$method(server, $($arg),*) . }; . // HACK(eddyb) don't use `panic::catch_unwind` in a panic. . // If client and server happen to use the same `libstd`, . // `catch_unwind` asserts that the panic counter was 0, . // even when the closure passed to it didn't panic. . let r = if thread::panicking() { . Ok(call_method()) . } else { 2,678,284 ( 0.06%) panic::catch_unwind(panic::AssertUnwindSafe(call_method)) . .map_err(PanicMessage::from) . }; . . b.clear(); 5,883,525 ( 0.13%) r.encode(&mut b, handle_store); . })* . }),* . } 3,156,972 ( 0.07%) b 4,735,458 ( 0.10%) } . } . } . } . with_api!(Self, self_, define_dispatcher_impl); . . pub trait ExecutionStrategy { . fn run_bridge_and_client( . &self, -- line 133 ---------------------------------------- -- line 145 ---------------------------------------- . fn run_bridge_and_client( . &self, . dispatcher: &mut impl DispatcherTrait, . input: Buffer, . run_client: extern "C" fn(Bridge<'_>, D) -> Buffer, . client_data: D, . force_show_panics: bool, . ) -> Buffer { 4,735,497 ( 0.10%) let mut dispatch = |b| dispatcher.dispatch(b); . 390 ( 0.00%) run_client( 429 ( 0.00%) Bridge { cached_buffer: input, dispatch: (&mut dispatch).into(), force_show_panics }, . client_data, . ) . } . } . . // NOTE(eddyb) Two implementations are provided, the second one is a bit . // faster but neither is anywhere near as fast as same-thread execution. . -- line 164 ---------------------------------------- -- line 263 ---------------------------------------- . *state.lock().unwrap() = State::Res(b); . join_handle.thread().unpark(); . } . . join_handle.join().unwrap() . } . } . 546 ( 0.00%) fn run_server< . S: Server, . I: Encode>>, . O: for<'a, 's> DecodeMut<'a, 's, HandleStore>>, . D: Copy + Send + 'static, . >( . strategy: &impl ExecutionStrategy, . handle_counters: &'static client::HandleCounters, . server: S, . input: I, . run_client: extern "C" fn(Bridge<'_>, D) -> Buffer, . client_data: D, . force_show_panics: bool, . ) -> Result { . let mut dispatcher = 663 ( 0.00%) Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) }; . . let mut b = Buffer::new(); 156 ( 0.00%) input.encode(&mut b, &mut dispatcher.handle_store); . 234 ( 0.00%) b = strategy.run_bridge_and_client( . &mut dispatcher, . b, . run_client, . client_data, . force_show_panics, . ); . 195 ( 0.00%) Result::decode(&mut &b[..], &mut dispatcher.handle_store) 390 ( 0.00%) } . . impl client::Client crate::TokenStream> { . pub fn run( . &self, . strategy: &impl ExecutionStrategy, . server: S, . input: S::TokenStream, . force_show_panics: bool, -- line 308 ---------------------------------------- -- line 325 ---------------------------------------- . pub fn run( . &self, . strategy: &impl ExecutionStrategy, . server: S, . input: S::TokenStream, . input2: S::TokenStream, . force_show_panics: bool, . ) -> Result { 78 ( 0.00%) let client::Client { get_handle_counters, run, f } = *self; 507 ( 0.00%) run_server( . strategy, 39 ( 0.00%) get_handle_counters(), 390 ( 0.00%) server, . ( . as Types>::TokenStream::mark(input), . as Types>::TokenStream::mark(input2), . ), . run, . f, . force_show_panics, . ) -- line 345 ---------------------------------------- 1,192,569 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs -------------------------------------------------------------------------------- Ir -- line 10 ---------------------------------------- . type Env; . } . . impl<'a, A, R> !Sync for Closure<'a, A, R> {} . impl<'a, A, R> !Send for Closure<'a, A, R> {} . . impl<'a, A, R, F: FnMut(A) -> R> From<&'a mut F> for Closure<'a, A, R> { . fn from(f: &'a mut F) -> Self { 1,578,486 ( 0.03%) unsafe extern "C" fn call R>(env: &mut Env, arg: A) -> R { . (*(env as *mut _ as *mut F))(arg) 2,104,648 ( 0.05%) } . Closure { call: call::, env: unsafe { &mut *(f as *mut _ as *mut Env) } } . } . } . . impl<'a, A, R> Closure<'a, A, R> { . pub fn call(&mut self, arg: A) -> R { 8,418,592 ( 0.18%) unsafe { (self.call)(self.env, arg) } . } . } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 46,898,192 ( 1.02%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 206 ---------------------------------------- . #[inline(always)] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_promotable] . #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")] . #[rustc_diagnostic_item = "ptr_null"] . pub const fn null() -> *const T { . 0 as *const T 1,965 ( 0.00%) } . . /// Creates a null mutable raw pointer. . /// . /// # Examples . /// . /// ``` . /// use std::ptr; . /// -- line 222 ---------------------------------------- -- line 251 ---------------------------------------- . /// let x = [5, 6, 7]; . /// let raw_pointer = x.as_ptr(); . /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3); . /// assert_eq!(unsafe { &*slice }[2], 7); . /// ``` . #[inline] . #[stable(feature = "slice_from_raw_parts", since = "1.42.0")] . #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] 553,120 ( 0.01%) pub const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { 691,400 ( 0.02%) from_raw_parts(data.cast(), len) 276,560 ( 0.01%) } . . /// Performs the same functionality as [`slice_from_raw_parts`], except that a . /// raw mutable slice is returned, as opposed to a raw immutable slice. . /// . /// See the documentation of [`slice_from_raw_parts`] for more details. . /// . /// This function is safe, but actually using the return value is unsafe. . /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements. -- line 269 ---------------------------------------- -- line 283 ---------------------------------------- . /// (*slice)[2] = 99; // assign a value at an index in the slice . /// }; . /// . /// assert_eq!(unsafe { &*slice }[2], 99); . /// ``` . #[inline] . #[stable(feature = "slice_from_raw_parts", since = "1.42.0")] . #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] 1,846,376 ( 0.04%) pub const fn slice_from_raw_parts_mut(data: *mut T, len: usize) -> *mut [T] { 692,391 ( 0.02%) from_raw_parts_mut(data.cast(), len) 461,594 ( 0.01%) } . . /// Swaps the values at two mutable locations of the same type, without . /// deinitializing either. . /// . /// But for the following two exceptions, this function is semantically . /// equivalent to [`mem::swap`]: . /// . /// * It operates on raw pointers instead of references. When references are -- line 301 ---------------------------------------- -- line 366 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { 119 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 119 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 817 ( 0.00%) let z = read(x); . copy_nonoverlapping(y, x, 1); . write(y, z); . } . } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { -- line 464 ---------------------------------------- -- line 677 ---------------------------------------- . /// . /// assert_eq!(s, "bar"); . /// ``` . /// . /// [valid]: self#safety . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")] 1,460,145 ( 0.03%) pub const unsafe fn read(src: *const T) -> T { . // We are calling the intrinsics directly to avoid function calls in the generated code . // as `intrinsics::copy_nonoverlapping` is a wrapper function. . extern "rust-intrinsic" { . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . 660,882 ( 0.01%) let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 2,220,593 ( 0.05%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 19,167,207 ( 0.42%) tmp.assume_init() . } 915,045 ( 0.02%) } . . /// Reads the value from `src` without moving it. This leaves the . /// memory in `src` unchanged. . /// . /// Unlike [`read`], `read_unaligned` works with unaligned pointers. . /// . /// # Safety . /// -- line 712 ---------------------------------------- -- line 872 ---------------------------------------- . /// swap(&mut foo, &mut bar); . /// . /// assert_eq!(foo, "bar"); . /// assert_eq!(bar, "foo"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")] 1,440,811 ( 0.03%) pub const unsafe fn write(dst: *mut T, src: T) { . // We are calling the intrinsics directly to avoid function calls in the generated code . // as `intrinsics::copy_nonoverlapping` is a wrapper function. . extern "rust-intrinsic" { . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . . // SAFETY: the caller must guarantee that `dst` is valid for writes. . // `dst` cannot overlap `src` because the caller has mutable access . // to `dst` while `src` is owned by this function. . unsafe { 33,396,034 ( 0.72%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } 763,456 ( 0.02%) } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. . /// . /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it . /// could leak allocations or resources, so care should be taken not to overwrite -- line 903 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 13,514 ( 0.00%) return wrapping_sub( 29,816 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 2,339,864 ( 0.05%) a == b . } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// -- line 1364 ---------------------------------------- 8,863,718 ( 0.19%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . use rustc_target::spec::abi; . use std::borrow::Cow; . use std::cmp::Ordering; . use std::marker::PhantomData; . use std::ops::Range; . use ty::util::IntTypeExt; . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 5 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 2,955 ( 0.00%) pub ty: Ty<'tcx>, 14,775 ( 0.00%) pub mutbl: hir::Mutability, . } . . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . /// A "free" region `fr` can be interpreted as "some region . /// at least as big as the scope `fr.scope`". . pub struct FreeRegion { 34,379 ( 0.00%) pub scope: DefId, 62,816 ( 0.00%) pub bound_region: BoundRegionKind, . } . 453,422 ( 0.01%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] 49 ( 0.00%) #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 37,967 ( 0.00%) BrAnon(u32), . . /// Named region parameters for functions (a in &'a T) . /// . /// The `DefId` is needed to distinguish free regions in . /// the event of shadowing. 256 ( 0.00%) BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 1,242 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 90,460 ( 0.00%) pub var: BoundVar, 78,774 ( 0.00%) pub kind: BoundRegionKind, . } . . impl BoundRegionKind { . pub fn is_named(&self) -> bool { . match *self { . BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime, . _ => false, . } . } . } . . /// Defines the kinds of types. . /// . /// N.B., if you change this, you'll probably want to change the corresponding . /// AST structure in `rustc_ast/src/ast.rs` as well. 12,703,438 ( 0.28%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] 92,700 ( 0.00%) #[derive(HashStable)] . #[rustc_diagnostic_item = "TyKind"] . pub enum TyKind<'tcx> { . /// The primitive boolean type. Written as `bool`. . Bool, . . /// The primitive character type; holds a Unicode scalar value . /// (a non-surrogate code point). Written as `char`. . Char, -- line 90 ---------------------------------------- -- line 99 ---------------------------------------- . Float(ty::FloatTy), . . /// Algebraic data types (ADT). For example: structures, enumerations and unions. . /// . /// InternalSubsts here, possibly against intuition, *may* contain `Param`s. . /// That is, even after substitution it is possible that there are type . /// variables. This happens when the `Adt` corresponds to an ADT . /// definition and not a concrete use of it. 1,130,053 ( 0.02%) Adt(&'tcx AdtDef, SubstsRef<'tcx>), . . /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. . Foreign(DefId), . . /// The pointee of a string slice. Written as `str`. . Str, . . /// An array with the given length. Written as `[T; n]`. 168,465 ( 0.00%) Array(Ty<'tcx>, &'tcx ty::Const<'tcx>), . . /// The pointee of an array slice. Written as `[T]`. . Slice(Ty<'tcx>), . . /// A raw pointer. Written as `*mut T` or `*const T` . RawPtr(TypeAndMut<'tcx>), . . /// A reference; a pointer with an associated lifetime. Written as . /// `&'a mut T` or `&'a T`. 1,381,144 ( 0.03%) Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), . . /// The anonymous type of a function declaration/definition. Each . /// function has a unique type, which is output (for a function . /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. . /// . /// For example the type of `bar` here: . /// . /// ```rust -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . /// . /// ```rust . /// fn foo() -> i32 { 1 } . /// let bar: fn() -> i32 = foo; . /// ``` . FnPtr(PolyFnSig<'tcx>), . . /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. 66,577 ( 0.00%) Dynamic(&'tcx List>>, ty::Region<'tcx>), . . /// The anonymous type of a closure. Used to represent the type of . /// `|a| a`. . Closure(DefId, SubstsRef<'tcx>), . . /// The anonymous type of a generator. Used to represent the type of . /// `|a| yield a`. . Generator(DefId, SubstsRef<'tcx>, hir::Movability), -- line 159 ---------------------------------------- -- line 180 ---------------------------------------- . /// The substitutions are for the generics of the function in question. . /// After typeck, the concrete type can be found in the `types` map. . Opaque(DefId, SubstsRef<'tcx>), . . /// A type parameter; for example, `T` in `fn f(x: T) {}`. . Param(ParamTy), . . /// Bound type variable, used only when preparing a trait query. 2,997 ( 0.00%) Bound(ty::DebruijnIndex, BoundTy), . . /// A placeholder type - universally quantified higher-ranked type. . Placeholder(ty::PlaceholderType), . . /// A type variable used during type checking. . Infer(InferTy), . . /// A placeholder for a type which could not be computed; this is -- line 196 ---------------------------------------- -- line 330 ---------------------------------------- . pub closure_kind_ty: T, . pub closure_sig_as_fn_ptr_ty: T, . pub tupled_upvars_ty: T, . } . . impl<'tcx> ClosureSubsts<'tcx> { . /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` . /// for the closure parent, alongside additional closure-specific components. 94 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 188 ( 0.00%) parts.parent_substs.iter().copied().chain( 376 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 188 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 2,750 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 17,620 ( 0.00%) [ 4,970 ( 0.00%) ref parent_substs @ .., 5,536 ( 0.00%) closure_kind_ty, 2,053 ( 0.00%) closure_sig_as_fn_ptr_ty, 3,991 ( 0.00%) tupled_upvars_ty, 11,000 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 8,250 ( 0.00%) } . . /// Returns `true` only if enough of the synthetic types are known to . /// allow using all of the methods on `ClosureSubsts` without panicking. . /// . /// Used primarily by `ty::print::pretty` to be able to handle closure . /// types that haven't had their synthetic types substituted in. 20 ( 0.00%) pub fn is_valid(self) -> bool { 40 ( 0.00%) self.substs.len() >= 3 40 ( 0.00%) && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) 40 ( 0.00%) } . . /// Returns the substitutions of the closure's parent. . pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { . self.split().parent_substs . } . . /// Returns an iterator over the list of types of captured paths by the closure. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] 1,182 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 1,692 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 876 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() 788 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 12,216 ( 0.00%) self.split().tupled_upvars_ty.expect_ty() . } . . /// Returns the closure kind for this closure; may return a type . /// variable during inference. To get the closure kind during . /// inference, use `infcx.closure_kind(substs)`. 1,367 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 2,734 ( 0.00%) } . . /// Returns the `fn` pointer type representing the closure signature for this . /// closure. . // FIXME(eddyb) this should be unnecessary, as the shallowly resolved . // type is known at the time of the creation of `ClosureSubsts`, . // see `rustc_typeck::check::closure`. . pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { . self.split().closure_sig_as_fn_ptr_ty.expect_ty() . } . . /// Returns the closure kind for this closure; only usable outside . /// of an inference context, because in that context we know that . /// there are no type variables. . /// . /// If you have an inference context, use `infcx.closure_kind()`. 65 ( 0.00%) pub fn kind(self) -> ty::ClosureKind { 113 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 130 ( 0.00%) } . . /// Extracts the signature from the closure. 943 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 1,886 ( 0.00%) match ty.kind() { 3,772 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 2,829 ( 0.00%) } . } . . /// Similar to `ClosureSubsts`; see the above documentation for more. . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GeneratorSubsts<'tcx> { . pub substs: SubstsRef<'tcx>, . } . -- line 448 ---------------------------------------- -- line 676 ---------------------------------------- . } . . impl<'tcx> UpvarSubsts<'tcx> { . /// Returns an iterator over the list of types of captured paths by the closure/generator. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] . pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 318 ( 0.00%) let tupled_tys = match self { 412 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 665 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 571 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() . } . . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 506 ( 0.00%) match self { 746 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . } . } . } . . /// An inline const is modeled like . /// . /// const InlineConst<'l0...'li, T0...Tj, R>: R; -- line 710 ---------------------------------------- -- line 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 50,348 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] 53,598 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub enum ExistentialPredicate<'tcx> { . /// E.g., `Iterator`. . Trait(ExistentialTraitRef<'tcx>), . /// E.g., `Iterator::Item = T`. . Projection(ExistentialProjection<'tcx>), . /// E.g., `Send`. 22 ( 0.00%) AutoTrait(DefId), . } . . impl<'tcx> ExistentialPredicate<'tcx> { . /// Compares via an ordering that will not change if modules are reordered or other changes are . /// made to the tree. In particular, this ordering is preserved across incremental compilations. 105 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 108 ( 0.00%) match (*self, *other) { . (Trait(_), Trait(_)) => Ordering::Equal, . (Projection(ref a), Projection(ref b)) => { . tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) . } . (AutoTrait(ref a), AutoTrait(ref b)) => { . tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b)) . } . (Trait(_), _) => Ordering::Less, . (Projection(_), Trait(_)) => Ordering::Greater, . (Projection(_), _) => Ordering::Less, . (AutoTrait(_), _) => Ordering::Greater, . } 126 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { 3,897 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; 2,165 ( 0.00%) match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) . } . ExistentialPredicate::Projection(p) => { . self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) . } . ExistentialPredicate::AutoTrait(did) => { . let trait_ref = self.rebind(ty::TraitRef { . def_id: did, . substs: tcx.mk_substs_trait(self_ty, &[]), . }); . trait_ref.without_const().to_predicate(tcx) . } . } 3,464 ( 0.00%) } . } . . impl<'tcx> List>> { . /// Returns the "principal `DefId`" of this set of existential predicates. . /// . /// A Rust trait object type consists (in addition to a lifetime bound) . /// of a set of trait bounds, which are separated into any number . /// of auto-trait bounds, and at most one non-auto-trait bound. The -- line 826 ---------------------------------------- -- line 839 ---------------------------------------- . /// are the set `{Sync}`. . /// . /// It is also possible to have a "trivial" trait object that . /// consists only of auto traits, with no principal - for example, . /// `dyn Send + Sync`. In that case, the set of auto-trait bounds . /// is `{Send, Sync}`, while there is no principal. These trait objects . /// have a "trivial" vtable consisting of just the size, alignment, . /// and destructor. 418 ( 0.00%) pub fn principal(&self) -> Option>> { 3,013 ( 0.00%) self[0] 1,759 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, 1,672 ( 0.00%) }) . .transpose() 1,254 ( 0.00%) } . 417 ( 0.00%) pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) 834 ( 0.00%) } . . #[inline] . pub fn projection_bounds<'a>( . &'a self, . ) -> impl Iterator>> + 'a { . self.iter().filter_map(|predicate| { 18 ( 0.00%) predicate 82 ( 0.00%) .map_bound(|pred| match pred { 10 ( 0.00%) ExistentialPredicate::Projection(projection) => Some(projection), . _ => None, . }) . .transpose() . }) . } . . #[inline] . pub fn auto_traits<'a>(&'a self) -> impl Iterator + 'a { -- line 875 ---------------------------------------- -- line 886 ---------------------------------------- . /// T: Foo . /// . /// This would be represented by a trait-reference where the `DefId` is the . /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, . /// and `U` as parameter 1. . /// . /// Trait references also appear in object types like `Foo`, but in . /// that case the `Self` parameter is absent from the substitutions. 24,028 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 1,887,760 ( 0.04%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 2,612 ( 0.00%) pub def_id: DefId, 1,033,592 ( 0.02%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 1,935 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 7,740 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 945 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 420 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 630 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 840 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 3,936 ( 0.00%) pub fn from_method( . tcx: TyCtxt<'tcx>, . trait_id: DefId, . substs: SubstsRef<'tcx>, . ) -> ty::TraitRef<'tcx> { . let defs = tcx.generics_of(trait_id); . 492 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 5,412 ( 0.00%) } . } . . pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>; . . impl<'tcx> PolyTraitRef<'tcx> { . pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> { . self.map_bound_ref(|tr| tr.self_ty()) . } . . pub fn def_id(&self) -> DefId { 13,017 ( 0.00%) self.skip_binder().def_id 4,339 ( 0.00%) } . 6,171 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 12,342 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 6,171 ( 0.00%) } . } . . /// An existential reference to a trait, where `Self` is erased. . /// For example, the trait object `Trait<'a, 'b, X, Y>` is: . /// . /// exists T. T: Trait<'a, 'b, X, Y> . /// . /// The substitutions don't include the erased `Self`, only trait . /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). 132 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 25,292 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 3,786 ( 0.00%) pub def_id: DefId, 30,972 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { 188 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. . trait_ref.substs.type_at(0); . . ty::ExistentialTraitRef { . def_id: trait_ref.def_id, . substs: tcx.intern_substs(&trait_ref.substs[1..]), . } 188 ( 0.00%) } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. 120 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> { . // otherwise the escaping vars would be captured by the binder . // debug_assert!(!self_ty.has_escaping_bound_vars()); . 60 ( 0.00%) ty::TraitRef { def_id: self.def_id, substs: tcx.mk_substs_trait(self_ty, self.substs) } 300 ( 0.00%) } . } . . pub type PolyExistentialTraitRef<'tcx> = Binder<'tcx, ExistentialTraitRef<'tcx>>; . . impl<'tcx> PolyExistentialTraitRef<'tcx> { . pub fn def_id(&self) -> DefId { . self.skip_binder().def_id . } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. 735 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> { 787 ( 0.00%) self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) 980 ( 0.00%) } . } . 78,485 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 110 ( 0.00%) #[derive(HashStable)] . pub enum BoundVariableKind { . Ty(BoundTyKind), . Region(BoundRegionKind), . Const, . } . . /// Binder is a binder for higher-ranked lifetimes or types. It is part of the . /// compiler's representation for things like `for<'a> Fn(&'a isize)` . /// (which would be represented by the type `PolyTraitRef == . /// Binder<'tcx, TraitRef>`). Note that when we instantiate, . /// erase, or otherwise "discharge" these bound vars, we change the . /// type from `Binder<'tcx, T>` to just `T` (see . /// e.g., `liberate_late_bound_regions`). . /// . /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. 65,584 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 367,561 ( 0.01%) pub struct Binder<'tcx, T>(T, &'tcx List); . . impl<'tcx, T> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . /// Wraps `value` in a binder, asserting that `value` does not . /// contain any bound vars that would be bound by the . /// binder. This is commonly used to 'inject' a value T into a . /// different binding level. 31,245 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 107,051 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 272,694 ( 0.01%) Binder(value, ty::List::empty()) 31,175 ( 0.00%) } . . pub fn bind_with_vars(value: T, vars: &'tcx List) -> Binder<'tcx, T> { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(vars); . value.visit_with(&mut validator); . } 27,127 ( 0.00%) Binder(value, vars) . } . } . . impl<'tcx, T> Binder<'tcx, T> { . /// Skips the binder and returns the "bound" value. This is a . /// risky thing to do because it's easy to get confused about . /// De Bruijn indices and the like. It is usually better to . /// discharge the binder using `no_bound_vars` or -- line 1053 ---------------------------------------- -- line 1059 ---------------------------------------- . /// accounting. . /// . /// Some examples where `skip_binder` is reasonable: . /// . /// - extracting the `DefId` from a PolyTraitRef; . /// - comparing the self type of a PolyTraitRef to see if it is equal to . /// a type parameter `X`, since the type `X` does not reference any regions . pub fn skip_binder(self) -> T { 1,165,621 ( 0.03%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 2,110 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 14,956 ( 0.00%) Binder(&self.0, self.1) . } . . pub fn map_bound_ref_unchecked(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . let value = f(&self.0); . Binder(value, self.1) -- line 1083 ---------------------------------------- -- line 1085 ---------------------------------------- . . pub fn map_bound_ref>(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . self.as_ref().map_bound(f) . } . 940 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 35,703 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 268,744 ( 0.01%) Binder(value, self.1) 941 ( 0.00%) } . . pub fn try_map_bound, E>(self, f: F) -> Result, E> . where . F: FnOnce(T) -> Result, . { . let value = f(self.0)?; . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 18,651 ( 0.00%) Ok(Binder(value, self.1)) . } . . /// Wraps a `value` in a binder, using the same bound variables as the . /// current `Binder`. This should not be used if the new value *changes* . /// the bound variables. Note: the (old or new) value itself does not . /// necessarily need to *name* all the bound variables. . /// . /// This currently doesn't do anything different than `bind`, because we -- line 1122 ---------------------------------------- -- line 1126 ---------------------------------------- . pub fn rebind(&self, value: U) -> Binder<'tcx, U> . where . U: TypeFoldable<'tcx>, . { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.bound_vars()); . value.visit_with(&mut validator); . } 21,255 ( 0.00%) Binder(value, self.1) . } . . /// Unwraps and returns the value within, but only if it contains . /// no bound vars at all. (In other words, if this binder -- . /// and indeed any enclosing binder -- doesn't bind anything at . /// all.) Otherwise, returns `None`. . /// . /// (One could imagine having a method that just unwraps a single -- line 1142 ---------------------------------------- -- line 1143 ---------------------------------------- . /// binder, but permits late-bound vars bound by enclosing . /// binders, but that would require adjusting the debruijn . /// indices, and given the shallow binding structure we often use, . /// would not be that useful.) . pub fn no_bound_vars(self) -> Option . where . T: TypeFoldable<'tcx>, . { 189,567 ( 0.00%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 465 ( 0.00%) } . . /// Splits the contents into two things that share the same binder . /// level as the original, returning two distinct binders. . /// . /// `f` should consider bound regions at depth 1 to be free, and . /// anything it produces with bound regions at depth 1 will be . /// bound in the resulting return values. . pub fn split(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>) -- line 1160 ---------------------------------------- -- line 1170 ---------------------------------------- . pub fn transpose(self) -> Option> { . let bound_vars = self.1; . self.0.map(|v| Binder(v, bound_vars)) . } . } . . /// Represents the projection of an associated type. In explicit UFCS . /// form this would be written `>::N`. 2,169 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 156,568 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 128,243 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The `DefId` of the `TraitItem` for the associated type `N`. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(item_def_id).container`. 151,620 ( 0.00%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 42,070 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 12,020 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 48,080 ( 0.00%) } . . /// Extracts the underlying trait reference and own substs from this projection. . /// For example, if this is a projection of `::Item<'a>`, . /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs 77,189 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 33,081 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 55,135 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 99,243 ( 0.00%) } . . /// Extracts the underlying trait reference from this projection. . /// For example, if this is a projection of `::Item`, . /// then this function would return a `T: Iterator` trait reference. . /// . /// WARNING: This will drop the substs for generic associated types . /// consider calling [Self::trait_ref_and_own_substs] to get those . /// as well. 53,604 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 5,956 ( 0.00%) let def_id = self.trait_def_id(tcx); 5,956 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 65,516 ( 0.00%) } . 11,670 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 35,010 ( 0.00%) self.substs.type_at(0) 23,340 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GenSig<'tcx> { . pub resume_ty: Ty<'tcx>, . pub yield_ty: Ty<'tcx>, . pub return_ty: Ty<'tcx>, . } -- line 1233 ---------------------------------------- -- line 1235 ---------------------------------------- . pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>; . . /// Signature of a function type, which we have arbitrarily . /// decided to use to refer to the input/output types. . /// . /// - `inputs`: is the list of arguments and their modes. . /// - `output`: is the return type. . /// - `c_variadic`: indicates whether this is a C-variadic function. 43,120 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 41,815 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 8,559 ( 0.00%) pub inputs_and_output: &'tcx List>, 61,695 ( 0.00%) pub c_variadic: bool, 14,591 ( 0.00%) pub unsafety: hir::Unsafety, 45,671 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 19,608 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 91,938 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 39,216 ( 0.00%) } . 11,880 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 93,949 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 23,760 ( 0.00%) } . . // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible . // method. . fn fake() -> FnSig<'tcx> { . FnSig { . inputs_and_output: List::empty(), . c_variadic: false, . unsafety: hir::Unsafety::Normal, -- line 1267 ---------------------------------------- -- line 1270 ---------------------------------------- . } . } . . pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; . . impl<'tcx> PolyFnSig<'tcx> { . #[inline] . pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> { 3,846 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 7,584 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.inputs()[index]) . } . pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List>> { . self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output) 396 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 4,505 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 712 ( 0.00%) self.skip_binder().c_variadic 356 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 2,812 ( 0.00%) self.skip_binder().unsafety 1,406 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 23,868 ( 0.00%) self.skip_binder().abi 5,967 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 196 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 678 ( 0.00%) #[derive(HashStable)] . pub struct ParamTy { 1,370 ( 0.00%) pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 716 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 358 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { 364 ( 0.00%) ParamTy::new(def.index, def.name) 182 ( 0.00%) } . . #[inline] . pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { . tcx.mk_ty_param(self.index, self.name) . } . } . . #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] 9 ( 0.00%) #[derive(HashStable)] . pub struct ParamConst { 120 ( 0.00%) pub index: u32, 120 ( 0.00%) pub name: Symbol, . } . . impl ParamConst { . pub fn new(index: u32, name: Symbol) -> ParamConst { . ParamConst { index, name } . } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamConst { -- line 1338 ---------------------------------------- -- line 1440 ---------------------------------------- . /// the inference variable is supposed to satisfy the relation . /// *for every value of the placeholder region*. To ensure that doesn't . /// happen, you can use `leak_check`. This is more clearly explained . /// by the [rustc dev guide]. . /// . /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ . /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 4,166,393 ( 0.09%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 1,548 ( 0.00%) pub enum RegionKind { . /// Region bound in a type or fn declaration which will be . /// substituted 'early' -- that is, at the same time when type . /// parameters are substituted. . ReEarlyBound(EarlyBoundRegion), . . /// Region bound in a function scope, which will be substituted when the . /// function is called. 156,894 ( 0.00%) ReLateBound(ty::DebruijnIndex, BoundRegion), . . /// When checking a function body, the types of all arguments and so forth . /// that refer to bound region parameters are modified to refer to free . /// region parameters. . ReFree(FreeRegion), . . /// Static data that has an "infinite" lifetime. Top in the region lattice. . ReStatic, -- line 1465 ---------------------------------------- -- line 1478 ---------------------------------------- . /// regions visible from `U`, but not less than regions not visible . /// from `U`. . ReEmpty(ty::UniverseIndex), . . /// Erased region, used by trait selection, in MIR and during codegen. . ReErased, . } . 16,374 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { 31,257 ( 0.00%) pub def_id: DefId, 38,138 ( 0.00%) pub index: u32, 41,100 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 2,619 ( 0.00%) pub index: u32, 1,786 ( 0.00%) pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } . } -- line 1505 ---------------------------------------- -- line 1513 ---------------------------------------- . rustc_index::newtype_index! { . pub struct BoundVar { .. } . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct BoundTy { . pub var: BoundVar, 2,997 ( 0.00%) pub kind: BoundTyKind, . } . 51,060 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundTyKind { . Anon, . Param(Symbol), . } . . impl From for BoundTy { . fn from(var: BoundVar) -> Self { . BoundTy { var, kind: BoundTyKind::Anon } . } . } . . /// A `ProjectionPredicate` for an `ExistentialTraitRef`. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 29 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialProjection<'tcx> { 6 ( 0.00%) pub item_def_id: DefId, 36 ( 0.00%) pub substs: SubstsRef<'tcx>, 9 ( 0.00%) pub term: Term<'tcx>, . } . . pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>; . . impl<'tcx> ExistentialProjection<'tcx> { . /// Extracts the underlying existential trait reference from this projection. . /// For example, if this is a projection of `exists T. ::Item == X`, . /// then this function would return an `exists T. T: Iterator` existential trait -- line 1551 ---------------------------------------- -- line 1585 ---------------------------------------- . item_def_id: projection_predicate.projection_ty.item_def_id, . substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]), . term: projection_predicate.term, . } . } . } . . impl<'tcx> PolyExistentialProjection<'tcx> { 15 ( 0.00%) pub fn with_self_ty( . &self, . tcx: TyCtxt<'tcx>, . self_ty: Ty<'tcx>, . ) -> ty::PolyProjectionPredicate<'tcx> { 15 ( 0.00%) self.map_bound(|p| p.with_self_ty(tcx, self_ty)) 18 ( 0.00%) } . . pub fn item_def_id(&self) -> DefId { 6 ( 0.00%) self.skip_binder().item_def_id 3 ( 0.00%) } . } . . /// Region utilities . impl RegionKind { . /// Is this region named by the user? . pub fn has_name(&self) -> bool { . match *self { . RegionKind::ReEarlyBound(ebr) => ebr.has_name(), -- line 1611 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 2,947 ( 0.00%) matches!(*self, ty::ReLateBound(..)) . } . . #[inline] . pub fn is_placeholder(&self) -> bool { . matches!(*self, ty::RePlaceholder(..)) . } . . #[inline] . pub fn bound_at_or_above_binder(&self, index: ty::DebruijnIndex) -> bool { 74,244 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 129,400 ( 0.00%) match *self { . ty::ReVar(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; . flags = flags | TypeFlags::HAS_RE_INFER; . } . ty::RePlaceholder(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; -- line 1651 ---------------------------------------- -- line 1669 ---------------------------------------- . ty::ReErased => { . flags = flags | TypeFlags::HAS_RE_ERASED; . } . } . . debug!("type_flags({:?}) = {:?}", self, flags); . . flags 6,845 ( 0.00%) } . . /// Given an early-bound or free region, returns the `DefId` where it was bound. . /// For example, consider the regions in this snippet of code: . /// . /// ``` . /// impl<'a> Foo { . /// ^^ -- early bound, declared on an impl . /// -- line 1685 ---------------------------------------- -- line 1713 ---------------------------------------- . . #[inline(always)] . pub fn flags(&self) -> TypeFlags { . self.flags . } . . #[inline] . pub fn is_unit(&self) -> bool { 2,818 ( 0.00%) match self.kind() { 890 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 25,433 ( 0.00%) matches!(self.kind(), Never) . } . . #[inline] . pub fn is_primitive(&self) -> bool { . self.kind().is_primitive() . } . . #[inline] -- line 1737 ---------------------------------------- -- line 1741 ---------------------------------------- . . #[inline] . pub fn is_ref(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_ty_var(&self) -> bool { 43,597 ( 0.00%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 39,328 ( 0.00%) match self.kind() { 5,790 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 282 ( 0.00%) matches!(self.kind(), Infer(_)) . } . . #[inline] . pub fn is_phantom_data(&self) -> bool { . if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false } . } . . #[inline] -- line 1770 ---------------------------------------- -- line 1775 ---------------------------------------- . /// Returns `true` if this type is a `str`. . #[inline] . pub fn is_str(&self) -> bool { . *self.kind() == Str . } . . #[inline] . pub fn is_param(&self, index: u32) -> bool { 545 ( 0.00%) match self.kind() { . ty::Param(ref data) => data.index == index, . _ => false, . } . } . . #[inline] . pub fn is_slice(&self) -> bool { . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 131 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { 5 ( 0.00%) match self.kind() { 2 ( 0.00%) Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 170 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 340 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => ty, . Str => tcx.mk_mach_uint(ty::UintTy::U8), . _ => bug!("`sequence_element_type` called on non-sequence value: {}", self), . } 170 ( 0.00%) } . 14 ( 0.00%) pub fn simd_size_and_type(&self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) { 4 ( 0.00%) match self.kind() { . Adt(def, substs) => { 4 ( 0.00%) assert!(def.repr.simd(), "`simd_size_and_type` called on non-SIMD type"); . let variant = def.non_enum_variant(); 8 ( 0.00%) let f0_ty = variant.fields[0].ty(tcx, substs); . 4 ( 0.00%) match f0_ty.kind() { . // If the first field is an array, we assume it is the only field and its . // elements are the SIMD components. . Array(f0_elem_ty, f0_len) => { . // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112 . // The way we evaluate the `N` in `[T; N]` here only works since we use . // `simd_size_and_type` post-monomorphization. It will probably start to ICE . // if we use it in generic code. See the `simd-array-trait` ui test. . (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, f0_elem_ty) . } . // Otherwise, the fields of this Adt are the SIMD components (and we assume they . // all have the same type). 4 ( 0.00%) _ => (variant.fields.len() as u64, f0_ty), . } . } . _ => bug!("`simd_size_and_type` called on invalid type"), . } 18 ( 0.00%) } . . #[inline] . pub fn is_region_ptr(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_mutable_ptr(&self) -> bool { 120 ( 0.00%) matches!( 80 ( 0.00%) self.kind(), . RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) . | Ref(_, _, hir::Mutability::Mut) . ) . } . . /// Get the mutability of the reference or `None` when not a reference . #[inline] . pub fn ref_mutability(&self) -> Option { -- line 1860 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 6,594 ( 0.00%) matches!(self.kind(), RawPtr(_)) . } . . /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer). . #[inline] . pub fn is_any_ptr(&self) -> bool { 4 ( 0.00%) self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr() . } . . #[inline] . pub fn is_box(&self) -> bool { 43,042 ( 0.00%) match self.kind() { 6,241 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. 966 ( 0.00%) pub fn boxed_ty(&self) -> Ty<'tcx> { 966 ( 0.00%) match self.kind() { 2,415 ( 0.00%) Adt(def, substs) if def.is_box() => substs.type_at(0), . _ => bug!("`boxed_ty` is called on non-box type {:?}", self), . } 966 ( 0.00%) } . . /// A scalar type is one that denotes an atomic datum, with no sub-components. . /// (A RawPtr is scalar because it represents a non-managed pointer, so its . /// contents are abstract to rustc.) . #[inline] . pub fn is_scalar(&self) -> bool { 330 ( 0.00%) matches!( 733 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) . ) . } . . /// Returns `true` if this type is a floating point type. . #[inline] . pub fn is_floating_point(&self) -> bool { 1,083 ( 0.00%) matches!(self.kind(), Float(_) | Infer(FloatVar(_))) . } . . #[inline] . pub fn is_trait(&self) -> bool { 190 ( 0.00%) matches!(self.kind(), Dynamic(..)) . } . . #[inline] . pub fn is_enum(&self) -> bool { 1,204 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum()) . } . . #[inline] . pub fn is_union(&self) -> bool { 9,689 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { 2,404 ( 0.00%) matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 3,126 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 3,209 ( 0.00%) matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_)) . } . . #[inline] . pub fn is_fresh_ty(&self) -> bool { . matches!(self.kind(), Infer(FreshTy(_))) . } . . #[inline] . pub fn is_fresh(&self) -> bool { 4,045 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] . pub fn is_numeric(&self) -> bool { . self.is_integral() || self.is_floating_point() . } . . #[inline] . pub fn is_signed(&self) -> bool { 250 ( 0.00%) matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { 549 ( 0.00%) matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] . pub fn has_concrete_skeleton(&self) -> bool { . !matches!(self.kind(), Param(_) | Infer(_) | Error(_)) . } . . /// Returns the type and mutability of `*ty`. . /// . /// The parameter `explicit` indicates if this is an *explicit* dereference. . /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. 9,288 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 71,583 ( 0.00%) match self.kind() { 1,300 ( 0.00%) Adt(def, _) if def.is_box() => { 1,200 ( 0.00%) Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 43,438 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), 404 ( 0.00%) RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 18,576 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { 378 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } 81 ( 0.00%) } . 73,688 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 36,844 ( 0.00%) match self.kind() { 27,564 ( 0.00%) FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), 115 ( 0.00%) FnPtr(f) => *f, . Error(_) => { . // ignore errors (#54954) . ty::Binder::dummy(FnSig::fake()) . } . Closure(..) => bug!( . "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", . ), . _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), . } 82,899 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 4,323 ( 0.00%) matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { . matches!(self.kind(), FnPtr(_)) . } . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 2,935 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 652 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 2,560 ( 0.00%) match self.kind() { 3,101 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 1,304 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 612 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 1,224 ( 0.00%) match self.kind() { 1,224 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 1,224 ( 0.00%) } . . /// If the type contains variants, returns the valid range of variant indices. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] . pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option> { . match self.kind() { . TyKind::Adt(adt, _) => Some(adt.variant_range()), -- line 2068 ---------------------------------------- -- line 2073 ---------------------------------------- . } . } . . /// If the type contains variants, returns the variant for `variant_index`. . /// Panics if `variant_index` is out of range. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] 2,390 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 2,957 ( 0.00%) match self.kind() { 1,026 ( 0.00%) TyKind::Adt(adt, _) if adt.variants.is_empty() => { . // This can actually happen during CTFE, see . // https://github.com/rust-lang/rust/issues/89765. . None . } 513 ( 0.00%) TyKind::Adt(adt, _) if adt.is_enum() => { . Some(adt.discriminant_for_variant(tcx, variant_index)) . } . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } 1,912 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 7,270 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 3,635 ( 0.00%) match self.kind() { 5,816 ( 0.00%) ty::Adt(adt, _) if adt.is_enum() => adt.repr.discr_type().to_ty(tcx), . ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), . . ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => { . let assoc_items = tcx.associated_item_def_ids( . tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), . ); . tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()])) . } -- line 2113 ---------------------------------------- -- line 2135 ---------------------------------------- . | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, . . ty::Bound(..) . | ty::Placeholder(_) . | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`discriminant_ty` applied to unexpected type: {:?}", self) . } . } 5,816 ( 0.00%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. 72 ( 0.00%) pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { 72 ( 0.00%) let tail = tcx.struct_tail_with_normalize(self, normalize); 40 ( 0.00%) match tail.kind() { . // Sized types . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) -- line 2160 ---------------------------------------- -- line 2170 ---------------------------------------- . | ty::Foreign(..) . // If returned by `struct_tail_without_normalization` this is a unit struct . // without any fields, or not a struct, and therefore is Sized. . | ty::Adt(..) . // If returned by `struct_tail_without_normalization` this is the empty tuple, . // a.k.a. unit type, which is Sized . | ty::Tuple(..) => tcx.types.unit, . 16 ( 0.00%) ty::Str | ty::Slice(_) => tcx.types.usize, . ty::Dynamic(..) => { . let dyn_metadata = tcx.lang_items().dyn_metadata().unwrap(); . tcx.type_of(dyn_metadata).subst(tcx, &[tail.into()]) . }, . . ty::Projection(_) . | ty::Param(_) . | ty::Opaque(..) . | ty::Infer(ty::TyVar(_)) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`ptr_metadata_ty` applied to unexpected type: {:?}", tail) . } . } 64 ( 0.00%) } . . /// When we create a closure, we record its kind (i.e., what trait . /// it implements) into its `ClosureSubsts` using a type . /// parameter. This is kind of a phantom type, except that the . /// most convenient thing for us to are the integral types. This . /// function converts such a special type into the closure . /// kind. To go the other way, use . /// `tcx.closure_kind_ty(closure_kind)`. . /// . /// Note that during type checking, we use an inference variable . /// to represent the closure kind, because it has not yet been . /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`) . /// is complete, that type variable will be unified. 3,272 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 6,544 ( 0.00%) match self.kind() { 6,216 ( 0.00%) Int(int_ty) => match int_ty { . ty::IntTy::I8 => Some(ty::ClosureKind::Fn), . ty::IntTy::I16 => Some(ty::ClosureKind::FnMut), . ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce), . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . }, . . // "Bound" types appear in canonical queries when the . // closure type is not yet known . Bound(..) | Infer(_) => None, . . Error(_) => Some(ty::ClosureKind::Fn), . . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . } 3,272 ( 0.00%) } . . /// Fast path helper for testing if a type is `Sized`. . /// . /// Returning true means the type is known to be sized. Returning . /// `false` means nothing -- could be sized, might not be. . /// . /// Note that we could never rely on the fact that a type such as `[_]` is . /// trivially `!Sized` because we could be in a type environment with a . /// bound such as `[_]: Copy`. A function with such a bound obviously never . /// can be called, but that doesn't mean it shouldn't typecheck. This is why . /// this method doesn't return `Option`. 146,421 ( 0.00%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 97,614 ( 0.00%) match self.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 2246 ---------------------------------------- -- line 2250 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => true, . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false, . 2,495 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 9,399 ( 0.00%) ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(), . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false, . . ty::Infer(ty::TyVar(_)) => false, . . ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`is_trivially_sized` applied to unexpected type: {:?}", self) . } . } 146,421 ( 0.00%) } . } . . /// Extra information about why we ended up with a particular variance. . /// This is only used to add more information to error messages, and . /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo` . /// may lead to confusing notes in error messages, it will never cause . /// a miscompilation or unsoundness. . /// . /// When in doubt, use `VarianceDiagInfo::default()` 18 ( 0.00%) #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] . pub enum VarianceDiagInfo<'tcx> { . /// No additional information - this is the default. . /// We will not add any additional information to error messages. . #[default] . None, . /// We switched our variance because a generic argument occurs inside . /// the invariant generic argument of another type. . Invariant { -- line 2290 ---------------------------------------- -- line 2295 ---------------------------------------- . /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`) . param_index: u32, . }, . } . . impl<'tcx> VarianceDiagInfo<'tcx> { . /// Mirrors `Variance::xform` - used to 'combine' the existing . /// and new `VarianceDiagInfo`s when our variance changes. 44,034 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 66,051 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 22,017 ( 0.00%) } . } 16,814,619 ( 0.36%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 3,199,504 ( 0.07%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 1,999,690 ( 0.04%) .intern(kind, |kind| { 73,692 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 147,384 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 3,599,442 ( 0.08%) } . . #[inline(never)] 883,776 ( 0.02%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 773,304 ( 0.02%) .intern(kind, |kind| { 138,456 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 994,248 ( 0.02%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 222,328 ( 0.00%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 167,663 ( 0.00%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 33,599 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 33,599 ( 0.00%) self.data.get(&id.local_id) 134,460 ( 0.00%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 2,376 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 1,584 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 8,364 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 98,974 ( 0.00%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 8,364 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 45,366 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 30,244 ( 0.00%) match *qpath { 78,498 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 12,234 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 75,610 ( 0.00%) } . 188 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 1,815 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 188 ( 0.00%) } . 3,410 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 7,151 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 6,820 ( 0.00%) } . 6,808 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 6,808 ( 0.00%) } . 13,581 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 13,581 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 13,581 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 3,527 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 865 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 4,608 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 2,304 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 5,794 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 2,897 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 968 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 484 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 31,788 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 15,894 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 52,870 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 26,435 ( 0.00%) } . 220,476 ( 0.00%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 36,746 ( 0.00%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 183,730 ( 0.00%) } . 50,601 ( 0.00%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 50,601 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 101,202 ( 0.00%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 6,708 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 3,354 ( 0.00%) } . 16,369 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 16,369 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 32,738 ( 0.00%) } . 11,053 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 11,053 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 22,106 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 4,780 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 41,330 ( 0.00%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 50,259 ( 0.00%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 20,198 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 10,099 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 33,730 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 16,865 ( 0.00%) } . 21,061 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 42,122 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 42,122 ( 0.00%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 3,570 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 714 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 1,616 ( 0.00%) } . 1,620 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 324 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 972 ( 0.00%) } . 1,627 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 3,254 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 4,782 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 3,254 ( 0.00%) } . 12,258 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 16,344 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 10,614 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 3,264 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 5,256 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 2,628 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 13,036 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 6,518 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 3,830 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 1,915 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 4,008 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 5,010 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 804 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 402 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { 156 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } 78 ( 0.00%) } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 2,388 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 1,194 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 1,584 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 792 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 804 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 402 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 39 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 13 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 26 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 402 ( 0.00%) &self.coercion_casts 402 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 162 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 296 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 1,140 ( 0.00%) pub fn is_identity(&self) -> bool { 2,280 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 1,140 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 3,042 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 1,509 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 24 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 2,280 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 1,776 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 12,722 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 20,440 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 8,176 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 16,352 ( 0.00%) } . 1,488 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 496 ( 0.00%) self.arena.alloc(Steal::new(thir)) 1,984 ( 0.00%) } . 9,920 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 1,984 ( 0.00%) self.arena.alloc(Steal::new(mir)) 13,888 ( 0.00%) } . 1,984 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 496 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 2,480 ( 0.00%) } . 1,134 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 2,016 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 504 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. . pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. . let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); . let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) . } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 8,904 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 4,452 ( 0.00%) let attrs = self.get_attrs(def_id); 18,921 ( 0.00%) let get = |name| { 4,452 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); 280 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 140 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 70 ( 0.00%) ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 22,260 ( 0.00%) }; 6,678 ( 0.00%) ( 6,678 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 3,339 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 8,904 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 15,435 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 2,205 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 16,806 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 17,640 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 770,154 ( 0.02%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 990,198 ( 0.02%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 84 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 96 ( 0.00%) } . . /// Obtain the diagnostic item's name 15,092 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 17,248 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 25,032 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 28,608 ( 0.00%) } . 7,322 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 9,414 ( 0.00%) } . 251,538 ( 0.01%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 287,472 ( 0.01%) } . 13,798 ( 0.00%) pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 89,186 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 135,348 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } 1,484 ( 0.00%) } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. 148 ( 0.00%) pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath { . // Accessing the DefPath is ok, since it is part of DefPathHash. 222 ( 0.00%) if let Some(id) = id.as_local() { 18 ( 0.00%) self.untracked_resolutions.definitions.def_path(id) . } else { 340 ( 0.00%) self.untracked_resolutions.cstore.def_path(id) . } 222 ( 0.00%) } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 4,841 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 3,222 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 64,596 ( 0.00%) &*self.untracked_resolutions.cstore 32,298 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 2,237 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 9,048 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 804 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 1,206 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 402 ( 0.00%) self.sess.opts.borrowck_mode 1,608 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { 499 ( 0.00%) let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. 297 ( 0.00%) features.generic_const_exprs . } . . #[inline] . pub fn local_crate_exports_generics(self) -> bool { . debug_assert!(self.sess.opts.share_generics()); . 809 ( 0.00%) self.sess.crate_types().iter().any(|crate_type| { 1,353 ( 0.00%) match crate_type { . CrateType::Executable . | CrateType::Staticlib . | CrateType::ProcMacro . | CrateType::Cdylib => false, . . // FIXME rust-lang/rust#64319, rust-lang/rust#64872: . // We want to block export of generics from dylibs, . // but we must fix rust-lang/rust#65890 before we can -- line 1450 ---------------------------------------- -- line 1540 ---------------------------------------- . // FIXME(#42706) -- in some cases, we could do better here. . return true; . } . false . } . . /// Determines whether identifiers in the assembly have strict naming rules. . /// Currently, only NVPTX* targets need it. 2,377 ( 0.00%) pub fn has_strict_asm_symbol_naming(self) -> bool { 2,377 ( 0.00%) self.sess.target.arch.contains("nvptx") 4,754 ( 0.00%) } . . /// Returns `&'static core::panic::Location<'static>`. 1,284 ( 0.00%) pub fn caller_location_ty(self) -> Ty<'tcx> { . self.mk_imm_ref( 214 ( 0.00%) self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) 428 ( 0.00%) .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) 1,284 ( 0.00%) } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 1,771 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 1,288 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 2,898 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 1,449 ( 0.00%) } . 11,200 ( 0.00%) pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit 12,800 ( 0.00%) } . 346,059 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 395,496 ( 0.01%) } . 49,147 ( 0.00%) pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit 56,168 ( 0.00%) } . 2,086 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 2,384 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1614 ---------------------------------------- . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option; . } . . macro_rules! nop_lift { . ($set:ident; $ty:ty => $lifted:ty) => { . impl<'a, 'tcx> Lift<'tcx> for $ty { . type Lifted = $lifted; . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { 1,776 ( 0.00%) if tcx.interners.$set.contains_pointer_to(&Interned(self)) { . Some(unsafe { mem::transmute(self) }) . } else { . None . } . } . } . }; . } -- line 1630 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 2 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 103,147 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 411,743 ( 0.01%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1791 ---------------------------------------- . . /// Allows access to the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with_context(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 914 ( 0.00%) with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls"))) . } . . /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument . /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime . /// as the `TyCtxt` passed in. . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 199,276 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 196,508 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 369,385 ( 0.01%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 173,796 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 90,117 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 28,668 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 342,311 ( 0.01%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 44,856 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 113,702 ( 0.00%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 34,688 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 958,518 ( 0.02%) pub fn $method(self, v: $ty) -> &'tcx $ty { 492,366 ( 0.01%) self.interners.$name.intern(v, |v| { 6,871 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 1,074,816 ( 0.02%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 3,757,248 ( 0.08%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 3,361,491 ( 0.07%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2129 ---------------------------------------- . /// unsafe. . pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { . assert_eq!(sig.unsafety(), hir::Unsafety::Normal); . self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig })) . } . . /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name` . /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`. 1,884 ( 0.00%) pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool { . self.super_traits_of(trait_def_id).any(|trait_did| { . self.associated_items(trait_did) . .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did) . .is_some() . }) 1,413 ( 0.00%) } . . /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally) . /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used . /// to identify which traits may define a given associated type to help avoid cycle errors. . /// Returns a `DefId` iterator. . fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator + 'tcx { . let mut set = FxHashSet::default(); 314 ( 0.00%) let mut stack = vec![trait_def_id]; . . set.insert(trait_def_id); . 1,413 ( 0.00%) iter::from_fn(move || -> Option { 490 ( 0.00%) let trait_did = stack.pop()?; 245 ( 0.00%) let generic_predicates = self.super_predicates_of(trait_did); . . for (predicate, _) in generic_predicates.predicates { 498 ( 0.00%) if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() { 332 ( 0.00%) if set.insert(data.def_id()) { . stack.push(data.def_id()); . } . } . } . . Some(trait_did) . }) . } -- line 2169 ---------------------------------------- -- line 2188 ---------------------------------------- . self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) . } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 119,804 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 2,819,891 ( 0.06%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 1,182,791 ( 0.03%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 2,053,864 ( 0.04%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 190,165 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 2,053,864 ( 0.04%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 269 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 269 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 528 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 528 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 290 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . -- line 2259 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 2,934 ( 0.00%) pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { . self.mk_ty(Array(ty, ty::Const::from_usize(self, n))) 3,056 ( 0.00%) } . . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { 912 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 1,511 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 17,410 ( 0.00%) iter.intern_with(|ts| { 5,440 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 18,663 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 15,291 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 1,460 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { . if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 1,928 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 2,988 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 29,785 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 19,391 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 5,652 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 6,626 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 29,785 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 924 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 924 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 1,848 ( 0.00%) } . 20 ( 0.00%) pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { 60 ( 0.00%) self.mk_place_elem(place, PlaceElem::Deref) 40 ( 0.00%) } . 160 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 160 ( 0.00%) self.mk_place_elem( . place, 320 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 320 ( 0.00%) } . . pub fn mk_place_downcast_unnamed( . self, . place: Place<'tcx>, . variant_index: VariantIdx, . ) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index)) . } . 2 ( 0.00%) pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> { 2 ( 0.00%) self.mk_place_elem(place, PlaceElem::Index(index)) 4 ( 0.00%) } . . /// This method copies `Place`'s projection, add an element and reintern it. Should not be used . /// to build a full `Place` it's just a convenient way to grab a projection and modify it in . /// flight. 11,196 ( 0.00%) pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } 12,440 ( 0.00%) } . 12,712 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 1,887 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 105 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 7,548 ( 0.00%) self._intern_poly_existential_predicates(eps) 14,528 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 8,329 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 5,103 ( 0.00%) self._intern_predicates(preds) . } 6,464 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 50,697 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 2,766 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 605,235 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 20,520 ( 0.00%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 22,601 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 19,602 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 28,083 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 282 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 16,743 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 20,056 ( 0.00%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 3,092 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 733 ( 0.00%) c_variadic, 885 ( 0.00%) unsafety, 1,162 ( 0.00%) abi, 540 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 7,232 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 26 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 18,203 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . 384 ( 0.00%) pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 390,876 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) 512 ( 0.00%) } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 140,497 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 18,025 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 36,050 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 72,329 ( 0.00%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 123,648 ( 0.00%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 123,648 ( 0.00%) let hir = self.hir(); . loop { 237,411 ( 0.01%) if id == bound { . return bound; . } . 310,479 ( 0.01%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 184,419 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 176,640 ( 0.00%) } . 7,248 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 59,682 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 5,222 ( 0.00%) let next = self.hir().get_parent_node(id); 15,666 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 7,248 ( 0.00%) } . 112 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 2,911 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 698 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 64 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 4,970 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 1,420 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 1,420 ( 0.00%) Some(&*candidates) 5,680 ( 0.00%) } . 16,891 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 21,717 ( 0.00%) } . 2,322 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 94 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 2,064 ( 0.00%) } . 12,243 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 15,741 ( 0.00%) } . 13,977 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 13,977 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 350 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 35 ( 0.00%) if self.is_const_fn_raw(def_id) { 4 ( 0.00%) match self.lookup_const_stability(def_id) { 8 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. . self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 315 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 176,904 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 1,724,546 ( 0.04%) E::intern_with(self, f) 120,753 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 244,208 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 298,940 ( 0.01%) match iter.size_hint() { . (0, Some(0)) => { 6 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 3 ( 0.00%) assert!(iter.next().is_none()); 48,937 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 246 ( 0.00%) assert!(iter.next().is_none()); 29,794 ( 0.00%) f(&[t0, t1]) . } 2,108 ( 0.00%) _ => f(&iter.collect::>()), . } 227,169 ( 0.00%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 9,871 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 216 ( 0.00%) f(&iter.cloned().collect::>()) 8,108 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 543,642 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 418,608 ( 0.01%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 5,268 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 43,626 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 262 ( 0.00%) let t0 = iter.next().unwrap()?; 262 ( 0.00%) let t1 = iter.next().unwrap()?; 393 ( 0.00%) assert!(iter.next().is_none()); 32,592 ( 0.00%) f(&[t0, t1]) . } 5,126 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 610,039 ( 0.01%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 199,276 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 11 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = . |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 8,352 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 1,314,446 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of . // a wrapper `fn` pointer, once `const fn` can reference `static`s. . extern "C" fn get() -> &'static Self { . static COUNTERS: HandleCounters = HandleCounters { . $($oty: AtomicUsize::new(1),)* . $($ity: AtomicUsize::new(1),)* . }; . &COUNTERS 78 ( 0.00%) } . } . . // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`. . #[repr(C)] . #[allow(non_snake_case)] . pub(super) struct HandleStore { . $($oty: handle::OwnedStore,)* . $($ity: handle::InternedStore,)* . } . . impl HandleStore { 234 ( 0.00%) pub(super) fn new(handle_counters: &'static HandleCounters) -> Self { 2,301 ( 0.00%) HandleStore { . $($oty: handle::OwnedStore::new(&handle_counters.$oty),)* . $($ity: handle::InternedStore::new(&handle_counters.$ity),)* . } 312 ( 0.00%) } . } . . $( . #[repr(C)] . pub(crate) struct $oty(handle::Handle); . impl !Send for $oty {} . impl !Sync for $oty {} . . // Forward `Drop::drop` to the inherent `drop` method. . impl Drop for $oty { 5,052 ( 0.00%) fn drop(&mut self) { 93,826 ( 0.00%) $oty(self.0).drop(); 7,578 ( 0.00%) } . } . . impl Encode for $oty { 312 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { 117 ( 0.00%) let handle = self.0; 156 ( 0.00%) mem::forget(self); 39 ( 0.00%) handle.encode(w, s); 78 ( 0.00%) } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 381,942 ( 0.01%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$oty.take(handle::Handle::decode(r, &mut ())) 509,256 ( 0.01%) } . } . . impl Encode for &$oty { . fn encode(self, w: &mut Writer, s: &mut S) { 373,425 ( 0.01%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> Decode<'_, 's, HandleStore>> . for &'s Marked . { 124,475 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &'s HandleStore>) -> Self { . &s.$oty[handle::Handle::decode(r, &mut ())] 248,950 ( 0.01%) } . } . . impl Encode for &mut $oty { . fn encode(self, w: &mut Writer, s: &mut S) { 183,903 ( 0.00%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore>> . for &'s mut Marked . { 61,301 ( 0.00%) fn decode( . r: &mut Reader<'_>, . s: &'s mut HandleStore> . ) -> Self { . &mut s.$oty[handle::Handle::decode(r, &mut ())] 122,602 ( 0.00%) } . } . . impl Encode>> . for Marked . { 687,606 ( 0.01%) fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 69,200 ( 0.00%) s.$oty.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $oty { 234 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 234 ( 0.00%) $oty(handle::Handle::decode(r, s)) 234 ( 0.00%) } . } . )* . . $( . #[repr(C)] 612,423 ( 0.01%) #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub(crate) struct $ity(handle::Handle); . impl !Send for $ity {} . impl !Sync for $ity {} . . impl Encode for $ity { . fn encode(self, w: &mut Writer, s: &mut S) { . self.0.encode(w, s); . } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 92,254 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$ity.copy(handle::Handle::decode(r, &mut ())) 184,508 ( 0.00%) } . } . . impl Encode>> . for Marked . { . fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 614,142 ( 0.01%) s.$ity.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $ity { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . $ity(handle::Handle::decode(r, s)) . } . } -- line 154 ---------------------------------------- -- line 175 ---------------------------------------- . . // FIXME(eddyb) generate these impls by pattern-matching on the . // names of methods - also could use the presence of `fn drop` . // to distinguish between 'owned and 'interned, above. . // Alternatively, special 'modes" could be listed of types in with_api . // instead of pattern matching on methods, here and in server decl. . . impl Clone for TokenStream { 2,022 ( 0.00%) fn clone(&self) -> Self { . self.clone() 2,022 ( 0.00%) } . } . . impl Clone for TokenStreamIter { . fn clone(&self) -> Self { . self.clone() . } . } . . impl Clone for Group { 369 ( 0.00%) fn clone(&self) -> Self { . self.clone() 369 ( 0.00%) } . } . . impl Clone for Literal { 999 ( 0.00%) fn clone(&self) -> Self { . self.clone() 999 ( 0.00%) } . } . . impl fmt::Debug for Literal { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("Literal") . // format the kind without quotes, as in `kind: Float` . .field("kind", &format_args!("{}", &self.debug_kind())) . .field("symbol", &self.symbol()) -- line 211 ---------------------------------------- -- line 219 ---------------------------------------- . impl Clone for SourceFile { . fn clone(&self) -> Self { . self.clone() . } . } . . impl fmt::Debug for Span { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 19,710 ( 0.00%) f.write_str(&self.debug()) . } . } . . macro_rules! define_client_side { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* . }),* $(,)?) => { . $(impl $name { 211,770 ( 0.00%) $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* { 109,404 ( 0.00%) Bridge::with(|bridge| { . let mut b = bridge.cached_buffer.take(); . . b.clear(); 1,578,486 ( 0.03%) api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ()); 303,243 ( 0.01%) reverse_encode!(b; $($arg),*); . 3,156,972 ( 0.07%) b = bridge.dispatch.call(b); . 2,240,648 ( 0.05%) let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ()); . 6,313,944 ( 0.14%) bridge.cached_buffer = b; . 929,088 ( 0.02%) r.unwrap_or_else(|e| panic::resume_unwind(e.into())) . }) 176,475 ( 0.00%) })* . })* . } . } . with_api!(self, self, define_client_side); . . enum BridgeState<'a> { . /// No server is currently connected to this client. . NotConnected, -- line 260 ---------------------------------------- -- line 270 ---------------------------------------- . enum BridgeStateL {} . . impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL { . type Out = BridgeState<'a>; . } . . thread_local! { . static BRIDGE_STATE: scoped_cell::ScopedCell = 3 ( 0.00%) scoped_cell::ScopedCell::new(BridgeState::NotConnected); . } . . impl BridgeState<'_> { . /// Take exclusive control of the thread-local . /// `BridgeState`, and pass it to `f`, mutably. . /// The state will be restored after `f` exits, even . /// by panic, including modifications made to it by `f`. . /// . /// N.B., while `f` is running, the thread-local state . /// is `BridgeState::InUse`. 467,255 ( 0.01%) fn with(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { 567,991 ( 0.01%) BRIDGE_STATE.with(|state| { 2,779,971 ( 0.06%) state.replace(BridgeState::InUse, |mut state| { . // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone 936 ( 0.00%) f(&mut *state) 156 ( 0.00%) }) 156 ( 0.00%) }) 378,442 ( 0.01%) } . } . . impl Bridge<'_> { . pub(crate) fn is_available() -> bool { 3 ( 0.00%) BridgeState::with(|state| match state { . BridgeState::Connected(_) | BridgeState::InUse => true, . BridgeState::NotConnected => false, . }) . } . 234 ( 0.00%) fn enter(self, f: impl FnOnce() -> R) -> R { 273 ( 0.00%) let force_show_panics = self.force_show_panics; . // Hide the default panic output within `proc_macro` expansions. . // NB. the server can't do this because it may use a different libstd. . static HIDE_PANICS_DURING_EXPANSION: Once = Once::new(); 197 ( 0.00%) HIDE_PANICS_DURING_EXPANSION.call_once(|| { 7 ( 0.00%) panic::update_hook(move |prev, info| { . let show = BridgeState::with(|state| match state { . BridgeState::NotConnected => true, . BridgeState::Connected(_) | BridgeState::InUse => force_show_panics, . }); . if show { . prev(info) . } . }); 2 ( 0.00%) }); . 1,443 ( 0.00%) BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f)) 78 ( 0.00%) } . 195 ( 0.00%) fn with(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R { 3,773,663 ( 0.08%) BridgeState::with(|state| match state { . BridgeState::NotConnected => { . panic!("procedural macro API is used outside of a procedural macro"); . } . BridgeState::InUse => { . panic!("procedural macro API is used while it's already in use"); . } 507 ( 0.00%) BridgeState::Connected(bridge) => f(bridge), 156 ( 0.00%) }) 156 ( 0.00%) } . } . . /// A client-side "global object" (usually a function pointer), . /// which may be using a different `proc_macro` from the one . /// used by the server, but can be interacted with compatibly. . /// . /// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer). . /// The call ABI of function pointers used for `F` doesn't -- line 345 ---------------------------------------- -- line 353 ---------------------------------------- . pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters, . pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer, . pub(super) f: F, . } . . /// Client-side helper for handling client panics, entering the bridge, . /// deserializing input and serializing output. . // FIXME(eddyb) maybe replace `Bridge::enter` with this? 273 ( 0.00%) fn run_client DecodeMut<'a, 's, ()>, R: Encode<()>>( . mut bridge: Bridge<'_>, . f: impl FnOnce(A) -> R, . ) -> Buffer { . // The initial `cached_buffer` contains the input. 234 ( 0.00%) let mut b = bridge.cached_buffer.take(); . 1,404 ( 0.00%) panic::catch_unwind(panic::AssertUnwindSafe(|| { 585 ( 0.00%) bridge.enter(|| { 741 ( 0.00%) let reader = &mut &b[..]; 273 ( 0.00%) let input = A::decode(reader, &mut ()); . . // Put the `cached_buffer` back in the `Bridge`, for requests. 780 ( 0.00%) Bridge::with(|bridge| bridge.cached_buffer = b.take()); . 624 ( 0.00%) let output = f(input); . . // Take the `cached_buffer` back out, for the output value. 741 ( 0.00%) b = Bridge::with(|bridge| bridge.cached_buffer.take()); . . // HACK(eddyb) Separate encoding a success value (`Ok(output)`) . // from encoding a panic (`Err(e: PanicMessage)`) to avoid . // having handles outside the `bridge.enter(|| ...)` scope, and . // to catch panics that could happen while encoding the success. . // . // Note that panics should be impossible beyond this point, but . // this is defensively trying to avoid any accidental panicking . // reaching the `extern "C"` (which should `abort` but might not . // at the moment, so this is also potentially preventing UB). 117 ( 0.00%) b.clear(); 390 ( 0.00%) Ok::<_, ()>(output).encode(&mut b, &mut ()); 156 ( 0.00%) }) 78 ( 0.00%) })) . .map_err(PanicMessage::from) 39 ( 0.00%) .unwrap_or_else(|e| { . b.clear(); . Err::<(), _>(e).encode(&mut b, &mut ()); . }); . b 78 ( 0.00%) } . . impl Client crate::TokenStream> { . #[rustc_allow_const_fn_unstable(const_fn)] 1 ( 0.00%) pub const fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self { . extern "C" fn run( . bridge: Bridge<'_>, . f: impl FnOnce(crate::TokenStream) -> crate::TokenStream, . ) -> Buffer { . run_client(bridge, |input| f(crate::TokenStream(input)).0) . } 5 ( 0.00%) Client { get_handle_counters: HandleCounters::get, run, f } 1 ( 0.00%) } . } . . impl Client crate::TokenStream> { . #[rustc_allow_const_fn_unstable(const_fn)] . pub const fn expand2( . f: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, . ) -> Self { 273 ( 0.00%) extern "C" fn run( . bridge: Bridge<'_>, . f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, . ) -> Buffer { 702 ( 0.00%) run_client(bridge, |(input, input2)| { 780 ( 0.00%) f(crate::TokenStream(input), crate::TokenStream(input2)).0 117 ( 0.00%) }) 78 ( 0.00%) } . Client { get_handle_counters: HandleCounters::get, run, f } . } . } . . #[repr(C)] . #[derive(Copy, Clone)] . pub enum ProcMacro { . CustomDerive { -- line 435 ---------------------------------------- 1,463,174 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.86/src/ident.rs -------------------------------------------------------------------------------- Ir -- line 13 ---------------------------------------- . #[cfg(feature = "parsing")] . #[doc(hidden)] . #[allow(non_snake_case)] . pub fn Ident(marker: lookahead::TokenMarker) -> Ident { . match marker {} . } . . #[cfg(feature = "parsing")] 35,106 ( 0.00%) fn accept_as_ident(ident: &Ident) -> bool { 117,020 ( 0.00%) match ident.to_string().as_str() { 93,511 ( 0.00%) "_" | . // Based on https://doc.rust-lang.org/grammar.html#keywords . // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md . // and https://github.com/rust-lang/rfcs/blob/master/text/2420-unreserve-proc.md 648,820 ( 0.01%) "abstract" | "as" | "become" | "box" | "break" | "const" | "continue" | 728,337 ( 0.02%) "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" | "fn" | 709,449 ( 0.02%) "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" | 597,405 ( 0.01%) "mod" | "move" | "mut" | "override" | "priv" | "pub" | "ref" | 584,290 ( 0.01%) "return" | "Self" | "self" | "static" | "struct" | "super" | "trait" | 582,778 ( 0.01%) "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" | "virtual" | 252,292 ( 0.01%) "where" | "while" | "yield" => false, 10,404 ( 0.00%) _ => true, . } 81,914 ( 0.00%) } . . #[cfg(feature = "parsing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] . impl Parse for Ident { 20,288 ( 0.00%) fn parse(input: ParseStream) -> Result { 35,504 ( 0.00%) input.step(|cursor| { 147,088 ( 0.00%) if let Some((ident, rest)) = cursor.ident() { 25,360 ( 0.00%) if accept_as_ident(&ident) { 96,368 ( 0.00%) return Ok((ident, rest)); . } 5,072 ( 0.00%) } . Err(cursor.error("expected identifier")) 10,144 ( 0.00%) }) 10,144 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl Token for Ident { 34,960 ( 0.00%) fn peek(cursor: Cursor) -> bool { 163,464 ( 0.00%) if let Some((ident, _rest)) = cursor.ident() { 33,150 ( 0.00%) accept_as_ident(&ident) 19,890 ( 0.00%) } else { 362 ( 0.00%) false . } 111,510 ( 0.00%) } . . fn display() -> &'static str { . "identifier" 681 ( 0.00%) } . } . . macro_rules! ident_from_token { . ($token:ident) => { . impl From for Ident { . fn from(token: Token![$token]) -> Ident { . Ident::new(stringify!($token), token.span) . } -- line 73 ---------------------------------------- 1,617,036 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 402 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 402 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 804 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 101,120 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 687,616 ( 0.01%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 60,672 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 121,344 ( 0.00%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 32,388 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 499,502 ( 0.01%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 3,790 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 14,297 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 101,614 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 125,724 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 164,576 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 214,854 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 11,370 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 2,283 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 2,220 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 2,835 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 20,224 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 60,672 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 20,224 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 8,928 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 10,912 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 4,960 ( 0.00%) self.with_opaque_type_inference(table_owner) 6,944 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 992 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 496 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 2,976 ( 0.00%) self 1,488 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 34,421 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 55,548 ( 0.00%) let (value, subst) = 3,384 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 82,689 ( 0.00%) f(infcx, value, subst) . }) 37,390 ( 0.00%) } . 96,975 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 55,973 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 845,389 ( 0.02%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 20,224 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 20,224 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 106,355 ( 0.00%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 492 ( 0.00%) let InferOk { value, obligations } = self; 2,016 ( 0.00%) for obligation in obligations { . fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 16,563 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 66,252 ( 0.00%) self.obligations 16,563 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 24,772 ( 0.00%) } . 225,392 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 253,566 ( 0.01%) t.fold_with(&mut self.freshener()) 253,566 ( 0.01%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 598 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 1,196 ( 0.00%) match *ty.kind() { 294 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 1,176 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } 5 ( 0.00%) _ => None, . } 1,196 ( 0.00%) } . 28,174 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 28,174 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 88,146 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 88,146 ( 0.00%) } . 2,120 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 1,060 ( 0.00%) let mut inner = self.inner.borrow_mut(); 1,060 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 588 ( 0.00%) .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) 100 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) 5 ( 0.00%) .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 3,710 ( 0.00%) } . 54,346 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 225,624 ( 0.00%) CombineFields { . infcx: self, 564,060 ( 0.01%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 54,346 ( 0.00%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 755 ---------------------------------------- . /// better than grovelling through megabytes of `RUSTC_LOG` output. . /// . /// HOWEVER, in some cases the flag is unhelpful. In particular, we . /// sometimes create a "mini-fulfilment-cx" in which we enroll . /// obligations. As long as this fulfillment cx is fully drained . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. 32 ( 0.00%) pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 6,282 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result 36 ( 0.00%) } . 304,988 ( 0.01%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 914,964 ( 0.02%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 152,494 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 609,976 ( 0.01%) } . 704,473 ( 0.02%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 64,043 ( 0.00%) undo_snapshot, 64,043 ( 0.00%) region_constraints_snapshot, 64,043 ( 0.00%) universe, 64,043 ( 0.00%) was_in_snapshot, 128,086 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 64,043 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 1,326,765 ( 0.03%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 88,451 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 88,451 ( 0.00%) was_in_snapshot, 176,902 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 65,696 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 82,500 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 7,500 ( 0.00%) let snapshot = self.start_snapshot(); 27,140 ( 0.00%) let r = f(&snapshot); 52,500 ( 0.00%) self.commit_from(snapshot); 54,876 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 726,919 ( 0.02%) #[instrument(skip(self, f), level = "debug")] 893,790 ( 0.02%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 121,110 ( 0.00%) let snapshot = self.start_snapshot(); 415,927 ( 0.01%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 88,201 ( 0.00%) match r { . Ok(_) => { 604,915 ( 0.01%) self.commit_from(snapshot); . } . Err(_) => { 273,626 ( 0.01%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 594,590 ( 0.01%) r . } . . /// Execute `f` then unroll any bindings it creates. 233,609 ( 0.01%) #[instrument(skip(self, f), level = "debug")] 277,580 ( 0.01%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 69,134 ( 0.00%) let snapshot = self.start_snapshot(); 113,347 ( 0.00%) let r = f(&snapshot); 315,137 ( 0.01%) self.rollback_to("probe", snapshot); 24,089 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. 15,615 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 20,820 ( 0.00%) pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 3,470 ( 0.00%) let snapshot = self.start_snapshot(); 1,735 ( 0.00%) let was_skip_leak_check = self.skip_leak_check.get(); 3,470 ( 0.00%) if should_skip { . self.skip_leak_check.set(true); . } 6,940 ( 0.00%) let r = f(&snapshot); 15,615 ( 0.00%) self.rollback_to("probe", snapshot); . self.skip_leak_check.set(was_skip_leak_check); 20,820 ( 0.00%) r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 20,706 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 41,412 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 31,059 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . 1,140 ( 0.00%) pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 855 ( 0.00%) } . 6,108 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 4,581 ( 0.00%) } . 45,250 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 40,725 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. . #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, -- line 947 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 171 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 114 ( 0.00%) let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); 285 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 228 ( 0.00%) } . 13,788 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 1,149 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 1,149 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 7,794 ( 0.00%) match (r_a.kind(), r_b.kind()) { 1,648 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 1,648 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 325 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 650 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 10,341 ( 0.00%) } . 10,800 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 9,000 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 7,200 ( 0.00%) } . . /// Number of type variables created so far. 128 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 256 ( 0.00%) } . 13,912 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 69,560 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 20,868 ( 0.00%) } . 12,374 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 47,925 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 18,561 ( 0.00%) } . 1,710 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 9,405 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 855 ( 0.00%) self.tcx.mk_ty_var(vid) 2,565 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 175 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 105 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 140 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 8,909 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 220,544 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 17,818 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 93,170 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 605,605 ( 0.01%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 232,925 ( 0.01%) self.tcx.mk_region(ty::ReVar(region_var)) 139,755 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 6,682 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 10,023 ( 0.00%) } . . /// Number of region variables created so far. 4,156 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 6,234 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 13,933 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 27,866 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 626 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 4,562 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 1,252 ( 0.00%) } . 321,136 ( 0.01%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 172,360 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 14,175 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 101,876 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 127,345 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 25,469 ( 0.00%) param.name, 25,469 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 25,469 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 5,478 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 498 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 3,984 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 61,644 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 314,983 ( 0.01%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 41,096 ( 0.00%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 1,402 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 35,165 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 2,103 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 35,301 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 95,817 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 5,043 ( 0.00%) assert!( 15,129 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 5,043 ( 0.00%) }; . . let region_rels = 5,043 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 45,387 ( 0.00%) let (lexical_region_resolutions, errors) = 121,032 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 20,172 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 5,043 ( 0.00%) assert!(old_value.is_none()); . . errors 45,387 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 50,430 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 10,086 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 15,129 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 10,086 ( 0.00%) self.report_region_errors(&errors); . } 25,215 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate -- line 1307 ---------------------------------------- -- line 1319 ---------------------------------------- . } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 19,732 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 2,480 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 9,424 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 496 ( 0.00%) .into_infos_and_data(); 496 ( 0.00%) assert!(data.is_empty()); . var_infos 3,968 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 7,692 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 23,076 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 26,922 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 169,052 ( 0.00%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 12,318 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 18,477 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. 35,472 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 177,519 ( 0.00%) if !value.needs_infer() { 171,218 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 167,366 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 207,399 ( 0.00%) value.fold_with(&mut r) 32,188 ( 0.00%) } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> . where -- line 1415 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 8,712 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 108,442 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 324,016 ( 0.01%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 5,808 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 26,192 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 9,822 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 55,658 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 22,918 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. 2,654 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 5,308 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 3,981 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 381,396 ( 0.01%) self.universe.get() 109,216 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 1,798 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 2,020 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 1,798 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 2,364,456 ( 0.05%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 1,213,540 ( 0.03%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 639,944 ( 0.01%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 2,864 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 939 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 2,660,013 ( 0.06%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 648,615 ( 0.01%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 1,440 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 5,700 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 5,700 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 1,624 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 64,528 ( 0.00%) match *ty.kind() { 14,220 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 44 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 1,624 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 459,587 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 3,920 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 3,092 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 2,830 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 1,698 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 4,900 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 28 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 70 ( 0.00%) match *self { 14 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 17,762 ( 0.00%) match *cause.code() { 3,536 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 17,680 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 2,062,279 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs -------------------------------------------------------------------------------- Ir -- line 124 ---------------------------------------- . /// sizes and avoid calling `memcpy`, which is good for speed. . /// . /// Unsafe because: unchecked indexing at start..start+len . #[inline] . unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { . debug_assert!(len < 8); . let mut i = 0; // current byte index (from LSB) in the output u64 . let mut out = 0; 1,259,876 ( 0.03%) if i + 3 < len { . // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee . // that the index start..start+len is in bounds. . out = unsafe { load_int_le!(buf, start + i, u32) } as u64; . i += 4; . } 2,603,153 ( 0.06%) if i + 1 < len { . // SAFETY: same as above. 1,301,568 ( 0.03%) out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); 650,562 ( 0.01%) i += 2 . } 1,487,619 ( 0.03%) if i < len { . // SAFETY: same as above. 1,658,914 ( 0.04%) out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8); . i += 1; . } . debug_assert_eq!(i, len); . out . } . . impl SipHasher { . /// Creates a new `SipHasher` with the two initial keys set to 0. -- line 153 ---------------------------------------- -- line 190 ---------------------------------------- . /// Creates a `SipHasher13` that is keyed off the provided keys. . #[inline] . #[unstable(feature = "hashmap_internals", issue = "none")] . #[rustc_deprecated( . since = "1.13.0", . reason = "use `std::collections::hash_map::DefaultHasher` instead" . )] . pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { 265,891 ( 0.01%) SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) } . } . } . . impl Hasher { . #[inline] . fn new_with_keys(key0: u64, key1: u64) -> Hasher { 9 ( 0.00%) let mut state = Hasher { . k0: key0, . k1: key1, . length: 0, . state: State { v0: 0, v1: 0, v2: 0, v3: 0 }, . tail: 0, . ntail: 0, . _marker: PhantomData, . }; . state.reset(); . state . } . . #[inline] . fn reset(&mut self) { . self.length = 0; 398,832 ( 0.01%) self.state.v0 = self.k0 ^ 0x736f6d6570736575; 419,683 ( 0.01%) self.state.v1 = self.k1 ^ 0x646f72616e646f6d; . self.state.v2 = self.k0 ^ 0x6c7967656e657261; . self.state.v3 = self.k1 ^ 0x7465646279746573; . self.ntail = 0; . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl super::Hasher for SipHasher { -- line 230 ---------------------------------------- -- line 258 ---------------------------------------- . // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*` . // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would . // greatly speed up integer hashing by those hashers, at the cost of . // slightly slowing down compile speeds on some benchmarks. See #69152 for . // details. . #[inline] . fn write(&mut self, msg: &[u8]) { . let length = msg.len(); 1,573,407 ( 0.03%) self.length += length; . . let mut needed = 0; . 1,552,545 ( 0.03%) if self.ntail != 0 { 769,012 ( 0.02%) needed = 8 - self.ntail; . // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length` 3,845,010 ( 0.08%) self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); 769,002 ( 0.02%) if length < needed { 502,494 ( 0.01%) self.ntail += length; . return; . } else { 133,254 ( 0.00%) self.state.v3 ^= self.tail; . S::c_rounds(&mut self.state); 266,508 ( 0.01%) self.state.v0 ^= self.tail; 133,254 ( 0.00%) self.ntail = 0; . } . } . . // Buffered tail is now flushed, process new input. 490,823 ( 0.01%) let len = length - needed; 490,834 ( 0.01%) let left = len & 0x7; // len % 8 . . let mut i = needed; 736,577 ( 0.02%) while i < len - left { . // SAFETY: because `len - left` is the biggest multiple of 8 under . // `len`, and because `i` starts at `needed` where `len` is `length - needed`, . // `i + 8` is guaranteed to be less than or equal to `length`. . let mi = unsafe { load_int_le!(msg, i, u64) }; . 163 ( 0.00%) self.state.v3 ^= mi; . S::c_rounds(&mut self.state); 163 ( 0.00%) self.state.v0 ^= mi; . 326 ( 0.00%) i += 8; . } . . // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`, . // so `i + left` = `needed + len` = `length`, which is by . // definition equal to `msg.len()`. 511,674 ( 0.01%) self.tail = unsafe { u8to64_le(msg, i, left) }; . self.ntail = left; . } . . #[inline] . fn finish(&self) -> u64 { 132,947 ( 0.00%) let mut state = self.state; . 664,735 ( 0.01%) let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; . 132,947 ( 0.00%) state.v3 ^= b; . S::c_rounds(&mut state); 132,947 ( 0.00%) state.v0 ^= b; . 132,947 ( 0.00%) state.v2 ^= 0xff; . S::d_rounds(&mut state); . 265,894 ( 0.01%) state.v0 ^ state.v1 ^ state.v2 ^ state.v3 . } . } . . impl Clone for Hasher { . #[inline] . fn clone(&self) -> Hasher { . Hasher { . k0: self.k0, -- line 331 ---------------------------------------- -- line 354 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip13Rounds; . . impl Sip for Sip13Rounds { . #[inline] . fn c_rounds(state: &mut State) { 1,731,962 ( 0.04%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 531,788 ( 0.01%) compress!(state); 531,788 ( 0.01%) compress!(state); 398,841 ( 0.01%) compress!(state); . } . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip for Sip24Rounds { . #[inline] -- line 377 ---------------------------------------- 3,594,598 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . /// let a = [1, 2, 3]; . /// assert_eq!(a.len(), 3); . /// ``` . #[lang = "slice_len_fn"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")] . #[inline] . // SAFETY: const sound because we transmute out the length field as a usize (which it must be) 47,631 ( 0.00%) pub const fn len(&self) -> usize { . // FIXME: Replace with `crate::ptr::metadata(self)` when that is const-stable. . // As of this writing this causes a "Const-stable functions can only call other . // const-stable functions" error. . . // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T . // and PtrComponents have the same memory layouts. Only std can make this . // guarantee. 47,631 ( 0.00%) unsafe { crate::ptr::PtrRepr { const_ptr: self }.components.metadata } 31,754 ( 0.00%) } . . /// Returns `true` if the slice has a length of 0. . /// . /// # Examples . /// . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 636,310 ( 0.01%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 5,005 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 1,628 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 22,601 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 282,022 ( 0.01%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 694,269 ( 0.02%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 317 ---------------------------------------- . /// let v = [10, 40, 30]; . /// assert_eq!(Some(&40), v.get(1)); . /// assert_eq!(Some(&[10, 40][..]), v.get(0..2)); . /// assert_eq!(None, v.get(3)); . /// assert_eq!(None, v.get(0..4)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 9,872 ( 0.00%) pub fn get(&self, index: I) -> Option<&I::Output> . where . I: SliceIndex, . { 2,468 ( 0.00%) index.get(self) 2,468 ( 0.00%) } . . /// Returns a mutable reference to an element or subslice depending on the . /// type of index (see [`get`]) or `None` if the index is out of bounds. . /// . /// [`get`]: slice::get . /// . /// # Examples . /// -- line 338 ---------------------------------------- -- line 447 ---------------------------------------- . /// } . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] 1,537,500 ( 0.03%) pub const fn as_ptr(&self) -> *const T { 898,533 ( 0.02%) self as *const [T] as *const T 768,750 ( 0.02%) } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer . /// to be reallocated, which would also make any pointers to it invalid. -- line 465 ---------------------------------------- -- line 475 ---------------------------------------- . /// *x_ptr.add(i) += 2; . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] 13,032 ( 0.00%) pub const fn as_mut_ptr(&mut self) -> *mut T { 17 ( 0.00%) self as *mut [T] as *mut T 6,516 ( 0.00%) } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. . /// -- line 493 ---------------------------------------- -- line 556 ---------------------------------------- . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "slice_ptr_range", since = "1.48.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> { . let start = self.as_mut_ptr(); . // SAFETY: See as_ptr_range() above for why `add` here is safe. . let end = unsafe { start.add(self.len()) }; 1 ( 0.00%) start..end . } . . /// Swaps two elements in the slice. . /// . /// # Arguments . /// . /// * a - The index of the first element . /// * b - The index of the second element -- line 572 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 27,856 ( 0.00%) let _ = &self[a]; 63,458 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 644 ---------------------------------------- . /// ``` . /// let mut v = [1, 2, 3]; . /// v.reverse(); . /// assert!(v == [3, 2, 1]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn reverse(&mut self) { 2 ( 0.00%) let half_len = self.len() / 2; . let Range { start, end } = self.as_mut_ptr_range(); . . // These slices will skip the middle item for an odd length, . // since that one doesn't need to move. . let (front_half, back_half) = . // SAFETY: Both are subparts of the original slice, so the memory . // range is valid, and they don't overlap because they're each only . // half (or less) of the original slice. -- line 660 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 4,533 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 697 ---------------------------------------- . /// . /// assert_eq!(iterator.next(), Some(&1)); . /// assert_eq!(iterator.next(), Some(&2)); . /// assert_eq!(iterator.next(), Some(&4)); . /// assert_eq!(iterator.next(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 629,829 ( 0.01%) pub fn iter(&self) -> Iter<'_, T> { 629,829 ( 0.01%) Iter::new(self) 419,886 ( 0.01%) } . . /// Returns an iterator that allows modifying each value. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [1, 2, 4]; . /// for elem in x.iter_mut() { . /// *elem += 2; . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 9,540 ( 0.00%) pub fn iter_mut(&mut self) -> IterMut<'_, T> { 9,540 ( 0.00%) IterMut::new(self) 6,360 ( 0.00%) } . . /// Returns an iterator over all contiguous windows of length . /// `size`. The windows overlap. If the slice is shorter than . /// `size`, the iterator returns no values. . /// . /// # Panics . /// . /// Panics if `size` is 0. -- line 732 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 348 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 51,882 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 4,627 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 308 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2137 ---------------------------------------- . /// . /// ``` . /// let v = &[10, 40, 30]; . /// assert!(v.starts_with(&[])); . /// let v: &[u8] = &[]; . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 24,458 ( 0.00%) pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { 10,482 ( 0.00%) let n = needle.len(); 63,101 ( 0.00%) self.len() >= n && needle == &self[..n] 17,470 ( 0.00%) } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; . /// assert!(v.ends_with(&[30])); -- line 2159 ---------------------------------------- -- line 2166 ---------------------------------------- . /// . /// ``` . /// let v = &[10, 40, 30]; . /// assert!(v.ends_with(&[])); . /// let v: &[u8] = &[]; . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 29,610 ( 0.00%) pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { 38,070 ( 0.00%) let (m, n) = (self.len(), needle.len()); 107,373 ( 0.00%) m >= n && needle == &self[m - n..] 21,150 ( 0.00%) } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. . /// -- line 2188 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 2,751,465 ( 0.06%) while left < right { 4,077,328 ( 0.09%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 504,288 ( 0.01%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 1,103,892 ( 0.02%) if cmp == Less { 2,047,961 ( 0.04%) left = mid + 1; 574,030 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 3,204,760 ( 0.07%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3187 ---------------------------------------- . /// assert_eq!(slice, [4, 5, 3, 4, 5]); . /// ``` . /// . /// [`clone_from_slice`]: slice::clone_from_slice . /// [`split_at_mut`]: slice::split_at_mut . #[doc(alias = "memcpy")] . #[stable(feature = "copy_from_slice", since = "1.9.0")] . #[track_caller] 780 ( 0.00%) pub fn copy_from_slice(&mut self, src: &[T]) . where . T: Copy, . { . // The panic code path was put into a cold function to not bloat the . // call site. . #[inline(never)] . #[cold] . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 127,348 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { 468 ( 0.00%) ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); . } 156 ( 0.00%) } . . /// Copies elements from one part of the slice to another part of itself, . /// using a memmove. . /// . /// `src` is the range within `self` to copy from. `dest` is the starting . /// index of the range within `self` to copy to, which will have the same . /// length as `src`. The two ranges may overlap. The ends of the two ranges . /// must be less than or equal to `self.len()`. -- line 3229 ---------------------------------------- -- line 3380 ---------------------------------------- . } . a << k . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! 2 ( 0.00%) let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 27,028 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 27,028 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 27,030 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- -- line 3731 ---------------------------------------- . /// let v = [1, 2, 3, 3, 5, 6, 7]; . /// let i = v.partition_point(|&x| x < 5); . /// . /// assert_eq!(i, 4); . /// assert!(v[..i].iter().all(|&x| x < 5)); . /// assert!(v[i..].iter().all(|&x| !(x < 5))); . /// ``` . #[stable(feature = "partition_point", since = "1.52.0")] 245 ( 0.00%) pub fn partition_point

(&self, mut pred: P) -> usize . where . P: FnMut(&T) -> bool, . { . self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i) 490 ( 0.00%) } . . /// Removes the subslice corresponding to the given range . /// and returns a reference to it. . /// . /// Returns `None` and does not modify the slice if the given . /// range is out of bounds. . /// . /// Note that this method only accepts one-sided ranges such as -- line 3752 ---------------------------------------- 2,849,926 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs -------------------------------------------------------------------------------- Ir -- line 246 ---------------------------------------- . // having an explicit negative impl is nice for documentation purposes . // and results in nicer error messages. . #[stable(feature = "rust1", since = "1.0.0")] . impl !Sync for Cell {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Cell { . #[inline] 28,036 ( 0.00%) fn clone(&self) -> Cell { 84,108 ( 0.00%) Cell::new(self.get()) 28,036 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Default for Cell { . /// Creates a `Cell`, with the `Default` value for T. . #[inline] . fn default() -> Cell { . Cell::new(Default::default()) -- line 264 ---------------------------------------- -- line 328 ---------------------------------------- . /// ``` . /// use std::cell::Cell; . /// . /// let c = Cell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_cell_new", since = "1.24.0")] . #[inline] 389,240 ( 0.01%) pub const fn new(value: T) -> Cell { 414,710 ( 0.01%) Cell { value: UnsafeCell::new(value) } 348,621 ( 0.01%) } . . /// Sets the contained value. . /// . /// # Examples . /// . /// ``` . /// use std::cell::Cell; . /// . /// let c = Cell::new(5); . /// . /// c.set(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 635,151 ( 0.01%) pub fn set(&self, val: T) { 2,973,484 ( 0.06%) let old = self.replace(val); 353,636 ( 0.01%) drop(old); 340,764 ( 0.01%) } . . /// Swaps the values of two `Cell`s. . /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. . /// . /// # Examples . /// . /// ``` . /// use std::cell::Cell; -- line 364 ---------------------------------------- -- line 392 ---------------------------------------- . /// use std::cell::Cell; . /// . /// let cell = Cell::new(5); . /// assert_eq!(cell.get(), 5); . /// assert_eq!(cell.replace(10), 5); . /// assert_eq!(cell.get(), 10); . /// ``` . #[stable(feature = "move_cell", since = "1.17.0")] 1,197,654 ( 0.03%) pub fn replace(&self, val: T) -> T { . // SAFETY: This can cause data races if called from a separate thread, . // but `Cell` is `!Sync` so this won't happen. 2,270,404 ( 0.05%) mem::replace(unsafe { &mut *self.value.get() }, val) 526,060 ( 0.01%) } . . /// Unwraps the value. . /// . /// # Examples . /// . /// ``` . /// use std::cell::Cell; . /// -- line 412 ---------------------------------------- -- line 431 ---------------------------------------- . /// use std::cell::Cell; . /// . /// let c = Cell::new(5); . /// . /// let five = c.get(); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 2,323,780 ( 0.05%) pub fn get(&self) -> T { . // SAFETY: This can cause data races if called from a separate thread, . // but `Cell` is `!Sync` so this won't happen. 972,558 ( 0.02%) unsafe { *self.value.get() } 929,512 ( 0.02%) } . . /// Updates the contained value using a function and returns the new value. . /// . /// # Examples . /// . /// ``` . /// #![feature(cell_update)] . /// -- line 451 ---------------------------------------- -- line 548 ---------------------------------------- . /// . /// let c = Cell::new(5); . /// let five = c.take(); . /// . /// assert_eq!(five, 5); . /// assert_eq!(c.into_inner(), 0); . /// ``` . #[stable(feature = "move_cell", since = "1.17.0")] 114,636 ( 0.00%) pub fn take(&self) -> T { 407,424 ( 0.01%) self.replace(Default::default()) 112,792 ( 0.00%) } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl, U> CoerceUnsized> for Cell {} . . impl Cell<[T]> { . /// Returns a `&[Cell]` from a `&Cell<[T]>` . /// -- line 566 ---------------------------------------- -- line 689 ---------------------------------------- . . #[inline(always)] . fn is_writing(x: BorrowFlag) -> bool { . x < UNUSED . } . . #[inline(always)] . fn is_reading(x: BorrowFlag) -> bool { 386,409 ( 0.01%) x > UNUSED . } . . impl RefCell { . /// Creates a new `RefCell` containing `value`. . /// . /// # Examples . /// . /// ``` . /// use std::cell::RefCell; . /// . /// let c = RefCell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")] . #[inline] 6,132 ( 0.00%) pub const fn new(value: T) -> RefCell { 104,899 ( 0.00%) RefCell { 76,028 ( 0.00%) value: UnsafeCell::new(value), 10,220 ( 0.00%) borrow: Cell::new(UNUSED), . #[cfg(feature = "debug_refcell")] . borrowed_at: Cell::new(None), . } 4,088 ( 0.00%) } . . /// Consumes the `RefCell`, returning the wrapped value. . /// . /// # Examples . /// . /// ``` . /// use std::cell::RefCell; . /// -- line 728 ---------------------------------------- -- line 731 ---------------------------------------- . /// let five = c.into_inner(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")] . #[inline] . pub const fn into_inner(self) -> T { . // Since this function takes `self` (the `RefCell`) by value, the . // compiler statically verifies that it is not currently borrowed. 3,172 ( 0.00%) self.value.into_inner() . } . . /// Replaces the wrapped value with a new one, returning the old value, . /// without deinitializing either one. . /// . /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html). . /// . /// # Panics -- line 747 ---------------------------------------- -- line 845 ---------------------------------------- . /// let c = RefCell::new(5); . /// . /// let m = c.borrow_mut(); . /// let b = c.borrow(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 4,471 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 13,413 ( 0.00%) } . . /// Immutably borrows the wrapped value, returning an error if the value is currently mutably . /// borrowed. . /// . /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be . /// taken out at the same time. . /// . /// This is the non-panicking variant of [`borrow`](#method.borrow). -- line 863 ---------------------------------------- -- line 937 ---------------------------------------- . /// let c = RefCell::new(5); . /// let m = c.borrow(); . /// . /// let b = c.borrow_mut(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 50,665 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { 78,688 ( 0.00%) self.try_borrow_mut().expect("already borrowed") 83,143 ( 0.00%) } . . /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed. . /// . /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived . /// from it exit scope. The value cannot be borrowed while this borrow is . /// active. . /// . /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). -- line 955 ---------------------------------------- -- line 966 ---------------------------------------- . /// assert!(c.try_borrow_mut().is_err()); . /// } . /// . /// assert!(c.try_borrow_mut().is_ok()); . /// ``` . #[stable(feature = "try_borrow", since = "1.13.0")] . #[inline] . #[cfg_attr(feature = "debug_refcell", track_caller)] 29,508 ( 0.00%) pub fn try_borrow_mut(&self) -> Result, BorrowMutError> { 88,524 ( 0.00%) match BorrowRefMut::new(&self.borrow) { 19,672 ( 0.00%) Some(b) => { . #[cfg(feature = "debug_refcell")] . { . self.borrowed_at.set(Some(crate::panic::Location::caller())); . } . . // SAFETY: `BorrowRef` guarantees unique access. 99,114 ( 0.00%) Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) . } . None => Err(BorrowMutError { . // If a borrow occurred, then we must already have an outstanding borrow, . // so `borrowed_at` will be `Some` . #[cfg(feature = "debug_refcell")] . location: self.borrowed_at.get().unwrap(), . }), . } 39,344 ( 0.00%) } . . /// Returns a raw pointer to the underlying data in this cell. . /// . /// # Examples . /// . /// ``` . /// use std::cell::RefCell; . /// -- line 1000 ---------------------------------------- -- line 1254 ---------------------------------------- . . struct BorrowRef<'b> { . borrow: &'b Cell, . } . . impl<'b> BorrowRef<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { 558,563 ( 0.01%) let b = borrow.get().wrapping_add(1); 331,770 ( 0.01%) if !is_reading(b) { . // Incrementing borrow can result in a non-reading value (<= 0) in these cases: . // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow . // due to Rust's reference aliasing rules . // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed . // into isize::MIN (the max amount of writing borrows) so we can't allow . // an additional read borrow because isize can't represent so many read borrows . // (this can only happen if you mem::forget more than a small constant amount of . // `Ref`s, which is not good practice) -- line 1271 ---------------------------------------- -- line 1279 ---------------------------------------- . Some(BorrowRef { borrow }) . } . } . } . . impl Drop for BorrowRef<'_> { . #[inline] . fn drop(&mut self) { 218,078 ( 0.00%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 442,897 ( 0.01%) self.borrow.set(borrow - 1); . } . } . . impl Clone for BorrowRef<'_> { . #[inline] . fn clone(&self) -> Self { . // Since this Ref exists, we know the borrow flag . // is a reading borrow. -- line 1297 ---------------------------------------- -- line 1644 ---------------------------------------- . } . . struct BorrowRefMut<'b> { . borrow: &'b Cell, . } . . impl Drop for BorrowRefMut<'_> { . #[inline] 29,508 ( 0.00%) fn drop(&mut self) { 4,277,287 ( 0.09%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 8,496,322 ( 0.18%) self.borrow.set(borrow + 1); 19,672 ( 0.00%) } . } . . impl<'b> BorrowRefMut<'b> { . #[inline] 29,508 ( 0.00%) fn new(borrow: &'b Cell) -> Option> { . // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial . // mutable reference, and so there must currently be no existing . // references. Thus, while clone increments the mutable refcount, here . // we explicitly only allow going from UNUSED to UNUSED - 1. 9,123,661 ( 0.20%) match borrow.get() { . UNUSED => { 29,508 ( 0.00%) borrow.set(UNUSED - 1); 39,344 ( 0.00%) Some(BorrowRefMut { borrow }) . } . _ => None, . } 29,508 ( 0.00%) } . . // Clones a `BorrowRefMut`. . // . // This is only valid if each `BorrowRefMut` is used to track a mutable . // reference to a distinct, nonoverlapping range of the original object. . // This isn't in a Clone impl so that code doesn't call this implicitly. . #[inline] . fn clone(&self) -> BorrowRefMut<'b> { -- line 1681 ---------------------------------------- -- line 1710 ---------------------------------------- . fn deref(&self) -> &T { . self.value . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DerefMut for RefMut<'_, T> { . #[inline] 19,672 ( 0.00%) fn deref_mut(&mut self) -> &mut T { 10,416 ( 0.00%) self.value 19,672 ( 0.00%) } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl<'b, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized> for RefMut<'b, T> {} . . #[stable(feature = "std_guard_impls", since = "1.20.0")] . impl fmt::Display for RefMut<'_, T> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 1728 ---------------------------------------- -- line 1863 ---------------------------------------- . /// use std::cell::UnsafeCell; . /// . /// let uc = UnsafeCell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_unsafe_cell_new", since = "1.32.0")] . #[inline(always)] . pub const fn new(value: T) -> UnsafeCell { 206,595 ( 0.00%) UnsafeCell { value } 247,796 ( 0.01%) } . . /// Unwraps the value. . /// . /// # Examples . /// . /// ``` . /// use std::cell::UnsafeCell; . /// -- line 1880 ---------------------------------------- -- line 1909 ---------------------------------------- . /// ``` . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")] . pub const fn get(&self) -> *mut T { . // We can just cast the pointer from `UnsafeCell` to `T` because of . // #[repr(transparent)]. This exploits libstd's special status, there is . // no guarantee for user code that this will work in future versions of the compiler! 2,508,612 ( 0.05%) self as *const UnsafeCell as *const T as *mut T . } . . /// Returns a mutable reference to the underlying data. . /// . /// This call borrows the `UnsafeCell` mutably (at compile-time) which . /// guarantees that we possess the only reference. . /// . /// # Examples -- line 1925 ---------------------------------------- 7,368,558 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.86/src/token.rs -------------------------------------------------------------------------------- Ir -- line 146 ---------------------------------------- . pub span: Span, . } . } . . #[cfg(feature = "parsing")] . impl private::Sealed for Ident {} . . #[cfg(feature = "parsing")] 35,945 ( 0.00%) fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool { . use crate::parse::Unexpected; . use std::cell::Cell; . use std::rc::Rc; . 20,540 ( 0.00%) let scope = Span::call_site(); 87,295 ( 0.00%) let unexpected = Rc::new(Cell::new(Unexpected::None)); 25,675 ( 0.00%) let buffer = crate::parse::new_parse_buffer(scope, cursor, unexpected); 15,405 ( 0.00%) peek(&buffer) 35,945 ( 0.00%) } . . macro_rules! impl_token { . ($display:tt $name:ty) => { . #[cfg(feature = "parsing")] . impl Token for $name { 15,405 ( 0.00%) fn peek(cursor: Cursor) -> bool { 15,405 ( 0.00%) fn peek(input: ParseStream) -> bool { 35,945 ( 0.00%) <$name as Parse>::parse(input).is_ok() 35,945 ( 0.00%) } 15,405 ( 0.00%) peek_impl(cursor, peek) 20,540 ( 0.00%) } . . fn display() -> &'static str { . $display 2,280 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl private::Sealed for $name {} . }; . } . . impl_token!("lifetime" Lifetime); -- line 186 ---------------------------------------- -- line 224 ---------------------------------------- . fn display() -> &'static str; . } . . #[cfg(feature = "parsing")] . impl private::Sealed for T {} . . #[cfg(feature = "parsing")] . impl Token for T { 678 ( 0.00%) fn peek(cursor: Cursor) -> bool { 452 ( 0.00%) ::peek(cursor) 904 ( 0.00%) } . . fn display() -> &'static str { . ::display() . } . } . . macro_rules! define_keywords { . ($($token:tt pub struct $name:ident #[$doc:meta])*) => { -- line 242 ---------------------------------------- -- line 303 ---------------------------------------- . #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] . impl Hash for $name { . fn hash(&self, _state: &mut H) {} . } . . #[cfg(feature = "printing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] . impl ToTokens for $name { 7,036 ( 0.00%) fn to_tokens(&self, tokens: &mut TokenStream) { 10,554 ( 0.00%) printing::keyword($token, self.span, tokens); 3,518 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] . impl Parse for $name { 5,896 ( 0.00%) fn parse(input: ParseStream) -> Result { 6,890 ( 0.00%) Ok($name { 21,884 ( 0.00%) span: parsing::keyword(input, $token)?, . }) 4,422 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl Token for $name { 205,533 ( 0.00%) fn peek(cursor: Cursor) -> bool { 274,044 ( 0.01%) parsing::peek_keyword(cursor, $token) 274,044 ( 0.01%) } . . fn display() -> &'static str { . concat!("`", $token, "`") 15,216 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl private::Sealed for $name {} . )* . }; . } . . macro_rules! impl_deref_if_len_is_1 { . ($name:ident/1) => { . impl Deref for $name { . type Target = WithSpan; . 324 ( 0.00%) fn deref(&self) -> &Self::Target { . unsafe { &*(self as *const Self as *const WithSpan) } 216 ( 0.00%) } . } . . impl DerefMut for $name { . fn deref_mut(&mut self) -> &mut Self::Target { . unsafe { &mut *(self as *mut Self as *mut WithSpan) } . } . } . }; -- line 358 ---------------------------------------- -- line 371 ---------------------------------------- . /// . /// [`Token!`]: crate::token . pub struct $name { . pub spans: [Span; $len], . } . . #[doc(hidden)] . #[allow(non_snake_case)] 396 ( 0.00%) pub fn $name>(spans: S) -> $name { 198 ( 0.00%) $name { 693 ( 0.00%) spans: spans.into_spans(), . } 297 ( 0.00%) } . . impl std::default::Default for $name { 10 ( 0.00%) fn default() -> Self { 20 ( 0.00%) $name { 90 ( 0.00%) spans: [Span::call_site(); $len], . } 30 ( 0.00%) } . } . . #[cfg(feature = "clone-impls")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] . impl Copy for $name {} . . #[cfg(feature = "clone-impls")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] . impl Clone for $name { 1,020 ( 0.00%) fn clone(&self) -> Self { 1,020 ( 0.00%) *self 1,530 ( 0.00%) } . } . . #[cfg(feature = "extra-traits")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] . impl Debug for $name { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . f.write_str(stringify!($name)) . } -- line 410 ---------------------------------------- -- line 438 ---------------------------------------- . $( . define_punctuation_structs! { . $token pub struct $name/$len #[$doc] . } . . #[cfg(feature = "printing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] . impl ToTokens for $name { 37,540 ( 0.00%) fn to_tokens(&self, tokens: &mut TokenStream) { 30,032 ( 0.00%) printing::punct($token, &self.spans, tokens); 15,016 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] . impl Parse for $name { 21,468 ( 0.00%) fn parse(input: ParseStream) -> Result { 26,835 ( 0.00%) Ok($name { 75,138 ( 0.00%) spans: parsing::punct(input, $token)?, . }) 16,101 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl Token for $name { 423,759 ( 0.01%) fn peek(cursor: Cursor) -> bool { 565,012 ( 0.01%) parsing::peek_punct(cursor, $token) 565,012 ( 0.01%) } . . fn display() -> &'static str { . concat!("`", $token, "`") 6,246 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl private::Sealed for $name {} . )* . }; . } . -- line 477 ---------------------------------------- -- line 480 ---------------------------------------- . $( . #[$doc] . pub struct $name { . pub span: Span, . } . . #[doc(hidden)] . #[allow(non_snake_case)] 7,548 ( 0.00%) pub fn $name>(span: S) -> $name { 3,774 ( 0.00%) $name { 16,983 ( 0.00%) span: span.into_spans()[0], . } 5,661 ( 0.00%) } . . impl std::default::Default for $name { . fn default() -> Self { . $name { . span: Span::call_site(), . } . } . } -- line 500 ---------------------------------------- -- line 501 ---------------------------------------- . . #[cfg(feature = "clone-impls")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] . impl Copy for $name {} . . #[cfg(feature = "clone-impls")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] . impl Clone for $name { 36 ( 0.00%) fn clone(&self) -> Self { 36 ( 0.00%) *self 54 ( 0.00%) } . } . . #[cfg(feature = "extra-traits")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] . impl Debug for $name { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . f.write_str(stringify!($name)) . } -- line 519 ---------------------------------------- -- line 534 ---------------------------------------- . #[cfg(feature = "extra-traits")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] . impl Hash for $name { . fn hash(&self, _state: &mut H) {} . } . . impl $name { . #[cfg(feature = "printing")] 14,688 ( 0.00%) pub fn surround(&self, tokens: &mut TokenStream, f: F) . where . F: FnOnce(&mut TokenStream), . { 14,688 ( 0.00%) printing::delim($token, self.span, tokens, f); 4,896 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl private::Sealed for $name {} . )* . }; . } . . define_punctuation_structs! { . "_" pub struct Underscore/1 /// `_` . } . . #[cfg(feature = "printing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] . impl ToTokens for Underscore { 432 ( 0.00%) fn to_tokens(&self, tokens: &mut TokenStream) { 1,188 ( 0.00%) tokens.append(Ident::new("_", self.span)); 216 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] . impl Parse for Underscore { 396 ( 0.00%) fn parse(input: ParseStream) -> Result { 693 ( 0.00%) input.step(|cursor| { 2,772 ( 0.00%) if let Some((ident, rest)) = cursor.ident() { 792 ( 0.00%) if ident == "_" { 2,673 ( 0.00%) return Ok((Underscore(ident.span()), rest)); . } 396 ( 0.00%) } . if let Some((punct, rest)) = cursor.punct() { . if punct.as_char() == '_' { . return Ok((Underscore(punct.span()), rest)); . } . } . Err(cursor.error("expected `_`")) 198 ( 0.00%) }) 198 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl Token for Underscore { 5,523 ( 0.00%) fn peek(cursor: Cursor) -> bool { 15,770 ( 0.00%) if let Some((ident, _rest)) = cursor.ident() { 6,304 ( 0.00%) return ident == "_"; 2,366 ( 0.00%) } 10 ( 0.00%) if let Some((punct, _rest)) = cursor.punct() { . return punct.as_char() == '_'; . } 1 ( 0.00%) false 3,945 ( 0.00%) } . . fn display() -> &'static str { . "`_`" 2,067 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl private::Sealed for Underscore {} . . #[cfg(feature = "parsing")] . impl Token for Paren { 23,154 ( 0.00%) fn peek(cursor: Cursor) -> bool { 30,872 ( 0.00%) lookahead::is_delimiter(cursor, Delimiter::Parenthesis) 30,872 ( 0.00%) } . . fn display() -> &'static str { . "parentheses" 2,571 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl Token for Brace { 10,794 ( 0.00%) fn peek(cursor: Cursor) -> bool { 14,392 ( 0.00%) lookahead::is_delimiter(cursor, Delimiter::Brace) 14,392 ( 0.00%) } . . fn display() -> &'static str { . "curly braces" . } . } . . #[cfg(feature = "parsing")] . impl Token for Bracket { 8,337 ( 0.00%) fn peek(cursor: Cursor) -> bool { 11,116 ( 0.00%) lookahead::is_delimiter(cursor, Delimiter::Bracket) 11,116 ( 0.00%) } . . fn display() -> &'static str { . "square brackets" 447 ( 0.00%) } . } . . #[cfg(feature = "parsing")] . impl Token for Group { 20,658 ( 0.00%) fn peek(cursor: Cursor) -> bool { 27,544 ( 0.00%) lookahead::is_delimiter(cursor, Delimiter::None) 27,544 ( 0.00%) } . . fn display() -> &'static str { . "invisible group" . } . } . . define_keywords! { . "abstract" pub struct Abstract /// `abstract` -- line 653 ---------------------------------------- -- line 888 ---------------------------------------- . #[cfg(feature = "parsing")] . pub mod parsing { . use crate::buffer::Cursor; . use crate::error::{Error, Result}; . use crate::parse::ParseStream; . use crate::span::FromSpans; . use proc_macro2::{Spacing, Span}; . 8,844 ( 0.00%) pub fn keyword(input: ParseStream, token: &str) -> Result { 17,688 ( 0.00%) input.step(|cursor| { 41,272 ( 0.00%) if let Some((ident, rest)) = cursor.ident() { 10,414 ( 0.00%) if ident == token { 26,182 ( 0.00%) return Ok((ident.span(), rest)); . } 6,856 ( 0.00%) } 3,744 ( 0.00%) Err(cursor.error(format!("expected `{}`", token))) 3,044 ( 0.00%) }) 2,948 ( 0.00%) } . 548,088 ( 0.01%) pub fn peek_keyword(cursor: Cursor, token: &str) -> bool { 1,472,485 ( 0.03%) if let Some((ident, _rest)) = cursor.ident() { 472,984 ( 0.01%) ident == token 177,369 ( 0.00%) } else { 9,388 ( 0.00%) false . } 1,086,788 ( 0.02%) } . 59,037 ( 0.00%) pub fn punct(input: ParseStream, token: &str) -> Result { 48,303 ( 0.00%) let mut spans = [input.span(); 3]; 59,037 ( 0.00%) punct_helper(input, token, &mut spans)?; 53,670 ( 0.00%) Ok(S::from_spans(&spans)) 16,101 ( 0.00%) } . 37,569 ( 0.00%) fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> { 91,239 ( 0.00%) input.step(|cursor| { 26,835 ( 0.00%) let mut cursor = *cursor; 48,303 ( 0.00%) assert!(token.len() <= spans.len()); . 209,353 ( 0.00%) for (i, ch) in token.chars().enumerate() { 71,489 ( 0.00%) match cursor.punct() { 64,990 ( 0.00%) Some((punct, rest)) => { 77,988 ( 0.00%) spans[i] = punct.span(); 38,994 ( 0.00%) if punct.as_char() != ch { . break; 72,621 ( 0.00%) } else if i == token.len() - 1 { 37,569 ( 0.00%) return Ok(((), rest)); 13,584 ( 0.00%) } else if punct.spacing() != Spacing::Joint { . break; . } 2,264 ( 0.00%) cursor = rest; . } . None => break, . } . } . . Err(Error::new(spans[0], format!("expected `{}`", token))) 10,734 ( 0.00%) }) 10,734 ( 0.00%) } . 1,836,289 ( 0.04%) pub fn peek_punct(mut cursor: Cursor, token: &str) -> bool { 4,551,161 ( 0.10%) for (i, ch) in token.chars().enumerate() { 1,399,370 ( 0.03%) match cursor.punct() { 566,890 ( 0.01%) Some((punct, rest)) => { 283,445 ( 0.01%) if punct.as_char() != ch { . break; 72,361 ( 0.00%) } else if i == token.len() - 1 { 4,639 ( 0.00%) return true; 35,306 ( 0.00%) } else if punct.spacing() != Spacing::Joint { . break; . } 3,270 ( 0.00%) cursor = rest; . } . None => break, . } . } 136,614 ( 0.00%) false 842,879 ( 0.02%) } . } . . // Not public API. . #[doc(hidden)] . #[cfg(feature = "printing")] . pub mod printing { . use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream}; . use quote::TokenStreamExt; . 82,588 ( 0.00%) pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) { 142,652 ( 0.00%) assert_eq!(s.len(), spans.len()); . 30,032 ( 0.00%) let mut chars = s.chars(); 30,032 ( 0.00%) let mut spans = spans.iter(); 52,556 ( 0.00%) let ch = chars.next_back().unwrap(); 52,556 ( 0.00%) let span = spans.next_back().unwrap(); 195,090 ( 0.00%) for (ch, span) in chars.zip(spans) { 14,498 ( 0.00%) let mut op = Punct::new(ch, Spacing::Joint); 6,590 ( 0.00%) op.set_span(*span); 13,180 ( 0.00%) tokens.append(op); . } . 90,096 ( 0.00%) let mut op = Punct::new(ch, Spacing::Alone); 37,540 ( 0.00%) op.set_span(*span); 67,572 ( 0.00%) tokens.append(op); 15,016 ( 0.00%) } . 19,349 ( 0.00%) pub fn keyword(s: &str, span: Span, tokens: &mut TokenStream) { 12,313 ( 0.00%) tokens.append(Ident::new(s, span)); 3,518 ( 0.00%) } . 24,480 ( 0.00%) pub fn delim(s: &str, span: Span, tokens: &mut TokenStream, f: F) . where . F: FnOnce(&mut TokenStream), . { 9,792 ( 0.00%) let delim = match s { 24,480 ( 0.00%) "(" => Delimiter::Parenthesis, 9,211 ( 0.00%) "[" => Delimiter::Bracket, 7,821 ( 0.00%) "{" => Delimiter::Brace, . " " => Delimiter::None, . _ => panic!("unknown delimiter: {}", s), . }; 9,792 ( 0.00%) let mut inner = TokenStream::new(); 17,136 ( 0.00%) f(&mut inner); 34,272 ( 0.00%) let mut g = Group::new(delim, inner); 17,136 ( 0.00%) g.set_span(span); 26,928 ( 0.00%) tokens.append(g); 9,792 ( 0.00%) } . } 1,247,279 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.86/src/buffer.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . // NOTE: Do not implement clone on this - there are raw pointers inside . // these entries which will be messed up. Moving the `TokenBuffer` itself is . // safe as the data pointed to won't be moved. . ptr: *const Entry, . len: usize, . } . . impl Drop for TokenBuffer { 6,597 ( 0.00%) fn drop(&mut self) { . unsafe { 15,393 ( 0.00%) let slice = slice::from_raw_parts_mut(self.ptr as *mut Entry, self.len); 13,194 ( 0.00%) let _ = Box::from_raw(slice); . } 4,398 ( 0.00%) } . } . . impl TokenBuffer { . // NOTE: Do not mutate the Vec returned from this function once it returns; . // the address of its backing memory must remain stable. 8,796 ( 0.00%) fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer { . // Build up the entries list, recording the locations of any Groups . // in the list to be processed later. 28,587 ( 0.00%) let mut entries = Vec::new(); 10,995 ( 0.00%) let mut groups = Vec::new(); 377,579 ( 0.01%) for tt in stream { 32,338 ( 0.00%) match tt { 43,860 ( 0.00%) TokenTree::Ident(sym) => { 138,890 ( 0.00%) entries.push(Entry::Ident(sym)); . } 26,956 ( 0.00%) TokenTree::Punct(op) => { 101,085 ( 0.00%) entries.push(Entry::Punct(op)); . } 620 ( 0.00%) TokenTree::Literal(l) => { 2,325 ( 0.00%) entries.push(Entry::Literal(l)); . } 13,755 ( 0.00%) TokenTree::Group(g) => { . // Record the index of the interesting entry, and store an . // `End(null)` there temporarily. 47,160 ( 0.00%) groups.push((entries.len(), g)); 13,755 ( 0.00%) entries.push(Entry::End(ptr::null())); 3,930 ( 0.00%) } . } . } . // Add an `End` entry to the end with a reference to the enclosing token . // stream which was passed in. 15,393 ( 0.00%) entries.push(Entry::End(up)); . . // NOTE: This is done to ensure that we don't accidentally modify the . // length of the backing buffer. The backing buffer must remain at a . // constant address after this point, as we are going to store a raw . // pointer into it. 41,781 ( 0.00%) let mut entries = entries.into_boxed_slice(); 117,762 ( 0.00%) for (idx, group) in groups { . // We know that this index refers to one of the temporary . // `End(null)` entries, and we know that the last entry is . // `End(up)`, so the next index is also valid. 21,615 ( 0.00%) let group_up = unsafe { entries.as_ptr().add(idx + 1) }; . . // The end entry stored at the end of this Entry::Group should . // point to the Entry which follows the Group in the list. 21,615 ( 0.00%) let inner = Self::inner_new(group.stream(), group_up); 66,810 ( 0.00%) entries[idx] = Entry::Group(group, inner); 1,965 ( 0.00%) } . 10,995 ( 0.00%) let len = entries.len(); 19,791 ( 0.00%) let ptr = Box::into_raw(entries); 4,398 ( 0.00%) TokenBuffer { . ptr: ptr as *const Entry, . len, . } 17,592 ( 0.00%) } . . /// Creates a `TokenBuffer` containing all the tokens from the input . /// `proc_macro::TokenStream`. . /// . /// *This method is available only if Syn is built with both the `"parsing"` and . /// `"proc-macro"` features.* . #[cfg(all( . not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), -- line 118 ---------------------------------------- -- line 119 ---------------------------------------- . feature = "proc-macro" . ))] . pub fn new(stream: pm::TokenStream) -> Self { . Self::new2(stream.into()) . } . . /// Creates a `TokenBuffer` containing all the tokens from the input . /// `proc_macro2::TokenStream`. 468 ( 0.00%) pub fn new2(stream: TokenStream) -> Self { 3,276 ( 0.00%) Self::inner_new(stream, ptr::null()) 468 ( 0.00%) } . . /// Creates a cursor referencing the first token in the buffer and able to . /// traverse until the end of the buffer. 7,310 ( 0.00%) pub fn begin(&self) -> Cursor { 51,170 ( 0.00%) unsafe { Cursor::create(self.ptr, self.ptr.add(self.len - 1)) } 7,310 ( 0.00%) } . } . . /// A cheaply copyable cursor into a `TokenBuffer`. . /// . /// This cursor holds a shared reference into the immutable data which is used . /// internally to represent a `TokenStream`, and can be efficiently manipulated . /// and copied around. . /// -- line 143 ---------------------------------------- -- line 156 ---------------------------------------- . scope: *const Entry, . // Cursor is covariant in 'a. This field ensures that our pointers are still . // valid. . marker: PhantomData<&'a Entry>, . } . . impl<'a> Cursor<'a> { . /// Creates a cursor referencing a static empty TokenStream. 115 ( 0.00%) pub fn empty() -> Self { . // It's safe in this situation for us to put an `Entry` object in global . // storage, despite it not actually being safe to send across threads . // (`Ident` is a reference into a thread-local table). This is because . // this entry never includes a `Ident` object. . // . // This wrapper struct allows us to break the rules and put a `Sync` . // object in global storage. . struct UnsafeSyncEntry(Entry); . unsafe impl Sync for UnsafeSyncEntry {} . static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry)); . 345 ( 0.00%) Cursor { . ptr: &EMPTY_ENTRY.0, . scope: &EMPTY_ENTRY.0, . marker: PhantomData, . } 460 ( 0.00%) } . . /// This create method intelligently exits non-explicitly-entered . /// `None`-delimited scopes when the cursor reaches the end of them, . /// allowing for them to be treated transparently. 609,648 ( 0.01%) unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self { . // NOTE: If we're looking at a `End(..)`, we want to advance the cursor . // past it, unless `ptr == scope`, which means that we're at the edge of . // our cursor's scope. We should only have `ptr != scope` at the exit . // from None-delimited groups entered with `ignore_none`. 690,692 ( 0.01%) while let Entry::End(exit) = *ptr { 40,522 ( 0.00%) if ptr == scope { . break; . } . ptr = exit; . } . 304,824 ( 0.01%) Cursor { 152,412 ( 0.00%) ptr, . scope, . marker: PhantomData, . } 609,648 ( 0.01%) } . . /// Get the current entry. 2,406,744 ( 0.05%) fn entry(self) -> &'a Entry { . unsafe { &*self.ptr } 1,203,372 ( 0.03%) } . . /// Bump the cursor to point at the next token after the current one. This . /// is undefined behavior if the cursor is currently looking at an . /// `Entry::End`. 892,542 ( 0.02%) unsafe fn bump(self) -> Cursor<'a> { 446,271 ( 0.01%) Cursor::create(self.ptr.offset(1), self.scope) 297,514 ( 0.01%) } . . /// While the cursor is looking at a `None`-delimited group, move it to look . /// at the first token inside instead. If the group is empty, this will move . /// the cursor past the `None`-delimited group. . /// . /// WARNING: This mutates its argument. 1,052,860 ( 0.02%) fn ignore_none(&mut self) { 1,995,721 ( 0.04%) while let Entry::Group(group, buf) = self.entry() { 255,360 ( 0.01%) if group.delimiter() == Delimiter::None { . // NOTE: We call `Cursor::create` here to make sure that . // situations where we should immediately exit the span after . // entering it are handled correctly. . unsafe { . *self = Cursor::create(buf.ptr, self.scope); . } . } else { . break; . } . } 526,430 ( 0.01%) } . . /// Checks whether the cursor is currently pointing at the end of its valid . /// scope. 177,543 ( 0.00%) pub fn eof(self) -> bool { . // We're at eof if we're at the end of our scope. 118,362 ( 0.00%) self.ptr == self.scope 236,724 ( 0.01%) } . . /// If the cursor is pointing at a `Group` with the given delimiter, returns . /// a cursor into that group and one pointing to the next `TokenTree`. 298,466 ( 0.01%) pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> { . // If we're not trying to enter a none-delimited group, we want to . // ignore them. We have to make sure to _not_ ignore them when we want . // to enter them, of course. For obvious reasons. 282,527 ( 0.01%) if delim != Delimiter::None { 47,817 ( 0.00%) self.ignore_none(); . } . 387,528 ( 0.01%) if let Entry::Group(group, buf) = self.entry() { 62,899 ( 0.00%) if group.delimiter() == delim { 82,104 ( 0.00%) return Some((buf.begin(), group.span(), unsafe { self.bump() })); . } . } . 39,217 ( 0.00%) None 124,493 ( 0.00%) } . . /// If the cursor is pointing at a `Ident`, returns it along with a cursor . /// pointing at the next `TokenTree`. 443,135 ( 0.01%) pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> { 177,254 ( 0.00%) self.ignore_none(); 620,389 ( 0.01%) match self.entry() { 1,886,976 ( 0.04%) Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump() })), 10,003 ( 0.00%) _ => None, . } 177,254 ( 0.00%) } . . /// If the cursor is pointing at a `Punct`, returns it along with a cursor . /// pointing at the next `TokenTree`. 766,650 ( 0.02%) pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> { 306,660 ( 0.01%) self.ignore_none(); 1,073,310 ( 0.02%) match self.entry() { 2,406,008 ( 0.05%) Entry::Punct(op) if op.as_char() != '\'' => Some((op.clone(), unsafe { self.bump() })), 180,028 ( 0.00%) _ => None, . } 306,660 ( 0.01%) } . . /// If the cursor is pointing at a `Literal`, return it along with a cursor . /// pointing at the next `TokenTree`. 21,690 ( 0.00%) pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> { 8,676 ( 0.00%) self.ignore_none(); 30,366 ( 0.00%) match self.entry() { 3,950 ( 0.00%) Entry::Literal(lit) => Some((lit.clone(), unsafe { self.bump() })), 4,180 ( 0.00%) _ => None, . } 8,676 ( 0.00%) } . . /// If the cursor is pointing at a `Lifetime`, returns it along with a . /// cursor pointing at the next `TokenTree`. 4,905 ( 0.00%) pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> { 1,962 ( 0.00%) self.ignore_none(); 6,867 ( 0.00%) match self.entry() { 180 ( 0.00%) Entry::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => { . let next = unsafe { self.bump() }; . match next.ident() { . Some((ident, rest)) => { . let lifetime = Lifetime { . apostrophe: op.span(), . ident, . }; . Some((lifetime, rest)) . } . None => None, . } . } 1,962 ( 0.00%) _ => None, . } 1,962 ( 0.00%) } . . /// Copies all remaining tokens visible from this cursor into a . /// `TokenStream`. 805 ( 0.00%) pub fn token_stream(self) -> TokenStream { 460 ( 0.00%) let mut tts = Vec::new(); 230 ( 0.00%) let mut cursor = self; 6,289 ( 0.00%) while let Some((tt, rest)) = cursor.token_tree() { 1,672 ( 0.00%) tts.push(tt); 304 ( 0.00%) cursor = rest; . } 1,610 ( 0.00%) tts.into_iter().collect() 345 ( 0.00%) } . . /// If the cursor is pointing at a `TokenTree`, returns it along with a . /// cursor pointing at the next `TokenTree`. . /// . /// Returns `None` if the cursor has reached the end of its stream. . /// . /// This method does not treat `None`-delimited groups as transparent, and . /// will return a `Group(None, ..)` if the cursor is looking at one. 3,410 ( 0.00%) pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> { 1,240 ( 0.00%) let tree = match self.entry() { 387 ( 0.00%) Entry::Group(group, _) => group.clone().into(), 608 ( 0.00%) Entry::Literal(lit) => lit.clone().into(), . Entry::Ident(ident) => ident.clone().into(), 1,368 ( 0.00%) Entry::Punct(op) => op.clone().into(), 115 ( 0.00%) Entry::End(..) => return None, . }; . 4,290 ( 0.00%) Some((tree, unsafe { self.bump() })) 815 ( 0.00%) } . . /// Returns the `Span` of the current token, or `Span::call_site()` if this . /// cursor points to eof. 90,885 ( 0.00%) pub fn span(self) -> Span { 121,180 ( 0.00%) match self.entry() { 8,365 ( 0.00%) Entry::Group(group, _) => group.span(), 721 ( 0.00%) Entry::Literal(l) => l.span(), 138,810 ( 0.00%) Entry::Ident(t) => t.span(), 64,169 ( 0.00%) Entry::Punct(o) => o.span(), . Entry::End(..) => Span::call_site(), . } 90,885 ( 0.00%) } . . /// Skip over the next token without cloning it. Returns `None` if this . /// cursor points to eof. . /// . /// This method treats `'lifetimes` as a single token. 33,473 ( 0.00%) pub(crate) fn skip(self) -> Option> { 20,966 ( 0.00%) match self.entry() { . Entry::End(..) => None, . . // Treat lifetimes as a single tt for the purposes of 'skip'. 23,660 ( 0.00%) Entry::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => { . let next = unsafe { self.bump() }; . match next.entry() { . Entry::Ident(_) => Some(unsafe { next.bump() }), . _ => Some(next), . } . } 24,344 ( 0.00%) _ => Some(unsafe { self.bump() }), . } 6,086 ( 0.00%) } . } . . impl<'a> Copy for Cursor<'a> {} . . impl<'a> Clone for Cursor<'a> { . fn clone(&self) -> Self { . *self . } -- line 384 ---------------------------------------- -- line 393 ---------------------------------------- . *ptr == other.ptr && *scope == other.scope . } . } . . pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool { . a.scope == b.scope . } . 65,325 ( 0.00%) pub(crate) fn open_span_of_group(cursor: Cursor) -> Span { 65,325 ( 0.00%) match cursor.entry() { 5,047 ( 0.00%) Entry::Group(group, _) => group.span_open(), 49,376 ( 0.00%) _ => cursor.span(), . } 39,195 ( 0.00%) } . 9,220 ( 0.00%) pub(crate) fn close_span_of_group(cursor: Cursor) -> Span { 9,220 ( 0.00%) match cursor.entry() { 12,908 ( 0.00%) Entry::Group(group, _) => group.span_close(), . _ => cursor.span(), . } 5,532 ( 0.00%) } 2,454,973 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 2,129,587 ( 0.05%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 170,213 ( 0.00%) ctrl & 0x01 != 0 . } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize -- line 140 ---------------------------------------- -- line 143 ---------------------------------------- . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h2(hash: u64) -> u8 { . // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit . // value, some hash functions (such as FxHash) produce a usize result . // instead, which means that the top 32 bits are 0 on 32-bit platforms. . let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 44,823,253 ( 0.97%) let top7 = hash >> (hash_len * 8 - 7); . (top7 & 0x7f) as u8 // truncation . } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups -- line 159 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 319,026 ( 0.01%) self.stride += Group::WIDTH; 319,026 ( 0.01%) self.pos += self.stride; 271,312 ( 0.01%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 163,138 ( 0.00%) if cap < 8 { . // We don't bother with a table size of 2 buckets since that can only . // hold a single element. Instead we skip directly to a 4 bucket table . // which can hold 3 elements. 342,135 ( 0.01%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 78,852 ( 0.00%) let adjusted_cap = cap.checked_mul(8)? / 7; . . // Any overflows will have been caught by the checked_mul. Also, any . // rounding errors from the division above will be cleaned up by . // next_power_of_two (which can't overflow because of the previous division). . Some(adjusted_cap.next_power_of_two()) . } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] . fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 448,300 ( 0.01%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 93,752 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } . } . . /// Helper which allows the max calculation for ctrl_align to be statically computed for each T . /// while keeping the rest of `calculate_layout_for` independent of `T` . #[derive(Copy, Clone)] . struct TableLayout { . size: usize, -- line 233 ---------------------------------------- -- line 246 ---------------------------------------- . . #[inline] . fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . . let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 318,685 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 435,784 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 1,536 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 894 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 635 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 12,182 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 527 ---------------------------------------- . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); . Bucket::from_base_index(self.data_end(), index) . } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 28,866 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 28,866 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 57,732 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 14,026 ( 0.00%) self.erase_no_drop(&item); . item.drop(); . } . . /// Finds and erases an element from the table, dropping it in place. . /// Returns true if an element was found. . #[cfg(feature = "raw")] . #[cfg_attr(feature = "inline-more", inline)] . pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool { -- line 554 ---------------------------------------- -- line 563 ---------------------------------------- . } . } . . /// Removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { 43,706 ( 0.00%) self.erase_no_drop(&item); 88 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 794,656 ( 0.02%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 2,870 ( 0.00%) match self.find(hash, eq) { 7,931 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 134,946 ( 0.00%) None => None, . } 1,069,965 ( 0.02%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 7 ( 0.00%) unsafe fn drop_elements(&mut self) { 18,376 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { . for item in self.iter() { . item.drop(); . } . } 8 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 642 ---------------------------------------- . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 460,261 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 284,577 ( 0.01%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 653,333 ( 0.01%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { . self.table.reserve_rehash_inner( . additional, -- line 687 ---------------------------------------- -- line 690 ---------------------------------------- . TableLayout::new::(), . if mem::needs_drop::() { . Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 458,544 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 2,917,686 ( 0.06%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 6,875 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 2,055,013 ( 0.04%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 2,151,506 ( 0.05%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 848,536 ( 0.02%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 211 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 636,402 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 2,446 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 481,279 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 12,958 ( 0.00%) let bucket = self.table.bucket(index); . . // If we are replacing a DELETED entry then we don't need to update . // the load counter. 1,000,026 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 784,351 ( 0.02%) self.table.items += 1; . bucket 4,851 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 813 ---------------------------------------- . true . } else { . false . } . } . . /// Searches for an element in the table. . #[inline] 26,746 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 10,126 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 24,263 ( 0.00%) eq(self.bucket(index).as_ref()) 3,325 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 1,124 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 29,880 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 22,034 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] 2,856 ( 0.00%) pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 14,978 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 3,264 ( 0.00%) } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. . /// . /// At most one mutable reference will be returned to any entry. `None` will be returned if any . /// of the hashes are duplicates. `None` will be returned if the hash is not found. . /// -- line 859 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 961,881 ( 0.02%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . -- line 936 ---------------------------------------- -- line 938 ---------------------------------------- . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { . let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 111,645 ( 0.00%) items: self.table.items, . } . } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. -- line 954 ---------------------------------------- -- line 995 ---------------------------------------- . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 7,780 ( 0.00%) let allocation = self.into_allocation(); 5,835 ( 0.00%) RawIntoIter { 9,725 ( 0.00%) iter, . allocation, . marker: PhantomData, . alloc, . } . } . . /// Converts the table into a raw allocation. The contents of the table . /// should be dropped using a `RawIter` before freeing the allocation. . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 3,492 ( 0.00%) let alloc = if self.table.is_empty_singleton() { . None . } else { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match calculate_layout::(self.table.buckets()) { . Some(lco) => lco, . None => unsafe { hint::unreachable_unchecked() }, . }; . Some(( 603 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1042 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 915,289 ( 0.02%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 556,223 ( 0.01%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 131,888 ( 0.00%) let ptr: NonNull = match do_alloc(&alloc, layout) { . Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . . let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 307,986 ( 0.01%) Ok(Self { . ctrl, 133,027 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 405,036 ( 0.01%) } . . #[inline] 33,274 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 8,620 ( 0.00%) if capacity == 0 { 7,431 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 252,375 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 16,469 ( 0.00%) Ok(result) . } . } 33,274 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element and sets the hash for that slot. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] 167,799 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 167,799 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 335,598 ( 0.01%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 1,394,567 ( 0.03%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 4,072,084 ( 0.09%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 1,870,548 ( 0.04%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 118,628 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 4,525,249 ( 0.10%) for bit in group.match_byte(h2_hash) { 9,024,226 ( 0.20%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 5,817,089 ( 0.13%) if likely(eq(index)) { . return Some(index); . } . } . 1,315,577 ( 0.03%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] -- line 1198 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 4,963,312 ( 0.11%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] . fn probe_seq(&self, hash: u64) -> ProbeSeq { . ProbeSeq { 25,274,615 ( 0.55%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } . } . . /// Returns the index of a bucket for which a value must be inserted if there is enough rooom . /// in the table, otherwise returns error . #[cfg(feature = "raw")] . #[inline] -- line 1257 ---------------------------------------- -- line 1263 ---------------------------------------- . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] . unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 2,569,961 ( 0.06%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 2,054,504 ( 0.04%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 3,914,229 ( 0.08%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 1,304,253 ( 0.03%) *self.ctrl(index) = ctrl; 1,304,678 ( 0.03%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 364,042 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 336,186 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 1,697,021 ( 0.04%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 3,492 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 176,494 ( 0.00%) new_table.growth_left -= self.items; . new_table.items = self.items; . . // The hash function may panic, in which case we simply free the new . // table without dropping any elements that may have been copied into . // it. . // . // This guard is also used to free the old table on success, see . // the comment at the bottom of this function. . Ok(guard(new_table, move |self_| { 79,981 ( 0.00%) if !self_.is_empty_singleton() { . self_.free_buckets(table_layout); . } . })) . } . . /// Reserves or rehashes to make room for `additional` more elements. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1383 ---------------------------------------- -- line 1388 ---------------------------------------- . &mut self, . additional: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . drop: Option, . ) -> Result<(), TryReserveError> { . // Avoid `Option::ok_or_else` because it bloats LLVM IR. 159,965 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 159,962 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 339,345 ( 0.01%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 79,981 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } . } . . /// Allocates a new table of a different size and moves the contents of the -- line 1418 ---------------------------------------- -- line 1424 ---------------------------------------- . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 8,722 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 772,665 ( 0.02%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 79,981 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1554 ---------------------------------------- . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 54,378 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); . } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 15,400 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 18,148 ( 0.00%) self.items = 0; 15,473 ( 0.00%) self.growth_left = bucket_mask_to_capacity(self.bucket_mask); . } . . #[inline] . unsafe fn erase(&mut self, index: usize) { . debug_assert!(is_full(*self.ctrl(index))); 136,432 ( 0.00%) let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask; . let empty_before = Group::load(self.ctrl(index_before)).match_empty(); . let empty_after = Group::load(self.ctrl(index)).match_empty(); . . // If we are inside a continuous block of Group::WIDTH full or deleted . // cells then a probe window may have seen a full block when trying to . // insert. We therefore need to keep that block non-empty so that . // lookups will continue searching to the next probe window. . // . // Note that in this context `leading_zeros` refers to the bytes at the . // end of a group, while `trailing_zeros` refers to the bytes at the . // beginning of a group. 545,728 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 670,055 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 545,728 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 2,400 ( 0.00%) fn clone(&self) -> Self { 428 ( 0.00%) if self.table.is_empty_singleton() { . Self::new_in(self.table.alloc.clone()) . } else { . unsafe { . let mut new_table = ManuallyDrop::new( . // Avoid `Result::ok_or_else` because it bloats LLVM IR. . match Self::new_uninitialized( . self.table.alloc.clone(), . self.table.buckets(), -- line 1615 ---------------------------------------- -- line 1624 ---------------------------------------- . // We need to free the memory allocated for the new table. . new_table.free_buckets(); . }); . . // Return the newly created table. . ManuallyDrop::into_inner(new_table) . } . } 2,700 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 254 ( 0.00%) self.table.growth_left = source.table.growth_left; . } . } . . impl RawTable { . /// Common code for clone and clone_from. Assumes `self.buckets() == source.buckets()`. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn clone_from_impl(&mut self, source: &Self, mut on_panic: impl FnMut(&mut Self)) { . // Copy the control bytes unchanged. We do this in a single pass -- line 1703 ---------------------------------------- -- line 1790 ---------------------------------------- . fn default() -> Self { . Self::new_in(Default::default()) . } . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] 837,516 ( 0.02%) fn drop(&mut self) { 733,906 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 892,136 ( 0.02%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 7,780 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 9,725 ( 0.00%) } . } . . /// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does . /// not track an item count. . pub(crate) struct RawIterRange { . // Mask of full buckets in the current group. Bits are cleared from this . // mask as each element is processed. . current_group: BitMask, -- line 1838 ---------------------------------------- -- line 1934 ---------------------------------------- . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option> { . unsafe { . loop { 267,933 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 41,170 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 63,844 ( 0.00%) return Some(self.data.next_n(index)); . } . 225,556 ( 0.00%) if self.next_ctrl >= self.end { . return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 6,805 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 5,659 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 14,001 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( -- line 1966 ---------------------------------------- -- line 2102 ---------------------------------------- . } . } else { . // We must have already iterated past the removed item. . } . } . } . . unsafe fn drop_elements(&mut self) { 1,445 ( 0.00%) if mem::needs_drop::() && self.len() != 0 { . for item in self { . item.drop(); . } . } . } . } . . impl Clone for RawIter { -- line 2118 ---------------------------------------- -- line 2124 ---------------------------------------- . } . } . } . . impl Iterator for RawIter { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 43,903 ( 0.00%) fn next(&mut self) -> Option> { 103,980 ( 0.00%) if let Some(b) = self.iter.next() { 391,740 ( 0.01%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); . None . } 87,806 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (self.items, Some(self.items)) . } . } . . impl ExactSizeIterator for RawIter {} -- line 2151 ---------------------------------------- -- line 2177 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] 2,806 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 16,550 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 294 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 1,616 ( 0.00%) fn next(&mut self) -> Option { 945 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 3,888 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 4 ( 0.00%) self.iter.size_hint() . } . } . . impl ExactSizeIterator for RawIntoIter {} . impl FusedIterator for RawIntoIter {} . . /// Iterator which consumes elements without freeing the table storage. . pub struct RawDrain<'a, T, A: Allocator + Clone = Global> { -- line 2231 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 848 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 106 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 848 ( 0.00%) } . } . . impl Iterator for RawDrain<'_, T, A> { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option { . unsafe { -- line 2289 ---------------------------------------- 13,868,864 ( 0.30%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . . /// An entity in the Rust type system, which can be one of . /// several kinds (types, lifetimes, and consts). . /// To reduce memory usage, a `GenericArg` is an interned pointer, . /// with the lowest 2 bits being reserved for a tag to . /// indicate the type (`Ty`, `Region`, or `Const`) it points to. . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct GenericArg<'tcx> { 480,432 ( 0.01%) ptr: NonZeroUsize, 1,454,290 ( 0.03%) marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>, . } . . const TAG_MASK: usize = 0b11; . const TYPE_TAG: usize = 0b00; . const REGION_TAG: usize = 0b01; . const CONST_TAG: usize = 0b10; . 67,665 ( 0.00%) #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] . pub enum GenericArgKind<'tcx> { . Lifetime(ty::Region<'tcx>), . Type(Ty<'tcx>), . Const(&'tcx ty::Const<'tcx>), . } . . impl<'tcx> GenericArgKind<'tcx> { 16,964 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 16,964 ( 0.00%) let (tag, ptr) = match self { . GenericArgKind::Lifetime(lt) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0); . (REGION_TAG, lt as *const _ as usize) . } . GenericArgKind::Type(ty) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0); -- line 56 ---------------------------------------- -- line 58 ---------------------------------------- . } . GenericArgKind::Const(ct) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0); . (CONST_TAG, ct as *const _ as usize) . } . }; . 153,332 ( 0.00%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 16,964 ( 0.00%) } . } . . impl<'tcx> fmt::Debug for GenericArg<'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.fmt(f), . GenericArgKind::Type(ty) => ty.fmt(f), . GenericArgKind::Const(ct) => ct.fmt(f), -- line 75 ---------------------------------------- -- line 85 ---------------------------------------- . . impl<'tcx> PartialOrd for GenericArg<'tcx> { . fn partial_cmp(&self, other: &GenericArg<'_>) -> Option { . Some(self.cmp(&other)) . } . } . . impl<'tcx> From> for GenericArg<'tcx> { 103,624 ( 0.00%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 103,624 ( 0.00%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 805,857 ( 0.02%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 805,857 ( 0.02%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { 587 ( 0.00%) fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() 587 ( 0.00%) } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 8,839,920 ( 0.19%) match ptr & TAG_MASK { 100,098 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 2,206,848 ( 0.05%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 2,083 ( 0.00%) CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)), . _ => intrinsics::unreachable(), . } . } . } . . /// Unpack the `GenericArg` as a type when it is known certainly to be a type. . /// This is true in cases where `Substs` is used in places where the kinds are known . /// to be limited (e.g. in tuples, where the only parameters are type parameters). . pub fn expect_ty(self) -> Ty<'tcx> { . match self.unpack() { . GenericArgKind::Type(ty) => ty, . _ => bug!("expected a type, but found another kind"), . } 28,786 ( 0.00%) } . . /// Unpack the `GenericArg` as a const when it is known certainly to be a const. . pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { . match self.unpack() { . GenericArgKind::Const(c) => c, . _ => bug!("expected a const, but found another kind"), . } . } -- line 140 ---------------------------------------- -- line 170 ---------------------------------------- . GenericArgKind::Type(ty) => ty.visit_with(visitor), . GenericArgKind::Const(ct) => ct.visit_with(visitor), . } . } . } . . impl<'tcx, E: TyEncoder<'tcx>> Encodable for GenericArg<'tcx> { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { 10,768 ( 0.00%) self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 84,820 ( 0.00%) fn decode(d: &mut D) -> GenericArg<'tcx> { 84,820 ( 0.00%) GenericArgKind::decode(d).pack() . } . } . . /// A substitution mapping generic parameters to new values. . pub type InternalSubsts<'tcx> = List>; . . pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; . . impl<'a, 'tcx> InternalSubsts<'tcx> { . /// Interpret these substitutions as the substitutions of a closure type. . /// Closure substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and closure kind; . /// see `ty::ClosureSubsts` struct for more comments. 4,708 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 4,708 ( 0.00%) } . . /// Interpret these substitutions as the substitutions of a generator type. . /// Generator substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and generator kind; . /// see `ty::GeneratorSubsts` struct for more comments. . pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { . GeneratorSubsts { substs: self } . } -- line 208 ---------------------------------------- -- line 211 ---------------------------------------- . /// Inline const substitutions have a particular structure controlled by the . /// compiler that encodes information like the inferred type; . /// see `ty::InlineConstSubsts` struct for more comments. . pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { . InlineConstSubsts { substs: self } . } . . /// Creates an `InternalSubsts` that maps each generic parameter to itself. 18,650 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 13,044 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 16,785 ( 0.00%) } . . /// Creates an `InternalSubsts` for generic parameter definitions, . /// by calling closures to obtain each kind. . /// The closures get to observe the `InternalSubsts` as they're . /// being built, which can be used to correctly . /// substitute defaults of generic parameters. 206,126 ( 0.00%) pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . let defs = tcx.generics_of(def_id); . let count = defs.count(); . let mut substs = SmallVec::with_capacity(count); 75,243 ( 0.00%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 45,362 ( 0.00%) tcx.intern_substs(&substs) 207,288 ( 0.00%) } . . pub fn extend_to(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . Self::for_item(tcx, def_id, |param, substs| { . self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) . }) . } . 272,575 ( 0.01%) pub fn fill_item( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . tcx: TyCtxt<'tcx>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { 111,425 ( 0.00%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 11,042 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 216,976 ( 0.00%) } . 216 ( 0.00%) pub fn fill_single( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . substs.reserve(defs.params.len()); . for param in &defs.params { 84 ( 0.00%) let kind = mk_kind(param, substs); 227,038 ( 0.00%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } 216 ( 0.00%) } . . #[inline] . pub fn types(&'a self) -> impl DoubleEndedIterator> + 'a { . self.iter() . .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) . } . . #[inline] -- line 284 ---------------------------------------- -- line 302 ---------------------------------------- . self.iter().filter_map(|k| match k.unpack() { . GenericArgKind::Lifetime(_) => None, . generic => Some(generic), . }) . } . . #[inline] . pub fn type_at(&self, i: usize) -> Ty<'tcx> { 254,151 ( 0.01%) if let GenericArgKind::Type(ty) = self[i].unpack() { . ty . } else { . bug!("expected type for param #{} in {:?}", i, self); . } . } . . #[inline] . pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { -- line 318 ---------------------------------------- -- line 350 ---------------------------------------- . /// impl X for U { fn f() {} } . /// ``` . /// . /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. . /// * If `source_ancestor` is the def_id of the trait. . /// * If `target_substs` is `[U]`, the substs for the impl. . /// * Then we will return `[U, T]`, the subst for `f` in the impl that . /// are needed for it to match the trait. 13,013 ( 0.00%) pub fn rebase_onto( . &self, . tcx: TyCtxt<'tcx>, . source_ancestor: DefId, . target_substs: SubstsRef<'tcx>, . ) -> SubstsRef<'tcx> { . let defs = tcx.generics_of(source_ancestor); 3,718 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 14,872 ( 0.00%) } . 640 ( 0.00%) pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { . tcx.mk_substs(self.iter().take(generics.count())) 1,280 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { 412,132 ( 0.01%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // The match arms are in order of frequency. The 1, 2, and 0 cases are . // typically hit in 90--99.99% of cases. When folding doesn't change . // the substs, it's faster to reuse the existing substs rather than . // calling `intern_substs`. 2,649,704 ( 0.06%) match self.len() { . 1 => { 430,789 ( 0.01%) let param0 = self[0].try_fold_with(folder)?; 1,184,830 ( 0.03%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 259,826 ( 0.01%) let param0 = self[0].try_fold_with(folder)?; 639,017 ( 0.01%) let param1 = self[1].try_fold_with(folder)?; 717,960 ( 0.02%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 336,923 ( 0.01%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 54,782 ( 0.00%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 4,160 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 9,184 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 506,831 ( 0.01%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 287,505 ( 0.01%) self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . /////////////////////////////////////////////////////////////////////////// . // Public trait `Subst` . // . // Just call `foo.subst(tcx, substs)` to perform a substitution across . // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when -- line 420 ---------------------------------------- -- line 435 ---------------------------------------- . . impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T { . fn subst_spanned( . self, . tcx: TyCtxt<'tcx>, . substs: &[GenericArg<'tcx>], . span: Option, . ) -> T { 839,984 ( 0.02%) let mut folder = SubstFolder { tcx, substs, span, binders_passed: 0 }; . self.fold_with(&mut folder) . } . } . . /////////////////////////////////////////////////////////////////////////// . // The actual substitution engine itself is a type folder. . . struct SubstFolder<'a, 'tcx> { -- line 451 ---------------------------------------- -- line 456 ---------------------------------------- . span: Option, . . /// Number of region binders we have passed through while doing the substitution . binders_passed: u32, . } . . impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 183,430 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 197,240 ( 0.00%) self.binders_passed += 1; 47,460 ( 0.00%) let t = t.super_fold_with(self); 197,240 ( 0.00%) self.binders_passed -= 1; . t . } . 246,894 ( 0.01%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . // Note: This routine only handles regions that are bound on . // type declarations and other outer declarations, not those . // bound in *fn types*. Region substitution of the bound . // regions that appear in a function signature is done using . // the specialized routine `ty::replace_late_regions()`. 82,298 ( 0.00%) match *r { 53,670 ( 0.00%) ty::ReEarlyBound(data) => { 53,670 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 26,835 ( 0.00%) Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), . _ => { . let span = self.span.unwrap_or(DUMMY_SP); . let msg = format!( . "Region parameter out of range \ . when substituting in region {} (index={})", . data.name, data.index . ); . span_bug!(span, "{}", msg); . } . } . } . _ => r, . } 288,043 ( 0.01%) } . 913,752 ( 0.02%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 304,584 ( 0.01%) if !t.needs_subst() { . return t; . } . 477,298 ( 0.01%) match *t.kind() { 693,050 ( 0.02%) ty::Param(p) => self.ty_for_param(p, t), 600,234 ( 0.01%) _ => t.super_fold_with(self), . } 1,022,725 ( 0.02%) } . 110,047 ( 0.00%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 34,707 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 135,612 ( 0.00%) c.super_fold_with(self) . } 5,224 ( 0.00%) } . . #[inline] . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } . . impl<'a, 'tcx> SubstFolder<'a, 'tcx> { . fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { . // Look up the type in the substitutions. It really should be in there. 277,220 ( 0.01%) let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ty = match opt_ty { . Some(GenericArgKind::Type(ty)) => ty, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected type for `{:?}` ({:?}/{}) but found {:?} \ . when substituting, substs={:?}", -- line 539 ---------------------------------------- -- line 562 ---------------------------------------- . } . . fn const_for_param( . &self, . p: ParamConst, . source_ct: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { . // Look up the const in the substitutions. It really should be in there. 1,306 ( 0.00%) let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ct = match opt_ct { . Some(GenericArgKind::Const(ct)) => ct, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected const for `{:?}` ({:?}/{}) but found {:?} \ . when substituting substs={:?}", -- line 578 ---------------------------------------- -- line 645 ---------------------------------------- . fn shift_vars_through_binders>(&self, val: T) -> T { . debug!( . "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", . val, . self.binders_passed, . val.has_escaping_bound_vars() . ); . 494,520 ( 0.01%) if self.binders_passed == 0 || !val.has_escaping_bound_vars() { . return val; . } . . let result = ty::fold::shift_vars(self.tcx(), val, self.binders_passed); . debug!("shift_vars: shifted result = {:?}", result); . . result . } . . fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { 59,683 ( 0.00%) if self.binders_passed == 0 || !region.has_escaping_bound_vars() { . return region; . } . ty::fold::shift_region(self.tcx, region, self.binders_passed) . } . } . . /// Stores the user-given substs to reach some fully qualified path . /// (e.g., `::Item` or `::Item`). . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 4,635 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSubsts<'tcx> { . /// The substitutions for the item as given by the user. . pub substs: SubstsRef<'tcx>, . . /// The self type, in the case of a `::Item` path (when applied . /// to an inherent impl). See `UserSelfTy` below. 1,044 ( 0.00%) pub user_self_ty: Option>, . } . . /// Specifies the user-given self type. In the case of a path that . /// refers to a member in an inherent impl, this self type is . /// sometimes needed to constrain the type parameters on the impl. For . /// example, in this code: . /// . /// ``` -- line 689 ---------------------------------------- -- line 696 ---------------------------------------- . /// self type `Foo`. Then we can instantiate the parameters of . /// the impl (with the substs from `UserSubsts`) and apply those to . /// the self type, giving `Foo`. Finally, we unify that with . /// the self type here, which contains `?A` to be `&'static u32` . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSelfTy<'tcx> { . pub impl_def_id: DefId, 489 ( 0.00%) pub self_ty: Ty<'tcx>, . } 3,651,429 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . . impl NodeRef { . /// Looks up a given key in a (sub)tree headed by the node, recursively. . /// Returns a `Found` with the handle of the matching KV, if any. Otherwise, . /// returns a `GoDown` with the handle of the leaf edge where the key belongs. . /// . /// The result is meaningful only if the tree is ordered by key, like the tree . /// in a `BTreeMap` is. 2,565,897 ( 0.06%) pub fn search_tree( . mut self, . key: &Q, . ) -> SearchResult . where . Q: Ord, . K: Borrow, . { . loop { . self = match self.search_node(key) { . Found(handle) => return Found(handle), 309,853 ( 0.01%) GoDown(handle) => match handle.force() { . Leaf(leaf) => return GoDown(leaf), . Internal(internal) => internal.descend(), . }, . } . } 1,045,645 ( 0.02%) } . . /// Descends to the nearest node where the edge matching the lower bound . /// of the range is different from the edge matching the upper bound, i.e., . /// the nearest node that has at least one key contained in the range. . /// . /// If found, returns an `Ok` with that node, the strictly ascending pair of . /// edge indices in the node delimiting the range, and the corresponding . /// pair of bounds for continuing the search in the child nodes, in case -- line 73 ---------------------------------------- -- line 202 ---------------------------------------- . unsafe fn find_key_index(&self, key: &Q, start_index: usize) -> IndexResult . where . Q: Ord, . K: Borrow, . { . let node = self.reborrow(); . let keys = node.keys(); . debug_assert!(start_index <= keys.len()); 4,472,395 ( 0.10%) for (offset, k) in unsafe { keys.get_unchecked(start_index..) }.iter().enumerate() { 20,226,378 ( 0.44%) match key.cmp(k.borrow()) { . Ordering::Greater => {} . Ordering::Equal => return IndexResult::KV(start_index + offset), . Ordering::Less => return IndexResult::Edge(start_index + offset), . } . } . IndexResult::Edge(keys.len()) . } . -- line 219 ---------------------------------------- 825,925 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs -------------------------------------------------------------------------------- Ir -- line 29 ---------------------------------------- . /// ``` . /// let s: &str = "Follow the rabbit"; . /// let ptr: *const u8 = s.as_ptr(); . /// assert!(!ptr.is_null()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")] . #[inline] 1,799,528 ( 0.04%) pub const fn is_null(self) -> bool { . // Compare via a cast to a thin pointer, so fat pointers are only . // considering their "data" part for null-ness. 1,799,528 ( 0.04%) (self as *const u8).guaranteed_eq(null()) 1,799,528 ( 0.04%) } . . /// Casts to a pointer of another type. . #[stable(feature = "ptr_cast", since = "1.38.0")] . #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")] . #[inline] 414,840 ( 0.01%) pub const fn cast(self) -> *const U { . self as _ 276,560 ( 0.01%) } . . /// Changes constness without changing the type. . /// . /// This is a bit safer than `as` because it wouldn't silently change the type if the code is . /// refactored. . #[unstable(feature = "ptr_const_cast", issue = "92675")] . #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")] . pub const fn as_mut(self) -> *mut T { -- line 57 ---------------------------------------- -- line 287 ---------------------------------------- . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const unsafe fn offset(self, count: isize) -> *const T . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. 8,477,481 ( 0.18%) unsafe { intrinsics::offset(self, count) } . } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 303 ---------------------------------------- -- line 436 ---------------------------------------- . /// // they point to the same address! . /// unsafe { . /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior . /// } . /// ``` . #[stable(feature = "ptr_offset_from", since = "1.47.0")] . #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")] . #[inline] 50,945 ( 0.00%) pub const unsafe fn offset_from(self, origin: *const T) -> isize . where . T: Sized, . { 10,189 ( 0.00%) let pointee_size = mem::size_of::(); 132,457 ( 0.00%) assert!(0 < pointee_size && pointee_size <= isize::MAX as usize); . // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`. 1,655,294 ( 0.04%) unsafe { intrinsics::ptr_offset_from(self, origin) } 20,378 ( 0.00%) } . . /// Returns whether two pointers are guaranteed to be equal. . /// . /// At runtime this function behaves like `self == other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine equality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be equal. . /// But when it returns `true`, the pointers are guaranteed to be equal. -- line 460 ---------------------------------------- -- line 470 ---------------------------------------- . /// affect the outcome, but just the performance. . /// The consequences of using this method to make runtime and compile-time code behave . /// differently have not been explored. This method should not be used to introduce such . /// differences, and it should also not be stabilized before we have a better understanding . /// of this issue. . #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[inline] 1,349,646 ( 0.03%) pub const fn guaranteed_eq(self, other: *const T) -> bool . where . T: Sized, . { 2,699,321 ( 0.06%) intrinsics::ptr_guaranteed_eq(self, other) 1,799,528 ( 0.04%) } . . /// Returns whether two pointers are guaranteed to be unequal. . /// . /// At runtime this function behaves like `self != other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine the inequality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be unequal. . /// But when it returns `true`, the pointers are guaranteed to be unequal. -- line 491 ---------------------------------------- -- line 569 ---------------------------------------- . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const unsafe fn add(self, count: usize) -> Self . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . unsafe { self.offset(count as isize) } 1,965 ( 0.00%) } . . /// Calculates the offset from a pointer (convenience for . /// `.offset((count as isize).wrapping_neg())`). . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 585 ---------------------------------------- -- line 886 ---------------------------------------- . /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`]. . /// . /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples. . /// . /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping() . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[inline] 1,100 ( 0.00%) pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize) . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`. 275 ( 0.00%) unsafe { copy_nonoverlapping(self, dest, count) } 550 ( 0.00%) } . . /// Computes the offset that needs to be applied to the pointer in order to make it aligned to . /// `align`. . /// . /// If it is not possible to align the pointer, the implementation returns . /// `usize::MAX`. It is permissible for the implementation to *always* . /// return `usize::MAX`. Only your algorithm's performance can depend . /// on getting a usable offset here, not its correctness. -- line 908 ---------------------------------------- -- line 983 ---------------------------------------- . /// use std::ptr; . /// . /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); . /// assert_eq!(slice.len(), 3); . /// ``` . #[inline] . #[unstable(feature = "slice_ptr_len", issue = "71146")] . #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")] 16,194 ( 0.00%) pub const fn len(self) -> usize { 10,796 ( 0.00%) metadata(self) 10,796 ( 0.00%) } . . /// Returns a raw pointer to the slice's buffer. . /// . /// This is equivalent to casting `self` to `*const T`, but more type-safe. . /// . /// # Examples . /// . /// ```rust -- line 1001 ---------------------------------------- -- line 1003 ---------------------------------------- . /// use std::ptr; . /// . /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); . /// assert_eq!(slice.as_ptr(), 0 as *const i8); . /// ``` . #[inline] . #[unstable(feature = "slice_ptr_get", issue = "74265")] . #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] 40,040 ( 0.00%) pub const fn as_ptr(self) -> *const T { . self as *const T 20,020 ( 0.00%) } . . /// Returns a raw pointer to an element or subslice, without doing bounds . /// checking. . /// . /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable . /// is *[undefined behavior]* even if the resulting pointer is not used. . /// . /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html -- line 1021 ---------------------------------------- 1,525,293 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . . pub(super) trait DecodeMut<'a, 's, S>: Sized { . fn decode(r: &mut Reader<'a>, s: &'s mut S) -> Self; . } . . macro_rules! rpc_encode_decode { . (le $ty:ty) => { . impl Encode for $ty { 2,792,243 ( 0.06%) fn encode(self, w: &mut Writer, _: &mut S) { 234 ( 0.00%) w.extend_from_array(&self.to_le_bytes()); 3,490,138 ( 0.08%) } . } . . impl DecodeMut<'_, '_, S> for $ty { 312 ( 0.00%) fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { . const N: usize = ::std::mem::size_of::<$ty>(); . 390 ( 0.00%) let mut bytes = [0; N]; 507,242 ( 0.01%) bytes.copy_from_slice(&r[..N]); 1,831,791 ( 0.04%) *r = &r[N..]; . 390 ( 0.00%) Self::from_le_bytes(bytes) 156 ( 0.00%) } . } . }; . (struct $name:ident { $($field:ident),* $(,)? }) => { . impl Encode for $name { . fn encode(self, w: &mut Writer, s: &mut S) { . $(self.$field.encode(w, s);)* . } . } -- line 51 ---------------------------------------- -- line 55 ---------------------------------------- . $name { . $($field: DecodeMut::decode(r, s)),* . } . } . } . }; . (enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => { . impl),+)?> Encode for $name $(<$($T),+>)? { 8,217,783 ( 0.18%) fn encode(self, w: &mut Writer, s: &mut S) { . // HACK(eddyb): `Tag` enum duplicated between the . // two impls as there's no other place to stash it. . #[allow(non_upper_case_globals)] . mod tag { . #[repr(u8)] enum Tag { $($variant),* } . . $(pub const $variant: u8 = Tag::$variant as u8;)* . } . 4,627,480 ( 0.10%) match self { 1,045,138 ( 0.02%) $($name::$variant $(($field))* => { 26,896 ( 0.00%) tag::$variant.encode(w, s); 1,031,710 ( 0.02%) $($field.encode(w, s);)* 78 ( 0.00%) })* . } 5,860,654 ( 0.13%) } . } . . impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> . for $name $(<$($T),+>)? . { 2,350,573 ( 0.05%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { . // HACK(eddyb): `Tag` enum duplicated between the . // two impls as there's no other place to stash it. . #[allow(non_upper_case_globals)] . mod tag { . #[repr(u8)] enum Tag { $($variant),* } . . $(pub const $variant: u8 = Tag::$variant as u8;)* . } . 1,980,868 ( 0.04%) match u8::decode(r, s) { . $(tag::$variant => { 80,561 ( 0.00%) $(let $field = DecodeMut::decode(r, s);)* 1,605,011 ( 0.03%) $name::$variant $(($field))* 40,222 ( 0.00%) })* . _ => unreachable!(), . } 3,994,666 ( 0.09%) } . } . } . } . . impl Encode for () { . fn encode(self, _: &mut Writer, _: &mut S) {} . } . . impl DecodeMut<'_, '_, S> for () { . fn decode(_: &mut Reader<'_>, _: &mut S) -> Self {} . } . . impl Encode for u8 { 131,613 ( 0.00%) fn encode(self, w: &mut Writer, _: &mut S) { 78 ( 0.00%) w.push(self); 109,528 ( 0.00%) } . } . . impl DecodeMut<'_, '_, S> for u8 { . fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { 8,195,059 ( 0.18%) let x = r[0]; 4,559,988 ( 0.10%) *r = &r[1..]; . x . } . } . . rpc_encode_decode!(le u32); . rpc_encode_decode!(le usize); . . impl Encode for bool { . fn encode(self, w: &mut Writer, s: &mut S) { 16,887 ( 0.00%) (self as u8).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for bool { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 11,258 ( 0.00%) match u8::decode(r, s) { . 0 => false, . 1 => true, . _ => unreachable!(), . } . } . } . . impl Encode for char { . fn encode(self, w: &mut Writer, s: &mut S) { 25,484 ( 0.00%) (self as u32).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for char { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . char::from_u32(u32::decode(r, s)).unwrap() . } . } . . impl Encode for NonZeroU32 { 234 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { 1,750,471 ( 0.04%) self.get().encode(w, s); 78 ( 0.00%) } . } . . impl DecodeMut<'_, '_, S> for NonZeroU32 { 234 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 546 ( 0.00%) Self::new(u32::decode(r, s)).unwrap() 156 ( 0.00%) } . } . . impl, B: Encode> Encode for (A, B) { 429 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { . self.0.encode(w, s); . self.1.encode(w, s); . } . } . . impl<'a, S, A: for<'s> DecodeMut<'a, 's, S>, B: for<'s> DecodeMut<'a, 's, S>> DecodeMut<'a, '_, S> . for (A, B) . { 195 ( 0.00%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { 546 ( 0.00%) (DecodeMut::decode(r, s), DecodeMut::decode(r, s)) 117 ( 0.00%) } . } . . rpc_encode_decode!( . enum Bound { . Included(x), . Excluded(x), . Unbounded, . } -- line 192 ---------------------------------------- -- line 204 ---------------------------------------- . Ok(x), . Err(e), . } . ); . . impl Encode for &[u8] { . fn encode(self, w: &mut Writer, s: &mut S) { . self.len().encode(w, s); 341,212 ( 0.01%) w.write_all(self).unwrap(); . } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a [u8] { . fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { . let len = usize::decode(r, s); . let xs = &r[..len]; 272,913 ( 0.01%) *r = &r[len..]; . xs . } . } . . impl Encode for &str { 341,212 ( 0.01%) fn encode(self, w: &mut Writer, s: &mut S) { . self.as_bytes().encode(w, s); 426,515 ( 0.01%) } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a str { 90,971 ( 0.00%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { 181,942 ( 0.00%) str::from_utf8(<&[u8]>::decode(r, s)).unwrap() 181,942 ( 0.00%) } . } . . impl Encode for String { . fn encode(self, w: &mut Writer, s: &mut S) { 341,212 ( 0.01%) self[..].encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for String { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 426,515 ( 0.01%) <&str>::decode(r, s).to_string() . } . } . . /// Simplified version of panic payloads, ignoring . /// types other than `&'static str` and `String`. . pub enum PanicMessage { . StaticStr(&'static str), . String(String), -- line 253 ---------------------------------------- 8,113,653 ( 0.18%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs -------------------------------------------------------------------------------- Ir -- line 222 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . fn eq(&self, other: &Rhs) -> bool; . . /// This method tests for `!=`. . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] 140,493 ( 0.00%) fn ne(&self, other: &Rhs) -> bool { 172,118 ( 0.00%) !self.eq(other) 187,324 ( 0.00%) } . } . . /// Derive macro generating an impl of the trait `PartialEq`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics, structural_match)] . pub macro PartialEq($item:item) { . /* compiler built-in */ -- line 240 ---------------------------------------- -- line 328 ---------------------------------------- . /// assert_eq!(Ordering::Less, result); . /// . /// let result = 1.cmp(&1); . /// assert_eq!(Ordering::Equal, result); . /// . /// let result = 2.cmp(&1); . /// assert_eq!(Ordering::Greater, result); . /// ``` 27,975 ( 0.00%) #[derive(Clone, Copy, PartialEq, Debug, Hash)] . #[stable(feature = "rust1", since = "1.0.0")] . #[repr(i8)] . pub enum Ordering { . /// An ordering where a compared value is less than another. . #[stable(feature = "rust1", since = "1.0.0")] . Less = -1, . /// An ordering where a compared value is equal to another. . #[stable(feature = "rust1", since = "1.0.0")] -- line 344 ---------------------------------------- -- line 569 ---------------------------------------- . /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); . /// . /// assert_eq!(result, Ordering::Less); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "ordering_chaining", since = "1.17.0")] . pub fn then_with Ordering>(self, f: F) -> Ordering { 48,975 ( 0.00%) match self { . Equal => f(), . _ => self, . } . } . } . . /// A helper struct for reverse ordering. . /// -- line 585 ---------------------------------------- -- line 788 ---------------------------------------- . /// . /// ``` . /// assert_eq!(2, 1.max(2)); . /// assert_eq!(2, 2.max(2)); . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] 218,880 ( 0.00%) fn max(self, other: Self) -> Self . where . Self: Sized, . { 219,720 ( 0.00%) max_by(self, other, Ord::cmp) 145,920 ( 0.00%) } . . /// Compares and returns the minimum of two values. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(1, 1.min(2)); . /// assert_eq!(2, 2.min(2)); . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] 117 ( 0.00%) fn min(self, other: Self) -> Self . where . Self: Sized, . { 4,748 ( 0.00%) min_by(self, other, Ord::cmp) 78 ( 0.00%) } . . /// Restrict a value to a certain interval. . /// . /// Returns `max` if `self` is greater than `max`, and `min` if `self` is . /// less than `min`. Otherwise this returns `self`. . /// . /// # Panics . /// -- line 829 ---------------------------------------- -- line 1097 ---------------------------------------- . /// let result = 2.0 < 1.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn lt(&self, other: &Rhs) -> bool { 64,989 ( 0.00%) matches!(self.partial_cmp(other), Some(Less)) . } . . /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1113 ---------------------------------------- -- line 1121 ---------------------------------------- . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn le(&self, other: &Rhs) -> bool { . // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`. . // FIXME: The root cause was fixed upstream in LLVM with: . // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775 . // Revert this workaround once support for LLVM 12 gets dropped. 469,179 ( 0.01%) !matches!(self.partial_cmp(other), None | Some(Greater)) . } . . /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. . /// . /// # Examples . /// . /// ``` . /// let result = 1.0 > 2.0; -- line 1137 ---------------------------------------- -- line 1139 ---------------------------------------- . /// . /// let result = 2.0 > 2.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] 204 ( 0.00%) fn gt(&self, other: &Rhs) -> bool { 1,542,723 ( 0.03%) matches!(self.partial_cmp(other), Some(Greater)) 340 ( 0.00%) } . . /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` . /// operator. . /// . /// # Examples . /// . /// ``` . /// let result = 2.0 >= 1.0; -- line 1157 ---------------------------------------- -- line 1159 ---------------------------------------- . /// . /// let result = 2.0 >= 2.0; . /// assert_eq!(result, true); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] 28,776 ( 0.00%) fn ge(&self, other: &Rhs) -> bool { 135,439 ( 0.00%) matches!(self.partial_cmp(other), Some(Greater | Equal)) 47,960 ( 0.00%) } . } . . /// Derive macro generating an impl of the trait `PartialOrd`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics)] . pub macro PartialOrd($item:item) { . /* compiler built-in */ -- line 1177 ---------------------------------------- -- line 1190 ---------------------------------------- . /// . /// assert_eq!(1, cmp::min(1, 2)); . /// assert_eq!(2, cmp::min(2, 2)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")] 117 ( 0.00%) pub fn min(v1: T, v2: T) -> T { 78 ( 0.00%) v1.min(v2) 78 ( 0.00%) } . . /// Returns the minimum of two values with respect to the specified comparison function. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1208 ---------------------------------------- -- line 1209 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1); . /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 117 ( 0.00%) pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { 640,587 ( 0.01%) match compare(&v1, &v2) { 156 ( 0.00%) Ordering::Less | Ordering::Equal => v1, . Ordering::Greater => v2, . } 519 ( 0.00%) } . . /// Returns the element that gives the minimum value from the specified function. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1230 ---------------------------------------- -- line 1231 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1); . /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 1,008 ( 0.00%) pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { 672 ( 0.00%) min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) 672 ( 0.00%) } . . /// Compares and returns the maximum of two values. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// Internally uses an alias to [`Ord::max`]. . /// . /// # Examples -- line 1249 ---------------------------------------- -- line 1253 ---------------------------------------- . /// . /// assert_eq!(2, cmp::max(1, 2)); . /// assert_eq!(2, cmp::max(2, 2)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")] 218,880 ( 0.00%) pub fn max(v1: T, v2: T) -> T { 145,920 ( 0.00%) v1.max(v2) 145,920 ( 0.00%) } . . /// Returns the maximum of two values with respect to the specified comparison function. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1271 ---------------------------------------- -- line 1272 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 218,880 ( 0.00%) pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { 2,241,271 ( 0.05%) match compare(&v1, &v2) { 184,417 ( 0.00%) Ordering::Less | Ordering::Equal => v2, 81,876 ( 0.00%) Ordering::Greater => v1, . } 610,972 ( 0.01%) } . . /// Returns the element that gives the maximum value from the specified function. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1293 ---------------------------------------- -- line 1308 ---------------------------------------- . use crate::cmp::Ordering::{self, Equal, Greater, Less}; . use crate::hint::unreachable_unchecked; . . macro_rules! partial_eq_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for $t { . #[inline] 247,513 ( 0.01%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] 79,289 ( 0.00%) fn ne(&self, other: &$t) -> bool { (*self) != (*other) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for () { . #[inline] . fn eq(&self, _other: &()) -> bool { -- line 1326 ---------------------------------------- -- line 1392 ---------------------------------------- . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for $t { . #[inline] . fn partial_cmp(&self, other: &$t) -> Option { . Some(self.cmp(other)) . } . #[inline] 4,660,890 ( 0.10%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] 45,906 ( 0.00%) fn le(&self, other: &$t) -> bool { (*self) <= (*other) } . #[inline] . fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } . #[inline] . fn gt(&self, other: &$t) -> bool { (*self) > (*other) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for $t { . #[inline] 413,295 ( 0.01%) fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 20,359,330 ( 0.44%) if *self < *other { Less } 185,158 ( 0.00%) else if *self == *other { Equal } 36,710 ( 0.00%) else { Greater } 247,977 ( 0.01%) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for () { . #[inline] . fn cmp(&self, _other: &()) -> Ordering { -- line 1426 ---------------------------------------- -- line 1430 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for bool { . #[inline] . fn cmp(&self, other: &bool) -> Ordering { . // Casting to i8's and converting the difference to an Ordering generates . // more optimal assembly. . // See for more info. 2,266 ( 0.00%) match (*self as i8) - (*other as i8) { . -1 => Less, . 0 => Equal, . 1 => Greater, . // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else . _ => unsafe { unreachable_unchecked() }, . } . } . } -- line 1446 ---------------------------------------- -- line 1474 ---------------------------------------- . // & pointers . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&B> for &A . where . A: PartialEq, . { . #[inline] 3,082,481 ( 0.07%) fn eq(&self, other: &&B) -> bool { 5,067,854 ( 0.11%) PartialEq::eq(*self, *other) 2,686,719 ( 0.06%) } . #[inline] 700 ( 0.00%) fn ne(&self, other: &&B) -> bool { 66 ( 0.00%) PartialEq::ne(*self, *other) 36,711 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd<&B> for &A . where . A: PartialOrd, . { . #[inline] . fn partial_cmp(&self, other: &&B) -> Option { 10 ( 0.00%) PartialOrd::partial_cmp(*self, *other) . } . #[inline] . fn lt(&self, other: &&B) -> bool { . PartialOrd::lt(*self, *other) . } . #[inline] . fn le(&self, other: &&B) -> bool { . PartialOrd::le(*self, *other) -- line 1505 ---------------------------------------- -- line 1515 ---------------------------------------- . } . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for &A . where . A: Ord, . { . #[inline] . fn cmp(&self, other: &Self) -> Ordering { 2 ( 0.00%) Ord::cmp(*self, *other) 14,848 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for &A where A: Eq {} . . // &mut pointers . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&mut B> for &mut A -- line 1532 ---------------------------------------- 5,048,081 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/enumerate.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . #[derive(Clone, Debug)] . #[must_use = "iterators are lazy and do nothing unless consumed"] . #[stable(feature = "rust1", since = "1.0.0")] . pub struct Enumerate { . iter: I, . count: usize, . } . impl Enumerate { 592,504 ( 0.01%) pub(in crate::iter) fn new(iter: I) -> Enumerate { 444,378 ( 0.01%) Enumerate { iter, count: 0 } 296,252 ( 0.01%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for Enumerate . where . I: Iterator, . { . type Item = (usize, ::Item); -- line 32 ---------------------------------------- -- line 37 ---------------------------------------- . /// `usize::MAX` elements either produces the wrong result or panics. If . /// debug assertions are enabled, a panic is guaranteed. . /// . /// # Panics . /// . /// Might panic if the index of the element overflows a `usize`. . #[inline] . #[rustc_inherit_overflow_checks] 451,623 ( 0.01%) fn next(&mut self) -> Option<(usize, ::Item)> { 2,119,719 ( 0.05%) let a = self.iter.next()?; 591,298 ( 0.01%) let i = self.count; 2,524,244 ( 0.05%) self.count += 1; 1,253,085 ( 0.03%) Some((i, a)) 751,873 ( 0.02%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 125,138 ( 0.00%) self.iter.size_hint() . } . . #[inline] . #[rustc_inherit_overflow_checks] . fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> { . let a = self.iter.nth(n)?; 746 ( 0.00%) let i = self.count + n; 753 ( 0.00%) self.count = i + 1; . Some((i, a)) . } . . #[inline] . fn count(self) -> usize { . self.iter.count() . } . -- line 70 ---------------------------------------- -- line 76 ---------------------------------------- . R: Try, . { . #[inline] . fn enumerate<'a, T, Acc, R>( . count: &'a mut usize, . mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a, . ) -> impl FnMut(Acc, T) -> R + 'a { . #[rustc_inherit_overflow_checks] 12,049 ( 0.00%) move |acc, item| { 32,247 ( 0.00%) let acc = fold(acc, (*count, item)); 280,311 ( 0.01%) *count += 1; . acc . } . } . 15,731 ( 0.00%) self.iter.try_fold(init, enumerate(&mut self.count, fold)) . } . . #[inline] . fn fold(self, init: Acc, fold: Fold) -> Acc . where . Fold: FnMut(Acc, Self::Item) -> Acc, . { . #[inline] . fn enumerate( . mut count: usize, . mut fold: impl FnMut(Acc, (usize, T)) -> Acc, . ) -> impl FnMut(Acc, T) -> Acc { . #[rustc_inherit_overflow_checks] 51,552 ( 0.00%) move |acc, item| { 142 ( 0.00%) let acc = fold(acc, (count, item)); 64,842 ( 0.00%) count += 1; . acc . } . } . 232,832 ( 0.01%) self.iter.fold(init, enumerate(self.count, fold)) . } . . #[inline] . #[rustc_inherit_overflow_checks] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . match self.iter.advance_by(n) { . ret @ Ok(_) => { . self.count += n; -- line 120 ---------------------------------------- -- line 131 ---------------------------------------- . #[doc(hidden)] . unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> ::Item . where . Self: TrustedRandomAccessNoCoerce, . { . // SAFETY: the caller must uphold the contract for . // `Iterator::__iterator_get_unchecked`. . let value = unsafe { try_get_unchecked(&mut self.iter, idx) }; 252 ( 0.00%) (self.count + idx, value) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for Enumerate . where . I: ExactSizeIterator + DoubleEndedIterator, . { -- line 147 ---------------------------------------- -- line 172 ---------------------------------------- . { . // Can safely add and subtract the count, as `ExactSizeIterator` promises . // that the number of elements fits into a `usize`. . fn enumerate( . mut count: usize, . mut fold: impl FnMut(Acc, (usize, T)) -> R, . ) -> impl FnMut(Acc, T) -> R { . move |acc, item| { 23,846 ( 0.00%) count -= 1; . fold(acc, (count, item)) . } . } . 7,729 ( 0.00%) let count = self.count + self.iter.len(); . self.iter.try_rfold(init, enumerate(count, fold)) . } . . #[inline] . fn rfold(self, init: Acc, fold: Fold) -> Acc . where . Fold: FnMut(Acc, Self::Item) -> Acc, . { -- line 193 ---------------------------------------- 1,261,969 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 46,371 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 53,428 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 116,071 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 11,726 ( 0.00%) i += 2 . } . 53,428 ( 0.00%) if i < count { 42,223 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 547,154 ( 0.01%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 3,649,926 ( 0.08%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 1,121,138 ( 0.02%) self.nbuf = nbuf + size; . . return; . } . 180,850 ( 0.00%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 55,118 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 55,118 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 551,180 ( 0.01%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 440,944 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 496,062 ( 0.01%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 257,254 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 220,472 ( 0.00%) self.processed += BUFFER_SIZE; 110,236 ( 0.00%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 10,124 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 145,142 ( 0.00%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 53,534 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 27,208 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 14,687 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 9,805 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 1,961 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 5,883 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 1,961 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 3,922 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 15,124 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 17,085 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 30,248 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 3,922 ( 0.00%) let input_left = length - processed; 1,569 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 1,018 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 1,018 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 1,018 ( 0.00%) self.state.v0 ^= elem; 2,036 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 1,961 ( 0.00%) self.nbuf = extra_bytes_left; 9,805 ( 0.00%) self.processed += nbuf + processed; 11,766 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 29,847 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 39,796 ( 0.00%) let mut state = self.state; . . for i in 0..last { 28,327 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 28,327 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 28,327 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 19,898 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 7,774 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 26,958 ( 0.00%) let length = self.processed + self.nbuf; 18,466 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 9,233 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 9,233 ( 0.00%) state.v0 ^= b; . 9,233 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 31,626 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 13,158 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 13,158 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 2,039,585 ( 0.04%) compress!(state); 2,189,310 ( 0.05%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 63,248 ( 0.00%) compress!(state); 63,248 ( 0.00%) compress!(state); 63,248 ( 0.00%) compress!(state); 54,016 ( 0.00%) compress!(state); . } . } 440,418 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs -------------------------------------------------------------------------------- Ir -- line 123 ---------------------------------------- . // `cap: 0` means "unallocated". zero-sized types are ignored. . Self { ptr: Unique::dangling(), cap: 0, alloc } . } . . /// Like `with_capacity`, but parameterized over the choice of . /// allocator for the returned `RawVec`. . #[cfg(not(no_global_oom_handling))] . #[inline] 3,364 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 14,204 ( 0.00%) Self::allocate_in(capacity, AllocInit::Uninitialized, alloc) 3,364 ( 0.00%) } . . /// Like `with_capacity_zeroed`, but parameterized over the choice . /// of allocator for the returned `RawVec`. . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { . Self::allocate_in(capacity, AllocInit::Zeroed, alloc) . } -- line 141 ---------------------------------------- -- line 147 ---------------------------------------- . /// . /// # Safety . /// . /// * `len` must be greater than or equal to the most recently requested capacity, and . /// * `len` must be less than or equal to `self.capacity()`. . /// . /// Note, that the requested capacity and `self.capacity()` could differ, as . /// an allocator could overallocate and return a greater memory block than requested. 12,608 ( 0.00%) pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit], A> { . // Sanity-check one half of the safety requirement (we cannot check the other half). 5,030 ( 0.00%) debug_assert!( . len <= self.capacity(), . "`len` must be smaller than or equal to `self.capacity()`" . ); . 22,635 ( 0.00%) let me = ManuallyDrop::new(self); . unsafe { 35,210 ( 0.00%) let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit, len); 22,635 ( 0.00%) Box::from_raw_in(slice, ptr::read(&me.alloc)) . } 5,063 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] 14,952 ( 0.00%) fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { 10,092 ( 0.00%) if mem::size_of::() == 0 { . Self::new_in(alloc) . } else { . // We avoid `unwrap_or_else` here because it bloats the amount of . // LLVM IR generated. 20,184 ( 0.00%) let layout = match Layout::array::(capacity) { 11,774 ( 0.00%) Ok(layout) => layout, . Err(_) => capacity_overflow(), . }; 13,456 ( 0.00%) match alloc_guard(layout.size()) { . Ok(_) => {} . Err(_) => capacity_overflow(), . } 7,476 ( 0.00%) let result = match init { 16,820 ( 0.00%) AllocInit::Uninitialized => alloc.allocate(layout), . AllocInit::Zeroed => alloc.allocate_zeroed(layout), . }; 8,410 ( 0.00%) let ptr = match result { 10,092 ( 0.00%) Ok(ptr) => ptr, . Err(_) => handle_alloc_error(layout), . }; . . // Allocators currently return a `NonNull<[u8]>` whose length . // matches the size requested. If that ever changes, the capacity . // here should change to `ptr.len() / mem::size_of::()`. 3,364 ( 0.00%) Self { 20,184 ( 0.00%) ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }, . cap: capacity, 1,682 ( 0.00%) alloc, . } . } 12,803 ( 0.00%) } . . /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. . /// . /// # Safety . /// . /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given . /// `capacity`. . /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit . /// systems). ZST vectors may have a capacity up to `usize::MAX`. . /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is . /// guaranteed. . #[inline] 60,944 ( 0.00%) pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self { 91,416 ( 0.00%) Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap: capacity, alloc } 60,944 ( 0.00%) } . . /// Gets a raw pointer to the start of the allocation. Note that this is . /// `Unique::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must . /// be careful. . #[inline] 684,696 ( 0.01%) pub fn ptr(&self) -> *mut T { 1,027,044 ( 0.02%) self.ptr.as_ptr() 684,696 ( 0.01%) } . . /// Gets the capacity of the allocation. . /// . /// This will always be `usize::MAX` if `T` is zero-sized. . #[inline(always)] . pub fn capacity(&self) -> usize { 497,875 ( 0.01%) if mem::size_of::() == 0 { usize::MAX } else { self.cap } 199,160 ( 0.00%) } . . /// Returns a shared reference to the allocator backing this `RawVec`. 22,935 ( 0.00%) pub fn allocator(&self) -> &A { . &self.alloc 15,290 ( 0.00%) } . 879,495 ( 0.02%) fn current_memory(&self) -> Option<(NonNull, Layout)> { 9,477,823 ( 0.21%) if mem::size_of::() == 0 || self.cap == 0 { 476,799 ( 0.01%) None . } else { . // We have an allocated chunk of memory, so we can bypass runtime . // checks to get our current layout. . unsafe { 242,260 ( 0.01%) let align = mem::align_of::(); 3,537,721 ( 0.08%) let size = mem::size_of::() * self.cap; 847,910 ( 0.02%) let layout = Layout::from_size_align_unchecked(size, align); 2,097,496 ( 0.05%) Some((self.ptr.cast().into(), layout)) . } . } 351,798 ( 0.01%) } . . /// Ensures that the buffer contains at least enough space to hold `len + . /// additional` elements. If it doesn't already have enough capacity, will . /// reallocate enough space plus comfortable slack space to get amortized . /// *O*(1) behavior. Will limit this behavior if it would needlessly cause . /// itself to panic. . /// . /// If `len` exceeds `self.capacity()`, this may fail to actually allocate -- line 261 ---------------------------------------- -- line 268 ---------------------------------------- . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] . #[inline] 164,647 ( 0.00%) pub fn reserve(&mut self, len: usize, additional: usize) { . // Callers expect this function to be very cheap when there is already sufficient capacity. . // Therefore, we move all the resizing and error-handling logic from grow_amortized and . // handle_reserve behind a call, while making sure that this function is likely to be . // inlined as just a comparison and a call if the comparison fails. . #[cold] 1,071,320 ( 0.02%) fn do_reserve_and_handle( . slf: &mut RawVec, . len: usize, . additional: usize, . ) { 81,406 ( 0.00%) handle_reserve(slf.grow_amortized(len, additional)); 1,246,193 ( 0.03%) } . 1,040,590 ( 0.02%) if self.needs_to_grow(len, additional) { 1,132,349 ( 0.02%) do_reserve_and_handle(self, len, additional); . } 47,042 ( 0.00%) } . . /// A specialized version of `reserve()` used only by the hot and . /// oft-instantiated `Vec::push()`, which does its own capacity check. . #[cfg(not(no_global_oom_handling))] . #[inline(never)] 1,011,176 ( 0.02%) pub fn reserve_for_push(&mut self, len: usize) { 84,370 ( 0.00%) handle_reserve(self.grow_amortized(len, 1)); 1,173,484 ( 0.03%) } . . /// The same as `reserve`, but returns on errors instead of panicking or aborting. . pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . if self.needs_to_grow(len, additional) { . self.grow_amortized(len, additional) . } else { . Ok(()) . } -- line 309 ---------------------------------------- -- line 322 ---------------------------------------- . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] 32,485 ( 0.00%) pub fn reserve_exact(&mut self, len: usize, additional: usize) { . handle_reserve(self.try_reserve_exact(len, additional)); 32,485 ( 0.00%) } . . /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. . pub fn try_reserve_exact( . &mut self, . len: usize, . additional: usize, . ) -> Result<(), TryReserveError> { 13,554 ( 0.00%) if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) } . } . . /// Shrinks the buffer down to the specified capacity. If the given amount . /// is 0, actually completely deallocates. . /// . /// # Panics . /// . /// Panics if the given amount is *larger* than the current capacity. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] 21,985 ( 0.00%) pub fn shrink_to_fit(&mut self, cap: usize) { 7,272 ( 0.00%) handle_reserve(self.shrink(cap)); 19,110 ( 0.00%) } . } . . impl RawVec { . /// Returns if the buffer needs to grow to fulfill the needed extra capacity. . /// Mainly used to make inlining reserve-calls possible without inlining `grow`. 188,168 ( 0.00%) fn needs_to_grow(&self, len: usize, additional: usize) -> bool { 1,718,745 ( 0.04%) additional > self.capacity().wrapping_sub(len) 94,084 ( 0.00%) } . 497,874 ( 0.01%) fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) { . // Allocators currently return a `NonNull<[u8]>` whose length matches . // the size requested. If that ever changes, the capacity here should . // change to `ptr.len() / mem::size_of::()`. 793,550 ( 0.02%) self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }; 564,384 ( 0.01%) self.cap = cap; 76,596 ( 0.00%) } . . // This method is usually instantiated many times. So we want it to be as . // small as possible, to improve compile times. But we also want as much of . // its contents to be statically computable as possible, to make the . // generated code run faster. Therefore, this method is carefully written . // so that all of the code that depends on `T` is within it, while as much . // of the code that doesn't depend on `T` as possible is in functions that . // are non-generic over `T`. 332,064 ( 0.01%) fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . // This is ensured by the calling contexts. . debug_assert!(additional > 0); . 109,440 ( 0.00%) if mem::size_of::() == 0 { . // Since we return a capacity of `usize::MAX` when `elem_size` is . // 0, getting to here necessarily means the `RawVec` is overfull. . return Err(CapacityOverflow.into()); . } . . // Nothing we can really do about these checks, sadly. 656,640 ( 0.01%) let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; . . // This guarantees exponential growth. The doubling cannot overflow . // because `cap <= isize::MAX` and the type of `cap` is `usize`. 2,505,716 ( 0.05%) let cap = cmp::max(self.cap * 2, required_cap); 145,920 ( 0.00%) let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap); . 182,400 ( 0.00%) let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 2,188,601 ( 0.05%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; 72,960 ( 0.00%) self.set_ptr_and_cap(ptr, cap); 36,480 ( 0.00%) Ok(()) 113,183 ( 0.00%) } . . // The constraints on this method are much the same as those on . // `grow_amortized`, but this method is usually instantiated less often so . // it's less critical. . fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . if mem::size_of::() == 0 { . // Since we return a capacity of `usize::MAX` when the type size is . // 0, getting to here necessarily means the `RawVec` is overfull. . return Err(CapacityOverflow.into()); . } . . let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; . let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 17,714 ( 0.00%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; . self.set_ptr_and_cap(ptr, cap); . Ok(()) . } . 14,544 ( 0.00%) fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> { 16,827 ( 0.00%) assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity"); . 50,904 ( 0.00%) let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) }; 22,281 ( 0.00%) let new_size = cap * mem::size_of::(); . . let ptr = unsafe { 12,726 ( 0.00%) let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); 32,724 ( 0.00%) self.alloc 7,272 ( 0.00%) .shrink(ptr, layout, new_layout) 3,636 ( 0.00%) .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? . }; 3,636 ( 0.00%) self.set_ptr_and_cap(ptr, cap); 1,818 ( 0.00%) Ok(()) 5,454 ( 0.00%) } . } . . // This function is outside `RawVec` to minimize compile times. See the comment . // above `RawVec::grow_amortized` for details. (The `A` parameter isn't . // significant, because the number of different `A` types seen in practice is . // much smaller than the number of `T` types.) . #[inline(never)] 2,906,230 ( 0.06%) fn finish_grow( . new_layout: Result, . current_memory: Option<(NonNull, Layout)>, . alloc: &mut A, . ) -> Result, TryReserveError> . where . A: Allocator, . { . // Check for the error here to minimize the size of `RawVec::grow_*`. 510,720 ( 0.01%) let new_layout = new_layout.map_err(|_| CapacityOverflow)?; . 437,760 ( 0.01%) alloc_guard(new_layout.size())?; . 2,002,044 ( 0.04%) let memory = if let Some((ptr, old_layout)) = current_memory { . debug_assert_eq!(old_layout.align(), new_layout.align()); . unsafe { . // The allocator checks for alignment equality 34,650 ( 0.00%) intrinsics::assume(old_layout.align() == new_layout.align()); 48,510 ( 0.00%) alloc.grow(ptr, old_layout, new_layout) . } . } else { 147,750 ( 0.00%) alloc.allocate(new_layout) . }; . 255,360 ( 0.01%) memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into()) 2,200,952 ( 0.05%) } . . unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec { . /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. 560,203 ( 0.01%) fn drop(&mut self) { 4,145,430 ( 0.09%) if let Some((ptr, layout)) = self.current_memory() { 224,764 ( 0.00%) unsafe { self.alloc.deallocate(ptr, layout) } . } 283,598 ( 0.01%) } . } . . // Central function for reserve error handling. . #[cfg(not(no_global_oom_handling))] . #[inline] 38,298 ( 0.00%) fn handle_reserve(result: Result<(), TryReserveError>) { 459,576 ( 0.01%) match result.map_err(|e| e.kind()) { . Err(CapacityOverflow) => capacity_overflow(), . Err(AllocError { layout, .. }) => handle_alloc_error(layout), . Ok(()) => { /* yay */ } . } 76,596 ( 0.00%) } . . // We need to guarantee the following: . // * We don't ever allocate `> isize::MAX` byte-size objects. . // * We don't overflow `usize::MAX` and actually allocate too little. . // . // On 64-bit we just need to check for overflow since trying to allocate . // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add . // an extra guard for this in case we're running on a platform which can use . // all 4GB in user-space, e.g., PAE or x32. . . #[inline] 152,648 ( 0.00%) fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> { 152,648 ( 0.00%) if usize::BITS < 64 && alloc_size > isize::MAX as usize { . Err(CapacityOverflow.into()) . } else { 38,162 ( 0.00%) Ok(()) . } 76,324 ( 0.00%) } . . // One central function responsible for reporting capacity overflows. This'll . // ensure that the code generation related to these panics is minimal as there's . // only one location which panics rather than a bunch throughout the module. . #[cfg(not(no_global_oom_handling))] . fn capacity_overflow() -> ! { . panic!("capacity overflow"); . } -- line 519 ---------------------------------------- 12,143,919 ( 0.26%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32; . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<[B]> for [A] . where . A: PartialEq, . { 3,123,266 ( 0.07%) fn eq(&self, other: &[B]) -> bool { 1,211,030 ( 0.03%) SlicePartialEq::equal(self, other) 2,540,008 ( 0.06%) } . . fn ne(&self, other: &[B]) -> bool { . SlicePartialEq::not_equal(self, other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for [T] {} -- line 36 ---------------------------------------- -- line 41 ---------------------------------------- . fn cmp(&self, other: &[T]) -> Ordering { . SliceOrd::compare(self, other) . } . } . . /// Implements comparison of vectors [lexicographically](Ord#lexicographical-comparison). . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for [T] { 30 ( 0.00%) fn partial_cmp(&self, other: &[T]) -> Option { . SlicePartialOrd::partial_compare(self, other) 24 ( 0.00%) } . } . . #[doc(hidden)] . // intermediate trait for specialization of slice's PartialEq . trait SlicePartialEq { . fn equal(&self, other: &[B]) -> bool; . . fn not_equal(&self, other: &[B]) -> bool { -- line 59 ---------------------------------------- -- line 62 ---------------------------------------- . } . . // Generic slice equality . impl SlicePartialEq for [A] . where . A: PartialEq, . { . default fn equal(&self, other: &[B]) -> bool { 714,768 ( 0.02%) if self.len() != other.len() { . return false; . } . 49,499 ( 0.00%) self.iter().zip(other.iter()).all(|(x, y)| x == y) . } . } . . // Use memcmp for bytewise equality when the types allow . impl SlicePartialEq for [A] . where . A: BytewiseEquality, . { 5,449,635 ( 0.12%) fn equal(&self, other: &[B]) -> bool { 1,392,639 ( 0.03%) if self.len() != other.len() { 519,458 ( 0.01%) return false; . } . . // SAFETY: `self` and `other` are references and are thus guaranteed to be valid. . // The two slices have been checked to have the same size above. . unsafe { 344,228 ( 0.01%) let size = mem::size_of_val(self); 1,346,883 ( 0.03%) memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0 . } 3,113,632 ( 0.07%) } . } . . #[doc(hidden)] . // intermediate trait for specialization of slice's PartialOrd . trait SlicePartialOrd: Sized { . fn partial_compare(left: &[Self], right: &[Self]) -> Option; . } . -- line 102 ---------------------------------------- -- line 104 ---------------------------------------- . default fn partial_compare(left: &[A], right: &[A]) -> Option { . let l = cmp::min(left.len(), right.len()); . . // Slice to the loop iteration range to enable bound check . // elimination in the compiler . let lhs = &left[..l]; . let rhs = &right[..l]; . 18 ( 0.00%) for i in 0..l { 4 ( 0.00%) match lhs[i].partial_cmp(&rhs[i]) { . Some(Ordering::Equal) => (), . non_eq => return non_eq, . } . } . . left.len().partial_cmp(&right.len()) . } . } -- line 121 ---------------------------------------- -- line 168 ---------------------------------------- . default fn compare(left: &[Self], right: &[Self]) -> Ordering { . let l = cmp::min(left.len(), right.len()); . . // Slice to the loop iteration range to enable bound check . // elimination in the compiler . let lhs = &left[..l]; . let rhs = &right[..l]; . 2 ( 0.00%) for i in 0..l { . match lhs[i].cmp(&rhs[i]) { . Ordering::Equal => (), . non_eq => return non_eq, . } . } . . left.len().cmp(&right.len()) . } -- line 184 ---------------------------------------- -- line 188 ---------------------------------------- . // this matches the order we want for [u8], but no others (not even [i8]). . impl SliceOrd for u8 { . #[inline] . fn compare(left: &[Self], right: &[Self]) -> Ordering { . let order = . // SAFETY: `left` and `right` are references and are thus guaranteed to be valid. . // We use the minimum of both lengths which guarantees that both regions are . // valid for reads in that interval. 21,411 ( 0.00%) unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) }; 23,978 ( 0.00%) if order == 0 { . left.len().cmp(&right.len()) 23,271 ( 0.00%) } else if order < 0 { . Less . } else { . Greater . } . } . } . . // Hack to allow specializing on `Eq` even though `Eq` has a method. -- line 207 ---------------------------------------- -- line 230 ---------------------------------------- . pub(super) trait SliceContains: Sized { . fn slice_contains(&self, x: &[Self]) -> bool; . } . . impl SliceContains for T . where . T: PartialEq, . { 308 ( 0.00%) default fn slice_contains(&self, x: &[Self]) -> bool { 48,103 ( 0.00%) x.iter().any(|y| *y == *self) 462 ( 0.00%) } . } . . impl SliceContains for u8 { . #[inline] . fn slice_contains(&self, x: &[Self]) -> bool { . memchr::memchr(*self, x).is_some() . } . } -- line 248 ---------------------------------------- 2,238,995 ( 0.05%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../elf/dl-tls.c ./elf/../sysdeps/x86_64/dl-machine.h ./elf/../sysdeps/x86_64/dl-tls.c ./elf/../sysdeps/x86_64/tls_get_addr.S ./elf/dl-lookup.c ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 1,323,314,273 (28.71%) events annotated