-
Notifications
You must be signed in to change notification settings - Fork 231
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
tech-debt: Context lib #4060
Merged
tech-debt: Context lib #4060
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
[package] | ||
name = "context" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dependencies] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
use std::{ | ||
any::{Any, TypeId}, | ||
collections::HashMap, | ||
sync::{Arc, Mutex}, | ||
}; | ||
|
||
#[derive(Debug, Default)] | ||
pub struct Context { | ||
store: HashMap<(String, TypeId), Box<dyn Any>>, | ||
} | ||
|
||
impl Context { | ||
pub fn concurrent(self) -> Arc<Mutex<Context>> { | ||
Arc::new(Mutex::new(self)) | ||
} | ||
Comment on lines
+13
to
+15
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like that the |
||
|
||
pub fn insert<T: Any>(&mut self, key: &str, value: T) { | ||
self.store.insert((key.to_owned(), TypeId::of::<T>()), Box::new(value)); | ||
} | ||
|
||
pub fn get<T: Any>(&self, key: &str) -> Option<&T> { | ||
self.store | ||
.get(&(key.to_owned(), TypeId::of::<T>())) | ||
.map(|v| v.downcast_ref::<T>().unwrap()) | ||
} | ||
|
||
pub fn get_mut<T: Any>(&mut self, key: &str) -> Option<&mut T> { | ||
self.store | ||
.get_mut(&(key.to_owned(), TypeId::of::<T>())) | ||
.map(|v| v.downcast_mut::<T>().unwrap()) | ||
} | ||
|
||
pub fn remove<T: Any>(&mut self, key: &str) -> Option<T> { | ||
self.store | ||
.remove(&(key.to_owned(), TypeId::of::<T>())) | ||
.map(|v| *v.downcast::<T>().unwrap()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::Context; | ||
|
||
#[test] | ||
fn set_and_retrieve() { | ||
let mut ctx: Context = Context::default(); | ||
ctx.insert("foo", 42 as u32); | ||
|
||
let val: u32 = *ctx.get("foo").unwrap(); | ||
assert_eq!(val, 42 as u32) | ||
} | ||
|
||
#[test] | ||
fn concurrent() { | ||
let mut ctx: Context = Context::default(); | ||
ctx.insert("foo", 42 as u32); | ||
|
||
assert_eq!(42 as u32, *ctx.get::<u32>("foo").unwrap()); | ||
assert_eq!(None, ctx.get::<u32>("bar")); | ||
|
||
let safe_context = ctx.concurrent(); | ||
let mut ctx = safe_context.lock().unwrap(); | ||
ctx.insert("bar", 32 as u32); | ||
assert_eq!(32 as u32, *ctx.get::<u32>("bar").unwrap()); | ||
assert_eq!(42 as u32, *ctx.get::<u32>("foo").unwrap()); | ||
} | ||
|
||
#[test] | ||
fn get_mut() { | ||
let mut ctx: Context = Context::default(); | ||
ctx.insert("foo", 42 as u32); | ||
|
||
let val: &mut u32 = ctx.get_mut("foo").unwrap(); | ||
*val = 32 as u32; | ||
assert_eq!(32 as u32, *ctx.get::<u32>("foo").unwrap()); | ||
} | ||
|
||
#[test] | ||
fn remove() { | ||
let mut ctx: Context = Context::default(); | ||
ctx.insert("foo", 42 as u32); | ||
|
||
let val: u32 = ctx.remove("foo").unwrap(); | ||
assert_eq!(42 as u32, val); | ||
assert_eq!(None, ctx.get::<u32>("foo")); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we adopt something different than a
String
as a key type?I'd strive to avoid too many memory allocations just to retrieve dynamically populated values from
Context
. Could the key be represented a closed set type, like a numericenum
, whose static list is append-only (similar to the introspection warning codes list we had some months ago)?E.g.:
and
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
One can also try to extend this idea to
TypeId
as well, but I think that can happen in a future query and only if we see a noticeable slowdown in benchmarked performance.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No we can't sorry, if we had an enum then the enum has to be known by the context, thus making it coupled to it (which will be a very bad design decision) On top of that if this is passed down as owned value it won't be cloned so there would only be one allocation per key (in case it's not wrapped in an Arc)
What I will do in case needed, is to make it receive a &'static str as a key, as the users of context will identify the keys by name, but rather not prematurely optimize anything until I see how this is applied when refactoring (I have one in progress)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see. I was recommending intentionally coupling
Context
with its availableContextKeys
for the sake of avoiding String allocations, which have already bit us several times in the past: we risk usingString
s now just to replace them later. Considering this is a library for the Query Engine and not a general purpose crate, I’d find the coupling acceptable