screeps/enums/action_error_codes/
constructionsite_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/// [ConstructionSite::remove](crate::ConstructionSite::remove).
10///
11/// [Screeps API Docs](https://docs.screeps.com/api/#ConstructionSite.remove).
12///
13/// [Screeps Engine Source Code](https://github.com/screeps/engine/blob/97c9d12385fed686655c13b09f5f2457dd83a2bf/src/game/construction-sites.js#L50)
14#[derive(
15    Debug, PartialEq, Eq, Clone, Copy, Hash, FromPrimitive, Deserialize_repr, Serialize_repr,
16)]
17#[repr(i8)]
18pub enum ConstructionSiteRemoveErrorCode {
19    NotOwner = -1,
20}
21
22impl FromReturnCode for ConstructionSiteRemoveErrorCode {
23    type Error = Self;
24
25    fn result_from_i8(val: i8) -> Result<(), Self::Error> {
26        let maybe_result = Self::try_result_from_i8(val);
27        #[cfg(feature = "unsafe-return-conversion")]
28        unsafe {
29            maybe_result.unwrap_unchecked()
30        }
31        #[cfg(not(feature = "unsafe-return-conversion"))]
32        maybe_result.unwrap()
33    }
34
35    fn try_result_from_i8(val: i8) -> Option<Result<(), Self::Error>> {
36        match val {
37            0 => Some(Ok(())),
38            -1 => Some(Err(ConstructionSiteRemoveErrorCode::NotOwner)),
39            _ => None,
40        }
41    }
42}
43
44impl fmt::Display for ConstructionSiteRemoveErrorCode {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        let msg: &'static str = match self {
47            ConstructionSiteRemoveErrorCode::NotOwner => {
48                "you are not the owner of this construction site, and it's not in your room"
49            }
50        };
51
52        write!(f, "{}", msg)
53    }
54}
55
56impl Error for ConstructionSiteRemoveErrorCode {}
57
58impl From<ConstructionSiteRemoveErrorCode> for ErrorCode {
59    fn from(value: ConstructionSiteRemoveErrorCode) -> Self {
60        // Safety: ConstructionSiteRemoveErrorCode is repr(i8), so we can cast it to get
61        // the discriminant value, which will match the raw return code value that
62        // ErrorCode expects.   Ref: https://doc.rust-lang.org/reference/items/enumerations.html#r-items.enum.discriminant.coercion.intro
63        // Safety: ConstructionSiteRemoveErrorCode discriminants are always error code
64        // values, and thus the Result returned here will always be an `Err` variant, so
65        // we can always extract the error without panicking
66        Self::result_from_i8(value as i8).unwrap_err()
67    }
68}