valence_protocol/
byte_angle.rs
1use std::f32::consts::TAU;
2use std::fmt;
3use std::io::Write;
4
5use crate::{Decode, Encode};
6
7#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct ByteAngle(pub u8);
10
11impl ByteAngle {
12 pub fn from_degrees(f: f32) -> ByteAngle {
13 ByteAngle((f.rem_euclid(360.0) / 360.0 * 256.0).round() as u8)
14 }
15
16 pub fn from_radians(f: f32) -> ByteAngle {
17 ByteAngle((f.rem_euclid(TAU) / TAU * 256.0).round() as u8)
18 }
19
20 pub fn to_degrees(self) -> f32 {
21 f32::from(self.0) / 256.0 * 360.0
22 }
23
24 pub fn to_radians(self) -> f32 {
25 f32::from(self.0) / 256.0 * TAU
26 }
27}
28
29impl fmt::Debug for ByteAngle {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 fmt::Display::fmt(self, f)
32 }
33}
34
35impl fmt::Display for ByteAngle {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 write!(f, "{}°", self.to_degrees())
38 }
39}
40
41impl Encode for ByteAngle {
42 fn encode(&self, w: impl Write) -> anyhow::Result<()> {
43 self.0.encode(w)
44 }
45}
46
47impl Decode<'_> for ByteAngle {
48 fn decode(r: &mut &[u8]) -> anyhow::Result<Self> {
49 u8::decode(r).map(ByteAngle)
50 }
51}