Skip to content

Precalculated attribute set hashes #1407

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions opentelemetry-sdk/src/attributes/set.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::{
cmp::Ordering,
Expand Down Expand Up @@ -104,13 +105,13 @@ impl Eq for HashKeyValue {}
///
/// This must implement [Hash], [PartialEq], and [Eq] so it may be used as
/// HashMap keys and other de-duplication methods.
#[derive(Clone, Default, Debug, Hash, PartialEq, Eq)]
pub struct AttributeSet(Vec<HashKeyValue>);
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct AttributeSet(Vec<HashKeyValue>, u64);

impl From<&[KeyValue]> for AttributeSet {
fn from(values: &[KeyValue]) -> Self {
let mut seen_keys = HashSet::with_capacity(values.len());
let mut vec = values
let vec = values
.iter()
.rev()
.filter_map(|kv| {
Expand All @@ -121,25 +122,34 @@ impl From<&[KeyValue]> for AttributeSet {
}
})
.collect::<Vec<_>>();
vec.sort_unstable();

AttributeSet(vec)
AttributeSet::new(vec)
}
}

impl From<&Resource> for AttributeSet {
fn from(values: &Resource) -> Self {
let mut vec = values
let vec = values
.iter()
.map(|(key, value)| HashKeyValue(KeyValue::new(key.clone(), value.clone())))
.collect::<Vec<_>>();
vec.sort_unstable();

AttributeSet(vec)
AttributeSet::new(vec)
}
}

impl AttributeSet {
fn new(mut values: Vec<HashKeyValue>) -> Self {
values.sort_unstable();
let mut hasher = DefaultHasher::new();
values.iter().fold(&mut hasher, |mut hasher, item| {
item.hash(&mut hasher);
hasher
});

AttributeSet(values, hasher.finish())
}

/// Returns the number of elements in the set.
pub fn len(&self) -> usize {
self.0.len()
Expand All @@ -163,3 +173,9 @@ impl AttributeSet {
self.0.iter().map(|kv| (&kv.0.key, &kv.0.value))
}
}

impl Hash for AttributeSet {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.1)
}
}