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

Experiment with Equivalent that takes self by value #257

Closed
wants to merge 3 commits into from

Conversation

cuviper
Copy link
Member

@cuviper cuviper commented Feb 7, 2023

@JustForFun88
Copy link

ref: #253 (comment)

Is it possible not to do this, please? That is, extracting the Equivalent trait in a separate crate is a cool idea. But accepting a key by value, not by reference, doesn't sound like a good idea to me.
See comment.

@stepancheg
Copy link
Contributor

stepancheg commented Feb 27, 2023

Even if we pass Equivalent trait by value, we should:

  • take self by reference
  • do not require Copy

The case is this.

Suppose we are implementing a function like:

struct Interner<T> { ... }

impl Interner<T> {
  fn intern(&self, q: Q) -> &'T
     where Q: Equivalent<T> + Into<T>
  {
    if let Some(value) = self.lookup(&q) {
      return value;
    } else {
      self.do_insert(value.into())
    }
  }
}

for example, if we want to intern

struct MyString(String)

interner.intern(MyString(...))

The idea is:

  • we want to preserve, not clone the MyString value when the value is not interned yet to avoid Clone, so we want Into , so we want to avoid Copy for Q
  • if we want to avoid Copy, we no longer can take self in equivalent

And if we take &self in Equivalent, we kill some perf gains of taking Q by value.

@cuviper
Copy link
Member Author

cuviper commented Feb 27, 2023

If you're calling lookup(&q), that seems to be a case where you'd want &Q: Equivalent<T> in the new design (and that probably needs the annoying HRTB for<'q> &'q Q: ...). The old design handles this fine.

And if we take &self in Equivalent, we kill some perf gains of taking Q by value.

I'm leaning towards not changing the trait, as the intended perf gains are only for a more niche use case, and come at a cost to ergonomics when more references and/or HRTB get involved.

For indexmap in particular, maybe instead we can add get_index_of_val(&self, Q), although I don't like calling it "val" when it's related to the key in a key-value map. It's no better as get_index_of_key given that get_index_of is also about the key. Maybe get_index_of_owned? Bikeshed aside, the point is that we can avoid a ton of duplication in the API -- having one new way to get an index then lets you follow up with shared/mut access in various ways.

@cuviper cuviper closed this Jun 6, 2023
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

Successfully merging this pull request may close these issues.

3 participants