fuchsia_wayland_core/
fixed.rsuse std::fmt;
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Fixed(i32);
impl Fixed {
pub fn from_bits(v: i32) -> Self {
Fixed(v)
}
pub fn from_float(v: f32) -> Self {
Fixed((v * 256.0) as i32)
}
pub fn to_float(self) -> f32 {
(self.0 as f32) / 256.0
}
pub fn bits(self) -> i32 {
self.0
}
}
impl fmt::Display for Fixed {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{}", self.to_float())
}
}
impl fmt::Debug for Fixed {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{:?}", self.to_float())
}
}
impl From<f32> for Fixed {
fn from(v: f32) -> Self {
Self::from_float(v)
}
}
impl From<i32> for Fixed {
fn from(v: i32) -> Self {
Self::from_bits(v)
}
}
impl Into<f32> for Fixed {
fn into(self) -> f32 {
self.to_float()
}
}
#[cfg(test)]
mod tests {
use zerocopy::transmute;
use super::*;
#[test]
fn fixed_to_float() {
let fixed: Fixed = 256.into();
assert_eq!(1.0, fixed.to_float());
let fixed: Fixed = 257.into();
assert_eq!(1.00390625, fixed.to_float());
let i: i32 = transmute!(0xffffff00u32);
let fixed: Fixed = i.into();
assert_eq!(-1.0, fixed.to_float());
let i: i32 = transmute!(0xfffffeffu32);
let fixed: Fixed = i.into();
assert_eq!(-1.00390625, fixed.to_float());
}
#[test]
fn float_to_fixed() {
let fixed: Fixed = 1.0.into();
assert_eq!(256, fixed.bits());
let fixed: Fixed = 1.00390625.into();
assert_eq!(257, fixed.bits());
let fixed: Fixed = (-1.0).into();
let i: i32 = transmute!(0xffffff00u32);
assert_eq!(i, fixed.bits());
let fixed: Fixed = (-1.00390625).into();
let i: i32 = transmute!(0xfffffeffu32);
assert_eq!(i, fixed.bits());
}
}