Skip to main content

thin_status/
thin_status.rs

1// Copyright 2026 <https://github.com/ppetr/>
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(feature = "use_cloud_rpc")]
16use google_cloud_rpc::model as cloud_rpc;
17use std::error::Error;
18use std::fmt::Display;
19use std::num::NonZeroI32;
20
21use crate::any_details::any::Details;
22use crate::builder;
23use crate::status_code;
24use crate::thin_arc_or_int::{IsizeInPtr, ThinArcOrInt};
25
26type Result<T, Error = ThinStatus> = std::result::Result<T, Error>;
27
28/// Holds a status code, and if enabled by feature `use_any`, also a list of `google_cloud_wkt.Any`
29/// instances that can provide structured details.
30#[derive(Clone, Debug, PartialEq)]
31#[cfg_attr(not(feature = "use_any"), derive(Copy, Eq, PartialOrd, Ord, Hash))]
32pub(crate) struct FullStatus {
33    pub(crate) code: NonZeroI32,
34    pub(crate) details: Details,
35}
36
37/// Coverts `FullStatus` to a code embedded inside a pointer as a tagged integer if:
38/// - There are no `google_cloud_wkt.Any` details attached.
39/// - The integer fits in `IsizeInPtr`.
40///
41/// Otherwise returns the very same instance.
42impl TryFrom<FullStatus> for IsizeInPtr {
43    type Error = FullStatus;
44
45    fn try_from(value: FullStatus) -> Result<IsizeInPtr, FullStatus> {
46        if value.details.is_empty() {
47            value.code.get().try_into().map_err(|_| value)
48        } else {
49            Err(value)
50        }
51    }
52}
53
54/// Holds a non-OK status code (in most cases `ErrorCode`), a descriptive string message, and
55/// optionally (if enabled by feature `use_any`) also `[google_cloud_wkt::Any]`.
56///
57/// It occupies only a single pointer word, which either wraps a tagged integer code (if there is
58/// neither message nor details), or a `ThinArc` pointer that holds a more complex value.
59/// Furthermore its representation is never `nullptr`, therefore `Option<ThinStatus>` and
60/// `Result<(), ThinStatus>` occupy just a single memory word.
61///
62/// Note that `Copy`, `Eq`, `PartialOrd` and `Hash` are only provided (derived) when feature
63/// `use_any` is disabled, since the `Any` datatype doesn't provide them.
64#[derive(Clone, Debug, PartialEq)]
65#[cfg_attr(not(feature = "use_any"), derive(Eq, PartialOrd, Ord, Hash))]
66pub struct ThinStatus {
67    // The wrapped `isize` integer is always non-zero.
68    // The `&[u8]` is always in UTF-8.
69    thin: ThinArcOrInt<FullStatus, u8>,
70}
71
72impl ThinStatus {
73    /// Constructs a builder that allows convenient creation of `ThinStatus` instances.
74    pub fn builder<'a, C: Into<NonZeroI32>>(code: C) -> builder::ThinStatusBuilder<'a> {
75        builder::ThinStatusBuilder::new(code)
76    }
77
78    /// Converts a builder into a new instance.
79    ///
80    /// This involves at most one heap allocation (if there is a message and/or `google_cloud_wkt.Any`.
81    pub(crate) fn from_builder(builder: builder::ThinStatusBuilder) -> Self {
82        ThinStatus {
83            thin: ThinArcOrInt::from_convertible(builder.full, builder.message.as_bytes()),
84        }
85    }
86
87    /// A utility function to create a status with just a raw code. If it fits, it'll be stored just
88    /// as a tagged integer inside an internal pointer.
89    pub fn from_code<C: Into<NonZeroI32>>(code: C) -> Self {
90        ThinStatus {
91            thin: ThinArcOrInt::from_convertible(
92                FullStatus {
93                    code: code.into(),
94                    details: Default::default(),
95                },
96                &[],
97            ),
98        }
99    }
100
101    /// Returns the stored error code, or `None` if the raw numerical value doesn't match any of the
102    /// `ErrorCode` values.
103    pub fn code(&self) -> Option<status_code::ErrorCode> {
104        self.code_raw().get().try_into().ok()
105    }
106
107    /// Convenience wrapper to `code()` that converts an unknown error to `ErrorCode::Unknown`.
108    pub fn code_or_unknown(&self) -> status_code::ErrorCode {
109        self.code().unwrap_or(status_code::ErrorCode::Unknown)
110    }
111
112    /// Returns the raw numerical error code.
113    pub fn code_raw(&self) -> NonZeroI32 {
114        match self.thin.as_isize() {
115            Some(code) => unsafe { NonZeroI32::new_unchecked(code as i32) },
116            None => {
117                let val = &self.thin.as_arc();
118                let val = val.expect("ThinArcOrInt contains neither code nor arc");
119                val.header.header.code
120            }
121        }
122    }
123
124    /// Returns the message attached to the status (if any).
125    pub fn message(&self) -> &str {
126        match self.thin.as_arc() {
127            None => "",
128            Some(arc) => unsafe { str::from_utf8_unchecked(&arc.slice) },
129        }
130    }
131
132    /// Returns the list of `google_cloud_wkt::Any` objects attached to the status.
133    #[cfg(feature = "use_any")]
134    pub fn details(&self) -> &[google_cloud_wkt::Any] {
135        let &arc = &self.thin.as_arc();
136        arc.map_or::<&[google_cloud_wkt::Any], _>(&[], |t| &t.header.header.details.get())
137    }
138
139    /// Converts a `ThinStatus` into a `google_cloud_rpc::Status`.
140    #[cfg(feature = "use_cloud_rpc")]
141    pub fn to_cloud_rpc(&self) -> cloud_rpc::Status {
142        self.into()
143    }
144
145    /// If a given `Status` is non-OK, converts it into `ThinStatus`.
146    #[cfg(feature = "use_cloud_rpc")]
147    pub fn try_from_cloud_rpc(status: cloud_rpc::Status) -> Result<Self, ()> {
148        status.try_into()
149    }
150
151    /// If a given `Status` is non-OK, converts it into `ThinStatus`.
152    /// Details of type `google_cloud_wkt.Any` are cloned.
153    #[cfg(feature = "use_cloud_rpc")]
154    pub fn try_from_cloud_rpc_ref(status: &cloud_rpc::Status) -> Result<Self, ()> {
155        status.try_into()
156    }
157}
158
159/// If the contained error code corresponds to an `ErrorCode` (`code()` returns `Some(...)`), it's
160/// printed as an upper-case string (such as `NOT_FOUND`); otherwise just as a number.
161/// This is followed by a colon, space and the contained message (if there is any).
162impl Display for ThinStatus {
163    /// If the `alternate` flag is set, always prints the error code as a number.
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        let code = self.code_raw().get();
166        if let Some(error_code) = status_code::ErrorCode::try_from(code).ok() {
167            error_code.fmt(f)?;
168        } else {
169            code.fmt(f)?;
170        }
171        let msg = self.message();
172        if !msg.is_empty() {
173            write!(f, ": {}", msg)?;
174        }
175        Ok(())
176    }
177}
178
179impl Error for ThinStatus {}
180
181impl From<status_code::ErrorCode> for ThinStatus {
182    fn from(code: status_code::ErrorCode) -> Self {
183        Self::from_code(NonZeroI32::from(code))
184    }
185}
186
187/// If a given `Status` is non-OK, converts it into `ThinStatus`.
188#[cfg(feature = "use_cloud_rpc")]
189impl TryFrom<cloud_rpc::Status> for ThinStatus {
190    type Error = ();
191
192    fn try_from(status: cloud_rpc::Status) -> Result<Self, ()> {
193        let code: NonZeroI32 = status.code.try_into().map_err(|_| ())?;
194        Ok(Self::builder(code)
195            .message(&status.message)
196            .details(status.details)
197            .build())
198    }
199}
200
201/// If a given `Status` is non-OK, converts it into `ThinStatus`.
202/// Details of type `google_cloud_wkt.Any` are cloned.
203#[cfg(feature = "use_cloud_rpc")]
204impl TryFrom<&cloud_rpc::Status> for ThinStatus {
205    type Error = ();
206
207    fn try_from(status: &cloud_rpc::Status) -> Result<Self, ()> {
208        let code: NonZeroI32 = status.code.try_into().map_err(|_| ())?;
209        Ok(Self::builder(code)
210            .message(&status.message)
211            .details(status.details.clone())
212            .build())
213    }
214}
215
216/// Converts a `ThinStatus` into a `google_cloud_rpc::Status`.
217#[cfg(feature = "use_cloud_rpc")]
218impl From<&ThinStatus> for cloud_rpc::Status {
219    fn from(status: &ThinStatus) -> Self {
220        let mut result = Self::new();
221        result.code = status.code_raw().get();
222        result.message = status.message().to_string();
223        result.details = status.details().to_vec();
224        result
225    }
226}
227
228#[cfg(test)]
229mod thin_status_tests {
230    use super::*;
231    use std::fmt::Write;
232
233    /// Represents the maximal `i32` value that can be stored inside the integer variant of
234    /// `ThinArcOrInt`.
235    const MAX_THIN: NonZeroI32 = NonZeroI32::new(if IsizeInPtr::MAX as u64 <= i32::MAX as u64 {
236        IsizeInPtr::MAX as i32
237    } else {
238        i32::MAX
239    })
240    .unwrap();
241
242    const fn non_zero(value: i32) -> NonZeroI32 {
243        NonZeroI32::new(value).unwrap()
244    }
245
246    #[test]
247    fn test_size_optimization() {
248        // Ensure that ThinStatus takes up exactly the size of a single pointer.
249        assert_eq!(
250            std::mem::size_of::<ThinStatus>(),
251            std::mem::size_of::<usize>()
252        );
253    }
254
255    #[test]
256    fn test_from_error_code_raw() {
257        // Values exactly at the boundary and within MAX_THIN should not allocate a ThinArc.
258        let status: ThinStatus = status_code::ErrorCode::NotFound.into();
259        assert_eq!(i32::from(status.code_raw()), 5);
260        assert_eq!(status.message(), "");
261        #[cfg(feature = "use_any")]
262        assert_eq!(status.details(), &[]);
263        assert!(status.thin.has_number());
264        assert_eq!(format!("{}", status), "NOT_FOUND");
265    }
266
267    #[test]
268    fn test_from_code_within_max_thin() {
269        // Values exactly at the boundary and within MAX_THIN should not allocate a ThinArc.
270        let status_pos = ThinStatus::from_code(MAX_THIN);
271        assert_eq!(status_pos.code_raw(), MAX_THIN);
272        assert_eq!(status_pos.message(), "");
273        assert!(status_pos.thin.has_number());
274
275        let status_neg = ThinStatus::from_code(-MAX_THIN);
276        assert_eq!(status_neg.code_raw(), -MAX_THIN);
277        assert_eq!(
278            status_neg.code_or_unknown(),
279            status_code::ErrorCode::Unknown
280        );
281        assert_eq!(status_neg.message(), "");
282        assert!(status_neg.thin.has_number());
283
284        let status_normal = ThinStatus::from_code(non_zero(42));
285        assert_eq!(status_normal.code_raw(), non_zero(42));
286        assert_eq!(status_normal.message(), "");
287        assert!(status_normal.thin.has_number());
288    }
289
290    /// Values outside MAX_THIN must force a ThinArc allocation.
291    #[test]
292    fn test_from_code_outside_max_thin() {
293        // If MAX_THIN equals i32::MAX, testing values beyond the boundary
294        // is not meaningful due to i32 overflow, so we check if it is smaller first.
295        if MAX_THIN.get() < NonZeroI32::MAX.into() {
296            let larger: NonZeroI32 = non_zero(MAX_THIN.get() + 1);
297            let status_overflow = ThinStatus::from_code(larger);
298            assert_eq!(status_overflow.code_raw(), larger);
299            assert_eq!(status_overflow.message(), "");
300
301            let status_underflow = ThinStatus::from_code(-larger);
302            assert_eq!(status_underflow.code_raw(), -larger);
303            assert_eq!(status_underflow.message(), "");
304            assert!(status_overflow.thin.has_ref());
305            assert!(status_underflow.thin.has_ref());
306        }
307
308        // Extreme i32 values (these will surely exceed MAX_THIN if MAX_THIN is smaller).
309        let status_max = ThinStatus::from_code(NonZeroI32::MAX);
310        assert_eq!(status_max.code_raw(), NonZeroI32::MAX);
311        let status_min = ThinStatus::from_code(NonZeroI32::MIN);
312        assert_eq!(status_min.code_raw(), NonZeroI32::MIN);
313        if MAX_THIN.get() < NonZeroI32::MAX.into() {
314            assert!(status_max.thin.has_ref());
315            assert!(status_min.thin.has_ref());
316        }
317    }
318
319    #[test]
320    fn test_from_error_code_and_message() {
321        let mut builder = ThinStatus::builder(status_code::ErrorCode::NotFound);
322        write!(builder, "message").expect("write! failed");
323        let status = builder.build();
324        assert_eq!(i32::from(status.code_raw()), 5);
325        assert_eq!(status.code(), Some(status_code::ErrorCode::NotFound));
326        assert_eq!(status.code_or_unknown(), status_code::ErrorCode::NotFound);
327        assert_eq!(status.message(), "message");
328        #[cfg(feature = "use_any")]
329        assert_eq!(status.details(), &[]);
330        assert!(status.thin.has_ref());
331        assert_eq!(format!("{}", status), "NOT_FOUND: message");
332    }
333
334    #[cfg(feature = "use_any")]
335    #[test]
336    fn test_with_details() {
337        let detail =
338            google_cloud_wkt::Any::from_msg(&google_cloud_wkt::Duration::clamp(123, 456)).unwrap();
339        let status = ThinStatus::builder(status_code::ErrorCode::NotFound)
340            .add_detail(detail.clone())
341            .build();
342        assert_eq!(i32::from(status.code_raw()), 5);
343        assert_eq!(status.message(), "");
344        assert_eq!(status.details(), vec![detail]);
345        assert!(status.thin.has_ref());
346        let formatted = format!("{:#?}", status);
347        assert!(formatted.contains("Any"));
348        assert!(formatted.contains("type.googleapis.com/google.protobuf.Duration"));
349        assert!(formatted.contains("123"));
350    }
351
352    #[test]
353    fn test_clone_and_equality() {
354        let status1 = ThinStatus::builder(non_zero(13))
355            .message("Permission Denied")
356            .build();
357        let status2 = status1.clone();
358
359        assert_eq!(status1, status2);
360        assert_eq!(status1.code_raw(), status2.code_raw());
361        assert_eq!(status1.message(), status2.message());
362
363        let _status_different = ThinStatus::from_code(non_zero(13));
364        assert_ne!(status1, _status_different);
365    }
366
367    #[cfg(feature = "use_cloud_rpc")]
368    #[test]
369    fn test_cloud_rpc_status_conversions() {
370        assert!(
371            ThinStatus::try_from(cloud_rpc::Status::new()).is_err(),
372            "OK status shouldn't be convertible to ThinStatus"
373        );
374
375        let detail =
376            google_cloud_wkt::Any::from_msg(&google_cloud_wkt::Duration::clamp(123, 456)).unwrap();
377        let status = ThinStatus::builder(status_code::ErrorCode::NotFound)
378            .message("Be yourself! Everyone else is already taken.")
379            .add_detail(detail)
380            .build();
381        assert_eq!(
382            ThinStatus::try_from(cloud_rpc::Status::from(&status)).as_ref(),
383            Ok(&status)
384        );
385
386        assert_eq!(
387            ThinStatus::try_from(&cloud_rpc::Status::from(&status)),
388            Ok(status)
389        );
390    }
391}
392
393trait ThinStatusExtSealed {}
394
395#[allow(private_bounds)]
396pub trait ThinStatusExt: ThinStatusExtSealed {
397    fn error_code_builder(&self, code: status_code::ErrorCode) -> builder::ThinStatusBuilder<'_>;
398
399    fn error_code(&self, code: status_code::ErrorCode) -> ThinStatus {
400        self.error_code_builder(code).build()
401    }
402}
403
404impl<M: Display> ThinStatusExtSealed for M {}
405
406impl<M: Display> ThinStatusExt for M {
407    fn error_code_builder(&self, code: status_code::ErrorCode) -> builder::ThinStatusBuilder<'_> {
408        ThinStatus::builder(code).message(self.to_string())
409    }
410
411    fn error_code(&self, code: status_code::ErrorCode) -> ThinStatus {
412        self.error_code_builder(code).build()
413    }
414}
415
416#[cfg(test)]
417mod thin_status_ext_tests {
418    use super::*;
419
420    #[test]
421    fn test_from_error_code_and_message() {
422        let status = "message".error_code(status_code::ErrorCode::NotFound);
423        assert_eq!(i32::from(status.code_raw()), 5);
424        assert_eq!(status.code(), Some(status_code::ErrorCode::NotFound));
425        assert_eq!(status.message(), "message");
426    }
427}