Hacker News new | ask | show | jobs
by Const-me 3349 days ago
Technically, yes I can.

However, look at the Rust implementation of the LRU cache: https://github.com/contain-rs/linked-hash-map/blob/master/sr...

See how much code is there (more than 1k lines), and note most code is unsafe.

In C++, one would probably use list<pair<K,V>> for storage, together with unordered_map<K, list<pair<K,V>>::iterator> for indexing. And the implementation would be trivial, because there’s no need to re-implement a linked list, you only need to implement these get/set methods that update both collections at the same time.

In Rust however, they had to come up with their own implementation of linked list. The LinkedList from standard library doesn’t expose raw node pointers in the API, therefore it can’t be used for the job.

1 comments

Sure, but that's an oversight of the LinkedList API (which, honestly, was almost removed from std all-together, it's not exactly a shining beacon of API design) than some sort of inherent limitation of smart pointers, which seems to be what you're saying here.
I don’t think that was an oversight.

I think rust safety model prevents rust containers from returning mutable pointers to the contained items. Especially pointers to item's implementation details, like nodes of that linked lists.

And without raw pointers to items, you can’t easily compose containers to make higher-level data structures from them.

https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#met...

(That is, many data structure _do_ do this, and you _can_ do it. It is an oversight.)