Skip to content
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

Alternative (immutable) semantics: "insert on read" #11

Open
rljacobson opened this issue Sep 7, 2020 · 1 comment
Open

Alternative (immutable) semantics: "insert on read" #11

rljacobson opened this issue Sep 7, 2020 · 1 comment

Comments

@rljacobson
Copy link
Contributor

rljacobson commented Sep 7, 2020

I have a use case where it would be convenient to insert the default value on a call to get() or on immutable index. For example, suppose you want to store RefCells in a DefaultHashMap. You would presumably use the immutable access methods for the same reason you are using a RefCell. But then any interior mutation of the RefCell actually mutates self.default.

You can't just insert the default value in get(), because get() borrows self immutably. You also can't just put the backing HashMap in a RefCell, either, because RefCell returns a RefMut that wouldn't outlive the call to get(), and thus the lifetime of the reference extracted from the RefMut can't outlive the call to get() and so can't be returned.

The way to do achieve this is to put the backing HashMap in a RefCell and then use Ref::map(), which gives a Ref object that can be returned:

pub fn get(&self, k: K) -> Ref<'_, V> {
	Ref::map(self.hash_map.borrow(), |hm| hm.get(k))
}

or something like that.

The user needs to choose the consequences of insert on read, or else they could end up accidentally trying to allocate the universe. Thus I propose the semantics be selectible, defaulting to insert on write. You'd have an enum:

// In the `default` module:
enum InsertSemantics {
	OnWrite,
	OnRead
}

// In the client code:
let mut map = defaultmap::HashMap::with_semantics(InsertSemantics::OnRead);
...
// Might as well make it settable:
map.set_semantics(InsertSemantics::OnWrite);

This is obviously a breaking change.

What do you think?

@JelteF
Copy link
Owner

JelteF commented Sep 11, 2020

Originally, I think I wanted to insert on reads as well. The problem was indeed that you only have a immutable reference, not an mutable one when calling get.

From your description it's still not entirely clear to me how you would implement it. If you can create a PR that shows it working, I'm definitely open to merging it. What the default should be I'm not sure yet. I guess it will matter a bit on the implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants