# Safely acquiring a pointer to one of the elements of a boxed slice

**URL:** <https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958>\
**Category:** help\
**Created:** [September 16, 2023, 5:09am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958 "2023-09-16T05:09:20Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![wallefan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/wallefan/32/33998_2.png) [@wallefan](https://users.rust-lang.org/u/wallefan)\
**Post date:** [September 16, 2023, 5:09am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/1 "2023-09-16T05:09:20Z")

</div>

I have a rather large boxed slice (~4M elements). Each element contains a string. I would like to build a hash map to allow me to index that slice by that string. To avoid duplicating ~4M strings and using up additional memory (and on the hardware I'm targeting, I care), I'd like the keys in my hashmap to point directly to those strings rather than being copies. I've already built an unsafe wrapper type around a \*const str that passes through `Hash` and `Eq`, and when building the hash map I simply iterate through the boxed slice, cast a reference to the string to that type, and insert it into my hash map as the key, with a \*const pointer to the element itself as the value. The boxed slice and the hash map containing raw pointers to it are both private members of a struct that the user then interacts with.

Is there something magical I need to do involving pinning in order for this to be sound, or is the fact that the boxed slice is a private member of the struct containing it sufficient to guarantee that its contents will not move unless I move them?

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [September 16, 2023, 5:16am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/2 "2023-09-16T05:16:27Z")

</div>

After reading this question 2-3 times I can confidently say it would benefit from some concrete code for illustration, especially to precisely explain the types involved.

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [September 16, 2023, 5:40am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/3 "2023-09-16T05:40:04Z")

</div>

I think I understand what you are trying to do. You are building a self-referential type.

> [@wallefan](#):
>
> Is there something magical I need to do involving pinning in order for this to be sound, or is the fact that the boxed slice is a private member of the struct containing it sufficient to guarantee that its contents will not move unless I move them?

Neither of the points you listed (privacy or pinning) has anything to do with whether this is sound. That has to do with the fact that `String` heap-allocates its backing buffer, therefore its address is stable. So as long as you don't modify the `String` in a way that causes it to reallocate, you should be safe.

To be clear, this means that you are allowed to:

- move it around
- read from it, iterate over it, slice it immutably or mutably
- mutate it in a way that does not affect its capacity, eg. `clear()` or `pop()`
- publicly expose immutable references to it
- publicly expose mutable subslices to it

but you are not allowed to:

- `push()` to it
- drop it
- drop it and replace it with a freshly allocated `String`
- publicly expose a mutable reference of type `&mut String`

* * *

You mentioned pinning, but pinning wouldn't help here at all. **Pinning isn't a prescription, it's a description.** Types can be `Unpin`, meaning that they are safe to move around without self-referential pointers (if any) becoming invalid. This is a safety _requirement_ that you can _rely on_ in generic code by requiring the `Unpin` bound, but you can't _force_ a type to have this property.

Concrete types either are or aren't `Unpin`, which is a structural property determined by their implementation. If `String` didn't heap-allocate its buffer (or otherwise ensured a stable adress for it), then you couldn't magically force it to work in a self-referential setting anyway.

---

<div class="post-metadata">

**Author:** ![samuelpilz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/samuelpilz/32/33384_2.png) [@samuelpilz](https://users.rust-lang.org/u/samuelpilz)\
**Post date:** [September 16, 2023, 5:54am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/4 "2023-09-16T05:54:17Z")

</div>

I understand the question a bit differently, I focus on this sentence:

> [@wallefan](#):
>
> I'd like the keys in my hashmap to point directly to those strings rather than being copies

Remember that mutating the keys of a hashmap is a logic-error. For this reason, I assume the Strings are effectively-immutable (while in the map).

In this case, what is wrong with the following solution?

```rust
struct Element {
   element: Arc<str>,
}

type MyHashMap = HashMap<Arc<str>, Element>

```

This makes the key "point to" the same memory region that contains the `str` data.

If you want to mutate the string while not inserted in the map, you can use `Arc<String>` instead of `Arc<str>` and call [`Arc::get_mut`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.get_mut).

---

<div class="post-metadata">

**Author:** ![samuelpilz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/samuelpilz/32/33384_2.png) [@samuelpilz](https://users.rust-lang.org/u/samuelpilz)\
**Post date:** [September 16, 2023, 6:03am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/5 "2023-09-16T06:03:35Z")

</div>

Another suggestion, but may not be applicable to your use-case: If the `HashMap` lives short enough and the elements are immutable and owned by someone else (or you leak them) , you could go with `HashMap<&str, &Element>`. You can insert into that map with `map.insert(&element.key, &element)`

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [September 16, 2023, 6:13am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/6 "2023-09-16T06:13:11Z")

</div>

Indeed, that isn't applicable, because:

> [@wallefan](#):
>
> The boxed slice and the hash map containing raw pointers to it are both private members of a struct

---

<div class="post-metadata">

**Author:** ![samuelpilz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/samuelpilz/32/33384_2.png) [@samuelpilz](https://users.rust-lang.org/u/samuelpilz)\
**Post date:** [September 16, 2023, 6:23am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/7 "2023-09-16T06:23:32Z")

</div>

Most probably. Similar to steffahn, I did not understand much after "I've already built..." of the original post.

I have had success in the past refactoring the data flow to allow different solutions than originally anticipated.

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/skifire13/32/17959_2.png) [@SkiFire13](https://users.rust-lang.org/u/SkiFire13)\
**Post date:** [September 16, 2023, 7:20am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/8 "2023-09-16T07:20:03Z")

</div>

You could use a [`RawTable<usize>`](https://docs.rs/hashbrown/latest/hashbrown/raw/struct.RawTable.html) where the `usize` are indexes into your boxed slice. The hashing methods for inserting/finding etc etc all take a custom closure to hash, and you can have that deref to the implementation of `Hash` for the string at the given index.

Edit: here's an example of how you would do this [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=025c01d7811fb717b9ed97015211547f)

```rs
struct Map {
    items: Box<[String]>,
    indices: RawTable<usize>,
    hasher: RandomState,
}

impl Map {
    fn new(items: Box<[String]>) -> Self {
        let mut indices = RawTable::with_capacity(items.len());
        let hasher = RandomState::new();

        for (idx, item) in items.iter().enumerate() {
            let hash = hasher.hash_one(item);
            // Note: this assumes all items are different
            indices.insert(hash, idx, |&idx2| hasher.hash_one(&items[idx2]));
        }

        Map {
            items,
            indices,
            hasher,
        }
    }

    fn index_of(&self, s: &str) -> Option<usize> {
        let hash = self.hasher.hash_one(&s);
        self.indices
            .get(hash, |&idx2| s == self.items[idx2])
            .copied()
    }
}

```

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [September 16, 2023, 7:23am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/9 "2023-09-16T07:23:42Z")

</div>

My understanding is that OP has approximately the following data structure, and s/he is asking whether it's sound:

```rust
struct RawStr(*const str);

impl Eq for RawStr {}
impl Hash for RawStr { ... }

struct Map {
    items: Box<[String]>,
    indices: HashMap<RawStr, usize>,
}

impl Map {
    fn new(items: Box<[String]>) -> Self {
        let indices = items
            .iter()
            .enumerate()
            .map(|(i, s)| {
                let key = RawStr::from(s.as_ptr());
                let value = i;
                (key, value)
            })
            .collect();
        Map { items, indices }
    }
}

```

If I'm right, your `Arc<str>`/`Rc<str>` suggestion would be an equivalent but safe alternative.

---

<div class="post-metadata">

**Author:** ![wallefan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/wallefan/32/33998_2.png) [@wallefan](https://users.rust-lang.org/u/wallefan)\
**Post date:** [September 19, 2023, 4:19am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/10 "2023-09-19T04:19:08Z")

</div>

H2CO3 is correct. That code seems to work in testing, but I'm worried whether there are gremlins lurking in it that will bite me in the long term.

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [September 19, 2023, 5:43am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/11 "2023-09-19T05:43:00Z")

</div>

You should probably just use @samuelpilz's solution based on reference counting. As a rule of thumb, you shouldn't write unsafe of which the soundness you need to ask about.

---

<div class="post-metadata">

**Author:** ![SebastianJL](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/sebastianjl/32/26174_2.png) [@SebastianJL](https://users.rust-lang.org/u/SebastianJL)\
**Post date:** [September 19, 2023, 7:26am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/12 "2023-09-19T07:26:09Z")

</div>

Very different Ansatz but if you only need to find the index of a string in the slice how about sorting the slice of strings once and doing binary search instead of using a hashmap?

If you can't sort the slice because it's structure is somehow important you could still sort an array of indices with argsort and use that to do the binary search.

```rust
pub fn argsort<T: Ord>(data: &[T]) -> Vec<usize> {
    let mut indices = (0..data.len()).collect::<Vec<_>>();
    indices.sort_by_key(|&i| &data[i]);
    indices
}

```

Code taken from [StackOverflow answer](https://stackoverflow.com/a/69764256/9874789).

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [December 18, 2023, 7:26am UTC](https://users.rust-lang.org/t/safely-acquiring-a-pointer-to-one-of-the-elements-of-a-boxed-slice/99958/13 "2023-12-18T07:26:21Z")

</div>

Closed on December 18, 2023, 7:26am UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
