screeps/enums/action_error_codes/
structurerampart_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/// [StructureRampart::set_public](crate::StructureRampart::set_public).
10///
11/// [Screeps API Docs](https://docs.screeps.com/api/#StructureRampart.setPublic).
12///
13/// [Screeps Engine Source Code](https://github.com/screeps/engine/blob/97c9d12385fed686655c13b09f5f2457dd83a2bf/src/game/structures.js#L651)
14#[derive(
15    Debug, PartialEq, Eq, Clone, Copy, Hash, FromPrimitive, Deserialize_repr, Serialize_repr,
16)]
17#[repr(i8)]
18pub enum SetPublicErrorCode {
19    NotOwner = -1,
20}
21
22impl FromReturnCode for SetPublicErrorCode {
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(SetPublicErrorCode::NotOwner)),
39            _ => None,
40        }
41    }
42}
43
44impl fmt::Display for SetPublicErrorCode {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        let msg: &'static str = match self {
47            SetPublicErrorCode::NotOwner => "you are not the owner of this structure",
48        };
49
50        write!(f, "{}", msg)
51    }
52}
53
54impl Error for SetPublicErrorCode {}
55
56impl From<SetPublicErrorCode> for ErrorCode {
57    fn from(value: SetPublicErrorCode) -> Self {
58        // Safety: SetPublicErrorCode is repr(i8), so we can cast it to get the
59        // discriminant value, which will match the raw return code value that ErrorCode
60        // expects.   Ref: https://doc.rust-lang.org/reference/items/enumerations.html#r-items.enum.discriminant.coercion.intro
61        // Safety: SetPublicErrorCode discriminants are always error code values, and
62        // thus the Result returned here will always be an `Err` variant, so we can
63        // always extract the error without panicking
64        Self::result_from_i8(value as i8).unwrap_err()
65    }
66}