Peter Hall Peter Hall - 2 months ago 13
C Question

Why are functions like memchr bound to C implementations rather than being written in pure Rust?

Functions like

memchr
seem quite simple but Rust projects use bindings to the C code with only a Rust fallback, rather than implementing them in Rust. Can't
memchr
be efficiently implemented in Rust?

Answer

They can. If you look at glibc's implementation, it will look somewhat like fallback:memchr. However, that's only part of the story. The generic implementation is used only when there isn't a more appropriate one available.

For example, x68-64 has a variant written in assembly. And so do many other architectures, that provide sophisticated instructions.

So to reach the same speed, Rust would have to provide something similar on instruction level, which essentially boils down to the same (or better) assembly. At that point you're just duplicating work. It's already there, no need to create everything anew.

Comments