Eine aufbereitete Darstellung der Quelle

 
     
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung
 
 
 
 

Benutzer

Quelle  raw.rs

  Sprache: Rust
 

#![allow(unsafe_code)]
//! This module encapsulates the `unsafe` access to `hashbrown::raw::RawTable`,
//! mostly in dealing with its bucket "pointers".

use super::{equivalent, get_hash, Bucket, HashValue, IndexMapCore};
use hashbrown::raw::RawTable;

type RawBucket = hashbrown::raw::Bucket<usize>;

/// Inserts many entries into a raw table without reallocating.
///
/// ***Panics*** if there is not sufficient capacity already.
pub(superfn insert_bulk_no_grow<K, V>(indices: &mut RawTable<usize>, entries: &[Bucket<K, V>]) {
    assert!(indices.capacity() - indices.len() >= entries.len());
    for entry in entries {
        // SAFETY: we asserted that sufficient capacity exists for all entries.
        unsafe {
            indices.insert_no_grow(entry.hash.get(), indices.len());
        }
    }
}

#[cfg(feature = "test_debug")]
pub(superstruct DebugIndices<'a>(pub &'a RawTable<usize>);

#[cfg(feature = "test_debug")]
impl core::fmt::Debug for DebugIndices<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // SAFETY: we're not letting any of the buckets escape this function
        let indices = unsafe { self.0.iter().map(|raw_bucket| *raw_bucket.as_ref()) };
        f.debug_list().entries(indices).finish()
    }
}

impl<K, V> IndexMapCore<K, V> {
    /// Sweep the whole table to erase indices start..end
    pub(superfn erase_indices_sweep(&mut self, start: usize, end: usize) {
        // SAFETY: we're not letting any of the buckets escape this function
        unsafe {
            let offset = end - start;
            for bucket in self.indices.iter() {
                let i = bucket.as_mut();
                if *i >= end {
                    *i -= offset;
                } else if *i >= start {
                    self.indices.erase(bucket);
                }
            }
        }
    }

    /// Search for a key in the table and return `Ok(entry_index)` if found.
    /// Otherwise, insert the key and return `Err(new_index)`.
    ///
    /// Note that hashbrown may resize the table to reserve space for insertion,
    /// even before checking if it's already present, so this is somewhat biased
    /// towards new items.
    pub(cratefn find_or_insert(&mut self, hash: HashValue, key: &K)&nbsp;-> Result<usize, usize>
    where
        K: Eq,
    {
        let hash = hash.get();
        let eq = equivalent(key, &self.entries);
        let hasher = get_hash(&self.entries);
        // SAFETY: We're not mutating between find and read/insert.
        unsafe {
            match self.indices.find_or_find_insert_slot(hash, eq, hasher) {
                Ok(raw_bucket) => Ok(*raw_bucket.as_ref()),
                Err(slot) => {
                    let index = self.indices.len();
                    self.indices.insert_in_slot(hash, slot, index);
                    Err(index)
                }
            }
        }
    }

    pub(superfn raw_entry(
        &mut self,
        hash: HashValue,
        mut is_match: impl FnMut(&K) -> bool,
    ) -> Result<RawTableEntry<'_, K, V>, &mut Self> {
        let entries = &*self.entries;
        let eq = move |&i: &usize| is_match(&entries[i].key);
        match self.indices.find(hash.get(), eq) {
            // SAFETY: The entry is created with a live raw bucket, at the same time
            // we have a &mut reference to the map, so it can not be modified further.
            Some(raw_bucket) => Ok(RawTableEntry {
                map: self,
                raw_bucket,
            }),
            None => Err(self),
        }
    }

    pub(superfn indices_mut(&mut self) -> impl Iterator<Item = &yle='color:red'>mut usize> {
        // SAFETY: we're not letting any of the buckets escape this function,
        // only the item references that are appropriately bound to `&mut self`.
        unsafe { self.indices.iter().map(|bucket| bucket.as_mut()) }
    }
}

/// A view into an occupied raw entry in an `IndexMap`.
// SAFETY: The lifetime of the map reference also constrains the raw bucket,
// which is essentially a raw pointer into the map indices.
pub(superstruct RawTableEntry<'a, K, V> {
    map: &'a mut IndexMapCore<K, V>,
    raw_bucket: RawBucket,
}

// `hashbrown::raw::Bucket` is only `Send`, not `Sync`.
// SAFETY: `&self` only accesses the bucket to read it.
unsafe impl<K: Sync, V: Sync> Sync for RawTableEntry<'_, K, V> {}

impl<'a, K, V> RawTableEntry<'a, K, V> {
    /// Return the index of the key-value pair
    #[inline]
    pub(superfn index(&self) -> usize {
        // SAFETY: we have `&mut map` keeping the bucket stable
        unsafe { *self.raw_bucket.as_ref() }
    }

    #[inline]
    pub(superfn bucket(&self) -> &Bucket<K, V> {
        &self.map.entries[self.index()]
    }

    #[inline]
    pub(superfn bucket_mut(&mut self) -> &mut Bucket<K, V> {
        let index = self.index();
        &mut self.map.entries[index]
    }

    #[inline]
    pub(superfn into_bucket(self) -> &'a mut Bucket<K, V> {
        let index = self.index();
        &mut self.map.entries[index]
    }

    /// Remove the index from indices, leaving the actual entries to the caller.
    pub(superfn remove_index(self) -> (&'a mut IndexMapCore<K, V>, usize) {
        // SAFETY: This is safe because it can only happen once (self is consumed)
        // and map.indices have not been modified since entry construction
        let (index, _slot) = unsafe { self.map.indices.remove(self.raw_bucket) };
        (self.map, index)
    }

    /// Take no action, just return the index and the original map reference.
    pub(superfn into_inner(self) -> (&'a mut IndexMapCore<K, V>, usize) {
        let index = self.index();
        (self.map, index)
    }
}

Messung V0.5 in Prozent
C=84 H=95 G=89

¤ Dauer der Verarbeitung: 0.0 Sekunden  (vorverarbeitet am  2026-06-19) ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

PVS Prover

Isabelle Prover

NIST Cobol Testsuite

Cephes Mathematical Library

Vienna Development Method

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.






                                                                                                                                                                                                                                                                                                                                                                                                     


Neuigkeiten

     Aktuelles
     Motto des Tages

Software

     Quellcodebibliothek
     Eigene Quellcodes
     Fremde Quellcodes
     Suchen

Aktivitäten

     Artikel über Sicherheit
     Anleitung zur Aktivierung von SSL

Muße

     Gedichte
     Musik
     Bilder

Jenseits des Üblichen ....

Besucherstatistik

Besucherstatistik