-------------------------------------------------------------------------------- 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 js_sys --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 -C metadata=d226ceb0800f44e2 -C extra-filename=-d226ceb0800f44e2 --out-dir /usr/home/liquid/tmp/.tmpVisG3l/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpVisG3l/target/debug/deps --extern wasm_bindgen=/usr/home/liquid/tmp/.tmpVisG3l/target/debug/deps/libwasm_bindgen-257a3b187db57b05.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-js-sys-0.3.56-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 15,794,441,928 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 520,871,610 ( 3.30%) ./malloc/malloc.c:_int_free 443,031,537 ( 2.80%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 415,426,557 ( 2.63%) ./malloc/malloc.c:_int_malloc 303,198,848 ( 1.92%) ./malloc/malloc.c:malloc 294,916,693 ( 1.87%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 155,662,534 ( 0.99%) ./malloc/malloc.c:free 145,655,039 ( 0.92%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs:> as proc_macro::bridge::server::DispatcherTrait>::dispatch 132,077,880 ( 0.84%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 106,614,176 ( 0.68%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 95,615,302 ( 0.61%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 87,270,113 ( 0.55%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 65,425,027 ( 0.41%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 65,119,748 ( 0.41%) /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:: 63,676,963 ( 0.40%) ./malloc/malloc.c:malloc_consolidate 62,816,684 ( 0.40%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::decode 58,395,070 ( 0.37%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 58,317,605 ( 0.37%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 58,138,204 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 55,374,608 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>>::insert 54,087,441 ( 0.34%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 51,225,542 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 50,842,623 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 50,687,704 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 49,376,768 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 48,073,761 ( 0.30%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 48,027,193 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 47,296,299 ( 0.30%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 47,130,249 ( 0.30%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 46,953,609 ( 0.30%) ./malloc/malloc.c:realloc 46,468,668 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>>::insert 45,499,446 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 45,467,367 ( 0.29%) ./elf/../sysdeps/x86_64/tls_get_addr.S:__tls_get_addr 45,301,939 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 44,605,625 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 43,302,712 ( 0.27%) ???:llvm::MCExpr::evaluateAsRelocatableImpl(llvm::MCValue&, llvm::MCAssembler const*, llvm::MCAsmLayout const*, llvm::MCFixup const*, llvm::DenseMap, llvm::detail::DenseMapPair > const*, bool) const 43,231,665 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs: as proc_macro::bridge::rpc::DecodeMut>::decode 41,332,226 ( 0.26%) ./malloc/malloc.c:unlink_chunk.constprop.0 40,537,655 ( 0.26%) /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 40,443,952 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 38,315,929 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 37,679,360 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 36,383,316 ( 0.23%) ???:llvm::TargetRegisterInfo::checkAllSuperRegsMarked(llvm::BitVector const&, llvm::ArrayRef) const 36,057,990 ( 0.23%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 35,605,654 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::mem::replace 35,388,472 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 35,237,852 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::iterator::Iterator>::next 34,609,419 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 33,236,415 ( 0.21%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 33,122,304 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 33,018,550 ( 0.21%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 32,371,913 ( 0.20%) ./malloc/malloc.c:_int_realloc 31,970,700 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 31,661,456 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::read 31,231,501 ( 0.20%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 31,218,905 ( 0.20%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 30,966,954 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 29,886,471 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 29,546,323 ( 0.19%) ./malloc/malloc.c:calloc 28,744,250 ( 0.18%) ???:(anonymous namespace)::Verifier::visitCallBase(llvm::CallBase&) 28,620,368 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::guaranteed_eq 28,493,069 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 28,479,440 ( 0.18%) ???:(anonymous namespace)::VarLocBasedLDV::process(llvm::MachineInstr&, (anonymous namespace)::VarLocBasedLDV::OpenRangesSet&, (anonymous namespace)::VarLocBasedLDV::VarLocMap&, llvm::SmallVector<(anonymous namespace)::VarLocBasedLDV::TransferDebugPair, 4u>&) 27,646,596 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 27,431,305 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 26,796,710 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>>::insert 26,576,056 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::is_null 25,873,071 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::KV>>::remove_leaf_kv::<>>::remove_kv::{closure#0}> 25,847,874 ( 0.16%) ???:llvm::TargetRegisterInfo::shouldRealignStack(llvm::MachineFunction const&) const 25,300,080 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::remove_entry 24,307,808 ( 0.15%) ???:multikeySort(llvm::MutableArrayRef*>, int) 24,126,394 ( 0.15%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 23,961,277 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 23,957,549 ( 0.15%) ???:??? 23,951,554 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 23,467,680 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 23,132,793 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.36/src/wrapper.rs:>::extend 22,749,723 ( 0.14%) /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}> 22,323,600 ( 0.14%) /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_fit 22,271,814 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs:core::iter::traits::iterator::Iterator::fold 22,263,182 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 21,798,024 ( 0.14%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 21,729,325 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs:core::ptr::non_null::NonNull::as_ptr 21,643,346 ( 0.14%) ???:(anonymous namespace)::TwoAddressInstructionPass::runOnMachineFunction(llvm::MachineFunction&) 21,179,546 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:alloc::vec::Vec::push 20,858,261 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs: as core::ops::try_trait::Try>::branch 20,833,630 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 20,744,274 ( 0.13%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 20,520,830 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 20,125,404 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:core::str::traits::::eq 20,055,210 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::KV>>::remove_leaf_kv::<>>::remove_kv::{closure#0}> 19,946,675 ( 0.13%) ???:llvm::SmallSet >::insert(llvm::Register const&) 19,860,131 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs:<[A] as core::slice::cmp::SlicePartialEq>::equal 19,779,602 ( 0.13%) ???:llvm::MCAsmLayout::getFragmentOffset(llvm::MCFragment const*) const 19,719,121 ( 0.12%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 19,525,692 ( 0.12%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 19,420,858 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::insert 19,385,534 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 19,152,111 ( 0.12%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 19,128,988 ( 0.12%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 18,900,601 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 18,813,884 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::from_lit_token 18,603,000 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs:>>::insert 18,253,726 ( 0.12%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 18,180,154 ( 0.12%) ???:llvm::MCAsmLayout::getSymbolOffset(llvm::MCSymbol const&) const 18,045,955 ( 0.11%) ???:(anonymous namespace)::Verifier::verify(llvm::Function const&) [clone .llvm.4153962086227604281] 17,746,233 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/maybe_uninit.rs:core::ptr::read 17,694,229 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.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}> 17,351,546 ( 0.11%) ???:(anonymous namespace)::X86MCCodeEmitter::emitPrefixImpl(unsigned int&, llvm::MCInst const&, llvm::MCSubtargetInfo const&, llvm::raw_ostream&) const 17,192,159 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:>::decode 17,160,166 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:alloc::raw_vec::RawVec::current_memory 17,111,770 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:, proc_macro::bridge::rpc::PanicMessage> as proc_macro::bridge::rpc::Encode>>>::encode 17,037,902 ( 0.11%) ???:(anonymous namespace)::VarLocBasedLDV::ExtendRanges(llvm::MachineFunction&, llvm::TargetPassConfig*) [clone .llvm.4451506318407214204] 17,022,461 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 17,019,784 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 16,377,302 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs:, alloc::collections::btree::node::marker::LeafOrInternal>, alloc::collections::btree::node::marker::KV>>::remove_kv_tracking::<>>::remove_kv::{closure#0}> 15,949,252 ( 0.10%) ./elf/dl-lookup.c:do_lookup_x 15,855,199 ( 0.10%) ???:(anonymous namespace)::PEI::runOnMachineFunction(llvm::MachineFunction&) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs -------------------------------------------------------------------------------- Ir -- line 193 ---------------------------------------- . /// assert_eq!(a.iter().count(), 5); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn count(self) -> usize . where . Self: Sized, . { 34,887 ( 0.00%) self.fold( . 0, . #[rustc_inherit_overflow_checks] 50,615 ( 0.00%) |count, _| count + 1, . ) . } . . /// Consumes the iterator, returning the last element. . /// . /// This method will evaluate the iterator until it returns [`None`]. While . /// doing so, it keeps track of the current element. After [`None`] is . /// returned, `last()` will then return the last element it saw. -- line 212 ---------------------------------------- -- line 267 ---------------------------------------- . /// assert_eq!(iter.next(), Some(&3)); . /// assert_eq!(iter.advance_by(0), Ok(())); . /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped . /// ``` . #[inline] . #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . for i in 0..n { 4,976 ( 0.00%) self.next().ok_or(i)?; . } . Ok(()) . } . . /// Returns the `n`th element of the iterator. . /// . /// Like most indexing operations, the count starts from zero, so `nth(0)` . /// returns the first value, `nth(1)` the second, and so on. -- line 283 ---------------------------------------- -- line 313 ---------------------------------------- . /// Returning `None` if there are less than `n + 1` elements: . /// . /// ``` . /// let a = [1, 2, 3]; . /// assert_eq!(a.iter().nth(10), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 8 ( 0.00%) fn nth(&mut self, n: usize) -> Option { . self.advance_by(n).ok()?; 12,746 ( 0.00%) self.next() . } . . /// Creates an iterator starting at the same point, but stepping by . /// the given amount at each iteration. . /// . /// Note 1: The first element of the iterator will always be returned, . /// regardless of the step given. . /// -- line 331 ---------------------------------------- -- line 436 ---------------------------------------- . /// s.encode_wide().chain(std::iter::once(0)).collect() . /// } . /// ``` . /// . /// [`once`]: crate::iter::once . /// [`OsStr`]: ../../std/ffi/struct.OsStr.html . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 573,252 ( 0.00%) fn chain(self, other: U) -> Chain . where . Self: Sized, . U: IntoIterator, . { 2,153,682 ( 0.01%) Chain::new(self, other.into_iter()) 191,084 ( 0.00%) } . . /// 'Zips up' two iterators into a single iterator of pairs. . /// . /// `zip()` returns a new iterator that will iterate over two other . /// iterators, returning a tuple where the first element comes from the . /// first iterator, and the second element comes from the second iterator. . /// . /// In other words, it zips two iterators together, into a single one. -- line 458 ---------------------------------------- -- line 550 ---------------------------------------- . /// # assert_eq!(zipped.next(), None); . /// ``` . /// . /// [`enumerate`]: Iterator::enumerate . /// [`next`]: Iterator::next . /// [`zip`]: crate::iter::zip . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 176,445 ( 0.00%) fn zip(self, other: U) -> Zip . where . Self: Sized, . U: IntoIterator, . { 141,211 ( 0.00%) Zip::new(self, other.into_iter()) 23,526 ( 0.00%) } . . /// Creates a new iterator which places a copy of `separator` between adjacent . /// items of the original iterator. . /// . /// In case `separator` does not implement [`Clone`] or needs to be . /// computed every time, use [`intersperse_with`]. . /// . /// # Examples -- line 572 ---------------------------------------- -- line 709 ---------------------------------------- . /// . /// // Instead, use for: . /// for x in 0..5 { . /// println!("{}", x); . /// } . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 421,006 ( 0.00%) fn map(self, f: F) -> Map . where . Self: Sized, . F: FnMut(Self::Item) -> B, . { 1,260,758 ( 0.01%) Map::new(self, f) 279,824 ( 0.00%) } . . /// Calls a closure on each element of an iterator. . /// . /// This is equivalent to using a [`for`] loop on the iterator, although . /// `break` and `continue` are not possible from a closure. It's generally . /// more idiomatic to use a `for` loop, but `for_each` may be more legible . /// when processing items at the end of longer iterator chains. In some . /// cases `for_each` may also be faster than a loop, because it will use -- line 731 ---------------------------------------- -- line 754 ---------------------------------------- . /// ``` . /// (0..5).flat_map(|x| x * 100 .. x * 110) . /// .enumerate() . /// .filter(|&(i, x)| (i + x) % 3 == 0) . /// .for_each(|(i, x)| println!("{}:{}", i, x)); . /// ``` . #[inline] . #[stable(feature = "iterator_for_each", since = "1.21.0")] 512,242 ( 0.00%) fn for_each(self, f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . #[inline] 205,615 ( 0.00%) fn call(mut f: impl FnMut(T)) -> impl FnMut((), T) { 6,599,534 ( 0.04%) move |(), item| f(item) 306,116 ( 0.00%) } . 7,820,197 ( 0.05%) self.fold((), call(f)); 210,228 ( 0.00%) } . . /// Creates an iterator which uses a closure to determine if an element . /// should be yielded. . /// . /// Given an element the closure must return `true` or `false`. The returned . /// iterator will yield only the elements for which the closure returns . /// true. . /// -- line 781 ---------------------------------------- -- line 829 ---------------------------------------- . /// assert_eq!(iter.next(), None); . /// ``` . /// . /// of these layers. . /// . /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 2,139 ( 0.00%) fn filter

(self, predicate: P) -> Filter . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 181,059 ( 0.00%) Filter::new(self, predicate) 1,386 ( 0.00%) } . . /// Creates an iterator that both filters and maps. . /// . /// The returned iterator yields only the `value`s for which the supplied . /// closure returns `Some(value)`. . /// . /// `filter_map` can be used to make chains of [`filter`] and [`map`] more . /// concise. The example below shows how a `map().filter().map()` can be -- line 851 ---------------------------------------- -- line 874 ---------------------------------------- . /// let a = ["1", "two", "NaN", "four", "5"]; . /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap()); . /// assert_eq!(iter.next(), Some(1)); . /// assert_eq!(iter.next(), Some(5)); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 41,597 ( 0.00%) fn filter_map(self, f: F) -> FilterMap . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 64,049 ( 0.00%) FilterMap::new(self, f) 27,670 ( 0.00%) } . . /// Creates an iterator which gives the current iteration count as well as . /// the next value. . /// . /// The iterator returned yields pairs `(i, val)`, where `i` is the . /// current index of iteration and `val` is the value returned by the . /// iterator. . /// -- line 896 ---------------------------------------- -- line 920 ---------------------------------------- . /// . /// assert_eq!(iter.next(), Some((0, &'a'))); . /// assert_eq!(iter.next(), Some((1, &'b'))); . /// assert_eq!(iter.next(), Some((2, &'c'))); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 547,828 ( 0.00%) fn enumerate(self) -> Enumerate . where . Self: Sized, . { 115,680 ( 0.00%) Enumerate::new(self) 220,208 ( 0.00%) } . . /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods . /// to look at the next element of the iterator without consuming it. See . /// their documentation for more information. . /// . /// Note that the underlying iterator is still advanced when [`peek`] or . /// [`peek_mut`] are called for the first time: In order to retrieve the . /// next element, [`next`] is called on the underlying iterator, hence any -- line 941 ---------------------------------------- -- line 995 ---------------------------------------- . /// [`peek_mut`]: Peekable::peek_mut . /// [`next`]: Iterator::next . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn peekable(self) -> Peekable . where . Self: Sized, . { 13 ( 0.00%) Peekable::new(self) . } . . /// Creates an iterator that [`skip`]s elements based on a predicate. . /// . /// [`skip`]: Iterator::skip . /// . /// `skip_while()` takes a closure as an argument. It will call this . /// closure on each element of the iterator, and ignore elements -- line 1011 ---------------------------------------- -- line 1256 ---------------------------------------- . /// . /// let mut iter = a.iter().skip(2); . /// . /// assert_eq!(iter.next(), Some(&3)); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 464 ( 0.00%) fn skip(self, n: usize) -> Skip . where . Self: Sized, . { 928 ( 0.00%) Skip::new(self, n) 232 ( 0.00%) } . . /// Creates an iterator that yields the first `n` elements, or fewer . /// if the underlying iterator ends sooner. . /// . /// `take(n)` yields elements until `n` elements are yielded or the end of . /// the iterator is reached (whichever happens first). . /// The returned iterator is a prefix of length `n` if the original iterator . /// contains at least `n` elements, otherwise it contains all of the -- line 1277 ---------------------------------------- -- line 1309 ---------------------------------------- . /// let v = [1, 2]; . /// let mut iter = v.into_iter().take(5); . /// assert_eq!(iter.next(), Some(1)); . /// assert_eq!(iter.next(), Some(2)); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 175,876 ( 0.00%) fn take(self, n: usize) -> Take . where . Self: Sized, . { 351,752 ( 0.00%) Take::new(self, n) 87,938 ( 0.00%) } . . /// An iterator adapter similar to [`fold`] that holds internal state and . /// produces a new iterator. . /// . /// [`fold`]: Iterator::fold . /// . /// `scan()` takes two arguments: an initial value which seeds the internal . /// state, and a closure with two arguments, the first being a mutable -- line 1330 ---------------------------------------- -- line 1399 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn flat_map(self, f: F) -> FlatMap . where . Self: Sized, . U: IntoIterator, . F: FnMut(Self::Item) -> U, . { 8 ( 0.00%) FlatMap::new(self, f) . } . . /// Creates an iterator that flattens nested structure. . /// . /// This is useful when you have an iterator of iterators or an iterator of . /// things that can be turned into iterators and you want to remove one . /// level of indirection. . /// -- line 1415 ---------------------------------------- -- line 1537 ---------------------------------------- . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn fuse(self) -> Fuse . where . Self: Sized, . { 15,421 ( 0.00%) Fuse::new(self) . } . . /// Does something with each element of an iterator, passing the value on. . /// . /// When using iterators, you'll often chain several of them together. . /// While working on such code, you might want to check out what's . /// happening at various parts in the pipeline. To do that, insert . /// a call to `inspect()`. -- line 1553 ---------------------------------------- -- line 1765 ---------------------------------------- . /// ``` . /// . /// [`iter`]: Iterator::next . /// [`String`]: ../../std/string/struct.String.html . /// [`char`]: type@char . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] 237,708 ( 0.00%) fn collect>(self) -> B . where . Self: Sized, . { 1,136,468 ( 0.01%) FromIterator::from_iter(self) 336,726 ( 0.00%) } . . /// Consumes an iterator, creating two collections from it. . /// . /// The predicate passed to `partition()` can return `true`, or `false`. . /// `partition()` returns a pair, all of the elements for which it returned . /// `true`, and all of the elements for which it returned `false`. . /// . /// See also [`is_partitioned()`] and [`partition_in_place()`]. -- line 1786 ---------------------------------------- -- line 1798 ---------------------------------------- . /// let (even, odd): (Vec, Vec) = a . /// .iter() . /// .partition(|&n| n % 2 == 0); . /// . /// assert_eq!(even, vec![2]); . /// assert_eq!(odd, vec![1, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 776 ( 0.00%) fn partition(self, f: F) -> (B, B) . where . Self: Sized, . B: Default + Extend, . F: FnMut(&Self::Item) -> bool, . { . #[inline] . fn extend<'a, T, B: Extend>( . mut f: impl FnMut(&T) -> bool + 'a, . left: &'a mut B, . right: &'a mut B, . ) -> impl FnMut((), T) + 'a { . move |(), x| { 578 ( 0.00%) if f(&x) { . left.extend_one(x); . } else { . right.extend_one(x); . } . } . } . . let mut left: B = Default::default(); . let mut right: B = Default::default(); . 2,908 ( 0.00%) self.fold((), extend(f, &mut left, &mut right)); . 3,096 ( 0.00%) (left, right) 873 ( 0.00%) } . . /// Reorders the elements of this iterator *in-place* according to the given predicate, . /// such that all those that return `true` precede all those that return `false`. . /// Returns the number of `true` elements found. . /// . /// The relative order of partitioned items is not maintained. . /// . /// # Current implementation -- line 1841 ---------------------------------------- -- line 2011 ---------------------------------------- . /// } else { . /// ControlFlow::Break(prev) . /// } . /// }); . /// assert_eq!(triangular, ControlFlow::Continue(435)); . /// ``` . #[inline] . #[stable(feature = "iterator_try_fold", since = "1.27.0")] 101,750 ( 0.00%) fn try_fold(&mut self, init: B, mut f: F) -> R . where . Self: Sized, . F: FnMut(B, Self::Item) -> R, . R: Try, . { 27,032 ( 0.00%) let mut accum = init; 6,227,085 ( 0.04%) while let Some(x) = self.next() { 7,402,533 ( 0.05%) accum = f(accum, x)?; . } 37,885 ( 0.00%) try { accum } 88,859 ( 0.00%) } . . /// An iterator method that applies a fallible function to each item in the . /// iterator, stopping at the first error and returning that error. . /// . /// This can also be thought of as the fallible form of [`for_each()`] . /// or as the stateless version of [`try_fold()`]. . /// . /// [`for_each()`]: Iterator::for_each -- line 2038 ---------------------------------------- -- line 2077 ---------------------------------------- . fn try_for_each(&mut self, f: F) -> R . where . Self: Sized, . F: FnMut(Self::Item) -> R, . R: Try, . { . #[inline] . fn call(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R { 12,300 ( 0.00%) move |(), x| f(x) . } . 708 ( 0.00%) self.try_fold((), call(f)) . } . . /// Folds every element into an accumulator by applying an operation, . /// returning the final result. . /// . /// `fold()` takes two arguments: an initial value, and a closure with two . /// arguments: an 'accumulator', and an element. The closure returns the value that . /// the accumulator should have for the next iteration. -- line 2096 ---------------------------------------- -- line 2188 ---------------------------------------- . /// // they're the same . /// assert_eq!(result, result2); . /// ``` . /// . /// [`reduce()`]: Iterator::reduce . #[doc(alias = "inject", alias = "foldl")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 797,142 ( 0.01%) fn fold(mut self, init: B, mut f: F) -> B . where . Self: Sized, . F: FnMut(B, Self::Item) -> B, . { 405,146 ( 0.00%) let mut accum = init; 16,578,020 ( 0.10%) while let Some(x) = self.next() { 6,624,221 ( 0.04%) accum = f(accum, x); . } 200,656 ( 0.00%) accum 914,021 ( 0.01%) } . . /// Reduces the elements to a single one, by repeatedly applying a reducing . /// operation. . /// . /// If the iterator is empty, returns [`None`]; otherwise, returns the . /// result of the reduction. . /// . /// The reducing function is a closure with two arguments: an 'accumulator', and an element. -- line 2214 ---------------------------------------- -- line 2240 ---------------------------------------- . #[inline] . #[stable(feature = "iterator_fold_self", since = "1.51.0")] . fn reduce(mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item, Self::Item) -> Self::Item, . { . let first = self.next()?; 28,165 ( 0.00%) Some(self.fold(first, f)) . } . . /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the . /// closure returns a failure, the failure is propagated back to the caller immediately. . /// . /// The return type of this method depends on the return type of the closure. If the closure . /// returns `Result`, then this function will return `Result, . /// E>`. If the closure returns `Option`, then this function will return -- line 2256 ---------------------------------------- -- line 2370 ---------------------------------------- . fn all(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 105,448 ( 0.00%) if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK } . } . } 25,811 ( 0.00%) self.try_fold((), check(f)) == ControlFlow::CONTINUE . } . . /// Tests if any element of the iterator matches a predicate. . /// . /// `any()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, and if any of them return . /// `true`, then so does `any()`. If they all return `false`, it . /// returns `false`. -- line 2389 ---------------------------------------- -- line 2423 ---------------------------------------- . fn any(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 102 ( 0.00%) if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE } . } . } . . self.try_fold((), check(f)) == ControlFlow::BREAK . } . . /// Searches for an element of an iterator that satisfies a predicate. . /// -- line 2439 ---------------------------------------- -- line 2475 ---------------------------------------- . /// . /// // we can still use `iter`, as there are more elements. . /// assert_eq!(iter.next(), Some(&3)); . /// ``` . /// . /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 8,977 ( 0.00%) fn find

(&mut self, predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { . #[inline] . fn check(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow { 31,604 ( 0.00%) move |(), x| { 281,369 ( 0.00%) if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE } 47,301 ( 0.00%) } 2,377 ( 0.00%) } . 129,112 ( 0.00%) self.try_fold((), check(predicate)).break_value() 4,754 ( 0.00%) } . . /// Applies function to the elements of iterator and returns . /// the first non-none result. . /// . /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`. . /// . /// # Examples . /// -- line 2504 ---------------------------------------- -- line 2506 ---------------------------------------- . /// let a = ["lol", "NaN", "2", "5"]; . /// . /// let first_number = a.iter().find_map(|s| s.parse().ok()); . /// . /// assert_eq!(first_number, Some(2)); . /// ``` . #[inline] . #[stable(feature = "iterator_find_map", since = "1.30.0")] 17,378 ( 0.00%) fn find_map(&mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { . #[inline] 3,872 ( 0.00%) fn check(mut f: impl FnMut(T) -> Option) -> impl FnMut((), T) -> ControlFlow { 318,028 ( 0.00%) move |(), x| match f(x) { 93,287 ( 0.00%) Some(x) => ControlFlow::Break(x), . None => ControlFlow::CONTINUE, 2,549 ( 0.00%) } 5,808 ( 0.00%) } . 20,911 ( 0.00%) self.try_fold((), check(f)).break_value() 3,872 ( 0.00%) } . . /// Applies function to the elements of iterator and returns . /// the first true result or the first error. . /// . /// The return type of this method depends on the return type of the closure. . /// If you return `Result` from the closure, you'll get a `Result; E>`. . /// If you return `Option` from the closure, you'll get an `Option>`. . /// -- line 2536 ---------------------------------------- -- line 2655 ---------------------------------------- . P: FnMut(Self::Item) -> bool, . { . #[inline] . fn check( . mut predicate: impl FnMut(T) -> bool, . ) -> impl FnMut(usize, T) -> ControlFlow { . #[rustc_inherit_overflow_checks] . move |i, x| { 1 ( 0.00%) if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) } . } . } . . self.try_fold(0, check(predicate)).break_value() . } . . /// Searches for an element in an iterator from the right, returning its . /// index. -- line 2671 ---------------------------------------- -- line 2812 ---------------------------------------- . /// # Examples . /// . /// ``` . /// let a = [-3_i32, 0, 1, 5, -10]; . /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10); . /// ``` . #[inline] . #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] 357 ( 0.00%) fn max_by_key(self, f: F) -> Option . where . Self: Sized, . F: FnMut(&Self::Item) -> B, . { . #[inline] . fn key(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { 660 ( 0.00%) move |x| (f(&x), x) . } . . #[inline] . fn compare((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { . x_p.cmp(y_p) . } . 1,086 ( 0.00%) let (_, x) = self.map(key(f)).max_by(compare)?; . Some(x) 408 ( 0.00%) } . . /// Returns the element that gives the maximum value with respect to the . /// specified comparison function. . /// . /// If several elements are equally maximum, the last element is . /// returned. If the iterator is empty, [`None`] is returned. . /// . /// # Examples -- line 2845 ---------------------------------------- -- line 2852 ---------------------------------------- . #[stable(feature = "iter_max_by", since = "1.15.0")] . fn max_by(self, compare: F) -> Option . where . Self: Sized, . F: FnMut(&Self::Item, &Self::Item) -> Ordering, . { . #[inline] . fn fold(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { 672 ( 0.00%) move |x, y| cmp::max_by(x, y, &mut compare) . } . 43,254 ( 0.00%) self.reduce(fold(compare)) . } . . /// Returns the element that gives the minimum value from the . /// specified function. . /// . /// If several elements are equally minimum, the first element is . /// returned. If the iterator is empty, [`None`] is returned. . /// -- line 2871 ---------------------------------------- -- line 2946 ---------------------------------------- . /// ``` . #[inline] . #[doc(alias = "reverse")] . #[stable(feature = "rust1", since = "1.0.0")] . fn rev(self) -> Rev . where . Self: Sized + DoubleEndedIterator, . { 13 ( 0.00%) Rev::new(self) . } . . /// Converts an iterator of pairs into a pair of containers. . /// . /// `unzip()` consumes an entire iterator of pairs, producing two . /// collections: one from the left elements of the pairs, and one . /// from the right elements. . /// -- line 2962 ---------------------------------------- -- line 2987 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . fn unzip(self) -> (FromA, FromB) . where . FromA: Default + Extend, . FromB: Default + Extend, . Self: Sized + Iterator, . { . let mut unzipped: (FromA, FromB) = Default::default(); 6,289 ( 0.00%) unzipped.extend(self); . unzipped . } . . /// Creates an iterator which copies all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// -- line 3003 ---------------------------------------- -- line 3017 ---------------------------------------- . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "iter_copied", since = "1.36.0")] . fn copied<'a, T: 'a>(self) -> Copied . where . Self: Sized + Iterator, . T: Copy, . { 159,041 ( 0.00%) Copied::new(self) . } . . /// Creates an iterator which [`clone`]s all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// . /// [`clone`]: Clone::clone -- line 3033 ---------------------------------------- -- line 3043 ---------------------------------------- . /// . /// // cloned is the same as .map(|&x| x), for integers . /// let v_map: Vec<_> = a.iter().map(|&x| x).collect(); . /// . /// assert_eq!(v_cloned, vec![1, 2, 3]); . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 195 ( 0.00%) fn cloned<'a, T: 'a>(self) -> Cloned . where . Self: Sized + Iterator, . T: Clone, . { 327,642 ( 0.00%) Cloned::new(self) 130 ( 0.00%) } . . /// Repeats an iterator endlessly. . /// . /// Instead of stopping at [`None`], the iterator will instead start again, . /// from the beginning. After iterating again, it will start at the . /// beginning again. And again. And again. Forever. Note that in case the . /// original iterator is empty, the resulting iterator will also be empty. . /// -- line 3065 ---------------------------------------- -- line 3313 ---------------------------------------- . /// . /// # Examples . /// . /// ``` . /// assert_eq!([1].iter().eq([1].iter()), true); . /// assert_eq!([1].iter().eq([1, 2].iter()), false); . /// ``` . #[stable(feature = "iter_order", since = "1.5.0")] 7 ( 0.00%) fn eq(self, other: I) -> bool . where . I: IntoIterator, . Self::Item: PartialEq, . Self: Sized, . { 8 ( 0.00%) self.eq_by(other, |x, y| x == y) 8 ( 0.00%) } . . /// Determines if the elements of this [`Iterator`] are equal to those of . /// another with respect to the specified equality function. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 3336 ---------------------------------------- -- line 3344 ---------------------------------------- . /// ``` . #[unstable(feature = "iter_order_by", issue = "64295")] . fn eq_by(mut self, other: I, mut eq: F) -> bool . where . Self: Sized, . I: IntoIterator, . F: FnMut(Self::Item, I::Item) -> bool, . { 10 ( 0.00%) let mut other = other.into_iter(); . . loop { 3 ( 0.00%) let x = match self.next() { . None => return other.next().is_none(), 11 ( 0.00%) Some(val) => val, . }; . 3 ( 0.00%) let y = match other.next() { . None => return false, . Some(val) => val, . }; . . if !eq(x, y) { . return false; . } . } -- line 3368 ---------------------------------------- -- line 3589 ---------------------------------------- . unreachable!("Always specialized"); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for &mut I { . type Item = I::Item; . #[inline] 78 ( 0.00%) fn next(&mut self) -> Option { 339,193 ( 0.00%) (**self).next() 117 ( 0.00%) } . fn size_hint(&self) -> (usize, Option) { 2 ( 0.00%) (**self).size_hint() . } . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . (**self).advance_by(n) . } . fn nth(&mut self, n: usize) -> Option { . (**self).nth(n) . } . } -- line 3609 ---------------------------------------- 4,521,295 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 36,609 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 11,019 ( 0.00%) self.file = file; 13,026 ( 0.00%) self.file_index = file_idx; . } . 27,568 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 71,166 ( 0.00%) self.line_number = line_index + 1; 107,738 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 656,785 ( 0.00%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 22,746 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 11,373 ( 0.00%) let first_file = files[0].clone(); . let entry = CacheEntry { . time_stamp: 0, . line_number: 0, . line: BytePos(0)..BytePos(0), . file: first_file, . file_index: 0, . }; . 56,865 ( 0.00%) CachingSourceMapView { . source_map, 79,611 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 45,492 ( 0.00%) } . . pub fn byte_pos_to_line_and_col( . &mut self, . pos: BytePos, . ) -> Option<(Lrc, usize, BytePos)> { . self.time_stamp += 1; . . // Check if the position is in one of the cached lines -- line 85 ---------------------------------------- -- line 106 ---------------------------------------- . }; . . let cache_entry = &mut self.line_cache[oldest]; . cache_entry.update(new_file_and_idx, pos, self.time_stamp); . . Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start)) . } . 2,412,774 ( 0.02%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 1,378,728 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 344,682 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 344,682 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 625,054 ( 0.00%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 624,206 ( 0.00%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 1,872,618 ( 0.01%) if lo.file_index != hi.file_index { . return None; . } . . ( 624,206 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 312,103 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 312,103 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 312,103 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 1,248,412 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 64,310 ( 0.00%) let oldest = if lo_cache_idx != -1 || hi_cache_idx != -1 { . let avoid_idx = if lo_cache_idx != -1 { lo_cache_idx } else { hi_cache_idx }; . self.oldest_cache_entry_index_avoid(avoid_idx as usize) . } else { . self.oldest_cache_entry_index() . }; . . // If the entry doesn't point to the correct file, get the new file and index. . // Return early if the file containing beginning of span doesn't contain end of span. 253,916 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 25,055 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 30,066 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 20,044 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 82,704 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 82,704 ( 0.00%) None . }; . . // Update the cache entries. 162,895 ( 0.00%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 90,420 ( 0.00%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 848 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 1,272 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 2,015 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 4,030 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 8,060 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 65,158 ( 0.00%) assert!(span_data.lo >= lo.line.start); 32,579 ( 0.00%) assert!(span_data.lo <= lo.line.end); 65,158 ( 0.00%) assert!(span_data.hi >= hi.line.start); 32,579 ( 0.00%) assert!(span_data.hi <= hi.line.end); 162,895 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 97,737 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 97,737 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 97,737 ( 0.00%) Some(( 32,579 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 32,579 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 3,102,138 ( 0.02%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 3,182,072 ( 0.02%) if cache_entry.line.contains(&pos) { . return idx as isize; . } . } . . -1 . } . . fn oldest_cache_entry_index(&self) -> usize { . let mut oldest = 0; . . for idx in 1..self.line_cache.len() { 180,840 ( 0.00%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 32,027 ( 0.00%) if idx != avoid_idx 17,581 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 25,055 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 5,011 ( 0.00%) if !self.source_map.files().is_empty() { 10,022 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 40,088 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 25,055 ( 0.00%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 4,082,385 ( 0.03%) -------------------------------------------------------------------------------- -- 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. 308 ( 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")] 3 ( 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")] 6,876 ( 0.00%) pub const fn is_ok(&self) -> bool { 20,687 ( 0.00%) matches!(*self, Ok(_)) 17,190 ( 0.00%) } . . /// Returns `true` if the result is [`Ok`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] . /// -- line 551 ---------------------------------------- -- line 577 ---------------------------------------- . /// . /// let x: Result = Err("Some error message"); . /// assert_eq!(x.is_err(), true); . /// ``` . #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"] . #[rustc_const_stable(feature = "const_result", since = "1.48.0")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 422 ( 0.00%) pub const fn is_err(&self) -> bool { 633 ( 0.00%) !self.is_ok() 844 ( 0.00%) } . . /// Returns `true` if the result is [`Err`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] . /// use std::io::{Error, ErrorKind}; -- line 595 ---------------------------------------- -- 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")] 24 ( 0.00%) pub fn ok(self) -> Option { 237,331 ( 0.00%) match self { 473,089 ( 0.00%) Ok(x) => Some(x), 12 ( 0.00%) Err(_) => None, . } 109 ( 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> { 3,635 ( 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")] 30,083 ( 0.00%) pub fn map U>(self, op: F) -> Result { 1,122,582 ( 0.01%) match self { 1,186,851 ( 0.01%) Ok(t) => Ok(op(t)), 349,027 ( 0.00%) Err(e) => Err(e), . } 37,605 ( 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 { 3,077 ( 0.00%) match self { 1,266 ( 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")] 2,432,861 ( 0.02%) pub fn map_err F>(self, op: O) -> Result { 11,042,281 ( 0.07%) match self { 11,486,859 ( 0.07%) Ok(t) => Ok(t), 8,787 ( 0.00%) Err(e) => Err(op(e)), . } 2,320,551 ( 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")] 543,624 ( 0.00%) pub fn expect(self, msg: &str) -> T . where . E: fmt::Debug, . { 4,225,081 ( 0.03%) match self { 401,155 ( 0.00%) Ok(t) => t, . Err(e) => unwrap_failed(msg, &e), . } 127,026 ( 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")] 4,057 ( 0.00%) pub fn unwrap(self) -> T . where . E: fmt::Debug, . { 740,966 ( 0.00%) match self { 438,768 ( 0.00%) Ok(t) => t, . Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), . } 3,791 ( 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, . { 15,198 ( 0.00%) match self { 8,968 ( 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, . { 1,000 ( 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,922,615 ( 0.01%) 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 { 61,852 ( 0.00%) match self { 109,889 ( 0.00%) Ok(t) => op(t), 16,536 ( 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 { 35,608 ( 0.00%) match self { 95,466 ( 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 { 194 ( 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")] 18,152 ( 0.00%) pub fn unwrap_or_else T>(self, op: F) -> T { 5,381,514 ( 0.03%) match self { 724,522 ( 0.00%) Ok(t) => t, . Err(e) => op(e), . } 54,001 ( 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> { 1,230 ( 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] 59,777 ( 0.00%) fn clone(&self) -> Self { 888,759 ( 0.01%) match self { 330,426 ( 0.00%) Ok(x) => Ok(x.clone()), 117,616 ( 0.00%) Err(x) => Err(x.clone()), . } 126,898 ( 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 2007 ---------------------------------------- . /// }).collect(); . /// assert_eq!(res, Err("Underflow!")); . /// assert_eq!(shared, 6); . /// ``` . /// . /// 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] 585 ( 0.00%) fn from_iter>>(iter: I) -> Result { . // FIXME(#11084): This could be replaced with Iterator::scan when this . // performance bug is closed. . 12,428 ( 0.00%) iter::process_results(iter.into_iter(), |i| i.collect()) 390 ( 0.00%) } . } . . #[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 { 6,920 ( 0.00%) Ok(output) . } . . #[inline] 4,109,882 ( 0.03%) fn branch(self) -> ControlFlow { 12,342,897 ( 0.08%) match self { 16,498,855 ( 0.10%) Ok(v) => ControlFlow::Continue(v), 1,167,777 ( 0.01%) Err(e) => ControlFlow::Break(Err(e)), . } 3,034,156 ( 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] 20,748 ( 0.00%) fn from_residual(residual: Result) -> Self { . match residual { 753,968 ( 0.00%) Err(e) => Err(From::from(e)), . } 13,832 ( 0.00%) } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Result { . type TryType = Result; . } 9,658,048 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs -------------------------------------------------------------------------------- Ir -- line 165 ---------------------------------------- . #[rustc_insignificant_dtor] . pub struct BTreeMap { . root: Option>, . length: usize, . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap { 1,181,437 ( 0.01%) fn drop(&mut self) { . drop(unsafe { ptr::read(self) }.into_iter()) 1,241,661 ( 0.01%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for BTreeMap { . fn clone(&self) -> BTreeMap { 42 ( 0.00%) fn clone_subtree<'a, K: Clone, V: Clone>( . node: NodeRef, K, V, marker::LeafOrInternal>, . ) -> BTreeMap . where . K: 'a, . V: 'a, . { 5 ( 0.00%) match node.force() { . Leaf(leaf) => { 15 ( 0.00%) let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 }; . . { . let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped . let mut out_node = match root.borrow_mut().force() { . Leaf(leaf) => leaf, . Internal(_) => unreachable!(), . }; . . let mut in_edge = leaf.first_edge(); . while let Ok(kv) = in_edge.right_kv() { . let (k, v) = kv.into_kv(); . in_edge = kv.right_edge(); . 16 ( 0.00%) out_node.push(k.clone(), v.clone()); 42 ( 0.00%) out_tree.length += 1; . } . } . 23 ( 0.00%) out_tree . } . Internal(internal) => { . let mut out_tree = clone_subtree(internal.first_edge().descend()); . . { . let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root); . let mut out_node = out_root.push_internal_level(); . let mut in_edge = internal.first_edge(); -- line 217 ---------------------------------------- -- line 235 ---------------------------------------- . out_node.push(k, v, subroot.unwrap_or_else(Root::new)); . out_tree.length += 1 + sublength; . } . } . . out_tree . } . } 40 ( 0.00%) } . 6 ( 0.00%) if self.is_empty() { . BTreeMap::new() . } else { 14 ( 0.00%) clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty . } . } . } . . impl super::Recover for BTreeMap . where . K: Borrow + Ord, . Q: Ord, -- line 256 ---------------------------------------- -- line 515 ---------------------------------------- . /// . /// // entries can now be inserted into the empty map . /// map.insert(1, "a"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . #[must_use] . pub const fn new() -> BTreeMap { 640,900 ( 0.00%) BTreeMap { root: None, length: 0 } . } . . /// Clears the map, removing all elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 531 ---------------------------------------- -- line 560 ---------------------------------------- . /// assert_eq!(map.get(&2), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, key: &Q) -> Option<&V> . where . K: Borrow + Ord, . Q: Ord, . { 1,084,185 ( 0.01%) let root_node = self.root.as_ref()?.reborrow(); 4,785,859 ( 0.03%) match root_node.search_tree(key) { 12,512 ( 0.00%) Found(handle) => Some(handle.into_kv().1), . GoDown(_) => 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 the ordering . /// on the borrowed form *must* match the ordering on the key type. -- line 578 ---------------------------------------- -- line 814 ---------------------------------------- . /// ``` . // See `get` for implementation notes, this is basically a copy-paste with mut's added . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> . where . K: Borrow + Ord, . Q: Ord, . { 576,553 ( 0.00%) let root_node = self.root.as_mut()?.borrow_mut(); 4,035,871 ( 0.03%) match root_node.search_tree(key) { . Found(handle) => Some(handle.into_val_mut()), . GoDown(_) => None, . } . } . . /// Inserts a key-value pair into the map. . /// . /// If the map did not have this key present, `None` is returned. -- line 831 ---------------------------------------- -- line 848 ---------------------------------------- . /// 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"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 8,524,782 ( 0.05%) pub fn insert(&mut self, key: K, value: V) -> Option . where . K: Ord, . { 456 ( 0.00%) match self.entry(key) { . Occupied(mut entry) => Some(entry.insert(value)), . Vacant(entry) => { 10,708,581 ( 0.07%) entry.insert(value); 293,821 ( 0.00%) None . } . } 7,491,750 ( 0.05%) } . . /// Tries to insert a key-value pair into the map, and returns . /// a mutable reference to the value in the entry. . /// . /// If the map already had this key present, nothing is updated, and . /// an error containing the occupied entry and the value is returned. . /// . /// # Examples -- line 875 ---------------------------------------- -- line 914 ---------------------------------------- . /// use std::collections::BTreeMap; . /// . /// let mut map = BTreeMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,560,172 ( 0.01%) pub fn remove(&mut self, key: &Q) -> Option . where . K: Borrow + Ord, . Q: Ord, . { 2,178,541 ( 0.01%) self.remove_entry(key).map(|(_, v)| v) 1,849,789 ( 0.01%) } . . /// 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 the ordering . /// on the borrowed form *must* match the ordering on the key type. . /// . /// # Examples -- line 936 ---------------------------------------- -- line 947 ---------------------------------------- . /// ``` . #[stable(feature = "btreemap_remove_entry", since = "1.45.0")] . pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> . where . K: Borrow + Ord, . Q: Ord, . { . let (map, dormant_map) = DormantMutRef::new(self); 1,039,660 ( 0.01%) let root_node = map.root.as_mut()?.borrow_mut(); 2,743,458 ( 0.02%) match root_node.search_tree(key) { . Found(handle) => { 8,164,635 ( 0.05%) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) 206,872 ( 0.00%) } . GoDown(_) => None, . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. . /// The elements are visited in ascending key order. -- line 967 ---------------------------------------- -- line 1135 ---------------------------------------- . /// // count the number of occurrences of letters in the vec . /// for x in ["a", "b", "a", "c", "a", "b"] { . /// *count.entry(x).or_insert(0) += 1; . /// } . /// . /// assert_eq!(count["a"], 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 10 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V> . where . K: Ord, . { . // FIXME(@porglezomp) Avoid allocating if we don't insert . let (map, dormant_map) = DormantMutRef::new(self); . let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); 403,817 ( 0.00%) match root_node.search_tree(&key) { 8,056 ( 0.00%) Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), . GoDown(handle) => { 99,522 ( 0.00%) Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }) . } . } 9 ( 0.00%) } . . /// Splits the collection into two at the given key. Returns everything after the given key, . /// including the key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1164 ---------------------------------------- -- line 1307 ---------------------------------------- . } . . /// Makes a `BTreeMap` from a sorted iterator. . pub(crate) fn bulk_build_from_sorted_iter(iter: I) -> Self . where . K: Ord, . I: IntoIterator, . { 2 ( 0.00%) let mut root = Root::new(); 1 ( 0.00%) let mut length = 0; 5 ( 0.00%) root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length); 2 ( 0.00%) BTreeMap { root: Some(root), length } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> IntoIterator for &'a BTreeMap { . type Item = (&'a K, &'a V); . type IntoIter = Iter<'a, K, V>; . -- line 1326 ---------------------------------------- -- line 1328 ---------------------------------------- . self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . 12 ( 0.00%) fn next(&mut self) -> Option<(&'a K, &'a V)> { 580,048 ( 0.00%) if self.length == 0 { . None . } else { 231,387 ( 0.00%) self.length -= 1; . Some(unsafe { self.range.next_unchecked() }) . } 19 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . (self.length, Some(self.length)) . } . . fn last(mut self) -> Option<(&'a K, &'a V)> { . self.next_back() . } -- line 1351 ---------------------------------------- -- line 1460 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for BTreeMap { . type Item = (K, V); . type IntoIter = IntoIter; . . fn into_iter(self) -> IntoIter { . let mut me = ManuallyDrop::new(self); 491,148 ( 0.00%) if let Some(root) = me.root.take() { . let full_range = root.into_dying().full_range(); . 6 ( 0.00%) IntoIter { range: full_range, length: me.length } . } else { 541,320 ( 0.00%) IntoIter { range: LazyLeafRange::none(), length: 0 } . } . } . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . impl Drop for IntoIter { 30,392 ( 0.00%) fn drop(&mut self) { . struct DropGuard<'a, K, V>(&'a mut IntoIter); . . impl<'a, K, V> Drop for DropGuard<'a, K, V> { . fn drop(&mut self) { . // Continue the same loop we perform below. This only runs when unwinding, so we . // don't have to care about panics this time (they'll abort). . while let Some(kv) = self.0.dying_next() { . // SAFETY: we consume the dying handle immediately. . unsafe { kv.drop_key_val() }; . } . } . } . 675,588 ( 0.00%) while let Some(kv) = self.dying_next() { . let guard = DropGuard(self); . // SAFETY: we don't touch the tree before consuming the dying handle. 33,736 ( 0.00%) unsafe { kv.drop_key_val() }; . mem::forget(guard); . } 30,392 ( 0.00%) } . } . . impl IntoIter { . /// Core of a `next` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. 775,692 ( 0.00%) fn dying_next( . &mut self, . ) -> Option, marker::KV>> { 939,882 ( 0.01%) if self.length == 0 { . self.range.deallocating_end(); 154,016 ( 0.00%) None . } else { 248,748 ( 0.00%) self.length -= 1; 139,083 ( 0.00%) Some(unsafe { self.range.deallocating_next_unchecked() }) . } 775,688 ( 0.00%) } . . /// Core of a `next_back` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. . fn dying_next_back( . &mut self, . ) -> Option, marker::KV>> { . if self.length == 0 { . self.range.deallocating_end(); -- line 1524 ---------------------------------------- -- line 1529 ---------------------------------------- . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = (K, V); . 6,671 ( 0.00%) fn next(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next().map(unsafe { |kv| kv.into_key_val() }) 7,624 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { 819 ( 0.00%) (self.length, Some(self.length)) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . fn next_back(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next_back().map(unsafe { |kv| kv.into_key_val() }) -- line 1551 ---------------------------------------- -- line 1562 ---------------------------------------- . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for IntoIter {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . fn next(&mut self) -> Option<&'a K> { 10 ( 0.00%) self.inner.next().map(|(k, _)| k) . } . . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . . fn last(mut self) -> Option<&'a K> { . self.next_back() -- line 1578 ---------------------------------------- -- line 2089 ---------------------------------------- . /// println!("{}: {}", key, value); . /// } . /// . /// let (first_key, first_value) = map.iter().next().unwrap(); . /// assert_eq!((*first_key, *first_value), (1, "a")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn iter(&self) -> Iter<'_, K, V> { 811,936 ( 0.01%) if let Some(root) = &self.root { . let full_range = root.reborrow().full_range(); . 15 ( 0.00%) Iter { range: full_range, length: self.length } . } else { 6 ( 0.00%) Iter { range: LazyLeafRange::none(), length: 0 } . } . } . . /// Gets a mutable iterator over the entries of the map, sorted by key. . /// . /// # Examples . /// . /// Basic usage: -- line 2110 ---------------------------------------- -- line 2149 ---------------------------------------- . /// a.insert(2, "b"); . /// a.insert(1, "a"); . /// . /// let keys: Vec<_> = a.keys().cloned().collect(); . /// assert_eq!(keys, [1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn keys(&self) -> Keys<'_, K, V> { 7,719 ( 0.00%) Keys { inner: self.iter() } . } . . /// Gets an iterator over the values of the map, in order by key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2165 ---------------------------------------- -- line 2217 ---------------------------------------- . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn len(&self) -> usize { 3 ( 0.00%) self.length . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2233 ---------------------------------------- -- line 2238 ---------------------------------------- . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn is_empty(&self) -> bool { 76,114 ( 0.00%) self.len() == 0 . } . . /// If the root node is the empty (non-allocated) root node, allocate our . /// own node. Is an associated function to avoid borrowing the entire BTreeMap. . fn ensure_is_owned(root: &mut Option>) -> &mut Root { . root.get_or_insert_with(Root::new) . } . } -- line 2254 ---------------------------------------- 3,420,994 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 3,938,713 ( 0.02%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 585 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,096 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { . LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate -- line 173 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 2,765 ( 0.00%) self.remapped_path_if_available().hash(state) . } . } . . // This is functionally identical to #[derive(Encodable)], with the exception of . // an added assert statement . impl Encodable for RealFileName { . fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 2 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 8 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 213 ---------------------------------------- . } . } . . impl RealFileName { . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. . pub fn local_path(&self) -> Option<&Path> { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => { . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 48,920 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 2 ( 0.00%) } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. Otherwise returns the remapped name. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. . pub fn local_path_if_available(&self) -> &Path { 1 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . 20,144 ( 0.00%) pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 33,429 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } 30,216 ( 0.00%) } . } . . /// Differentiates between real files and common virtual files. 331,753 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,634 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. . QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) . MacroExpansion(u64), 8,138 ( 0.00%) ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), . /// Strings provided as crate attributes in the CLI. . CliCrateAttr(u64), . /// Custom sources for explicit parser calls from plugins and drivers. . Custom(String), . DocTest(PathBuf, isize), . /// Post-substitution inline assembly from LLVM. . InlineAsm(u64), . } . . impl From for FileName { 7 ( 0.00%) fn from(p: PathBuf) -> Self { 2 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 6 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 7 ( 0.00%) } . } . 34 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] . pub enum FileNameDisplayPreference { . Remapped, . Local, . } . . pub struct FileNameDisplay<'a> { . inner: &'a FileName, . display_pref: FileNameDisplayPreference, . } . . impl fmt::Display for FileNameDisplay<'_> { 49,548 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 74,322 ( 0.00%) match *self.inner { . Real(ref name) => { 74,322 ( 0.00%) write!(fmt, "{}", name.to_string_lossy(self.display_pref)) . } . QuoteExpansion(_) => write!(fmt, ""), . MacroExpansion(_) => write!(fmt, ""), . Anon(_) => write!(fmt, ""), . ProcMacroSourceCode(_) => write!(fmt, ""), . CfgSpec(_) => write!(fmt, ""), . CliCrateAttr(_) => write!(fmt, ""), . Custom(ref s) => write!(fmt, "<{}>", s), . DocTest(ref path, _) => write!(fmt, "{}", path.display()), . InlineAsm(_) => write!(fmt, ""), . } 61,935 ( 0.00%) } . } . . impl FileNameDisplay<'_> { 3,592 ( 0.00%) pub fn to_string_lossy(&self) -> Cow<'_, str> { 2,694 ( 0.00%) match self.inner { 898 ( 0.00%) FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } 3,592 ( 0.00%) } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 25,836 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) . | DocTest(_, _) . | InlineAsm(_) => false, . } . } . 13,266 ( 0.00%) pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } 26,532 ( 0.00%) } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 1 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 2 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . . pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); -- line 375 ---------------------------------------- -- line 377 ---------------------------------------- . } . . pub fn anon_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::Anon(hasher.finish()) . } . 40,690 ( 0.00%) pub fn proc_macro_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 16,276 ( 0.00%) FileName::ProcMacroSourceCode(hasher.finish()) 40,690 ( 0.00%) } . . pub fn cfg_spec_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::QuoteExpansion(hasher.finish()) . } . . pub fn cli_crate_attr_source_code(src: &str) -> FileName { -- line 397 ---------------------------------------- -- line 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 3 ( 0.00%) pub lo: BytePos, 3 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 9 ( 0.00%) pub ctxt: SyntaxContext, 3 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 1,297,809 ( 0.01%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 1,728 ( 0.00%) self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 298,288 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 223,716 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 298,288 ( 0.00%) } . } . impl Ord for Span { . fn cmp(&self, rhs: &Self) -> Ordering { . Ord::cmp(&self.data(), &rhs.data()) . } . } . . /// A collection of `Span`s. -- line 520 ---------------------------------------- -- line 532 ---------------------------------------- . } . . impl Span { . #[inline] . pub fn lo(self) -> BytePos { . self.data().lo . } . #[inline] 208,242 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 138,828 ( 0.00%) } . #[inline] 80,012 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 80,012 ( 0.00%) } . #[inline] 208,773 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 139,182 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 52,885 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 31,731 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] 603 ( 0.00%) pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) 402 ( 0.00%) } . . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { . self.data_untracked().is_dummy() . } . . /// Returns `true` if this span comes from a macro or desugaring. -- line 574 ---------------------------------------- -- line 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 87 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 58 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 5,184 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 3,456 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 663 ---------------------------------------- . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 2,120 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 1,060 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 2,332 ( 0.00%) } . . /// Edition of the crate from which this span came. 104,430 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 69,620 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 27,478 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 2,666 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 4,573 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 8,185 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 1,637 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 6,548 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 94,080 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 80,640 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 67,200 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 65 ( 0.00%) pub fn desugaring_kind(self) -> Option { 78 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 52 ( 0.00%) } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). 6,804 ( 0.00%) pub fn allows_unsafe(self) -> bool { 1,701 ( 0.00%) self.ctxt().outer_expn_data().allow_internal_unsafe 6,804 ( 0.00%) } . . pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { . let expn_data = self.ctxt().outer_expn_data(); . if expn_data.is_root() { . return None; -- line 752 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 3,900,259 ( 0.02%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 703,864 ( 0.00%) if span_data.ctxt != end_data.ctxt { 5,274 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 3,860 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 2,448,586 ( 0.02%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 3,191,121 ( 0.02%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 19,349 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 12,313 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 14,072 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 60,159 ( 0.00%) pub fn until(self, end: Span) -> Span { . // Most of this function's body is copied from `to`. . // We can't just do `self.to(end.shrink_to_lo())`, . // because to also does some magic where it uses min/max so . // it can handle overlapping spans. Some advanced mis-use of . // `until` with different ctxts makes this visible. . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 8,239 ( 0.00%) if span_data.ctxt != end_data.ctxt { 2,699 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 737 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 24,549 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 49,221 ( 0.00%) } . . pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) . } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 3,264 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 1,590 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { 130 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 29,904 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 17,444 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 253,566 ( 0.00%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { . let mut span = self.data(); . let mark = span.ctxt.remove_mark(); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark -- line 897 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 274,005 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 182,670 ( 0.00%) let mut span = self.data(); 148,503 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 274,005 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 300,728 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { 1,932 ( 0.00%) let mut span = self.data(); 2,898 ( 0.00%) let mark = span.ctxt.glob_adjust(expn_id, glob_span); 7,728 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 5,184 ( 0.00%) pub fn reverse_glob_adjust( . &mut self, . expn_id: ExpnId, . glob_span: Span, . ) -> Option> { 15,950 ( 0.00%) let mut span = self.data(); 27,868 ( 0.00%) let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); 55,160 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 5,760 ( 0.00%) } . . #[inline] 336,928 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) 294,812 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1048 ---------------------------------------- . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . . pub fn from_span(primary_span: Span) -> MultiSpan { 96,145 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 280 ( 0.00%) MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 16,979 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans 208 ( 0.00%) } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { . self.primary_spans.iter().any(|sp| !sp.is_dummy()) . } . . /// Returns `true` if this contains only a dummy primary span with any hygienic context. . pub fn is_dummy(&self) -> bool { -- line 1084 ---------------------------------------- -- line 1139 ---------------------------------------- . . /// Returns `true` if any of the span labels is displayable. . pub fn has_span_labels(&self) -> bool { . self.span_labels.iter().any(|(sp, _)| !sp.is_dummy()) . } . } . . impl From for MultiSpan { 96,145 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 96,145 ( 0.00%) } . } . . impl From> for MultiSpan { 280 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 224 ( 0.00%) MultiSpan::from_spans(spans) 280 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 341 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 312 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } -- line 1176 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 540 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 156 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 540 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 468 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 3 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 1,178 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,114 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 6 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,228 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { 1 ( 0.00%) let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 30 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } . hash . } . . /// Check if the stored hash matches the hash of the string. . pub fn matches(&self, src: &str) -> bool { 1 ( 0.00%) Self::new(self.kind, src) == *self . } . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { 108 ( 0.00%) let len = self.hash_len(); 108 ( 0.00%) &self.value[..len] 108 ( 0.00%) } . . fn hash_len(&self) -> usize { 245 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 58 ( 0.00%) #[derive(Clone)] . pub struct SourceFile { . /// The name of the file that the source came from. Source that doesn't . /// originate from files has names between angle brackets by convention . /// (e.g., ``). . pub name: FileName, . /// The complete source code. 1 ( 0.00%) pub src: Option>, . /// The source code's hash. . pub src_hash: SourceFileHash, . /// The external source code (used for external crates, which will have a `None` . /// value as `self.src`. . pub external_src: Lock, . /// The start position of this source in the `SourceMap`. . pub start_pos: BytePos, . /// The end position of this source in the `SourceMap`. -- line 1361 ---------------------------------------- -- line 1364 ---------------------------------------- . pub lines: Vec, . /// Locations of multi-byte characters in the source code. . pub multibyte_chars: Vec, . /// Width of characters that are not narrow in the source code. . pub non_narrow_chars: Vec, . /// Locations of characters removed during normalization. . pub normalized_pos: Vec, . /// A hash of the filename, used for speeding up hashing in incremental compilation. 1 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 1 ( 0.00%) pub cnum: CrateNum, . } . . impl Encodable for SourceFile { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_struct(false, |s| { . s.emit_struct_field("name", true, |s| self.name.encode(s))?; . s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?; . s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?; . s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?; . s.emit_struct_field("lines", false, |s| { . let lines = &self.lines[..]; . // Store the length. . s.emit_u32(lines.len() as u32)?; . 4 ( 0.00%) if !lines.is_empty() { . // In order to preserve some space, we exploit the fact that . // the lines list is sorted and individual lines are . // probably not that long. Because of that we can store lines . // as a difference list, using as little space as possible . // for the differences. . let max_line_length = if lines.len() == 1 { . 0 . } else { -- line 1397 ---------------------------------------- -- line 1399 ---------------------------------------- . .array_windows() . .map(|&[fst, snd]| snd - fst) . .map(|bp| bp.to_usize()) . .max() . .unwrap() . }; . . let bytes_per_diff: u8 = match max_line_length { 2 ( 0.00%) 0..=0xFF => 1, . 0x100..=0xFFFF => 2, . _ => 4, . }; . . // Encode the number of bytes used per diff. . bytes_per_diff.encode(s)?; . . // Encode the first element. . lines[0].encode(s)?; . . let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); . 2 ( 0.00%) match bytes_per_diff { . 1 => { . for diff in diff_iter { . (diff.0 as u8).encode(s)? . } . } . 2 => { . for diff in diff_iter { . (diff.0 as u16).encode(s)? -- line 1428 ---------------------------------------- -- line 1436 ---------------------------------------- . _ => unreachable!(), . } . } . . Ok(()) . })?; . s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?; . s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?; 3 ( 0.00%) s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?; . s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?; 11 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 5,013 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 557 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 901,124 ( 0.01%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,114 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 6,127 ( 0.00%) SourceFile { 4,456 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,228 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,228 ( 0.00%) lines, 2,228 ( 0.00%) multibyte_chars, 2,228 ( 0.00%) non_narrow_chars, 2,228 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 5,013 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 99 ( 0.00%) pub fn new( . name: FileName, . mut src: String, . start_pos: BytePos, . hash_kind: SourceFileHashAlgorithm, . ) -> Self { . // Compute the file hash before any normalization. . let src_hash = SourceFileHash::new(hash_kind, &src); 27 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 18 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 18 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 27 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 108 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 18 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 153 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 99 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 36 ( 0.00%) lines, 36 ( 0.00%) multibyte_chars, 36 ( 0.00%) non_narrow_chars, 36 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 81 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. 95,026 ( 0.00%) pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); 47,513 ( 0.00%) self.lines[line_index] 95,026 ( 0.00%) } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 20,118 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 2,876 ( 0.00%) if matches!( 5,748 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { 1 ( 0.00%) let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it 3 ( 0.00%) if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src . { 5 ( 0.00%) if let Some(mut src) = src { . // The src_hash needs to be computed on the pre-normalized src. 1 ( 0.00%) if self.src_hash.matches(&src) { 3 ( 0.00%) normalize_src(&mut src, BytePos::from_usize(0)); 8 ( 0.00%) *src_kind = ExternalSourceKind::Present(Lrc::new(src)); . return true; . } . } else { . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 2,873 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 25,866 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. . pub fn get_line(&self, line_number: usize) -> Option> { . fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. -- line 1610 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 12,918 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 117,110 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 107,758 ( 0.00%) match self.lines.binary_search(&pos) { . Ok(idx) => Some(idx), . Err(0) => None, . Err(idx) => Some(idx - 1), . } . } . . pub fn line_bounds(&self, line_index: usize) -> Range { 109,753 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 73,181 ( 0.00%) assert!(line_index < self.lines.len()); 106,749 ( 0.00%) if line_index == (self.lines.len() - 1) { 6 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 71,162 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 3,310 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 9,930 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 167,972 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 496,440 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 413,700 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 19,860 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 16,550 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 6,620 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 11,585 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 3,310 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 977 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 1,655 ( 0.00%) let linebpos = self.lines[a]; 3,310 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 1,655 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 13,240 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 13,240 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 4,965 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 3,310 ( 0.00%) if line > 0 { . let col = col_or_chpos; 1,655 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); 6 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 8,275 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 11,585 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 100 ( 0.00%) fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec { . let mut normalized_pos = vec![]; . remove_bom(src, &mut normalized_pos); . normalize_newlines(src, &mut normalized_pos); . . // Offset all the positions by start_pos to match the final file positions. . for np in &mut normalized_pos { . np.pos.0 += start_pos.0; . } . . normalized_pos 90 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 9 ( 0.00%) if src.starts_with('\u{feff}') { . src.drain(..3); . normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); . } . } . . /// Replaces `\r\n` with `\n` in-place in `src`. . /// . /// Returns error if there's a lone `\r` in the string. . fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec) { 10 ( 0.00%) if !src.as_bytes().contains(&b'\r') { . return; . } . . // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. . // While we *can* call `as_mut_vec` and do surgery on the live string . // directly, let's rather steal the contents of `src`. This makes the code . // safe even if a panic occurs. . -- line 1816 ---------------------------------------- -- line 1877 ---------------------------------------- . ( . $( . $(#[$attr:meta])* . $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); . )* . ) => { . $( . $(#[$attr])* 169,219 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 4,577 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 134,647 ( 0.00%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 3,580,287 ( 0.02%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 4,982,517 ( 0.03%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1946 ---------------------------------------- . impl Encodable for BytePos { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) . } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 1,930,744 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 2,437,470 ( 0.02%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 449,015 ( 0.00%) if !ctx.hash_spans() { . return; . } . 1,988,455 ( 0.01%) let span = self.data_untracked(); 742,219 ( 0.00%) span.ctxt.hash_stable(ctx, hasher); 1,044,630 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 699,948 ( 0.00%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 689,364 ( 0.00%) if let Some(parent) = span.parent { . let def_span = ctx.def_span(parent).data_untracked(); . if def_span.contains(span) { . // This span is enclosed in a definition: only hash the relative position. . Hash::hash(&TAG_RELATIVE_SPAN, hasher); . (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); . (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); . return; . } . } . . // If this is not an empty or invalid span, we want to hash the last . // position that belongs to it, as opposed to hashing the first . // position past it. 1,378,728 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 689,364 ( 0.00%) Some(pos) => pos, . None => { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . }; . . Hash::hash(&TAG_VALID_SPAN, hasher); . // We truncate the stable ID hash and line and column numbers. The chances -- line 2129 ---------------------------------------- -- line 2134 ---------------------------------------- . // hash only the length, for example, then two otherwise equal spans with . // different end locations will have the same hash. This can cause a problem . // during incremental compilation wherein a previous result for a query that . // depends on the end location of a span will be incorrectly reused when the . // end location of the span it depends on has changed (see issue #74890). A . // similar analysis applies if some query depends specifically on the length . // of the span, but we only hash the end location. So hash both. . 344,682 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 344,682 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 2,785,680 ( 0.02%) } . } 7,764,774 ( 0.05%) -------------------------------------------------------------------------------- -- 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")] 221,275 ( 0.00%) pub const fn forget(t: T) { 4,095 ( 0.00%) let _ = ManuallyDrop::new(t); 89,628 ( 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")] 661,490 ( 0.00%) pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 948,309 ( 0.01%) unsafe { intrinsics::size_of_val(val) } 451,562 ( 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)] 33,935 ( 0.00%) pub const fn align_of_val(val: &T) -> usize { . // SAFETY: val is a reference, so it's a valid raw pointer 49,788 ( 0.00%) unsafe { intrinsics::min_align_of_val(val) } 33,192 ( 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"] 121 ( 0.00%) pub const fn needs_drop() -> bool { 363 ( 0.00%) intrinsics::needs_drop::() 484 ( 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 694 ---------------------------------------- . /// mem::swap(&mut x, &mut y); . /// . /// assert_eq!(42, x); . /// assert_eq!(5, y); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 192 ( 0.00%) pub const fn swap(x: &mut T, y: &mut T) { . // SAFETY: the raw pointers have been created from safe mutable references satisfying all the . // constraints on `ptr::swap_nonoverlapping_one` . unsafe { 64 ( 0.00%) ptr::swap_nonoverlapping_one(x, y); . } 128 ( 0.00%) } . . /// Replaces `dest` with the default value of `T`, returning the previous `dest` value. . /// . /// * If you want to replace the values of two variables, see [`swap`]. . /// * If you want to replace with a passed value instead of the default value, see [`replace`]. . /// . /// # Examples . /// -- line 716 ---------------------------------------- -- 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,950 ( 0.00%) pub fn take(dest: &mut T) -> T { 1,560 ( 0.00%) replace(dest, T::default()) 780 ( 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")] 8,362,369 ( 0.05%) 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 { 9,972,929 ( 0.06%) let result = ptr::read(dest); 103,704,896 ( 0.66%) ptr::write(dest, src); . result . } 3,035,587 ( 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")] 1,160,950 ( 0.01%) 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")] 975 ( 0.00%) pub const unsafe fn transmute_copy(src: &T) -> U { . // If U has a higher alignment requirement, src might not be suitably aligned. 390 ( 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. 390 ( 0.00%) unsafe { ptr::read(src as *const T as *const U) } . } 390 ( 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 { 6,480 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 11,814 ( 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 { 131,151 ( 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 ---------------------------------------- 4,496,526 ( 0.03%) -------------------------------------------------------------------------------- -- 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, . { 4,515,950 ( 0.03%) fn eq(&self, other: &[B]) -> bool { 1,721,236 ( 0.01%) SlicePartialEq::equal(self, other) 3,699,815 ( 0.02%) } . . 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 62 ---------------------------------------- . } . . // Generic slice equality . impl SlicePartialEq for [A] . where . A: PartialEq, . { . default fn equal(&self, other: &[B]) -> bool { 1,455,610 ( 0.01%) if self.len() != other.len() { . return false; . } . 152,529 ( 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, . { 7,745,562 ( 0.05%) fn equal(&self, other: &[B]) -> bool { 2,887,027 ( 0.02%) if self.len() != other.len() { 651,433 ( 0.00%) 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 { 836,740 ( 0.01%) let size = mem::size_of_val(self); 8,321,530 ( 0.05%) memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0 . } 4,512,275 ( 0.03%) } . } . . #[doc(hidden)] . // intermediate trait for specialization of slice's PartialOrd . trait SlicePartialOrd: Sized { . fn partial_compare(left: &[Self], right: &[Self]) -> Option; . } . -- line 102 ---------------------------------------- -- 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. 94,676 ( 0.00%) unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) }; 108,954 ( 0.00%) if order == 0 { . left.len().cmp(&right.len()) 119,394 ( 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, . { 222 ( 0.00%) default fn slice_contains(&self, x: &[Self]) -> bool { 441,909 ( 0.00%) x.iter().any(|y| *y == *self) 333 ( 0.00%) } . } . . impl SliceContains for u8 { . #[inline] . fn slice_contains(&self, x: &[Self]) -> bool { . memchr::memchr(*self, x).is_some() . } . } -- line 248 ---------------------------------------- 4,603,636 ( 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 { 14,597,377 ( 0.09%) fn encode(self, w: &mut Writer, _: &mut S) { 390 ( 0.00%) w.extend_from_array(&self.to_le_bytes()); 18,246,445 ( 0.12%) } . } . . impl DecodeMut<'_, '_, S> for $ty { 520 ( 0.00%) fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { . const N: usize = ::std::mem::size_of::<$ty>(); . 650 ( 0.00%) let mut bytes = [0; N]; 2,273,478 ( 0.01%) bytes.copy_from_slice(&r[..N]); 9,130,713 ( 0.06%) *r = &r[N..]; . 650 ( 0.00%) Self::from_le_bytes(bytes) 260 ( 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),+>)? { 38,961,043 ( 0.25%) 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;)* . } . 21,510,227 ( 0.14%) match self { 4,539,768 ( 0.03%) $($name::$variant $(($field))* => { 346,350 ( 0.00%) tag::$variant.encode(w, s); 5,779,094 ( 0.04%) $($field.encode(w, s);)* 130 ( 0.00%) })* . } 30,505,692 ( 0.19%) } . } . . impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> . for $name $(<$($T),+>)? . { 9,897,953 ( 0.06%) 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;)* . } . 9,359,711 ( 0.06%) match u8::decode(r, s) { . $(tag::$variant => { 252,863 ( 0.00%) $(let $field = DecodeMut::decode(r, s);)* 6,751,230 ( 0.04%) $name::$variant $(($field))* 126,334 ( 0.00%) })* . _ => unreachable!(), . } 17,225,220 ( 0.11%) } . } . } . } . . 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 { 1,656,017 ( 0.01%) fn encode(self, w: &mut Writer, _: &mut S) { 130 ( 0.00%) w.push(self); 1,379,765 ( 0.01%) } . } . . impl DecodeMut<'_, '_, S> for u8 { . fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { 38,649,802 ( 0.24%) let x = r[0]; 21,619,813 ( 0.14%) *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) { 269,973 ( 0.00%) (self as u8).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for bool { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 179,982 ( 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) { 265,016 ( 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 { 390 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { 10,845,168 ( 0.07%) self.get().encode(w, s); 130 ( 0.00%) } . } . . impl DecodeMut<'_, '_, S> for NonZeroU32 { 390 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 910 ( 0.00%) Self::new(u32::decode(r, s)).unwrap() 260 ( 0.00%) } . } . . impl, B: Encode> Encode for (A, B) { 715 ( 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) . { 325 ( 0.00%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { 910 ( 0.00%) (DecodeMut::decode(r, s), DecodeMut::decode(r, s)) 195 ( 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); 312,516 ( 0.00%) 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]; 539,932 ( 0.00%) *r = &r[len..]; . xs . } . } . . impl Encode for &str { 312,516 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { . self.as_bytes().encode(w, s); 390,645 ( 0.00%) } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a str { 179,934 ( 0.00%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { 359,868 ( 0.00%) str::from_utf8(<&[u8]>::decode(r, s)).unwrap() 359,868 ( 0.00%) } . } . . impl Encode for String { . fn encode(self, w: &mut Writer, s: &mut S) { 312,516 ( 0.00%) self[..].encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for String { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 390,645 ( 0.00%) <&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 ---------------------------------------- 36,800,876 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 333 ---------------------------------------- . #[unstable(feature = "dispatch_from_dyn", issue = "none")] . impl, U: ?Sized> DispatchFromDyn> for Rc {} . . impl Rc { . #[inline(always)] . fn inner(&self) -> &RcBox { . // This unsafety is ok because while this Rc is alive we're guaranteed . // that the inner pointer is valid. 373,202 ( 0.00%) unsafe { self.ptr.as_ref() } . } . 72,696 ( 0.00%) unsafe fn from_inner(ptr: NonNull>) -> Self { 36,348 ( 0.00%) Self { ptr, phantom: PhantomData } 109,044 ( 0.00%) } . . unsafe fn from_ptr(ptr: *mut RcBox) -> Self { . unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) } . } . } . . impl Rc { . /// Constructs a new `Rc`. -- line 354 ---------------------------------------- -- line 357 ---------------------------------------- . /// . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 137,369 ( 0.00%) pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { 63,412 ( 0.00%) Self::from_inner( 6,068,723 ( 0.04%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 89,810 ( 0.00%) } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or . /// indirectly, should not hold a strong reference to prevent a memory leak. . /// In `data_fn`, initialization of `T` can make use of the weak reference . /// by cloning and storing it inside `T` for use at a later time. -- line 383 ---------------------------------------- -- line 474 ---------------------------------------- . /// . /// let five = unsafe { five.assume_init() }; . /// . /// assert_eq!(*five, 5) . /// ``` . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "new_uninit", issue = "63291")] . #[must_use] 12,732 ( 0.00%) pub fn new_uninit() -> Rc> { . unsafe { . Rc::from_ptr(Rc::allocate_for_layout( . Layout::new::(), . |layout| Global.allocate(layout), . |mem| mem as *mut RcBox>, . )) . } 25,464 ( 0.00%) } . . /// Constructs a new `Rc` with uninitialized contents, with the memory . /// being filled with `0` bytes. . /// . /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and . /// incorrect usage of this method. . /// . /// # Examples -- line 498 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 493,275 ( 0.00%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1023 ---------------------------------------- . pub unsafe fn decrement_strong_count(ptr: *const T) { . unsafe { mem::drop(Rc::from_raw(ptr)) }; . } . . /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to . /// this allocation. . #[inline] . fn is_unique(this: &Self) -> bool { 2,727 ( 0.00%) Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 . } . . /// Returns a mutable reference into the given `Rc`, if there are . /// no other `Rc` or [`Weak`] pointers to the same allocation. . /// . /// Returns [`None`] otherwise, because it is not safe to . /// mutate a shared value. . /// -- line 1039 ---------------------------------------- -- line 1053 ---------------------------------------- . /// assert_eq!(*x, 4); . /// . /// let _y = Rc::clone(&x); . /// assert!(Rc::get_mut(&mut x).is_none()); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn get_mut(this: &mut Self) -> Option<&mut T> { 909 ( 0.00%) if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } . } . . /// Returns a mutable reference into the given `Rc`, . /// without any check. . /// . /// See also [`get_mut`], which is safe and does appropriate checks. . /// . /// [`get_mut`]: Rc::get_mut -- line 1069 ---------------------------------------- -- line 1085 ---------------------------------------- . /// let mut x = Rc::new(String::new()); . /// unsafe { . /// Rc::get_mut_unchecked(&mut x).push_str("foo") . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] 31,706 ( 0.00%) pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 303,281 ( 0.00%) unsafe { &mut (*this.ptr.as_ptr()).value } 31,706 ( 0.00%) } . . #[inline] . #[stable(feature = "ptr_eq", since = "1.17.0")] . /// Returns `true` if the two `Rc`s point to the same allocation . /// (in a vein similar to [`ptr::eq`]). . /// . /// # Examples . /// -- line 1105 ---------------------------------------- -- line 1109 ---------------------------------------- . /// let five = Rc::new(5); . /// let same_five = Rc::clone(&five); . /// let other_five = Rc::new(5); . /// . /// assert!(Rc::ptr_eq(&five, &same_five)); . /// assert!(!Rc::ptr_eq(&five, &other_five)); . /// ``` . pub fn ptr_eq(this: &Self, other: &Self) -> bool { 6,797 ( 0.00%) this.ptr.as_ptr() == other.ptr.as_ptr() . } . } . . impl Rc { . /// Makes a mutable reference into the given `Rc`. . /// . /// If there are other `Rc` pointers to the same allocation, then `make_mut` will . /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also -- line 1125 ---------------------------------------- -- line 1167 ---------------------------------------- . /// *Rc::make_mut(&mut data) += 1; . /// . /// assert!(76 == *data); . /// assert!(weak.upgrade().is_none()); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] 893,722 ( 0.01%) pub fn make_mut(this: &mut Self) -> &mut T { 523,428 ( 0.00%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 39,429 ( 0.00%) let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . (**this).write_clone_into_raw(data.as_mut_ptr()); 2,466 ( 0.00%) *this = rc.assume_init(); . } 327,032 ( 0.00%) } else if Rc::weak_count(this) != 0 { . // Can just steal the data, all that's left is Weaks . let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); . . this.inner().dec_strong(); . // Remove implicit strong-weak ref (no need to craft a fake -- line 1193 ---------------------------------------- -- line 1196 ---------------------------------------- . ptr::write(this, rc.assume_init()); . } . } . // This unsafety is ok because we're guaranteed that the pointer . // returned is the *only* pointer that will ever be returned to T. Our . // reference count is guaranteed to be 1 at this point, and we required . // the `Rc` itself to be `mut`, so we're returning the only possible . // reference to the allocation. 177,481 ( 0.00%) unsafe { &mut this.ptr.as_mut().value } 1,068,198 ( 0.01%) } . } . . impl Rc { . #[inline] . #[stable(feature = "rc_downcast", since = "1.29.0")] . /// Attempt to downcast the `Rc` to a concrete type. . /// . /// # Examples -- line 1213 ---------------------------------------- -- line 1344 ---------------------------------------- . ) . } . } . . /// Copy elements from slice into newly allocated Rc<\[T\]> . /// . /// Unsafe because the caller must either take ownership or bind `T: Copy` . #[cfg(not(no_global_oom_handling))] 42,723 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 9,132 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 55,050 ( 0.00%) } . . /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. . /// . /// Behavior is undefined should the size be wrong. . #[cfg(not(no_global_oom_handling))] . unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Rc<[T]> { . // Panic guard while cloning T elements. . // In the event of a panic, elements that have been written -- line 1366 ---------------------------------------- -- line 1419 ---------------------------------------- . unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } . } . } . . #[cfg(not(no_global_oom_handling))] . impl RcFromSlice for Rc<[T]> { . #[inline] . fn from_slice(v: &[T]) -> Self { 13 ( 0.00%) unsafe { Rc::copy_from_slice(v) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Deref for Rc { . type Target = T; . . #[inline(always)] . fn deref(&self) -> &T { 928,263 ( 0.01%) &self.inner().value . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Rc {} . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { -- line 1445 ---------------------------------------- -- line 1463 ---------------------------------------- . /// } . /// . /// let foo = Rc::new(Foo); . /// let foo2 = Rc::clone(&foo); . /// . /// drop(foo); // Doesn't print anything . /// drop(foo2); // Prints "dropped!" . /// ``` 9,786,684 ( 0.06%) fn drop(&mut self) { . unsafe { 2,138,993 ( 0.01%) self.inner().dec_strong(); 5,603,716 ( 0.04%) if self.inner().strong() == 0 { . // destroy the contained object 292,062 ( 0.00%) ptr::drop_in_place(Self::get_mut_unchecked(self)); . . // remove the implicit "strong weak" pointer now that we've . // destroyed the contents. 15,854 ( 0.00%) self.inner().dec_weak(); . 2,056,554 ( 0.01%) if self.inner().weak() == 0 { 180,517 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 6,830,486 ( 0.04%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Rc { . /// Makes a clone of the `Rc` pointer. . /// . /// This creates another pointer to the same allocation, increasing the . /// strong reference count. -- line 1495 ---------------------------------------- -- line 1499 ---------------------------------------- . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// . /// let _ = Rc::clone(&five); . /// ``` . #[inline] 81,980 ( 0.00%) fn clone(&self) -> Rc { . unsafe { 20,495 ( 0.00%) self.inner().inc_strong(); 61,485 ( 0.00%) Self::from_inner(self.ptr) . } 40,990 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Default for Rc { . /// Creates a new `Rc`, with the `Default` value for `T`. . /// . /// # Examples -- line 1520 ---------------------------------------- -- line 1562 ---------------------------------------- . /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to . /// the same value, than two `&T`s. . /// . /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. . #[stable(feature = "rust1", since = "1.0.0")] . impl RcEqIdent for Rc { . #[inline] . fn eq(&self, other: &Rc) -> bool { 6,857 ( 0.00%) Rc::ptr_eq(self, other) || **self == **other . } . . #[inline] . fn ne(&self, other: &Rc) -> bool { . !Rc::ptr_eq(self, other) && **self != **other . } . } . -- line 1578 ---------------------------------------- -- line 1879 ---------------------------------------- . /// # use std::rc::Rc; . /// let original: Box> = Box::new(vec![1, 2, 3]); . /// let shared: Rc> = Rc::from(original); . /// assert_eq!(vec![1, 2, 3], *shared); . /// ``` . #[inline] . fn from(mut v: Vec) -> Rc<[T]> { . unsafe { 12,341 ( 0.00%) let rc = Rc::copy_from_slice(&v); . . // Allow the Vec to free its memory, but not destroy its contents . v.set_len(0); . . rc . } . } . } -- line 1895 ---------------------------------------- -- line 2080 ---------------------------------------- . #[must_use] . pub fn new() -> Weak { . Weak { ptr: NonNull::new(usize::MAX as *mut RcBox).expect("MAX is not 0") } . } . } . . pub(crate) fn is_dangling(ptr: *mut T) -> bool { . let address = ptr as *mut () as usize; 126 ( 0.00%) address == usize::MAX . } . . /// Helper type to allow accessing the reference counts without . /// making any assertions about the data field. . struct WeakInner<'a> { . weak: &'a Cell, . strong: &'a Cell, . } -- line 2096 ---------------------------------------- -- line 2299 ---------------------------------------- . }) . .unwrap_or(0) . } . . /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`, . /// (i.e., when this `Weak` was created by `Weak::new`). . #[inline] . fn inner(&self) -> Option> { 1 ( 0.00%) if is_dangling(self.ptr.as_ptr()) { . None . } else { . // We are careful to *not* create a reference covering the "data" field, as . // the field may be mutated concurrently (for example, if the last `Rc` . // is dropped, the data field will be dropped in-place). . Some(unsafe { . let ptr = self.ptr.as_ptr(); . WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } -- line 2315 ---------------------------------------- -- line 2391 ---------------------------------------- . /// assert!(other_weak_foo.upgrade().is_none()); . /// ``` . fn drop(&mut self) { . let inner = if let Some(inner) = self.inner() { inner } else { return }; . . inner.dec_weak(); . // the weak count starts at 1, and will only go to zero if all . // the strong pointers have disappeared. 2 ( 0.00%) if inner.weak() == 0 { . unsafe { . Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); . } . } . } . } . . #[stable(feature = "rc_weak", since = "1.4.0")] -- line 2407 ---------------------------------------- -- line 2463 ---------------------------------------- . // clone these much in Rust thanks to ownership and move-semantics. . . #[doc(hidden)] . trait RcInnerPtr { . fn weak_ref(&self) -> &Cell; . fn strong_ref(&self) -> &Cell; . . #[inline] 465,955 ( 0.00%) fn strong(&self) -> usize { 186,382 ( 0.00%) self.strong_ref().get() 186,382 ( 0.00%) } . . #[inline] 61,485 ( 0.00%) fn inc_strong(&self) { 1,782,779 ( 0.01%) let strong = self.strong(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at . // an otherwise missed optimization. 5,430,049 ( 0.03%) if strong == 0 || strong == usize::MAX { . abort(); . } 189,707 ( 0.00%) self.strong_ref().set(strong + 1); 40,990 ( 0.00%) } . . #[inline] 218,088 ( 0.00%) fn dec_strong(&self) { 8,468,531 ( 0.05%) self.strong_ref().set(self.strong() - 1); 72,696 ( 0.00%) } . . #[inline] 95,118 ( 0.00%) fn weak(&self) -> usize { 63,412 ( 0.00%) self.weak_ref().get() 63,412 ( 0.00%) } . . #[inline] . fn inc_weak(&self) { . let weak = self.weak(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at -- line 2505 ---------------------------------------- -- line 2506 ---------------------------------------- . // an otherwise missed optimization. . if weak == 0 || weak == usize::MAX { . abort(); . } . self.weak_ref().set(weak + 1); . } . . #[inline] 63,412 ( 0.00%) fn dec_weak(&self) { 3,065,754 ( 0.02%) self.weak_ref().set(self.weak() - 1); 31,706 ( 0.00%) } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { 95,118 ( 0.00%) &self.weak . } . . #[inline(always)] . fn strong_ref(&self) -> &Cell { . &self.strong . } . } . -- line 2530 ---------------------------------------- 2,561,517 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . use rustc_data_structures::sync::Lrc; . use rustc_macros::HashStable_Generic; . use rustc_span::symbol::{kw, sym}; . use rustc_span::symbol::{Ident, Symbol}; . use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; . use std::borrow::Cow; . use std::{fmt, mem}; . 356,294 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 4,457 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 198,029 ( 0.00%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 81,141 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum LitKind { . Bool, // AST only, must never appear in a `Token` . Byte, . Char, . Integer, . Float, . Str, . StrRaw(u16), // raw string delimited by `n` hash symbols . ByteStr, . ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols . Err, . } . . /// A literal token. 573,203 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { 8,555 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 15,399 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 2,256 ( 0.00%) Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 2,877 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 4,894 ( 0.00%) if let Some(suffix) = suffix { 5,152 ( 0.00%) write!(f, "{}", suffix)?; . } . . Ok(()) 8,555 ( 0.00%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 123 ---------------------------------------- . Float => "float", . Str | StrRaw(..) => "string", . ByteStr | ByteStrRaw(..) => "byte string", . Err => "error", . } . } . . crate fn may_have_suffix(self) -> bool { 2,948 ( 0.00%) matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 43,241 ( 0.00%) } . } . 228 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 399 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 167 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 285 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 5,838 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 2,036 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 50,032,067 ( 0.32%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum TokenKind { . /* Expression-operator symbols. */ . Eq, . Lt, . Le, . EqEq, . Ne, . Ge, . Gt, . AndAnd, . OrOr, . Not, . Tilde, 335,742 ( 0.00%) BinOp(BinOpToken), . BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, -- line 202 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 664,530 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 230,703 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 308,095 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 603,984 ( 0.00%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. 4,194 ( 0.00%) Lifetime(Symbol), . 20,805 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 41,958 ( 0.00%) DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 4,117,126 ( 0.03%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 230,369 ( 0.00%) pub kind: TokenKind, . pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) 14,395 ( 0.00%) } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 31,329 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 125,981 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 31,254 ( 0.00%) _ => return None, . }) 31,329 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 4,246 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 952 ( 0.00%) } . } . . impl Token { 105,909 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 442,834 ( 0.00%) Token { kind, span } 105,909 ( 0.00%) } . . /// Some token that will be thrown away later. 40,329 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 40,329 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 3,584 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 28,869 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 28,869 ( 0.00%) } . . /// For interpolated tokens, returns a span of the fragment to which the interpolated . /// token refers. For all other tokens this is just a regular span. . /// It is particularly important to use this for identifiers and lifetimes . /// for which spans affect name resolution and edition checks. . /// Note that keywords are also identifiers, so they should use this . /// if they keep spans or perform edition checks. . pub fn uninterpolated_span(&self) -> Span { 6,232 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 3,116 ( 0.00%) _ => self.span, . } 3,116 ( 0.00%) } . . pub fn is_op(&self) -> bool { 86,607 ( 0.00%) !matches!( 28,869 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 28,869 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 185,117 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 36,991 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 786 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 3,930 ( 0.00%) match self.uninterpolate().kind { 513 ( 0.00%) Ident(name, is_raw) => 171 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference . // DotDotDot is no longer supported, but we need some way to display the error . DotDot | DotDotDot | DotDotEq | // range notation . Lt | BinOp(Shl) | // associated path . ModSep | // global path . Lifetime(..) | // labeled loop . Pound => true, // expression attributes 8 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 1,572 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 7,164 ( 0.00%) pub fn can_begin_type(&self) -> bool { 12,656 ( 0.00%) match self.uninterpolate().kind { 8,757 ( 0.00%) Ident(name, is_raw) => 973 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path 759 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 10,746 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 5,635 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, 848 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 1,021 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } 106 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) . || self == &Question . || self == &OpenDelim(Paren) -- line 421 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 2,509 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 17,499 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 3,512 ( 0.00%) Ident(name, false) if name.is_bool_lit() => true, . Interpolated(ref nt) => match &**nt { . NtLiteral(_) => true, . NtExpr(e) => match &e.kind { . ast::ExprKind::Lit(_) => true, . ast::ExprKind::Unary(ast::UnOp::Neg, e) => { . matches!(&e.kind, ast::ExprKind::Lit(_)) . } . _ => false, . }, . _ => false, . }, . _ => false, . } 5,018 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 45,137 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 3,928,384 ( 0.02%) match &self.kind { 136,444 ( 0.00%) Interpolated(nt) => match **nt { 24,963 ( 0.00%) NtIdent(ident, is_raw) => { 62,428 ( 0.00%) Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 45,137 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 347,012 ( 0.00%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 2,644,536 ( 0.02%) match token.kind { 11,363,212 ( 0.07%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 2,762,407 ( 0.02%) } . . /// Returns a lifetime identifier if this token is a lifetime. 3,551 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 33,816 ( 0.00%) match token.kind { 8,002 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 24,857 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 26,129 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 13,357 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 26,714 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 7,951 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 15,902 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 164,544 ( 0.00%) if let Interpolated(ref nt) = self.kind { 1,532 ( 0.00%) if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? . /// That is, is this a pre-parsed expression dropped into the token stream -- line 516 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 6,138 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 3,069 ( 0.00%) } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 22,312 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 119,822 ( 0.00%) self == &Lt || self == &BinOp(Shl) 9,363 ( 0.00%) } . 195,020 ( 0.00%) pub fn is_path_start(&self) -> bool { 260,150 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 37,763 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 243,775 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 777,596 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 1,555,192 ( 0.01%) } . 7,659 ( 0.00%) pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 16,771 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 16,771 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 16,771 ( 0.00%) pub fn is_unused_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_unused_keyword) . } . . /// Returns `true` if the token is either a special identifier or a keyword. . pub fn is_reserved_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_reserved) . } . . /// Returns `true` if the token is the identifier `true` or `false`. 7,659 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 15,318 ( 0.00%) self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) . } . . pub fn is_numeric_lit(&self) -> bool { . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. 9,032 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 5,462,995 ( 0.03%) match self.ident() { 37,218 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 11,290 ( 0.00%) } . 380,980 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 190,490 ( 0.00%) let kind = match self.kind { 292 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 145 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 799 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 110 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 26,449 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 3 ( 0.00%) BinOp(And) if op == And => AndAnd, 2 ( 0.00%) BinOp(Or) if op == Or => OrOr, 4,350 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 9 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 58,412 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, 1,100 ( 0.00%) SingleQuote => match joint.kind { 2,475 ( 0.00%) Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 441,896 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 342,882 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 2,124,314 ( 0.01%) self.kind == *rhs . } . } . 980 ( 0.00%) #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), . NtStmt(ast::Stmt), . NtPat(P), 280 ( 0.00%) NtExpr(P), . NtTy(P), . NtIdent(Ident, /* is_raw */ bool), . NtLifetime(Ident), . NtLiteral(P), . /// Stuff inside brackets for attributes . NtMeta(P), . NtPath(ast::Path), . NtVis(ast::Visibility), -- line 686 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 288 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 654 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 288 ( 0.00%) } . fn symbol(self) -> Symbol { . match self { . NonterminalKind::Item => sym::item, . NonterminalKind::Block => sym::block, . NonterminalKind::Stmt => sym::stmt, . NonterminalKind::PatParam { inferred: false } => sym::pat_param, . NonterminalKind::PatParam { inferred: true } | NonterminalKind::PatWithOr => sym::pat, . NonterminalKind::Expr => sym::expr, -- line 753 ---------------------------------------- 15,364,194 ( 0.10%) -------------------------------------------------------------------------------- -- 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)) => 197,970 ( 0.00%) (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) }); . (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) => 29,611 ( 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 63 ---------------------------------------- . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . impl Types for MarkedTypes { . $(type $name = Marked;)* . } . . $(impl $name for MarkedTypes { 48,828 ( 0.00%) $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? { 9,883,433 ( 0.06%) <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*)) 48,828 ( 0.00%) })* . })* . } . } . with_api!(Self, self_, define_mark_types_impls); . . struct Dispatcher { . handle_store: HandleStore, . server: S, -- line 81 ---------------------------------------- -- 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;)* 25,277,470 ( 0.16%) fn dispatch(&mut self, mut b: Buffer) -> Buffer { . let Dispatcher { handle_store, server } = self; . 7,583,241 ( 0.05%) let mut reader = &b[..]; 17,694,229 ( 0.11%) match api_tags::Method::decode(&mut reader, &mut ()) { 12,238,368 ( 0.08%) $(api_tags::Method::$name(m) => match m { . $(api_tags::$name::$method => { . let mut call_method = || { 8,131,842 ( 0.05%) reverse_decode!(reader, handle_store; $($arg: $arg_ty),*); 24,414 ( 0.00%) $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 { 11,530,340 ( 0.07%) panic::catch_unwind(panic::AssertUnwindSafe(call_method)) . .map_err(PanicMessage::from) . }; . . b.clear(); 27,718,279 ( 0.18%) r.encode(&mut b, handle_store); . })* . }),* . } 15,166,482 ( 0.10%) b 22,749,723 ( 0.14%) } . } . } . } . 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 { 22,749,788 ( 0.14%) let mut dispatch = |b| dispatcher.dispatch(b); . 650 ( 0.00%) run_client( 715 ( 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() . } . } . 910 ( 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 = 1,105 ( 0.00%) Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) }; . . let mut b = Buffer::new(); 260 ( 0.00%) input.encode(&mut b, &mut dispatcher.handle_store); . 390 ( 0.00%) b = strategy.run_bridge_and_client( . &mut dispatcher, . b, . run_client, . client_data, . force_show_panics, . ); . 325 ( 0.00%) Result::decode(&mut &b[..], &mut dispatcher.handle_store) 650 ( 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 { 130 ( 0.00%) let client::Client { get_handle_counters, run, f } = *self; 845 ( 0.00%) run_server( . strategy, 65 ( 0.00%) get_handle_counters(), 650 ( 0.00%) server, . ( . as Types>::TokenStream::mark(input), . as Types>::TokenStream::mark(input2), . ), . run, . f, . force_show_panics, . ) -- line 345 ---------------------------------------- 5,880,134 ( 0.04%) -------------------------------------------------------------------------------- -- 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] 98,160 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 358,578 ( 0.00%) Self::allocate_in(capacity, AllocInit::Uninitialized, alloc) 98,160 ( 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. 39,024 ( 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). 15,594 ( 0.00%) debug_assert!( . len <= self.capacity(), . "`len` must be smaller than or equal to `self.capacity()`" . ); . 70,173 ( 0.00%) let me = ManuallyDrop::new(self); . unsafe { 109,158 ( 0.00%) let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit, len); 70,173 ( 0.00%) Box::from_raw_in(slice, ptr::read(&me.alloc)) . } 15,633 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] 324,516 ( 0.00%) fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { 294,480 ( 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. 588,960 ( 0.00%) let layout = match Layout::array::(capacity) { 343,560 ( 0.00%) Ok(layout) => layout, . Err(_) => capacity_overflow(), . }; 392,640 ( 0.00%) match alloc_guard(layout.size()) { . Ok(_) => {} . Err(_) => capacity_overflow(), . } 162,258 ( 0.00%) let result = match init { 490,800 ( 0.00%) AllocInit::Uninitialized => alloc.allocate(layout), . AllocInit::Zeroed => alloc.allocate_zeroed(layout), . }; 245,400 ( 0.00%) let ptr = match result { 294,480 ( 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::()`. 98,160 ( 0.00%) Self { 588,960 ( 0.00%) ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }, . cap: capacity, 49,080 ( 0.00%) alloc, . } . } 233,865 ( 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] 75,148 ( 0.00%) pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self { 112,722 ( 0.00%) Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap: capacity, alloc } 75,148 ( 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] 2,123,218 ( 0.01%) pub fn ptr(&self) -> *mut T { 3,184,827 ( 0.02%) self.ptr.as_ptr() 2,123,218 ( 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 { 2,695,000 ( 0.02%) if mem::size_of::() == 0 { usize::MAX } else { self.cap } 1,078,000 ( 0.01%) } . . /// Returns a shared reference to the allocator backing this `RawVec`. 172,734 ( 0.00%) pub fn allocator(&self) -> &A { . &self.alloc 115,156 ( 0.00%) } . 2,065,150 ( 0.01%) fn current_memory(&self) -> Option<(NonNull, Layout)> { 30,219,412 ( 0.19%) if mem::size_of::() == 0 || self.cap == 0 { 1,197,682 ( 0.01%) None . } else { . // We have an allocated chunk of memory, so we can bypass runtime . // checks to get our current layout. . unsafe { 456,388 ( 0.00%) let align = mem::align_of::(); 9,282,368 ( 0.06%) let size = mem::size_of::() * self.cap; 1,597,358 ( 0.01%) let layout = Layout::from_size_align_unchecked(size, align); 4,747,692 ( 0.03%) Some((self.ptr.cast().into(), layout)) . } . } 826,060 ( 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] 237,853 ( 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] 2,073,505 ( 0.01%) fn do_reserve_and_handle( . slf: &mut RawVec, . len: usize, . additional: usize, . ) { 106,315 ( 0.00%) handle_reserve(slf.grow_amortized(len, additional)); 2,450,402 ( 0.02%) } . 3,109,976 ( 0.02%) if self.needs_to_grow(len, additional) { 2,115,648 ( 0.01%) do_reserve_and_handle(self, len, additional); . } 67,958 ( 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)] 3,969,977 ( 0.03%) pub fn reserve_for_push(&mut self, len: usize) { 600,890 ( 0.00%) handle_reserve(self.grow_amortized(len, 1)); 4,414,599 ( 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))] 110,830 ( 0.00%) pub fn reserve_exact(&mut self, len: usize, additional: usize) { . handle_reserve(self.try_reserve_exact(len, additional)); 110,830 ( 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> { 44,966 ( 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))] 94,715 ( 0.00%) pub fn shrink_to_fit(&mut self, cap: usize) { 14,516 ( 0.00%) handle_reserve(self.shrink(cap)); 99,142 ( 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`. 271,832 ( 0.00%) fn needs_to_grow(&self, len: usize, additional: usize) -> bool { 5,750,144 ( 0.04%) additional > self.capacity().wrapping_sub(len) 135,916 ( 0.00%) } . 1,938,053 ( 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::()`. 2,475,313 ( 0.02%) self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }; 1,581,873 ( 0.01%) self.cap = cap; 298,162 ( 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`. 1,315,350 ( 0.01%) fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . // This is ensured by the calling contexts. . debug_assert!(additional > 0); . 436,356 ( 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. 2,618,136 ( 0.02%) 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`. 7,343,044 ( 0.05%) let cap = cmp::max(self.cap * 2, required_cap); 581,808 ( 0.00%) let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap); . 727,260 ( 0.00%) let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 6,747,376 ( 0.04%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; 290,904 ( 0.00%) self.set_ptr_and_cap(ptr, cap); 145,452 ( 0.00%) Ok(()) 442,637 ( 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`. 51,097 ( 0.00%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; . self.set_ptr_and_cap(ptr, cap); . Ok(()) . } . 29,032 ( 0.00%) fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> { 64,087 ( 0.00%) assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity"); . 101,612 ( 0.00%) let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) }; 74,974 ( 0.00%) let new_size = cap * mem::size_of::(); . . let ptr = unsafe { 25,403 ( 0.00%) let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); 65,322 ( 0.00%) self.alloc 14,516 ( 0.00%) .shrink(ptr, layout, new_layout) 7,258 ( 0.00%) .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? . }; 7,258 ( 0.00%) self.set_ptr_and_cap(ptr, cap); 3,629 ( 0.00%) Ok(()) 10,887 ( 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)] 8,245,746 ( 0.05%) 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_*`. 2,036,328 ( 0.01%) let new_layout = new_layout.map_err(|_| CapacityOverflow)?; . 1,745,424 ( 0.01%) alloc_guard(new_layout.size())?; . 6,047,948 ( 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 218,455 ( 0.00%) intrinsics::assume(old_layout.align() == new_layout.align()); 305,837 ( 0.00%) alloc.grow(ptr, old_layout, new_layout) . } . } else { 508,805 ( 0.00%) alloc.allocate(new_layout) . }; . 1,018,164 ( 0.01%) memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into()) 6,102,060 ( 0.04%) } . . unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec { . /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. 1,093,096 ( 0.01%) fn drop(&mut self) { 11,344,700 ( 0.07%) if let Some((ptr, layout)) = self.current_memory() { 361,748 ( 0.00%) unsafe { self.alloc.deallocate(ptr, layout) } . } 559,338 ( 0.00%) } . } . . // Central function for reserve error handling. . #[cfg(not(no_global_oom_handling))] . #[inline] 149,081 ( 0.00%) fn handle_reserve(result: Result<(), TryReserveError>) { 1,788,972 ( 0.01%) match result.map_err(|e| e.kind()) { . Err(CapacityOverflow) => capacity_overflow(), . Err(AllocError { layout, .. }) => handle_alloc_error(layout), . Ok(()) => { /* yay */ } . } 298,162 ( 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] 778,128 ( 0.00%) fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> { 778,128 ( 0.00%) if usize::BITS < 64 && alloc_size > isize::MAX as usize { . Err(CapacityOverflow.into()) . } else { 194,532 ( 0.00%) Ok(()) . } 389,064 ( 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 ---------------------------------------- 35,044,090 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs -------------------------------------------------------------------------------- Ir -- line 416 ---------------------------------------- . /// ``` . /// # #![allow(unused_mut)] . /// let mut vec: Vec = Vec::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 155,424 ( 0.00%) pub const fn new() -> Self { 18,549,561 ( 0.12%) Vec { buf: RawVec::NEW, len: 0 } 155,588 ( 0.00%) } . . /// Constructs a new, empty `Vec` with the specified capacity. . /// . /// The vector will be able to hold exactly `capacity` elements without . /// reallocating. If `capacity` is 0, the vector will not allocate. . /// . /// It is important to note that although the returned vector has the . /// *capacity* specified, the vector will have a zero *length*. For an -- line 434 ---------------------------------------- -- line 461 ---------------------------------------- . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 15,664 ( 0.00%) pub fn with_capacity(capacity: usize) -> Self { 3,916 ( 0.00%) Self::with_capacity_in(capacity, Global) 7,832 ( 0.00%) } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: . /// -- line 479 ---------------------------------------- -- line 529 ---------------------------------------- . /// . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts(p, len, cap); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 1,170 ( 0.00%) pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { 195 ( 0.00%) unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } 390 ( 0.00%) } . } . . impl Vec { . /// Constructs a new, empty `Vec`. . /// . /// The vector will not allocate until elements are pushed onto it. . /// . /// # Examples -- line 547 ---------------------------------------- -- line 600 ---------------------------------------- . /// // ...but this may make the vector reallocate . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] 343,560 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 4,957,118 ( 0.03%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } 98,160 ( 0.00%) } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: . /// -- line 618 ---------------------------------------- -- line 676 ---------------------------------------- . /// . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] 65,715 ( 0.00%) pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 1,102,616 ( 0.01%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } 10,110 ( 0.00%) } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. . /// -- line 694 ---------------------------------------- -- line 777 ---------------------------------------- . /// # Examples . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 40,852 ( 0.00%) pub fn capacity(&self) -> usize { 997,100 ( 0.01%) self.buf.capacity() 20,426 ( 0.00%) } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// . /// # Panics -- line 795 ---------------------------------------- -- line 800 ---------------------------------------- . /// . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 169,895 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 2,489,926 ( 0.02%) self.buf.reserve(self.len, additional); 67,958 ( 0.00%) } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it . /// requests. Therefore, capacity can not be relied upon to be precisely -- line 818 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 49,143 ( 0.00%) self.buf.reserve_exact(self.len, additional); . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `try_reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 845 ---------------------------------------- -- line 926 ---------------------------------------- . /// let mut vec = Vec::with_capacity(10); . /// vec.extend([1, 2, 3]); . /// assert_eq!(vec.capacity(), 10); . /// vec.shrink_to_fit(); . /// assert!(vec.capacity() >= 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 23,391 ( 0.00%) pub fn shrink_to_fit(&mut self) { . // The capacity is never less than the length, and there's nothing to do when . // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` . // by only calling it with a greater capacity. 151,431 ( 0.00%) if self.capacity() > self.len { 113,545 ( 0.00%) self.buf.shrink_to_fit(self.len); . } 15,594 ( 0.00%) } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// . /// If the current capacity is less than the lower limit, this is a no-op. . /// -- line 949 ---------------------------------------- -- line 987 ---------------------------------------- . /// vec.extend([1, 2, 3]); . /// . /// assert_eq!(vec.capacity(), 10); . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 15,594 ( 0.00%) pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { 46,782 ( 0.00%) self.shrink_to_fit(); 88,799 ( 0.00%) let me = ManuallyDrop::new(self); 77,970 ( 0.00%) let buf = ptr::read(&me.buf); 38,985 ( 0.00%) let len = me.len(); 101,361 ( 0.00%) buf.into_box(len).assume_init() 7,797 ( 0.00%) } 15,594 ( 0.00%) } . . /// Shortens the vector, keeping the first `len` elements and dropping . /// the rest. . /// . /// If `len` is greater than the vector's current length, this has no . /// effect. . /// . /// The [`drain`] method can emulate `truncate`, but causes the excess -- line 1011 ---------------------------------------- -- line 1040 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.truncate(0); . /// assert_eq!(vec, []); . /// ``` . /// . /// [`clear`]: Vec::clear . /// [`drain`]: Vec::drain . #[stable(feature = "rust1", since = "1.0.0")] 2,531,453 ( 0.02%) pub fn truncate(&mut self, len: usize) { . // This is safe because: . // . // * the slice passed to `drop_in_place` is valid; the `len > self.len` . // case avoids creating an invalid slice, and . // * the `len` of the vector is shrunk before calling `drop_in_place`, . // such that no value will be dropped twice in case `drop_in_place` . // were to panic once (if it panics twice, the program aborts). . unsafe { . // Note: It's intentional that this is `>` and not `>=`. . // Changing it to `>=` has negative performance . // implications in some cases. See #78884 for more. 1,766,255 ( 0.01%) if len > self.len { . return; . } . let remaining_len = self.len - len; . let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 1,121,025 ( 0.01%) self.len = len; 22,025 ( 0.00%) ptr::drop_in_place(s); . } 3,037,724 ( 0.02%) } . . /// Extracts a slice containing the entire vector. . /// . /// Equivalent to `&s[..]`. . /// . /// # Examples . /// . /// ``` . /// use std::io::{self, Write}; . /// let buffer = vec![1, 2, 3, 5, 8]; . /// io::sink().write(buffer.as_slice()).unwrap(); . /// ``` . #[inline] . #[stable(feature = "vec_as_slice", since = "1.7.0")] 1,456 ( 0.00%) pub fn as_slice(&self) -> &[T] { 2,184 ( 0.00%) self 1,456 ( 0.00%) } . . /// Extracts a mutable slice of the entire vector. . /// . /// Equivalent to `&mut s[..]`. . /// . /// # Examples . /// . /// ``` -- line 1093 ---------------------------------------- -- line 1123 ---------------------------------------- . /// assert_eq!(*x_ptr.add(i), 1 << i); . /// } . /// } . /// ``` . /// . /// [`as_mut_ptr`]: Vec::as_mut_ptr . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] 415,492 ( 0.00%) pub fn as_ptr(&self) -> *const T { . // We shadow the slice method of the same name to avoid going through . // `deref`, which creates an intermediate reference. 17,727,540 ( 0.11%) let ptr = self.buf.ptr(); . unsafe { 207,746 ( 0.00%) assume(!ptr.is_null()); . } . ptr 415,492 ( 0.00%) } . . /// Returns an unsafe mutable pointer to the vector's buffer. . /// . /// The caller must ensure that the vector outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// Modifying the vector may cause its buffer to be reallocated, . /// which would also make any pointers to it invalid. . /// -- line 1147 ---------------------------------------- -- line 1159 ---------------------------------------- . /// *x_ptr.add(i) = i as i32; . /// } . /// x.set_len(size); . /// } . /// assert_eq!(&*x, &[0, 1, 2, 3]); . /// ``` . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] 1,692,132 ( 0.01%) pub fn as_mut_ptr(&mut self) -> *mut T { . // We shadow the slice method of the same name to avoid going through . // `deref_mut`, which creates an intermediate reference. 15,897,433 ( 0.10%) let ptr = self.buf.ptr(); . unsafe { 846,066 ( 0.01%) assume(!ptr.is_null()); . } . ptr 1,692,132 ( 0.01%) } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] 115,156 ( 0.00%) pub fn allocator(&self) -> &A { 115,156 ( 0.00%) self.buf.allocator() 115,156 ( 0.00%) } . . /// Forces the length of the vector to `new_len`. . /// . /// This is a low-level operation that maintains none of the normal . /// invariants of the type. Normally changing the length of a vector . /// is done using one of the safe operations instead, such as . /// [`truncate`], [`resize`], [`extend`], or [`clear`]. . /// -- line 1190 ---------------------------------------- -- line 1256 ---------------------------------------- . /// vec.set_len(0); . /// } . /// ``` . /// . /// Normally, here, one would use [`clear`] instead to correctly drop . /// the contents and thus not leak memory. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 344,409 ( 0.00%) pub unsafe fn set_len(&mut self, new_len: usize) { . debug_assert!(new_len <= self.capacity()); . 2,535,613 ( 0.02%) self.len = new_len; 275,564 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1305 ---------------------------------------- . assert_failed(index, len); . } . unsafe { . // We replace self[index] with the last element. Note that if the . // bounds check above succeeds there must be a last element (which . // can be self[index] itself). . let value = ptr::read(self.as_ptr().add(index)); . let base_ptr = self.as_mut_ptr(); 2 ( 0.00%) ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); . self.set_len(len - 1); . value . } . } . . /// Inserts an element at position `index` within the vector, shifting all . /// elements after it to the right. . /// -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 12,999 ( 0.00%) pub fn insert(&mut self, index: usize, element: T) { . #[cold] . #[inline(never)] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("insertion index (is {}) should be <= len (is {})", index, len); . } . 2,183 ( 0.00%) let len = self.len(); 6,600 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 14,980 ( 0.00%) if len == self.buf.capacity() { . self.reserve(1); . } . . unsafe { . // infallible . // The spot to put the new value . { . let p = self.as_mut_ptr().add(index); . // Shift everything over to make space. (Duplicating the . // `index`th element into two consecutive places.) 21,492 ( 0.00%) ptr::copy(p, p.offset(1), len - index); . // Write it in, overwriting the first copy of the `index`th . // element. . ptr::write(p, element); . } 14,980 ( 0.00%) self.set_len(len + 1); . } 11,142 ( 0.00%) } . . /// Removes and returns the element at position `index` within the vector, . /// shifting all elements after it to the left. . /// . /// Note: Because this shifts over the remaining elements, it has a . /// worst-case performance of *O*(*n*). If you don't need the order of elements . /// to be preserved, use [`swap_remove`] instead. If you'd like to remove . /// elements from the beginning of the `Vec`, consider using -- line 1376 ---------------------------------------- -- line 1387 ---------------------------------------- . /// . /// ``` . /// let mut v = vec![1, 2, 3]; . /// assert_eq!(v.remove(1), 2); . /// assert_eq!(v, [1, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[track_caller] 106,416 ( 0.00%) pub fn remove(&mut self, index: usize) -> T { . #[cold] . #[inline(never)] . #[track_caller] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("removal index (is {}) should be < len (is {})", index, len); . } . 38,917 ( 0.00%) let len = self.len(); 110,135 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. 3,630 ( 0.00%) let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 243,370 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 82,306 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 47,205 ( 0.00%) self.set_len(len - 1); 726 ( 0.00%) ret 726 ( 0.00%) } 166,712 ( 0.00%) } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1431 ---------------------------------------- -- line 1442 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3, 4, 5]; . /// let keep = [false, true, true, false, true]; . /// let mut iter = keep.iter(); . /// vec.retain(|_| *iter.next().unwrap()); . /// assert_eq!(vec, [2, 3, 5]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,345,551 ( 0.01%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 28,307 ( 0.00%) self.retain_mut(|elem| f(elem)); 1,323,264 ( 0.01%) } . . /// Retains only the elements specified by the predicate, passing a mutable reference to it. . /// . /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1463 ---------------------------------------- -- line 1474 ---------------------------------------- . /// }); . /// assert_eq!(vec, [2, 3, 4]); . /// ``` . #[unstable(feature = "vec_retain_mut", issue = "90829")] . pub fn retain_mut(&mut self, mut f: F) . where . F: FnMut(&mut T) -> bool, . { 172,823 ( 0.00%) let original_len = self.len(); . // Avoid double drop if the drop guard is not executed, . // since we may make some holes during the process. . unsafe { self.set_len(0) }; . . // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] . // |<- processed len ->| ^- next to check . // |<- deleted cnt ->| . // |<- original_len ->| -- line 1490 ---------------------------------------- -- line 1499 ---------------------------------------- . v: &'a mut Vec, . processed_len: usize, . deleted_cnt: usize, . original_len: usize, . } . . impl Drop for BackshiftOnDrop<'_, T, A> { . fn drop(&mut self) { 172,490 ( 0.00%) if self.deleted_cnt > 0 { . // SAFETY: Trailing unchecked items must be valid since we never touch them. . unsafe { . ptr::copy( . self.v.as_ptr().add(self.processed_len), 123,545 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 1,668,161 ( 0.01%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 410,806 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 96,896 ( 0.00%) g.processed_len += 1; 45,606 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 4 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 60,279 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 59,704 ( 0.00%) g.processed_len += 1; . } . } . . // Stage 1: Nothing was deleted. . process_loop::(original_len, &mut f, &mut g); . . // Stage 2: Some elements were deleted. . process_loop::(original_len, &mut f, &mut g); -- line 1565 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 24,171 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 11,421 ( 0.00%) let len = self.len(); 35,730 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 48,941 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 271 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 31,061 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 27,624 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1717 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2]; . /// vec.push(3); . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 2,475,806 ( 0.02%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 22,521,367 ( 0.14%) if self.len == self.buf.capacity() { 2,397,870 ( 0.02%) self.buf.reserve_for_push(self.len); . } . unsafe { 5,197,273 ( 0.03%) let end = self.as_mut_ptr().add(self.len); 3,394,733 ( 0.02%) ptr::write(end, value); 29,908,929 ( 0.19%) self.len += 1; . } 891,064 ( 0.01%) } . . /// Removes the last element from a vector and returns it, or [`None`] if it . /// is empty. . /// . /// If you'd like to pop the first element, consider using . /// [`VecDeque::pop_front`] instead. . /// . /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front -- line 1744 ---------------------------------------- -- line 1748 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3]; . /// assert_eq!(vec.pop(), Some(3)); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop(&mut self) -> Option { 5,266,609 ( 0.03%) if self.len == 0 { 3 ( 0.00%) None . } else { . unsafe { 3,969,833 ( 0.03%) self.len -= 1; 684,819 ( 0.00%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 18,179 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { 2,912 ( 0.00%) self.append_elements(other.as_slice() as _); 2,184 ( 0.00%) other.set_len(0); . } 12,046 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] 285,990 ( 0.00%) unsafe fn append_elements(&mut self, other: *const [T]) { 28,599 ( 0.00%) let count = unsafe { (*other).len() }; 28,599 ( 0.00%) self.reserve(count); 620,507 ( 0.00%) let len = self.len(); 85,845 ( 0.00%) unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 2,799,939 ( 0.02%) self.len += count; 57,198 ( 0.00%) } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is . /// unspecified how many elements are removed. -- line 1808 ---------------------------------------- -- line 1820 ---------------------------------------- . /// assert_eq!(v, &[1]); . /// assert_eq!(u, &[2, 3]); . /// . /// // A full range clears the vector . /// v.drain(..); . /// assert_eq!(v, &[]); . /// ``` . #[stable(feature = "drain", since = "1.6.0")] 453,145 ( 0.00%) pub fn drain(&mut self, range: R) -> Drain<'_, T, A> . where . R: RangeBounds, . { . // Memory safety . // . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 518,240 ( 0.00%) let len = self.len(); 971,025 ( 0.01%) let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked 194,205 ( 0.00%) self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 1,036,266 ( 0.01%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 326,167 ( 0.00%) Drain { . tail_start: end, 324,047 ( 0.00%) tail_len: len - end, 323,675 ( 0.00%) iter: range_slice.iter(), 258,940 ( 0.00%) vec: NonNull::from(self), . } . } 129,470 ( 0.00%) } . . /// Clears the vector, removing all values. . /// . /// Note that this method has no effect on the allocated capacity . /// of the vector. . /// . /// # Examples . /// -- line 1866 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 4,526,949 ( 0.03%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` . /// let a = vec![1, 2, 3]; . /// assert_eq!(a.len(), 3); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 538,122 ( 0.00%) pub fn len(&self) -> usize { 269,061 ( 0.00%) self.len 538,122 ( 0.00%) } . . /// Returns `true` if the vector contains no elements. . /// . /// # Examples . /// . /// ``` . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 250,060 ( 0.00%) pub fn is_empty(&self) -> bool { 2,499,858 ( 0.02%) self.len() == 0 500,120 ( 0.00%) } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// . /// # Panics -- line 1917 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 16,697 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 12,727 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 104,553 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 14,051 ( 0.00%) let len = self.len(); 28,102 ( 0.00%) if new_len > len { 153,787 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 90,502 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2064 ---------------------------------------- . /// unsafe { . /// v.set_len(3); . /// } . /// . /// assert_eq!(&v, &[0, 1, 2]); . /// ``` . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] 131,907 ( 0.00%) pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { 175,876 ( 0.00%) slice::from_raw_parts_mut( 307,785 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 219,886 ( 0.00%) self.buf.capacity() - self.len, . ) . } 87,938 ( 0.00%) } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data . /// (e.g. by reading from a file) before marking the data as initialized using . /// the [`set_len`] method. . /// -- line 2090 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 121,580 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 12,158 ( 0.00%) let len = self.len(); . 36,474 ( 0.00%) if new_len > len { 23,844 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 13,198 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2220 ---------------------------------------- . /// let mut vec = vec![1]; . /// vec.extend_from_slice(&[2, 3, 4]); . /// assert_eq!(vec, [1, 2, 3, 4]); . /// ``` . /// . /// [`extend`]: Vec::extend . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] 305,734 ( 0.00%) pub fn extend_from_slice(&mut self, other: &[T]) { 111,176 ( 0.00%) self.spec_extend(other.iter()) 55,588 ( 0.00%) } . . /// Copies elements from `src` range to the end of the vector. . /// . /// # Panics . /// . /// Panics if the starting point is greater than the end point or if . /// the end point is greater than the length of the vector. . /// -- line 2238 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 95 ( 0.00%) self.0.clone() . } . fn last(self) -> T { . self.0 . } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { -- line 2287 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 1,193,195 ( 0.01%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 35,536 ( 0.00%) let mut ptr = self.as_mut_ptr().add(self.len()); . // Use SetLenOnDrop to work around bug where compiler . // might not realize the store through `ptr` through self.set_len() . // don't alias. . let mut local_len = SetLenOnDrop::new(&mut self.len); . . // Write all elements except the last one . for _ in 1..n { . ptr::write(ptr, value.next()); . ptr = ptr.offset(1); . // Increment the length in every step in case next() panics . local_len.increment_len(1); . } . 1,320,969 ( 0.01%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 948,935 ( 0.01%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 3,455 ( 0.00%) self.dedup_by(|a, b| a == b) . } . } . . //////////////////////////////////////////////////////////////////////////////// . // Internal methods and functions . //////////////////////////////////////////////////////////////////////////////// . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 273,168 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 1,437,860 ( 0.01%) ::from_elem(elem, n, Global) 293,406 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2423 ---------------------------------------- . //////////////////////////////////////////////////////////////////////////////// . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . 623,238 ( 0.00%) fn deref(&self) -> &[T] { 24,401,930 ( 0.15%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 415,986 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { 2,886 ( 0.00%) fn deref_mut(&mut self) -> &mut [T] { 5,190,772 ( 0.03%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } 1,924 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . . #[cfg(not(no_global_oom_handling))] -- line 2448 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 1,906,051 ( 0.01%) fn clone(&self) -> Self { 219,230 ( 0.00%) let alloc = self.allocator().clone(); 394,616 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 2,145,230 ( 0.01%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2517 ---------------------------------------- . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] 738 ( 0.00%) fn index(&self, index: I) -> &Self::Output { 543,120 ( 0.00%) Index::index(&**self, index) 492 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] 1,300 ( 0.00%) fn index_mut(&mut self, index: I) -> &mut Self::Output { 3,532 ( 0.00%) IndexMut::index_mut(&mut **self, index) 520 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] 8,776 ( 0.00%) fn from_iter>(iter: I) -> Vec { 6,171,317 ( 0.04%) >::from_iter(iter.into_iter()) 5,504 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . . /// Creates a consuming iterator, that is, one that moves each value out of -- line 2556 ---------------------------------------- -- line 2562 ---------------------------------------- . /// ``` . /// let v = vec!["a".to_string(), "b".to_string()]; . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] 41,196 ( 0.00%) fn into_iter(self) -> IntoIter { . unsafe { 2,760,764 ( 0.02%) let mut me = ManuallyDrop::new(self); 27,464 ( 0.00%) let alloc = ptr::read(me.allocator()); 68,660 ( 0.00%) let begin = me.as_mut_ptr(); 41,196 ( 0.00%) let end = if mem::size_of::() == 0 { . arith_offset(begin as *const i8, me.len() as isize) as *const T . } else { 68,660 ( 0.00%) begin.add(me.len()) as *const T . }; 13,732 ( 0.00%) let cap = me.buf.capacity(); 1,000,703 ( 0.01%) IntoIter { 54,928 ( 0.00%) buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, 13,732 ( 0.00%) end, . } . } 27,464 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . 7,572 ( 0.00%) fn into_iter(self) -> slice::Iter<'a, T> { 22,716 ( 0.00%) self.iter() 7,572 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . . fn into_iter(self) -> slice::IterMut<'a, T> { 1,114 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 28,841 ( 0.00%) fn extend>(&mut self, iter: I) { 2,669,196 ( 0.02%) >::spec_extend(self, iter.into_iter()) 25,246 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { 968 ( 0.00%) self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { . self.reserve(additional); . } . } . . impl Vec { . // leaf method to which various SpecFrom/SpecExtend implementations delegate when . // they have no further optimizations to apply . #[cfg(not(no_global_oom_handling))] 5,696 ( 0.00%) fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 560,286 ( 0.00%) while let Some(element) = iterator.next() { 74,184 ( 0.00%) let len = self.len(); 989,660 ( 0.01%) if len == self.capacity() { 6,176 ( 0.00%) let (lower, _) = iterator.size_hint(); 282 ( 0.00%) self.reserve(lower.saturating_add(1)); . } . unsafe { 31,811 ( 0.00%) ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 718,731 ( 0.00%) self.set_len(len + 1); . } 2,026 ( 0.00%) } 19,673 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 1,485 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 25,356 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 135,624 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// . /// [`copy_from_slice`]: slice::copy_from_slice . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "extend_ref", since = "1.2.0")] . impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec { 4,896 ( 0.00%) fn extend>(&mut self, iter: I) { . self.spec_extend(iter.into_iter()) 3,672 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, &item: &'a T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2783 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 4,694,293 ( 0.03%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 3,934,507 ( 0.02%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 5,135,764 ( 0.03%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. 1,170 ( 0.00%) fn default() -> Vec { 390 ( 0.00%) Vec::new() 780 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Debug for Vec { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&**self, f) . } . } -- line 2836 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 16,928,992 ( 0.11%) -------------------------------------------------------------------------------- -- 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] 8,177,248 ( 0.05%) 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. 8,177,248 ( 0.05%) (self as *mut u8).guaranteed_eq(null_mut()) 8,177,248 ( 0.05%) } . . /// 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`. 75,300,774 ( 0.48%) 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. 3,817 ( 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] 6,132,936 ( 0.04%) pub const fn guaranteed_eq(self, other: *mut T) -> bool . where . T: Sized, . { 12,287,241 ( 0.08%) intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _) 8,177,248 ( 0.05%) } . . /// 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 683 ---------------------------------------- . #[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) } 726 ( 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 699 ---------------------------------------- -- line 741 ---------------------------------------- . /// println!("{}", *end.sub(1) as char); . /// println!("{}", *end.sub(2) as char); . /// } . /// ``` . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] 38,388 ( 0.00%) pub const unsafe fn sub(self, count: usize) -> Self . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . unsafe { self.offset((count as isize).wrapping_neg()) } 10,968 ( 0.00%) } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// (convenience for `.wrapping_offset(count as isize)`) . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 763 ---------------------------------------- -- 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`. 6,745 ( 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`. 103,526 ( 0.00%) unsafe { write(self, val) } 728 ( 0.00%) } . . /// 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() . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")] . #[inline(always)] . pub const unsafe fn write_bytes(self, val: u8, count: usize) . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `write_bytes`. 256 ( 0.00%) unsafe { write_bytes(self, val, count) } 64 ( 0.00%) } . . /// Performs a volatile write of a memory location with the given value without . /// reading or dropping the old value. . /// . /// Volatile operations are intended to act on I/O memory, and are guaranteed . /// to not be elided or reordered by the compiler across other volatile . /// operations. . /// -- line 1106 ---------------------------------------- -- 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 { 142,236 ( 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 ---------------------------------------- 5,555,968 ( 0.04%) -------------------------------------------------------------------------------- -- 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. 1,667,653 ( 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 { 3,597,186 ( 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. 6,954,233 ( 0.04%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; 599,531 ( 0.00%) old . } 1,199,062 ( 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`. 166,981 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; 47,138 ( 0.00%) self.end . } 47,138 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 5,602,293 ( 0.04%) len!(self) 130,816 ( 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] 2,233,833 ( 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 { 4,043,025 ( 0.03%) assume(!self.ptr.as_ptr().is_null()); 3,723,055 ( 0.02%) if mem::size_of::() != 0 { 1,915,875 ( 0.01%) assume(!self.end.is_null()); . } 200,251,464 ( 1.27%) if is_empty!(self) { 145,080 ( 0.00%) None . } else { 1,199,063 ( 0.01%) Some(next_unchecked!(self)) . } . } 2,233,833 ( 0.01%) } . . #[inline] 14,235 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 4,155,051 ( 0.03%) let exact = len!(self); 25,623 ( 0.00%) (exact, Some(exact)) 5,694 ( 0.00%) } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 132,011 ( 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() { 12,985 ( 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, . { 14,484 ( 0.00%) while let Some(x) = self.next() { 27,246 ( 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] 1,992 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,699,032 ( 0.01%) while let Some(x) = self.next() { 10,991,372 ( 0.07%) if f(x) { . return true; . } . } . false 1,992 ( 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] 100 ( 0.00%) fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 240,293 ( 0.00%) while let Some(x) = self.next() { 354,789 ( 0.00%) if predicate(&x) { . return Some(x); . } . } 20 ( 0.00%) None 2,716 ( 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] 94,487 ( 0.00%) fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 581,866 ( 0.00%) while let Some(x) = self.next() { 938,460 ( 0.01%) if let Some(y) = f(x) { 46,868 ( 0.00%) return Some(y); . } 24,214 ( 0.00%) } 11,661 ( 0.00%) None 71,758 ( 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() { 341,751 ( 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; 263,048 ( 0.00%) while let Some(x) = self.next_back() { 3,418,537 ( 0.02%) i -= 1; 2,829,991 ( 0.02%) 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` 183,778 ( 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] 70,821 ( 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 { 97,366 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); 118,035 ( 0.00%) if mem::size_of::() != 0 { 50,174 ( 0.00%) assume(!self.end.is_null()); . } 4,111,502 ( 0.03%) if is_empty!(self) { 38 ( 0.00%) None . } else { 47,138 ( 0.00%) Some(next_back_unchecked!(self)) . } . } 70,821 ( 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 ---------------------------------------- 34,204,466 ( 0.22%) -------------------------------------------------------------------------------- -- 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 { 1,170 ( 0.00%) fn default() -> Self { 1,560 ( 0.00%) Self::from(vec![]) 780 ( 0.00%) } . } . . impl Deref for Buffer { . type Target = [T]; 195 ( 0.00%) fn deref(&self) -> &[T] { 5,784,122 ( 0.04%) unsafe { slice::from_raw_parts(self.data as *const T, self.len) } 130 ( 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() . } . 130 ( 0.00%) pub(super) fn clear(&mut self) { 12,118,308 ( 0.08%) self.len = 0; 130 ( 0.00%) } . 1,560 ( 0.00%) pub(super) fn take(&mut self) -> Self { 390 ( 0.00%) mem::take(self) 780 ( 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. 325 ( 0.00%) pub(super) fn extend_from_array(&mut self, xs: &[T; N]) { 26,413,552 ( 0.17%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 2,730 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 4,517,625 ( 0.03%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 13,652,470 ( 0.09%) self.len += xs.len(); . } 130 ( 0.00%) } . 611,220 ( 0.00%) pub(super) fn extend_from_slice(&mut self, xs: &[T]) { 1,079,994 ( 0.01%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 5,460 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 260 ( 0.00%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 539,997 ( 0.00%) self.len += xs.len(); . } 713,090 ( 0.00%) } . 390 ( 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. 29,656,821 ( 0.19%) if self.len == self.capacity { . let b = self.take(); . *self = (b.reserve)(b, 1); . } . unsafe { 19,449,771 ( 0.12%) *self.data.add(self.len) = v; 17,387,712 ( 0.11%) self.len += 1; . } 130 ( 0.00%) } . } . . impl Write for Buffer { . fn write(&mut self, xs: &[u8]) -> io::Result { . self.extend_from_slice(xs); . Ok(xs.len()) . } . 468,774 ( 0.00%) fn write_all(&mut self, xs: &[u8]) -> io::Result<()> { 305,610 ( 0.00%) self.extend_from_slice(xs); . Ok(()) 703,161 ( 0.00%) } . . fn flush(&mut self) -> io::Result<()> { . Ok(()) . } . } . . impl Drop for Buffer { 585 ( 0.00%) fn drop(&mut self) { 390 ( 0.00%) let b = self.take(); 30,336,669 ( 0.19%) (b.drop)(b); 390 ( 0.00%) } . } . . impl From> for Buffer { 2,340 ( 0.00%) fn from(mut v: Vec) -> Self { 10,140 ( 0.00%) let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity()); 3,120 ( 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`. 585 ( 0.00%) fn to_vec(b: Buffer) -> Vec { . unsafe { 1,755 ( 0.00%) let Buffer { data, len, capacity, .. } = b; 975 ( 0.00%) mem::forget(b); 195 ( 0.00%) Vec::from_raw_parts(data, len, capacity) . } 390 ( 0.00%) } . 1,560 ( 0.00%) extern "C" fn reserve(b: Buffer, additional: usize) -> Buffer { 1,170 ( 0.00%) let mut v = to_vec(b); . v.reserve(additional); 1,170 ( 0.00%) Buffer::from(v) 1,560 ( 0.00%) } . 390 ( 0.00%) extern "C" fn drop(b: Buffer) { 2,529,437 ( 0.02%) mem::drop(to_vec(b)); 2,528,137 ( 0.02%) } . 5,980 ( 0.00%) Buffer { data, len, capacity, reserve, drop } 780 ( 0.00%) } . } 12,215,980 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs -------------------------------------------------------------------------------- Ir -- line 120 ---------------------------------------- . } . . /// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the . /// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed . /// sizes and avoid calling `memcpy`, which is good for speed. . /// . /// Unsafe because: unchecked indexing at start..start+len . #[inline] 89,721 ( 0.00%) unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { . debug_assert!(len < 8); 9,969 ( 0.00%) let mut i = 0; // current byte index (from LSB) in the output u64 9,969 ( 0.00%) let mut out = 0; 8,058,393 ( 0.05%) 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. 51,066 ( 0.00%) out = unsafe { load_int_le!(buf, start + i, u32) } as u64; 19,859 ( 0.00%) i += 4; . } 16,664,257 ( 0.11%) if i + 1 < len { . // SAFETY: same as above. 8,352,760 ( 0.05%) out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); 4,156,172 ( 0.03%) i += 2 . } 9,282,722 ( 0.06%) if i < len { . // SAFETY: same as above. 13,367,234 ( 0.08%) out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8); 44,696 ( 0.00%) i += 1; . } . debug_assert_eq!(i, len); . out 29,907 ( 0.00%) } . . impl SipHasher { . /// Creates a new `SipHasher` with the two initial keys set to 0. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_deprecated( . since = "1.13.0", . reason = "use `std::collections::hash_map::DefaultHasher` instead" -- line 158 ---------------------------------------- -- line 189 ---------------------------------------- . . /// 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" . )] 8,325 ( 0.00%) pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { 1,609,550 ( 0.01%) SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) } 3,330 ( 0.00%) } . } . . impl Hasher { . #[inline] 9,990 ( 0.00%) fn new_with_keys(key0: u64, key1: u64) -> Hasher { 24,231 ( 0.00%) let mut state = Hasher { . k0: key0, . k1: key1, . length: 0, 6,660 ( 0.00%) state: State { v0: 0, v1: 0, v2: 0, v3: 0 }, . tail: 0, . ntail: 0, . _marker: PhantomData, . }; 1,665 ( 0.00%) state.reset(); . state 3,330 ( 0.00%) } . . #[inline] 3,330 ( 0.00%) fn reset(&mut self) { 1,665 ( 0.00%) self.length = 0; 2,403,042 ( 0.02%) self.state.v0 = self.k0 ^ 0x736f6d6570736575; 2,559,849 ( 0.02%) self.state.v1 = self.k1 ^ 0x646f72616e646f6d; 4,995 ( 0.00%) self.state.v2 = self.k0 ^ 0x6c7967656e657261; 4,995 ( 0.00%) self.state.v3 = self.k1 ^ 0x7465646279746573; 1,665 ( 0.00%) self.ntail = 0; 3,330 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl super::Hasher for SipHasher { . #[inline] . fn write(&mut self, msg: &[u8]) { . self.0.hasher.write(msg) . } -- line 234 ---------------------------------------- -- line 237 ---------------------------------------- . fn finish(&self) -> u64 { . self.0.hasher.finish() . } . } . . #[unstable(feature = "hashmap_internals", issue = "none")] . impl super::Hasher for SipHasher13 { . #[inline] 33,880 ( 0.00%) fn write(&mut self, msg: &[u8]) { 8,470 ( 0.00%) self.hasher.write(msg) 16,940 ( 0.00%) } . . #[inline] 5,048 ( 0.00%) fn finish(&self) -> u64 { 5,048 ( 0.00%) self.hasher.finish() 5,048 ( 0.00%) } . } . . impl super::Hasher for Hasher { . // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined . // for this type. We could add them, copy the `short_write` implementation . // 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] 59,290 ( 0.00%) fn write(&mut self, msg: &[u8]) { 8,470 ( 0.00%) let length = msg.len(); 10,232,030 ( 0.06%) self.length += length; . 8,470 ( 0.00%) let mut needed = 0; . 10,049,802 ( 0.06%) if self.ntail != 0 { 5,116,477 ( 0.03%) needed = 8 - self.ntail; . // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length` 25,545,332 ( 0.16%) self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); 5,094,837 ( 0.03%) if length < needed { 3,503,526 ( 0.02%) self.ntail += length; . return; . } else { 804,158 ( 0.01%) self.state.v3 ^= self.tail; 4,497 ( 0.00%) S::c_rounds(&mut self.state); 1,603,819 ( 0.01%) self.state.v0 ^= self.tail; 801,160 ( 0.01%) self.ntail = 0; . } . } . . // Buffered tail is now flushed, process new input. 2,916,597 ( 0.02%) let len = length - needed; 2,900,579 ( 0.02%) let left = len & 0x7; // len % 8 . 10,686 ( 0.00%) let mut i = needed; 4,452,730 ( 0.03%) 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`. 106,896 ( 0.00%) let mi = unsafe { load_int_le!(msg, i, u64) }; . 13,523 ( 0.00%) self.state.v3 ^= mi; 13,362 ( 0.00%) S::c_rounds(&mut self.state); 13,523 ( 0.00%) self.state.v0 ^= mi; . 47,089 ( 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()`. 3,068,061 ( 0.02%) self.tail = unsafe { u8to64_le(msg, i, left) }; 5,343 ( 0.00%) self.ntail = left; 25,410 ( 0.00%) } . . #[inline] 7,572 ( 0.00%) fn finish(&self) -> u64 { 819,544 ( 0.01%) let mut state = self.state; . 4,014,428 ( 0.03%) let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; . 804,400 ( 0.01%) state.v3 ^= b; 5,048 ( 0.00%) S::c_rounds(&mut state); 804,400 ( 0.01%) state.v0 ^= b; . 806,924 ( 0.01%) state.v2 ^= 0xff; 5,048 ( 0.00%) S::d_rounds(&mut state); . 1,608,800 ( 0.01%) state.v0 ^ state.v1 ^ state.v2 ^ state.v3 5,048 ( 0.00%) } . } . . impl Clone for Hasher { . #[inline] . fn clone(&self) -> Hasher { . Hasher { . k0: self.k0, . k1: self.k1, -- line 332 ---------------------------------------- -- line 353 ---------------------------------------- . fn d_rounds(_: &mut State); . } . . #[derive(Debug, Clone, Default)] . struct Sip13Rounds; . . impl Sip for Sip13Rounds { . #[inline] 32,112 ( 0.00%) fn c_rounds(state: &mut State) { 10,994,659 ( 0.07%) compress!(state); 21,408 ( 0.00%) } . . #[inline] 7,572 ( 0.00%) fn d_rounds(state: &mut State) { 3,338,752 ( 0.02%) compress!(state); 3,338,752 ( 0.02%) compress!(state); 2,539,400 ( 0.02%) compress!(state); 5,048 ( 0.00%) } . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip for Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { -- line 378 ---------------------------------------- 24,105,413 ( 0.15%) -------------------------------------------------------------------------------- -- 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] 4,258,143 ( 0.03%) pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { . // SAFETY: the caller must guarantee that `ptr` is non-null. 10,756,808 ( 0.07%) unsafe { NonNull { pointer: ptr as _ } } 6,261,357 ( 0.04%) } . . /// 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] 664,497 ( 0.00%) pub fn new(ptr: *mut T) -> Option { 1,107,495 ( 0.01%) if !ptr.is_null() { . // SAFETY: The pointer is already checked and is not null 664,497 ( 0.00%) Some(unsafe { Self::new_unchecked(ptr) }) . } else { . None . } 664,497 ( 0.00%) } . . /// 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] 13,238,967 ( 0.08%) pub const fn as_ptr(self) -> *mut T { . self.pointer as *mut T 8,490,358 ( 0.05%) } . . /// 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] 363,552 ( 0.00%) pub const unsafe fn as_ref<'a>(&self) -> &'a T { . // SAFETY: the caller must guarantee that `self` meets all the . // requirements for a reference. 545,328 ( 0.00%) unsafe { &*self.as_ptr() } 363,552 ( 0.00%) } . . /// 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] 669,581 ( 0.00%) pub const fn cast(self) -> NonNull { . // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null 915,792 ( 0.01%) unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) } 457,494 ( 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] 1,006,860 ( 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 2,013,720 ( 0.01%) unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) } 503,430 ( 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")] 118,884 ( 0.00%) pub const fn as_non_null_ptr(self) -> NonNull { . // SAFETY: We know `self` is non-null. 198,140 ( 0.00%) unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) } 79,256 ( 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")] 118,692 ( 0.00%) pub const fn as_mut_ptr(self) -> *mut T { 158,256 ( 0.00%) self.as_non_null_ptr().as_ptr() 79,128 ( 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] 537,292 ( 0.00%) fn from(unique: Unique) -> Self { . // SAFETY: A Unique pointer cannot be null, so the conditions for . // new_unchecked() are respected. 1,074,584 ( 0.01%) unsafe { NonNull::new_unchecked(unique.as_ptr()) } 537,292 ( 0.00%) } . } . . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From<&mut T> for NonNull { . #[inline] 161,176 ( 0.00%) fn from(reference: &mut T) -> Self { . // SAFETY: A mutable reference cannot be null. 218,073 ( 0.00%) unsafe { NonNull { pointer: reference as *mut T } } 241,764 ( 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 ---------------------------------------- 4,012,396 ( 0.03%) -------------------------------------------------------------------------------- -- 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> { 260 ( 0.00%) fn deref_mut(&mut self) -> &mut Self::Target { 130 ( 0.00%) self.0 260 ( 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`. 18,664,213 ( 0.12%) 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> { 585 ( 0.00%) fn drop(&mut self) { 2,529,893 ( 0.02%) self.cell.0.set(self.value.take().unwrap()); 390 ( 0.00%) } . } . 5,058,810 ( 0.03%) let mut put_back_on_drop = PutBackOnDrop { . cell: self, 1,950 ( 0.00%) value: Some(self.0.replace(unsafe { 390 ( 0.00%) let erased = mem::transmute_copy(&replacement); 2,340 ( 0.00%) mem::forget(replacement); 1,950 ( 0.00%) erased . })), . }; . 1,532,216 ( 0.01%) f(RefMutL(put_back_on_drop.value.as_mut().unwrap())) 24,550,013 ( 0.16%) } . . /// Sets the value in `self` to `value` while running `f`. 455 ( 0.00%) pub fn set(&self, value: >::Out, f: impl FnOnce() -> R) -> R { 1,040 ( 0.00%) self.replace(value, |_| f()) 130 ( 0.00%) } . } 1,031,134 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/maybe_uninit.rs -------------------------------------------------------------------------------- Ir -- line 290 ---------------------------------------- . /// ``` . /// . /// [`assume_init`]: MaybeUninit::assume_init . #[stable(feature = "maybe_uninit", since = "1.36.0")] . #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")] . #[must_use = "use `forget` to avoid running Drop code"] . #[inline(always)] . pub const fn new(val: T) -> MaybeUninit { 1,524,099 ( 0.01%) MaybeUninit { value: ManuallyDrop::new(val) } 133,152 ( 0.00%) } . . /// Creates a new `MaybeUninit` in an uninitialized state. . /// . /// Note that dropping a `MaybeUninit` will never call `T`'s drop code. . /// It is your responsibility to make sure `T` gets dropped if it got initialized. . /// . /// See the [type-level documentation][MaybeUninit] for some examples. . /// -- line 307 ---------------------------------------- -- line 314 ---------------------------------------- . /// ``` . #[stable(feature = "maybe_uninit", since = "1.36.0")] . #[rustc_const_stable(feature = "const_maybe_uninit", since = "1.36.0")] . #[must_use] . #[inline(always)] . #[rustc_diagnostic_item = "maybe_uninit_uninit"] . pub const fn uninit() -> MaybeUninit { . MaybeUninit { uninit: () } 1,149,310 ( 0.01%) } . . /// Create a new array of `MaybeUninit` items, in an uninitialized state. . /// . /// Note: in a future Rust version this method may become unnecessary . /// when Rust allows . /// [inline const expressions](https://github.com/rust-lang/rust/issues/76001). . /// The example below could then use `let mut buf = [const { MaybeUninit::::uninit() }; 32];`. . /// -- line 330 ---------------------------------------- -- line 488 ---------------------------------------- . /// unsafe { Pin::new_unchecked(ref_) } . /// } . /// } . /// ``` . #[stable(feature = "maybe_uninit_write", since = "1.55.0")] . #[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")] . #[inline(always)] . pub const fn write(&mut self, val: T) -> &mut T { 11,804,566 ( 0.07%) *self = MaybeUninit::new(val); . // SAFETY: We just initialized this value. . unsafe { self.assume_init_mut() } 139,673 ( 0.00%) } . . /// Gets a pointer to the contained value. Reading from this pointer or turning it . /// into a reference is undefined behavior unless the `MaybeUninit` is initialized. . /// Writing to memory that this pointer (non-transitively) points to is undefined behavior . /// (except inside an `UnsafeCell`). . /// . /// # Examples . /// -- line 507 ---------------------------------------- -- line 568 ---------------------------------------- . /// . /// (Notice that the rules around references to uninitialized data are not finalized yet, but . /// until they are, it is advisable to avoid them.) . #[stable(feature = "maybe_uninit", since = "1.36.0")] . #[rustc_const_unstable(feature = "const_maybe_uninit_as_mut_ptr", issue = "75251")] . #[inline(always)] . pub const fn as_mut_ptr(&mut self) -> *mut T { . // `MaybeUninit` and `ManuallyDrop` are both `repr(transparent)` so we can cast the pointer. 3,186,220 ( 0.02%) self as *mut _ as *mut T . } . . /// Extracts the value from the `MaybeUninit` container. This is a great way . /// to ensure that the data will get dropped, because the resulting `T` is . /// subject to the usual drop handling. . /// . /// # Safety . /// -- line 584 ---------------------------------------- -- line 626 ---------------------------------------- . #[inline(always)] . #[rustc_diagnostic_item = "assume_init"] . #[track_caller] . pub const unsafe fn assume_init(self) -> T { . // SAFETY: the caller must guarantee that `self` is initialized. . // This also means that `self` must be a `value` variant. . unsafe { . intrinsics::assert_inhabited::(); 9,740,144 ( 0.06%) ManuallyDrop::into_inner(self.value) . } 709,288 ( 0.00%) } . . /// Reads the value from the `MaybeUninit` container. The resulting `T` is subject . /// to the usual drop handling. . /// . /// Whenever possible, it is preferable to use [`assume_init`] instead, which . /// prevents duplicating the content of the `MaybeUninit`. . /// . /// # Safety -- line 644 ---------------------------------------- -- line 696 ---------------------------------------- . #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init_read", issue = "63567")] . #[inline(always)] . #[track_caller] . pub const unsafe fn assume_init_read(&self) -> T { . // SAFETY: the caller must guarantee that `self` is initialized. . // Reading from `self.as_ptr()` is safe since `self` should be initialized. . unsafe { . intrinsics::assert_inhabited::(); 262 ( 0.00%) self.as_ptr().read() . } . } . . /// Drops the contained value in place. . /// . /// If you have ownership of the `MaybeUninit`, you can also use . /// [`assume_init`] as an alternative. . /// -- line 712 ---------------------------------------- -- line 723 ---------------------------------------- . /// this does not constitute a stable guarantee), because the only . /// requirement the compiler knows about it is that the data pointer must be . /// non-null. Dropping such a `Vec` however will cause undefined . /// behaviour. . /// . /// [`assume_init`]: MaybeUninit::assume_init . /// [`Vec`]: ../../std/vec/struct.Vec.html . #[stable(feature = "maybe_uninit_extra", since = "1.60.0")] 101,193 ( 0.00%) pub unsafe fn assume_init_drop(&mut self) { . // SAFETY: the caller must guarantee that `self` is initialized and . // satisfies all invariants of `T`. . // Dropping the value in place is safe if that is the case. . unsafe { ptr::drop_in_place(self.as_mut_ptr()) } 22,240 ( 0.00%) } . . /// Gets a shared reference to the contained value. . /// . /// This can be useful when we want to access a `MaybeUninit` that has been . /// initialized but don't have ownership of the `MaybeUninit` (preventing the use . /// of `.assume_init()`). . /// . /// # Safety -- line 744 ---------------------------------------- 3,116,733 ( 0.02%) -------------------------------------------------------------------------------- -- 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] 121,704 ( 0.00%) fn ne(&self, other: &Rhs) -> bool { 343,551 ( 0.00%) !self.eq(other) 162,272 ( 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); . /// ``` 72,160 ( 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 { 114,891 ( 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] 878,199 ( 0.01%) fn max(self, other: Self) -> Self . where . Self: Sized, . { 905,206 ( 0.01%) max_by(self, other, Ord::cmp) 585,466 ( 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] 21,057 ( 0.00%) fn min(self, other: Self) -> Self . where . Self: Sized, . { 20,302 ( 0.00%) min_by(self, other, Ord::cmp) 14,038 ( 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 { 548,269 ( 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. 2,744,634 ( 0.02%) !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 1140 ---------------------------------------- . /// 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] . fn gt(&self, other: &Rhs) -> bool { 3,038,004 ( 0.02%) matches!(self.partial_cmp(other), Some(Greater)) . } . . /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1156 ---------------------------------------- -- 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] 144 ( 0.00%) fn ge(&self, other: &Rhs) -> bool { 4,086 ( 0.00%) matches!(self.partial_cmp(other), Some(Greater | Equal)) 240 ( 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")] 13,878 ( 0.00%) pub fn min(v1: T, v2: T) -> T { 9,252 ( 0.00%) v1.min(v2) 9,252 ( 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")] 21,057 ( 0.00%) pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { 3,559,953 ( 0.02%) match compare(&v1, &v2) { 24,140 ( 0.00%) Ordering::Less | Ordering::Equal => v1, 2,952 ( 0.00%) Ordering::Greater => v2, . } 62,245 ( 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")] 348 ( 0.00%) pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { 232 ( 0.00%) min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) 232 ( 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")] 876,984 ( 0.01%) pub fn max(v1: T, v2: T) -> T { 584,656 ( 0.00%) v1.max(v2) 584,656 ( 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")] 878,199 ( 0.01%) pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { 8,232,429 ( 0.05%) match compare(&v1, &v2) { 624,644 ( 0.00%) Ordering::Less | Ordering::Equal => v2, 411,246 ( 0.00%) Ordering::Greater => v1, . } 2,478,946 ( 0.02%) } . . /// 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] 468,085 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] 112,116 ( 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] 15,393,543 ( 0.10%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] 368,108 ( 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] 1,499,000 ( 0.01%) fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 159,172,351 ( 1.01%) if *self < *other { Less } 707,814 ( 0.00%) else if *self == *other { Equal } 138,114 ( 0.00%) else { Greater } 899,400 ( 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. 29,082 ( 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] 4,304,200 ( 0.03%) fn eq(&self, other: &&B) -> bool { 9,132,293 ( 0.06%) PartialEq::eq(*self, *other) 3,804,812 ( 0.02%) } . #[inline] 8,915 ( 0.00%) fn ne(&self, other: &&B) -> bool { 66 ( 0.00%) PartialEq::ne(*self, *other) 123,948 ( 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 { -- line 1496 ---------------------------------------- -- line 1516 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for &A . where . A: Ord, . { . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(*self, *other) 76,977 ( 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 ---------------------------------------- 16,531,826 ( 0.10%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs -------------------------------------------------------------------------------- Ir . use super::map::MIN_LEN; . use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef}; . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { . /// Removes a key-value pair from the tree, and returns that pair, as well as . /// the leaf edge corresponding to that former pair. It's possible this empties . /// a root node that is internal, which the caller should pop from the map . /// holding the tree. The caller should also decrement the map's length. 5,198,467 ( 0.03%) pub fn remove_kv_tracking( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 4,158,640 ( 0.03%) match self.force() { 7,265,356 ( 0.05%) Leaf(node) => node.remove_leaf_kv(handle_emptied_internal_root), . Internal(node) => node.remove_internal_kv(handle_emptied_internal_root), . } 6,238,127 ( 0.04%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { 7,277,620 ( 0.05%) fn remove_leaf_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 4,910,807 ( 0.03%) let (old_kv, mut pos) = self.remove(); . let len = pos.reborrow().into_node().len(); 2,079,320 ( 0.01%) if len < MIN_LEN { . let idx = pos.idx(); . // We have to temporarily forget the child type, because there is no . // distinct node type for the immediate parents of a leaf. . let new_pos = match pos.into_node().forget_type().choose_parent_kv() { . Ok(Left(left_parent_kv)) => { . debug_assert!(left_parent_kv.right_child_len() == MIN_LEN - 1); 120,349 ( 0.00%) if left_parent_kv.can_merge() { 1,658,522 ( 0.01%) left_parent_kv.merge_tracking_child_edge(Right(idx)) . } else { . debug_assert!(left_parent_kv.left_child_len() > MIN_LEN); 13,749 ( 0.00%) left_parent_kv.steal_left(idx) . } . } . Ok(Right(right_parent_kv)) => { . debug_assert!(right_parent_kv.left_child_len() == MIN_LEN - 1); 3,816 ( 0.00%) if right_parent_kv.can_merge() { 35,677 ( 0.00%) right_parent_kv.merge_tracking_child_edge(Left(idx)) . } else { . debug_assert!(right_parent_kv.right_child_len() > MIN_LEN); 8,919 ( 0.00%) right_parent_kv.steal_right(idx) . } . } . Err(pos) => unsafe { Handle::new_edge(pos, idx) }, . }; . // SAFETY: `new_pos` is the leaf we started from or a sibling. 1,403,506 ( 0.01%) pos = unsafe { new_pos.cast_to_leaf_unchecked() }; . . // Only if we merged, the parent (if any) has shrunk, but skipping . // the following step otherwise does not pay off in benchmarks. . // . // SAFETY: We won't destroy or rearrange the leaf where `pos` is at . // by handling its parent recursively; at worst we will destroy or . // rearrange the parent through the grandparent, thus change the . // link to the parent inside the leaf. . if let Ok(parent) = unsafe { pos.reborrow_mut() }.into_node().ascend() { 40,628 ( 0.00%) if !parent.into_node().forget_type().fix_node_and_affected_ancestors() { . handle_emptied_internal_root(); . } . } . } 8,560,924 ( 0.05%) (old_kv, pos) 8,317,280 ( 0.05%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { . fn remove_internal_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { . // Remove an adjacent KV from its leaf and then put it back in place of . // the element we were asked to remove. Prefer the left adjacent KV, . // for the reasons listed in `choose_parent_kv`. . let left_leaf_kv = self.left_edge().descend().last_leaf_edge().left_kv(); . let left_leaf_kv = unsafe { left_leaf_kv.ok().unwrap_unchecked() }; 25,316 ( 0.00%) let (left_kv, left_hole) = left_leaf_kv.remove_leaf_kv(handle_emptied_internal_root); . . // The internal node may have been stolen from or merged. Go back right . // to find where the original KV ended up. . let mut internal = unsafe { left_hole.next_kv().ok().unwrap_unchecked() }; 1,265 ( 0.00%) let old_kv = internal.replace_kv(left_kv.0, left_kv.1); . let pos = internal.next_leaf_edge(); 15,097 ( 0.00%) (old_kv, pos) . } . } 5,505,544 ( 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")] 4,860 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 2,430 ( 0.00%) from_str_radix(src, radix) 7,290 ( 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 { 1,330,326 ( 0.01%) 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 { 1,670,494 ( 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 { 1,348,541 ( 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 { 76,576,100 ( 0.48%) 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] 729,730 ( 0.00%) pub const fn checked_add(self, rhs: Self) -> Option { 583,788 ( 0.00%) let (a, b) = self.overflowing_add(rhs); 1,459,460 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 583,784 ( 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`. 3,046,912 ( 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 498 ---------------------------------------- . #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")] . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), 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] 3,715 ( 0.00%) pub const fn checked_sub(self, rhs: Self) -> Option { 2,972 ( 0.00%) let (a, b) = self.overflowing_sub(rhs); 7,430 ( 0.00%) if unlikely!(b) {None} else {Some(a)} 2,972 ( 0.00%) } . . /// Unchecked integer subtraction. 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 517 ---------------------------------------- -- 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`. 459,423 ( 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] 1,168,134 ( 0.01%) pub const fn checked_mul(self, rhs: Self) -> Option { 778,756 ( 0.00%) let (a, b) = self.overflowing_mul(rhs); 1,946,890 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 778,756 ( 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 2,088 ( 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 { 952,437 ( 0.01%) intrinsics::saturating_add(self, rhs) 1,424 ( 0.00%) } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1052 ---------------------------------------- -- 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 { 44,090 ( 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 1104 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn saturating_mul(self, rhs: Self) -> Self { 6 ( 0.00%) match self.checked_mul(rhs) { . Some(x) => x, . None => Self::MAX, . } . } . . /// Saturating integer division. Computes `self / rhs`, saturating at the . /// numeric bounds instead of overflowing. . /// -- line 1120 ---------------------------------------- -- 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 { 43,841,737 ( 0.28%) 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 { 9,454,942 ( 0.06%) 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 { 23,750,287 ( 0.15%) 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)] 53 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 4,727,744 ( 0.03%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); 291,892 ( 0.00%) (a as Self, b) 583,890 ( 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 1588 ---------------------------------------- . #[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)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 637,045 ( 0.00%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); 1,486 ( 0.00%) (a as Self, b) 2,972 ( 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) { 9,266,104 ( 0.06%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); 389,378 ( 0.00%) (a as Self, b) 778,756 ( 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 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 { 921 ( 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")] 285 ( 0.00%) const fn one_less_than_next_power_of_two(self) -> Self { 175,298 ( 0.00%) if self <= 1 { return 0; } . 253,781 ( 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. 759,749 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 254,113 ( 0.00%) <$SelfT>::MAX >> z 380 ( 0.00%) } . . /// 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). . /// . /// # Examples -- line 2172 ---------------------------------------- -- line 2178 ---------------------------------------- . #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")] . /// ``` . #[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] 190 ( 0.00%) pub const fn next_power_of_two(self) -> Self { 331,633 ( 0.00%) self.one_less_than_next_power_of_two() + 1 190 ( 0.00%) } . . /// 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 . /// . /// Basic usage: -- line 2196 ---------------------------------------- -- 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] 325 ( 0.00%) pub const fn to_le_bytes(self) -> [u8; mem::size_of::()] { 260 ( 0.00%) self.to_le().to_ne_bytes() 195 ( 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] 3,452 ( 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 1,726 ( 0.00%) unsafe { mem::transmute(self) } 5,178 ( 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] 520 ( 0.00%) pub const fn from_le_bytes(bytes: [u8; mem::size_of::()]) -> Self { 650 ( 0.00%) Self::from_le(Self::from_ne_bytes(bytes)) 260 ( 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] 520 ( 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 780 ( 0.00%) unsafe { mem::transmute(bytes) } 260 ( 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 ---------------------------------------- 2,397,561 ( 0.02%) -------------------------------------------------------------------------------- -- 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)] 184,852,929 ( 1.17%) 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 5,549 ( 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")] 1,306,832 ( 0.01%) pub const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { 1,633,540 ( 0.01%) from_raw_parts(data.cast(), len) 653,416 ( 0.00%) } . . /// 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")] 5,127,760 ( 0.03%) pub const fn slice_from_raw_parts_mut(data: *mut T, len: usize) -> *mut [T] { 1,922,910 ( 0.01%) from_raw_parts_mut(data.cast(), len) 1,281,940 ( 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 { 16 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 16 ( 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 413 ---------------------------------------- . /// } . /// . /// assert_eq!(x, [7, 8, 3, 4]); . /// assert_eq!(y, [1, 2, 9]); . /// ``` . #[inline] . #[stable(feature = "swap_nonoverlapping", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 384 ( 0.00%) pub const unsafe fn swap_nonoverlapping(x: *mut T, y: *mut T, count: usize) { 128 ( 0.00%) let x = x as *mut u8; 64 ( 0.00%) let y = y as *mut u8; 448 ( 0.00%) let len = mem::size_of::() * count; . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. 128 ( 0.00%) unsafe { swap_nonoverlapping_bytes(x, y, len) } 128 ( 0.00%) } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 320 ( 0.00%) pub(crate) const unsafe fn swap_nonoverlapping_one(x: *mut T, y: *mut T) { . // NOTE(eddyb) SPIR-V's Logical addressing model doesn't allow for arbitrary . // reinterpretation of values as (chunkable) byte arrays, and the loop in the . // block optimization in `swap_nonoverlapping_bytes` is hard to rewrite back . // into the (unoptimized) direct swapping implementation, so we disable it. . // FIXME(eddyb) the block optimization also prevents MIR optimizations from . // understanding `mem::replace`, `Option::take`, etc. - a better overall . // solution might be to make `swap_nonoverlapping` into an intrinsic, which . // a backend can choose to implement using the block optimization, or not. . #[cfg(not(target_arch = "spirv"))] 64 ( 0.00%) { . // Only apply the block optimization in `swap_nonoverlapping_bytes` for types . // at least as large as the block size, to avoid pessimizing codegen. 64 ( 0.00%) if mem::size_of::() >= 32 { . // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`. 128 ( 0.00%) unsafe { swap_nonoverlapping(x, y, 1) }; . 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 { 1,010 ( 0.00%) let z = read(x); . copy_nonoverlapping(y, x, 1); . write(y, z); . } 192 ( 0.00%) } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 640 ( 0.00%) const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { . // The approach here is to utilize simd to swap x & y efficiently. Testing reveals . // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel . // Haswell E processors. LLVM is more able to optimize if we give a struct a . // #[repr(simd)], even if we don't actually use this struct directly. . // . // FIXME repr(simd) broken on emscripten and redox . #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))] . struct Block(u64, u64, u64, u64); . struct UnalignedBlock(u64, u64, u64, u64); . 64 ( 0.00%) let block_size = mem::size_of::(); . . // Loop through x & y, copying them `Block` at a time . // The optimizer should unroll the loop fully for most types . // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively 64 ( 0.00%) let mut i = 0; 1,152 ( 0.00%) while i + block_size <= len { . // Create some uninitialized memory as scratch space . // Declaring `t` here avoids aligning the stack when this loop is unused . let mut t = mem::MaybeUninit::::uninit(); 192 ( 0.00%) let t = t.as_mut_ptr() as *mut u8; . . // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid . // for `len` bytes, `x + i` and `y + i` must be valid addresses, which fulfills the . // safety contract for `add`. . // . // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned, . // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`. . unsafe { 384 ( 0.00%) let x = x.add(i); 384 ( 0.00%) let y = y.add(i); . . // Swap a block of bytes of x & y, using t as a temporary buffer . // This should be optimized into efficient SIMD operations where available 128 ( 0.00%) copy_nonoverlapping(x, t, block_size); 128 ( 0.00%) copy_nonoverlapping(y, x, block_size); 128 ( 0.00%) copy_nonoverlapping(t, y, block_size); . } 448 ( 0.00%) i += block_size; . } . 192 ( 0.00%) if i < len { . // Swap any remaining bytes . let mut t = mem::MaybeUninit::::uninit(); . let rem = len - i; . . let t = t.as_mut_ptr() as *mut u8; . . // SAFETY: see previous safety comment. . unsafe { -- line 514 ---------------------------------------- -- line 515 ---------------------------------------- . let x = x.add(i); . let y = y.add(i); . . copy_nonoverlapping(x, t, rem); . copy_nonoverlapping(y, x, rem); . copy_nonoverlapping(t, y, rem); . } . } 192 ( 0.00%) } . . /// Moves `src` into the pointed `dst`, returning the previous `dst` value. . /// . /// Neither value is dropped. . /// . /// This function is semantically equivalent to [`mem::replace`] except that it . /// operates on raw pointers instead of references. When references are . /// available, [`mem::replace`] should be preferred. -- line 531 ---------------------------------------- -- 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")] 8,146,973 ( 0.05%) 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); . } . 2,567,886 ( 0.02%) 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 { 16,599,159 ( 0.11%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 88,567,329 ( 0.56%) tmp.assume_init() . } 4,240,620 ( 0.03%) } . . /// 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")] 6,060,962 ( 0.04%) 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 { 110,693,059 ( 0.70%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } 3,524,396 ( 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. 86,344 ( 0.00%) return wrapping_sub( 186,032 ( 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 { 3,165,153 ( 0.02%) 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 ---------------------------------------- 33,134,488 ( 0.21%) -------------------------------------------------------------------------------- -- 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 { 7,583,241 ( 0.05%) unsafe extern "C" fn call R>(env: &mut Env, arg: A) -> R { . (*(env as *mut _ as *mut F))(arg) 10,110,988 ( 0.06%) } . 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 { 40,443,952 ( 0.26%) unsafe { (self.call)(self.env, arg) } . } . } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 11,708,420 ( 0.07%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 2,425,225 ( 0.02%) Token(Token), . /// A delimited sequence of token trees. 380,526 ( 0.00%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 3,438 ( 0.00%) match self { 7,081 ( 0.00%) TokenTree::Token(token) => token.span, 3,476 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 850 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 3,438 ( 0.00%) match self { 850 ( 0.00%) TokenTree::Token(token) => token.span = span, 1,738 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 1,719 ( 0.00%) } . 387,078 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 2,146,780 ( 0.01%) TokenTree::Token(Token::new(kind, span)) 387,078 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 75,302 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 225,906 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 75,302 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 74,315 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 222,945 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 74,315 ( 0.00%) } . 60,009 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 40,006 ( 0.00%) match self { 180,027 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 80,012 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 21,501 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 169,900 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 19,112 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { -- line 131 ---------------------------------------- -- line 135 ---------------------------------------- . . /// A lazy version of [`TokenStream`], which defers creation . /// of an actual `TokenStream` until it is needed. . /// `Box` is here only to reduce the structure size. . #[derive(Clone)] . pub struct LazyTokenStream(Lrc>); . . impl LazyTokenStream { 204 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 204 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 14,853 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 355,228 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 355,228 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. 3,711 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 6,143 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 79,303 ( 0.00%) .flat_map(|tree| match &tree.0 { 44,762 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 111,905 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } 48,640 ( 0.00%) AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( 7,296 ( 0.00%) TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), 2,432 ( 0.00%) tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); . let mut inner_attrs = Vec::new(); . for attr in &data.attrs { . match attr.style { . crate::AttrStyle::Outer => { -- line 223 ---------------------------------------- -- line 279 ---------------------------------------- . flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } . flat.extend(target_tokens); . flat.into_iter() . } . }) . .collect(); . TokenStream::new(trees) 7,422 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 1,254,170 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 371 ---------------------------------------- . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 1,463,455 ( 0.01%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 186,473 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { 5,482 ( 0.00%) fn from_iter>(iter: I) -> Self { 5,758 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) 8,223 ( 0.00%) } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) . } -- line 400 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 35,779 ( 0.00%) self.0.is_empty() 35,779 ( 0.00%) } . . pub fn len(&self) -> usize { 1,322,278 ( 0.01%) self.0.len() 7,924 ( 0.00%) } . 798,624 ( 0.01%) pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { 399,306 ( 0.00%) match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with . // the elements from the subsequent streams. This requires . // using `make_mut()` on the first stream, and in practice this . // doesn't cause cloning 99.9% of the time. . // -- line 425 ---------------------------------------- -- line 430 ---------------------------------------- . . // Determine how much the first stream will be extended. . // Needed to avoid quadratic blow up from on-the-fly . // reallocations (#57735). . let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum(); . . // Get the first stream. If it's `None`, create an empty . // stream. 198,088 ( 0.00%) let mut iter = streams.drain(..); 198,088 ( 0.00%) let mut first_stream_lrc = iter.next().unwrap().0; . . // Append the elements to the first stream, after reserving . // space for them. 99,044 ( 0.00%) let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc); . first_vec_mut.reserve(num_appends); 1,658,649 ( 0.01%) for stream in iter { . first_vec_mut.extend(stream.0.iter().cloned()); . } . . // Create the final `TokenStream`. 198,088 ( 0.00%) TokenStream(first_stream_lrc) . } . } 898,452 ( 0.01%) } . . pub fn trees(&self) -> Cursor { 97,437 ( 0.00%) self.clone().into_trees() 194,874 ( 0.00%) } . 92,504 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 185,008 ( 0.00%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 803 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 10,314 ( 0.00%) .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint)) . .collect(), . )) . } . } . . // 99.5%+ of the time we have 1 or 2 elements in this vector. . #[derive(Clone)] . pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>); . . impl TokenStreamBuilder { 99,828 ( 0.00%) pub fn new() -> TokenStreamBuilder { 99,828 ( 0.00%) TokenStreamBuilder(SmallVec::new()) 99,828 ( 0.00%) } . 4,389,048 ( 0.03%) pub fn push>(&mut self, stream: T) { 487,672 ( 0.00%) let mut stream = stream.into(); . . // If `self` is not empty and the last tree within the last stream is a . // token tree marked with `Joint`... 1,463,016 ( 0.01%) if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() { 2,311,458 ( 0.01%) if let Some((TokenTree::Token(last_token), Spacing::Joint)) = last_stream_lrc.last() { . // ...and `stream` is not empty and the first tree within it is . // a token tree... . let TokenStream(ref mut stream_lrc) = stream; 231,364 ( 0.00%) if let Some((TokenTree::Token(token), spacing)) = stream_lrc.first() { . // ...and the two tokens can be glued together... 231,364 ( 0.00%) if let Some(glued_tok) = last_token.glue(&token) { . // ...then do so, by overwriting the last token . // tree in `self` and removing the first token tree . // from `stream`. This requires using `make_mut()` . // on the last stream in `self` and on `stream`, . // and in practice this doesn't cause cloning 99.9% . // of the time. . . // Overwrite the last token tree with the merged . // token. 33,052 ( 0.00%) let last_vec_mut = Lrc::make_mut(last_stream_lrc); 760,196 ( 0.00%) *last_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing); . . // Remove the first token tree from `stream`. (This . // is almost always the only tree in `stream`.) 33,052 ( 0.00%) let stream_vec_mut = Lrc::make_mut(stream_lrc); 198,312 ( 0.00%) stream_vec_mut.remove(0); . . // Don't push `stream` if it's empty -- that could . // block subsequent token gluing, by getting . // between two token trees that should be glued . // together. 99,156 ( 0.00%) if !stream.is_empty() { . self.0.push(stream); . } . return; . } . } . } . } . self.0.push(stream); 3,901,376 ( 0.02%) } . 99,828 ( 0.00%) pub fn build(self) -> TokenStream { 598,968 ( 0.00%) TokenStream::from_streams(self.0) 199,656 ( 0.00%) } . } . . /// By-reference iterator over a [`TokenStream`]. . #[derive(Clone)] . pub struct CursorRef<'t> { . stream: &'t TokenStream, . index: usize, . } -- line 550 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 663,999 ( 0.00%) fn next(&mut self) -> Option { 1,047,556 ( 0.01%) self.next_with_spacing().map(|(tree, _)| tree) 885,332 ( 0.01%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 3,651,510 ( 0.02%) pub fn next_with_spacing(&mut self) -> Option { 2,854,905 ( 0.02%) if self.index < self.stream.len() { 1,367,084 ( 0.01%) self.index += 1; 3,860,563 ( 0.02%) Some(self.stream.0[self.index - 1].clone()) . } else { 357,586 ( 0.00%) None . } 4,381,812 ( 0.03%) } . . pub fn index(&self) -> usize { . self.index . } . . pub fn append(&mut self, new_stream: TokenStream) { . if new_stream.is_empty() { . return; . } . let index = self.index; . let stream = mem::take(&mut self.stream); . *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees(); . self.index = index; . } . 340,576 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 681,152 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 681,152 ( 0.00%) } . } . 548,211 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 77,468 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 154,936 ( 0.00%) } . 10,316 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 5,158 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 31,815 ( 0.00%) } . 79,040 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 59,280 ( 0.00%) } . } 2,661,595 ( 0.02%) -------------------------------------------------------------------------------- -- 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); . 218,481 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 231,328 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 492,153 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 67,370 ( 0.00%) i += 2 . } . 231,328 ( 0.00%) if i < count { 168,772 ( 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::(); 3,195,267 ( 0.02%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 21,972,875 ( 0.14%) 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); . } . 6,938,014 ( 0.04%) self.nbuf = nbuf + size; . . return; . } . 1,170,819 ( 0.01%) 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)] 349,426 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 349,426 ( 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 { 3,494,260 ( 0.02%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 2,795,408 ( 0.02%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 3,144,834 ( 0.02%) 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. 1,663,490 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 1,397,704 ( 0.01%) self.processed += BUFFER_SIZE; 698,852 ( 0.00%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 25,061 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 719,847 ( 0.00%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 263,598 ( 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); . } . } . 133,124 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 128,184 ( 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)] 77,535 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 15,507 ( 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. 46,521 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 15,507 ( 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. 31,014 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 105,452 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 120,959 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 210,904 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 31,014 ( 0.00%) let input_left = length - processed; 27,105 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 36,104 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 36,104 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 36,104 ( 0.00%) self.state.v0 ^= elem; 72,208 ( 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); . 15,507 ( 0.00%) self.nbuf = extra_bytes_left; 77,535 ( 0.00%) self.processed += nbuf + processed; 93,042 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 178,908 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 238,544 ( 0.00%) let mut state = self.state; . . for i in 0..last { 151,257 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 151,257 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 151,257 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 119,272 ( 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); 45,152 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 161,803 ( 0.00%) let length = self.processed + self.nbuf; 114,024 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 57,012 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 57,012 ( 0.00%) state.v0 ^= b; . 57,012 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 188,780 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 74,752 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 74,752 ( 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) { 12,976,879 ( 0.08%) compress!(state); 13,945,566 ( 0.09%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 377,552 ( 0.00%) compress!(state); 377,552 ( 0.00%) compress!(state); 377,552 ( 0.00%) compress!(state); 320,542 ( 0.00%) compress!(state); . } . } 2,519,937 ( 0.02%) -------------------------------------------------------------------------------- -- 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 . // . 21,894,814 ( 0.14%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 16,421,109 ( 0.10%) 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. 1,071,468 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 1,607,202 ( 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) { 5,740,884 ( 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 { 1,971,788 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 3,943,576 ( 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/proc-macro2-1.0.36/src/wrapper.rs -------------------------------------------------------------------------------- Ir -- line 3 ---------------------------------------- . use std::fmt::{self, Debug, Display}; . use std::iter::FromIterator; . use std::ops::RangeBounds; . use std::panic; . #[cfg(super_unstable)] . use std::path::PathBuf; . use std::str::FromStr; . 621,831 ( 0.00%) #[derive(Clone)] . pub(crate) enum TokenStream { 177,666 ( 0.00%) Compiler(DeferredTokenStream), . Fallback(fallback::TokenStream), . } . . // Work around https://github.com/rust-lang/rust/issues/65080. . // In `impl Extend for TokenStream` which is used heavily by quote, . // we hold on to the appended tokens and do proc_macro::TokenStream::extend as . // late as possible to batch together consecutive uses of the Extend impl. 414,554 ( 0.00%) #[derive(Clone)] . pub(crate) struct DeferredTokenStream { 236,888 ( 0.00%) stream: proc_macro::TokenStream, 148,055 ( 0.00%) extra: Vec, . } . . pub(crate) enum LexError { . Compiler(proc_macro::LexError), . Fallback(fallback::LexError), . } . . impl LexError { -- line 32 ---------------------------------------- -- line 37 ---------------------------------------- . } . } . . fn mismatch() -> ! { . panic!("stable/nightly mismatch") . } . . impl DeferredTokenStream { 512,364 ( 0.00%) fn new(stream: proc_macro::TokenStream) -> Self { 683,152 ( 0.00%) DeferredTokenStream { 170,788 ( 0.00%) stream, 341,576 ( 0.00%) extra: Vec::new(), . } 170,788 ( 0.00%) } . . fn is_empty(&self) -> bool { . self.stream.is_empty() && self.extra.is_empty() . } . 375,090 ( 0.00%) fn evaluate_now(&mut self) { . // If-check provides a fast short circuit for the common case of `extra` . // being empty, which saves a round trip over the proc macro bridge. . // Improves macro expansion time in winrt by 6% in debug mode. 625,150 ( 0.00%) if !self.extra.is_empty() { 512,088 ( 0.00%) self.stream.extend(self.extra.drain(..)); . } 250,060 ( 0.00%) } . 186,998 ( 0.00%) fn into_token_stream(mut self) -> proc_macro::TokenStream { 280,497 ( 0.00%) self.evaluate_now(); 186,998 ( 0.00%) self.stream 467,495 ( 0.00%) } . } . . impl TokenStream { 199,701 ( 0.00%) pub fn new() -> Self { 266,268 ( 0.00%) if inside_proc_macro() { 1,065,072 ( 0.01%) TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::new())) . } else { . TokenStream::Fallback(fallback::TokenStream::new()) . } 133,134 ( 0.00%) } . . pub fn is_empty(&self) -> bool { . match self { . TokenStream::Compiler(tts) => tts.is_empty(), . TokenStream::Fallback(tts) => tts.is_empty(), . } . } . 63,062 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::TokenStream { 94,593 ( 0.00%) match self { 504,496 ( 0.00%) TokenStream::Compiler(s) => s.into_token_stream(), . TokenStream::Fallback(_) => mismatch(), . } 157,655 ( 0.00%) } . . fn unwrap_stable(self) -> fallback::TokenStream { . match self { . TokenStream::Compiler(_) => mismatch(), . TokenStream::Fallback(s) => s, . } . } . } . . impl FromStr for TokenStream { . type Err = LexError; . 56,966 ( 0.00%) fn from_str(src: &str) -> Result { 40,690 ( 0.00%) if inside_proc_macro() { 154,622 ( 0.00%) Ok(TokenStream::Compiler(DeferredTokenStream::new( 130,208 ( 0.00%) proc_macro_parse(src)?, . ))) . } else { . Ok(TokenStream::Fallback(src.parse()?)) . } 16,276 ( 0.00%) } . } . . // Work around https://github.com/rust-lang/rust/issues/58736. 24,414 ( 0.00%) fn proc_macro_parse(src: &str) -> Result { 179,036 ( 0.00%) let result = panic::catch_unwind(|| src.parse().map_err(LexError::Compiler)); 89,518 ( 0.00%) result.unwrap_or_else(|_| Err(LexError::call_site())) 24,414 ( 0.00%) } . . impl Display for TokenStream { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . TokenStream::Compiler(tts) => Display::fmt(&tts.clone().into_token_stream(), f), . TokenStream::Fallback(tts) => Display::fmt(tts, f), . } . } . } . . impl From for TokenStream { 780 ( 0.00%) fn from(inner: proc_macro::TokenStream) -> TokenStream { 1,820 ( 0.00%) TokenStream::Compiler(DeferredTokenStream::new(inner)) 260 ( 0.00%) } . } . . impl From for proc_macro::TokenStream { 130 ( 0.00%) fn from(inner: TokenStream) -> proc_macro::TokenStream { 195 ( 0.00%) match inner { 1,430 ( 0.00%) TokenStream::Compiler(inner) => inner.into_token_stream(), . TokenStream::Fallback(inner) => inner.to_string().parse().unwrap(), . } 195 ( 0.00%) } . } . . impl From for TokenStream { . fn from(inner: fallback::TokenStream) -> TokenStream { . TokenStream::Fallback(inner) . } . } . . // Assumes inside_proc_macro(). 648,578 ( 0.00%) fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree { 648,578 ( 0.00%) match token { 1,224,580 ( 0.01%) TokenTree::Group(tt) => tt.inner.unwrap_nightly().into(), 530,032 ( 0.00%) TokenTree::Punct(tt) => { 1,113,658 ( 0.01%) let spacing = match tt.spacing() { 26,797 ( 0.00%) Spacing::Joint => proc_macro::Spacing::Joint, 211,422 ( 0.00%) Spacing::Alone => proc_macro::Spacing::Alone, . }; 1,325,080 ( 0.01%) let mut punct = proc_macro::Punct::new(tt.as_char(), spacing); 1,987,620 ( 0.01%) punct.set_span(tt.span().inner.unwrap_nightly()); 1,060,064 ( 0.01%) punct.into() . } 2,497,420 ( 0.02%) TokenTree::Ident(tt) => tt.inner.unwrap_nightly().into(), 147,706 ( 0.00%) TokenTree::Literal(tt) => tt.inner.unwrap_nightly().into(), . } 972,867 ( 0.01%) } . . impl From for TokenStream { . fn from(token: TokenTree) -> TokenStream { . if inside_proc_macro() { . TokenStream::Compiler(DeferredTokenStream::new(into_compiler_token(token).into())) . } else { . TokenStream::Fallback(token.into()) . } . } . } . . impl FromIterator for TokenStream { 17,144 ( 0.00%) fn from_iter>(trees: I) -> Self { 30,002 ( 0.00%) if inside_proc_macro() { 60,004 ( 0.00%) TokenStream::Compiler(DeferredTokenStream::new( 98,578 ( 0.00%) trees.into_iter().map(into_compiler_token).collect(), . )) . } else { . TokenStream::Fallback(trees.into_iter().collect()) . } 8,572 ( 0.00%) } . } . . impl FromIterator for TokenStream { . fn from_iter>(streams: I) -> Self { . let mut streams = streams.into_iter(); . match streams.next() { . Some(TokenStream::Compiler(mut first)) => { . first.evaluate_now(); -- line 197 ---------------------------------------- -- line 209 ---------------------------------------- . TokenStream::Fallback(first) . } . None => TokenStream::new(), . } . } . } . . impl Extend for TokenStream { 1,170,668 ( 0.01%) fn extend>(&mut self, stream: I) { 878,001 ( 0.01%) match self { 878,001 ( 0.01%) TokenStream::Compiler(tts) => { . // Here is the reason for DeferredTokenStream. 12,883,673 ( 0.08%) for token in stream { 5,272,956 ( 0.03%) tts.extra.push(into_compiler_token(token)); . } . } . TokenStream::Fallback(tts) => tts.extend(stream), . } 585,334 ( 0.00%) } . } . . impl Extend for TokenStream { 126,124 ( 0.00%) fn extend>(&mut self, streams: I) { 157,655 ( 0.00%) match self { 94,593 ( 0.00%) TokenStream::Compiler(tts) => { 94,593 ( 0.00%) tts.evaluate_now(); 220,717 ( 0.00%) tts.stream 536,027 ( 0.00%) .extend(streams.into_iter().map(TokenStream::unwrap_nightly)); . } . TokenStream::Fallback(tts) => { . tts.extend(streams.into_iter().map(TokenStream::unwrap_stable)); . } . } 63,062 ( 0.00%) } . } . . impl Debug for TokenStream { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . TokenStream::Compiler(tts) => Debug::fmt(&tts.clone().into_token_stream(), f), . TokenStream::Fallback(tts) => Debug::fmt(tts, f), . } -- line 250 ---------------------------------------- -- line 303 ---------------------------------------- . Compiler(proc_macro::token_stream::IntoIter), . Fallback(fallback::TokenTreeIter), . } . . impl IntoIterator for TokenStream { . type Item = TokenTree; . type IntoIter = TokenTreeIter; . 33,900 ( 0.00%) fn into_iter(self) -> TokenTreeIter { 25,425 ( 0.00%) match self { 67,800 ( 0.00%) TokenStream::Compiler(tts) => { 186,450 ( 0.00%) TokenTreeIter::Compiler(tts.into_token_stream().into_iter()) 8,475 ( 0.00%) } . TokenStream::Fallback(tts) => TokenTreeIter::Fallback(tts.into_iter()), . } 16,950 ( 0.00%) } . } . . impl Iterator for TokenTreeIter { . type Item = TokenTree; . 358,210 ( 0.00%) fn next(&mut self) -> Option { 214,926 ( 0.00%) let token = match self { 1,496,007 ( 0.01%) TokenTreeIter::Compiler(iter) => iter.next()?, . TokenTreeIter::Fallback(iter) => return iter.next(), . }; 315,835 ( 0.00%) Some(match token { 198,075 ( 0.00%) proc_macro::TokenTree::Group(tt) => crate::Group::_new(Group::Compiler(tt)).into(), 51,134 ( 0.00%) proc_macro::TokenTree::Punct(tt) => { 211,010 ( 0.00%) let spacing = match tt.spacing() { 3,237 ( 0.00%) proc_macro::Spacing::Joint => Spacing::Joint, 44,660 ( 0.00%) proc_macro::Spacing::Alone => Spacing::Alone, . }; 332,371 ( 0.00%) let mut o = Punct::new(tt.as_char(), spacing); 383,505 ( 0.00%) o.set_span(crate::Span::_new(Span::Compiler(tt.span()))); 281,237 ( 0.00%) o.into() . } 308,760 ( 0.00%) proc_macro::TokenTree::Ident(s) => crate::Ident::_new(Ident::Compiler(s)).into(), 49,543 ( 0.00%) proc_macro::TokenTree::Literal(l) => crate::Literal::_new(Literal::Compiler(l)).into(), . }) 214,926 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . match self { . TokenTreeIter::Compiler(tts) => tts.size_hint(), . TokenTreeIter::Fallback(tts) => tts.size_hint(), . } . } . } -- line 351 ---------------------------------------- -- line 403 ---------------------------------------- . . #[derive(Copy, Clone)] . pub(crate) enum Span { . Compiler(proc_macro::Span), . Fallback(fallback::Span), . } . . impl Span { 236,845 ( 0.00%) pub fn call_site() -> Self { 947,380 ( 0.01%) if inside_proc_macro() { 1,421,070 ( 0.01%) Span::Compiler(proc_macro::Span::call_site()) . } else { . Span::Fallback(fallback::Span::call_site()) . } 710,535 ( 0.00%) } . . #[cfg(not(no_hygiene))] . pub fn mixed_site() -> Self { . if inside_proc_macro() { . Span::Compiler(proc_macro::Span::mixed_site()) . } else { . Span::Fallback(fallback::Span::mixed_site()) . } -- line 425 ---------------------------------------- -- line 525 ---------------------------------------- . pub fn eq(&self, other: &Span) -> bool { . match (self, other) { . (Span::Compiler(a), Span::Compiler(b)) => a.eq(b), . (Span::Fallback(a), Span::Fallback(b)) => a.eq(b), . _ => false, . } . } . 530,032 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Span { 662,540 ( 0.00%) match self { 265,016 ( 0.00%) Span::Compiler(s) => s, . Span::Fallback(_) => mismatch(), . } 397,524 ( 0.00%) } . } . . impl From for crate::Span { . fn from(proc_span: proc_macro::Span) -> crate::Span { . crate::Span::_new(Span::Compiler(proc_span)) . } . } . -- line 546 ---------------------------------------- -- line 563 ---------------------------------------- . match span { . Span::Compiler(s) => { . debug.field("span", &s); . } . Span::Fallback(s) => fallback::debug_span_field_if_nontrivial(debug, s), . } . } . 13,035 ( 0.00%) #[derive(Clone)] . pub(crate) enum Group { 6,952 ( 0.00%) Compiler(proc_macro::Group), . Fallback(fallback::Group), . } . . impl Group { 320,568 ( 0.00%) pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { 160,284 ( 0.00%) match stream { 213,712 ( 0.00%) TokenStream::Compiler(tts) => { 106,856 ( 0.00%) let delimiter = match delimiter { 53,548 ( 0.00%) Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis, 35,188 ( 0.00%) Delimiter::Bracket => proc_macro::Delimiter::Bracket, 16,008 ( 0.00%) Delimiter::Brace => proc_macro::Delimiter::Brace, 1,056 ( 0.00%) Delimiter::None => proc_macro::Delimiter::None, . }; 1,282,272 ( 0.01%) Group::Compiler(proc_macro::Group::new(delimiter, tts.into_token_stream())) 53,428 ( 0.00%) } . TokenStream::Fallback(stream) => { . Group::Fallback(fallback::Group::new(delimiter, stream)) . } . } 106,856 ( 0.00%) } . 39,045 ( 0.00%) pub fn delimiter(&self) -> Delimiter { 39,045 ( 0.00%) match self { 91,105 ( 0.00%) Group::Compiler(g) => match g.delimiter() { 7,600 ( 0.00%) proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis, 14,710 ( 0.00%) proc_macro::Delimiter::Bracket => Delimiter::Bracket, 1,300 ( 0.00%) proc_macro::Delimiter::Brace => Delimiter::Brace, 2,420 ( 0.00%) proc_macro::Delimiter::None => Delimiter::None, . }, . Group::Fallback(g) => g.delimiter(), . } 39,045 ( 0.00%) } . 31,365 ( 0.00%) pub fn stream(&self) -> TokenStream { 18,819 ( 0.00%) match self { 125,460 ( 0.00%) Group::Compiler(g) => TokenStream::Compiler(DeferredTokenStream::new(g.stream())), . Group::Fallback(g) => TokenStream::Fallback(g.stream()), . } 12,546 ( 0.00%) } . 17,154 ( 0.00%) pub fn span(&self) -> Span { 17,154 ( 0.00%) match self { 57,180 ( 0.00%) Group::Compiler(g) => Span::Compiler(g.span()), . Group::Fallback(g) => Span::Fallback(g.span()), . } 17,154 ( 0.00%) } . 444 ( 0.00%) pub fn span_open(&self) -> Span { 444 ( 0.00%) match self { . #[cfg(not(no_group_open_close))] 1,480 ( 0.00%) Group::Compiler(g) => Span::Compiler(g.span_open()), . #[cfg(no_group_open_close)] . Group::Compiler(g) => Span::Compiler(g.span()), . Group::Fallback(g) => Span::Fallback(g.span_open()), . } 444 ( 0.00%) } . 13,926 ( 0.00%) pub fn span_close(&self) -> Span { 13,926 ( 0.00%) match self { . #[cfg(not(no_group_open_close))] 46,420 ( 0.00%) Group::Compiler(g) => Span::Compiler(g.span_close()), . #[cfg(no_group_open_close)] . Group::Compiler(g) => Span::Compiler(g.span()), . Group::Fallback(g) => Span::Fallback(g.span_close()), . } 13,926 ( 0.00%) } . 82,505 ( 0.00%) pub fn set_span(&mut self, span: Span) { 264,016 ( 0.00%) match (self, span) { 165,010 ( 0.00%) (Group::Compiler(g), Span::Compiler(s)) => g.set_span(s), . (Group::Fallback(g), Span::Fallback(s)) => g.set_span(s), . _ => mismatch(), . } 33,002 ( 0.00%) } . 122,458 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Group { 183,687 ( 0.00%) match self { 244,916 ( 0.00%) Group::Compiler(g) => g, . Group::Fallback(_) => mismatch(), . } 367,374 ( 0.00%) } . } . . impl From for Group { . fn from(g: fallback::Group) -> Self { . Group::Fallback(g) . } . } . -- line 662 ---------------------------------------- -- line 673 ---------------------------------------- . fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { . match self { . Group::Compiler(group) => Debug::fmt(group, formatter), . Group::Fallback(group) => Debug::fmt(group, formatter), . } . } . } . 1,715,910 ( 0.01%) #[derive(Clone)] . pub(crate) enum Ident { 915,152 ( 0.01%) Compiler(proc_macro::Ident), . Fallback(fallback::Ident), . } . . impl Ident { 899,910 ( 0.01%) pub fn new(string: &str, span: Span) -> Self { 449,955 ( 0.00%) match span { 1,259,874 ( 0.01%) Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new(string, s)), . Span::Fallback(s) => Ident::Fallback(fallback::Ident::new(string, s)), . } 179,982 ( 0.00%) } . . pub fn new_raw(string: &str, span: Span) -> Self { . match span { . Span::Compiler(s) => { . let p: proc_macro::TokenStream = string.parse().unwrap(); . let ident = match p.into_iter().next() { . Some(proc_macro::TokenTree::Ident(mut i)) => { . i.set_span(s); -- line 701 ---------------------------------------- -- line 704 ---------------------------------------- . _ => panic!(), . }; . Ident::Compiler(ident) . } . Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_raw(string, s)), . } . } . 81,129 ( 0.00%) pub fn span(&self) -> Span { 81,129 ( 0.00%) match self { 270,430 ( 0.00%) Ident::Compiler(t) => Span::Compiler(t.span()), . Ident::Fallback(t) => Span::Fallback(t.span()), . } 81,129 ( 0.00%) } . 31,420 ( 0.00%) pub fn set_span(&mut self, span: Span) { 100,544 ( 0.00%) match (self, span) { 62,840 ( 0.00%) (Ident::Compiler(t), Span::Compiler(s)) => t.set_span(s), . (Ident::Fallback(t), Span::Fallback(s)) => t.set_span(s), . _ => mismatch(), . } 12,568 ( 0.00%) } . 249,742 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Ident { 374,613 ( 0.00%) match self { 499,484 ( 0.00%) Ident::Compiler(s) => s, . Ident::Fallback(_) => mismatch(), . } 749,226 ( 0.00%) } . } . . impl PartialEq for Ident { . fn eq(&self, other: &Ident) -> bool { . match (self, other) { . (Ident::Compiler(t), Ident::Compiler(o)) => t.to_string() == o.to_string(), . (Ident::Fallback(t), Ident::Fallback(o)) => t == o, . _ => mismatch(), -- line 740 ---------------------------------------- -- line 741 ---------------------------------------- . } . } . } . . impl PartialEq for Ident . where . T: ?Sized + AsRef, . { 390,516 ( 0.00%) fn eq(&self, other: &T) -> bool { 223,152 ( 0.00%) let other = other.as_ref(); 167,364 ( 0.00%) match self { 725,244 ( 0.00%) Ident::Compiler(t) => t.to_string() == other, . Ident::Fallback(t) => t == other, . } 278,940 ( 0.00%) } . } . . impl Display for Ident { 108,220 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 64,932 ( 0.00%) match self { 129,864 ( 0.00%) Ident::Compiler(t) => Display::fmt(t, f), . Ident::Fallback(t) => Display::fmt(t, f), . } 108,220 ( 0.00%) } . } . . impl Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . Ident::Compiler(t) => Debug::fmt(t, f), . Ident::Fallback(t) => Debug::fmt(t, f), . } . } . } . 49,755 ( 0.00%) #[derive(Clone)] . pub(crate) enum Literal { 26,536 ( 0.00%) Compiler(proc_macro::Literal), . Fallback(fallback::Literal), . } . . macro_rules! suffixed_numbers { . ($($name:ident => $kind:ident,)*) => ($( 7,370 ( 0.00%) pub fn $name(n: $kind) -> Literal { 5,896 ( 0.00%) if inside_proc_macro() { 10,318 ( 0.00%) Literal::Compiler(proc_macro::Literal::$name(n)) . } else { . Literal::Fallback(fallback::Literal::$name(n)) . } 2,948 ( 0.00%) } . )*) . } . . macro_rules! unsuffixed_integers { . ($($name:ident => $kind:ident,)*) => ($( . pub fn $name(n: $kind) -> Literal { . if inside_proc_macro() { . Literal::Compiler(proc_macro::Literal::$name(n)) -- line 798 ---------------------------------------- -- line 856 ---------------------------------------- . pub fn f64_unsuffixed(f: f64) -> Literal { . if inside_proc_macro() { . Literal::Compiler(proc_macro::Literal::f64_unsuffixed(f)) . } else { . Literal::Fallback(fallback::Literal::f64_unsuffixed(f)) . } . } . 5,096 ( 0.00%) pub fn string(t: &str) -> Literal { 2,912 ( 0.00%) if inside_proc_macro() { 5,096 ( 0.00%) Literal::Compiler(proc_macro::Literal::string(t)) . } else { . Literal::Fallback(fallback::Literal::string(t)) . } 1,456 ( 0.00%) } . . pub fn character(t: char) -> Literal { . if inside_proc_macro() { . Literal::Compiler(proc_macro::Literal::character(t)) . } else { . Literal::Fallback(fallback::Literal::character(t)) . } . } . 455 ( 0.00%) pub fn byte_string(bytes: &[u8]) -> Literal { 260 ( 0.00%) if inside_proc_macro() { 455 ( 0.00%) Literal::Compiler(proc_macro::Literal::byte_string(bytes)) . } else { . Literal::Fallback(fallback::Literal::byte_string(bytes)) . } 130 ( 0.00%) } . 1,896 ( 0.00%) pub fn span(&self) -> Span { 1,896 ( 0.00%) match self { 6,320 ( 0.00%) Literal::Compiler(lit) => Span::Compiler(lit.span()), . Literal::Fallback(lit) => Span::Fallback(lit.span()), . } 1,896 ( 0.00%) } . 3,690 ( 0.00%) pub fn set_span(&mut self, span: Span) { 11,808 ( 0.00%) match (self, span) { 7,380 ( 0.00%) (Literal::Compiler(lit), Span::Compiler(s)) => lit.set_span(s), . (Literal::Fallback(lit), Span::Fallback(s)) => lit.set_span(s), . _ => mismatch(), . } 1,476 ( 0.00%) } . . pub fn subspan>(&self, range: R) -> Option { . match self { . #[cfg(proc_macro_span)] . Literal::Compiler(lit) => lit.subspan(range).map(Span::Compiler), . #[cfg(not(proc_macro_span))] . Literal::Compiler(_lit) => None, . Literal::Fallback(lit) => lit.subspan(range).map(Span::Fallback), . } . } . 11,362 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Literal { 17,043 ( 0.00%) match self { 22,724 ( 0.00%) Literal::Compiler(s) => s, . Literal::Fallback(_) => mismatch(), . } 34,086 ( 0.00%) } . } . . impl From for Literal { . fn from(s: fallback::Literal) -> Literal { . Literal::Fallback(s) . } . } . -- line 926 ---------------------------------------- -- line 951 ---------------------------------------- . return Ok(literal); . } . } . Err(LexError::call_site()) . } . } . . impl Display for Literal { 3,485 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 2,091 ( 0.00%) match self { 4,182 ( 0.00%) Literal::Compiler(t) => Display::fmt(t, f), . Literal::Fallback(t) => Display::fmt(t, f), . } 3,485 ( 0.00%) } . } . . impl Debug for Literal { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . Literal::Compiler(t) => Debug::fmt(t, f), . Literal::Fallback(t) => Debug::fmt(t, f), . } -- line 972 ---------------------------------------- 7,172,095 ( 0.05%) -------------------------------------------------------------------------------- -- 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. 11,371,943 ( 0.07%) 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), 4,014,215 ( 0.03%) GoDown(handle) => match handle.force() { . Leaf(leaf) => return GoDown(leaf), . Internal(internal) => internal.descend(), . }, . } . } 4,537,459 ( 0.03%) } . . /// 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()); 33,400,711 ( 0.21%) for (offset, k) in unsafe { keys.get_unchecked(start_index..) }.iter().enumerate() { 160,241,164 ( 1.01%) 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 ---------------------------------------- 2,450,076 ( 0.02%) -------------------------------------------------------------------------------- -- 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 130 ( 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 { 390 ( 0.00%) pub(super) fn new(handle_counters: &'static HandleCounters) -> Self { 3,835 ( 0.00%) HandleStore { . $($oty: handle::OwnedStore::new(&handle_counters.$oty),)* . $($ity: handle::InternedStore::new(&handle_counters.$ity),)* . } 520 ( 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 { 33,316 ( 0.00%) fn drop(&mut self) { 239,985 ( 0.00%) $oty(self.0).drop(); 49,974 ( 0.00%) } . } . . impl Encode for $oty { 520 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { 195 ( 0.00%) let handle = self.0; 260 ( 0.00%) mem::forget(self); 65 ( 0.00%) handle.encode(w, s); 130 ( 0.00%) } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 2,232,360 ( 0.01%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$oty.take(handle::Handle::decode(r, &mut ())) 2,976,480 ( 0.02%) } . } . . impl Encode for &$oty { . fn encode(self, w: &mut Writer, s: &mut S) { 461,649 ( 0.00%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> Decode<'_, 's, HandleStore>> . for &'s Marked . { 153,883 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &'s HandleStore>) -> Self { . &s.$oty[handle::Handle::decode(r, &mut ())] 307,766 ( 0.00%) } . } . . impl Encode for &mut $oty { . fn encode(self, w: &mut Writer, s: &mut S) { 1,729,659 ( 0.01%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore>> . for &'s mut Marked . { 576,553 ( 0.00%) fn decode( . r: &mut Reader<'_>, . s: &'s mut HandleStore> . ) -> Self { . &mut s.$oty[handle::Handle::decode(r, &mut ())] 1,153,106 ( 0.01%) } . } . . impl Encode>> . for Marked . { 4,547,105 ( 0.03%) fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 837,766 ( 0.01%) s.$oty.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $oty { 390 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 390 ( 0.00%) $oty(handle::Handle::decode(r, s)) 390 ( 0.00%) } . } . )* . . $( . #[repr(C)] 1,652,119 ( 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 . { 488,558 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$ity.copy(handle::Handle::decode(r, &mut ())) 977,116 ( 0.01%) } . } . . impl Encode>> . for Marked . { . fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 3,875,909 ( 0.02%) 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 { 88,833 ( 0.00%) fn clone(&self) -> Self { . self.clone() 88,833 ( 0.00%) } . } . . impl Clone for TokenStreamIter { . fn clone(&self) -> Self { . self.clone() . } . } . . impl Clone for Group { 37,194 ( 0.00%) fn clone(&self) -> Self { . self.clone() 37,194 ( 0.00%) } . } . . impl Clone for Literal { 9,951 ( 0.00%) fn clone(&self) -> Self { . self.clone() 9,951 ( 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 228 ---------------------------------------- . } . } . . macro_rules! define_client_side { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* . }),* $(,)?) => { . $(impl $name { 2,926,032 ( 0.02%) $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* { 1,516,444 ( 0.01%) Bridge::with(|bridge| { . let mut b = bridge.cached_buffer.take(); . . b.clear(); 7,583,241 ( 0.05%) api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ()); 1,808,575 ( 0.01%) reverse_encode!(b; $($arg),*); . 15,166,482 ( 0.10%) b = bridge.dispatch.call(b); . 10,454,021 ( 0.07%) let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ()); . 30,332,964 ( 0.19%) bridge.cached_buffer = b; . 3,680,739 ( 0.02%) r.unwrap_or_else(|e| panic::resume_unwind(e.into())) . }) 2,438,360 ( 0.02%) })* . })* . } . } . 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`. 1,532,810 ( 0.01%) fn with(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { 1,344,511 ( 0.01%) BRIDGE_STATE.with(|state| { 13,605,008 ( 0.09%) state.replace(BridgeState::InUse, |mut state| { . // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone 1,560 ( 0.00%) f(&mut *state) 260 ( 0.00%) }) 260 ( 0.00%) }) 1,326,076 ( 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, . }) . } . 390 ( 0.00%) fn enter(self, f: impl FnOnce() -> R) -> R { 455 ( 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(); 327 ( 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%) }); . 2,405 ( 0.00%) BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f)) 130 ( 0.00%) } . 325 ( 0.00%) fn with(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R { 17,903,823 ( 0.11%) 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"); . } 845 ( 0.00%) BridgeState::Connected(bridge) => f(bridge), 260 ( 0.00%) }) 260 ( 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? 455 ( 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. 390 ( 0.00%) let mut b = bridge.cached_buffer.take(); . 2,340 ( 0.00%) panic::catch_unwind(panic::AssertUnwindSafe(|| { 975 ( 0.00%) bridge.enter(|| { 1,235 ( 0.00%) let reader = &mut &b[..]; 455 ( 0.00%) let input = A::decode(reader, &mut ()); . . // Put the `cached_buffer` back in the `Bridge`, for requests. 1,300 ( 0.00%) Bridge::with(|bridge| bridge.cached_buffer = b.take()); . 1,040 ( 0.00%) let output = f(input); . . // Take the `cached_buffer` back out, for the output value. 1,235 ( 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). 195 ( 0.00%) b.clear(); 650 ( 0.00%) Ok::<_, ()>(output).encode(&mut b, &mut ()); 260 ( 0.00%) }) 130 ( 0.00%) })) . .map_err(PanicMessage::from) 65 ( 0.00%) .unwrap_or_else(|e| { . b.clear(); . Err::<(), _>(e).encode(&mut b, &mut ()); . }); . b 130 ( 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 { 455 ( 0.00%) extern "C" fn run( . bridge: Bridge<'_>, . f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, . ) -> Buffer { 1,170 ( 0.00%) run_client(bridge, |(input, input2)| { 1,300 ( 0.00%) f(crate::TokenStream(input), crate::TokenStream(input2)).0 195 ( 0.00%) }) 130 ( 0.00%) } . Client { get_handle_counters: HandleCounters::get, run, f } . } . } . . #[repr(C)] . #[derive(Copy, Clone)] . pub enum ProcMacro { . CustomDerive { -- line 435 ---------------------------------------- 6,784,426 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs -------------------------------------------------------------------------------- Ir -- line 140 ---------------------------------------- . /// let mut map: BTreeMap<&str, String> = BTreeMap::new(); . /// let s = "hoho".to_string(); . /// . /// map.entry("poneyland").or_insert_with(|| s); . /// . /// assert_eq!(map["poneyland"], "hoho".to_string()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 692,442 ( 0.00%) pub fn or_insert_with V>(self, default: F) -> &'a mut V { 301,362 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 2,010,752 ( 0.01%) Vacant(entry) => entry.insert(default()), . } 831,527 ( 0.01%) } . . /// Ensures a value is in the entry by inserting, if empty, the result of the default function. . /// This method allows for generating key-derived values for insertion by providing the default . /// function a reference to the key that was moved during the `.entry(key)` method call. . /// . /// The reference to the moved key is provided so that cloning or copying the key is . /// unnecessary, unlike with `.or_insert_with(|| ... )`. . /// -- line 161 ---------------------------------------- -- line 245 ---------------------------------------- . /// ``` . /// use std::collections::BTreeMap; . /// . /// let mut map: BTreeMap<&str, Option> = BTreeMap::new(); . /// map.entry("poneyland").or_default(); . /// . /// assert_eq!(map["poneyland"], None); . /// ``` 4,149 ( 0.00%) pub fn or_default(self) -> &'a mut V { 2,766 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 151 ( 0.00%) Vacant(entry) => entry.insert(Default::default()), . } 6,915 ( 0.00%) } . } . . impl<'a, K: Ord, V> VacantEntry<'a, K, V> { . /// Gets a reference to the key that would be used when inserting a value . /// through the VacantEntry. . /// . /// # Examples . /// -- line 266 ---------------------------------------- -- line 306 ---------------------------------------- . /// let mut map: BTreeMap<&str, u32> = BTreeMap::new(); . /// . /// if let Entry::Vacant(o) = map.entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 5,519,347 ( 0.03%) pub fn insert(self, value: V) -> &'a mut V { 14,134,975 ( 0.09%) let out_ptr = match self.handle.insert_recursing(self.key, value) { 1,137,647 ( 0.01%) (Fit(_), val_ptr) => { . // SAFETY: We have consumed self.handle and the handle returned. 1,020,317 ( 0.01%) let map = unsafe { self.dormant_map.awaken() }; 4,390,461 ( 0.03%) map.length += 1; . val_ptr . } 70,296 ( 0.00%) (Split(ins), val_ptr) => { . drop(ins.left); . // SAFETY: We have consumed self.handle and the reference returned. 7,681 ( 0.00%) let map = unsafe { self.dormant_map.awaken() }; . let root = map.root.as_mut().unwrap(); 57,429 ( 0.00%) root.push_internal_level().push(ins.kv.0, ins.kv.1, ins.right); 40,255 ( 0.00%) map.length += 1; . val_ptr . } . }; . // Now that we have finished growing the tree using borrowed references, . // dereference the pointer to a part of it, that we picked up along the way. . unsafe { &mut *out_ptr } 5,672,902 ( 0.04%) } . } . . impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> { . /// Gets a reference to the key in the entry. . /// . /// # Examples . /// . /// ``` -- line 343 ---------------------------------------- -- line 368 ---------------------------------------- . /// // We delete the entry from the map. . /// o.remove_entry(); . /// } . /// . /// // If now try to get the value, it will panic: . /// // println!("{}", map["poneyland"]); . /// ``` . #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")] 4,703,325 ( 0.03%) pub fn remove_entry(self) -> (K, V) { 940,849 ( 0.01%) self.remove_kv() 7,132,414 ( 0.05%) } . . /// Gets a reference to the value in the entry. . /// . /// # Examples . /// . /// ``` . /// use std::collections::BTreeMap; . /// use std::collections::btree_map::Entry; -- line 386 ---------------------------------------- -- line 448 ---------------------------------------- . /// if let Entry::Occupied(o) = map.entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_mut(self) -> &'a mut V { 3,576 ( 0.00%) self.handle.into_val_mut() . } . . /// Sets the value of the entry with the `OccupiedEntry`'s key, . /// and returns the entry's old value. . /// . /// # Examples . /// . /// ``` -- line 464 ---------------------------------------- -- line 497 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn remove(self) -> V { . self.remove_kv().1 . } . . // Body of `remove_entry`, probably separate because the name reflects the returned pair. . pub(super) fn remove_kv(self) -> (K, V) { 1,039,902 ( 0.01%) let mut emptied_internal_root = false; 13,795,823 ( 0.09%) let (old_kv, _) = self.handle.remove_kv_tracking(|| emptied_internal_root = true); . // SAFETY: we consumed the intermediate root borrow, `self.handle`. . let map = unsafe { self.dormant_map.awaken() }; 4,158,640 ( 0.03%) map.length -= 1; 2,079,320 ( 0.01%) if emptied_internal_root { . let root = map.root.as_mut().unwrap(); . root.pop_internal_level(); . } . old_kv . } . } 1,969,262 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 113,948 ( 0.00%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 114,796 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 4,402 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 3,294 ( 0.00%) pub token: Token, . /// The spacing for the current token 1,945 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 4,941 ( 0.00%) pub prev_token: Token, 2,243 ( 0.00%) pub capture_cfg: bool, 4,784 ( 0.00%) restrictions: Restrictions, 3,890 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 3,890 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 3,890 ( 0.00%) unmatched_angle_bracket_count: u32, 5,835 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 1,945 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 1,945 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 8,590 ( 0.00%) #[derive(Clone)] . struct CaptureState { 7,780 ( 0.00%) capturing: Capturing, 1,945 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 43,419 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 985,004 ( 0.01%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 227,718 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 72,510 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 450,492 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 182,997 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 365,994 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 48,745 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 94,938 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 6,539,100 ( 0.04%) fn next(&mut self) -> (Token, Spacing) { . loop { 3,248,107 ( 0.02%) let (tree, spacing) = if !self.frame.open_delim { 75,302 ( 0.00%) self.frame.open_delim = true; 376,510 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 6,311,858 ( 0.04%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 317,588 ( 0.00%) } else if !self.frame.close_delim { 74,315 ( 0.00%) self.frame.close_delim = true; 371,575 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 147,662 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 959,803 ( 0.01%) self.frame = frame; . continue; . } else { 191,664 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 1,240,178 ( 0.01%) match tree { . TokenTree::Token(token) => { 4,359,400 ( 0.03%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 4,359,400 ( 0.03%) } . 71,400 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 21,696 ( 0.00%) let (data, attr_style, sp) = match self.next() { 414 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 35,010 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; 32,864 ( 0.00%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 10 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 552 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 690 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 1,656 ( 0.00%) [ 966 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 552 ( 0.00%) TokenTree::token(token::Eq, sp), 1,104 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 138 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 138 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 1,656 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 414 ( 0.00%) self.next() 64,260 ( 0.00%) } . } . 431,975 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 345,607 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 51 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 33,542 ( 0.00%) Some(match token.kind { 67,084 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 67,084 ( 0.00%) _ if token.is_used_keyword() => "keyword", 67,084 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 117,397 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 33,542 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 117,397 ( 0.00%) _ => format!("`{}`", token_str), . } 83,855 ( 0.00%) } . . impl<'a> Parser<'a> { 136,486 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 9,749 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 19,498 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 302,219 ( 0.00%) let mut parser = Parser { . sess, 9,749 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 9,749 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 58,494 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 19,498 ( 0.00%) parser.bump(); . . parser 87,741 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 3,030,492 ( 0.02%) let (mut next, spacing) = if self.desugar_doc_comments { 28,560 ( 0.00%) self.token_cursor.next_desugared() . } else { 1,493,826 ( 0.01%) self.token_cursor.next() . }; 2,020,328 ( 0.01%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 505,082 ( 0.00%) self.token_cursor.break_last_token = false; 2,020,328 ( 0.01%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 39,008 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 1,724,163 ( 0.01%) if matches!( 1,010,164 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 2,005,936 ( 0.01%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 821,853 ( 0.01%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 91,317 ( 0.00%) if self.expected_tokens.is_empty() { 98,532 ( 0.00%) if self.token == *t { 82,110 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 898,740 ( 0.01%) self.expect_one_of(slice::from_ref(t), &[]) . } 1,369,755 ( 0.01%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 1,040,664 ( 0.01%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 173,444 ( 0.00%) if edible.contains(&self.token.kind) { 225,054 ( 0.00%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 1,300,830 ( 0.01%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 484,740 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 362,139 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 844,557 ( 0.01%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 120,651 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 723,906 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 482,604 ( 0.00%) self.bump(); . Ok(ident) 1,206,510 ( 0.01%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 8,646,400 ( 0.05%) fn check(&mut self, tok: &TokenKind) -> bool { 3,752,077 ( 0.02%) let is_present = self.token == *tok; 2,531,168 ( 0.02%) if !is_present { 5,061,095 ( 0.03%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 8,646,400 ( 0.05%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 12 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 1,942,522 ( 0.01%) let is_present = self.check(tok); 1,281,364 ( 0.01%) if is_present { 287,284 ( 0.00%) self.bump() . } . is_present 15 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 293,540 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 80,581 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 2,245,095 ( 0.01%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 518,375 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 424,402 ( 0.00%) if self.check_keyword(kw) { 58,556 ( 0.00%) self.bump(); . true . } else { . false . } 518,375 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 91,772 ( 0.00%) if self.token.is_keyword(kw) { 22,688 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 8,875 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 7,100 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 525,544 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 262,772 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 591,237 ( 0.00%) } . 326,574 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 143,686 ( 0.00%) if ok { . true . } else { 61,280 ( 0.00%) self.expected_tokens.push(typ); . false . } 326,574 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 69,015 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 124,576 ( 0.00%) fn check_path(&mut self) -> bool { 268,347 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 155,720 ( 0.00%) } . . fn check_type(&mut self) -> bool { 9,064 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 9,016 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 69,048 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 38,360 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 69,048 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 52,620 ( 0.00%) self.check_or_expected( 26,310 ( 0.00%) self.token.is_like_plus(), 26,310 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 577,176 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 336,686 ( 0.00%) if self.token.kind == expected { 33,538 ( 0.00%) self.bump(); . return true; . } 156,645 ( 0.00%) match self.token.kind.break_two_token_op() { 525 ( 0.00%) Some((first, second)) if first == expected => { 300 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 375 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 675 ( 0.00%) self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 75 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 1,050 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 93,762 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 557,898 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 756 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 36,552 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { 102 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 45,024 ( 0.00%) fn eat_lt(&mut self) -> bool { 128,658 ( 0.00%) let ate = self.break_and_eat(token::Lt); 82,482 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 38,444 ( 0.00%) self.unmatched_angle_bracket_count += 1; 43,112 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 45,024 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. . /// Signals an error if `>` was not eaten. . fn expect_gt(&mut self) -> PResult<'a, ()> { 6,732 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 3,366 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 2,244 ( 0.00%) self.unmatched_angle_bracket_count -= 1; . debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); . } . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 176,046 ( 0.00%) TokenExpectType::Expect => self.check(k), 351 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 144,269 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 110,614 ( 0.00%) if let Some(ref t) = sep.sep { 155,563 ( 0.00%) if first { . first = false; . } else { 49,736 ( 0.00%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 53,802 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 35,458 ( 0.00%) let t = f(self)?; 102,486 ( 0.00%) v.push(t); . } . 107,732 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 112,609 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 126,370 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 66,637 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 41,027 ( 0.00%) if !recovered { . self.eat(ket); . } 167,786 ( 0.00%) Ok((val, trailing)) 101,096 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 59,775 ( 0.00%) self.expect(bra)?; 101,096 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 25,972 ( 0.00%) &token::OpenDelim(delim), 39,307 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 6,520,267 ( 0.04%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 3,009,354 ( 0.02%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 2,006,236 ( 0.01%) self.prev_token = mem::replace(&mut self.token, next_token); 501,559 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 501,559 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 4,011,872 ( 0.03%) pub fn bump(&mut self) { 2,005,936 ( 0.01%) let next_token = self.next_tok(self.token.span); 3,008,904 ( 0.02%) self.bump_with(next_token); 4,011,872 ( 0.03%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. . pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 38,454 ( 0.00%) if dist == 0 { 15,097 ( 0.00%) return looker(&self.token); . } . 153,656 ( 0.00%) let frame = &self.token_cursor.frame; 177,459 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 507,762 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 656,723 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 820,187 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 271,932 ( 0.00%) Some(tree) => match tree { 121,645 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 102,921 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 217,025 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 12,695 ( 0.00%) let mut token = Token::dummy(); 1,786 ( 0.00%) while i < dist { 113,663 ( 0.00%) token = cursor.next().0; 59,266 ( 0.00%) if matches!( 32,166 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 940 ( 0.00%) i += 1; . } 144 ( 0.00%) return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 156,690 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 52,858 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 156,690 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 13,142 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 4,360 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 52,568 ( 0.00%) } . . /// Parses constness: `const` or nothing. 120,216 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 33,610 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 3,685 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 210,378 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 12,317 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 792 ( 0.00%) fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } 792 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 454 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 681 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 1,712 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 55,617 ( 0.00%) self.parse_mac_args_common(false) . } . 174,249 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 154,888 ( 0.00%) Ok( 147,313 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 37,881 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 37,881 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 26,980 ( 0.00%) match self.parse_token_tree() { 33,725 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 13,490 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 25,232 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 9,194 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 9,194 ( 0.00%) let expr = self.parse_expr_force_collect()?; 9,194 ( 0.00%) let span = expr.span; . 45,970 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 82,746 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 135,527 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 104,802 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 48,972 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 54,544 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 20,470 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 197,844 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 126,242 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 13,628 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 13,628 ( 0.00%) let span = frame.span; 6,814 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 13,628 ( 0.00%) self.bump(); 34,070 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 8 ( 0.00%) self.bump(); 20 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 47,726 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 43,428 ( 0.00%) let old = self.restrictions; 56,140 ( 0.00%) self.restrictions = res; . let res = f(self); 59,118 ( 0.00%) self.restrictions = old; . res . } . 187,728 ( 0.00%) fn is_crate_vis(&self) -> bool { 117,330 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 211,194 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 154,330 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 30,889 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 15,431 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 61,724 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 13,161 ( 0.00%) return Ok(Visibility { 39,483 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 2,270 ( 0.00%) let lo = self.prev_token.span; . 11,350 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. . if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. -- line 1303 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 6,810 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 138,897 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 7,498 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. 14,660 ( 0.00%) fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { 8,796 ( 0.00%) Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, . _ => { . self.struct_span_err(lit.span, "non-string ABI literal") . .span_suggestion( . lit.span, . "specify the ABI with a string literal", . "\"C\"".to_string(), -- line 1392 ---------------------------------------- -- line 1393 ---------------------------------------- . Applicability::MaybeIncorrect, . ) . .emit(); . None . } . }, . Err(None) => None, . } 11,728 ( 0.00%) } . 99,690 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 10,045 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 99,690 ( 0.00%) } . . /// `::{` or `::*` 875,360 ( 0.01%) fn is_import_coupler(&mut self) -> bool { 437,680 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 311,688 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 822,753 ( 0.01%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 158,656 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 79,328 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 79,328 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 158,656 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 3,107,331 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 176 ---------------------------------------- . } . fn sess(self) -> Option<&'tcx Session> { . None . } . fn tcx(self) -> Option> { . None . } . 16,902 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 5,634 ( 0.00%) let tcx = self.tcx(); 824,630 ( 0.01%) DecodeContext { 94,442 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), 5,634 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 32,214 ( 0.00%) sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 85,413 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 16,902 ( 0.00%) } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self . } . } -- line 206 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 120,381 ( 0.00%) fn decode>(self, metadata: M) -> T { 70,741 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 249,420 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 80,330 ( 0.00%) T::decode(&mut dcx) 153,568 ( 0.00%) } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { 329 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 94 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 571,550 ( 0.00%) (0..self.meta).map(move |_| T::decode(&mut dcx)) . } . } . . impl<'a, 'tcx> DecodeContext<'a, 'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext"); . self.tcx.unwrap() -- line 285 ---------------------------------------- -- line 292 ---------------------------------------- . . #[inline] . pub fn cdata(&self) -> CrateMetadataRef<'a> { . debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); . self.cdata.unwrap() . } . . fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum { 227,275 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 64,569 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 61,567 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 14,974 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 29,948 ( 0.00%) assert!(distance <= start); . start - distance . } 9,987 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 36,606 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 64,569 ( 0.00%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 326 ---------------------------------------- . . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx.expect("missing TyCtxt in DecodeContext") . } . . #[inline] . fn peek_byte(&self) -> u8 { 202,395 ( 0.00%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 158,277 ( 0.00%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 22,611 ( 0.00%) let tcx = self.tcx(); . 22,611 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 67,844 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 5,650 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 203,499 ( 0.00%) } . . fn with_position(&mut self, pos: usize, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . let new_opaque = opaque::Decoder::new(self.opaque.data, pos); . let old_opaque = mem::replace(&mut self.opaque, new_opaque); . let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); . let r = f(self); 31,275 ( 0.00%) self.opaque = old_opaque; 6,255 ( 0.00%) self.lazy_state = old_state; . r . } . . fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId { . if let Some(alloc_decoding_session) = self.alloc_decoding_session { . alloc_decoding_session.decode_alloc_id(self) . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 105,286 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 354 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 193,751 ( 0.00%) DefIndex::from_u32(d.read_u32()) 708 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 1,305,188 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 326,297 ( 0.00%) let cdata = decoder.cdata(); 326,297 ( 0.00%) let sess = decoder.sess.unwrap(); 652,594 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 7,000 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 1,631,485 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 27,867 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 3,981 ( 0.00%) let local_cdata = decoder.cdata(); 3,981 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 1,773 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 8,865 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 8,865 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 17,730 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 31,848 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 2,568,376 ( 0.02%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 321,047 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 642,094 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 962,892 ( 0.01%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 656,791 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` 248 ( 0.00%) if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); . panic!( . "Decoding of crate {:?} tried to access proc-macro dep {:?}", . decoder.cdata().root.name, . cnum . ); -- line 513 ---------------------------------------- -- line 518 ---------------------------------------- . "SpecializedDecoder::specialized_decode: loading source files from cnum {:?}", . cnum . ); . . // Decoding 'foreign' spans should be rare enough that it's . // not worth it to maintain a per-CrateNum cache for `last_source_file_index`. . // We just set it to 0, to ensure that we don't try to access something out . // of bounds for our initial 'guess' 496 ( 0.00%) decoder.last_source_file_index = 0; . 248 ( 0.00%) let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 962,892 ( 0.01%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 1,282,520 ( 0.01%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 29,714 ( 0.00%) .unwrap_or_else(|index| index - 1); . . // Don't try to cache the index for foreign spans, . // as this would require a map from CrateNums to indices 14,863 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 14,621 ( 0.00%) decoder.last_source_file_index = index; . } 29,726 ( 0.00%) &imported_source_files[index] . } . }; . . // Make sure our binary search above is correct. . debug_assert!( . lo >= source_file.original_start_pos && lo <= source_file.original_end_pos, . "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . lo, -- line 558 ---------------------------------------- -- line 565 ---------------------------------------- . hi >= source_file.original_start_pos && hi <= source_file.original_end_pos, . "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . hi, . source_file.original_start_pos, . source_file.original_end_pos . ); . . let lo = 1,283,856 ( 0.01%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 2,889,423 ( 0.02%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 27,277 ( 0.00%) decoder.read_lazy_with_meta(()) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy<[T]> . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 18,566 ( 0.00%) if len == 0 { Lazy::empty() } else { decoder.read_lazy_with_meta(len) } . } . } . . impl<'a, 'tcx, I: Idx, T: Decodable>> Decodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 11,830 ( 0.00%) decoder.read_lazy_with_meta(len) . } . } . . implement_ty_decoder!(DecodeContext<'a, 'tcx>); . . impl<'tcx> MetadataBlob { . crate fn new(metadata_ref: MetadataRef) -> MetadataBlob { . MetadataBlob(Lrc::new(metadata_ref)) -- line 626 ---------------------------------------- -- line 630 ---------------------------------------- . self.blob().starts_with(METADATA_HEADER) . } . . crate fn get_rustc_version(&self) -> String { . Lazy::::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap()) . .decode(self) . } . 210 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 70 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 350 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 140 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 280 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 210 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 350 ( 0.00%) } . . crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> { . let root = self.get_root(); . writeln!(out, "Crate info:")?; . writeln!(out, "name {}{}", root.name, root.extra_filename)?; . writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?; . writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?; . writeln!(out, "=External Dependencies=")?; -- line 654 ---------------------------------------- -- line 666 ---------------------------------------- . } . write!(out, "\n")?; . Ok(()) . } . } . . impl CrateRoot<'_> { . crate fn is_proc_macro_crate(&self) -> bool { 43 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 4 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 22 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 47 ( 0.00%) self.stable_crate_id . } . . crate fn triple(&self) -> &TargetTriple { . &self.triple . } . . crate fn decode_crate_deps<'a>( . &self, . metadata: &'a MetadataBlob, . ) -> impl ExactSizeIterator + Captures<'a> { 42 ( 0.00%) self.crate_deps.decode(metadata) . } . } . . impl<'a, 'tcx> CrateMetadataRef<'a> { 7 ( 0.00%) fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro { . // DefIndex's in root.proc_macro_data have a one-to-one correspondence . // with items in 'raw_proc_macros'. 2 ( 0.00%) let pos = self . .root . .proc_macro_data . .as_ref() . .unwrap() . .macros . .decode(self) . .position(|i| i == id) . .unwrap(); 4 ( 0.00%) &self.raw_proc_macros.unwrap()[pos] 9 ( 0.00%) } . 37,554 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 28,522 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 17,696 ( 0.00%) let span = match self.root.tables.ident_span.get(self, item_index) { . Some(lazy_span) => lazy_span.decode((self, sess)), . None => { . // FIXME: this weird case of a name with no span is specific to `extern crate` . // items, which are supposed to be treated like `use` items and only be encoded . // to metadata as `Export`s, return `None` because that's what all the callers . // expect in this case. 99 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 48,280 ( 0.00%) } . 314 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 8,189 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 628 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 27,874 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 111,496 ( 0.00%) fn kind(self, item_id: DefIndex) -> EntryKind { . self.maybe_kind(item_id).unwrap_or_else(|| { . bug!( . "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 83,622 ( 0.00%) } . 68,803 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 48,946 ( 0.00%) self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| { . bug!( . "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 39,316 ( 0.00%) } . 2,826 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 7,291 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 1,570 ( 0.00%) } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { 18 ( 0.00%) let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { . ProcMacro::CustomDerive { trait_name, attributes, client } => { . let helper_attrs = . attributes.iter().cloned().map(Symbol::intern).collect::>(); . ( . trait_name, . SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })), . helper_attrs, . ) . } 4 ( 0.00%) ProcMacro::Attr { name, client } => { 4 ( 0.00%) (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new()) . } . ProcMacro::Bang { name, client } => { . (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new()) . } . }; . 5 ( 0.00%) let attrs: Vec<_> = self.get_item_attrs(id, sess).collect(); 12 ( 0.00%) SyntaxExtension::new( . sess, 5 ( 0.00%) kind, . self.get_span(id, sess), 4 ( 0.00%) helper_attrs, 3 ( 0.00%) self.root.edition, 1 ( 0.00%) Symbol::intern(name), . &attrs, . ) . } . 923 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 284 ( 0.00%) match self.kind(item_id) { 71 ( 0.00%) EntryKind::Trait(data) => { 426 ( 0.00%) let data = data.decode((self, sess)); 1,136 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 142 ( 0.00%) data.unsafety, 142 ( 0.00%) data.paren_sugar, 142 ( 0.00%) data.has_auto_impl, 142 ( 0.00%) data.is_marker, 71 ( 0.00%) data.skip_array_during_method_dispatch, 71 ( 0.00%) data.specialization_kind, 284 ( 0.00%) self.def_path_hash(item_id), 71 ( 0.00%) data.must_implement_one_of, . ) . } . EntryKind::TraitAlias => ty::TraitDef::new( . self.local_def_id(item_id), . hir::Unsafety::Normal, . false, . false, . false, . false, . ty::trait_def::TraitSpecializationKind::None, . self.def_path_hash(item_id), . None, . ), . _ => bug!("def-index does not refer to trait or trait alias"), . } 639 ( 0.00%) } . 540 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 240 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 300 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 202 ( 0.00%) let adt_kind = match kind { . EntryKind::Variant(_) => ty::AdtKind::Enum, . EntryKind::Struct(..) => ty::AdtKind::Struct, . EntryKind::Union(..) => ty::AdtKind::Union, . _ => bug!(), . }; . . let variant_did = . if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None }; 120 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 1,320 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 240 ( 0.00%) data.discr, 360 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 76 ( 0.00%) did: self.local_def_id(index), 152 ( 0.00%) name: self.item_ident(index, sess).name, 152 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 60 ( 0.00%) data.is_non_exhaustive, . ) 540 ( 0.00%) } . 750 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 200 ( 0.00%) let kind = self.kind(item_id); 100 ( 0.00%) let did = self.local_def_id(item_id); . 232 ( 0.00%) let (adt_kind, repr) = match kind { . EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr), . EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr), . EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr), . _ => bug!("get_adt_def called on a non-ADT {:?}", did), . }; . . let variants = if let ty::AdtKind::Enum = adt_kind { 50 ( 0.00%) self.root . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) 340 ( 0.00%) .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 320 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 750 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 350 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 8,885 ( 0.00%) self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_inferred_outlives( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 8,885 ( 0.00%) self.root . .tables . .inferred_outlives . .get(self, item_id) 12 ( 0.00%) .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_super_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 365 ( 0.00%) self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_explicit_item_bounds( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 115 ( 0.00%) self.root . .tables . .explicit_item_bounds . .get(self, item_id) 88 ( 0.00%) .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics { 37,824 ( 0.00%) self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess)) . } . . fn get_type(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 14,910 ( 0.00%) self.root . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 955 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { 15 ( 0.00%) self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 1,120 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 240 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 9,427 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 160 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 65,112 ( 0.00%) match self.kind(id) { 54,260 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 31,236 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 287 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 149 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { 4 ( 0.00%) self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 7,540 ( 0.00%) self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode(self)) . } . . fn get_coerce_unsized_info(self, id: DefIndex) -> Option { . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { 125,881 ( 0.00%) self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 2,290 ( 0.00%) self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess)) . } . . fn get_const_param_default( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> rustc_middle::ty::Const<'tcx> { . self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx)) -- line 1026 ---------------------------------------- -- line 1028 ---------------------------------------- . . /// Iterates over all the stability attributes in the given crate. . fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option)] { . tcx.arena.alloc_from_iter(self.root.lib_features.decode(self)) . } . . /// Iterates over the language items in the given crate. . fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { 66 ( 0.00%) tcx.arena.alloc_from_iter( 44 ( 0.00%) self.root . .lang_items . .decode(self) 564 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); 44 ( 0.00%) let name_to_id = self . .root . .diagnostic_items . .decode(self) . .map(|(name, def_index)| { 130 ( 0.00%) let id = self.local_def_id(def_index); 130 ( 0.00%) id_to_name.insert(id, name); . (name, id) . }) . .collect(); 198 ( 0.00%) DiagnosticItems { id_to_name, name_to_id } . } . . /// Iterates over all named children of the given module, . /// including both proper items and reexports. . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 356 ( 0.00%) if let Some(data) = &self.root.proc_macro_data { . // If we are loading as a proc macro, we want to return . // the view of this crate as a proc macro crate. . if id == CRATE_DEF_INDEX { . for def_index in data.macros.decode(self) { . let raw_macro = self.raw_proc_macro(def_index); . let res = Res::Def( . DefKind::Macro(macro_kind(raw_macro)), . self.local_def_id(def_index), -- line 1078 ---------------------------------------- -- line 1085 ---------------------------------------- . span: ident.span, . }); . } . } . return; . } . . // Iterate over all children. 712 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 1,424 ( 0.00%) for child_index in children.decode((self, sess)) { 10,374 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 2,133 ( 0.00%) let kind = self.def_kind(child_index); 1,422 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 2,716 ( 0.00%) match kind { . DefKind::Struct => { 37 ( 0.00%) if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); . } . } . DefKind::Variant => { . // Braced variants, unlike structs, generate unusable names in . // value namespace, they are reserved for possible future use. . // It's ok to use the variant's id as a ctor id since an . // error will be reported on any use of such resolution anyway. 24 ( 0.00%) let (ctor_def_id, ctor_kind) = self . .get_ctor_def_id_and_kind(child_index) . .unwrap_or((def_id, CtorKind::Fictive)); . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id); . let mut vis = self.get_visibility(ctor_def_id.index); 8 ( 0.00%) if ctor_def_id == def_id && vis.is_public() { . // For non-exhaustive variants lower the constructor visibility to . // within the crate. We only need this for fictive constructors, . // for other constructors correct visibilities . // were already encoded in metadata. . let mut attrs = self.get_item_attrs(def_id.index, sess); . if attrs.any(|item| item.has_name(sym::non_exhaustive)) { . let crate_def_id = self.local_def_id(CRATE_DEF_INDEX); . vis = ty::Visibility::Restricted(crate_def_id); -- line 1141 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 911 ( 0.00%) match self.kind(id) { 56 ( 0.00%) EntryKind::Mod(exports) => { 1,950 ( 0.00%) for exp in exports.decode((self, sess)) { . callback(exp); . } . } . EntryKind::Enum(..) | EntryKind::Trait(..) => {} . _ => bug!("`for_each_module_child` is called on a non-module: {:?}", self.def_kind(id)), . } . } . . fn is_ctfe_mir_available(self, id: DefIndex) -> bool { 216 ( 0.00%) self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { 1,044 ( 0.00%) self.root.tables.mir.get(self, id).is_some() . } . . fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId { 2,842 ( 0.00%) match self.kind(id) { . EntryKind::Mod(_) | EntryKind::Enum(_) | EntryKind::Trait(_) => { . self.get_expn_that_defined(id, sess) . } . _ => panic!("Expected module, found {:?}", self.local_def_id(id)), . } . } . . fn get_optimized_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 1,300 ( 0.00%) self.root . .tables . .mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn get_mir_for_ctfe(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 270 ( 0.00%) self.root . .tables . .mir_for_ctfe . .get(self, id) . .unwrap_or_else(|| { . bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1200 ---------------------------------------- -- line 1216 ---------------------------------------- . .tables . .unused_generic_params . .get(self, id) . .map(|params| params.decode(self)) . .unwrap_or_default() . } . . fn get_promoted_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec> { 30 ( 0.00%) self.root . .tables . .promoted_mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn mir_const_qualif(self, id: DefIndex) -> mir::ConstQualifs { 15 ( 0.00%) match self.kind(id) { . EntryKind::AnonConst(qualif, _) . | EntryKind::Const(qualif, _) . | EntryKind::AssocConst( . AssocContainer::ImplDefault . | AssocContainer::ImplFinal . | AssocContainer::TraitWithDefault, 2 ( 0.00%) qualif, . _, . ) => qualif, . _ => bug!("mir_const_qualif: unexpected kind"), . } . } . . fn get_fn_has_self_parameter(self, id: DefIndex) -> bool { 755 ( 0.00%) match self.kind(id) { 604 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).has_self, . _ => false, . } . } . . fn get_associated_item_def_ids(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [DefId] { 1,750 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 750 ( 0.00%) tcx.arena.alloc_from_iter( 250 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 14,664 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 8,554 ( 0.00%) let def_key = self.def_key(id); . let parent = self.local_def_id(def_key.parent.unwrap()); . let ident = self.item_ident(id, sess); . 8,854 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { 96 ( 0.00%) EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 1,096 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 7,672 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 204 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 21,996 ( 0.00%) ty::AssocItem { . name: ident.name, . kind, . vis: self.get_visibility(id), . defaultness: container.defaultness(), . def_id: self.local_def_id(id), . trait_item_def_id: self.get_trait_item_def_id(id), . container: container.with_def_id(parent), . fn_has_self_parameter: has_self, . } 10,998 ( 0.00%) } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { 140 ( 0.00%) self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self) . } . . fn get_ctor_def_id_and_kind(self, node_id: DefIndex) -> Option<(DefId, CtorKind)> { 1,701 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 732 ( 0.00%) let vdata = data.decode(self); 485 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 968 ( 0.00%) } . 69,720 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 25,884 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 52,290 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 930 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 3,140 ( 0.00%) .map(move |index| respan(self.get_span(index, sess), self.item_ident(index, sess).name)) . } . . fn get_struct_field_visibilities(self, id: DefIndex) -> impl Iterator + 'a { 220 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 80 ( 0.00%) .map(move |field_index| self.get_visibility(field_index)) . } . . fn get_inherent_implementations_for_type( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> &'tcx [DefId] { 48 ( 0.00%) tcx.arena.alloc_from_iter( 60 ( 0.00%) self.root . .tables . .inherent_impls . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 1,166 ( 0.00%) .map(|index| self.local_def_id(index)), . ) . } . . fn get_traits(self) -> impl Iterator + 'a { . self.root.traits.decode(self).map(move |index| self.local_def_id(index)) . } . . fn get_trait_impls(self) -> impl Iterator)> + 'a { -- line 1376 ---------------------------------------- -- line 1380 ---------------------------------------- . index: *trait_index, . }; . impls.decode(self).map(move |(impl_index, simplified_self_ty)| { . (trait_def_id, self.local_def_id(impl_index), simplified_self_ty) . }) . }) . } . 14,850 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 1,650 ( 0.00%) if self.trait_impls.is_empty() { . return &[]; . } . . // Do a reverse lookup beforehand to avoid touching the crate_num . // hash map in the loop below. 2,166 ( 0.00%) let key = match self.reverse_translate_def_id(trait_def_id) { . Some(def_id) => (def_id.krate.as_u32(), def_id.index), . None => return &[], . }; . . if let Some(impls) = self.trait_impls.get(&key) { 1,108 ( 0.00%) tcx.arena.alloc_from_iter( 554 ( 0.00%) impls . .decode(self) 11,471 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 13,200 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 1,744 ( 0.00%) let def_key = self.def_key(id); 2,180 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 3,879 ( 0.00%) def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 44 ( 0.00%) self.root.native_libraries.decode((self, sess)) . } . . fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span { . self.root . .tables . .proc_macro_quoted_spans . .get(self, index) . .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index)) -- line 1437 ---------------------------------------- -- line 1450 ---------------------------------------- . self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { . let cnum = CrateNum::new(i + 1); . link.map(|link| (self.cnum_map[cnum], link)) . }), . ) . } . . fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] { 110 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; . tcx.arena.alloc_from_iter(param_names.decode((self, tcx))) . } . . fn exported_symbols( . self, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] { 132 ( 0.00%) tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx))) . } . . fn get_rendered_const(self, id: DefIndex) -> String { . match self.kind(id) { . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 78 ( 0.00%) match self.kind(id) { 13 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { 180 ( 0.00%) let constness = match self.kind(id) { 36 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, 12 ( 0.00%) EntryKind::Fn(data) => data.decode(self).constness, . EntryKind::ForeignFn(data) => data.decode(self).constness, . EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const, . _ => hir::Constness::NotConst, . }; . constness == hir::Constness::Const . } . . fn asyncness(self, id: DefIndex) -> hir::IsAsync { -- line 1506 ---------------------------------------- -- line 1508 ---------------------------------------- . EntryKind::Fn(data) => data.decode(self).asyncness, . EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness, . EntryKind::ForeignFn(data) => data.decode(self).asyncness, . _ => bug!("asyncness: expected function kind"), . } . } . . fn is_foreign_item(self, id: DefIndex) -> bool { 3,564 ( 0.00%) match self.kind(id) { . EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => { . true . } . _ => false, . } . } . . fn static_mutability(self, id: DefIndex) -> Option { 594 ( 0.00%) match self.kind(id) { . EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not), . EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut), . _ => None, . } . } . . fn generator_kind(self, id: DefIndex) -> Option { 40 ( 0.00%) match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 2,175 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 354,991 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 101,700 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 17,475 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 405,704 ( 0.00%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); 208 ( 0.00%) DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 126,426 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 3,755 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 442,491 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 505,704 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 641,928 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 641,928 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 2,785 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 641,680 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 33 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 11,697 ( 0.00%) mut name, 3,342 ( 0.00%) src_hash, 557 ( 0.00%) start_pos, 1,114 ( 0.00%) end_pos, 2,785 ( 0.00%) mut lines, 2,785 ( 0.00%) mut multibyte_chars, 3,342 ( 0.00%) mut non_narrow_chars, 2,785 ( 0.00%) mut normalized_pos, 3,342 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 1,114 ( 0.00%) if let Some(virtual_dir) = . &sess.opts.debugging_opts.simulate_remapped_rust_src_base . { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(ref mut old_name) = name { . if let rustc_span::RealFileName::LocalPath(local) = old_name { . if let Ok(rest) = local.strip_prefix(real_dir) { . *old_name = rustc_span::RealFileName::Remapped { . local_path: None, -- line 1753 ---------------------------------------- -- line 1767 ---------------------------------------- . let source_length = (end_pos - start_pos).to_usize(); . . // Translate line-start positions and multibyte character . // position into frame of reference local to file. . // `SourceMap::new_imported_source_file()` will then translate those . // coordinates to their new global frame of reference when the . // offset of the SourceFile is known. . for pos in &mut lines { 741,842 ( 0.00%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,618 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 936 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 10,026 ( 0.00%) let local_version = sess.source_map().new_imported_source_file( 7,241 ( 0.00%) name, 3,899 ( 0.00%) src_hash, . name_hash, . source_length, 1,114 ( 0.00%) self.cnum, 2,785 ( 0.00%) lines, 3,342 ( 0.00%) multibyte_chars, 2,785 ( 0.00%) non_narrow_chars, 2,228 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 1,671 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 264 ( 0.00%) crate fn new( . sess: &Session, . blob: MetadataBlob, . root: CrateRoot<'static>, . raw_proc_macros: Option<&'static [ProcMacro]>, . cnum: CrateNum, . cnum_map: CrateNumMap, . dep_kind: CrateDepKind, . source: CrateSource, . private_dep: bool, . host_hash: Option, . ) -> CrateMetadata { 66 ( 0.00%) let trait_impls = root . .impls . .decode((&blob, sess)) . .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)) . .collect(); . let alloc_decoding_state = 66 ( 0.00%) AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect()); . let dependencies = Lock::new(cnum_map.iter().cloned().collect()); . . // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation . // that does not copy any data. It just does some data verification. 22 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 506 ( 0.00%) CrateMetadata { 22 ( 0.00%) blob, 66 ( 0.00%) root, 88 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 88 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 154 ( 0.00%) alloc_decoding_state, . cnum, 88 ( 0.00%) cnum_map, 110 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 264 ( 0.00%) source, . private_dep, . host_hash, . extern_crate: Lock::new(None), . hygiene_context: Default::default(), . def_key_cache: Default::default(), . def_path_hash_cache: Default::default(), . } 198 ( 0.00%) } . . crate fn dependencies(&self) -> LockGuard<'_, Vec> { . self.dependencies.borrow() . } . . crate fn add_dependency(&self, cnum: CrateNum) { . self.dependencies.borrow_mut().push(cnum); . } . . crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool { . let mut extern_crate = self.extern_crate.borrow_mut(); . let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank); . if update { 115 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { 25,832 ( 0.00%) &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { . *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 6,548 ( 0.00%) self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind)) . } . . crate fn panic_strategy(&self) -> PanicStrategy { . self.root.panic_strategy . } . . crate fn needs_panic_runtime(&self) -> bool { . self.root.needs_panic_runtime -- line 1905 ---------------------------------------- -- line 1909 ---------------------------------------- . self.root.panic_runtime . } . . crate fn is_profiler_runtime(&self) -> bool { . self.root.profiler_runtime . } . . crate fn needs_allocator(&self) -> bool { 5 ( 0.00%) self.root.needs_allocator . } . . crate fn has_global_allocator(&self) -> bool { . self.root.has_global_allocator . } . . crate fn has_default_lib_allocator(&self) -> bool { . self.root.has_default_lib_allocator . } . . crate fn is_proc_macro_crate(&self) -> bool { . self.root.is_proc_macro_crate() . } . . crate fn name(&self) -> Symbol { 125,439 ( 0.00%) self.root.name . } . . crate fn stable_crate_id(&self) -> StableCrateId { . self.root.stable_crate_id . } . . crate fn hash(&self) -> Svh { . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 20,666 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { 5,751 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 4,282,434 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 110 ---------------------------------------- . /// Control byte value for an empty bucket. . 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] 8,280 ( 0.00%) fn is_full(ctrl: u8) -> bool { 5,931,673 ( 0.04%) ctrl & 0x80 == 0 11,040 ( 0.00%) } . . /// 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] 2,376 ( 0.00%) fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 512,490 ( 0.00%) ctrl & 0x01 != 0 3,168 ( 0.00%) } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] 7,371 ( 0.00%) fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize 4,914 ( 0.00%) } . . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] 7,179 ( 0.00%) 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. 14,358 ( 0.00%) let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 122,158,423 ( 0.77%) let top7 = hash >> (hash_len * 8 - 7); 2,393 ( 0.00%) (top7 & 0x7f) as u8 // truncation 4,786 ( 0.00%) } . . /// 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 . /// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on. . /// -- line 161 ---------------------------------------- -- line 163 ---------------------------------------- . /// . struct ProbeSeq { . pos: usize, . stride: usize, . } . . impl ProbeSeq { . #[inline] 450 ( 0.00%) 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" . ); . 711,328 ( 0.00%) self.stride += Group::WIDTH; 711,418 ( 0.00%) self.pos += self.stride; 619,430 ( 0.00%) self.pos &= bucket_mask; 180 ( 0.00%) } . } . . /// 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)] 192 ( 0.00%) 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. 624,790 ( 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. 1,371,388 ( 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. 228,865 ( 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). 35 ( 0.00%) Some(adjusted_cap.next_power_of_two()) 263 ( 0.00%) } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] 384 ( 0.00%) fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 1,541,794 ( 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. 115 ( 0.00%) bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 289,969 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } 384 ( 0.00%) } . . /// 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, . ctrl_align: usize, . } . . impl TableLayout { . #[inline] 119 ( 0.00%) fn new() -> Self { 476 ( 0.00%) let layout = Layout::new::(); 238 ( 0.00%) Self { 357 ( 0.00%) size: layout.size(), 714 ( 0.00%) ctrl_align: usize::max(layout.align(), Group::WIDTH), . } 476 ( 0.00%) } . . #[inline] 1,651 ( 0.00%) fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . 254 ( 0.00%) let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 1,341,108 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 1,750,352 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . 1,143 ( 0.00%) Some(( 508 ( 0.00%) unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) 381 ( 0.00%) } . } . . /// Returns a Layout which describes the allocation required for a hash table, . /// and the offset of the control bytes in the allocation. . /// (the offset is also one past last element of buckets) . /// . /// Returns `None` if an overflow occurs. . #[cfg_attr(feature = "inline-more", inline)] -- line 269 ---------------------------------------- -- line 292 ---------------------------------------- . #[inline] . fn clone(&self) -> Self { . Self { ptr: self.ptr } . } . } . . impl Bucket { . #[inline] 9,280 ( 0.00%) unsafe fn from_base_index(base: NonNull, index: usize) -> Self { 7,424 ( 0.00%) let ptr = if mem::size_of::() == 0 { . // won't overflow because index must be less than length . (index + 1) as *mut T . } else { 7,424 ( 0.00%) base.as_ptr().sub(index) . }; 1,856 ( 0.00%) Self { 7,424 ( 0.00%) ptr: NonNull::new_unchecked(ptr), . } 5,568 ( 0.00%) } . #[inline] . unsafe fn to_base_index(&self, base: NonNull) -> usize { . if mem::size_of::() == 0 { . self.ptr.as_ptr() as usize - 1 . } else { . offset_from(base.as_ptr(), self.ptr.as_ptr()) . } . } . #[inline] 5,178 ( 0.00%) pub fn as_ptr(&self) -> *mut T { 6,904 ( 0.00%) if mem::size_of::() == 0 { . // Just return an arbitrary ZST pointer which is properly aligned . mem::align_of::() as *mut T . } else { 10,356 ( 0.00%) unsafe { self.ptr.as_ptr().sub(1) } . } 5,178 ( 0.00%) } . #[inline] 275 ( 0.00%) unsafe fn next_n(&self, offset: usize) -> Self { 220 ( 0.00%) let ptr = if mem::size_of::() == 0 { . (self.ptr.as_ptr() as usize + offset) as *mut T . } else { 275 ( 0.00%) self.ptr.as_ptr().sub(offset) . }; 55 ( 0.00%) Self { 220 ( 0.00%) ptr: NonNull::new_unchecked(ptr), . } 165 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] 110 ( 0.00%) pub unsafe fn drop(&self) { 110 ( 0.00%) self.as_ptr().drop_in_place(); 110 ( 0.00%) } . #[inline] . pub unsafe fn read(&self) -> T { 1,968 ( 0.00%) self.as_ptr().read() . } . #[inline] 2,184 ( 0.00%) pub unsafe fn write(&self, val: T) { 8,228 ( 0.00%) self.as_ptr().write(val); 1,456 ( 0.00%) } . #[inline] 1,886 ( 0.00%) pub unsafe fn as_ref<'a>(&self) -> &'a T { 1,886 ( 0.00%) &*self.as_ptr() 1,886 ( 0.00%) } . #[inline] . pub unsafe fn as_mut<'a>(&self) -> &'a mut T { . &mut *self.as_ptr() . } . #[cfg(feature = "raw")] . #[inline] . pub unsafe fn copy_from_nonoverlapping(&self, other: &Self) { . self.as_ptr().copy_from_nonoverlapping(other.as_ptr(), 1); -- line 362 ---------------------------------------- -- line 392 ---------------------------------------- . . impl RawTable { . /// Creates a new empty hash table without allocating any memory. . /// . /// 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] 390 ( 0.00%) pub const fn new() -> Self { 1,040 ( 0.00%) Self { 260 ( 0.00%) table: RawTableInner::new_in(Global), . marker: PhantomData, . } 260 ( 0.00%) } . . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . #[cfg(feature = "raw")] . pub fn try_with_capacity(capacity: usize) -> Result { . Self::try_with_capacity_in(capacity, Global) . } . -- line 413 ---------------------------------------- -- line 421 ---------------------------------------- . impl RawTable { . /// 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] 3 ( 0.00%) pub fn new_in(alloc: A) -> Self { 5,843 ( 0.00%) Self { 2 ( 0.00%) table: RawTableInner::new_in(alloc), . marker: PhantomData, . } 2 ( 0.00%) } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 3,815 ( 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 { 44,152 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 493 ---------------------------------------- . /// Returns a reference to the underlying allocator. . #[inline] . pub fn allocator(&self) -> &A { . &self.table.alloc . } . . /// Deallocates the table without dropping any entries. . #[cfg_attr(feature = "inline-more", inline)] 165 ( 0.00%) unsafe fn free_buckets(&mut self) { 220 ( 0.00%) self.table.free_buckets(TableLayout::new::()); 110 ( 0.00%) } . . /// Returns pointer to one past last element of data table. . #[inline] 1,928 ( 0.00%) pub unsafe fn data_end(&self) -> NonNull { 4,820 ( 0.00%) NonNull::new_unchecked(self.table.ctrl.as_ptr().cast()) 1,928 ( 0.00%) } . . /// Returns pointer to start of data table. . #[inline] . #[cfg(feature = "nightly")] . pub unsafe fn data_start(&self) -> *mut T { . self.data_end().as_ptr().wrapping_sub(self.buckets()) . } . -- line 517 ---------------------------------------- -- line 518 ---------------------------------------- . /// Returns the index of a bucket from a `Bucket`. . #[inline] . pub unsafe fn bucket_index(&self, bucket: &Bucket) -> usize { . bucket.to_base_index(self.data_end()) . } . . /// Returns a pointer to an element in the table. . #[inline] 3,116 ( 0.00%) pub unsafe fn bucket(&self, index: usize) -> Bucket { . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); 3,116 ( 0.00%) Bucket::from_base_index(self.data_end(), index) 1,558 ( 0.00%) } . . /// 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")] 67,420 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 67,420 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 134,840 ( 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. 35,330 ( 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 { 99,510 ( 0.00%) self.erase_no_drop(&item); 1,210 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 2,373,836 ( 0.02%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 7,628 ( 0.00%) match self.find(hash, eq) { 26,743 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 599,097 ( 0.00%) None => None, . } 3,484,790 ( 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(); . } . } . 172 ( 0.00%) unsafe fn drop_elements(&mut self) { 82,454 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { 1,650 ( 0.00%) for item in self.iter() { 110 ( 0.00%) item.drop(); . } . } 118 ( 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 641 ---------------------------------------- . } . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] 448 ( 0.00%) pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 1,390,792 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 1,044,443 ( 0.01%) if self 128 ( 0.00%) .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } 320 ( 0.00%) } . . /// Tries to ensure that at least `additional` items can be inserted into . /// the table without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn try_reserve( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, -- line 667 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 2,498,198 ( 0.02%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { 768 ( 0.00%) self.table.reserve_rehash_inner( . additional, 20,708 ( 0.00%) &|table, index| hasher(table.bucket::(index).as_ref()), . fallibility, 320 ( 0.00%) TableLayout::new::(), 384 ( 0.00%) if mem::needs_drop::() { 320 ( 0.00%) Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 1,823,144 ( 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)] 8,834,194 ( 0.06%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { 5,824 ( 0.00%) 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. 38,177 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 5,572,822 ( 0.04%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { 320 ( 0.00%) self.reserve(1, hasher); 320 ( 0.00%) index = self.table.find_insert_slot(hash); . } . 3,640 ( 0.00%) self.table.record_item_insert_at(index, old_ctrl, hash); . 4,368 ( 0.00%) let bucket = self.bucket(index); 7,502 ( 0.00%) bucket.write(value); 1,456 ( 0.00%) bucket . } 6,497,254 ( 0.04%) } . . /// 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)] 803,368 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 166 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 602,526 ( 0.00%) } . . /// 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"))] 6,456 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 1,450,854 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 29,480 ( 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. 2,935,300 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 2,356,310 ( 0.01%) self.table.items += 1; . bucket 12,803 ( 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] 147,844 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 43,641 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 174,686 ( 0.00%) eq(self.bucket(index).as_ref()) 10,947 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. 2,319 ( 0.00%) match result { 4,651 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), 1,546 ( 0.00%) None => None, . } 164,276 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] 180 ( 0.00%) pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 102,613 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), 90 ( 0.00%) None => None, . } 135 ( 0.00%) } . . /// Gets a mutable reference to an element in the table. . #[inline] 5,005 ( 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. 85,733 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), 1,456 ( 0.00%) None => None, . } 4,576 ( 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 913 ---------------------------------------- . /// more, but is guaranteed to be able to hold at least this many. . #[inline] . pub fn capacity(&self) -> usize { . self.table.items + self.table.growth_left . } . . /// Returns the number of elements in the table. . #[inline] 356 ( 0.00%) pub fn len(&self) -> usize { 178 ( 0.00%) self.table.items 356 ( 0.00%) } . . /// Returns `true` if the table contains no elements. . #[inline] 356 ( 0.00%) pub fn is_empty(&self) -> bool { 3,820,652 ( 0.02%) self.len() == 0 712 ( 0.00%) } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// 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] 1,295 ( 0.00%) pub unsafe fn iter(&self) -> RawIter { 1,295 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); 1,665 ( 0.00%) RawIter { 1,295 ( 0.00%) iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 526,548 ( 0.00%) items: self.table.items, . } 370 ( 0.00%) } . . /// 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. . /// . /// It is up to the caller to ensure that the `RawTable` outlives the -- line 956 ---------------------------------------- -- 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(); 58,932 ( 0.00%) let allocation = self.into_allocation(); 44,199 ( 0.00%) RawIntoIter { 73,665 ( 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)> { 27,907 ( 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(( 4,839 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1041 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] 393 ( 0.00%) const fn new_in(alloc: A) -> Self { 3,269,053 ( 0.02%) Self { . // Be careful to cast the entire slice to a raw pointer. 917 ( 0.00%) ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } 262 ( 0.00%) } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 2,500,778 ( 0.02%) 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. 1,024 ( 0.00%) let (layout, ctrl_offset) = match table_layout.calculate_layout_for(buckets) { 768 ( 0.00%) Some(lco) => lco, . None => return Err(fallibility.capacity_overflow()), . }; . . // We need an additional check to ensure that the allocation doesn't . // 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. 256 ( 0.00%) if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 547,298 ( 0.00%) let ptr: NonNull = match do_alloc(&alloc, layout) { 448 ( 0.00%) Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . 576 ( 0.00%) let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 1,371,142 ( 0.01%) Ok(Self { . ctrl, 541,799 ( 0.00%) bucket_mask: buckets - 1, . items: 0, 576 ( 0.00%) growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 1,819,058 ( 0.01%) } . . #[inline] 141,304 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 37,628 ( 0.00%) if capacity == 0 { 24,997 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = 1,344 ( 0.00%) capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 1,135,030 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; 768 ( 0.00%) result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 79,627 ( 0.00%) Ok(result) . } . } 140,728 ( 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] 508,201 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { 2,676 ( 0.00%) let index = self.find_insert_slot(hash); 508,201 ( 0.00%) let old_ctrl = *self.ctrl(index); 892 ( 0.00%) self.set_ctrl_h2(index, hash); 1,784 ( 0.00%) (index, old_ctrl) 1,011,050 ( 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] 6,736 ( 0.00%) fn find_insert_slot(&self, hash: u64) -> usize { 6,736 ( 0.00%) let mut probe_seq = self.probe_seq(hash); 1,729 ( 0.00%) loop { . unsafe { 13,832 ( 0.00%) let group = Group::load(self.ctrl(probe_seq.pos)); 3,887,397 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 11,367,574 ( 0.07%) 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). 5,194,800 ( 0.03%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); 15 ( 0.00%) return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . 3,366 ( 0.00%) return result; . } . } 135 ( 0.00%) probe_seq.move_next(self.bucket_mask); . } 5,052 ( 0.00%) } . . /// 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] 9,276 ( 0.00%) fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { 2,319 ( 0.00%) let h2_hash = h2(hash); 3,092 ( 0.00%) let mut probe_seq = self.probe_seq(hash); . 336,106 ( 0.00%) loop { 6,544 ( 0.00%) let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 14,761,114 ( 0.09%) for bit in group.match_byte(h2_hash) { 30,555,618 ( 0.19%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 20,365,036 ( 0.13%) if likely(eq(index)) { . return Some(index); . } . } . 3,874,584 ( 0.02%) if likely(group.match_empty().any_bit_set()) { 773 ( 0.00%) return None; . } . 180 ( 0.00%) probe_seq.move_next(self.bucket_mask); . } 3,092 ( 0.00%) } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_rehash_in_place(&mut self) { . // Bulk convert all full control bytes to DELETED, and all DELETED . // control bytes to EMPTY. This effectively frees up all buckets . // containing a DELETED entry. . for i in (0..self.buckets()).step_by(Group::WIDTH) { -- line 1204 ---------------------------------------- -- line 1214 ---------------------------------------- . .copy_to(self.ctrl(Group::WIDTH), self.buckets()); . } else { . self.ctrl(0) . .copy_to(self.ctrl(self.buckets()), Group::WIDTH); . } . } . . #[inline] 3,568 ( 0.00%) unsafe fn bucket(&self, index: usize) -> Bucket { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); 3,568 ( 0.00%) Bucket::from_base_index(self.data_end(), index) 1,784 ( 0.00%) } . . #[inline] 10,704 ( 0.00%) unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); 8,920 ( 0.00%) let base: *mut u8 = self.data_end().as_ptr(); 13,256,992 ( 0.08%) base.sub((index + 1) * size_of) 3,568 ( 0.00%) } . . #[inline] 5,352 ( 0.00%) unsafe fn data_end(&self) -> NonNull { 13,380 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().cast()) 5,352 ( 0.00%) } . . /// 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] 17,199 ( 0.00%) fn probe_seq(&self, hash: u64) -> ProbeSeq { 4,914 ( 0.00%) ProbeSeq { 80,673,364 ( 0.51%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } 9,828 ( 0.00%) } . . /// 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] . unsafe fn prepare_insert_no_grow(&mut self, hash: u64) -> Result { . let index = self.find_insert_slot(hash); . let old_ctrl = *self.ctrl(index); -- line 1260 ---------------------------------------- -- line 1262 ---------------------------------------- . Err(()) . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] 6,552 ( 0.00%) unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 6,964,040 ( 0.04%) self.growth_left -= special_is_empty(old_ctrl) as usize; 1,456 ( 0.00%) self.set_ctrl_h2(index, hash); 5,567,752 ( 0.04%) self.items += 1; 1,456 ( 0.00%) } . . #[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) . } . . /// Sets a control byte to the hash, and possibly also the replicated control byte at . /// the end of the array. . #[inline] 14,580 ( 0.00%) unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) { 6,480 ( 0.00%) self.set_ctrl(index, h2(hash)); 3,240 ( 0.00%) } . . #[inline] . unsafe fn replace_ctrl_h2(&self, index: usize, hash: u64) -> u8 { . let prev_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . prev_ctrl . } . . /// Sets a control byte, and possibly also the replicated control byte at . /// the end of the array. . #[inline] 16,200 ( 0.00%) unsafe fn set_ctrl(&self, index: usize, ctrl: u8) { . // Replicate the first Group::WIDTH control bytes at the end of . // the array without using a branch: . // - If index >= Group::WIDTH then index == index2. . // - Otherwise index2 == self.bucket_mask + 1 + index. . // . // The very last replicated control byte is never actually read because . // we mask the initial index for unaligned loads, but we write it . // anyways because it makes the set_ctrl implementation simpler. -- line 1309 ---------------------------------------- -- 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] | . // --------------------------------------------- 10,680,948 ( 0.07%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 3,561,260 ( 0.02%) *self.ctrl(index) = ctrl; 3,560,514 ( 0.02%) *self.ctrl(index2) = ctrl; 3,240 ( 0.00%) } . . /// Returns a pointer to a control byte. . #[inline] 40,928 ( 0.00%) unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); 30,696 ( 0.00%) self.ctrl.as_ptr().add(index) 20,464 ( 0.00%) } . . #[inline] 624 ( 0.00%) fn buckets(&self) -> usize { 1,619,789 ( 0.01%) self.bucket_mask + 1 624 ( 0.00%) } . . #[inline] 128 ( 0.00%) fn num_ctrl_bytes(&self) -> usize { 1,254,890 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH 128 ( 0.00%) } . . #[inline] 388 ( 0.00%) fn is_empty_singleton(&self) -> bool { 6,011,110 ( 0.04%) self.bucket_mask == 0 776 ( 0.00%) } . . #[allow(clippy::mut_mut)] . #[inline] 1,088 ( 0.00%) unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { 64 ( 0.00%) debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 22,498 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( 64 ( 0.00%) self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 659,092 ( 0.00%) new_table.growth_left -= self.items; 128 ( 0.00%) 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. 1,792 ( 0.00%) Ok(guard(new_table, move |self_| { 306,471 ( 0.00%) if !self_.is_empty_singleton() { 24 ( 0.00%) self_.free_buckets(table_layout); . } 128 ( 0.00%) })) 256 ( 0.00%) } . . /// Reserves or rehashes to make room for `additional` more elements. . /// . /// This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations when inlined. . #[allow(clippy::inline_always)] . #[inline(always)] . unsafe fn reserve_rehash_inner( -- line 1387 ---------------------------------------- -- 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. 613,058 ( 0.00%) let new_items = match self.items.checked_add(additional) { 256 ( 0.00%) Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 612,606 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 1,281,273 ( 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( 306,783 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } 128 ( 0.00%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . /// . /// This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations when inlined. . #[allow(clippy::inline_always)] . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 54,619 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. 19,772 ( 0.00%) for i in 0..self.buckets() { 2,152,984 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. 8,028 ( 0.00%) let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. . // - we know there is enough space in the table. . // - all elements are unique. 10,704 ( 0.00%) let (index, _) = new_table.prepare_insert_slot(hash); . 2,676 ( 0.00%) ptr::copy_nonoverlapping( 3,568 ( 0.00%) self.bucket_ptr(i, layout.size), 8,028 ( 0.00%) new_table.bucket_ptr(index, layout.size), . layout.size, . ); . } . . // 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). 512 ( 0.00%) mem::swap(self, &mut new_table); . 306,207 ( 0.00%) Ok(()) 384 ( 0.00%) } . . /// 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 . /// code generated, but it is eliminated by LLVM optimizations when inlined. -- line 1471 ---------------------------------------- -- line 1547 ---------------------------------------- . } . . guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; . . mem::forget(guard); . } . . #[inline] 441 ( 0.00%) unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. 1,260 ( 0.00%) let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { 756 ( 0.00%) Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; 189 ( 0.00%) self.alloc.deallocate( 205,797 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); 126 ( 0.00%) } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 36,251 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 57,798 ( 0.00%) self.items = 0; 36,307 ( 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))); 400,326 ( 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. 1,601,304 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 1,998,750 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 1,601,304 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 15,576 ( 0.00%) fn clone(&self) -> Self { 2,718 ( 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) . } . } 17,523 ( 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; 1,526 ( 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)] 3,391,549 ( 0.02%) fn drop(&mut self) { 2,597,145 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { 55 ( 0.00%) self.drop_elements(); 55 ( 0.00%) self.free_buckets(); . } . } 3,614,126 ( 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)] 58,932 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 73,665 ( 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 1848 ---------------------------------------- . end: *const u8, . } . . impl RawIterRange { . /// Returns a `RawIterRange` covering a subset of a table. . /// . /// The control byte address must be aligned to the group size. . #[cfg_attr(feature = "inline-more", inline)] 2,220 ( 0.00%) unsafe fn new(ctrl: *const u8, data: Bucket, len: usize) -> Self { . debug_assert_ne!(len, 0); . debug_assert_eq!(ctrl as usize % Group::WIDTH, 0); 185 ( 0.00%) let end = ctrl.add(len); . . // Load the first group and advance ctrl to point to the next group 1,110 ( 0.00%) let current_group = Group::load_aligned(ctrl).match_full(); 185 ( 0.00%) let next_ctrl = ctrl.add(Group::WIDTH); . 740 ( 0.00%) Self { . current_group, . data, . next_ctrl, . end, . } 370 ( 0.00%) } . . /// Splits a `RawIterRange` into two halves. . /// . /// Returns `None` if the remaining range is smaller than or equal to the . /// group width. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(feature = "rayon")] . pub(crate) fn split(mut self) -> (Self, Option>) { -- line 1879 ---------------------------------------- -- line 1931 ---------------------------------------- . } . } . } . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 960 ( 0.00%) fn next(&mut self) -> Option> { . unsafe { . loop { 2,237,041 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 176,255 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 319,859 ( 0.00%) return Some(self.data.next_n(index)); . } . 1,231,311 ( 0.01%) if self.next_ctrl >= self.end { 185 ( 0.00%) 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). 18,637 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 24,202 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 24,344 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } 720 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( . 0, . Some(unsafe { offset_from(self.end, self.next_ctrl) + Group::WIDTH }), . ) -- line 1969 ---------------------------------------- -- line 2102 ---------------------------------------- . } . } else { . // We must have already iterated past the removed item. . } . } . } . . unsafe fn drop_elements(&mut self) { 11,328 ( 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)] 248,657 ( 0.00%) fn next(&mut self) -> Option> { 2,674,716 ( 0.02%) if let Some(b) = self.iter.next() { 3,466,635 ( 0.02%) self.items -= 1; 55 ( 0.00%) 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); 185 ( 0.00%) None . } 496,594 ( 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)] 23,498 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 130,755 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 646 ( 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)] 6,226 ( 0.00%) fn next(&mut self) -> Option { 921 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 15,050 ( 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)] 6,488 ( 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. 811 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 6,488 ( 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 ---------------------------------------- 51,793,362 ( 0.33%) -------------------------------------------------------------------------------- -- 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); 17,246 ( 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. 1,354,815 ( 0.01%) 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> { 3,115,793 ( 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); 1,018,089 ( 0.01%) unsafe { (*leaf_ptr).parent } . .as_ref() . .map(|parent| Handle { 1,444,648 ( 0.01%) node: NodeRef::from_internal(*parent, self.height + 1), 443,792 ( 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 { 8,714,977 ( 0.06%) 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(), 130,782 ( 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 { 1 ( 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. 1,231,413 ( 0.01%) 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); 272,985 ( 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(); 7,463 ( 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`. 51,738 ( 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 } 68,984 ( 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) { 22,231 ( 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. 7,463 ( 0.00%) self.node = unsafe { internal_node.edges[0].assume_init_read() }; 14,926 ( 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> { 7,026,537 ( 0.04%) 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(); 22 ( 0.00%) let idx = usize::from(*len); 11 ( 0.00%) assert!(idx < CAPACITY); 24 ( 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) { 34,492 ( 0.00%) assert!(edge.height == self.height - 1); . . let len = self.len_mut(); 17,246 ( 0.00%) let idx = usize::from(*len); 8,623 ( 0.00%) assert!(idx < CAPACITY); 17,246 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); 8,623 ( 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, . > { 8,636,068 ( 0.05%) 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> { 332,556 ( 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()); . 1,652,773 ( 0.01%) Handle { node, idx, _marker: PhantomData } . } . . pub fn left_kv(self) -> Result, marker::KV>, Self> { 136,354 ( 0.00%) if self.idx > 0 { 130,548 ( 0.00%) Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) }) . } else { . Err(self) . } . } . . pub fn right_kv(self) -> Result, marker::KV>, Self> { 539,879 ( 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. 143,521 ( 0.00%) fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) { . debug_assert!(edge_idx <= CAPACITY); . // Rust issue #74834 tries to explain these symmetric rules. 573,806 ( 0.00%) match edge_idx { 287,042 ( 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)), 429,672 ( 0.00%) _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))), . } 143,521 ( 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. 9,215,638 ( 0.06%) 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 { 1,164,025 ( 0.01%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 1,310,402 ( 0.01%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); 1,164,022 ( 0.01%) *self.node.len_mut() = new_len as u16; . . self.node.val_area_mut(self.idx).assume_init_mut() . } 9,312,418 ( 0.06%) } . } . . 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) { 3,492,066 ( 0.02%) if self.node.len() < CAPACITY { 5,428,635 ( 0.03%) let val_ptr = self.insert_fit(key, val); 2,063,846 ( 0.01%) let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . (InsertResult::Fit(kv), val_ptr) . } else { 1,056,792 ( 0.01%) let (middle_kv_idx, insertion) = splitpoint(self.idx); 261,307 ( 0.00%) let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 658,300 ( 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) . }, . }; 312,015 ( 0.00%) let val_ptr = insertion_edge.insert_fit(key, val); 266,596 ( 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. 1,075,084 ( 0.01%) 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 { 134,898 ( 0.00%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 12,916 ( 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); 134,898 ( 0.00%) *self.node.len_mut() = new_len as u16; . . self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1); . } 1,079,184 ( 0.01%) } . . /// 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> { 404,694 ( 0.00%) assert!(edge.height == self.node.height - 1); . 269,796 ( 0.00%) if self.node.len() < CAPACITY { 401,642 ( 0.00%) self.insert_fit(key, val, edge); . let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . InsertResult::Fit(kv) . } else { 81,274 ( 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(); 12,682 ( 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) . }, . }; 89,237 ( 0.00%) insertion_edge.insert_fit(key, val, edge); 20,579 ( 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. 11,519,671 ( 0.07%) pub fn insert_recursing( . self, . key: K, . value: V, . ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) { 6,738,459 ( 0.04%) let (mut split, val_ptr) = match self.insert(key, value) { . (InsertResult::Fit(handle), ptr) => { 5,159,615 ( 0.03%) return (InsertResult::Fit(handle.forget_node_type()), ptr); . } . (InsertResult::Split(split), val_ptr) => (split.forget_node_type(), val_ptr), . }; . . loop { 1,036,181 ( 0.01%) split = match split.left.ascend() { 539,721 ( 0.00%) Ok(parent) => match parent.insert(split.kv.0, split.kv.1, split.right) { . InsertResult::Fit(handle) => { 626,336 ( 0.00%) return (InsertResult::Fit(handle.forget_node_type()), val_ptr); . } 604 ( 0.00%) InsertResult::Split(split) => split.forget_node_type(), . }, . Err(root) => { 85,793 ( 0.00%) return (InsertResult::Split(SplitResult { left: root, ..split }), val_ptr); . } . }; . } 10,476,198 ( 0.07%) } . } . . 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() }; 416,941 ( 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() }; 661,346 ( 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 { 2,833 ( 0.00%) let leaf = self.node.as_leaf_mut(); 2,833 ( 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(); 4,468 ( 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] 6 ( 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 { 1 ( 0.00%) leaf.keys.get_unchecked_mut(self.idx).assume_init_drop(); 33,731 ( 0.00%) leaf.vals.get_unchecked_mut(self.idx).assume_init_drop(); . } 7 ( 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(); 727,479 ( 0.00%) let new_len = old_len - self.idx - 1; 144,454 ( 0.00%) new_node.len = new_len as u16; . unsafe { 152,562 ( 0.00%) let k = self.node.key_area_mut(self.idx).assume_init_read(); 126,290 ( 0.00%) let v = self.node.val_area_mut(self.idx).assume_init_read(); . . move_to_slice( 430,563 ( 0.00%) self.node.key_area_mut(self.idx + 1..old_len), 143,521 ( 0.00%) &mut new_node.keys[..new_len], . ); . move_to_slice( . self.node.val_area_mut(self.idx + 1..old_len), 153,620 ( 0.00%) &mut new_node.vals[..new_len], . ); . 269,816 ( 0.00%) *self.node.len_mut() = self.idx as u16; 37,920 ( 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); 1,132,182 ( 0.01%) 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); 744,120 ( 0.00%) let v = slice_remove(self.node.val_area_mut(..old_len), self.idx); 3,863,100 ( 0.02%) *self.node.len_mut() = (old_len - 1) as u16; 3,709,258 ( 0.02%) ((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 1150 ---------------------------------------- . /// left of this handle. . /// - The key and value pointed to by this handle are extracted. . /// - All the edges and 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::Internal> { . let old_len = self.node.len(); . unsafe { . let mut new_node = InternalNode::new(); 30,297 ( 0.00%) let kv = self.split_leaf_data(&mut new_node.data); . let new_len = usize::from(new_node.data.len); . move_to_slice( 11,422 ( 0.00%) self.node.edge_area_mut(self.idx + 1..old_len + 1), 22,844 ( 0.00%) &mut new_node.edges[..new_len + 1], . ); . . let height = self.node.height; . let right = NodeRef::from_new_internal(new_node, height); . 72,059 ( 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 { 403,807 ( 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(); 263,538 ( 0.00%) let new_left_len = old_left_len + 1 + right_len; . 263,538 ( 0.00%) assert!(new_left_len <= CAPACITY); . . unsafe { 131,769 ( 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), . ); . 131,769 ( 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); 790,614 ( 0.01%) *parent_node.len_mut() -= 1; . 263,538 ( 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), 10,310 ( 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()`. 72,170 ( 0.00%) pub fn merge_tracking_parent(self) -> NodeRef, K, V, marker::Internal> { 20,620 ( 0.00%) self.do_merge(|parent, _child| parent) 103,040 ( 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()`. 850,213 ( 0.01%) pub fn merge_tracking_child_edge( . self, . track_edge_idx: LeftOrRight, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 121,459 ( 0.00%) let old_left_len = self.left_child.len(); 121,459 ( 0.00%) let right_len = self.right_child.len(); 364,377 ( 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(); 121,459 ( 0.00%) let new_idx = match track_edge_idx { . LeftOrRight::Left(idx) => idx, 356,172 ( 0.00%) LeftOrRight::Right(idx) => old_left_len + 1 + idx, . }; . unsafe { Handle::new_edge(child, new_idx) } 971,672 ( 0.01%) } . . /// 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> { 3,250 ( 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> { 2,162 ( 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. 11,375 ( 0.00%) pub fn bulk_steal_left(&mut self, count: usize) { 3,250 ( 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; 1,625 ( 0.00%) let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 8,125 ( 0.00%) assert!(old_right_len + count <= CAPACITY); 4,873 ( 0.00%) assert!(old_left_len >= count); . . let new_left_len = old_left_len - count; . let new_right_len = old_right_len + count; 1,625 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 2,372 ( 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( 3,250 ( 0.00%) left_node.key_area_mut(new_left_len + 1..old_left_len), 1,625 ( 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. 1,623 ( 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(); 4,400 ( 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); . } . 8,125 ( 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!(), . } . } 13,000 ( 0.00%) } . . /// The symmetric clone of `bulk_steal_left`. 8,456 ( 0.00%) pub fn bulk_steal_right(&mut self, count: usize) { 2,416 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; 1,208 ( 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. 6,040 ( 0.00%) assert!(old_left_len + count <= CAPACITY); 2,563 ( 0.00%) assert!(old_right_len >= count); . . let new_left_len = old_left_len + count; . let new_right_len = old_right_len - count; 1,208 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 1,208 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Move the right-most stolen pair to the parent. 2,240 ( 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(); 4,128 ( 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), 1,208 ( 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); . } . 6,040 ( 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), 127 ( 0.00%) left.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . // Fill gap where stolen edges used to be. 127 ( 0.00%) slice_shl(right.edge_area_mut(..old_right_len + 1), count); . . left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); 254 ( 0.00%) right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 9,664 ( 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(); 9,612,750 ( 0.06%) if len > idx + 1 { 412,440 ( 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(); 10,425,584 ( 0.07%) 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. . unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) { . unsafe { . let slice_ptr = slice.as_mut_ptr(); 254 ( 0.00%) ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance); . } . } . . /// 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(); 4,128 ( 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]) { 600,888 ( 0.00%) assert!(src.len() == dst.len()); . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); . } . } . . #[cfg(test)] . mod tests; 29,087,507 ( 0.18%) -------------------------------------------------------------------------------- -- 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] 6,966,486 ( 0.04%) fn eq(&self, other: &str) -> bool { 6,192,432 ( 0.04%) self.as_bytes() == other.as_bytes() 3,096,216 ( 0.02%) } . #[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] 280,849 ( 0.00%) fn index(&self, index: I) -> &I::Output { 259,839 ( 0.00%) index.index(self) 173,226 ( 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] 494,466 ( 0.00%) fn index(self, slice: &str) -> &Self::Output { . slice 164,822 ( 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> { 493,694 ( 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) }; 396,056 ( 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] 54,626 ( 0.00%) fn get(self, slice: &str) -> Option<&Self::Output> { 120,281 ( 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. 21,010 ( 0.00%) Some(unsafe { &*self.get_unchecked(slice) }) . } else { . None . } 16,808 ( 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] 54,626 ( 0.00%) unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output { 8,404 ( 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`. 12,606 ( 0.00%) let ptr = unsafe { slice.as_ptr().add(self.start) }; 157,026 ( 0.00%) let len = slice.len() - self.start; 16,808 ( 0.00%) ptr::slice_from_raw_parts(ptr, len) as *const str 8,404 ( 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] 58,828 ( 0.00%) fn index(self, slice: &str) -> &Self::Output { 42,020 ( 0.00%) let (start, end) = (self.start, slice.len()); 42,020 ( 0.00%) match self.get(slice) { 16,808 ( 0.00%) Some(s) => s, . None => super::slice_error_fail(slice, start, end), . } 8,404 ( 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 ---------------------------------------- -- line 410 ---------------------------------------- . } . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output { . // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`. . unsafe { self.into_slice_range().get_unchecked_mut(slice) } . } . #[inline] . fn index(self, slice: &str) -> &Self::Output { 6 ( 0.00%) if *self.end() == usize::MAX { . str_index_overflow_fail(); . } . self.into_slice_range().index(slice) . } . #[inline] . fn index_mut(self, slice: &mut str) -> &mut Self::Output { . if *self.end() == usize::MAX { . str_index_overflow_fail(); -- line 426 ---------------------------------------- 4,273,437 ( 0.03%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./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 -------------------------------------------------------------------------------- 4,793,084,225 (30.35%) events annotated