]> git.lizzy.rs Git - rust.git/commit
Auto merge of #39271 - est31:add_float_bits, r=BurntSushi
authorbors <bors@rust-lang.org>
Tue, 18 Apr 2017 11:23:44 +0000 (11:23 +0000)
committerbors <bors@rust-lang.org>
Tue, 18 Apr 2017 11:23:44 +0000 (11:23 +0000)
commitc398efc53f09f6e1a8cba4ec2259ffb9d89f0542
tree17060193776655170f41a7489ff173152172f1eb
parente621e1c73f1487b4450446eafe6ccad3a99e3cd8
parent0c148153f4de0c32206582ed9b51346f9769f10c
Auto merge of #39271 - est31:add_float_bits, r=BurntSushi

Add functions to safely transmute float to int

The safe subset of Rust tries to be as powerful as possible. While it is very powerful already, its currently impossible to safely transmute integers to floats. While crates exist that provide a safe interface, most prominently the `iee754` crate (which also inspired naming of the added functions), they themselves only use the unsafe `mem::transmute` function to accomplish this task.

Also, including an entire crate for just two lines of unsafe code seems quite wasteful.

That's why this PR adds functions to safely transmute integers to floats and vice versa, currently gated by the newly added `float_bits_conv` feature.

The functions added are no niche case. Not just `ieee754` [currently implements](https://github.com/huonw/ieee754/blob/master/src/lib.rs#L441) float to int transmutation via unsafe code but also the [very popular `byteorder` crate](https://github.com/BurntSushi/byteorder/blob/1.0.0/src/lib.rs#L258). This functionality of byteorder is in turn used by higher level crates. I only give two examples out of many: [chor](https://github.com/pyfisch/cbor/blob/a7363ea9aaf372e3d24b52414b5c76552ecc91c8/src/ser.rs#L227) and [bincode](https://github.com/TyOverby/bincode/blob/f06a4cfcb5b194e54d4997c200c75b88b6c3fba4/src/serde/reader.rs#L218).

One alternative would be to manually use functions like pow or multiplication by 1 to get a similar result, but they only work in the int -> float direction, and are not bit exact, and much slower (also, most likely the optimizer will never optimize it to a transmute because the conversion is not bit exact while the transmute is).

Tracking issue: #40470
src/doc/unstable-book/src/SUMMARY.md