Skip to main content

screeps/enums/action_error_codes/
game_cpu_error_codes.rs

1use std::{error::Error, fmt};
2
3use num_derive::FromPrimitive;
4use serde_repr::{Deserialize_repr, Serialize_repr};
5
6use crate::{constants::ErrorCode, FromReturnCode};
7
8/// Error codes used by
9/// [game::cpu::set_shard_limits](crate::game::cpu::set_shard_limits).
10///
11/// [Screeps API Docs](https://docs.screeps.com/api/#Game.cpu.setShardLimits).
12#[cfg(feature = "mmo")]
13#[derive(
14    Debug, PartialEq, Eq, Clone, Copy, Hash, FromPrimitive, Deserialize_repr, Serialize_repr,
15)]
16#[repr(i8)]
17pub enum SetShardLimitsErrorCode {
18    Busy = -4,
19    InvalidArgs = -10,
20}
21
22#[cfg(feature = "mmo")]
23impl FromReturnCode for SetShardLimitsErrorCode {
24    type Error = Self;
25
26    fn result_from_i8(val: i8) -> Result<(), Self::Error> {
27        let maybe_result = Self::try_result_from_i8(val);
28        #[cfg(feature = "unsafe-return-conversion")]
29        unsafe {
30            maybe_result.unwrap_unchecked()
31        }
32        #[cfg(not(feature = "unsafe-return-conversion"))]
33        maybe_result.unwrap()
34    }
35
36    fn try_result_from_i8(val: i8) -> Option<Result<(), Self::Error>> {
37        match val {
38            0 => Some(Ok(())),
39            -4 => Some(Err(SetShardLimitsErrorCode::Busy)),
40            -10 => Some(Err(SetShardLimitsErrorCode::InvalidArgs)),
41            _ => None,
42        }
43    }
44}
45
46#[cfg(feature = "mmo")]
47impl fmt::Display for SetShardLimitsErrorCode {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        let msg: &'static str = match self {
50            SetShardLimitsErrorCode::Busy => "12-hours cooldown period is not over yet",
51            SetShardLimitsErrorCode::InvalidArgs => {
52                "the argument is not a valid shard limits object"
53            }
54        };
55
56        write!(f, "{}", msg)
57    }
58}
59
60#[cfg(feature = "mmo")]
61impl Error for SetShardLimitsErrorCode {}
62
63#[cfg(feature = "mmo")]
64impl From<SetShardLimitsErrorCode> for ErrorCode {
65    fn from(value: SetShardLimitsErrorCode) -> Self {
66        // Safety: SetShardLimitsErrorCode is repr(i8), so we can cast it to get the
67        // discriminant value, which will match the raw return code value that ErrorCode
68        // expects.   Ref: https://doc.rust-lang.org/reference/items/enumerations.html#r-items.enum.discriminant.coercion.intro
69        // Safety: SetShardLimitsErrorCode discriminants are always error code values,
70        // and thus the Result returned here will always be an `Err` variant, so we can
71        // always extract the error without panicking
72        Self::result_from_i8(value as i8).unwrap_err()
73    }
74}
75
76/// Error codes used by [game::cpu::unlock](crate::game::cpu::unlock).
77///
78/// [Screeps API Docs](https://docs.screeps.com/api/#Game.cpu.unlock).
79#[derive(
80    Debug, PartialEq, Eq, Clone, Copy, Hash, FromPrimitive, Deserialize_repr, Serialize_repr,
81)]
82#[repr(i8)]
83pub enum UnlockErrorCode {
84    NotEnoughResources = -6,
85    Full = -8,
86}
87
88impl FromReturnCode for UnlockErrorCode {
89    type Error = Self;
90
91    fn result_from_i8(val: i8) -> Result<(), Self::Error> {
92        let maybe_result = Self::try_result_from_i8(val);
93        #[cfg(feature = "unsafe-return-conversion")]
94        unsafe {
95            maybe_result.unwrap_unchecked()
96        }
97        #[cfg(not(feature = "unsafe-return-conversion"))]
98        maybe_result.unwrap()
99    }
100
101    fn try_result_from_i8(val: i8) -> Option<Result<(), Self::Error>> {
102        match val {
103            0 => Some(Ok(())),
104            -6 => Some(Err(UnlockErrorCode::NotEnoughResources)),
105            -8 => Some(Err(UnlockErrorCode::Full)),
106            _ => None,
107        }
108    }
109}
110
111impl fmt::Display for UnlockErrorCode {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        let msg: &'static str = match self {
114            UnlockErrorCode::NotEnoughResources => {
115                "your account does not have enough cpuunlock resource"
116            }
117            UnlockErrorCode::Full => "your cpu is unlocked with a subscription",
118        };
119
120        write!(f, "{}", msg)
121    }
122}
123
124impl Error for UnlockErrorCode {}
125
126impl From<UnlockErrorCode> for ErrorCode {
127    fn from(value: UnlockErrorCode) -> Self {
128        // Safety: UnlockErrorCode is repr(i8), so we can cast it to get the
129        // discriminant value, which will match the raw return code value that ErrorCode
130        // expects.   Ref: https://doc.rust-lang.org/reference/items/enumerations.html#r-items.enum.discriminant.coercion.intro
131        // Safety: UnlockErrorCode discriminants are always error code values, and thus
132        // the Result returned here will always be an `Err` variant, so we can always
133        // extract the error without panicking
134        Self::result_from_i8(value as i8).unwrap_err()
135    }
136}
137
138/// Error codes used by
139/// [game::cpu::generate_pixel](crate::game::cpu::generate_pixel).
140///
141/// [Screeps API Docs](https://docs.screeps.com/api/#Game.cpu.generatePixel).
142#[derive(
143    Debug, PartialEq, Eq, Clone, Copy, Hash, FromPrimitive, Deserialize_repr, Serialize_repr,
144)]
145#[repr(i8)]
146pub enum GeneratePixelErrorCode {
147    NotEnoughResources = -6,
148}
149
150impl FromReturnCode for GeneratePixelErrorCode {
151    type Error = Self;
152
153    fn result_from_i8(val: i8) -> Result<(), Self::Error> {
154        let maybe_result = Self::try_result_from_i8(val);
155        #[cfg(feature = "unsafe-return-conversion")]
156        unsafe {
157            maybe_result.unwrap_unchecked()
158        }
159        #[cfg(not(feature = "unsafe-return-conversion"))]
160        maybe_result.unwrap()
161    }
162
163    fn try_result_from_i8(val: i8) -> Option<Result<(), Self::Error>> {
164        match val {
165            0 => Some(Ok(())),
166            -6 => Some(Err(GeneratePixelErrorCode::NotEnoughResources)),
167            _ => None,
168        }
169    }
170}
171
172impl fmt::Display for GeneratePixelErrorCode {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        let msg: &'static str = match self {
175            GeneratePixelErrorCode::NotEnoughResources => "your bucket does not have enough cpu",
176        };
177
178        write!(f, "{}", msg)
179    }
180}
181
182impl Error for GeneratePixelErrorCode {}
183
184impl From<GeneratePixelErrorCode> for ErrorCode {
185    fn from(value: GeneratePixelErrorCode) -> Self {
186        // Safety: GeneratePixelErrorCode is repr(i8), so we can cast it to get the
187        // discriminant value, which will match the raw return code value that ErrorCode
188        // expects.   Ref: https://doc.rust-lang.org/reference/items/enumerations.html#r-items.enum.discriminant.coercion.intro
189        // Safety: GeneratePixelErrorCode discriminants are always error code values,
190        // and thus the Result returned here will always be an `Err` variant, so we can
191        // always extract the error without panicking
192        Self::result_from_i8(value as i8).unwrap_err()
193    }
194}