1use std::ffi::{c_char, CStr, CString};
2use std::fmt;
3
4use crate::error::{check, Result};
5use crate::sys::{AnvilGameTag, AnvilResult};
6
7pub(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 unsafe { CString::from_vec_unchecked(bytes) }
14 })
15}
16
17pub(crate) unsafe fn static_str(text: *const c_char) -> Option<&'static str> {
22 if text.is_null() {
23 return None;
24 }
25 unsafe { CStr::from_ptr(text) }.to_str().ok()
27}
28
29pub(crate) unsafe fn owned_string(text: *const c_char) -> String {
34 if text.is_null() {
35 return String::new();
36 }
37 unsafe { CStr::from_ptr(text) }
39 .to_string_lossy()
40 .into_owned()
41}
42
43pub(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 length = whole;
65 }
66 Err(crate::Error::new(
67 crate::ErrorCode::Internal,
68 format!("{}: the text keeps growing", context()),
69 ))
70}
71
72pub(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#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
99pub struct Tag([u8; 3]);
100
101impl Tag {
102 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 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 Some(Self(
121 tag.map(|b| if b.is_ascii_graphic() { b } else { b'?' }),
122 ))
123 }
124
125 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 pub fn as_str(&self) -> &str {
143 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}