Skip to main content

anvil/
text.rs

1use std::ffi::{c_char, CStr, CString};
2use std::fmt;
3
4use crate::error::{check, Result};
5use crate::sys::{AnvilGameTag, AnvilResult};
6
7/// `text` as a C string; a NUL inside it is dropped.
8pub(crate) fn c_string(text: &str) -> CString {
9    CString::new(text).unwrap_or_else(|error| {
10        let mut bytes = error.into_vec();
11        bytes.retain(|&byte| byte != 0);
12        // SAFETY: the NULs were just removed.
13        unsafe { CString::from_vec_unchecked(bytes) }
14    })
15}
16
17/// A C string the host or a service keeps for the process.
18///
19/// # Safety
20/// `text` is null or a NUL-terminated string that lives until the process ends.
21pub(crate) unsafe fn static_str(text: *const c_char) -> Option<&'static str> {
22    if text.is_null() {
23        return None;
24    }
25    // SAFETY: the caller's contract.
26    unsafe { CStr::from_ptr(text) }.to_str().ok()
27}
28
29/// A C string as owned text (invalid UTF-8 replaced).
30///
31/// # Safety
32/// `text` is null or NUL-terminated and valid during the call.
33pub(crate) unsafe fn owned_string(text: *const c_char) -> String {
34    if text.is_null() {
35        return String::new();
36    }
37    // SAFETY: the caller's contract.
38    unsafe { CStr::from_ptr(text) }
39        .to_string_lossy()
40        .into_owned()
41}
42
43/// Text from a call that fills the caller's buffer as far as it fits and
44/// writes the whole length (without the NUL): asked with capacity 0 first.
45pub(crate) fn read_text(
46    context: impl Fn() -> String,
47    mut call: impl FnMut(*mut c_char, u32, *mut u32) -> AnvilResult,
48) -> Result<String> {
49    let mut length = 0u32;
50    check(call(std::ptr::null_mut(), 0, &mut length), &context)?;
51    for _ in 0..4 {
52        let mut buffer = vec![0u8; length as usize + 1];
53        let capacity = u32::try_from(buffer.len()).unwrap_or(u32::MAX);
54        let mut whole = 0u32;
55        check(
56            call(buffer.as_mut_ptr().cast(), capacity, &mut whole),
57            &context,
58        )?;
59        if whole <= length {
60            buffer.truncate(whole as usize);
61            return Ok(String::from_utf8_lossy(&buffer).into_owned());
62        }
63        // It grew between the calls; ask again with the new size.
64        length = whole;
65    }
66    Err(crate::Error::new(
67        crate::ErrorCode::Internal,
68        format!("{}: the text keeps growing", context()),
69    ))
70}
71
72/// A list from a call that fills the caller's array as far as it fits and
73/// writes the whole count: asked with capacity 0 first.
74pub(crate) fn read_list<T: Copy>(
75    empty: T,
76    context: impl Fn() -> String,
77    mut call: impl FnMut(*mut T, u32, *mut u32) -> AnvilResult,
78) -> Result<Vec<T>> {
79    let mut count = 0u32;
80    check(call(std::ptr::null_mut(), 0, &mut count), &context)?;
81    for _ in 0..4 {
82        let mut items = vec![empty; count as usize];
83        let mut whole = 0u32;
84        check(call(items.as_mut_ptr(), count, &mut whole), &context)?;
85        if whole <= count {
86            items.truncate(whole as usize);
87            return Ok(items);
88        }
89        count = whole;
90    }
91    Err(crate::Error::new(
92        crate::ErrorCode::Internal,
93        format!("{}: the list keeps growing", context()),
94    ))
95}
96
97/// A country's tag: three ASCII letters or digits, e.g. `RUS`.
98#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
99pub struct Tag([u8; 3]);
100
101impl Tag {
102    /// The tag of `text`, `None` unless it is three ASCII letters or digits.
103    /// The world service ignores case; the tag keeps it as given.
104    pub fn new(text: &str) -> Option<Self> {
105        let bytes: [u8; 3] = text.as_bytes().try_into().ok()?;
106        bytes
107            .iter()
108            .all(u8::is_ascii_alphanumeric)
109            .then_some(Self(bytes))
110    }
111
112    /// The tag a service wrote; `None` for "" (no country).
113    pub fn from_raw(raw: &AnvilGameTag) -> Option<Self> {
114        let bytes = raw.text.map(|c| c as u8);
115        if bytes[0] == 0 {
116            return None;
117        }
118        let tag = [bytes[0], bytes[1], bytes[2]];
119        // The game's tags are ASCII; anything else shows as '?'.
120        Some(Self(
121            tag.map(|b| if b.is_ascii_graphic() { b } else { b'?' }),
122        ))
123    }
124
125    /// The tag as the C API takes it: three characters and a NUL.
126    pub fn to_raw(self) -> AnvilGameTag {
127        AnvilGameTag {
128            text: [
129                self.0[0] as c_char,
130                self.0[1] as c_char,
131                self.0[2] as c_char,
132                0,
133            ],
134        }
135    }
136
137    pub(crate) fn c_text(self) -> [c_char; 4] {
138        self.to_raw().text
139    }
140
141    /// The three characters.
142    pub fn as_str(&self) -> &str {
143        // Only ASCII is ever stored.
144        std::str::from_utf8(&self.0).unwrap_or("???")
145    }
146}
147
148impl fmt::Display for Tag {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.write_str(self.as_str())
151    }
152}
153
154impl fmt::Debug for Tag {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(f, "Tag({})", self.as_str())
157    }
158}
159
160impl std::str::FromStr for Tag {
161    type Err = crate::Error;
162
163    fn from_str(text: &str) -> Result<Self> {
164        Self::new(text).ok_or_else(|| {
165            crate::Error::new(
166                crate::ErrorCode::InvalidArgument,
167                format!("{text:?} is not a country tag"),
168            )
169        })
170    }
171}