-------------------------------------------------------------------------------- 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 -C embed-bitcode=no -C debuginfo=2 -C metadata=edd5117fa6a6e0e6 -C extra-filename=-edd5117fa6a6e0e6 --out-dir /usr/home/liquid/tmp/.tmpA3IuiE/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpA3IuiE/target/debug/deps --extern wasm_bindgen=/usr/home/liquid/tmp/.tmpA3IuiE/target/debug/deps/libwasm_bindgen-556f0b76b0891e97.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-js-sys-0.3.56-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 11,152,877,131 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 380,431,150 ( 3.41%) ./malloc/malloc.c:_int_free 283,111,970 ( 2.54%) ./malloc/malloc.c:_int_malloc 267,794,101 ( 2.40%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 227,123,073 ( 2.04%) ./malloc/malloc.c:malloc 145,655,039 ( 1.31%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs:> as proc_macro::bridge::server::DispatcherTrait>::dispatch 132,077,880 ( 1.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 114,470,455 ( 1.03%) ./malloc/malloc.c:free 95,615,302 ( 0.86%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 65,119,748 ( 0.58%) /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:: 62,816,684 ( 0.56%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::decode 58,138,204 ( 0.52%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 55,374,608 ( 0.50%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>>::insert 51,225,542 ( 0.46%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 50,842,623 ( 0.46%) /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.45%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 48,027,193 ( 0.43%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 47,966,891 ( 0.43%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 46,468,668 ( 0.42%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>>::insert 45,974,645 ( 0.41%) ./malloc/malloc.c:malloc_consolidate 45,499,446 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 45,301,939 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 45,275,351 ( 0.41%) ./elf/../sysdeps/x86_64/tls_get_addr.S:__tls_get_addr 44,605,625 ( 0.40%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 43,231,665 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs: as proc_macro::bridge::rpc::DecodeMut>::decode 40,537,655 ( 0.36%) /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.36%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 38,743,718 ( 0.35%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 37,906,780 ( 0.34%) ./malloc/malloc.c:realloc 37,679,360 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 35,605,654 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::mem::replace 35,388,472 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 35,237,852 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::iterator::Iterator>::next 34,609,419 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 34,055,854 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 32,176,548 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 31,970,700 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 31,661,456 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::read 30,966,954 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 29,886,471 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 28,620,312 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::guaranteed_eq 28,493,069 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 28,159,778 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 27,979,493 ( 0.25%) ./malloc/malloc.c:unlink_chunk.constprop.0 27,646,596 ( 0.25%) /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.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 26,796,710 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>>::insert 26,576,004 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::is_null 26,151,719 ( 0.23%) ./malloc/malloc.c:_int_realloc 25,873,071 ( 0.23%) /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,300,080 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::remove_entry 23,961,277 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 23,947,685 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 23,467,680 ( 0.21%) /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.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.36/src/wrapper.rs:>::extend 22,749,723 ( 0.20%) /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.20%) /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.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs:core::iter::traits::iterator::Iterator::fold 22,255,631 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 21,794,086 ( 0.20%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 21,729,380 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs:core::ptr::non_null::NonNull::as_ptr 21,179,546 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:alloc::vec::Vec::push 20,858,261 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs: as core::ops::try_trait::Try>::branch 20,833,630 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 20,125,352 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:core::str::traits::::eq 20,055,210 ( 0.18%) /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}> 20,022,294 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 19,860,147 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs:<[A] as core::slice::cmp::SlicePartialEq>::equal 19,420,858 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::insert 19,385,534 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 18,900,601 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 18,812,987 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::from_lit_token 18,603,000 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs:>>::insert 17,746,233 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/maybe_uninit.rs:core::ptr::read 17,694,229 ( 0.16%) /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,160,166 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:alloc::raw_vec::RawVec::current_memory 17,111,770 ( 0.15%) /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,022,461 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 17,019,784 ( 0.15%) /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.15%) /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}> 16,182,430 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:>::decode 15,939,394 ( 0.14%) ./elf/dl-lookup.c:do_lookup_x 15,629,785 ( 0.14%) ???:??? 15,541,666 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs:core::ptr::const_ptr::::guaranteed_eq 15,183,448 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::push:: 15,181,392 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/proc_macro_server.rs: as rustc_expand::proc_macro_server::ToInternal>::to_internal 15,155,047 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 15,106,001 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:core::option::Option::map 14,880,132 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/map.rs:core::iter::adapters::map::map_fold::{{closure}} 14,504,496 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::check_lint_name 14,472,644 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.36/src/wrapper.rs:proc_macro2::imp::into_compiler_token 14,431,547 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs:core::ptr::const_ptr::::is_null 14,190,410 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 14,169,269 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 13,938,389 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 13,769,856 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:core::cmp::impls:: for &A>::eq 13,756,622 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 13,513,436 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 13,459,738 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::write 13,396,358 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 13,101,281 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:, proc_macro::bridge::Marked, proc_macro::bridge::Marked, proc_macro::bridge::Marked> as proc_macro::bridge::rpc::DecodeMut>>>::decode 13,045,517 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:> as core::ops::drop::Drop>::drop 12,931,205 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 12,832,430 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>>>::encode 12,799,776 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:alloc::raw_vec::RawVec::grow_amortized 12,788,685 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::hash_one::<&proc_macro::bridge::Marked> 12,774,405 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs:core::ptr::non_null::NonNull::new_unchecked 12,538,975 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 12,512,156 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:core::option::Option::ok_or 12,393,059 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 12,380,046 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs: as proc_macro::bridge::rpc::Encode>>>::encode 12,358,612 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:::push:: 12,270,453 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::hash_one::<&proc_macro::bridge::Marked> 12,171,743 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:>::into 12,114,809 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:core::str::converts::from_utf8 12,043,192 ( 0.11%) ./malloc/malloc.c:calloc 12,033,331 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 11,940,336 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_u32 11,909,474 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>::search_tree:: 11,838,628 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/slice.rs:::to_vec 11,702,237 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:::rollback_to 11,699,193 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 11,688,888 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 11,400,458 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/result.rs:core::result::Result::map_err 11,326,572 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/mod.rs:::hash_one::<&proc_macro::bridge::Marked> 11,285,406 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter.rs:core::slice::iter::Iter::new 11,208,464 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace -------------------------------------------------------------------------------- -- 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.06%) fn next(&mut self) -> (Token, Spacing) { . loop { 3,248,107 ( 0.03%) 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.06%) } 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.04%) 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.04%) } . 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.03%) 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.02%) 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.02%) 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.02%) if matches!( 1,010,164 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 2,005,936 ( 0.02%) 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.01%) 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.08%) fn check(&mut self, tok: &TokenKind) -> bool { 3,752,077 ( 0.03%) let is_present = self.token == *tok; 2,531,168 ( 0.02%) if !is_present { 5,061,095 ( 0.05%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 8,646,400 ( 0.08%) } . . /// 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.02%) 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.02%) 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.01%) } . 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.01%) 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.01%) } . . /// 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.06%) 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.03%) 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.02%) 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.04%) pub fn bump(&mut self) { 2,005,936 ( 0.02%) let next_token = self.next_tok(self.token.span); 3,008,904 ( 0.03%) self.bump_with(next_token); 4,011,872 ( 0.04%) } . . /// 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.01%) !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.03%) -------------------------------------------------------------------------------- -- 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.09%) <_>::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.23%) fn dispatch(&mut self, mut b: Buffer) -> Buffer { . let Dispatcher { handle_store, server } = self; . 7,583,241 ( 0.07%) let mut reader = &b[..]; 17,694,229 ( 0.16%) match api_tags::Method::decode(&mut reader, &mut ()) { 12,238,368 ( 0.11%) $(api_tags::Method::$name(m) => match m { . $(api_tags::$name::$method => { . let mut call_method = || { 8,131,842 ( 0.07%) 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.10%) panic::catch_unwind(panic::AssertUnwindSafe(call_method)) . .map_err(PanicMessage::from) . }; . . b.clear(); 27,718,279 ( 0.25%) r.encode(&mut b, handle_store); . })* . }),* . } 15,166,482 ( 0.14%) b 22,749,723 ( 0.20%) } . } . } . } . 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.20%) 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.05%) -------------------------------------------------------------------------------- -- 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.05%) 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.11%) 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.24%) 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.04%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 13,652,470 ( 0.12%) self.len += xs.len(); . } 130 ( 0.00%) } . 611,220 ( 0.01%) 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.01%) } . 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.27%) if self.len == self.capacity { . let b = self.take(); . *self = (b.reserve)(b, 1); . } . unsafe { 19,449,771 ( 0.17%) *self.data.add(self.len) = v; 17,387,712 ( 0.16%) 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.01%) } . . 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.27%) (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.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . /// `ctxt` values depend partly on the crate size and partly on the form of . /// the code. No crates in `rustc-perf` need more than 15 bits for `ctxt`, . /// but larger crates might need more than 16 bits. . /// . /// In order to reliably use parented spans in incremental compilation, . /// the dependency to the parent definition's span. This is performed . /// using the callback `SPAN_TRACK` to access the query engine. . /// 2,144,032 ( 0.02%) #[derive(Clone, Copy, Eq, PartialEq, Hash)] . // FIXME(@lcnr): Enable this attribute once the bootstrap . // compiler knows of `rustc_pass_by_value`. . // . // Right now, this lint would only trigger when compiling the . // stage 2 compiler, which is fairly annoying as there are . // a lot of places using `&Span` right now. After the next bootstrap bump, . // the lint will already trigger when using stage 1, which is a lot less annoying. . // . // #[cfg_attr(not(bootstrap), rustc_pass_by_value)] . pub struct Span { 1,463,403 ( 0.01%) base_or_index: u32, 805,530 ( 0.01%) len_or_tag: u16, 4,676,761 ( 0.04%) ctxt_or_zero: u16, . } . . const LEN_TAG: u16 = 0b1000_0000_0000_0000; . const MAX_LEN: u32 = 0b0111_1111_1111_1111; . const MAX_CTXT: u32 = 0b1111_1111_1111_1111; . . /// Dummy span, both position and length are zero, syntax context is zero as well. . pub const DUMMY_SP: Span = Span { base_or_index: 0, len_or_tag: 0, ctxt_or_zero: 0 }; -- line 84 ---------------------------------------- -- line 86 ---------------------------------------- . impl Span { . #[inline] . pub fn new( . mut lo: BytePos, . mut hi: BytePos, . ctxt: SyntaxContext, . parent: Option, . ) -> Self { 1,341,406 ( 0.01%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 2,682,812 ( 0.02%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 12,199,958 ( 0.11%) if len <= MAX_LEN && ctxt2 <= MAX_CTXT && parent.is_none() { . // Inline format. . Span { base_or_index: base, len_or_tag: len as u16, ctxt_or_zero: ctxt2 as u16 } . } else { . // Interned format. . let index = 85 ( 0.00%) with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt, parent })); . Span { base_or_index: index, len_or_tag: LEN_TAG, ctxt_or_zero: 0 } . } 4,410,757 ( 0.04%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 4 ( 0.00%) if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 12,283,627 ( 0.11%) if self.len_or_tag != LEN_TAG { . // Inline format. . debug_assert!(self.len_or_tag as u32 <= MAX_LEN); . SpanData { . lo: BytePos(self.base_or_index), 11,370,118 ( 0.10%) hi: BytePos(self.base_or_index + self.len_or_tag as u32), . ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32), . parent: None, . } . } else { . // Interned format. . debug_assert!(self.ctxt_or_zero == 0); 18 ( 0.00%) let index = self.base_or_index; 52 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 2,904,043 ( 0.03%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 24 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 32 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 32 ( 0.00%) } . } . . // If an interner exists, return it. Otherwise, prepare a fresh one. . #[inline] . fn with_span_interner T>(f: F) -> T { . crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock())) . } 13,452,712 ( 0.12%) -------------------------------------------------------------------------------- -- 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,661,754 ( 0.10%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 2,425,013 ( 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.02%) 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%) } . 59,934 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 39,956 ( 0.00%) match self { 179,802 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 79,912 ( 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,250,179 ( 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,119 ( 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.04%) 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.02%) 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.01%) *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.03%) } . 99,828 ( 0.00%) pub fn build(self) -> TokenStream { 598,968 ( 0.01%) 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.01%) fn next(&mut self) -> Option { 1,046,892 ( 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,650,715 ( 0.03%) pub fn next_with_spacing(&mut self) -> Option { 2,854,428 ( 0.03%) if self.index < self.stream.len() { 1,366,978 ( 0.01%) self.index += 1; 3,860,192 ( 0.03%) Some(self.stream.0[self.index - 1].clone()) . } else { 357,374 ( 0.00%) None . } 4,380,858 ( 0.04%) } . . 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.01%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 681,152 ( 0.01%) } . } . 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,659,626 ( 0.02%) -------------------------------------------------------------------------------- -- 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,468 ( 0.06%) fn eq(&self, other: &str) -> bool { 6,192,416 ( 0.06%) self.as_bytes() == other.as_bytes() 3,096,208 ( 0.03%) } . #[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,689 ( 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) }; 395,700 ( 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> { 49,593 ( 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) }; 86,330 ( 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,202,729 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 2,984 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 2,984 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 5,968 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 233,715 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 1,589,262 ( 0.01%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 140,229 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 280,458 ( 0.00%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 41,300 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 881,320 ( 0.01%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 1,136 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 6,290 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 233,289 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 260,660 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 616,440 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 916,601 ( 0.01%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 59,761 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 2,072 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 537 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 478 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 46,743 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 140,229 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 46,743 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 75,978 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 92,862 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 42,210 ( 0.00%) self.with_opaque_type_inference(table_owner) 59,094 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 6,004 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 3,002 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 22,888 ( 0.00%) self 9,006 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 24,628 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 42,376 ( 0.00%) let (value, subst) = 1,659 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 60,624 ( 0.00%) f(infcx, value, subst) . }) 26,898 ( 0.00%) } . 331,424 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 123,070 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 2,107,334 ( 0.02%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 46,743 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 46,743 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 360,173 ( 0.00%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 1,223 ( 0.00%) let InferOk { value, obligations } = self; 4,428 ( 0.00%) for obligation in obligations { . fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 43,429 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 173,716 ( 0.00%) self.obligations 43,429 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 83,631 ( 0.00%) } . 426,224 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 479,502 ( 0.00%) t.fold_with(&mut self.freshener()) 479,502 ( 0.00%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 1,568 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 3,136 ( 0.00%) match *ty.kind() { 771 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 3,084 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } 13 ( 0.00%) _ => None, . } 3,136 ( 0.00%) } . 53,278 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 53,278 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 257,816 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 257,816 ( 0.00%) } . 15,020 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 7,510 ( 0.00%) let mut inner = self.inner.borrow_mut(); 7,510 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 814 ( 0.00%) .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) 58 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) 13 ( 0.00%) .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 26,285 ( 0.00%) } . 137,827 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 579,584 ( 0.01%) CombineFields { . infcx: self, 1,448,960 ( 0.01%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 137,827 ( 0.00%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 760 ---------------------------------------- . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. . pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 28,584 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result . } . 764,488 ( 0.01%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 2,293,464 ( 0.02%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 382,244 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 1,528,976 ( 0.01%) } . 1,667,501 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 151,591 ( 0.00%) undo_snapshot, 151,591 ( 0.00%) region_constraints_snapshot, 151,591 ( 0.00%) universe, 151,591 ( 0.00%) was_in_snapshot, 303,182 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 151,591 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 3,459,795 ( 0.03%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 230,653 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 230,653 ( 0.00%) was_in_snapshot, 461,306 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 240,678 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 294,316 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 26,756 ( 0.00%) let snapshot = self.start_snapshot(); 80,793 ( 0.00%) let r = f(&snapshot); 187,292 ( 0.00%) self.commit_from(snapshot); 160,710 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 1,559,879 ( 0.01%) #[instrument(skip(self, f), level = "debug")] 1,926,990 ( 0.02%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 298,478 ( 0.00%) let snapshot = self.start_snapshot(); 914,621 ( 0.01%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 308,923 ( 0.00%) match r { . Ok(_) => { 1,464,408 ( 0.01%) self.commit_from(snapshot); . } . Err(_) => { 589,003 ( 0.01%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 1,546,276 ( 0.01%) r . } . . /// Execute `f` then unroll any bindings it creates. 498,697 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 639,636 ( 0.01%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 164,315 ( 0.00%) let snapshot = self.start_snapshot(); 295,846 ( 0.00%) let r = f(&snapshot); 757,286 ( 0.01%) self.rollback_to("probe", snapshot); 93,047 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. 63,486 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 84,648 ( 0.00%) pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 14,108 ( 0.00%) let snapshot = self.start_snapshot(); 7,054 ( 0.00%) let was_skip_leak_check = self.skip_leak_check.get(); 14,108 ( 0.00%) if should_skip { . self.skip_leak_check.set(true); . } 28,216 ( 0.00%) let r = f(&snapshot); 63,486 ( 0.00%) self.rollback_to("probe", snapshot); . self.skip_leak_check.set(was_skip_leak_check); 84,648 ( 0.00%) r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 10,422 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 20,844 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 15,633 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . 36 ( 0.00%) pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 27 ( 0.00%) } . 24,600 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 18,450 ( 0.00%) } . 68,570 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 61,713 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. 5 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, . definition_span: Span, . hidden_ty: Ty<'tcx>, . region: ty::Region<'tcx>, . in_regions: &Lrc>>, . ) { 5 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().member_constraint( . opaque_type_def_id, . definition_span, . hidden_ty, . region, . in_regions, . ); . } . -- line 961 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 3 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 2 ( 0.00%) let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); 5 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 4 ( 0.00%) } . 2,724 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 227 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 227 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 1,756 ( 0.00%) match (r_a.kind(), r_b.kind()) { 424 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 424 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 15 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 30 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 2,043 ( 0.00%) } . 22,164 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 18,470 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 14,776 ( 0.00%) } . . /// Number of type variables created so far. 771 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 1,542 ( 0.00%) } . 50,030 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 250,150 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 75,045 ( 0.00%) } . 49,080 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 174,630 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 73,620 ( 0.00%) } . 2,000 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 11,000 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 1,000 ( 0.00%) self.tcx.mk_ty_var(vid) 3,000 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 75 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 45 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 60 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 12,827 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 667,239 ( 0.01%) self.next_region_var_in_universe(origin, self.universe()) 25,654 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 261,710 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 1,701,115 ( 0.02%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 654,275 ( 0.01%) self.tcx.mk_region(ty::ReVar(region_var)) 392,565 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 9,932 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 14,898 ( 0.00%) } . . /// Number of region variables created so far. 24,042 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 36,063 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 27,647 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 55,294 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 10 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 110 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 20 ( 0.00%) } . 907,928 ( 0.01%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 402,835 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 82,310 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 123,884 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 154,855 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 30,971 ( 0.00%) param.name, 30,971 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 30,971 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 2,310 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 210 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 1,680 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 236,049 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 1,023,128 ( 0.01%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 157,366 ( 0.00%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 7,540 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 184,760 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 11,310 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 184,765 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 501,505 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 26,395 ( 0.00%) assert!( 79,185 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 26,395 ( 0.00%) }; . . let region_rels = 26,395 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 237,555 ( 0.00%) let (lexical_region_resolutions, errors) = 633,480 ( 0.01%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 105,580 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 26,395 ( 0.00%) assert!(old_value.is_none()); . . errors 237,555 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 263,950 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 52,790 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 79,185 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 52,790 ( 0.00%) self.report_region_errors(&errors); . } 131,975 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate . /// region constraints as normal, but then we take them and . /// translate them into the form that the NLL solver . /// understands. See the NLL module for mode details. 6 ( 0.00%) pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> { 2 ( 0.00%) assert!( . self.inner.borrow().region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . self.inner.borrow().region_obligations . ); . 8 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data() 10 ( 0.00%) } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 13,336 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 15,005 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 57,019 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 3,001 ( 0.00%) .into_infos_and_data(); 3,001 ( 0.00%) assert!(data.is_empty()); . var_infos 24,008 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 15,362 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 46,086 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 53,767 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 442,100 ( 0.00%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 31,544 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 47,316 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. 141,608 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 385,097 ( 0.00%) if !value.needs_infer() { 545,678 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 433,928 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 543,788 ( 0.00%) value.fold_with(&mut r) 127,632 ( 0.00%) } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> . where -- line 1415 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 65,277 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 134,028 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 322,226 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 43,518 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 40 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 15 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 85 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 35 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. 252 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 504 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 378 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 960,219 ( 0.01%) self.universe.get() 268,322 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 18 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 102 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 18 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 4,042,632 ( 0.04%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 2,090,207 ( 0.02%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 1,106,192 ( 0.01%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 1,000 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 309 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 4,547,961 ( 0.04%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 390,799 ( 0.00%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 322 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 13,124 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 13,124 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 422 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 121,776 ( 0.00%) match *ty.kind() { 27,034 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 26 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 422 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 766,826 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 2,212 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 2,212 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 2,765 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 1,659 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 2,765 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { . self.cause.span . } . . pub fn types( -- line 1787 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 39,041 ( 0.00%) match *cause.code() { 6,793 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 33,965 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 3,412,657 ( 0.03%) -------------------------------------------------------------------------------- -- 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 { 10,721,413 ( 0.10%) *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.03%) 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,738,602 ( 0.09%) ManuallyDrop::into_inner(self.value) . } 709,288 ( 0.01%) } . . /// 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.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,348,846 ( 0.05%) 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)); 461,740 ( 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::()); 110,204,527 ( 0.99%) 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] 540 ( 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" . ); . 554,342 ( 0.00%) self.stride += Group::WIDTH; 554,450 ( 0.00%) self.pos += self.stride; 491,611 ( 0.00%) self.pos &= bucket_mask; 216 ( 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. 608,860 ( 0.01%) 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,338,258 ( 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. 220,831 ( 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,490,425 ( 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. 281,013 ( 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,309,757 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 1,707,806 ( 0.02%) 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,270 ( 0.00%) unsafe fn from_base_index(base: NonNull, index: usize) -> Self { 7,416 ( 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,416 ( 0.00%) base.as_ptr().sub(index) . }; 1,854 ( 0.00%) Self { 7,416 ( 0.00%) ptr: NonNull::new_unchecked(ptr), . } 5,562 ( 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,172 ( 0.00%) pub fn as_ptr(&self) -> *mut T { 6,896 ( 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,344 ( 0.00%) unsafe { self.ptr.as_ptr().sub(1) } . } 5,172 ( 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,882 ( 0.00%) pub unsafe fn as_ref<'a>(&self) -> &'a T { 1,882 ( 0.00%) &*self.as_ptr() 1,882 ( 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 { 42,804 ( 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,924 ( 0.00%) pub unsafe fn data_end(&self) -> NonNull { 4,810 ( 0.00%) NonNull::new_unchecked(self.table.ctrl.as_ptr().cast()) 1,924 ( 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,108 ( 0.00%) pub unsafe fn bucket(&self, index: usize) -> Bucket { . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); 3,108 ( 0.00%) Bucket::from_base_index(self.data_end(), index) 1,554 ( 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")] 66,915 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 66,915 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 133,830 ( 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,312 ( 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 { 98,518 ( 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,179,004 ( 0.02%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 730 ( 0.00%) match self.find(hash, eq) { 26,743 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 598,975 ( 0.01%) None => None, . } 3,226,669 ( 0.03%) } . . /// 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) { 76,196 ( 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,287,093 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 1,019,595 ( 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,434,773 ( 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,774,496 ( 0.02%) } . . /// 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,052,460 ( 0.07%) 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. 37,881 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 5,101,466 ( 0.05%) 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 . } 5,916,074 ( 0.05%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 757,128 ( 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() } 567,846 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 6,158 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 1,293,804 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 25,953 ( 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,624,732 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 2,120,079 ( 0.02%) self.table.items += 1; . bucket 12,207 ( 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] 21,998 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 38,569 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 161,393 ( 0.00%) eq(self.bucket(index).as_ref()) 9,738 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. 2,319 ( 0.00%) match result { 4,287 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), 1,546 ( 0.00%) None => None, . } 20,452 ( 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. 79,390 ( 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] 2,912 ( 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. 17,747 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), 1,456 ( 0.00%) None => None, . } 2,184 ( 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,571,288 ( 0.03%) 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()), 496,883 ( 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,864 ( 0.00%) let allocation = self.into_allocation(); 44,148 ( 0.00%) RawIntoIter { 73,580 ( 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,890 ( 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,822 ( 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,103,639 ( 0.03%) 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,477,776 ( 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()); . } . 532,646 ( 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,358,242 ( 0.01%) Ok(Self { . ctrl, 531,684 ( 0.00%) bucket_mask: buckets - 1, . items: 0, 576 ( 0.00%) growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 1,802,290 ( 0.02%) } . . #[inline] 113,888 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 30,774 ( 0.00%) if capacity == 0 { 23,827 ( 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,124,496 ( 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()); . 60,469 ( 0.00%) Ok(result) . } . } 113,312 ( 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] 457,749 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { 2,676 ( 0.00%) let index = self.find_insert_slot(hash); 457,749 ( 0.00%) let old_ctrl = *self.ctrl(index); 892 ( 0.00%) self.set_ctrl_h2(index, hash); 1,784 ( 0.00%) (index, old_ctrl) 910,146 ( 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,738 ( 0.00%) loop { . unsafe { 13,904 ( 0.00%) let group = Group::load(self.ctrl(probe_seq.pos)); 3,495,308 ( 0.03%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 10,279,483 ( 0.09%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 4,714,265 ( 0.04%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . 3,368 ( 0.00%) return result; . } . } 162 ( 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); . 249,003 ( 0.00%) loop { 6,616 ( 0.00%) let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 13,180,305 ( 0.12%) for bit in group.match_byte(h2_hash) { 26,929,965 ( 0.24%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 17,025,578 ( 0.15%) if likely(eq(index)) { . return Some(index); . } . } . 3,580,283 ( 0.03%) if likely(group.match_empty().any_bit_set()) { 773 ( 0.00%) return None; . } . 216 ( 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(); 11,760,272 ( 0.11%) 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 { 71,880,291 ( 0.64%) 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,372,861 ( 0.06%) self.growth_left -= special_is_empty(old_ctrl) as usize; 1,456 ( 0.00%) self.set_ctrl_h2(index, hash); 5,096,396 ( 0.05%) 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] | . // --------------------------------------------- 9,608,643 ( 0.09%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 3,205,581 ( 0.03%) *self.ctrl(index) = ctrl; 3,204,835 ( 0.03%) *self.ctrl(index2) = ctrl; 3,240 ( 0.00%) } . . /// Returns a pointer to a control byte. . #[inline] 40,996 ( 0.00%) unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); 30,747 ( 0.00%) self.ctrl.as_ptr().add(index) 20,498 ( 0.00%) } . . #[inline] 624 ( 0.00%) fn buckets(&self) -> usize { 1,541,457 ( 0.01%) self.bucket_mask + 1 624 ( 0.00%) } . . #[inline] 128 ( 0.00%) fn num_ctrl_bytes(&self) -> usize { 1,241,289 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH 128 ( 0.00%) } . . #[inline] 388 ( 0.00%) fn is_empty_singleton(&self) -> bool { 5,688,729 ( 0.05%) 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. 13,228 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( 64 ( 0.00%) self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 642,165 ( 0.01%) 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_| { 298,609 ( 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. 597,334 ( 0.01%) let new_items = match self.items.checked_add(additional) { 256 ( 0.00%) Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 596,882 ( 0.01%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 1,248,283 ( 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( 298,921 ( 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> { 30,132 ( 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() { 1,932,854 ( 0.02%) 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); . 298,345 ( 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( 199,743 ( 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) { 24,123 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 34,438 ( 0.00%) self.items = 0; 24,123 ( 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))); 355,499 ( 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,421,996 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 1,774,330 ( 0.02%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 1,421,996 ( 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,191,668 ( 0.03%) fn drop(&mut self) { 2,450,896 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { 55 ( 0.00%) self.drop_elements(); 55 ( 0.00%) self.free_buckets(); . } . } 3,410,894 ( 0.03%) } . } . #[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,864 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 73,580 ( 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,129,777 ( 0.02%) if let Some(index) = self.current_group.lowest_set_bit() { 151,172 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 275,384 ( 0.00%) return Some(self.data.next_n(index)); . } . 1,172,373 ( 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). 15,842 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 19,346 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 20,715 ( 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,325 ( 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)] 225,745 ( 0.00%) fn next(&mut self) -> Option> { 2,610,182 ( 0.02%) if let Some(b) = self.iter.next() { 3,298,489 ( 0.03%) 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 . } 450,770 ( 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,490 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 130,670 ( 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)] 3,603 ( 0.00%) fn next(&mut self) -> Option { 879 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 7,206 ( 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 ---------------------------------------- 46,988,113 ( 0.42%) -------------------------------------------------------------------------------- -- 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,135 ( 0.04%) pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { . // SAFETY: the caller must guarantee that `ptr` is non-null. 9,643,652 ( 0.09%) unsafe { NonNull { pointer: ptr as _ } } 6,261,345 ( 0.06%) } . . /// 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.01%) 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.01%) Some(unsafe { Self::new_unchecked(ptr) }) . } else { . None . } 664,497 ( 0.01%) } . . /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a . /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer. . /// . /// See the documentation of [`std::ptr::from_raw_parts`] for more details. . /// . /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts . #[unstable(feature = "ptr_metadata", issue = "81513")] -- line 230 ---------------------------------------- -- line 268 ---------------------------------------- . /// unsafe { *ptr.as_ptr() += 2; } . /// let x_value = unsafe { *ptr.as_ptr() }; . /// assert_eq!(x_value, 2); . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")] . #[must_use] . #[inline] 13,239,000 ( 0.12%) pub const fn as_ptr(self) -> *mut T { . self.pointer as *mut T 8,490,380 ( 0.08%) } . . /// 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.01%) 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.02%) 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. 207,977 ( 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,392 ( 0.04%) -------------------------------------------------------------------------------- -- 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,232 ( 0.07%) 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,232 ( 0.07%) (self as *mut u8).guaranteed_eq(null_mut()) 8,177,232 ( 0.07%) } . . /// 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`. 68,037,359 ( 0.61%) 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,924 ( 0.05%) pub const fn guaranteed_eq(self, other: *mut T) -> bool . where . T: Sized, . { 12,266,309 ( 0.11%) intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _) 8,177,232 ( 0.07%) } . . /// 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,360 ( 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,960 ( 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`. 163 ( 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 { 130,018 ( 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,552,775 ( 0.05%) -------------------------------------------------------------------------------- -- 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); . /// ``` 7,704 ( 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 { 190 ( 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.01%) } . . /// 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 { 385,474 ( 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,662,255 ( 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 { 2,923,711 ( 0.03%) 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 { 1,432 ( 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,464,822 ( 0.03%) match compare(&v1, &v2) { 24,140 ( 0.00%) Ordering::Less | Ordering::Equal => v1, 2,952 ( 0.00%) Ordering::Greater => v2, . } 62,187 ( 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 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.01%) v1.max(v2) 584,656 ( 0.01%) } . . /// 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 { 7,945,301 ( 0.07%) match compare(&v1, &v2) { 624,644 ( 0.01%) 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] 224,891 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] 106,379 ( 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] 12,906,523 ( 0.12%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] 368,070 ( 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. 156,816,723 ( 1.41%) if *self < *other { Less } 707,814 ( 0.01%) 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. 28,910 ( 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,303,152 ( 0.04%) fn eq(&self, other: &&B) -> bool { 8,913,646 ( 0.08%) PartialEq::eq(*self, *other) 3,784,278 ( 0.03%) } . #[inline] . fn ne(&self, other: &&B) -> bool { 66 ( 0.00%) PartialEq::ne(*self, *other) 106,242 ( 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) 66,872 ( 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 ---------------------------------------- 15,189,449 ( 0.14%) -------------------------------------------------------------------------------- -- 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,503,263 ( 0.04%) fn eq(&self, other: &[B]) -> bool { 1,721,232 ( 0.02%) SlicePartialEq::equal(self, other) 3,683,772 ( 0.03%) } . . 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,304,260 ( 0.01%) if self.len() != other.len() { . return false; . } . 108,160 ( 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,544 ( 0.07%) fn equal(&self, other: &[B]) -> bool { 2,680,206 ( 0.02%) if self.len() != other.len() { 651,429 ( 0.01%) return false; . } . . // SAFETY: `self` and `other` are references and are thus guaranteed to be valid. . // The two slices have been checked to have the same size above. . unsafe { 836,748 ( 0.01%) let size = mem::size_of_val(self); 7,990,491 ( 0.07%) memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0 . } 4,512,267 ( 0.04%) } . } . . #[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. 7,817 ( 0.00%) unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) }; 15,634 ( 0.00%) if order == 0 { . left.len().cmp(&right.len()) 225 ( 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,372,215 ( 0.04%) -------------------------------------------------------------------------------- -- 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, . { 17,933 ( 0.00%) self.fold( . 0, . #[rustc_inherit_overflow_checks] 47,403 ( 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()?; 8,896 ( 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.01%) fn chain(self, other: U) -> Chain . where . Self: Sized, . U: IntoIterator, . { 2,104,528 ( 0.02%) 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,196,147 ( 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.06%) move |(), item| f(item) 306,116 ( 0.00%) } . 7,434,456 ( 0.07%) 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, . { 180,243 ( 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,013 ( 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,664 ( 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,389 ( 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,378 ( 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")] 100,966 ( 0.00%) fn try_fold(&mut self, init: B, mut f: F) -> R . where . Self: Sized, . F: FnMut(B, Self::Item) -> R, . R: Try, . { 22,002 ( 0.00%) let mut accum = init; 5,285,436 ( 0.05%) while let Some(x) = self.next() { 6,516,024 ( 0.06%) accum = f(accum, x)?; . } 28,620 ( 0.00%) try { accum } 88,075 ( 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 { 11,988 ( 0.00%) move |(), x| f(x) . } . 692 ( 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, . { 403,314 ( 0.00%) let mut accum = init; 16,047,917 ( 0.14%) while let Some(x) = self.next() { 6,458,959 ( 0.06%) 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()?; 24,912 ( 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 } . } . } 13,140 ( 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| { 72 ( 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, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 90,760 ( 0.00%) while let Some(x) = self.next() { 298,339 ( 0.00%) if predicate(&x) { . return Some(x); . } . } 20 ( 0.00%) None 2,892 ( 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, . { 578,631 ( 0.01%) while let Some(x) = self.next() { 921,068 ( 0.01%) if let Some(y) = f(x) { 46,838 ( 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() { 307,833 ( 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; 50,259 ( 0.00%) while let Some(x) = self.next_back() { 536,104 ( 0.00%) i -= 1; 448,613 ( 0.00%) 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` 166,970 ( 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 { 94,428 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); 118,035 ( 0.00%) if mem::size_of::() != 0 { 47,236 ( 0.00%) assume(!self.end.is_null()); . } 2,013,253 ( 0.02%) 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 ---------------------------------------- 28,622,702 ( 0.26%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 4,433,800 ( 0.04%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 2,771,125 ( 0.02%) .intern(kind, |kind| { 57,174 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 114,348 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 4,988,025 ( 0.04%) } . . #[inline(never)] 1,751,824 ( 0.02%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 1,532,846 ( 0.01%) .intern(kind, |kind| { 122,226 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 1,970,802 ( 0.02%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 869,494 ( 0.01%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 642,354 ( 0.01%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 130,918 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 130,918 ( 0.00%) self.data.get(&id.local_id) 514,372 ( 0.00%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 17,616 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 11,744 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 68,556 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 811,246 ( 0.01%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 68,556 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 138,036 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 92,024 ( 0.00%) match *qpath { 250,452 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 25,620 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 230,060 ( 0.00%) } . 742 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 9,527 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 742 ( 0.00%) } . 7,037 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 14,428 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 14,074 ( 0.00%) } . 12,484 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 12,484 ( 0.00%) } . 53,708 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 53,708 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 53,708 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 4,292 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 807 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 5,904 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 2,952 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 24,690 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 12,345 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 5,268 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 2,634 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 127,814 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 63,907 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 235,176 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 117,588 ( 0.00%) } . 978,174 ( 0.01%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 163,029 ( 0.00%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 815,145 ( 0.01%) } . 200,465 ( 0.00%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 200,465 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 400,930 ( 0.00%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 23,696 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 11,848 ( 0.00%) } . 70,454 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 70,454 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 140,908 ( 0.00%) } . 48,898 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 48,898 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 97,796 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 29,524 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 188,356 ( 0.00%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 146,920 ( 0.00%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 83,960 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 41,980 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 117,562 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 58,781 ( 0.00%) } . 69,146 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 138,292 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 138,292 ( 0.00%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 3,170 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 634 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 712 ( 0.00%) } . 10 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 2 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 8 ( 0.00%) } . 8,785 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 17,570 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 17,954 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 17,570 ( 0.00%) } . 61,362 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 81,816 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 48,658 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 14,102 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 27,244 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 13,622 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 45,300 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 22,650 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 14,782 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 7,391 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 12,284 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 15,355 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 5,968 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 2,984 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } . } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 17,712 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 8,856 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 11,744 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 5,872 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 5,968 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 2,984 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 675 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 225 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 450 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 2,984 ( 0.00%) &self.coercion_casts 2,984 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 2,702 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 1,359 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 3,825 ( 0.00%) pub fn is_identity(&self) -> bool { 7,650 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 3,825 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 8,116 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 3,058 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 10 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 7,650 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 8,154 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 50,129 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 121,180 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 48,472 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 96,944 ( 0.00%) } . 9,003 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 3,001 ( 0.00%) self.arena.alloc(Steal::new(thir)) 12,004 ( 0.00%) } . 45,340 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 9,068 ( 0.00%) self.arena.alloc(Steal::new(mir)) 63,476 ( 0.00%) } . 12,004 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 3,001 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 15,005 ( 0.00%) } . 783 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 1,392 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 348 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. . pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. . let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); . let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) . } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 6,968 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 3,484 ( 0.00%) let attrs = self.get_attrs(def_id); 14,807 ( 0.00%) let get = |name| { 3,484 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); . if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { . kind: ast::LitKind::Int(a, _), .. -- line 1111 ---------------------------------------- -- line 1114 ---------------------------------------- . ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 17,420 ( 0.00%) }; 5,226 ( 0.00%) ( 5,226 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 2,613 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 6,968 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 469 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 67 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 528 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 536 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 1,610,609 ( 0.01%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 2,070,783 ( 0.02%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 392 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 448 ( 0.00%) } . . /// Obtain the diagnostic item's name 151,172 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 172,768 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 66,080 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 75,520 ( 0.00%) } . 38,864 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 49,968 ( 0.00%) } . 1,137,605 ( 0.01%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 1,300,120 ( 0.01%) } . 60 ( 0.00%) pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 54,614 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 26,398 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } . } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. -- line 1272 ---------------------------------------- -- line 1277 ---------------------------------------- . } else { . self.untracked_resolutions.cstore.def_path(id) . } . } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 27,540 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 572 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 71,586 ( 0.00%) &*self.untracked_resolutions.cstore 35,793 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 66 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 329 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 5,968 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 8,952 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 2,984 ( 0.00%) self.sess.opts.borrowck_mode 11,936 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { . let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. . features.generic_const_exprs -- line 1434 ---------------------------------------- -- line 1554 ---------------------------------------- . self.mk_imm_ref( . self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) . .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) . } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 17,908 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 13,024 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 29,304 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 14,652 ( 0.00%) } . . pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit . } . 605,689 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 692,216 ( 0.01%) } . . pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit . } . 931 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 1,064 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 1 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 277,724 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 1,083,286 ( 0.01%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1805 ---------------------------------------- . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 535,193 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 535,142 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 534,339 ( 0.00%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 86,004 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 203,123 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 28,668 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 640,424 ( 0.01%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 44,198 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 232,045 ( 0.00%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 54,372 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 1,930,142 ( 0.02%) pub fn $method(self, v: $ty) -> &'tcx $ty { 988,315 ( 0.01%) self.interners.$name.intern(v, |v| { 10,108 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 2,170,647 ( 0.02%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 6,703,979 ( 0.06%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 5,996,781 ( 0.05%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2170 ---------------------------------------- . . /// Given a closure signature, returns an equivalent fn signature. Detuples . /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then . /// you would get a `fn(u32, i32)`. . /// `unsafety` determines the unsafety of the fn signature. If you pass . /// `hir::Unsafety::Unsafe` in the previous example, then you would get . /// an `unsafe fn (u32, i32)`. . /// It cannot convert a closure that requires unsafe. 30 ( 0.00%) pub fn signature_unclosure( . self, . sig: PolyFnSig<'tcx>, . unsafety: hir::Unsafety, . ) -> PolyFnSig<'tcx> { 48 ( 0.00%) sig.map_bound(|s| { 30 ( 0.00%) let params_iter = match s.inputs()[0].kind() { . ty::Tuple(params) => params.into_iter().map(|k| k.expect_ty()), . _ => bug!(), . }; 42 ( 0.00%) self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) 24 ( 0.00%) } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 147,860 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 3,986,206 ( 0.04%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 2,335,601 ( 0.02%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 1,350,680 ( 0.01%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 75,324 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 1,350,680 ( 0.01%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 869 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 869 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 4,032 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 4,032 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { 896 ( 0.00%) match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } 896 ( 0.00%) } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 1,674 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . -- line 2259 ---------------------------------------- -- line 2341 ---------------------------------------- . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { . let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 60 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 10,700 ( 0.00%) iter.intern_with(|ts| { 4,182 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 28,351 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 9,630 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 456 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { 5,824 ( 0.00%) if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 1,736 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 1,260 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 18,844 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 10,340 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 9,360 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 2,264 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 18,844 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . . pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Field(f, ty)) -- line 2471 ---------------------------------------- -- line 2504 ---------------------------------------- . /// flight. . pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } . } . 10,192 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 5,159 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 20,757 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 20,636 ( 0.00%) self._intern_poly_existential_predicates(eps) 11,648 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 33,010 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 1,150 ( 0.00%) self._intern_predicates(preds) . } 63,736 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 121,899 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 178 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 1,114,811 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 135,940 ( 0.00%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 14,761 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 10,586 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 62,477 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 970 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 21,333 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 29,004 ( 0.00%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 20,641 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 3,737 ( 0.00%) c_variadic, 5,376 ( 0.00%) unsafety, 4,202 ( 0.00%) abi, 140 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 6,784 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 4 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 12,841 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 584,509 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) . } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 678 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 55,054 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 110,108 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 92,175 ( 0.00%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 541,716 ( 0.00%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 541,716 ( 0.00%) let hir = self.hir(); . loop { 893,862 ( 0.01%) if id == bound { . return bound; . } . 1,108,518 ( 0.01%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 661,698 ( 0.01%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 773,880 ( 0.01%) } . 43,600 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 242,980 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 18,520 ( 0.00%) let next = self.hir().get_parent_node(id); 55,560 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 43,600 ( 0.00%) } . 784 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 7,283 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 1,890 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 448 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 12,362 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 3,532 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 3,532 ( 0.00%) Some(&*candidates) 14,128 ( 0.00%) } . 78,806 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 101,322 ( 0.00%) } . 4,086 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 209 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 3,632 ( 0.00%) } . 45,458 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 58,446 ( 0.00%) } . 41,940 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 41,940 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 440 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 44 ( 0.00%) if self.is_const_fn_raw(def_id) { 2 ( 0.00%) match self.lookup_const_stability(def_id) { 4 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. . self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 396 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 115,856 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 3,099,899 ( 0.03%) E::intern_with(self, f) 121,896 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 533,227 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 599,610 ( 0.01%) match iter.size_hint() { . (0, Some(0)) => { 3 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 271 ( 0.00%) assert!(iter.next().is_none()); 91,052 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 1,662 ( 0.00%) assert!(iter.next().is_none()); 73,325 ( 0.00%) f(&[t0, t1]) . } 8,312 ( 0.00%) _ => f(&iter.collect::>()), . } 598,480 ( 0.01%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 23,503 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 56 ( 0.00%) f(&iter.cloned().collect::>()) 18,854 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 898,838 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 601,034 ( 0.01%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 807 ( 0.00%) let t0 = iter.next().unwrap()?; 18 ( 0.00%) assert!(iter.next().is_none()); 31,289 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 3,572 ( 0.00%) let t0 = iter.next().unwrap()?; 3,572 ( 0.00%) let t1 = iter.next().unwrap()?; 1,650 ( 0.00%) assert!(iter.next().is_none()); 34,868 ( 0.00%) f(&[t0, t1]) . } 6,503 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 1,011,197 ( 0.01%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 535,193 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 11 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = . |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 44,400 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 2,618,704 ( 0.02%) -------------------------------------------------------------------------------- -- 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,130,791 ( 0.05%) pub fn remove_kv_tracking( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 4,119,968 ( 0.04%) match self.force() { 7,197,680 ( 0.06%) Leaf(node) => node.remove_leaf_kv(handle_emptied_internal_root), . Internal(node) => node.remove_internal_kv(handle_emptied_internal_root), . } 6,160,783 ( 0.06%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { 7,209,944 ( 0.06%) fn remove_leaf_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 4,775,455 ( 0.04%) let (old_kv, mut pos) = self.remove(); . let len = pos.reborrow().into_node().len(); 2,059,984 ( 0.02%) 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,364,834 ( 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,425,572 ( 0.08%) (old_kv, pos) 8,239,936 ( 0.07%) } . } . . 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,476,540 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs -------------------------------------------------------------------------------- Ir -- line 504 ---------------------------------------- . use crate::panicking::{panic, panic_str}; . use crate::pin::Pin; . use crate::{ . convert, hint, mem, . ops::{self, ControlFlow, Deref, DerefMut}, . }; . . /// The `Option` type. See [the module level documentation](self) for more. 8,099,483 ( 0.07%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. . #[lang = "Some"] . #[stable(feature = "rust1", since = "1.0.0")] 183,686 ( 0.00%) Some(#[stable(feature = "rust1", since = "1.0.0")] T), . } . . ///////////////////////////////////////////////////////////////////////////// . // Type implementation . ///////////////////////////////////////////////////////////////////////////// . . impl Option { . ///////////////////////////////////////////////////////////////////////// -- line 531 ---------------------------------------- -- line 542 ---------------------------------------- . /// . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] 154,252 ( 0.00%) pub const fn is_some(&self) -> bool { 8,299,443 ( 0.07%) matches!(*self, Some(_)) 385,630 ( 0.00%) } . . /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] . /// -- line 560 ---------------------------------------- -- line 585 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_none(), true); . /// ``` . #[must_use = "if you intended to assert that this doesn't have a value, consider \ . `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] 68,522 ( 0.00%) pub const fn is_none(&self) -> bool { 102,783 ( 0.00%) !self.is_some() 137,044 ( 0.00%) } . . ///////////////////////////////////////////////////////////////////////// . // Adapter for working with references . ///////////////////////////////////////////////////////////////////////// . . /// Converts from `&Option` to `Option<&T>`. . /// . /// # Examples -- line 603 ---------------------------------------- -- line 615 ---------------------------------------- . /// // First, cast `Option` to `Option<&String>` with `as_ref`, . /// // then consume *that* with `map`, leaving `text` on the stack. . /// let text_length: Option = text.as_ref().map(|s| s.len()); . /// println!("still can print text: {:?}", text); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] 84,720 ( 0.00%) pub const fn as_ref(&self) -> Option<&T> { 26,368,418 ( 0.24%) match *self { 58,126 ( 0.00%) Some(ref x) => Some(x), 1,842 ( 0.00%) None => None, . } 84,720 ( 0.00%) } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples . /// . /// ``` . /// let mut x = Some(2); . /// match x.as_mut() { -- line 636 ---------------------------------------- -- line 637 ---------------------------------------- . /// Some(v) => *v = 42, . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 2,691 ( 0.00%) pub const fn as_mut(&mut self) -> Option<&mut T> { 16,102,826 ( 0.14%) match *self { 1,632 ( 0.00%) Some(ref mut x) => Some(x), 162 ( 0.00%) None => None, . } 2,691 ( 0.00%) } . . /// Converts from [Pin]<[&]Option\> to Option<[Pin]<[&]T>>. . /// . /// [&]: reference "shared reference" . #[inline] . #[must_use] . #[stable(feature = "pin", since = "1.33.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] -- line 658 ---------------------------------------- -- line 704 ---------------------------------------- . /// ```should_panic . /// let x: Option<&str> = None; . /// x.expect("fruits are healthy"); // panics with `fruits are healthy` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 585 ( 0.00%) pub const fn expect(self, msg: &str) -> T { 5,053,958 ( 0.05%) match self { 1,787,019 ( 0.02%) Some(val) => val, . None => expect_failed(msg), . } 130 ( 0.00%) } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] . /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or . /// [`unwrap_or_default`]. . /// -- line 725 ---------------------------------------- -- line 741 ---------------------------------------- . /// ```should_panic . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 145,070 ( 0.00%) pub const fn unwrap(self) -> T { 25,980,357 ( 0.23%) match self { 2,924,353 ( 0.03%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } 96,452 ( 0.00%) } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], . /// which is lazily evaluated. . /// . /// [`unwrap_or_else`]: Option::unwrap_or_else -- line 762 ---------------------------------------- -- line 765 ---------------------------------------- . /// . /// ``` . /// assert_eq!(Some("car").unwrap_or("bike"), "car"); . /// assert_eq!(None.unwrap_or("bike"), "bike"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 10,564 ( 0.00%) pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 2,907,695 ( 0.03%) match self { 7,662 ( 0.00%) Some(x) => x, 22,083 ( 0.00%) None => default, . } 21,872 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); . /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 4,977 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 2,672,522 ( 0.02%) match self { 233,796 ( 0.00%) Some(x) => x, 24,696 ( 0.00%) None => f(), . } 5,556 ( 0.00%) } . . /// Returns the contained [`Some`] value or a default. . /// . /// Consumes the `self` argument then, if [`Some`], returns the contained . /// value, otherwise if [`None`], returns the [default value] for that . /// type. . /// . /// # Examples -- line 812 ---------------------------------------- -- line 831 ---------------------------------------- . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_default(self) -> T . where . T: ~const Default, . { 45,096 ( 0.00%) match self { 15,210 ( 0.00%) Some(x) => x, . None => Default::default(), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety -- line 848 ---------------------------------------- -- line 892 ---------------------------------------- . /// // `Option::map` takes self *by value*, consuming `maybe_some_string` . /// let maybe_some_len = maybe_some_string.map(|s| s.len()); . /// . /// assert_eq!(maybe_some_len, Some(13)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 1,544,183 ( 0.01%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 15,061,336 ( 0.14%) match self { 11,168,658 ( 0.10%) Some(x) => Some(f(x)), 689,463 ( 0.01%) None => None, . } 3,585,775 ( 0.03%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 954 ---------------------------------------- . /// assert_eq!(x.map_or(42, |v| v.len()), 3); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.map_or(42, |v| v.len()), 42); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 14,212 ( 0.00%) pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 2,223,092 ( 0.02%) match self { 185,670 ( 0.00%) Some(t) => f(t), 8,781 ( 0.00%) None => default, . } 17,622 ( 0.00%) } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples . /// . /// ``` . /// let k = 21; -- line 980 ---------------------------------------- -- line 983 ---------------------------------------- . /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 385 ( 0.00%) pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 68,669 ( 0.00%) match self { 229 ( 0.00%) Some(t) => f(t), 212 ( 0.00%) None => default(), . } 440 ( 0.00%) } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// . /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`ok_or_else`], which is . /// lazily evaluated. . /// -- line 1010 ---------------------------------------- -- line 1020 ---------------------------------------- . /// assert_eq!(x.ok_or(0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or(0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 2,342,642 ( 0.02%) pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 6,290,848 ( 0.06%) match self { 2,046,399 ( 0.02%) Some(v) => Ok(v), 5,747 ( 0.00%) None => Err(err), . } 3,438,918 ( 0.03%) } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// . /// [`Ok(v)`]: Ok . /// [`Err(err())`]: Err . /// [`Some(v)`]: Some . /// -- line 1044 ---------------------------------------- -- line 1049 ---------------------------------------- . /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or_else(|| 0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 9,812 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 388,531 ( 0.00%) match self { 200,907 ( 0.00%) Some(v) => Ok(v), 86,744 ( 0.00%) None => Err(err()), . } 8,130 ( 0.00%) } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// . /// # Examples . /// -- line 1074 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 55,510 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1213 ---------------------------------------- . /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); . /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); . /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); . /// assert_eq!(None.and_then(sq).and_then(sq), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 12,564 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 534,878 ( 0.00%) match self { 105,883 ( 0.00%) Some(x) => f(x), . None => None, . } 80,171 ( 0.00%) } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped . /// value), and . /// - [`None`] if `predicate` returns `false`. . /// -- line 1238 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 31,294 ( 0.00%) if let Some(x) = self { 7,518 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 438 ( 0.00%) } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. . /// . /// [`or_else`]: Option::or_else -- line 1279 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 45,336 ( 0.00%) match self { 1,589 ( 0.00%) Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// . /// # Examples -- line 1316 ---------------------------------------- -- line 1321 ---------------------------------------- . /// . /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); . /// assert_eq!(None.or_else(vikings), Some("vikings")); . /// assert_eq!(None.or_else(nobody), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 274,668 ( 0.00%) pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 498,024 ( 0.00%) match self { 95,551 ( 0.00%) Some(x) => Some(x), 171,726 ( 0.00%) None => f(), . } 240,722 ( 0.00%) } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// . /// ``` . /// let x = Some(2); . /// let y: Option = None; -- line 1346 ---------------------------------------- -- line 1431 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert(&mut self, value: T) -> &mut T . where . T: ~const Drop, . { 94,800 ( 0.00%) if let None = *self { 221,190 ( 0.00%) *self = Some(value); . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . /// Inserts the default value into the option if it is [`None`], then -- line 1448 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 4,573,960 ( 0.04%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. 6 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1532 ---------------------------------------- . /// let mut x: Option = None; . /// let y = x.take(); . /// assert_eq!(x, None); . /// assert_eq!(y, None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] 3,081,048 ( 0.03%) pub const fn take(&mut self) -> Option { . // FIXME replace `mem::replace` by `mem::take` when the latter is const ready 3,289,421 ( 0.03%) mem::replace(self, None) 1,970,196 ( 0.02%) } . . /// Replaces the actual value in the option by the value given in parameter, . /// returning the old value if present, . /// leaving a [`Some`] in its place without deinitializing either one. . /// . /// # Examples . /// . /// ``` -- line 1551 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 16,752 ( 0.00%) mem::replace(self, Some(value)) . } . . /// Returns `true` if the option is a [`Some`] value containing the given value. . /// . /// # Examples . /// . /// ``` . /// #![feature(option_result_contains)] -- line 1574 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 157,858 ( 0.00%) match self { 1,228,212 ( 0.01%) Some(&v) => Some(v), 32,360 ( 0.00%) None => None, . } 3 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 72,932 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 418,236 ( 0.00%) match self { 1,190,577 ( 0.01%) Some(t) => Some(t.clone()), 50,941 ( 0.00%) None => None, . } 199,954 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1842 ---------------------------------------- . . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] 180,303 ( 0.00%) fn clone(&self) -> Self { 7,420,824 ( 0.07%) match self { 236,607 ( 0.00%) Some(x) => Some(x.clone()), 53,186 ( 0.00%) None => None, . } 2,338,164 ( 0.02%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 1870 ---------------------------------------- . /// . /// # Examples . /// . /// ``` . /// let opt: Option = Option::default(); . /// assert!(opt.is_none()); . /// ``` . #[inline] 20,495 ( 0.00%) fn default() -> Option { 20,495 ( 0.00%) None 61,485 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Option { . type Item = T; . type IntoIter = IntoIter; . . /// Returns a consuming iterator over the possibly contained value. -- line 1888 ---------------------------------------- -- line 1894 ---------------------------------------- . /// let v: Vec<&str> = x.into_iter().collect(); . /// assert_eq!(v, ["string"]); . /// . /// let x = None; . /// let v: Vec<&str> = x.into_iter().collect(); . /// assert!(v.is_empty()); . /// ``` . #[inline] 1,408,857 ( 0.01%) fn into_iter(self) -> IntoIter { 4,553,988 ( 0.04%) IntoIter { inner: Item { opt: self } } 1,013,092 ( 0.01%) } . } . . #[stable(since = "1.4.0", feature = "option_iter")] . impl<'a, T> IntoIterator for &'a Option { . type Item = &'a T; . type IntoIter = Iter<'a, T>; . . fn into_iter(self) -> Iter<'a, T> { -- line 1912 ---------------------------------------- -- line 2000 ---------------------------------------- . struct Item { . opt: Option, . } . . impl Iterator for Item { . type Item = A; . . #[inline] 3,077,176 ( 0.03%) fn next(&mut self) -> Option { 1,507,025 ( 0.01%) self.opt.take() 1,966,714 ( 0.02%) } . . #[inline] 6,444 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 103,289 ( 0.00%) match self.opt { 10,710 ( 0.00%) Some(_) => (1, Some(1)), 648 ( 0.00%) None => (0, Some(0)), . } 3,222 ( 0.00%) } . } . . impl DoubleEndedIterator for Item { . #[inline] . fn next_back(&mut self) -> Option { . self.opt.take() . } . } -- line 2026 ---------------------------------------- -- line 2131 ---------------------------------------- . inner: Item, . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = A; . . #[inline] 3,077,176 ( 0.03%) fn next(&mut self) -> Option { 1,507,025 ( 0.01%) self.inner.next() 1,966,714 ( 0.02%) } . #[inline] 6,444 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 1,628 ( 0.00%) self.inner.size_hint() 3,222 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . self.inner.next_back() . } -- line 2153 ---------------------------------------- -- line 2241 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Option { . type Output = T; . type Residual = Option; . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) 20,940 ( 0.00%) } . . #[inline] 1,028,146 ( 0.01%) fn branch(self) -> ControlFlow { 5,267,626 ( 0.05%) match self { 2,851,417 ( 0.03%) Some(v) => ControlFlow::Continue(v), 71,222 ( 0.00%) None => ControlFlow::Break(None), . } 1,218,526 ( 0.01%) } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] 45,470 ( 0.00%) fn from_residual(residual: Option) -> Self { . match residual { 210,879 ( 0.00%) None => None, . } 122,726 ( 0.00%) } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } . . impl Option> { -- line 2276 ---------------------------------------- -- line 2297 ---------------------------------------- . /// let x: Option>> = Some(Some(Some(6))); . /// assert_eq!(Some(Some(6)), x.flatten()); . /// assert_eq!(Some(6), x.flatten().flatten()); . /// ``` . #[inline] . #[stable(feature = "option_flattening", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn flatten(self) -> Option { 6 ( 0.00%) match self { 33 ( 0.00%) Some(inner) => inner, . None => None, . } . } . } 23,111,112 ( 0.21%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs -------------------------------------------------------------------------------- Ir -- line 481 ---------------------------------------- . . // As lifts over & . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const AsRef for &T . where . T: ~const AsRef, . { 279,336 ( 0.00%) fn as_ref(&self) -> &U { 502,752 ( 0.00%) >::as_ref(*self) 223,416 ( 0.00%) } . } . . // As lifts over &mut . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const AsRef for &mut T . where . T: ~const AsRef, . { . fn as_ref(&self) -> &U { 575,099 ( 0.01%) >::as_ref(*self) . } . } . . // FIXME (#45742): replace the above impls for &/&mut with the following more general one: . // // As lifts over Deref . // impl>, U: ?Sized> AsRef for D { . // fn as_ref(&self) -> &U { . // self.deref().as_ref() -- line 510 ---------------------------------------- -- line 514 ---------------------------------------- . // AsMut lifts over &mut . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const AsMut for &mut T . where . T: ~const AsMut, . { . fn as_mut(&mut self) -> &mut U { 137,435 ( 0.00%) (*self).as_mut() . } . } . . // FIXME (#45742): replace the above impl for &mut with the following more general one: . // // AsMut lifts over DerefMut . // impl>, U: ?Sized> AsMut for D { . // fn as_mut(&mut self) -> &mut U { . // self.deref_mut().as_mut() -- line 530 ---------------------------------------- -- line 533 ---------------------------------------- . . // From implies Into . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const Into for T . where . U: ~const From, . { 5,280,647 ( 0.05%) fn into(self) -> U { 12,288,333 ( 0.11%) U::from(self) 3,565,808 ( 0.03%) } . } . . // From (and thus Into) is reflexive . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From for T { 24,019 ( 0.00%) fn from(t: T) -> T { 52,898 ( 0.00%) t 18,318 ( 0.00%) } . } . . /// **Stability note:** This impl does not yet exist, but we are . /// "reserving space" to add it in the future. See . /// [rust-lang/rust#64715][#64715] for details. . /// . /// [#64715]: https://github.com/rust-lang/rust/issues/64715 . #[stable(feature = "convert_infallible", since = "1.34.0")] -- line 560 ---------------------------------------- -- line 613 ---------------------------------------- . fn as_mut(&mut self) -> &mut [T] { . self . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl AsRef for str { . #[inline] 278,940 ( 0.00%) fn as_ref(&self) -> &str { . self 111,576 ( 0.00%) } . } . . #[stable(feature = "as_mut_str_for_str", since = "1.51.0")] . impl AsMut for str { . #[inline] . fn as_mut(&mut self) -> &mut str { . self . } -- line 631 ---------------------------------------- 1,163,307 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use std::cmp::Ordering; . use std::marker::PhantomData; . use std::ops::Range; . use ty::util::IntTypeExt; . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 1,620 ( 0.00%) pub ty: Ty<'tcx>, 8,100 ( 0.00%) pub mutbl: hir::Mutability, . } . . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . /// A "free" region `fr` can be interpreted as "some region . /// at least as big as the scope `fr.scope`". . pub struct FreeRegion { 86,052 ( 0.00%) pub scope: DefId, 159,298 ( 0.00%) pub bound_region: BoundRegionKind, . } . 660,944 ( 0.01%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 15,700 ( 0.00%) BrAnon(u32), . . /// Named region parameters for functions (a in &'a T) . /// . /// The `DefId` is needed to distinguish free regions in . /// the event of shadowing. 217 ( 0.00%) BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 1,586 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 112,764 ( 0.00%) pub var: BoundVar, 92,992 ( 0.00%) pub kind: BoundRegionKind, . } . . impl BoundRegionKind { . pub fn is_named(&self) -> bool { . match *self { . BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime, . _ => false, . } . } . } . . /// Defines the kinds of types. . /// . /// N.B., if you change this, you'll probably want to change the corresponding . /// AST structure in `rustc_ast/src/ast.rs` as well. 16,822,750 ( 0.15%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] . #[derive(HashStable)] . #[rustc_diagnostic_item = "TyKind"] . pub enum TyKind<'tcx> { . /// The primitive boolean type. Written as `bool`. . Bool, . . /// The primitive character type; holds a Unicode scalar value . /// (a non-surrogate code point). Written as `char`. -- line 89 ---------------------------------------- -- line 99 ---------------------------------------- . Float(ty::FloatTy), . . /// Algebraic data types (ADT). For example: structures, enumerations and unions. . /// . /// InternalSubsts here, possibly against intuition, *may* contain `Param`s. . /// That is, even after substitution it is possible that there are type . /// variables. This happens when the `Adt` corresponds to an ADT . /// definition and not a concrete use of it. 860,214 ( 0.01%) Adt(&'tcx AdtDef, SubstsRef<'tcx>), . . /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. . Foreign(DefId), . . /// The pointee of a string slice. Written as `str`. . Str, . . /// An array with the given length. Written as `[T; n]`. 258 ( 0.00%) Array(Ty<'tcx>, &'tcx ty::Const<'tcx>), . . /// The pointee of an array slice. Written as `[T]`. . Slice(Ty<'tcx>), . . /// A raw pointer. Written as `*mut T` or `*const T` . RawPtr(TypeAndMut<'tcx>), . . /// A reference; a pointer with an associated lifetime. Written as . /// `&'a mut T` or `&'a T`. 3,072,886 ( 0.03%) Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), . . /// The anonymous type of a function declaration/definition. Each . /// function has a unique type, which is output (for a function . /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. . /// . /// For example the type of `bar` here: . /// . /// ```rust -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . /// . /// ```rust . /// fn foo() -> i32 { 1 } . /// let bar: fn() -> i32 = foo; . /// ``` . FnPtr(PolyFnSig<'tcx>), . . /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. 94,316 ( 0.00%) Dynamic(&'tcx List>>, ty::Region<'tcx>), . . /// The anonymous type of a closure. Used to represent the type of . /// `|a| a`. . Closure(DefId, SubstsRef<'tcx>), . . /// The anonymous type of a generator. Used to represent the type of . /// `|a| yield a`. . Generator(DefId, SubstsRef<'tcx>, hir::Movability), -- line 159 ---------------------------------------- -- line 180 ---------------------------------------- . /// The substitutions are for the generics of the function in question. . /// After typeck, the concrete type can be found in the `types` map. . Opaque(DefId, SubstsRef<'tcx>), . . /// A type parameter; for example, `T` in `fn f(x: T) {}`. . Param(ParamTy), . . /// Bound type variable, used only when preparing a trait query. 5,898 ( 0.00%) Bound(ty::DebruijnIndex, BoundTy), . . /// A placeholder type - universally quantified higher-ranked type. . Placeholder(ty::PlaceholderType), . . /// A type variable used during type checking. . Infer(InferTy), . . /// A placeholder for a type which could not be computed; this is -- line 196 ---------------------------------------- -- line 330 ---------------------------------------- . pub closure_kind_ty: T, . pub closure_sig_as_fn_ptr_ty: T, . pub tupled_upvars_ty: T, . } . . impl<'tcx> ClosureSubsts<'tcx> { . /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` . /// for the closure parent, alongside additional closure-specific components. 17 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 34 ( 0.00%) parts.parent_substs.iter().copied().chain( 68 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 34 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 194 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 1,596 ( 0.00%) [ 400 ( 0.00%) ref parent_substs @ .., 458 ( 0.00%) closure_kind_ty, 237 ( 0.00%) closure_sig_as_fn_ptr_ty, 297 ( 0.00%) tupled_upvars_ty, 776 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 582 ( 0.00%) } . . /// Returns `true` only if enough of the synthetic types are known to . /// allow using all of the methods on `ClosureSubsts` without panicking. . /// . /// Used primarily by `ty::print::pretty` to be able to handle closure . /// types that haven't had their synthetic types substituted in. . pub fn is_valid(self) -> bool { . self.substs.len() >= 3 -- line 378 ---------------------------------------- -- line 383 ---------------------------------------- . pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { . self.split().parent_substs . } . . /// Returns an iterator over the list of types of captured paths by the closure. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] 6 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 57 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 38 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() 4 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 877 ( 0.00%) self.split().tupled_upvars_ty.expect_ty() . } . . /// Returns the closure kind for this closure; may return a type . /// variable during inference. To get the closure kind during . /// inference, use `infcx.closure_kind(substs)`. 126 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 252 ( 0.00%) } . . /// Returns the `fn` pointer type representing the closure signature for this . /// closure. . // FIXME(eddyb) this should be unnecessary, as the shallowly resolved . // type is known at the time of the creation of `ClosureSubsts`, . // see `rustc_typeck::check::closure`. 1 ( 0.00%) pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { . self.split().closure_sig_as_fn_ptr_ty.expect_ty() 2 ( 0.00%) } . . /// Returns the closure kind for this closure; only usable outside . /// of an inference context, because in that context we know that . /// there are no type variables. . /// . /// If you have an inference context, use `infcx.closure_kind()`. 1 ( 0.00%) pub fn kind(self) -> ty::ClosureKind { 1 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 2 ( 0.00%) } . . /// Extracts the signature from the closure. 133 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 266 ( 0.00%) match ty.kind() { 532 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 399 ( 0.00%) } . } . . /// Similar to `ClosureSubsts`; see the above documentation for more. . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GeneratorSubsts<'tcx> { . pub substs: SubstsRef<'tcx>, . } . -- line 448 ---------------------------------------- -- line 676 ---------------------------------------- . } . . impl<'tcx> UpvarSubsts<'tcx> { . /// Returns an iterator over the list of types of captured paths by the closure/generator. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] . pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 36 ( 0.00%) let tupled_tys = match self { 53 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 88 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 71 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() . } . . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 70 ( 0.00%) match self { 71 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . } . } . } . . /// An inline const is modeled like . /// . /// const InlineConst<'l0...'li, T0...Tj, R>: R; -- line 710 ---------------------------------------- -- line 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 253,052 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] 180,826 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub enum ExistentialPredicate<'tcx> { . /// E.g., `Iterator`. . Trait(ExistentialTraitRef<'tcx>), . /// E.g., `Iterator::Item = T`. . Projection(ExistentialProjection<'tcx>), . /// E.g., `Send`. 18 ( 0.00%) AutoTrait(DefId), . } . . impl<'tcx> ExistentialPredicate<'tcx> { . /// Compares via an ordering that will not change if modules are reordered or other changes are . /// made to the tree. In particular, this ordering is preserved across incremental compilations. 37,690 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 40,760 ( 0.00%) match (*self, *other) { . (Trait(_), Trait(_)) => Ordering::Equal, . (Projection(ref a), Projection(ref b)) => { . tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) . } . (AutoTrait(ref a), AutoTrait(ref b)) => { . tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b)) . } . (Trait(_), _) => Ordering::Less, . (Projection(_), Trait(_)) => Ordering::Greater, . (Projection(_), _) => Ordering::Less, . (AutoTrait(_), _) => Ordering::Greater, . } 45,228 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { 4,266 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; 2,370 ( 0.00%) match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) . } . ExistentialPredicate::Projection(p) => { . self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) . } . ExistentialPredicate::AutoTrait(did) => { . let trait_ref = self.rebind(ty::TraitRef { . def_id: did, . substs: tcx.mk_substs_trait(self_ty, &[]), . }); . trait_ref.without_const().to_predicate(tcx) . } . } 3,792 ( 0.00%) } . } . . impl<'tcx> List>> { . /// Returns the "principal `DefId`" of this set of existential predicates. . /// . /// A Rust trait object type consists (in addition to a lifetime bound) . /// of a set of trait bounds, which are separated into any number . /// of auto-trait bounds, and at most one non-auto-trait bound. The -- line 826 ---------------------------------------- -- line 839 ---------------------------------------- . /// are the set `{Sync}`. . /// . /// It is also possible to have a "trivial" trait object that . /// consists only of auto traits, with no principal - for example, . /// `dyn Send + Sync`. In that case, the set of auto-trait bounds . /// is `{Send, Sync}`, while there is no principal. These trait objects . /// have a "trivial" vtable consisting of just the size, alignment, . /// and destructor. 66 ( 0.00%) pub fn principal(&self) -> Option>> { 2,430 ( 0.00%) self[0] 2,232 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, 264 ( 0.00%) }) . .transpose() 198 ( 0.00%) } . 320 ( 0.00%) pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) 640 ( 0.00%) } . . #[inline] . pub fn projection_bounds<'a>( . &'a self, . ) -> impl Iterator>> + 'a { . self.iter().filter_map(|predicate| { . predicate 264 ( 0.00%) .map_bound(|pred| match pred { 88 ( 0.00%) ExistentialPredicate::Projection(projection) => Some(projection), . _ => None, . }) . .transpose() . }) . } . . #[inline] . pub fn auto_traits<'a>(&'a self) -> impl Iterator + 'a { -- line 875 ---------------------------------------- -- line 886 ---------------------------------------- . /// T: Foo . /// . /// This would be represented by a trait-reference where the `DefId` is the . /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, . /// and `U` as parameter 1. . /// . /// Trait references also appear in object types like `Foo`, but in . /// that case the `Self` parameter is absent from the substitutions. 35,358 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 1,507,693 ( 0.01%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 64 ( 0.00%) pub def_id: DefId, 1,062,683 ( 0.01%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 9,108 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 36,432 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 4,941 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 2,196 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 3,294 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 4,392 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 3,392 ( 0.00%) pub fn from_method( . tcx: TyCtxt<'tcx>, . trait_id: DefId, . substs: SubstsRef<'tcx>, . ) -> ty::TraitRef<'tcx> { . let defs = tcx.generics_of(trait_id); . 424 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 4,664 ( 0.00%) } . } . . pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>; . . impl<'tcx> PolyTraitRef<'tcx> { . pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> { . self.map_bound_ref(|tr| tr.self_ty()) . } . . pub fn def_id(&self) -> DefId { 18,858 ( 0.00%) self.skip_binder().def_id 6,286 ( 0.00%) } . 17,614 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 35,228 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 17,614 ( 0.00%) } . } . . /// An existential reference to a trait, where `Self` is erased. . /// For example, the trait object `Trait<'a, 'b, X, Y>` is: . /// . /// exists T. T: Trait<'a, 'b, X, Y> . /// . /// The substitutions don't include the erased `Self`, only trait . /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). 404 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 47,467 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 9,996 ( 0.00%) pub def_id: DefId, 65,460 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { 976 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. . trait_ref.substs.type_at(0); . . ty::ExistentialTraitRef { . def_id: trait_ref.def_id, . substs: tcx.intern_substs(&trait_ref.substs[1..]), . } 976 ( 0.00%) } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. . pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> { . // otherwise the escaping vars would be captured by the binder . // debug_assert!(!self_ty.has_escaping_bound_vars()); -- line 985 ---------------------------------------- -- line 994 ---------------------------------------- . pub fn def_id(&self) -> DefId { . self.skip_binder().def_id . } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. 66 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> { 66 ( 0.00%) self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) 88 ( 0.00%) } . } . 92,824 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundVariableKind { . Ty(BoundTyKind), . Region(BoundRegionKind), . Const, . } . . /// Binder is a binder for higher-ranked lifetimes or types. It is part of the -- line 1015 ---------------------------------------- -- line 1016 ---------------------------------------- . /// compiler's representation for things like `for<'a> Fn(&'a isize)` . /// (which would be represented by the type `PolyTraitRef == . /// Binder<'tcx, TraitRef>`). Note that when we instantiate, . /// erase, or otherwise "discharge" these bound vars, we change the . /// type from `Binder<'tcx, T>` to just `T` (see . /// e.g., `liberate_late_bound_regions`). . /// . /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. 214,512 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 617,901 ( 0.01%) pub struct Binder<'tcx, T>(T, &'tcx List); . . impl<'tcx, T> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . /// Wraps `value` in a binder, asserting that `value` does not . /// contain any bound vars that would be bound by the . /// binder. This is commonly used to 'inject' a value T into a . /// different binding level. 42,465 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 275,274 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 744,922 ( 0.01%) Binder(value, ty::List::empty()) 42,269 ( 0.00%) } . . pub fn bind_with_vars(value: T, vars: &'tcx List) -> Binder<'tcx, T> { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(vars); . value.visit_with(&mut validator); . } 44,602 ( 0.00%) Binder(value, vars) . } . } . . impl<'tcx, T> Binder<'tcx, T> { . /// Skips the binder and returns the "bound" value. This is a . /// risky thing to do because it's easy to get confused about . /// De Bruijn indices and the like. It is usually better to . /// discharge the binder using `no_bound_vars` or -- line 1053 ---------------------------------------- -- line 1059 ---------------------------------------- . /// accounting. . /// . /// Some examples where `skip_binder` is reasonable: . /// . /// - extracting the `DefId` from a PolyTraitRef; . /// - comparing the self type of a PolyTraitRef to see if it is equal to . /// a type parameter `X`, since the type `X` does not reference any regions . pub fn skip_binder(self) -> T { 1,985,619 ( 0.02%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 5,034 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 3,363 ( 0.00%) Binder(&self.0, self.1) . } . . pub fn map_bound_ref_unchecked(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . let value = f(&self.0); . Binder(value, self.1) -- line 1083 ---------------------------------------- -- line 1085 ---------------------------------------- . . pub fn map_bound_ref>(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . self.as_ref().map_bound(f) . } . 4,770 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 27,363 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 593,689 ( 0.01%) Binder(value, self.1) 4,286 ( 0.00%) } . . pub fn try_map_bound, E>(self, f: F) -> Result, E> . where . F: FnOnce(T) -> Result, . { . let value = f(self.0)?; . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 4,630 ( 0.00%) Ok(Binder(value, self.1)) . } . . /// Wraps a `value` in a binder, using the same bound variables as the . /// current `Binder`. This should not be used if the new value *changes* . /// the bound variables. Note: the (old or new) value itself does not . /// necessarily need to *name* all the bound variables. . /// . /// This currently doesn't do anything different than `bind`, because we -- line 1122 ---------------------------------------- -- line 1126 ---------------------------------------- . pub fn rebind(&self, value: U) -> Binder<'tcx, U> . where . U: TypeFoldable<'tcx>, . { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.bound_vars()); . value.visit_with(&mut validator); . } 25,779 ( 0.00%) Binder(value, self.1) . } . . /// Unwraps and returns the value within, but only if it contains . /// no bound vars at all. (In other words, if this binder -- . /// and indeed any enclosing binder -- doesn't bind anything at . /// all.) Otherwise, returns `None`. . /// . /// (One could imagine having a method that just unwraps a single -- line 1142 ---------------------------------------- -- line 1143 ---------------------------------------- . /// binder, but permits late-bound vars bound by enclosing . /// binders, but that would require adjusting the debruijn . /// indices, and given the shallow binding structure we often use, . /// would not be that useful.) . pub fn no_bound_vars(self) -> Option . where . T: TypeFoldable<'tcx>, . { 281,904 ( 0.00%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 75 ( 0.00%) } . . /// Splits the contents into two things that share the same binder . /// level as the original, returning two distinct binders. . /// . /// `f` should consider bound regions at depth 1 to be free, and . /// anything it produces with bound regions at depth 1 will be . /// bound in the resulting return values. . pub fn split(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>) -- line 1160 ---------------------------------------- -- line 1170 ---------------------------------------- . pub fn transpose(self) -> Option> { . let bound_vars = self.1; . self.0.map(|v| Binder(v, bound_vars)) . } . } . . /// Represents the projection of an associated type. In explicit UFCS . /// form this would be written `>::N`. 7,482 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 98,883 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 162,701 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The `DefId` of the `TraitItem` for the associated type `N`. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(item_def_id).container`. 119,129 ( 0.00%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 120,666 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 34,476 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 137,904 ( 0.00%) } . . /// Extracts the underlying trait reference and own substs from this projection. . /// For example, if this is a projection of `::Item<'a>`, . /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs 80,227 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 34,383 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 57,305 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 103,149 ( 0.00%) } . . /// Extracts the underlying trait reference from this projection. . /// For example, if this is a projection of `::Item`, . /// then this function would return a `T: Iterator` trait reference. . /// . /// WARNING: This will drop the substs for generic associated types . /// consider calling [Self::trait_ref_and_own_substs] to get those . /// as well. 155,016 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 17,224 ( 0.00%) let def_id = self.trait_def_id(tcx); 17,224 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 189,464 ( 0.00%) } . 34,658 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 103,974 ( 0.00%) self.substs.type_at(0) 69,316 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GenSig<'tcx> { . pub resume_ty: Ty<'tcx>, . pub yield_ty: Ty<'tcx>, . pub return_ty: Ty<'tcx>, . } -- line 1233 ---------------------------------------- -- line 1235 ---------------------------------------- . pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>; . . /// Signature of a function type, which we have arbitrarily . /// decided to use to refer to the input/output types. . /// . /// - `inputs`: is the list of arguments and their modes. . /// - `output`: is the return type. . /// - `c_variadic`: indicates whether this is a C-variadic function. 166,628 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 69,430 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 4,581 ( 0.00%) pub inputs_and_output: &'tcx List>, 53,564 ( 0.00%) pub c_variadic: bool, 12,155 ( 0.00%) pub unsafety: hir::Unsafety, 38,432 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 87,270 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 357,618 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 174,540 ( 0.00%) } . 55,738 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 397,576 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 111,476 ( 0.00%) } . . // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible . // method. . fn fake() -> FnSig<'tcx> { . FnSig { . inputs_and_output: List::empty(), . c_variadic: false, . unsafety: hir::Unsafety::Normal, -- line 1267 ---------------------------------------- -- line 1270 ---------------------------------------- . } . } . . pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; . . impl<'tcx> PolyFnSig<'tcx> { . #[inline] . pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> { 21,787 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 51,217 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.inputs()[index]) . } . pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List>> { . self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output) 2,936 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 38,590 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 5,872 ( 0.00%) self.skip_binder().c_variadic 2,936 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 16,028 ( 0.00%) self.skip_binder().unsafety 8,014 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 48,800 ( 0.00%) self.skip_binder().abi 12,200 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 16 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct ParamTy { 40 ( 0.00%) pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 24 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 12 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { 4 ( 0.00%) ParamTy::new(def.index, def.name) 2 ( 0.00%) } . . #[inline] . pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { . tcx.mk_ty_param(self.index, self.name) . } . } . . #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] . #[derive(HashStable)] . pub struct ParamConst { 164 ( 0.00%) pub index: u32, 164 ( 0.00%) pub name: Symbol, . } . . impl ParamConst { . pub fn new(index: u32, name: Symbol) -> ParamConst { . ParamConst { index, name } . } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamConst { -- line 1338 ---------------------------------------- -- line 1440 ---------------------------------------- . /// the inference variable is supposed to satisfy the relation . /// *for every value of the placeholder region*. To ensure that doesn't . /// happen, you can use `leak_check`. This is more clearly explained . /// by the [rustc dev guide]. . /// . /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ . /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 8,800,976 ( 0.08%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 60 ( 0.00%) pub enum RegionKind { . /// Region bound in a type or fn declaration which will be . /// substituted 'early' -- that is, at the same time when type . /// parameters are substituted. . ReEarlyBound(EarlyBoundRegion), . . /// Region bound in a function scope, which will be substituted when the . /// function is called. 185,984 ( 0.00%) ReLateBound(ty::DebruijnIndex, BoundRegion), . . /// When checking a function body, the types of all arguments and so forth . /// that refer to bound region parameters are modified to refer to free . /// region parameters. . ReFree(FreeRegion), . . /// Static data that has an "infinite" lifetime. Top in the region lattice. . ReStatic, -- line 1465 ---------------------------------------- -- line 1478 ---------------------------------------- . /// regions visible from `U`, but not less than regions not visible . /// from `U`. . ReEmpty(ty::UniverseIndex), . . /// Erased region, used by trait selection, in MIR and during codegen. . ReErased, . } . 41,432 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { 210,371 ( 0.00%) pub def_id: DefId, 235,696 ( 0.00%) pub index: u32, 63,797 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 5,081 ( 0.00%) pub index: u32, 553 ( 0.00%) pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } . } -- line 1505 ---------------------------------------- -- line 1513 ---------------------------------------- . rustc_index::newtype_index! { . pub struct BoundVar { .. } . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct BoundTy { . pub var: BoundVar, 5,898 ( 0.00%) pub kind: BoundTyKind, . } . 100,287 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundTyKind { . Anon, . Param(Symbol), . } . . impl From for BoundTy { . fn from(var: BoundVar) -> Self { . BoundTy { var, kind: BoundTyKind::Anon } . } . } . . /// A `ProjectionPredicate` for an `ExistentialTraitRef`. 286 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 45,358 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialProjection<'tcx> { 9,418 ( 0.00%) pub item_def_id: DefId, 47,020 ( 0.00%) pub substs: SubstsRef<'tcx>, 11,755 ( 0.00%) pub term: Term<'tcx>, . } . . pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>; . . impl<'tcx> ExistentialProjection<'tcx> { . /// Extracts the underlying existential trait reference from this projection. . /// For example, if this is a projection of `exists T. ::Item == X`, . /// then this function would return an `exists T. T: Iterator` existential trait . /// reference. 3,927 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> { 1,683 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); 1,122 ( 0.00%) let subst_count = tcx.generics_of(def_id).count() - 1; 561 ( 0.00%) let substs = tcx.intern_substs(&self.substs[..subst_count]); . ty::ExistentialTraitRef { def_id, substs } 5,049 ( 0.00%) } . . pub fn with_self_ty( . &self, . tcx: TyCtxt<'tcx>, . self_ty: Ty<'tcx>, . ) -> ty::ProjectionPredicate<'tcx> { . // otherwise the escaping regions would be captured by the binders . debug_assert!(!self_ty.has_escaping_bound_vars()); -- line 1566 ---------------------------------------- -- line 1569 ---------------------------------------- . projection_ty: ty::ProjectionTy { . item_def_id: self.item_def_id, . substs: tcx.mk_substs_trait(self_ty, self.substs), . }, . term: self.term, . } . } . 1,210 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . projection_predicate: ty::ProjectionPredicate<'tcx>, . ) -> Self { . // Assert there is a Self. 726 ( 0.00%) projection_predicate.projection_ty.substs.type_at(0); . 968 ( 0.00%) Self { 484 ( 0.00%) item_def_id: projection_predicate.projection_ty.item_def_id, . substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]), 242 ( 0.00%) term: projection_predicate.term, . } 1,694 ( 0.00%) } . } . . impl<'tcx> PolyExistentialProjection<'tcx> { . pub fn with_self_ty( . &self, . tcx: TyCtxt<'tcx>, . self_ty: Ty<'tcx>, . ) -> ty::PolyProjectionPredicate<'tcx> { -- line 1597 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 3,116 ( 0.00%) matches!(*self, ty::ReLateBound(..)) . } . . #[inline] . pub fn is_placeholder(&self) -> bool { 2 ( 0.00%) matches!(*self, ty::RePlaceholder(..)) . } . . #[inline] . pub fn bound_at_or_above_binder(&self, index: ty::DebruijnIndex) -> bool { 150,227 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 104,029 ( 0.00%) match *self { . ty::ReVar(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; . flags = flags | TypeFlags::HAS_RE_INFER; . } . ty::RePlaceholder(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; -- line 1651 ---------------------------------------- -- line 1669 ---------------------------------------- . ty::ReErased => { . flags = flags | TypeFlags::HAS_RE_ERASED; . } . } . . debug!("type_flags({:?}) = {:?}", self, flags); . . flags 4,589 ( 0.00%) } . . /// Given an early-bound or free region, returns the `DefId` where it was bound. . /// For example, consider the regions in this snippet of code: . /// . /// ``` . /// impl<'a> Foo { . /// ^^ -- early bound, declared on an impl . /// -- line 1685 ---------------------------------------- -- line 1713 ---------------------------------------- . . #[inline(always)] . pub fn flags(&self) -> TypeFlags { . self.flags . } . . #[inline] . pub fn is_unit(&self) -> bool { 16,940 ( 0.00%) match self.kind() { 4,258 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 116,753 ( 0.00%) matches!(self.kind(), Never) . } . . #[inline] . pub fn is_primitive(&self) -> bool { . self.kind().is_primitive() . } . . #[inline] -- line 1737 ---------------------------------------- -- line 1741 ---------------------------------------- . . #[inline] . pub fn is_ref(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_ty_var(&self) -> bool { 127,801 ( 0.00%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 119,746 ( 0.00%) match self.kind() { 16,390 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 51 ( 0.00%) matches!(self.kind(), Infer(_)) . } . . #[inline] . pub fn is_phantom_data(&self) -> bool { . if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false } . } . . #[inline] -- line 1770 ---------------------------------------- -- line 1775 ---------------------------------------- . /// Returns `true` if this type is a `str`. . #[inline] . pub fn is_str(&self) -> bool { . *self.kind() == Str . } . . #[inline] . pub fn is_param(&self, index: u32) -> bool { 24 ( 0.00%) match self.kind() { . ty::Param(ref data) => data.index == index, . _ => false, . } . } . . #[inline] . pub fn is_slice(&self) -> bool { . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 1,080 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { . match self.kind() { . Adt(def, _) => def.repr.simd(), . _ => false, . } -- line 1807 ---------------------------------------- -- line 1838 ---------------------------------------- . } . } . _ => bug!("`simd_size_and_type` called on invalid type"), . } . } . . #[inline] . pub fn is_region_ptr(&self) -> bool { 170 ( 0.00%) matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_mutable_ptr(&self) -> bool { . matches!( . self.kind(), . RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) . | Ref(_, _, hir::Mutability::Mut) -- line 1854 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 3,605 ( 0.00%) matches!(self.kind(), RawPtr(_)) . } . . /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer). . #[inline] . pub fn is_any_ptr(&self) -> bool { . self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr() . } . . #[inline] . pub fn is_box(&self) -> bool { 95,194 ( 0.00%) match self.kind() { 13,873 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. . pub fn boxed_ty(&self) -> Ty<'tcx> { . match self.kind() { . Adt(def, substs) if def.is_box() => substs.type_at(0), -- line 1889 ---------------------------------------- -- line 1891 ---------------------------------------- . } . } . . /// A scalar type is one that denotes an atomic datum, with no sub-components. . /// (A RawPtr is scalar because it represents a non-managed pointer, so its . /// contents are abstract to rustc.) . #[inline] . pub fn is_scalar(&self) -> bool { 805 ( 0.00%) matches!( 1,982 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) . ) . } . . /// Returns `true` if this type is a floating point type. . #[inline] . pub fn is_floating_point(&self) -> bool { 56 ( 0.00%) matches!(self.kind(), Float(_) | Infer(FloatVar(_))) . } . . #[inline] . pub fn is_trait(&self) -> bool { . matches!(self.kind(), Dynamic(..)) . } . . #[inline] . pub fn is_enum(&self) -> bool { . matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum()) . } . . #[inline] . pub fn is_union(&self) -> bool { 3,767 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { 1,232 ( 0.00%) matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 1,853 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 2,494 ( 0.00%) matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_)) . } . . #[inline] . pub fn is_fresh_ty(&self) -> bool { . matches!(self.kind(), Infer(FreshTy(_))) . } . . #[inline] . pub fn is_fresh(&self) -> bool { 3,151 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] . pub fn is_numeric(&self) -> bool { . self.is_integral() || self.is_floating_point() . } . . #[inline] . pub fn is_signed(&self) -> bool { 11 ( 0.00%) matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { 19,932 ( 0.00%) matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] . pub fn has_concrete_skeleton(&self) -> bool { . !matches!(self.kind(), Param(_) | Infer(_) | Error(_)) . } . . /// Returns the type and mutability of `*ty`. . /// . /// The parameter `explicit` indicates if this is an *explicit* dereference. . /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. 12,961 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 68,567 ( 0.00%) match self.kind() { 1,236 ( 0.00%) Adt(def, _) if def.is_box() => { . Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 41,298 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), 1,100 ( 0.00%) RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 25,922 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { . match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } . } . 188,272 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 94,136 ( 0.00%) match self.kind() { 70,548 ( 0.00%) FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), 90 ( 0.00%) FnPtr(f) => *f, . Error(_) => { . // ignore errors (#54954) . ty::Binder::dummy(FnSig::fake()) . } . Closure(..) => bug!( . "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", . ), . _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), . } 211,806 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 24 ( 0.00%) matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { . matches!(self.kind(), FnPtr(_)) . } . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 14,525 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 38 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 6,488 ( 0.00%) match self.kind() { 3,249 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 76 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 3 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 6 ( 0.00%) match self.kind() { 6 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 6 ( 0.00%) } . . /// If the type contains variants, returns the valid range of variant indices. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] . pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option> { . match self.kind() { . TyKind::Adt(adt, _) => Some(adt.variant_range()), -- line 2068 ---------------------------------------- -- line 2073 ---------------------------------------- . } . } . . /// If the type contains variants, returns the variant for `variant_index`. . /// Panics if `variant_index` is out of range. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] 20 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 10 ( 0.00%) match self.kind() { 4 ( 0.00%) TyKind::Adt(adt, _) if adt.variants.is_empty() => { . // This can actually happen during CTFE, see . // https://github.com/rust-lang/rust/issues/89765. . None . } 2 ( 0.00%) TyKind::Adt(adt, _) if adt.is_enum() => { . Some(adt.discriminant_for_variant(tcx, variant_index)) . } . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } 16 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 1,940 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 970 ( 0.00%) match self.kind() { 1,552 ( 0.00%) ty::Adt(adt, _) if adt.is_enum() => adt.repr.discr_type().to_ty(tcx), . ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), . . ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => { . let assoc_items = tcx.associated_item_def_ids( . tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), . ); . tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()])) . } -- line 2113 ---------------------------------------- -- line 2135 ---------------------------------------- . | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, . . ty::Bound(..) . | ty::Placeholder(_) . | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`discriminant_ty` applied to unexpected type: {:?}", self) . } . } 1,552 ( 0.00%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. . pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { . let tail = tcx.struct_tail_with_normalize(self, normalize); -- line 2151 ---------------------------------------- -- line 2200 ---------------------------------------- . /// function converts such a special type into the closure . /// kind. To go the other way, use . /// `tcx.closure_kind_ty(closure_kind)`. . /// . /// Note that during type checking, we use an inference variable . /// to represent the closure kind, because it has not yet been . /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`) . /// is complete, that type variable will be unified. 322 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 644 ( 0.00%) match self.kind() { 644 ( 0.00%) Int(int_ty) => match int_ty { . ty::IntTy::I8 => Some(ty::ClosureKind::Fn), . ty::IntTy::I16 => Some(ty::ClosureKind::FnMut), . ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce), . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . }, . . // "Bound" types appear in canonical queries when the . // closure type is not yet known . Bound(..) | Infer(_) => None, . . Error(_) => Some(ty::ClosureKind::Fn), . . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . } 322 ( 0.00%) } . . /// Fast path helper for testing if a type is `Sized`. . /// . /// Returning true means the type is known to be sized. Returning . /// `false` means nothing -- could be sized, might not be. . /// . /// Note that we could never rely on the fact that a type such as `[_]` is . /// trivially `!Sized` because we could be in a type environment with a . /// bound such as `[_]: Copy`. A function with such a bound obviously never . /// can be called, but that doesn't mean it shouldn't typecheck. This is why . /// this method doesn't return `Option`. 276,633 ( 0.00%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 184,422 ( 0.00%) match self.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 2246 ---------------------------------------- -- line 2250 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => true, . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false, . 3,731 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 13,755 ( 0.00%) ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(), . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false, . . ty::Infer(ty::TyVar(_)) => false, . . ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`is_trivially_sized` applied to unexpected type: {:?}", self) . } . } 276,633 ( 0.00%) } . } . . /// Extra information about why we ended up with a particular variance. . /// This is only used to add more information to error messages, and . /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo` . /// may lead to confusing notes in error messages, it will never cause . /// a miscompilation or unsoundness. . /// -- line 2280 ---------------------------------------- -- line 2295 ---------------------------------------- . /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`) . param_index: u32, . }, . } . . impl<'tcx> VarianceDiagInfo<'tcx> { . /// Mirrors `Variance::xform` - used to 'combine' the existing . /// and new `VarianceDiagInfo`s when our variance changes. 51,414 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 77,121 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 25,707 ( 0.00%) } . } 27,574,932 ( 0.25%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/mod.rs -------------------------------------------------------------------------------- Ir -- line 229 ---------------------------------------- . /// ``` . /// . /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html . /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices . /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous . /// [`hash`]: Hash::hash . /// [`hash_slice`]: Hash::hash_slice . #[stable(feature = "hash_slice", since = "1.3.0")] 26,895 ( 0.00%) fn hash_slice(data: &[Self], state: &mut H) . where . Self: Sized, . { . for piece in data { 51 ( 0.00%) piece.hash(state); . } 68,090 ( 0.00%) } . } . . // Separate module to reexport the macro `Hash` from prelude without the trait `Hash`. . pub(crate) mod macros { . /// Derive macro generating an impl of the trait `Hash`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics)] -- line 252 ---------------------------------------- -- line 334 ---------------------------------------- . /// println!("Hash is {:x}!", hasher.finish()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . fn write(&mut self, bytes: &[u8]); . . /// Writes a single `u8` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] 14,964 ( 0.00%) fn write_u8(&mut self, i: u8) { 2,373,080 ( 0.02%) self.write(&[i]) 7,482 ( 0.00%) } . /// Writes a single `u16` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] . fn write_u16(&mut self, i: u16) { 7,993,490 ( 0.07%) self.write(&i.to_ne_bytes()) . } . /// Writes a single `u32` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] 5,166 ( 0.00%) fn write_u32(&mut self, i: u32) { 6,374,665 ( 0.06%) self.write(&i.to_ne_bytes()) 1,476 ( 0.00%) } . /// Writes a single `u64` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] . fn write_u64(&mut self, i: u64) { 10 ( 0.00%) self.write(&i.to_ne_bytes()) . } . /// Writes a single `u128` into this hasher. . #[inline] . #[stable(feature = "i128", since = "1.26.0")] . fn write_u128(&mut self, i: u128) { 70,221 ( 0.00%) self.write(&i.to_ne_bytes()) . } . /// Writes a single `usize` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] 6,463 ( 0.00%) fn write_usize(&mut self, i: usize) { 7,220 ( 0.00%) self.write(&i.to_ne_bytes()) 1,850 ( 0.00%) } . . /// Writes a single `i8` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] . fn write_i8(&mut self, i: i8) { . self.write_u8(i as u8) . } . /// Writes a single `i16` into this hasher. -- line 382 ---------------------------------------- -- line 383 ---------------------------------------- . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] . fn write_i16(&mut self, i: i16) { . self.write_u16(i as u16) . } . /// Writes a single `i32` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] 2,214 ( 0.00%) fn write_i32(&mut self, i: i32) { 738 ( 0.00%) self.write_u32(i as u32) 1,476 ( 0.00%) } . /// Writes a single `i64` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] . fn write_i64(&mut self, i: i64) { . self.write_u64(i as u64) . } . /// Writes a single `i128` into this hasher. . #[inline] -- line 401 ---------------------------------------- -- line 402 ---------------------------------------- . #[stable(feature = "i128", since = "1.26.0")] . fn write_i128(&mut self, i: i128) { . self.write_u128(i as u128) . } . /// Writes a single `isize` into this hasher. . #[inline] . #[stable(feature = "hasher_write", since = "1.3.0")] . fn write_isize(&mut self, i: isize) { 4 ( 0.00%) self.write_usize(i as usize) . } . } . . #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] . impl Hasher for &mut H { . fn finish(&self) -> u64 { . (**self).finish() . } -- line 418 ---------------------------------------- -- line 541 ---------------------------------------- . /// bh.hash_one(OrderAmbivalentPair(2, 1)) . /// ); . /// assert_eq!( . /// bh.hash_one(OrderAmbivalentPair(10, 2)), . /// bh.hash_one(&OrderAmbivalentPair(2, 10)) . /// ); . /// ``` . #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")] 3,050,579 ( 0.03%) fn hash_one(&self, x: T) -> u64 . where . Self: Sized, . { 3,217,123 ( 0.03%) let mut hasher = self.build_hasher(); 1,761,291 ( 0.02%) x.hash(&mut hasher); 611,752 ( 0.01%) hasher.finish() 3,204,056 ( 0.03%) } . } . . /// Used to create a default [`BuildHasher`] instance for types that implement . /// [`Hasher`] and [`Default`]. . /// . /// `BuildHasherDefault` can be used when a type `H` implements [`Hasher`] and . /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is . /// defined. -- line 564 ---------------------------------------- -- line 651 ---------------------------------------- . . use super::*; . . macro_rules! impl_write { . ($(($ty:ident, $meth:ident),)*) => {$( . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for $ty { . #[inline] 14,013 ( 0.00%) fn hash(&self, state: &mut H) { 4,668 ( 0.00%) state.$meth(*self) 4,686 ( 0.00%) } . . #[inline] . fn hash_slice(data: &[$ty], state: &mut H) { 3,076 ( 0.00%) let newlen = data.len() * mem::size_of::<$ty>(); . let ptr = data.as_ptr() as *const u8; . // SAFETY: `ptr` is valid and aligned, as this macro is only used . // for numeric primitives which have no padding. The new slice only . // spans across `data` and is never mutated, and its total size is the . // same as the original `data` so it can't be over `isize::MAX`. . state.write(unsafe { slice::from_raw_parts(ptr, newlen) }) . } . } -- line 673 ---------------------------------------- -- line 703 ---------------------------------------- . fn hash(&self, state: &mut H) { . state.write_u32(*self as u32) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for str { . #[inline] 36,049 ( 0.00%) fn hash(&self, state: &mut H) { 5,114 ( 0.00%) state.write(self.as_bytes()); 6,136 ( 0.00%) state.write_u8(0xff) 20,709 ( 0.00%) } . } . . #[stable(feature = "never_hash", since = "1.29.0")] . impl Hash for ! { . #[inline] . fn hash(&self, _: &mut H) { . *self . } -- line 722 ---------------------------------------- -- line 731 ---------------------------------------- . } . ); . . ( $($name:ident)+) => ( . #[stable(feature = "rust1", since = "1.0.0")] . impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized { . #[allow(non_snake_case)] . #[inline] 6,730 ( 0.00%) fn hash(&self, state: &mut S) { 11,574 ( 0.00%) let ($(ref $name,)+) = *self; 8,874 ( 0.00%) $($name.hash(state);)+ 2,692 ( 0.00%) } . } . ); . } . . macro_rules! last_type { . ($a:ident,) => { $a }; . ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) }; . } -- line 750 ---------------------------------------- -- line 763 ---------------------------------------- . impl_hash_tuple! { A B C D E F G H I J K } . impl_hash_tuple! { A B C D E F G H I J K L } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for [T] { . #[inline] . fn hash(&self, state: &mut H) { . self.len().hash(state); 123,279 ( 0.00%) Hash::hash_slice(self, state) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for &T { . #[inline] 516,461 ( 0.00%) fn hash(&self, state: &mut H) { 870,541 ( 0.01%) (**self).hash(state); 511,376 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for &mut T { . #[inline] . fn hash(&self, state: &mut H) { . (**self).hash(state); . } -- line 788 ---------------------------------------- 12,264 ( 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.01%) #[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.01%) 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.01%) 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.01%) fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree { 648,578 ( 0.01%) 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.02%) 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.12%) for token in stream { 5,272,956 ( 0.05%) tts.extra.push(into_compiler_token(token)); . } . } . TokenStream::Fallback(tts) => tts.extend(stream), . } 585,334 ( 0.01%) } . } . . 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.01%) } . . #[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.01%) 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.02%) #[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.01%) } . } . . 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.01%) 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.06%) -------------------------------------------------------------------------------- -- 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.01%) 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.01%) 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.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 1,872,618 ( 0.02%) if lo.file_index != hi.file_index { . return None; . } . . ( 624,206 ( 0.01%) 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.03%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 3,182,072 ( 0.03%) 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.04%) -------------------------------------------------------------------------------- -- 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 . } . 12,483 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 4,161 ( 0.00%) let tcx = self.tcx(); 762,441 ( 0.01%) DecodeContext { 86,508 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), 4,161 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 29,094 ( 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() 79,094 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 12,483 ( 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 { 118,510 ( 0.00%) fn decode>(self, metadata: M) -> T { 60,309 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 230,149 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 73,716 ( 0.00%) T::decode(&mut dcx) 151,110 ( 0.00%) } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { 168 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 48 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 546,881 ( 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 { 206,549 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 60,621 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 58,039 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 13,803 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 27,606 ( 0.00%) assert!(distance <= start); . start - distance . } 9,978 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 34,258 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 60,621 ( 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 { 165,285 ( 0.00%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 130,249 ( 0.00%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 18,607 ( 0.00%) let tcx = self.tcx(); . 18,607 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 54,300 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 5,032 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 167,463 ( 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); 27,485 ( 0.00%) self.opaque = old_opaque; 5,497 ( 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 { 95,922 ( 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 { 176,927 ( 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,228,888 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 307,222 ( 0.00%) let cdata = decoder.cdata(); 307,222 ( 0.00%) let sess = decoder.sess.unwrap(); 614,444 ( 0.01%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 6,536 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 1,536,110 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 26,229 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 3,747 ( 0.00%) let local_cdata = decoder.cdata(); 3,747 ( 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,655 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 8,275 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 8,275 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 16,550 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 29,976 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 2,418,560 ( 0.02%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 302,320 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 604,640 ( 0.01%) 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; . 906,957 ( 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. 617,932 ( 0.01%) 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` 158 ( 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' 316 ( 0.00%) decoder.last_source_file_index = 0; . 158 ( 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. 906,957 ( 0.01%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 1,207,985 ( 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) 26,582 ( 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 13,294 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 13,142 ( 0.00%) decoder.last_source_file_index = index; . } 26,588 ( 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,209,276 ( 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,720,880 ( 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 { 25,336 ( 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(); 17,128 ( 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%) } . 35,079 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 26,722 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 16,121 ( 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)) 45,130 ( 0.00%) } . 314 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 7,019 ( 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 { 25,740 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 102,960 ( 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, . ) . }) 77,220 ( 0.00%) } . 68,803 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 46,441 ( 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 { 5,426 ( 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, . ) . } . 832 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 256 ( 0.00%) match self.kind(item_id) { 64 ( 0.00%) EntryKind::Trait(data) => { 384 ( 0.00%) let data = data.decode((self, sess)); 1,024 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 128 ( 0.00%) data.unsafety, 128 ( 0.00%) data.paren_sugar, 128 ( 0.00%) data.has_auto_impl, 128 ( 0.00%) data.is_marker, 64 ( 0.00%) data.skip_array_during_method_dispatch, 64 ( 0.00%) data.specialization_kind, 256 ( 0.00%) self.def_path_hash(item_id), 64 ( 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"), . } 576 ( 0.00%) } . 324 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 144 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 180 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 114 ( 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 }; 72 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 792 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 144 ( 0.00%) data.discr, 216 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 37 ( 0.00%) did: self.local_def_id(index), 74 ( 0.00%) name: self.item_ident(index, sess).name, 74 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 36 ( 0.00%) data.is_non_exhaustive, . ) 324 ( 0.00%) } . 420 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 112 ( 0.00%) let kind = self.kind(item_id); 56 ( 0.00%) let did = self.local_def_id(item_id); . 126 ( 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 { 35 ( 0.00%) self.root . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) 255 ( 0.00%) .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 168 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 427 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 196 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 6,890 ( 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)] { 6,890 ( 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> { 275 ( 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)] { 110 ( 0.00%) self.root . .tables . .explicit_item_bounds . .get(self, item_id) 84 ( 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 { 36,139 ( 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> { 12,790 ( 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 { 8,422 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 160 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 64,044 ( 0.00%) match self.kind(id) { 53,370 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 30,981 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 246 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 98 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { 3 ( 0.00%) self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 6,330 ( 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> { 124,682 ( 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 { 60 ( 0.00%) self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { . 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> { -- line 1180 ---------------------------------------- -- line 1184 ---------------------------------------- . .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> { 75 ( 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 1227 ---------------------------------------- . .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,442 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 618 ( 0.00%) tcx.arena.alloc_from_iter( 206 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 12,720 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 7,420 ( 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); . 7,698 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { 96 ( 0.00%) EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 945 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 6,615 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 182 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 19,080 ( 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, . } 9,540 ( 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 { 23,742 ( 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,081 ( 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) . }) . }) . } . 13,464 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 1,496 ( 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. 1,928 ( 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,064 ( 0.00%) tcx.arena.alloc_from_iter( 532 ( 0.00%) impls . .decode(self) 11,398 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 11,968 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 444 ( 0.00%) let def_key = self.def_key(id); 555 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 999 ( 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(), . }; -- line 1466 ---------------------------------------- -- line 1479 ---------------------------------------- . 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 { 171 ( 0.00%) let constness = match self.kind(id) { 36 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, 6 ( 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 1517 ---------------------------------------- . EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => { . true . } . _ => false, . } . } . . fn static_mutability(self, id: DefIndex) -> Option { 110 ( 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 { . match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 655 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 146,944 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 41,984 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 15,295 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 167,936 ( 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); . DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 118,622 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 1,115 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 415,177 ( 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) 474,488 ( 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`. 604,638 ( 0.01%) 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) . }); 604,638 ( 0.01%) 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,760 ( 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; . } . } . } . } . } . }; . 604,480 ( 0.01%) self.cdata.source_map_import_info.get_or_init(|| { 30 ( 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,592 ( 0.00%) mut name, 3,312 ( 0.00%) src_hash, 552 ( 0.00%) start_pos, 1,104 ( 0.00%) end_pos, 2,760 ( 0.00%) mut lines, 2,760 ( 0.00%) mut multibyte_chars, 3,312 ( 0.00%) mut non_narrow_chars, 2,760 ( 0.00%) mut normalized_pos, 3,312 ( 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,104 ( 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 { 740,396 ( 0.01%) *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; . } . 9,936 ( 0.00%) let local_version = sess.source_map().new_imported_source_file( 7,176 ( 0.00%) name, 3,864 ( 0.00%) src_hash, . name_hash, . source_length, 1,104 ( 0.00%) self.cnum, 2,760 ( 0.00%) lines, 3,312 ( 0.00%) multibyte_chars, 2,760 ( 0.00%) non_narrow_chars, 2,208 ( 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,656 ( 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 { 19,833 ( 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,296 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 4,010,781 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/slice.rs -------------------------------------------------------------------------------- Ir -- line 157 ---------------------------------------- . use core::alloc::Allocator; . . use crate::boxed::Box; . use crate::vec::Vec; . . // We shouldn't add inline attribute to this since this is used in . // `vec!` macro mostly and causes perf regression. See #71204 for . // discussion and perf results. 24,300 ( 0.00%) pub fn into_vec(b: Box<[T], A>) -> Vec { . unsafe { 43,740 ( 0.00%) let len = b.len(); 48,600 ( 0.00%) let (b, alloc) = Box::into_raw_with_allocator(b); 19,440 ( 0.00%) Vec::from_raw_parts_in(b as *mut T, len, len, alloc) . } 9,720 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] . #[inline] 231,673 ( 0.00%) pub fn to_vec(s: &[T], alloc: A) -> Vec { 45,164 ( 0.00%) T::to_vec(s, alloc) 95,064 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] . pub trait ConvertVec { . fn to_vec(s: &[Self], alloc: A) -> Vec . where . Self: Sized; . } . . #[cfg(not(no_global_oom_handling))] . impl ConvertVec for T { . #[inline] 485,005 ( 0.00%) default fn to_vec(s: &[Self], alloc: A) -> Vec { . struct DropGuard<'a, T, A: Allocator> { . vec: &'a mut Vec, . num_init: usize, . } . impl<'a, T, A: Allocator> Drop for DropGuard<'a, T, A> { . #[inline] . fn drop(&mut self) { . // SAFETY: . // items were marked initialized in the loop below . unsafe { . self.vec.set_len(self.num_init); . } . } . } 483,659 ( 0.00%) let mut vec = Vec::with_capacity_in(s.len(), alloc); 131,907 ( 0.00%) let mut guard = DropGuard { vec: &mut vec, num_init: 0 }; 527,628 ( 0.00%) let slots = guard.vec.spare_capacity_mut(); . // .take(slots.len()) is necessary for LLVM to remove bounds checks . // and has better codegen than zip. 5,007,442 ( 0.04%) for (i, b) in s.iter().enumerate().take(slots.len()) { 139,673 ( 0.00%) guard.num_init = i; 2,394,448 ( 0.02%) slots[i].write(b.clone()); . } 263,814 ( 0.00%) core::mem::forget(guard); . // SAFETY: . // the vec was allocated and initialized above to at least this length. . unsafe { 307,783 ( 0.00%) vec.set_len(s.len()); . } . vec 131,907 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . impl ConvertVec for T { . #[inline] 13,145 ( 0.00%) fn to_vec(s: &[Self], alloc: A) -> Vec { 11,950 ( 0.00%) let mut v = Vec::with_capacity_in(s.len(), alloc); . // SAFETY: . // allocated above with the capacity of `s`, and initialize to `s.len()` in . // ptr::copy_to_non_overlapping below. . unsafe { 17,925 ( 0.00%) s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len()); 8,365 ( 0.00%) v.set_len(s.len()); . } . v 2,390 ( 0.00%) } . } . } . . #[lang = "slice_alloc"] . #[cfg(not(test))] . impl [T] { . /// Sorts the slice. . /// -- line 244 ---------------------------------------- -- line 268 ---------------------------------------- . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn sort(&mut self) . where . T: Ord, . { 14,520 ( 0.00%) merge_sort(self, |a, b| a.lt(b)); . } . . /// Sorts the slice with a comparator function. . /// . /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case. . /// . /// The comparator function must define a total ordering for the elements in the slice. If . /// the ordering is not total, the order of the elements is unspecified. An order is a -- line 284 ---------------------------------------- -- line 323 ---------------------------------------- . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn sort_by(&mut self, mut compare: F) . where . F: FnMut(&T, &T) -> Ordering, . { 3,435 ( 0.00%) merge_sort(self, |a, b| compare(a, b) == Less); . } . . /// Sorts the slice with a key extraction function. . /// . /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*)) . /// worst-case, where the key function is *O*(*m*). . /// . /// For expensive key functions (e.g. functions that are not simple property accesses or -- line 339 ---------------------------------------- -- line 365 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "slice_sort_by_key", since = "1.7.0")] . #[inline] . pub fn sort_by_key(&mut self, mut f: F) . where . F: FnMut(&T) -> K, . K: Ord, . { 113,708 ( 0.00%) merge_sort(self, |a, b| f(a).lt(&f(b))); . } . . /// Sorts the slice with a key extraction function. . /// . /// During sorting, the key function is called at most once per element, by using . /// temporary storage to remember the results of key evaluation. . /// The order of calls to the key function is unspecified and may change in future versions . /// of the standard library. -- line 381 ---------------------------------------- -- line 437 ---------------------------------------- . } . . let sz_u8 = mem::size_of::<(K, u8)>(); . let sz_u16 = mem::size_of::<(K, u16)>(); . let sz_u32 = mem::size_of::<(K, u32)>(); . let sz_usize = mem::size_of::<(K, usize)>(); . . let len = self.len(); 6,070 ( 0.00%) if len < 2 { . return; . } . if sz_u8 < sz_u16 && len <= (u8::MAX as usize) { . return sort_by_key!(u8, self, f); . } . if sz_u16 < sz_u32 && len <= (u16::MAX as usize) { . return sort_by_key!(u16, self, f); . } . if sz_u32 < sz_usize && len <= (u32::MAX as usize) { . return sort_by_key!(u32, self, f); . } 15,785 ( 0.00%) sort_by_key!(usize, self, f) . } . . /// Copies `self` into a new `Vec`. . /// . /// # Examples . /// . /// ``` . /// let s = [10, 40, 30]; . /// let x = s.to_vec(); . /// // Here, `s` and `x` can be modified independently. . /// ``` . #[cfg(not(no_global_oom_handling))] . #[rustc_conversion_suggestion] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6,590 ( 0.00%) pub fn to_vec(&self) -> Vec . where . T: Clone, . { 1,318 ( 0.00%) self.to_vec_in(Global) 2,636 ( 0.00%) } . . /// Copies `self` into a new `Vec` with an allocator. . /// . /// # Examples . /// . /// ``` . /// #![feature(allocator_api)] . /// -- line 486 ---------------------------------------- -- line 488 ---------------------------------------- . /// . /// let s = [10, 40, 30]; . /// let x = s.to_vec_in(System); . /// // Here, `s` and `x` can be modified independently. . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] 225,820 ( 0.00%) pub fn to_vec_in(&self, alloc: A) -> Vec . where . T: Clone, . { . // N.B., see the `hack` module in this file for more details. 46,810 ( 0.00%) hack::to_vec(self, alloc) 90,328 ( 0.00%) } . . /// Converts `self` into a vector without clones or allocation. . /// . /// The resulting vector can be converted back into a box via . /// `Vec`'s `into_boxed_slice` method. . /// . /// # Examples . /// -- line 510 ---------------------------------------- -- line 512 ---------------------------------------- . /// let s: Box<[i32]> = Box::new([10, 40, 30]); . /// let x = s.into_vec(); . /// // `s` cannot be used anymore because it has been converted into `x`. . /// . /// assert_eq!(x, vec![10, 40, 30]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 24,300 ( 0.00%) pub fn into_vec(self: Box) -> Vec { . // N.B., see the `hack` module in this file for more details. 4,860 ( 0.00%) hack::into_vec(self) 9,720 ( 0.00%) } . . /// Creates a vector by repeating a slice `n` times. . /// . /// # Panics . /// . /// This function will panic if the capacity would overflow. . /// . /// # Examples -- line 531 ---------------------------------------- -- line 624 ---------------------------------------- . /// # Examples . /// . /// ``` . /// assert_eq!(["hello", "world"].join(" "), "hello world"); . /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]); . /// assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); . /// ``` . #[stable(feature = "rename_connect_to_join", since = "1.3.0")] 18 ( 0.00%) pub fn join(&self, sep: Separator) -> >::Output . where . Self: Join, . { . Join::join(self, sep) 18 ( 0.00%) } . . /// Flattens a slice of `T` into a single value `Self::Output`, placing a . /// given separator between each. . /// . /// # Examples . /// . /// ``` . /// # #![allow(deprecated)] -- line 645 ---------------------------------------- -- line 821 ---------------------------------------- . //////////////////////////////////////////////////////////////////////////////// . // Standard trait implementations for slices . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Borrow<[T]> for Vec { . fn borrow(&self) -> &[T] { . &self[..] 359,948 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl BorrowMut<[T]> for Vec { . fn borrow_mut(&mut self) -> &mut [T] { . &mut self[..] . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl ToOwned for [T] { . type Owned = Vec; . #[cfg(not(test))] 270,540 ( 0.00%) fn to_owned(&self) -> Vec { 1,318 ( 0.00%) self.to_vec() 213,796 ( 0.00%) } . . #[cfg(test)] . fn to_owned(&self) -> Vec { . hack::to_vec(self, Global) . } . . fn clone_into(&self, target: &mut Vec) { . // drop anything in target that will not be overwritten -- line 854 ---------------------------------------- -- line 871 ---------------------------------------- . /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted. . /// . /// This is the integral subroutine of insertion sort. . #[cfg(not(no_global_oom_handling))] . fn insert_head(v: &mut [T], is_less: &mut F) . where . F: FnMut(&T, &T) -> bool, . { 49,710 ( 0.00%) if v.len() >= 2 && is_less(&v[1], &v[0]) { . unsafe { . // There are three ways to implement insertion here: . // . // 1. Swap adjacent elements until the first one gets to its final destination. . // However, this way we copy data around more than is necessary. If elements are big . // structures (costly to copy), this method will be slow. . // . // 2. Iterate until the right place for the first element is found. Then shift the -- line 887 ---------------------------------------- -- line 890 ---------------------------------------- . // . // 3. Copy the first element into a temporary variable. Iterate until the right place . // for it is found. As we go along, copy every traversed element into the slot . // preceding it. Finally, copy data from the temporary variable into the remaining . // hole. This method is very good. Benchmarks demonstrated slightly better . // performance than with the 2nd method. . // . // All methods were benchmarked, and the 3rd showed best results. So we chose that one. 6 ( 0.00%) let tmp = mem::ManuallyDrop::new(ptr::read(&v[0])); . . // Intermediate state of the insertion process is always tracked by `hole`, which . // serves two purposes: . // 1. Protects integrity of `v` from panics in `is_less`. . // 2. Fills the remaining hole in `v` in the end. . // . // Panic safety: . // . // If `is_less` panics at any point during the process, `hole` will get dropped and . // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it . // initially held exactly once. . let mut hole = InsertionHole { src: &*tmp, dest: &mut v[1] }; . ptr::copy_nonoverlapping(&v[1], &mut v[0], 1); . . for i in 2..v.len() { 12,000 ( 0.00%) if !is_less(&v[i], &*tmp) { . break; . } . ptr::copy_nonoverlapping(&v[i], &mut v[i - 1], 1); . hole.dest = &mut v[i]; . } . // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`. . } . } -- line 922 ---------------------------------------- -- line 966 ---------------------------------------- . // . // Panic safety: . // . // If `is_less` panics at any point during the process, `hole` will get dropped and fill the . // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every . // object it initially held exactly once. . let mut hole; . 2,253 ( 0.00%) if mid <= len - mid { . // The left run is shorter. . unsafe { . ptr::copy_nonoverlapping(v, buf, mid); . hole = MergeHole { start: buf, end: buf.add(mid), dest: v }; . } . . // Initially, these pointers point to the beginnings of their arrays. . let left = &mut hole.start; . let mut right = v_mid; . let out = &mut hole.dest; . 93,198 ( 0.00%) while *left < hole.end && right < v_end { . // Consume the lesser side. . // If equal, prefer the left run to maintain stability. . unsafe { 91,565 ( 0.00%) let to_copy = if is_less(&*right, &**left) { . get_and_increment(&mut right) . } else { . get_and_increment(left) . }; . ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1); . } . } . } else { -- line 998 ---------------------------------------- -- line 1002 ---------------------------------------- . hole = MergeHole { start: buf, end: buf.add(len - mid), dest: v_mid }; . } . . // Initially, these pointers point past the ends of their arrays. . let left = &mut hole.dest; . let right = &mut hole.end; . let mut out = v_end; . 42,230 ( 0.00%) while v < *left && buf < *right { . // Consume the greater side. . // If equal, prefer the right run to maintain stability. . unsafe { 361 ( 0.00%) let to_copy = if is_less(&*right.offset(-1), &*left.offset(-1)) { . decrement_and_get(left) . } else { . decrement_and_get(right) . }; . ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1); . } . } . } -- line 1022 ---------------------------------------- -- line 1039 ---------------------------------------- . start: *mut T, . end: *mut T, . dest: *mut T, . } . . impl Drop for MergeHole { . fn drop(&mut self) { . // `T` is not a zero-sized type, so it's okay to divide by its size. 772 ( 0.00%) let len = (self.end as usize - self.start as usize) / mem::size_of::(); . unsafe { . ptr::copy_nonoverlapping(self.start, self.dest, len); . } . } . } . } . . /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail -- line 1055 ---------------------------------------- -- line 1060 ---------------------------------------- . /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are . /// satisfied: . /// . /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len` . /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len` . /// . /// The invariants ensure that the total running time is *O*(*n* \* log(*n*)) worst-case. . #[cfg(not(no_global_oom_handling))] 470,499 ( 0.00%) fn merge_sort(v: &mut [T], mut is_less: F) . where . F: FnMut(&T, &T) -> bool, . { . // Slices of up to this length get sorted using insertion sort. . const MAX_INSERTION: usize = 20; . // Very short runs are extended using insertion sort to span at least this many elements. . const MIN_RUN: usize = 10; . -- line 1076 ---------------------------------------- -- line 1077 ---------------------------------------- . // Sorting has no meaningful behavior on zero-sized types. . if size_of::() == 0 { . return; . } . . let len = v.len(); . . // Short arrays get sorted in-place via insertion sort to avoid allocations. 136,789 ( 0.00%) if len <= MAX_INSERTION { 123,168 ( 0.00%) if len >= 2 { 10 ( 0.00%) for i in (0..len - 1).rev() { . insert_head(&mut v[i..], &mut is_less); . } . } . return; . } . . // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it . // shallow copies of the contents of `v` without risking the dtors running on copies if . // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run, . // which will always have length at most `len / 2`. 75 ( 0.00%) let mut buf = Vec::with_capacity(len / 2); . . // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a . // strange decision, but consider the fact that merges more often go in the opposite direction . // (forwards). According to benchmarks, merging forwards is slightly faster than merging . // backwards. To conclude, identifying runs by traversing backwards improves performance. . let mut runs = vec![]; . let mut end = len; 1,740 ( 0.00%) while end > 0 { . // Find the next natural run, and reverse it if it's strictly descending. . let mut start = end - 1; . if start > 0 { 324 ( 0.00%) start -= 1; . unsafe { 1,567 ( 0.00%) if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) { 1,162 ( 0.00%) while start > 0 && is_less(v.get_unchecked(start), v.get_unchecked(start - 1)) { . start -= 1; . } . v[start..end].reverse(); . } else { 6,211 ( 0.00%) while start > 0 && !is_less(v.get_unchecked(start), v.get_unchecked(start - 1)) . { . start -= 1; . } . } . } . } . . // Insert some more elements into the run if it's too short. Insertion sort is faster than . // merge sort on short sequences, so this significantly improves performance. 27,231 ( 0.00%) while start > 0 && end - start < MIN_RUN { 2,562 ( 0.00%) start -= 1; . insert_head(&mut v[start..end], &mut is_less); . } . . // Push this run onto the stack. 822 ( 0.00%) runs.push(Run { start, len: end - start }); . end = start; . . // Merge some pairs of adjacent runs to satisfy the invariants. . while let Some(r) = collapse(&runs) { 386 ( 0.00%) let left = runs[r + 1]; 1,544 ( 0.00%) let right = runs[r]; . unsafe { . merge( 772 ( 0.00%) &mut v[left.start..right.start + right.len], . left.len, . buf.as_mut_ptr(), . &mut is_less, . ); . } 1,544 ( 0.00%) runs[r] = Run { start: left.start, len: left.len + right.len }; . runs.remove(r + 1); . } . } . . // Finally, exactly one run must remain in the stack. . debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len); . . // Examines the stack of runs and identifies the next pair of runs to merge. More specifically, -- line 1157 ---------------------------------------- -- line 1166 ---------------------------------------- . // hold for *all* runs in the stack. . // . // This function correctly checks invariants for the top four runs. Additionally, if the top . // run starts at index 0, it will always demand a merge operation until the stack is fully . // collapsed, in order to complete the sort. . #[inline] . fn collapse(runs: &[Run]) -> Option { . let n = runs.len(); 2,083 ( 0.00%) if n >= 2 3,895 ( 0.00%) && (runs[n - 1].start == 0 3,470 ( 0.00%) || runs[n - 2].len <= runs[n - 1].len 3,048 ( 0.00%) || (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) 1,599 ( 0.00%) || (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) . { 3,468 ( 0.00%) if n >= 3 && runs[n - 3].len < runs[n - 1].len { Some(n - 3) } else { Some(n - 2) } . } else { . None . } . } . . #[derive(Clone, Copy)] . struct Run { . start: usize, . len: usize, . } 415,376 ( 0.00%) } 2,507,745 ( 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.02%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$oty.take(handle::Handle::decode(r, &mut ())) 2,976,480 ( 0.03%) } . } . . 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.02%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore>> . for &'s mut Marked . { 576,553 ( 0.01%) 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.04%) 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.03%) 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.03%) $(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.07%) api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ()); 1,808,575 ( 0.02%) reverse_encode!(b; $($arg),*); . 15,166,482 ( 0.14%) b = bridge.dispatch.call(b); . 10,454,021 ( 0.09%) let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ()); . 30,332,964 ( 0.27%) bridge.cached_buffer = b; . 3,680,739 ( 0.03%) 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.12%) 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.16%) 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.06%) -------------------------------------------------------------------------------- -- 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)] 174,664,484 ( 1.57%) 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,816 ( 0.01%) pub const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { 1,633,520 ( 0.01%) from_raw_parts(data.cast(), len) 653,408 ( 0.01%) } . . /// Performs the same functionality as [`slice_from_raw_parts`], except that a . /// raw mutable slice is returned, as opposed to a raw immutable slice. . /// . /// See the documentation of [`slice_from_raw_parts`] for more details. . /// . /// This function is safe, but actually using the return value is unsafe. . /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements. -- line 269 ---------------------------------------- -- line 283 ---------------------------------------- . /// (*slice)[2] = 99; // assign a value at an index in the slice . /// }; . /// . /// assert_eq!(unsafe { &*slice }[2], 99); . /// ``` . #[inline] . #[stable(feature = "slice_from_raw_parts", since = "1.42.0")] . #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] 5,127,760 ( 0.05%) pub const fn slice_from_raw_parts_mut(data: *mut T, len: usize) -> *mut [T] { 1,922,910 ( 0.02%) 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 { 21 ( 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.07%) 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,300,590 ( 0.15%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 87,281,396 ( 0.78%) tmp.assume_init() . } 4,240,620 ( 0.04%) } . . /// 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.05%) 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 { 97,770,356 ( 0.88%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } 3,524,396 ( 0.03%) } . . /// 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. 15,656 ( 0.00%) return wrapping_sub( 44,656 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 2,588,668 ( 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 ---------------------------------------- 31,591,756 ( 0.28%) -------------------------------------------------------------------------------- -- 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}; . 349,190 ( 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. 197,917 ( 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, . } . 80,123 ( 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. 569,584 ( 0.01%) #[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,011,438 ( 0.45%) #[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.01%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 230,703 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 305,975 ( 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,934 ( 0.01%) 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,083,228 ( 0.04%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 226,831 ( 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,212 ( 0.04%) 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.10%) 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.01%) 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.05%) 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.02%) 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,348,271 ( 0.14%) -------------------------------------------------------------------------------- -- 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 { 18,084 ( 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 { 212,348 ( 0.00%) match self { 445,531 ( 0.00%) Ok(x) => Some(x), 12 ( 0.00%) Err(_) => None, . } 108 ( 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> { 811 ( 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,075,292 ( 0.01%) match self { 1,085,527 ( 0.01%) Ok(t) => Ok(op(t)), 321,108 ( 0.00%) Err(e) => Err(e), . } 37,504 ( 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,071 ( 0.00%) match self { 1,263 ( 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 { 10,344,106 ( 0.09%) match self { 10,861,298 ( 0.10%) Ok(t) => Ok(t), 8,737 ( 0.00%) Err(e) => Err(op(e)), . } 2,320,547 ( 0.02%) } . . /// 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,092,235 ( 0.04%) match self { 379,643 ( 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")] 2,657 ( 0.00%) pub fn unwrap(self) -> T . where . E: fmt::Debug, . { 661,535 ( 0.01%) match self { 365,475 ( 0.00%) Ok(t) => t, . Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), . } 1,691 ( 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,687,574 ( 0.02%) 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 { 53,973 ( 0.00%) match self { 86,587 ( 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 { 14,540 ( 0.00%) match self { 50,655 ( 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 { 17 ( 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,330,648 ( 0.05%) match self { 662,260 ( 0.01%) 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,208 ( 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] 58,626 ( 0.00%) fn clone(&self) -> Self { 482,751 ( 0.00%) match self { 241,131 ( 0.00%) Ok(x) => Ok(x.clone()), 114,250 ( 0.00%) Err(x) => Err(x.clone()), . } 124,596 ( 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. . 5,643 ( 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,364 ( 0.00%) Ok(output) . } . . #[inline] 4,109,882 ( 0.04%) fn branch(self) -> ControlFlow { 11,631,726 ( 0.10%) match self { 16,018,384 ( 0.14%) Ok(v) => ControlFlow::Continue(v), 1,064,153 ( 0.01%) Err(e) => ControlFlow::Break(Err(e)), . } 3,034,156 ( 0.03%) } . } . . #[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 { 650,911 ( 0.01%) 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,070,419 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/map.rs -------------------------------------------------------------------------------- Ir -- line 60 ---------------------------------------- . #[derive(Clone)] . pub struct Map { . // Used for `SplitWhitespace` and `SplitAsciiWhitespace` `as_str` methods . pub(crate) iter: I, . f: F, . } . . impl Map { 409,260 ( 0.00%) pub(in crate::iter) fn new(iter: I, f: F) -> Map { 1,494,208 ( 0.01%) Map { iter, f } 321,428 ( 0.00%) } . } . . #[stable(feature = "core_impl_debug", since = "1.9.0")] . impl fmt::Debug for Map { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("Map").field("iter", &self.iter).finish() . } . } . 276,524 ( 0.00%) fn map_fold( . mut f: impl FnMut(T) -> B, . mut g: impl FnMut(Acc, B) -> Acc, . ) -> impl FnMut(Acc, T) -> Acc { 14,336,233 ( 0.13%) move |acc, elt| g(acc, f(elt)) 411,919 ( 0.00%) } . 4,615 ( 0.00%) fn map_try_fold<'a, T, B, Acc, R>( . f: &'a mut impl FnMut(T) -> B, . mut g: impl FnMut(Acc, B) -> R + 'a, . ) -> impl FnMut(Acc, T) -> R + 'a { 68,519 ( 0.00%) move |acc, elt| g(acc, f(elt)) 1,846 ( 0.00%) } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for Map . where . F: FnMut(I::Item) -> B, . { . type Item = B; . . #[inline] 57,614 ( 0.00%) fn next(&mut self) -> Option { 179,339 ( 0.00%) self.iter.next().map(&mut self.f) 43,304 ( 0.00%) } . . #[inline] 17,832 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 318,729 ( 0.00%) self.iter.size_hint() 8,916 ( 0.00%) } . 382,948 ( 0.00%) fn try_fold(&mut self, init: Acc, g: G) -> R . where . Self: Sized, . G: FnMut(Acc, Self::Item) -> R, . R: Try, . { 157,400 ( 0.00%) self.iter.try_fold(init, map_try_fold(&mut self.f, g)) 482,363 ( 0.00%) } . 5,942,996 ( 0.05%) fn fold(self, init: Acc, g: G) -> Acc . where . G: FnMut(Acc, Self::Item) -> Acc, . { 7,846,864 ( 0.07%) self.iter.fold(init, map_fold(self.f, g)) 6,280,711 ( 0.06%) } . . #[doc(hidden)] . unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> B . where . Self: TrustedRandomAccessNoCoerce, . { . // SAFETY: the caller must uphold the contract for . // `Iterator::__iterator_get_unchecked`. -- line 133 ---------------------------------------- 1,674,047 ( 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 . // . 19,460,488 ( 0.17%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 14,595,366 ( 0.13%) 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. 441,344 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 662,016 ( 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) { 4,974,771 ( 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,613,112 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 3,226,224 ( 0.03%) 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 ---------------------------------------- -------------------------------------------------------------------------------- -- 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 { 343,602 ( 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,021 ( 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,630 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] 294,564 ( 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.01%) 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(), . } 147,282 ( 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.01%) ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }, . cap: capacity, 49,080 ( 0.00%) alloc, . } . } 196,425 ( 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,210 ( 0.02%) pub fn ptr(&self) -> *mut T { 3,184,815 ( 0.03%) self.ptr.as_ptr() 2,123,210 ( 0.02%) } . . /// 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.02%) fn current_memory(&self) -> Option<(NonNull, Layout)> { 27,645,698 ( 0.25%) if mem::size_of::() == 0 || self.cap == 0 { 1,072,037 ( 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::(); 7,910,259 ( 0.07%) let size = mem::size_of::() * self.cap; 1,597,358 ( 0.01%) let layout = Layout::from_size_align_unchecked(size, align); 4,425,684 ( 0.04%) 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] 1,777,422 ( 0.02%) fn do_reserve_and_handle( . slf: &mut RawVec, . len: usize, . additional: usize, . ) { 106,311 ( 0.00%) handle_reserve(slf.grow_amortized(len, additional)); 2,083,306 ( 0.02%) } . 2,660,051 ( 0.02%) if self.needs_to_grow(len, additional) { 1,765,079 ( 0.02%) 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,506,364 ( 0.03%) pub fn reserve_for_push(&mut self, len: usize) { 600,890 ( 0.01%) handle_reserve(self.grow_amortized(len, 1)); 3,835,312 ( 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,585 ( 0.00%) pub fn reserve_exact(&mut self, len: usize, additional: usize) { . handle_reserve(self.try_reserve_exact(len, additional)); 110,585 ( 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,556 ( 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))] 49,905 ( 0.00%) pub fn shrink_to_fit(&mut self, cap: usize) { 14,516 ( 0.00%) handle_reserve(self.shrink(cap)); 45,370 ( 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 { 4,837,644 ( 0.04%) additional > self.capacity().wrapping_sub(len) 135,916 ( 0.00%) } . 1,938,053 ( 0.02%) 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,260,181 ( 0.02%) self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }; 1,366,741 ( 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,344 ( 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`. 6,519,336 ( 0.06%) let cap = cmp::max(self.cap * 2, required_cap); 581,808 ( 0.01%) let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap); . 727,260 ( 0.01%) let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 6,112,820 ( 0.05%) 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,632 ( 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`. 50,338 ( 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> { 37,201 ( 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(()) }; 48,088 ( 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)] 7,214,901 ( 0.06%) fn finish_grow( . new_layout: Result, . current_memory: Option<(NonNull, Layout)>, . alloc: &mut A, . ) -> Result, TryReserveError> . where . A: Allocator, . { . // Check for the error here to minimize the size of `RawVec::grow_*`. 2,036,328 ( 0.02%) let new_layout = new_layout.map_err(|_| CapacityOverflow)?; . 1,745,424 ( 0.02%) alloc_guard(new_layout.size())?; . 5,348,961 ( 0.05%) 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()) 5,277,384 ( 0.05%) } . . unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec { . /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. 1,086,070 ( 0.01%) fn drop(&mut self) { 10,331,879 ( 0.09%) if let Some((ptr, layout)) = self.current_memory() { 361,748 ( 0.00%) unsafe { self.alloc.deallocate(ptr, layout) } . } 558,978 ( 0.01%) } . } . . // 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.02%) 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.01%) fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> { 778,128 ( 0.01%) 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 ---------------------------------------- 31,026,125 ( 0.28%) -------------------------------------------------------------------------------- -- 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,804 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 2,402 ( 0.00%) from_str_radix(src, radix) 7,206 ( 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 { 614,091 ( 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,449,035 ( 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,114,913 ( 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 { 73,554,801 ( 0.66%) 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.01%) pub const fn checked_add(self, rhs: Self) -> Option { 583,786 ( 0.01%) let (a, b) = self.overflowing_add(rhs); 1,459,460 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 583,784 ( 0.01%) } . . /// 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`. 2,646,584 ( 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`. 456,489 ( 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.01%) let (a, b) = self.overflowing_mul(rhs); 1,946,890 ( 0.02%) if unlikely!(b) {None} else {Some(a)} 778,756 ( 0.01%) } . . /// 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 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 { 554,648 ( 0.00%) 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 { 40,051 ( 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 { 42,831,998 ( 0.38%) 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 { 8,283,374 ( 0.07%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 20,920,378 ( 0.19%) 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 1492 ---------------------------------------- . #[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)] . pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 4,374,568 ( 0.04%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); 291,892 ( 0.00%) (a as Self, b) 583,784 ( 0.01%) } . . /// 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) { 604,498 ( 0.01%) 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) { 8,164,543 ( 0.07%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); 389,378 ( 0.00%) (a as Self, b) 778,756 ( 0.01%) } . . /// 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 { 172,180 ( 0.00%) if self <= 1 { return 0; } . 239,090 ( 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. 715,749 ( 0.01%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 239,445 ( 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 { 305,417 ( 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,317,432 ( 0.02%) -------------------------------------------------------------------------------- -- 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.07%) unsafe extern "C" fn call R>(env: &mut Env, arg: A) -> R { . (*(env as *mut _ as *mut F))(arg) 10,110,988 ( 0.09%) } . 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.36%) unsafe { (self.call)(self.env, arg) } . } . } -------------------------------------------------------------------------------- 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 -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 5,558,902,718 (49.84%) events annotated

(&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| { 280,658 ( 0.00%) if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE } 47,301 ( 0.00%) } 2,377 ( 0.00%) } . 128,316 ( 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 { 240,763 ( 0.00%) move |(), x| match f(x) { 81,653 ( 0.00%) Some(x) => ControlFlow::Break(x), . None => ControlFlow::CONTINUE, 2,549 ( 0.00%) } 5,808 ( 0.00%) } . 11,701 ( 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")] 14 ( 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) { 16 ( 0.00%) move |x| (f(&x), x) . } . . #[inline] . fn compare((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { . x_p.cmp(y_p) . } . 20 ( 0.00%) let (_, x) = self.map(key(f)).max_by(compare)?; . Some(x) 16 ( 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 { 42 ( 0.00%) move |x, y| cmp::max_by(x, y, &mut compare) . } . 40,884 ( 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(); 95 ( 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, . { 180,987 ( 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 { 141,364 ( 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,043,377 ( 0.04%) -------------------------------------------------------------------------------- -- 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); . 217,055 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 229,890 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 489,111 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 67,149 ( 0.00%) i += 2 . } . 229,890 ( 0.00%) if i < count { 167,116 ( 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,147,651 ( 0.03%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 21,586,404 ( 0.19%) 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,814,597 ( 0.06%) self.nbuf = nbuf + size; . . return; . } . 1,149,578 ( 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)] 340,579 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 340,579 ( 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,405,790 ( 0.03%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 2,724,632 ( 0.02%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 3,065,211 ( 0.03%) 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,619,335 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 1,362,316 ( 0.01%) self.processed += BUFFER_SIZE; 681,158 ( 0.01%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 24,854 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 715,395 ( 0.01%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 261,748 ( 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); . } . } . 132,145 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 128,098 ( 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,475 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 15,495 ( 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,485 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 15,495 ( 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. 30,990 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 105,374 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 120,869 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 210,748 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 30,990 ( 0.00%) let input_left = length - processed; 27,075 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 36,094 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 36,094 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 36,094 ( 0.00%) self.state.v0 ^= elem; 72,188 ( 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,495 ( 0.00%) self.nbuf = extra_bytes_left; 77,475 ( 0.00%) self.processed += nbuf + processed; 92,970 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 158,703 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 211,604 ( 0.00%) let mut state = self.state; . . for i in 0..last { 135,118 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 135,118 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 135,118 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 105,802 ( 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); 39,406 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 145,208 ( 0.00%) let length = self.processed + self.nbuf; 105,800 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 52,900 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 52,900 ( 0.00%) state.v0 ^= b; . 52,900 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 172,340 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 66,538 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 66,538 ( 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,603,536 ( 0.11%) compress!(state); 13,554,331 ( 0.12%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 344,676 ( 0.00%) compress!(state); 344,676 ( 0.00%) compress!(state); 344,676 ( 0.00%) compress!(state); 291,777 ( 0.00%) compress!(state); . } . } 2,455,080 ( 0.02%) -------------------------------------------------------------------------------- -- 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.13%) fn encode(self, w: &mut Writer, _: &mut S) { 390 ( 0.00%) w.extend_from_array(&self.to_le_bytes()); 18,246,445 ( 0.16%) } . } . . 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.02%) bytes.copy_from_slice(&r[..N]); 9,130,713 ( 0.08%) *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.35%) 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.19%) match self { 4,539,768 ( 0.04%) $($name::$variant $(($field))* => { 346,350 ( 0.00%) tag::$variant.encode(w, s); 5,779,094 ( 0.05%) $($field.encode(w, s);)* 130 ( 0.00%) })* . } 30,505,692 ( 0.27%) } . } . . impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> . for $name $(<$($T),+>)? . { 9,897,953 ( 0.09%) 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.08%) match u8::decode(r, s) { . $(tag::$variant => { 252,863 ( 0.00%) $(let $field = DecodeMut::decode(r, s);)* 6,751,230 ( 0.06%) $name::$variant $(($field))* 126,334 ( 0.00%) })* . _ => unreachable!(), . } 17,225,220 ( 0.15%) } . } . } . } . . 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.35%) let x = r[0]; 21,619,813 ( 0.19%) *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.10%) 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.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,340,677 ( 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,050,634 ( 0.03%) 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); 995,867 ( 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,586,465 ( 0.08%) 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(), 122,124 ( 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,217,575 ( 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> { 6,984,677 ( 0.06%) 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(); 16 ( 0.00%) let idx = usize::from(*len); 8 ( 0.00%) assert!(idx < CAPACITY); 18 ( 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,390,075 ( 0.08%) 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> { 331,956 ( 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,633,437 ( 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> { 530,936 ( 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.01%) 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,108,025 ( 0.08%) 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,150,093 ( 0.01%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 1,270,048 ( 0.01%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); 1,150,090 ( 0.01%) *self.node.len_mut() = new_len as u16; . . self.node.val_area_mut(self.idx).assume_init_mut() . } 9,200,962 ( 0.08%) } . } . . 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,450,270 ( 0.03%) if self.node.len() < CAPACITY { 5,276,451 ( 0.05%) let val_ptr = self.insert_fit(key, val); 2,035,982 ( 0.02%) 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.01%) 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,380,352 ( 0.10%) pub fn insert_recursing( . self, . key: K, . value: V, . ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) { 6,642,379 ( 0.06%) let (mut split, val_ptr) = match self.insert(key, value) { . (InsertResult::Fit(handle), ptr) => { 5,089,955 ( 0.05%) 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.01%) 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,350,810 ( 0.09%) } . } . . 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() }; 660,170 ( 0.01%) (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,448 ( 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.01%) 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.01%) let v = slice_remove(self.node.val_area_mut(..old_len), self.idx); 3,834,096 ( 0.03%) *self.node.len_mut() = (old_len - 1) as u16; 3,554,570 ( 0.03%) ((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,515,414 ( 0.09%) if len > idx + 1 { 409,250 ( 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,348,240 ( 0.09%) 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.01%) assert!(src.len() == dst.len()); . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); . } . } . . #[cfg(test)] . mod tests; 28,926,730 ( 0.26%) -------------------------------------------------------------------------------- -- 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")] 641,962 ( 0.01%) pub fn or_insert_with V>(self, default: F) -> &'a mut V { 277,233 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 1,839,841 ( 0.02%) Vacant(entry) => entry.insert(default()), . } 770,951 ( 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,488,783 ( 0.05%) pub fn insert(self, value: V) -> &'a mut V { 13,889,016 ( 0.12%) let out_ptr = match self.handle.insert_recursing(self.key, value) { 1,127,436 ( 0.01%) (Fit(_), val_ptr) => { . // SAFETY: We have consumed self.handle and the handle returned. 1,016,473 ( 0.01%) let map = unsafe { self.dormant_map.awaken() }; 4,348,665 ( 0.04%) 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,642,243 ( 0.05%) } . } . . 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.04%) pub fn remove_entry(self) -> (K, V) { 940,849 ( 0.01%) self.remove_kv() 7,132,414 ( 0.06%) } . . /// 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,560 ( 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,030,234 ( 0.01%) let mut emptied_internal_root = false; 13,641,135 ( 0.12%) 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,119,968 ( 0.04%) map.length -= 1; 2,059,984 ( 0.02%) if emptied_internal_root { . let root = map.root.as_mut().unwrap(); . root.pop_internal_level(); . } . old_kv . } . } 1,928,009 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 6,168 ( 0.00%) fn clone(&self) -> Self { 11,232 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 1,946 ( 0.00%) table: self.table.clone(), . } 6,939 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] 1,456 ( 0.00%) pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 743,062 ( 0.01%) move |val| make_hash::(hash_builder, &val.0) 2,184 ( 0.00%) } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] 1,546 ( 0.00%) fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 1,256,354 ( 0.01%) move |x| k.eq(x.0.borrow()) 2,319 ( 0.00%) } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 1,132,283 ( 0.01%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 2,813 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { 93,186 ( 0.00%) hash_builder.hash_one(val) 1,878 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 275 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 2,184 ( 0.00%) pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { 2,125,567 ( 0.02%) hash_builder.hash_one(val) 1,456 ( 0.00%) } . . #[cfg(feature = "ahash")] . impl HashMap { . /// Creates an empty `HashMap`. . /// . /// The hash map is initially created with a capacity of 0, so it will not allocate until it . /// is first inserted into. . /// -- line 297 ---------------------------------------- -- line 366 ---------------------------------------- . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] 910 ( 0.00%) pub const fn with_hasher(hash_builder: S) -> Self { 776,363 ( 0.01%) Self { . hash_builder, 520 ( 0.00%) table: RawTable::new(), . } 260 ( 0.00%) } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// . /// The hash map will be able to hold at least `capacity` elements without . /// reallocating. If `capacity` is 0, the hash map will not allocate. . /// . /// Warning: `hash_builder` is normally randomly generated, and -- line 387 ---------------------------------------- -- line 436 ---------------------------------------- . /// use hashbrown::HashMap; . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 7 ( 0.00%) pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 80 ( 0.00%) Self { . hash_builder, 4 ( 0.00%) table: RawTable::new_in(alloc), . } 2 ( 0.00%) } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// . /// The hash map will be able to hold at least `capacity` elements without . /// reallocating. If `capacity` is 0, the hash map will not allocate. . /// . /// Warning: `hash_builder` is normally randomly generated, and -- line 457 ---------------------------------------- -- line 599 ---------------------------------------- . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// for (key, val) in map.iter() { . /// println!("key: {} val: {}", key, val); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 520 ( 0.00%) pub fn iter(&self) -> Iter<'_, K, V> { . // Here we tie the lifetime of self to the iter. . unsafe { 520 ( 0.00%) Iter { 390 ( 0.00%) inner: self.table.iter(), . marker: PhantomData, . } . } 260 ( 0.00%) } . . /// An iterator visiting all key-value pairs in arbitrary order, . /// with mutable references to the values. . /// The iterator element type is `(&'a K, &'a mut V)`. . /// . /// # Examples . /// . /// ``` -- line 623 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 124,876 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 284,877 ( 0.00%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 352 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 10 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 430 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 440 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1041 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.get(&1), Some(&"a")); . /// assert_eq!(map.get(&2), None); . /// ``` . #[inline] 369 ( 0.00%) pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 2,369,139 ( 0.02%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), 246 ( 0.00%) None => None, . } 369 ( 0.00%) } . . /// 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 . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1067 ---------------------------------------- -- line 1086 ---------------------------------------- . // Avoid `Option::map` because it bloats LLVM IR. . match self.get_inner(k) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . #[inline] 615 ( 0.00%) fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 3,507,638 ( 0.03%) if self.table.is_empty() { 78 ( 0.00%) None . } else { 181 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); 270 ( 0.00%) self.table.get(hash, equivalent_key(k)) . } 369 ( 0.00%) } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1113 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,074,013 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 1,423,858 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,033 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 3,099 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 2,066 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 1,033 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); . self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. -- line 1219 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 9,325,074 ( 0.08%) pub fn insert(&mut self, k: K, v: V) -> Option { 6,552 ( 0.00%) let hash = make_insert_hash::(&self.hash_builder, &k); 15,273 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 3,970,904 ( 0.04%) self.table 3,283,970 ( 0.03%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 473,719 ( 0.00%) None . } 8,876,648 ( 0.08%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 239,201 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 2,197,576 ( 0.02%) match self.remove_entry(k) { 58,728 ( 0.00%) Some((_, v)) => Some(v), 243,642 ( 0.00%) None => None, . } 557,438 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 743,791 ( 0.01%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 1737 ---------------------------------------- . . impl Default for HashMap . where . S: Default, . A: Default + Allocator + Clone, . { . /// Creates an empty `HashMap`, with the `Default` value for the hasher and allocator. . #[cfg_attr(feature = "inline-more", inline)] 3 ( 0.00%) fn default() -> Self { 12 ( 0.00%) Self::with_hasher_in(Default::default(), Default::default()) 2 ( 0.00%) } . } . . impl Index<&Q> for HashMap . where . K: Eq + Hash + Borrow, . Q: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, -- line 1755 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 4,694,016 ( 0.04%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 12,021,697 ( 0.11%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 12,946,046 ( 0.12%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 1,800,972 ( 0.02%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 8,131,198 ( 0.07%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 322,745 ( 0.00%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 4,470,570 ( 0.04%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 5,740,109 ( 0.05%) self.from_hash(hash, equivalent(k)) 8,252,138 ( 0.07%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 8,187,966 ( 0.07%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 531,956 ( 0.00%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 13,174 ( 0.00%) fn into_iter(self) -> IntoIter { 247,623 ( 0.00%) IntoIter { 128,093 ( 0.00%) inner: self.table.into_iter(), . } 39,522 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] 260 ( 0.00%) fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 688,304 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 4,808 ( 0.00%) Some((&r.0, &r.1)) . }, 260 ( 0.00%) None => None, . } 520 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 1 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3018 ---------------------------------------- . type Item = (&'a K, &'a mut V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a mut V)> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some(x) => unsafe { . let r = x.as_mut(); 242 ( 0.00%) Some((&r.0, &mut r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } -- line 3034 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 7,202 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 1,522 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 3,044 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 6 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 199,688 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 170,879 ( 0.00%) let iter = iter.into_iter(); 95,780 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 11,967 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 240,129 ( 0.00%) self.insert(k, v); . }); 126,122 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 5,311,640 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs -------------------------------------------------------------------------------- Ir -- line 4 ---------------------------------------- . . use super::Utf8Error; . . /// Returns the initial codepoint accumulator for the first byte. . /// The first byte is special, only want bottom 5 bits for width 2, 4 bits . /// for width 3, and 3 bits for width 4. . #[inline] . const fn utf8_first_byte(byte: u8, width: u32) -> u32 { 922 ( 0.00%) (byte & (0x7F >> width)) as u32 . } . . /// Returns the value of `ch` updated with continuation byte `byte`. . #[inline] . const fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { 2,402 ( 0.00%) (ch << 6) | (byte & CONT_MASK) as u32 . } . . /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the . /// bits `10`). . #[inline] . pub(super) const fn utf8_is_cont_byte(byte: u8) -> bool { . (byte as i8) < -64 . } -- line 26 ---------------------------------------- -- line 28 ---------------------------------------- . /// Reads the next code point out of a byte iterator (assuming a . /// UTF-8-like encoding). . /// . /// # Safety . /// . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[unstable(feature = "str_internals", issue = "none")] . #[inline] 253,569 ( 0.00%) pub unsafe fn next_code_point<'a, I: Iterator>(bytes: &mut I) -> Option { . // Decode UTF-8 6,241,450 ( 0.06%) let x = *bytes.next()?; 10,210,310 ( 0.09%) if x < 128 { 232,530 ( 0.00%) return Some(x as u32); . } . . // Multibyte case follows . // Decode from a byte combination out of: [[[x y] z] w] . // NOTE: Performance is sensitive to the exact formulation here . let init = utf8_first_byte(x, 2); . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let y = unsafe { *bytes.next().unwrap_unchecked() }; . let mut ch = utf8_acc_cont_byte(init, y); 984 ( 0.00%) if x >= 0xE0 { . // [[x y z] w] case . // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let z = unsafe { *bytes.next().unwrap_unchecked() }; . let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z); . ch = init << 12 | y_z; 786 ( 0.00%) if x >= 0xF0 { . // [x y z w] case . // use only the lower 3 bits of `init` . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let w = unsafe { *bytes.next().unwrap_unchecked() }; 6 ( 0.00%) ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w); . } . } . . Some(ch) 422,615 ( 0.00%) } . . /// Reads the last code point out of a byte iterator (assuming a . /// UTF-8-like encoding). . /// . /// # Safety . /// . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[inline] 35,289 ( 0.00%) pub(super) unsafe fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option . where . I: DoubleEndedIterator, . { . // Decode UTF-8 141,156 ( 0.00%) let w = match *bytes.next_back()? { 128,373 ( 0.00%) next_byte if next_byte < 128 => return Some(next_byte as u32), . back_byte => back_byte, . }; . . // Multibyte case follows . // Decode from a byte combination out of: [x [y [z w]]] . let mut ch; . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. -- line 93 ---------------------------------------- -- line 105 ---------------------------------------- . ch = utf8_first_byte(x, 4); . ch = utf8_acc_cont_byte(ch, y); . } . ch = utf8_acc_cont_byte(ch, z); . } . ch = utf8_acc_cont_byte(ch, w); . . Some(ch) 58,815 ( 0.00%) } . . // use truncation to fit u64 into usize . const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize; . . /// Returns `true` if any byte in the word `x` is nonascii (>= 128). . #[inline] . const fn contains_nonascii(x: usize) -> bool { 35,537 ( 0.00%) (x & NONASCII_MASK) != 0 . } . . /// Walks through `v` checking that it's a valid UTF-8 sequence, . /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`. . #[inline(always)] . #[rustc_const_unstable(feature = "str_internals", issue = "none")] . pub(super) const fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { . let mut index = 0; . let len = v.len(); . . let usize_bytes = mem::size_of::(); . let ascii_block_size = 2 * usize_bytes; 542,115 ( 0.00%) let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 }; . let align = v.as_ptr().align_offset(usize_bytes); . 1,379,376 ( 0.01%) while index < len { . let old_offset = index; . macro_rules! err { . ($error_len: expr) => { . return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len }) . }; . } . . macro_rules! next { -- line 145 ---------------------------------------- -- line 148 ---------------------------------------- . // we needed data, but there was none: error! . if index >= len { . err!(None) . } . v[index] . }}; . } . 621,400 ( 0.01%) let first = v[index]; 1,242,800 ( 0.01%) if first >= 128 { . let w = utf8_char_width(first); . // 2-byte encoding is for codepoints \u{0080} to \u{07ff} . // first C2 80 last DF BF . // 3-byte encoding is for codepoints \u{0800} to \u{ffff} . // first E0 A0 80 last EF BF BF . // excluding surrogates codepoints \u{d800} to \u{dfff} . // ED A0 80 to ED BF BF . // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff -- line 165 ---------------------------------------- -- line 169 ---------------------------------------- . // . // https://tools.ietf.org/html/rfc3629 . // UTF8-1 = %x00-7F . // UTF8-2 = %xC2-DF UTF8-tail . // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / . // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) . // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / . // %xF4 %x80-8F 2( UTF8-tail ) 134 ( 0.00%) match w { . 2 => { 30 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(1)) . } . } . 3 => { 192 ( 0.00%) match (first, next!()) { . (0xE0, 0xA0..=0xBF) 168 ( 0.00%) | (0xE1..=0xEC, 0x80..=0xBF) . | (0xED, 0x80..=0x9F) . | (0xEE..=0xEF, 0x80..=0xBF) => {} . _ => err!(Some(1)), . } 120 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(2)) . } . } . 4 => { 6 ( 0.00%) match (first, next!()) { 3 ( 0.00%) (0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {} . _ => err!(Some(1)), . } 5 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(2)) . } 5 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(3)) . } . } . _ => err!(Some(1)), . } 93 ( 0.00%) index += 1; . } else { . // Ascii case, try to skip forward quickly. . // When the pointer is aligned, read 2 words of data per iteration . // until we find a word containing a non-ascii byte. 1,977,777 ( 0.02%) if align != usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 { . let ptr = v.as_ptr(); 298,372 ( 0.00%) while index < blocks_end { . // SAFETY: since `align - index` and `ascii_block_size` are . // multiples of `usize_bytes`, `block = ptr.add(index)` is . // always aligned with a `usize` so it's safe to dereference . // both `block` and `block.offset(1)`. . unsafe { . let block = ptr.add(index) as *const usize; . // break if there is a nonascii byte 35,537 ( 0.00%) let zu = contains_nonascii(*block); . let zv = contains_nonascii(*block.offset(1)); 71,074 ( 0.00%) if zu || zv { . break; . } . } 71,032 ( 0.00%) index += ascii_block_size; . } . // step from the point where the wordwise loop stopped 2,729,011 ( 0.02%) while index < len && v[index] < 128 { 541,084 ( 0.00%) index += 1; . } . } else { 507,699 ( 0.00%) index += 1; . } . } . } . . Ok(()) . } . . // https://tools.ietf.org/html/rfc3629 -- line 245 ---------------------------------------- -- line 263 ---------------------------------------- . 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F . ]; . . /// Given a first byte, determines how many bytes are in this UTF-8 character. . #[unstable(feature = "str_internals", issue = "none")] . #[must_use] . #[inline] . pub const fn utf8_char_width(b: u8) -> usize { 62 ( 0.00%) UTF8_CHAR_WIDTH[b as usize] as usize . } . . /// Mask of the value bits of a continuation byte. . const CONT_MASK: u8 = 0b0011_1111; . . // truncate `&str` to length at most equal to `max` . // return `true` if it were truncated, and the new str. . pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) { -- line 279 ---------------------------------------- 7,902,469 ( 0.07%) -------------------------------------------------------------------------------- -- 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,496 ( 0.01%) pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 936,425 ( 0.01%) unsafe { intrinsics::size_of_val(val) } 451,566 ( 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 14 ( 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.07%) 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,951,948 ( 0.09%) let result = ptr::read(dest); 103,516,216 ( 0.93%) ptr::write(dest, src); . result . } 3,035,587 ( 0.03%) } . . /// 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,548 ( 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 { 118,208 ( 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,372 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 756,961 ( 0.01%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- line 376 ---------------------------------------- . fn len(&self) -> usize { . self.iter.len() . } . } . . impl<'a, T: Array> FusedIterator for Drain<'a, T> {} . . impl<'a, T: 'a + Array> Drop for Drain<'a, T> { 693,308 ( 0.01%) fn drop(&mut self) { . self.for_each(drop); . 297,132 ( 0.00%) if self.tail_len > 0 { . unsafe { . let source_vec = self.vec.as_mut(); . . // memmove back untouched tail, update to new length . let start = source_vec.len(); . let tail = self.tail_start; . if tail != start { . let src = source_vec.as_ptr().add(tail); . let dst = source_vec.as_mut_ptr().add(start); . ptr::copy(src, dst, self.tail_len); . } . source_vec.set_len(start + self.tail_len); . } . } 693,308 ( 0.01%) } . } . . #[cfg(feature = "union")] . union SmallVecData { . inline: core::mem::ManuallyDrop>, . heap: (*mut A::Item, usize), . } . -- line 410 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 137,412 ( 0.00%) self.inline.as_mut_ptr() as *mut A::Item . } . #[inline] . fn from_inline(inline: MaybeUninit) -> SmallVecData { . SmallVecData { . inline: core::mem::ManuallyDrop::new(inline), . } . } . #[inline] . unsafe fn into_inline(self) -> MaybeUninit { . core::mem::ManuallyDrop::into_inner(self.inline) . } . #[inline] . unsafe fn heap(&self) -> (*mut A::Item, usize) { 88,633 ( 0.00%) self.heap . } . #[inline] . unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { . &mut self.heap . } . #[inline] . fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData { . SmallVecData { heap: (ptr, len) } -- line 452 ---------------------------------------- -- line 557 ---------------------------------------- . #[inline] . pub fn new() -> SmallVec { . // Try to detect invalid custom implementations of `Array`. Hopefully, . // this check should be optimized away entirely for valid ones. . assert!( . mem::size_of::() == A::size() * mem::size_of::() . && mem::align_of::() >= mem::align_of::() . ); 945,200 ( 0.01%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 579 ---------------------------------------- . /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100); . /// . /// assert!(v.is_empty()); . /// assert!(v.capacity() >= 100); . /// ``` . #[inline] . pub fn with_capacity(n: usize) -> Self { . let mut v = SmallVec::new(); 6 ( 0.00%) v.reserve_exact(n); . v . } . . /// Construct a new `SmallVec` from a `Vec`. . /// . /// Elements will be copied to the inline buffer if vec.capacity() <= Self::inline_capacity(). . /// . /// ```rust -- line 595 ---------------------------------------- -- line 635 ---------------------------------------- . /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf(buf: A) -> SmallVec { . SmallVec { . capacity: A::size(), 13,174 ( 0.00%) data: SmallVecData::from_inline(MaybeUninit::new(buf)), . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length, which must be less or . /// equal to the size of `buf`. . /// . /// ```rust -- line 651 ---------------------------------------- -- line 653 ---------------------------------------- . /// . /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; . /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { 12 ( 0.00%) assert!(len <= A::size()); 36 ( 0.00%) unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length. The user is responsible . /// for ensuring that `len <= A::size()`. . /// . /// ```rust . /// use smallvec::SmallVec; -- line 670 ---------------------------------------- -- line 674 ---------------------------------------- . /// let small_vec: SmallVec<_> = unsafe { . /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) . /// }; . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { 6 ( 0.00%) SmallVec { . capacity: len, . data: SmallVecData::from_inline(buf), . } . } . . /// Sets the length of a vector. . /// . /// This will explicitly set the size of the vector, without actually . /// modifying its buffers, so it is up to the caller to ensure that the . /// vector is actually the specified size. . pub unsafe fn set_len(&mut self, new_len: usize) { . let (_, len_ptr, _) = self.triple_mut(); 369,076 ( 0.00%) *len_ptr = new_len; . } . . /// The maximum number of elements this vector can hold inline . #[inline] . fn inline_capacity() -> usize { . if mem::size_of::() > 0 { . A::size() . } else { -- line 703 ---------------------------------------- -- line 725 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.triple().1 . } . . /// Returns `true` if the vector is empty . #[inline] . pub fn is_empty(&self) -> bool { 199,652 ( 0.00%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 7,338,183 ( 0.07%) if self.spilled() { . let (ptr, len) = self.data.heap(); . (ptr, len, self.capacity) . } else { . (self.data.inline(), self.capacity, Self::inline_capacity()) . } . } . } . . /// Returns a tuple with (data ptr, len ptr, capacity) . #[inline] . fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { . unsafe { 14,235,437 ( 0.13%) if self.spilled() { 29,801 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 13,037,228 ( 0.12%) self.capacity > Self::inline_capacity() . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// Note 1: The element range is removed even if the iterator is only . /// partially consumed or not consumed at all. . /// . /// Note 2: It is unspecified how many elements are removed from the vector . /// if the `Drain` value is leaked. . /// . /// # 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. 99,044 ( 0.00%) pub fn drain(&mut self, range: R) -> Drain<'_, A> . where . R: RangeBounds, . { . use core::ops::Bound::*; . . let len = self.len(); . let start = match range.start_bound() { . Included(&n) => n, -- line 800 ---------------------------------------- -- line 810 ---------------------------------------- . assert!(start <= end); . assert!(end <= len); . . unsafe { . self.set_len(start); . . let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); . 495,220 ( 0.00%) Drain { . tail_start: end, . tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } 99,044 ( 0.00%) } . . /// Append an item to the vector. . #[inline] 171,765 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 2,578,992 ( 0.02%) if *len == cap { 439 ( 0.00%) self.reserve(1); 87,225 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 169,102 ( 0.00%) ptr::write(ptr.add(*len), value); 4,197,671 ( 0.04%) *len += 1; . } 137,412 ( 0.00%) } . . /// Remove an item from the end of the vector and return it, or None if empty. . #[inline] . pub fn pop(&mut self) -> Option { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 485,448 ( 0.00%) if *len_ptr == 0 { . return None; . } 126,628 ( 0.00%) let last_index = *len_ptr - 1; 128,491 ( 0.00%) *len_ptr = last_index; 114,412 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 754 ( 0.00%) } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` . /// # use smallvec::{SmallVec, smallvec}; . /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3]; -- line 863 ---------------------------------------- -- line 879 ---------------------------------------- . /// or if the capacity computation overflows `usize`. . pub fn grow(&mut self, new_cap: usize) { . infallible(self.try_grow(new_cap)) . } . . /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. . /// . /// Panics if `new_cap` is less than the vector's length 7,374 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 106 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 173,562 ( 0.00%) assert!(new_cap >= len); 173,562 ( 0.00%) if new_cap <= self.inline_size() { . if unspilled { . return Ok(()); . } . self.data = SmallVecData::from_inline(MaybeUninit::uninit()); . ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); . self.capacity = len; . deallocate(ptr, cap); 173,562 ( 0.00%) } else if new_cap != cap { 172,879 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 86,781 ( 0.00%) if unspilled { . new_alloc = NonNull::new(alloc::alloc::alloc(layout)) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . ptr::copy_nonoverlapping(ptr, new_alloc, len); . } else { . // This should never fail since the same succeeded . // when previously allocating `ptr`. 83,392 ( 0.00%) let old_layout = layout_array::(cap)?; . . let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); . new_alloc = NonNull::new(new_ptr) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . } 173,562 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 259,864 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 7,480 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. . /// . /// Panics if the capacity computation overflows `usize`. . #[inline] 282,785 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 892,748 ( 0.01%) infallible(self.try_reserve(additional)) 323,016 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 2,981,853 ( 0.03%) pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . // prefer triple_mut() even if triple() would work . // so that the optimizer removes duplicated calls to it . // from callers like insert() 21,723 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 3,028,667 ( 0.03%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .and_then(usize::checked_next_power_of_two) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 278 ( 0.00%) self.try_grow(new_cap) 3,402,255 ( 0.03%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. 6 ( 0.00%) pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) 6 ( 0.00%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 342,491 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 797 ( 0.00%) self.try_grow(new_cap) 797 ( 0.00%) } . . /// Shrink the capacity of the vector as much as possible. . /// . /// When possible, this will move data from an external heap buffer to the vector's inline . /// storage. . pub fn shrink_to_fit(&mut self) { . if !self.spilled() { . return; -- line 981 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 92,394 ( 0.00%) while len < *len_ptr { . let last_index = *len_ptr - 1; . *len_ptr = last_index; . ptr::drop_in_place(ptr.add(last_index)); . } . } . } . . /// Extracts a slice containing the entire vector. -- line 1015 ---------------------------------------- -- line 1047 ---------------------------------------- . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. . pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 1,177 ( 0.00%) let len = *len_ptr; 4,098 ( 0.00%) assert!(index < len); 35,419 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 2,732 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } . } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 6,345 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 1,689 ( 0.00%) let len = *len_ptr; 2,266 ( 0.00%) assert!(index <= len); 4,532 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 2,266 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 4,040 ( 0.00%) } . . /// Insert multiple elements at position `index`, shifting all following elements toward the . /// back. . pub fn insert_many>(&mut self, index: usize, iterable: I) { . let mut iter = iterable.into_iter(); . if index == self.len() { . return self.extend(iter); . } -- line 1088 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . . /// 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 and preserves the order of the retained . /// elements. 181,548 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 38,844 ( 0.00%) if !f(&mut self[i]) { 462 ( 0.00%) del += 1; 12,272 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 40,344 ( 0.00%) self.truncate(len - del); 161,376 ( 0.00%) } . . /// Removes consecutive duplicate elements. 1,694 ( 0.00%) pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); 1,936 ( 0.00%) } . . /// Removes consecutive duplicate elements using the given equality relation. . pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut A::Item, &mut A::Item) -> bool, . { . // See the implementation of Vec::dedup_by in the . // standard library for an explanation of this algorithm. . let len = self.len(); 484 ( 0.00%) if len <= 1 { . return; . } . . let ptr = self.as_mut_ptr(); . let mut w: usize = 1; . . unsafe { . for r in 1..len { . let p_r = ptr.add(r); 1,936 ( 0.00%) let p_wm1 = ptr.add(w - 1); . if !same_bucket(&mut *p_r, &mut *p_wm1) { 484 ( 0.00%) if r != w { . let p_w = p_wm1.add(1); . mem::swap(&mut *p_r, &mut *p_w); . } 484 ( 0.00%) w += 1; . } . } . } . . self.truncate(w); . } . . /// Removes consecutive elements that map to the same key. -- line 1262 ---------------------------------------- -- line 1418 ---------------------------------------- . capacity: len, . data: SmallVecData::from_inline(unsafe { . let mut data: MaybeUninit = MaybeUninit::uninit(); . ptr::copy_nonoverlapping( . slice.as_ptr(), . data.as_mut_ptr() as *mut A::Item, . len, . ); 689 ( 0.00%) data . }), . } . } else { . let mut b = slice.to_vec(); . let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); . mem::forget(b); . SmallVec { . capacity: cap, -- line 1434 ---------------------------------------- -- line 1436 ---------------------------------------- . } . } . } . . /// Copy elements from a slice into the vector at position `index`, shifting any following . /// elements toward the back. . /// . /// For slices of `Copy` types, this is more efficient than `insert`. 763,173 ( 0.01%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 232,284 ( 0.00%) assert!(index <= len); . . unsafe { . let slice_ptr = slice.as_ptr(); . let ptr = self.as_mut_ptr().add(index); . ptr::copy(ptr, ptr.add(slice.len()), len - index); . ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); 154,856 ( 0.00%) self.set_len(len + slice.len()); . } 619,424 ( 0.01%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 194,769 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. . /// . /// If `len` is less than the current length, the vector simply truncated. . /// . /// If `len` is greater than the current length, `value` is appended to the . /// vector until its length equals `len`. 170 ( 0.00%) pub fn resize(&mut self, len: usize, value: A::Item) { . let old_len = self.len(); . 34 ( 0.00%) if len > old_len { . self.extend(repeat(value).take(len - old_len)); . } else { . self.truncate(len); . } 119 ( 0.00%) } . . /// Creates a `SmallVec` with `n` copies of `elem`. . /// ``` . /// use smallvec::SmallVec; . /// . /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); . /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); . /// ``` -- line 1495 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 44,587 ( 0.00%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1691 ---------------------------------------- . fn from(array: A) -> SmallVec { . SmallVec::from_buf(array) . } . } . . impl> ops::Index for SmallVec { . type Output = I::Output; . 3 ( 0.00%) fn index(&self, index: I) -> &I::Output { . &(**self)[index] 9 ( 0.00%) } . } . . impl> ops::IndexMut for SmallVec { . fn index_mut(&mut self, index: I) -> &mut I::Output { . &mut (&mut **self)[index] . } . } . -- line 1709 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 1,406,243 ( 0.01%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 3,446,204 ( 0.03%) fn extend>(&mut self, iterable: I) { 614,571 ( 0.01%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 66,652 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 1,689,913 ( 0.02%) while len.get() < cap { 431,143 ( 0.00%) if let Some(out) = iter.next() { . ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 503,675 ( 0.00%) for elem in iter { 3,008 ( 0.00%) self.push(elem); . } 3,038,834 ( 0.03%) } . } . . impl fmt::Debug for SmallVec . where . A::Item: fmt::Debug, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_list().entries(self.iter()).finish() -- line 1759 ---------------------------------------- -- line 1764 ---------------------------------------- . #[inline] . fn default() -> SmallVec { . SmallVec::new() . } . } . . #[cfg(feature = "may_dangle")] . unsafe impl<#[may_dangle] A: Array> Drop for SmallVec { 1,660,649 ( 0.01%) fn drop(&mut self) { . unsafe { 2,940,045 ( 0.03%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 1,884,238 ( 0.02%) } . } . . #[cfg(not(feature = "may_dangle"))] . impl Drop for SmallVec { . fn drop(&mut self) { . unsafe { . if self.spilled() { . let (ptr, len) = self.data.heap(); -- line 1789 ---------------------------------------- -- line 1888 ---------------------------------------- . A::Item: Clone, . { . fn clone(&self) -> IntoIter { . SmallVec::from(self.as_slice()).into_iter() . } . } . . impl Drop for IntoIter { 1,381 ( 0.00%) fn drop(&mut self) { 267,212 ( 0.00%) for _ in self {} 1,240 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 1,491,787 ( 0.01%) if self.current == self.end { 74,439 ( 0.00%) None . } else { . unsafe { . let current = self.current; 814,964 ( 0.01%) self.current += 1; 10,110 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 106,653 ( 0.00%) let size = self.end - self.current; . (size, Some(size)) . } . } . . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . if self.current == self.end { -- line 1927 ---------------------------------------- -- line 1955 ---------------------------------------- . impl IntoIterator for SmallVec { . type IntoIter = IntoIter; . type Item = A::Item; . fn into_iter(mut self) -> Self::IntoIter { . unsafe { . // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements . let len = self.len(); . self.set_len(0); 138,799 ( 0.00%) IntoIter { 1,005,973 ( 0.01%) data: self, . current: 0, . end: len, . } . } . } . } . . impl<'a, A: Array> IntoIterator for &'a SmallVec { -- line 1972 ---------------------------------------- -- line 2000 ---------------------------------------- . len: &'a mut usize, . local_len: usize, . } . . impl<'a> SetLenOnDrop<'a> { . #[inline] . fn new(len: &'a mut usize) -> Self { . SetLenOnDrop { 411,032 ( 0.00%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 240,627 ( 0.00%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 443,628 ( 0.00%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 10,261,287 ( 0.09%) -------------------------------------------------------------------------------- -- 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,012,058 ( 0.05%) 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`). 296,471 ( 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,592 ( 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,459 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 9,088 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 54,698 ( 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 { 701,485 ( 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,636,450 ( 0.09%) fn drop(&mut self) { . unsafe { 2,088,725 ( 0.02%) self.inner().dec_strong(); 5,449,798 ( 0.05%) if self.inner().strong() == 0 { . // destroy the contained object 285,252 ( 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,037,253 ( 0.02%) if self.inner().weak() == 0 { 180,473 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 6,634,308 ( 0.06%) } . } . . #[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,616 ( 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,253 ( 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; 27 ( 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,712,948 ( 0.02%) 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,220,045 ( 0.05%) 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,237,672 ( 0.07%) 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,043,749 ( 0.03%) 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,558,836 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 17,495,119 ( 0.16%) Vec { buf: RawVec::NEW, len: 0 } 155,574 ( 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,132,363 ( 0.04%) 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 { 994,022 ( 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 { 774,553 ( 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,066,368 ( 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) { 48,968 ( 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. 112,448 ( 0.00%) if self.capacity() > self.len { 41,487 ( 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,097 ( 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,714,410 ( 0.02%) 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); 950,685 ( 0.01%) self.len = len; 21,867 ( 0.00%) ptr::drop_in_place(s); . } 3,037,316 ( 0.03%) } . . /// 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,484 ( 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. 14,135,137 ( 0.13%) let ptr = self.buf.ptr(); . unsafe { 207,742 ( 0.00%) assume(!ptr.is_null()); . } . ptr 415,484 ( 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.02%) 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. 13,738,529 ( 0.12%) let ptr = self.buf.ptr(); . unsafe { 846,066 ( 0.01%) assume(!ptr.is_null()); . } . ptr 1,692,132 ( 0.02%) } . . /// 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()); . 1,933,570 ( 0.02%) self.len = new_len; 229,948 ( 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 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,292 ( 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,082 ( 0.00%) let len = self.len(); 6,378 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 14,540 ( 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.) 20,832 ( 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,540 ( 0.00%) self.set_len(len + 1); . } 10,536 ( 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,659 ( 0.00%) let len = self.len(); 109,103 ( 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. 81,790 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 46,947 ( 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")] 605,709 ( 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)); 595,472 ( 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, . { 81,849 ( 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) { 72,002 ( 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), 40,929 ( 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, . { 821,809 ( 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) }; 183,091 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 6,269 ( 0.00%) g.processed_len += 1; 3,108 ( 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 { 1,197 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 798 ( 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")] 20,545 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 2,937 ( 0.00%) let len = self.len(); 18,762 ( 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 { 9,839 ( 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 */ 7,289 ( 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); . } 23,480 ( 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,521 ( 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. 20,737,496 ( 0.19%) if self.len == self.buf.capacity() { 2,132,752 ( 0.02%) self.buf.reserve_for_push(self.len); . } . unsafe { 5,081,058 ( 0.05%) let end = self.as_mut_ptr().add(self.len); 3,394,733 ( 0.03%) ptr::write(end, value); 27,142,872 ( 0.24%) self.len += 1; . } 890,836 ( 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 { 3,830,152 ( 0.03%) if self.len == 0 { 2 ( 0.00%) None . } else { . unsafe { 3,202,965 ( 0.03%) self.len -= 1; 368,275 ( 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); 510,393 ( 0.00%) let len = self.len(); 85,797 ( 0.00%) unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 2,190,811 ( 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,007 ( 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,035,766 ( 0.01%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 325,922 ( 0.00%) Drain { . tail_start: end, 323,681 ( 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.04%) 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,318,931 ( 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,884 ( 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")] 670 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 67 ( 0.00%) let len = self.len(); . 201 ( 0.00%) if new_len > len { 23,022 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 67 ( 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 { 55 ( 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. 548,673 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 35,333 ( 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,109,192 ( 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 . } 433,339 ( 0.00%) } . } . . 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) { 2,937 ( 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")] 155,841 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 901,372 ( 0.01%) ::from_elem(elem, n, Global) 174,258 ( 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,226 ( 0.01%) fn deref(&self) -> &[T] { 18,299,891 ( 0.16%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 415,978 ( 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] { 3,396,522 ( 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,661,150 ( 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) 1,859,097 ( 0.02%) } . . // 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,136 ( 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 { 5,439,459 ( 0.05%) >::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,410,198 ( 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(); 865,904 ( 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,104 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 26,601 ( 0.00%) fn extend>(&mut self, iter: I) { 2,624,370 ( 0.02%) >::spec_extend(self, iter.into_iter()) 23,006 ( 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); . // } 526,335 ( 0.00%) while let Some(element) = iterator.next() { 69,468 ( 0.00%) let len = self.len(); 672,960 ( 0.01%) if len == self.capacity() { 3,041 ( 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 495,169 ( 0.00%) self.set_len(len + 1); . } 2,026 ( 0.00%) } 19,664 ( 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, . { 11 ( 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, . { 24,832 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 134,288 ( 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. . /// -- line 2768 ---------------------------------------- -- 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,513,941 ( 0.04%) 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,771,945 ( 0.03%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 4,924,992 ( 0.04%) } . } . . #[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 ---------------------------------------- 15,599,621 ( 0.14%) -------------------------------------------------------------------------------- -- 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. 10,689,455 ( 0.10%) 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,010,056 ( 0.04%) GoDown(handle) => match handle.force() { . Leaf(leaf) => return GoDown(leaf), . Internal(internal) => internal.descend(), . }, . } . } 4,220,680 ( 0.04%) } . . /// 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()); 32,936,600 ( 0.30%) for (offset, k) in unsafe { keys.get_unchecked(start_index..) }.iter().enumerate() { 159,760,898 ( 1.43%) 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,108,502 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . impl<'a, 'b, T: LambdaL> Deref for RefMutL<'a, 'b, T> { . type Target = >::Out; . fn deref(&self) -> &Self::Target { . self.0 . } . } . . impl<'a, 'b, T: LambdaL> DerefMut for RefMutL<'a, 'b, T> { 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.17%) 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.05%) 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.22%) } . . /// 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/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,831,904 ( 0.03%) 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,088 ( 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,745 ( 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 { 2,192 ( 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, . } . } . . pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 1 ( 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() . } . } . } . } . . /// Differentiates between real files and common virtual files. 331,699 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,581 ( 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%) } . } . 2 ( 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<'_> { 4 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 6 ( 0.00%) match *self.inner { . Real(ref name) => { 6 ( 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, ""), . } 5 ( 0.00%) } . } . . impl FileNameDisplay<'_> { . pub fn to_string_lossy(&self) -> Cow<'_, str> { . match self.inner { . FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } . } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,100 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) -- line 353 ---------------------------------------- -- line 357 ---------------------------------------- . } . . pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } . } . . // 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 { 1 ( 0.00%) pub lo: BytePos, 1 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 3 ( 0.00%) pub ctxt: SyntaxContext, 1 ( 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,209,745 ( 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] 79,912 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 79,912 ( 0.00%) } . #[inline] 208,548 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 139,032 ( 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.03%) 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.01%) 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.03%) } . . /// 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,104 ( 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,208 ( 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] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 29 ( 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 { 4,968 ( 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); 552 ( 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 { 899,688 ( 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,104 ( 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,072 ( 0.00%) SourceFile { 4,416 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,208 ( 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,208 ( 0.00%) lines, 2,208 ( 0.00%) multibyte_chars, 2,208 ( 0.00%) non_narrow_chars, 2,208 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 4,968 ( 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. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// 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() 550 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 81,912 ( 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 { 30,043 ( 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`. 574 ( 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; . 1,722 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 35,468 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 106,392 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 88,660 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 3,444 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 2,870 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 1,148 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 2,009 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 574 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 286 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 287 ( 0.00%) let linebpos = self.lines[a]; 574 ( 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); 287 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 2,296 ( 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`. 2,296 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 861 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 574 ( 0.00%) if line > 0 { . let col = col_or_chpos; 287 ( 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); . 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(); 1,435 ( 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) . } 2,009 ( 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,215 ( 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 { 131,911 ( 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,465,448 ( 0.03%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 4,762,972 ( 0.04%) $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,818,844 ( 0.02%) 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.02%) let span = self.data_untracked(); 742,219 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 1,044,630 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 699,948 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 689,364 ( 0.01%) 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.01%) 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,477,273 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/proc_macro_server.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . } . . trait ToInternal { . fn to_internal(self) -> T; . } . . impl FromInternal for Delimiter { . fn from_internal(delim: token::DelimToken) -> Delimiter { 30,270 ( 0.00%) match delim { . token::Paren => Delimiter::Parenthesis, . token::Brace => Delimiter::Brace, . token::Bracket => Delimiter::Bracket, . token::NoDelim => Delimiter::None, . } . } . } . . impl ToInternal for Delimiter { . fn to_internal(self) -> token::DelimToken { 187,119 ( 0.00%) match self { . Delimiter::Parenthesis => token::Paren, . Delimiter::Brace => token::Brace, . Delimiter::Bracket => token::Bracket, . Delimiter::None => token::NoDelim, . } . } . } . . impl FromInternal<(TreeAndSpacing, &'_ mut Vec, &mut Rustc<'_, '_>)> . for TokenTree . { 458,232 ( 0.00%) fn from_internal( 400,953 ( 0.00%) ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec, &mut Rustc<'_, '_>), . ) -> Self { . use rustc_ast::token::*; . . let joint = spacing == Joint; 350,503 ( 0.00%) let Token { kind, span } = match tree { . tokenstream::TokenTree::Delimited(span, delim, tts) => { . let delimiter = Delimiter::from_internal(delim); 70,630 ( 0.00%) return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false }); . } . tokenstream::TokenTree::Token(token) => token, . }; . . macro_rules! tt { . ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => ( . TokenTree::$ty(self::$ty { . $($field $(: $value)*,)+ -- line 76 ---------------------------------------- -- line 91 ---------------------------------------- . }}; . ($a:expr, $b:expr, $c:expr) => {{ . stack.push(tt!(Punct::new($c, joint))); . stack.push(tt!(Punct::new($b, true))); . tt!(Punct::new($a, true)) . }}; . } . 390,119 ( 0.00%) match kind { . Eq => op!('='), . Lt => op!('<'), . Le => op!('<', '='), . EqEq => op!('=', '='), . Ne => op!('!', '='), . Ge => op!('>', '='), . Gt => op!('>'), . AndAnd => op!('&', '&'), -- line 107 ---------------------------------------- -- line 131 ---------------------------------------- . At => op!('@'), . Dot => op!('.'), . DotDot => op!('.', '.'), . DotDotDot => op!('.', '.', '.'), . DotDotEq => op!('.', '.', '='), . Comma => op!(','), . Semi => op!(';'), . Colon => op!(':'), 14,808 ( 0.00%) ModSep => op!(':', ':'), 9,072 ( 0.00%) RArrow => op!('-', '>'), . LArrow => op!('<', '-'), . FatArrow => op!('=', '>'), . Pound => op!('#'), . Dollar => op!('$'), . Question => op!('?'), . SingleQuote => op!('\''), . . Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()), 185,256 ( 0.00%) Ident(name, is_raw) => tt!(Ident::new(rustc.sess(), name, is_raw)), . Lifetime(name) => { . let ident = symbol::Ident::new(name, span).without_first_quote(); . stack.push(tt!(Ident::new(rustc.sess(), ident.name, false))); . tt!(Punct::new('\'', true)) . } 26,677 ( 0.00%) Literal(lit) => tt!(Literal { lit }), 10,964 ( 0.00%) DocComment(_, attr_style, data) => { . let mut escaped = String::new(); 2,741 ( 0.00%) for ch in data.as_str().chars() { . escaped.extend(ch.escape_debug()); . } . let stream = [ . Ident(sym::doc, false), . Eq, 13,705 ( 0.00%) TokenKind::lit(token::Str, Symbol::intern(&escaped), None), . ] . .into_iter() 46,597 ( 0.00%) .map(|kind| tokenstream::TokenTree::token(kind, span)) . .collect(); 21,928 ( 0.00%) stack.push(TokenTree::Group(Group { . delimiter: Delimiter::Bracket, 2,741 ( 0.00%) stream, 5,482 ( 0.00%) span: DelimSpan::from_single(span), . flatten: false, . })); 2,741 ( 0.00%) if attr_style == ast::AttrStyle::Inner { . stack.push(tt!(Punct::new('!', false))); . } 10,964 ( 0.00%) tt!(Punct::new('#', false)) . } . . Interpolated(nt) 2,618 ( 0.00%) if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) => . { . TokenTree::Ident(Ident::new(rustc.sess(), name.name, is_raw, name.span)) . } 374 ( 0.00%) Interpolated(nt) => { 1,870 ( 0.00%) let stream = nt_to_tokenstream(&nt, rustc.sess(), CanSynthesizeMissingTokens::No); 4,114 ( 0.00%) TokenTree::Group(Group { . delimiter: Delimiter::None, 374 ( 0.00%) stream, 748 ( 0.00%) span: DelimSpan::from_single(span), 1,496 ( 0.00%) flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess()), . }) . } . . OpenDelim(..) | CloseDelim(..) => unreachable!(), . Eof => unreachable!(), . } 515,511 ( 0.00%) } . } . . impl ToInternal for TokenTree { 2,190,155 ( 0.02%) fn to_internal(self) -> TokenStream { . use rustc_ast::token::*; . 2,221,293 ( 0.02%) let (ch, joint, span) = match self { 152,808 ( 0.00%) TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span), 124,746 ( 0.00%) TokenTree::Group(Group { delimiter, stream, span, .. }) => { 124,746 ( 0.00%) return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream) . .into(); . } 651,507 ( 0.01%) TokenTree::Ident(self::Ident { sym, is_raw, span }) => { 1,520,183 ( 0.01%) return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into(); . } . TokenTree::Literal(self::Literal { . lit: token::Lit { kind: token::Integer, symbol, suffix }, . span, 2,948 ( 0.00%) }) if symbol.as_str().starts_with('-') => { . let minus = BinOp(BinOpToken::Minus); . let symbol = Symbol::intern(&symbol.as_str()[1..]); . let integer = TokenKind::lit(token::Integer, symbol, suffix); . let a = tokenstream::TokenTree::token(minus, span); . let b = tokenstream::TokenTree::token(integer, span); . return [a, b].into_iter().collect(); . } . TokenTree::Literal(self::Literal { -- line 226 ---------------------------------------- -- line 229 ---------------------------------------- . }) if symbol.as_str().starts_with('-') => { . let minus = BinOp(BinOpToken::Minus); . let symbol = Symbol::intern(&symbol.as_str()[1..]); . let float = TokenKind::lit(token::Float, symbol, suffix); . let a = tokenstream::TokenTree::token(minus, span); . let b = tokenstream::TokenTree::token(float, span); . return [a, b].into_iter().collect(); . } 17,043 ( 0.00%) TokenTree::Literal(self::Literal { lit, span }) => { 22,724 ( 0.00%) return tokenstream::TokenTree::token(Literal(lit), span).into(); . } . }; . 458,424 ( 0.00%) let kind = match ch { . '=' => Eq, . '<' => Lt, . '>' => Gt, . '!' => Not, . '~' => Tilde, . '+' => BinOp(Plus), . '-' => BinOp(Minus), . '*' => BinOp(Star), -- line 250 ---------------------------------------- -- line 260 ---------------------------------------- . ':' => Colon, . '#' => Pound, . '$' => Dollar, . '?' => Question, . '\'' => SingleQuote, . _ => unreachable!(), . }; . 1,069,656 ( 0.01%) let tree = tokenstream::TokenTree::token(kind, span); 764,040 ( 0.01%) TokenStream::new(vec![(tree, if joint { Joint } else { Alone })]) 2,190,155 ( 0.02%) } . } . . impl ToInternal for Level { . fn to_internal(self) -> rustc_errors::Level { . match self { . Level::Error => rustc_errors::Level::Error { lint: false }, . Level::Warning => rustc_errors::Level::Warning, . Level::Note => rustc_errors::Level::Note, -- line 278 ---------------------------------------- -- line 287 ---------------------------------------- . #[derive(Clone)] . pub struct TokenStreamIter { . cursor: tokenstream::Cursor, . stack: Vec>, . } . . #[derive(Clone)] . pub struct Group { 12,398 ( 0.00%) delimiter: Delimiter, 12,398 ( 0.00%) stream: TokenStream, . span: DelimSpan, . /// A hack used to pass AST fragments to attribute and derive macros . /// as a single nonterminal token instead of a token stream. . /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345). . flatten: bool, . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct Punct { 591,820 ( 0.01%) ch: char, . // NB. not using `Spacing` here because it doesn't implement `Hash`. 1,412,488 ( 0.01%) joint: bool, 273,556 ( 0.00%) span: Span, . } . . impl Punct { . fn new(ch: char, joint: bool, span: Span) -> Punct { . const LEGAL_CHARS: &[char] = &[ . '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';', . ':', '#', '$', '?', '\'', . ]; . if !LEGAL_CHARS.contains(&ch) { . panic!("unsupported character `{:?}`", ch) . } . Punct { ch, joint, span } 781,709 ( 0.01%) } . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct Ident { 470,421 ( 0.00%) sym: Symbol, 526,236 ( 0.00%) is_raw: bool, 91,595 ( 0.00%) span: Span, . } . . impl Ident { 1,105,750 ( 0.01%) fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident { 884,600 ( 0.01%) let sym = nfc_normalize(sym.as_str()); 331,725 ( 0.00%) let string = sym.as_str(); 552,875 ( 0.00%) if !rustc_lexer::is_ident(string) { . panic!("`{:?}` is not a valid identifier", string) . } 221,150 ( 0.00%) if is_raw && !sym.can_be_raw() { . panic!("`{}` cannot be a raw identifier", string); . } 552,875 ( 0.00%) sess.symbol_gallery.insert(sym, span); 110,575 ( 0.00%) Ident { sym, is_raw, span } 1,548,050 ( 0.01%) } . fn dollar_crate(span: Span) -> Ident { . // `$crate` is accepted as an ident only if it comes from the compiler. . Ident { sym: kw::DollarCrate, is_raw: false, span } . } . } . . // FIXME(eddyb) `Literal` should not expose internal `Debug` impls. . #[derive(Clone, Debug)] -- line 352 ---------------------------------------- -- line 360 ---------------------------------------- . def_site: Span, . call_site: Span, . mixed_site: Span, . krate: CrateNum, . rebased_spans: FxHashMap, . } . . impl<'a, 'b> Rustc<'a, 'b> { 585 ( 0.00%) pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self { 260 ( 0.00%) let expn_data = ecx.current_expansion.id.expn_data(); 325 ( 0.00%) Rustc { 65 ( 0.00%) def_site: ecx.with_def_site_ctxt(expn_data.def_site), 65 ( 0.00%) call_site: ecx.with_call_site_ctxt(expn_data.call_site), . mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site), 65 ( 0.00%) krate: expn_data.macro_def_id.unwrap().krate, . rebased_spans: FxHashMap::default(), . ecx, . } 585 ( 0.00%) } . . fn sess(&self) -> &ParseSess { . self.ecx.parse_sess() . } . . fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option) -> Literal { 11,447 ( 0.00%) Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) } . } . } . . impl server::Types for Rustc<'_, '_> { . type FreeFunctions = FreeFunctions; . type TokenStream = TokenStream; . type TokenStreamBuilder = tokenstream::TokenStreamBuilder; . type TokenStreamIter = TokenStreamIter; -- line 393 ---------------------------------------- -- line 417 ---------------------------------------- . impl server::TokenStream for Rustc<'_, '_> { . fn new(&mut self) -> Self::TokenStream { . TokenStream::default() . } . fn is_empty(&mut self, stream: &Self::TokenStream) -> bool { . stream.is_empty() . } . fn from_str(&mut self, src: &str) -> Self::TokenStream { 56,966 ( 0.00%) parse_stream_from_source_str( 16,276 ( 0.00%) FileName::proc_macro_source_code(src), . src.to_string(), 16,276 ( 0.00%) self.sess(), 8,138 ( 0.00%) Some(self.call_site), . ) . } . fn to_string(&mut self, stream: &Self::TokenStream) -> String { 232,296 ( 0.00%) pprust::tts_to_string(stream) . } . fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result { . // Parse the expression from our tokenstream. . let expr: PResult<'_, _> = try { . let mut p = rustc_parse::stream_to_parser( . self.sess(), . stream.clone(), . Some("proc_macro expand expr"), -- line 441 ---------------------------------------- -- line 479 ---------------------------------------- . }, . _ => Err(()), . } . } . fn from_token_tree( . &mut self, . tree: TokenTree, . ) -> Self::TokenStream { 3,504,248 ( 0.03%) tree.to_internal() . } . fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter { 8,475 ( 0.00%) TokenStreamIter { cursor: stream.trees(), stack: vec![] } . } . } . . impl server::TokenStreamBuilder for Rustc<'_, '_> { . fn new(&mut self) -> Self::TokenStreamBuilder { 99,828 ( 0.00%) tokenstream::TokenStreamBuilder::new() . } . fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) { 1,463,016 ( 0.01%) builder.push(stream); . } . fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream { 399,312 ( 0.00%) builder.build() . } . } . . impl server::TokenStreamIter for Rustc<'_, '_> { 1,074,630 ( 0.01%) fn next( . &mut self, . iter: &mut Self::TokenStreamIter, . ) -> Option> { . loop { 63,167 ( 0.00%) let tree = iter.stack.pop().or_else(|| { 197,262 ( 0.00%) let next = iter.cursor.next_with_spacing()?; 1,088,301 ( 0.01%) Some(TokenTree::from_internal((next, &mut iter.stack, self))) . })?; . // A hack used to pass AST fragments to attribute and derive macros . // as a single nonterminal token instead of a token stream. . // Such token needs to be "unwrapped" and not represented as a delimited group. . // FIXME: It needs to be removed, but there are some compatibility issues (see #73345). 152,744 ( 0.00%) if let TokenTree::Group(ref group) = tree { . if group.flatten { . iter.cursor.append(group.stream.clone()); . continue; . } . } 694,837 ( 0.01%) return Some(tree); . } 573,136 ( 0.01%) } . } . . impl server::Group for Rustc<'_, '_> { . fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group { . Group { . delimiter, 53,428 ( 0.00%) stream, 53,428 ( 0.00%) span: DelimSpan::from_single(server::Span::call_site(self)), . flatten: false, . } . } . fn delimiter(&mut self, group: &Self::Group) -> Delimiter { . group.delimiter . } . fn stream(&mut self, group: &Self::Group) -> Self::TokenStream { 6,273 ( 0.00%) group.stream.clone() . } . fn span(&mut self, group: &Self::Group) -> Self::Span { 22,872 ( 0.00%) group.span.entire() . } . fn span_open(&mut self, group: &Self::Group) -> Self::Span { 148 ( 0.00%) group.span.open . } . fn span_close(&mut self, group: &Self::Group) -> Self::Span { 4,642 ( 0.00%) group.span.close . } . fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) { 66,004 ( 0.00%) group.span = DelimSpan::from_single(span); . } . } . . impl server::Punct for Rustc<'_, '_> { 132,508 ( 0.00%) fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct { . Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self)) 265,016 ( 0.00%) } . fn as_char(&mut self, punct: Self::Punct) -> char { . punct.ch . } . fn spacing(&mut self, punct: Self::Punct) -> Spacing { 51,134 ( 0.00%) if punct.joint { Spacing::Joint } else { Spacing::Alone } . } . fn span(&mut self, punct: Self::Punct) -> Self::Span { 25,567 ( 0.00%) punct.span . } . fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct { . Punct { span, ..punct } 927,556 ( 0.01%) } . } . . impl server::Ident for Rustc<'_, '_> { . fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident { 1,529,847 ( 0.01%) Ident::new(self.sess(), Symbol::intern(string), is_raw, span) . } . fn span(&mut self, ident: Self::Ident) -> Self::Span { 27,043 ( 0.00%) ident.span . } . fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident { . Ident { span, ..ident } 43,988 ( 0.00%) } . } . . impl server::Literal for Rustc<'_, '_> { . fn from_str(&mut self, s: &str) -> Result { . let name = FileName::proc_macro_source_code(s); . let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned()); . . let first_span = parser.token.span.data(); -- line 595 ---------------------------------------- -- line 645 ---------------------------------------- . } . fn suffix(&mut self, literal: &Self::Literal) -> Option { . literal.lit.suffix.as_ref().map(Symbol::to_string) . } . fn integer(&mut self, n: &str) -> Self::Literal { . self.lit(token::Integer, Symbol::intern(n), None) . } . fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal { 8,844 ( 0.00%) self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind))) . } . fn float(&mut self, n: &str) -> Self::Literal { . self.lit(token::Float, Symbol::intern(n), None) . } . fn f32(&mut self, n: &str) -> Self::Literal { . self.lit(token::Float, Symbol::intern(n), Some(sym::f32)) . } . fn f64(&mut self, n: &str) -> Self::Literal { . self.lit(token::Float, Symbol::intern(n), Some(sym::f64)) . } 6,552 ( 0.00%) fn string(&mut self, string: &str) -> Self::Literal { . let mut escaped = String::new(); . for ch in string.chars() { . escaped.extend(ch.escape_debug()); . } 728 ( 0.00%) self.lit(token::Str, Symbol::intern(&escaped), None) 6,552 ( 0.00%) } . fn character(&mut self, ch: char) -> Self::Literal { . let mut escaped = String::new(); . escaped.extend(ch.escape_unicode()); . self.lit(token::Char, Symbol::intern(&escaped), None) . } 390 ( 0.00%) fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal { . let string = bytes . .iter() . .cloned() . .flat_map(ascii::escape_default) . .map(Into::::into) . .collect::(); 130 ( 0.00%) self.lit(token::ByteStr, Symbol::intern(&string), None) 390 ( 0.00%) } . fn span(&mut self, literal: &Self::Literal) -> Self::Span { 632 ( 0.00%) literal.span . } . fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) { 738 ( 0.00%) literal.span = span; . } . fn subspan( . &mut self, . literal: &Self::Literal, . start: Bound, . end: Bound, . ) -> Option { . let span = literal.span; -- line 697 ---------------------------------------- -- line 782 ---------------------------------------- . } else { . format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0) . } . } . fn def_site(&mut self) -> Self::Span { . self.def_site . } . fn call_site(&mut self) -> Self::Span { 322,185 ( 0.00%) self.call_site . } . fn mixed_site(&mut self) -> Self::Span { . self.mixed_site . } . fn source_file(&mut self, span: Self::Span) -> Self::SourceFile { . self.sess().source_map().lookup_char_pos(span.lo()).file . } . fn parent(&mut self, span: Self::Span) -> Option { -- line 798 ---------------------------------------- -- line 864 ---------------------------------------- . // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding, . // replace it with a def-site context until we are encoding it properly. . resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt()) . }) . } . } . . // See issue #74616 for details 2,992 ( 0.00%) fn ident_name_compatibility_hack( . nt: &Nonterminal, . orig_span: Span, . rustc: &mut Rustc<'_, '_>, . ) -> Option<(rustc_span::symbol::Ident, bool)> { 748 ( 0.00%) if let NtIdent(ident, is_raw) = nt { 1,144 ( 0.00%) if let ExpnKind::Macro(_, macro_name) = orig_span.ctxt().outer_expn_data().kind { 572 ( 0.00%) let source_map = rustc.sess().source_map(); 858 ( 0.00%) let filename = source_map.span_to_filename(orig_span); 4,004 ( 0.00%) if let FileName::Real(RealFileName::LocalPath(path)) = filename { 3,432 ( 0.00%) let matches_prefix = |prefix, filename| { . // Check for a path that ends with 'prefix*/src/' 1,144 ( 0.00%) let mut iter = path.components().rev(); 3,432 ( 0.00%) iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename) 2,860 ( 0.00%) && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src") . && iter . .next() . .and_then(|p| p.as_os_str().to_str()) . .map_or(false, |p| p.starts_with(prefix)) 2,002 ( 0.00%) }; . . let time_macros_impl = 572 ( 0.00%) macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs"); 2,002 ( 0.00%) let js_sys = macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs"); 1,144 ( 0.00%) if time_macros_impl || js_sys { . let snippet = source_map.span_to_snippet(orig_span); . if snippet.as_deref() == Ok("$name") { . if time_macros_impl { . rustc.sess().buffer_lint_with_diagnostic( . &PROC_MACRO_BACK_COMPAT, . orig_span, . ast::CRATE_NODE_ID, . "using an old version of `time-macros-impl`", -- line 904 ---------------------------------------- -- line 933 ---------------------------------------- . ); . return Some((*ident, *is_raw)); . } . } . } . } . } . 286 ( 0.00%) if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") { . let snippet = source_map.span_to_snippet(orig_span); . if snippet.as_deref() == Ok("$T") { . if let FileName::Real(RealFileName::LocalPath(macro_path)) = . source_map.span_to_filename(rustc.def_site) . { . if macro_path.to_string_lossy().contains("pin-project-internal-0.") { . rustc.sess().buffer_lint_with_diagnostic( . &PROC_MACRO_BACK_COMPAT, -- line 949 ---------------------------------------- -- line 958 ---------------------------------------- . } . } . } . } . } . } . } . None 4,862 ( 0.00%) } 4,705,634 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . PushRegionObligation, . } . . macro_rules! impl_from { . ($($ctor: ident ($ty: ty),)*) => { . $( . impl<'tcx> From<$ty> for UndoLog<'tcx> { . fn from(x: $ty) -> Self { 1,454 ( 0.00%) UndoLog::$ctor(x.into()) . } . } . )* . } . } . . // Upcast from a single kind of "undoable action" to the general enum . impl_from! { -- line 44 ---------------------------------------- -- line 57 ---------------------------------------- . ConstUnificationTable(sv::UndoLog>>), . . RegionUnificationTable(sv::UndoLog>>), . ProjectionCache(traits::UndoLog<'tcx>), . } . . /// The Rollback trait defines how to rollback a particular action. . impl<'tcx> Rollback> for InferCtxtInner<'tcx> { 1,363,065 ( 0.01%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 2,271,775 ( 0.02%) match undo { 1,547,800 ( 0.01%) UndoLog::TypeVariables(undo) => self.type_variable_storage.reverse(undo), 420 ( 0.00%) UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo), 266 ( 0.00%) UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo), . UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo), . UndoLog::RegionConstraintCollector(undo) => { 1,137,339 ( 0.01%) self.region_constraint_storage.as_mut().unwrap().reverse(undo) . } . UndoLog::RegionUnificationTable(undo) => { 273,074 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().unification_table.reverse(undo) . } . UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo), . UndoLog::PushRegionObligation => { . self.region_obligations.pop(); . } . } 1,817,420 ( 0.02%) } . } . . /// The combined undo log for all the various unification tables. For each change to the storage . /// for any kind of inference variable, we record an UndoLog entry in the vector here. . pub(crate) struct InferCtxtUndoLogs<'tcx> { . logs: Vec>, . num_open_snapshots: usize, . } . . impl Default for InferCtxtUndoLogs<'_> { . fn default() -> Self { 93,486 ( 0.00%) Self { logs: Default::default(), num_open_snapshots: Default::default() } . } . } . . /// The UndoLogs trait defines how we undo a particular kind of action (of type T). We can undo any . /// action that is convertable into an UndoLog (per the From impls above). . impl<'tcx, T> UndoLogs for InferCtxtUndoLogs<'tcx> . where . UndoLog<'tcx>: From, -- line 102 ---------------------------------------- -- line 103 ---------------------------------------- . { . #[inline] . fn num_open_snapshots(&self) -> usize { . self.num_open_snapshots . } . . #[inline] . fn push(&mut self, undo: T) { 348,484 ( 0.00%) if self.in_snapshot() { 11,632 ( 0.00%) self.logs.push(undo.into()) . } . } . . fn clear(&mut self) { . self.logs.clear(); . self.num_open_snapshots = 0; . } . -- line 120 ---------------------------------------- -- line 125 ---------------------------------------- . { . if self.in_snapshot() { . self.logs.extend(undos.into_iter().map(UndoLog::from)) . } . } . } . . impl<'tcx> InferCtxtInner<'tcx> { 909,546 ( 0.01%) pub fn rollback_to(&mut self, snapshot: Snapshot<'tcx>) { . debug!("rollback_to({})", snapshot.undo_len); . self.undo_log.assert_open_snapshot(&snapshot); . 1,666,247 ( 0.01%) while self.undo_log.logs.len() > snapshot.undo_len { . let undo = self.undo_log.logs.pop().unwrap(); 5,452,260 ( 0.05%) self.reverse(undo); . } . 404,731 ( 0.00%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 89,746 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 499,646 ( 0.00%) self.undo_log.num_open_snapshots -= 1; 1,061,137 ( 0.01%) } . . pub fn commit(&mut self, snapshot: Snapshot<'tcx>) { . debug!("commit({})", snapshot.undo_len); . 691,959 ( 0.01%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 196,386 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 790,152 ( 0.01%) self.undo_log.num_open_snapshots -= 1; . } . } . . impl<'tcx> InferCtxtUndoLogs<'tcx> { . pub fn start_snapshot(&mut self) -> Snapshot<'tcx> { 1,528,976 ( 0.01%) self.num_open_snapshots += 1; . Snapshot { undo_len: self.logs.len(), _marker: PhantomData } . } . . pub(crate) fn region_constraints_in_snapshot( . &self, . s: &Snapshot<'tcx>, . ) -> impl Iterator> + Clone { 15,979 ( 0.00%) self.logs[s.undo_len..].iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . pub(crate) fn region_constraints( . &self, . ) -> impl Iterator> + Clone { 17 ( 0.00%) self.logs.iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) { . // Failures here may indicate a failure to follow a stack discipline. 454,773 ( 0.00%) assert!(self.logs.len() >= snapshot.undo_len); 454,773 ( 0.00%) assert!(self.num_open_snapshots > 0); . } . } . . impl<'tcx> std::ops::Index for InferCtxtUndoLogs<'tcx> { . type Output = UndoLog<'tcx>; . . fn index(&self, key: usize) -> &Self::Output { . &self.logs[key] -- line 204 ---------------------------------------- 983,537 ( 0.01%) -------------------------------------------------------------------------------- -- 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,072,413 ( 0.01%) fn drop(&mut self) { . drop(unsafe { ptr::read(self) }.into_iter()) 1,131,209 ( 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(); . 13 ( 0.00%) out_node.push(k.clone(), v.clone()); 33 ( 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 { 603,537 ( 0.01%) 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,019,038 ( 0.01%) let root_node = self.root.as_ref()?.reborrow(); 4,525,278 ( 0.04%) 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.01%) let root_node = self.root.as_mut()?.borrow_mut(); 4,035,871 ( 0.04%) 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,523,974 ( 0.08%) pub fn insert(&mut self, key: K, value: V) -> Option . where . K: Ord, . { . match self.entry(key) { . Occupied(mut entry) => Some(entry.insert(value)), . Vacant(entry) => { 10,707,439 ( 0.10%) entry.insert(value); 293,632 ( 0.00%) None . } . } 7,491,058 ( 0.07%) } . . /// 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,482,828 ( 0.01%) pub fn remove(&mut self, key: &Q) -> Option . where . K: Borrow + Ord, . Q: Ord, . { 2,130,201 ( 0.02%) self.remove_entry(key).map(|(_, v)| v) 1,762,777 ( 0.02%) } . . /// 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,029,992 ( 0.01%) let root_node = map.root.as_mut()?.borrow_mut(); 2,695,118 ( 0.02%) match root_node.search_tree(key) { . Found(handle) => { 8,145,299 ( 0.07%) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) 197,204 ( 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(); 363,624 ( 0.00%) match root_node.search_tree(&key) { 8,016 ( 0.00%) Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), . GoDown(handle) => { 83,962 ( 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); . 10 ( 0.00%) fn next(&mut self) -> Option<(&'a K, &'a V)> { 576,853 ( 0.01%) if self.length == 0 { . None . } else { 230,987 ( 0.00%) self.length -= 1; . Some(unsafe { self.range.next_unchecked() }) . } 16 ( 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); 449,822 ( 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 { 514,337 ( 0.00%) IntoIter { range: LazyLeafRange::none(), length: 0 } . } . } . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . impl Drop for IntoIter { 28,022 ( 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() }; . } . } . } . 659,624 ( 0.01%) 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); . } 28,022 ( 0.00%) } . } . . impl IntoIter { . /// Core of a `next` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. 761,690 ( 0.01%) fn dying_next( . &mut self, . ) -> Option, marker::KV>> { 884,570 ( 0.01%) if self.length == 0 { . self.range.deallocating_end(); 150,066 ( 0.00%) None . } else { 240,214 ( 0.00%) self.length -= 1; 138,561 ( 0.00%) Some(unsafe { self.range.deallocating_next_unchecked() }) . } 761,687 ( 0.01%) } . . /// 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); . 3,906 ( 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() }) 4,464 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { 424 ( 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> { 8 ( 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> { 790,153 ( 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,713 ( 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 { 70,247 ( 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,374,596 ( 0.03%) -------------------------------------------------------------------------------- -- 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,389 ( 0.07%) 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,249 ( 0.15%) if i + 1 < len { . // SAFETY: same as above. 8,352,753 ( 0.07%) out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); 4,156,170 ( 0.04%) i += 2 . } 9,282,718 ( 0.08%) if i < len { . // SAFETY: same as above. 13,367,215 ( 0.12%) 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,027 ( 0.09%) self.length += length; . 8,470 ( 0.00%) let mut needed = 0; . 10,049,799 ( 0.09%) if self.ntail != 0 { 5,116,475 ( 0.05%) needed = 8 - self.ntail; . // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length` 25,545,322 ( 0.23%) self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); 5,094,835 ( 0.05%) if length < needed { 3,503,526 ( 0.03%) self.ntail += length; . return; . } else { 804,157 ( 0.01%) self.state.v3 ^= self.tail; 4,497 ( 0.00%) S::c_rounds(&mut self.state); 1,603,817 ( 0.01%) self.state.v0 ^= self.tail; 801,159 ( 0.01%) self.ntail = 0; . } . } . . // Buffered tail is now flushed, process new input. 2,916,595 ( 0.03%) let len = length - needed; 2,900,577 ( 0.03%) let left = len & 0x7; // len % 8 . 10,686 ( 0.00%) let mut i = needed; 4,452,727 ( 0.04%) 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,059 ( 0.03%) 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.04%) 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,650 ( 0.10%) compress!(state); 21,408 ( 0.00%) } . . #[inline] 7,572 ( 0.00%) fn d_rounds(state: &mut State) { 3,338,752 ( 0.03%) compress!(state); 3,338,752 ( 0.03%) 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,402 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs -------------------------------------------------------------------------------- Ir -- line 29 ---------------------------------------- . /// ``` . /// let s: &str = "Follow the rabbit"; . /// let ptr: *const u8 = s.as_ptr(); . /// assert!(!ptr.is_null()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")] . #[inline] 4,440,476 ( 0.04%) pub const fn is_null(self) -> bool { . // Compare via a cast to a thin pointer, so fat pointers are only . // considering their "data" part for null-ness. 4,440,476 ( 0.04%) (self as *const u8).guaranteed_eq(null()) 4,440,476 ( 0.04%) } . . /// Casts to a pointer of another type. . #[stable(feature = "ptr_cast", since = "1.38.0")] . #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")] . #[inline] 988,362 ( 0.01%) pub const fn cast(self) -> *const U { . self as _ 658,908 ( 0.01%) } . . /// Changes constness without changing the type. . /// . /// This is a bit safer than `as` because it wouldn't silently change the type if the code is . /// refactored. . #[unstable(feature = "ptr_const_cast", issue = "92675")] . #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")] . pub const fn as_mut(self) -> *mut T { -- line 57 ---------------------------------------- -- line 287 ---------------------------------------- . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const unsafe fn offset(self, count: isize) -> *const T . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. 30,691,700 ( 0.28%) unsafe { intrinsics::offset(self, count) } . } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 303 ---------------------------------------- -- line 436 ---------------------------------------- . /// // they point to the same address! . /// unsafe { . /// let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior . /// } . /// ``` . #[stable(feature = "ptr_offset_from", since = "1.47.0")] . #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "92980")] . #[inline] 89,740 ( 0.00%) pub const unsafe fn offset_from(self, origin: *const T) -> isize . where . T: Sized, . { 17,948 ( 0.00%) let pointee_size = mem::size_of::(); 233,324 ( 0.00%) assert!(0 < pointee_size && pointee_size <= isize::MAX as usize); . // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`. 4,574,371 ( 0.04%) unsafe { intrinsics::ptr_offset_from(self, origin) } 35,896 ( 0.00%) } . . /// Returns whether two pointers are guaranteed to be equal. . /// . /// At runtime this function behaves like `self == other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine equality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be equal. . /// But when it returns `true`, the pointers are guaranteed to be equal. -- line 460 ---------------------------------------- -- line 470 ---------------------------------------- . /// affect the outcome, but just the performance. . /// The consequences of using this method to make runtime and compile-time code behave . /// differently have not been explored. This method should not be used to introduce such . /// differences, and it should also not be stabilized before we have a better understanding . /// of this issue. . #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[inline] 3,330,357 ( 0.03%) pub const fn guaranteed_eq(self, other: *const T) -> bool . where . T: Sized, . { 6,660,872 ( 0.06%) intrinsics::ptr_guaranteed_eq(self, other) 4,440,476 ( 0.04%) } . . /// Returns whether two pointers are guaranteed to be unequal. . /// . /// At runtime this function behaves like `self != other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine the inequality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be unequal. . /// But when it returns `true`, the pointers are guaranteed to be unequal. -- line 491 ---------------------------------------- -- line 569 ---------------------------------------- . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const unsafe fn add(self, count: usize) -> Self . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . unsafe { self.offset(count as isize) } 5,549 ( 0.00%) } . . /// Calculates the offset from a pointer (convenience for . /// `.offset((count as isize).wrapping_neg())`). . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 585 ---------------------------------------- -- line 886 ---------------------------------------- . /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`]. . /// . /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples. . /// . /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping() . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[inline] 5,040 ( 0.00%) pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize) . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`. 1,260 ( 0.00%) unsafe { copy_nonoverlapping(self, dest, count) } 2,520 ( 0.00%) } . . /// Computes the offset that needs to be applied to the pointer in order to make it aligned to . /// `align`. . /// . /// If it is not possible to align the pointer, the implementation returns . /// `usize::MAX`. It is permissible for the implementation to *always* . /// return `usize::MAX`. Only your algorithm's performance can depend . /// on getting a usable offset here, not its correctness. -- line 908 ---------------------------------------- -- line 983 ---------------------------------------- . /// use std::ptr; . /// . /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); . /// assert_eq!(slice.len(), 3); . /// ``` . #[inline] . #[unstable(feature = "slice_ptr_len", issue = "71146")] . #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")] 12,996 ( 0.00%) pub const fn len(self) -> usize { 8,664 ( 0.00%) metadata(self) 8,664 ( 0.00%) } . . /// Returns a raw pointer to the slice's buffer. . /// . /// This is equivalent to casting `self` to `*const T`, but more type-safe. . /// . /// # Examples . /// . /// ```rust -- line 1001 ---------------------------------------- -- line 1003 ---------------------------------------- . /// use std::ptr; . /// . /// let slice: *const [i8] = ptr::slice_from_raw_parts(ptr::null(), 3); . /// assert_eq!(slice.as_ptr(), 0 as *const i8); . /// ``` . #[inline] . #[unstable(feature = "slice_ptr_get", issue = "74265")] . #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] 402,016 ( 0.00%) pub const fn as_ptr(self) -> *const T { . self as *const T 201,008 ( 0.00%) } . . /// Returns a raw pointer to an element or subslice, without doing bounds . /// checking. . /// . /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable . /// is *[undefined behavior]* even if the resulting pointer is not used. . /// . /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html -- line 1021 ---------------------------------------- 4,917,505 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter.rs -------------------------------------------------------------------------------- Ir -- line 79 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Sync for Iter<'_, T> {} . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Send for Iter<'_, T> {} . . impl<'a, T> Iter<'a, T> { . #[inline] 1,367,928 ( 0.01%) pub(super) fn new(slice: &'a [T]) -> Self { 1,025,946 ( 0.01%) let ptr = slice.as_ptr(); . // SAFETY: Similar to `IterMut::new`. . unsafe { 341,982 ( 0.00%) assume(!ptr.is_null()); . 1,709,910 ( 0.02%) let end = if mem::size_of::() == 0 { . (ptr as *const u8).wrapping_add(slice.len()) as *const T . } else { 341,982 ( 0.00%) ptr.add(slice.len()) . }; . 2,699,049 ( 0.02%) Self { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: PhantomData } . } 1,367,928 ( 0.01%) } . . /// Views the underlying data as a subslice of the original data. . /// . /// This has the same lifetime as the original slice, and so the . /// iterator can continue to be used while this exists. . /// . /// # Examples . /// -- line 109 ---------------------------------------- -- line 121 ---------------------------------------- . /// . /// // Next, we move to the second element of the slice: . /// iter.next(); . /// // Now `as_slice` returns "[2, 3]": . /// println!("{:?}", iter.as_slice()); . /// ``` . #[must_use] . #[stable(feature = "iter_to_slice", since = "1.4.0")] 111,176 ( 0.00%) pub fn as_slice(&self) -> &'a [T] { 298,557 ( 0.00%) self.make_slice() 55,588 ( 0.00%) } . } . . iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, { . fn is_sorted_by(self, mut compare: F) -> bool . where . Self: Sized, . F: FnMut(&Self::Item, &Self::Item) -> Option, . { -- line 139 ---------------------------------------- -- line 141 ---------------------------------------- . compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false) . }) . } . }} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Iter<'_, T> { . fn clone(&self) -> Self { 96,196 ( 0.00%) Iter { ptr: self.ptr, end: self.end, _marker: self._marker } . } . } . . #[stable(feature = "slice_iter_as_ref", since = "1.13.0")] . impl AsRef<[T]> for Iter<'_, T> { . fn as_ref(&self) -> &[T] { . self.as_slice() . } -- line 157 ---------------------------------------- -- line 199 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Sync for IterMut<'_, T> {} . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl Send for IterMut<'_, T> {} . . impl<'a, T> IterMut<'a, T> { . #[inline] 2,808 ( 0.00%) pub(super) fn new(slice: &'a mut [T]) -> Self { 2,106 ( 0.00%) let ptr = slice.as_mut_ptr(); . // SAFETY: There are several things here: . // . // `ptr` has been obtained by `slice.as_ptr()` where `slice` is a valid . // reference thus it is non-NUL and safe to use and pass to . // `NonNull::new_unchecked` . . // . // Adding `slice.len()` to the starting pointer gives a pointer . // at the end of `slice`. `end` will never be dereferenced, only checked -- line 216 ---------------------------------------- -- line 218 ---------------------------------------- . // done. . // . // In the case of a ZST, the end pointer is just the start pointer plus . // the length, to also allows for the fast `ptr == end` check. . // . // See the `next_unchecked!` and `is_empty!` macros as well as the . // `post_inc_start` method for more information. . unsafe { 702 ( 0.00%) assume(!ptr.is_null()); . 3,510 ( 0.00%) let end = if mem::size_of::() == 0 { . (ptr as *mut u8).wrapping_add(slice.len()) as *mut T . } else { 702 ( 0.00%) ptr.add(slice.len()) . }; . 16,113 ( 0.00%) Self { ptr: NonNull::new_unchecked(ptr), end, _marker: PhantomData } . } 2,808 ( 0.00%) } . . /// Views the underlying data as a subslice of the original data. . /// . /// To avoid creating `&mut` references that alias, this is forced . /// to consume the iterator. . /// . /// # Examples . /// -- line 244 ---------------------------------------- -- line 1711 ---------------------------------------- . v: &'a [T], . rem: &'a [T], . chunk_size: usize, . } . . impl<'a, T> ChunksExact<'a, T> { . #[inline] . pub(super) fn new(slice: &'a [T], chunk_size: usize) -> Self { 6 ( 0.00%) let rem = slice.len() % chunk_size; 9 ( 0.00%) let fst_len = slice.len() - rem; . // SAFETY: 0 <= fst_len <= slice.len() by construction above . let (fst, snd) = unsafe { slice.split_at_unchecked(fst_len) }; . Self { v: fst, rem: snd, chunk_size } . } . . /// Returns the remainder of the original slice that is not going to be . /// returned by the iterator. The returned slice has at most `chunk_size-1` . /// elements. -- line 1728 ---------------------------------------- -- line 1742 ---------------------------------------- . } . . #[stable(feature = "chunks_exact", since = "1.31.0")] . impl<'a, T> Iterator for ChunksExact<'a, T> { . type Item = &'a [T]; . . #[inline] . fn next(&mut self) -> Option<&'a [T]> { 9,408 ( 0.00%) if self.v.len() < self.chunk_size { . None . } else { . let (fst, snd) = self.v.split_at(self.chunk_size); . self.v = snd; . Some(fst) . } . } . -- line 1758 ---------------------------------------- -- line 2034 ---------------------------------------- . } . . #[unstable(feature = "array_windows", issue = "75027")] . impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> { . type Item = &'a [T; N]; . . #[inline] . fn next(&mut self) -> Option { 55,725 ( 0.00%) if self.num == 0 { . return None; . } . // SAFETY: . // This is safe because it's indexing into a slice guaranteed to be length > N. . let ret = unsafe { &*self.slice_head.cast::<[T; N]>() }; . // SAFETY: Guaranteed that there are at least 1 item remaining otherwise . // earlier branch would've been hit . self.slice_head = unsafe { self.slice_head.add(1) }; -- line 2050 ---------------------------------------- 3,736,597 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . #[inline] . pub fn $fn_name( . out: &mut [::std::mem::MaybeUninit; max_leb128_len!($int_ty)], . mut value: $int_ty, . ) -> &[u8] { . let mut i = 0; . . loop { 1,836,670 ( 0.02%) if value < 0x80 { . unsafe { 728,310 ( 0.01%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 975,414 ( 0.01%) i += 1; . break; . } else { . unsafe { 1,148,208 ( 0.01%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 450,201 ( 0.00%) value >>= 7; . i += 1; . } . } . . unsafe { ::std::mem::MaybeUninit::slice_assume_init_ref(&out.get_unchecked(..i)) } . } . }; . } -- line 45 ---------------------------------------- -- line 53 ---------------------------------------- . macro_rules! impl_read_unsigned_leb128 { . ($fn_name:ident, $int_ty:ty) => { . #[inline] . pub fn $fn_name(slice: &[u8], position: &mut usize) -> $int_ty { . // The first iteration of this loop is unpeeled. This is a . // performance win because this code is hot and integer values less . // than 128 are very common, typically occurring 50-80% or more of . // the time, even for u64 and u128. 10,312,292 ( 0.09%) let byte = slice[*position]; 5,156,146 ( 0.05%) *position += 1; 5,156,146 ( 0.05%) if (byte & 0x80) == 0 { 88 ( 0.00%) return byte as $int_ty; . } 1,114 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 2,626,689 ( 0.02%) let byte = slice[*position]; 1,743,986 ( 0.02%) *position += 1; 1,751,126 ( 0.02%) if (byte & 0x80) == 0 { 1,383,974 ( 0.01%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 3,034,436 ( 0.03%) -------------------------------------------------------------------------------- -- 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,625 ( 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.03%) 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,884,978 ( 0.06%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; 599,531 ( 0.01%) 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`. 165,005 ( 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,600,684 ( 0.05%) 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.02%) 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 { 3,990,697 ( 0.04%) assume(!self.ptr.as_ptr().is_null()); 3,723,055 ( 0.03%) if mem::size_of::() != 0 { 1,914,602 ( 0.02%) assume(!self.end.is_null()); . } 183,676,584 ( 1.65%) if is_empty!(self) { 145,080 ( 0.00%) None . } else { 1,199,063 ( 0.01%) Some(next_unchecked!(self)) . } . } 2,233,833 ( 0.02%) } . . #[inline] 14,235 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 3,239,687 ( 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> { 128,861 ( 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,203 ( 0.00%) while let Some(x) = self.next() { 20,348 ( 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,662,505 ( 0.01%) while let Some(x) = self.next() { 10,895,697 ( 0.10%) 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