3 ms·
`Vec` is always heap-allocated; it's not hidden if you know that. It's intentional that you have to write `vec![0u8; 100]` to get this, rather than just, say,
by comex 6y ago
`Vec` is always heap-allocated; it's not hidden if you know that. It's intentional that you have to write `vec![0u8; 100]` to get this, rather than just, say, `[0u8; 100]` (which will give you a stack allocation).
It's true that the example should use capacity() rather than hardcoding 100.
If you want a stack allocation, here's an example:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=df5c3f22652626ba50b8dcc0463df38c https://play.rust-lang.org/?version=stable&mode=debug&editio...
It's about the same length as the original, but it's hard to make a direct comparison. On one hand, the original snippet is totally wrong: it doesn't properly handle the nul terminator of either the input or the output. I fixed that, but at the cost of making the code a bit more verbose. On the other hand, the original snippet does try to parse the result as UTF-8, which is not what you want, so I removed it (it would add 2 lines or so).
That said… it's not true that avoiding heap allocation is what would actually be done in the kernel. Not for file paths, which is what readlink typically returns. Since kernel stack sizes are so small, paths have to be allocated on the heap. It's only in userland that you can plop PATH_MAX sized buffers on the stack.
On the other hand, if you were really doing heap allocation in the kernel you would need to handle out-of-memory conditions. Rust's standard library doesn't support recovering from OOM at all, but it's not like you'd be using the standard library in the kernel anyway. In contrast, Rust the language is actually quite good at this. A fallible allocation function would return something like Result<String, OOMError>; the use of Result forces you to handle the error case somehow (unlike C, you can't just assume it succeeded), but all you need to do to handle it is use the `?` operator to propagate errors to the caller.
- wahern 6y agoI realize Rust-the-language can handle OOM, and that with Result types it could prove cleaner and safer than in C. But it's rare to see examples of this, and the wg-allocator working group still seems to have alot of unfinished business.