valence_protocol/
velocity.rs
1use std::fmt;
2
3use derive_more::{From, Into};
4
5use crate::{Decode, Encode};
6
7#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, From, Into)]
9pub struct Velocity(pub [i16; 3]);
10
11impl Velocity {
12 pub fn from_ms_f32(ms: [f32; 3]) -> Self {
14 Self(ms.map(|v| (8000.0 / 20.0 * v) as i16))
15 }
16
17 pub fn from_ms_f64(ms: [f64; 3]) -> Self {
19 Self(ms.map(|v| (8000.0 / 20.0 * v) as i16))
20 }
21
22 pub fn to_ms_f32(self) -> [f32; 3] {
24 self.0.map(|v| f32::from(v) / (8000.0 / 20.0))
25 }
26
27 pub fn to_ms_f64(self) -> [f64; 3] {
29 self.0.map(|v| f64::from(v) / (8000.0 / 20.0))
30 }
31}
32
33impl fmt::Debug for Velocity {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 fmt::Display::fmt(self, f)
36 }
37}
38
39impl fmt::Display for Velocity {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 let [x, y, z] = self.to_ms_f32();
42 write!(f, "⟨{x},{y},{z}⟩ m/s")
43 }
44}
45
46#[cfg(test)]
47#[test]
48fn velocity_from_ms() {
49 let val_1 = Velocity::from_ms_f32([(); 3].map(|()| -3.3575)).0[0];
50 let val_2 = Velocity::from_ms_f64([(); 3].map(|()| -3.3575)).0[0];
51
52 assert_eq!(val_1, val_2);
53 assert_eq!(val_1, -1343);
54}