Skip to main content

thin_status/
builder.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.
14use std::borrow::Cow;
15use std::fmt;
16use std::num::NonZeroI32;
17
18use crate::{FullStatus, ThinStatus};
19
20/// Allows convenient construction of `ThinStatus` instances.
21pub struct ThinStatusBuilder<'a> {
22    pub(crate) full: FullStatus,
23    pub(crate) message: Cow<'a, str>,
24}
25
26impl<'a> ThinStatusBuilder<'a> {
27    /// Constructs a builder from an error code (which can be, and often is `ErrorCode`).
28    pub fn new<C: Into<NonZeroI32>>(code: C) -> Self {
29        Self {
30            full: FullStatus {
31                code: code.into(),
32                details: Default::default(),
33            },
34            message: Cow::Borrowed(""),
35        }
36    }
37
38    /// Sets the error code to `code`.
39    pub fn code<C: Into<NonZeroI32>>(mut self, code: C) -> Self {
40        self.full.code = code.into();
41        self
42    }
43
44    /// Sets the message to `message`, discarding any previous one. The builder captures only a
45    /// reference to it to avoid copying.
46    pub fn message(mut self, message: &'a str) -> Self {
47        self.message = Cow::Borrowed(message);
48        self
49    }
50
51    /// Appends a `google_cloud_wkt::Any` object to the list of details.
52    #[cfg(feature = "use_any")]
53    pub fn add_detail(mut self, detail: google_cloud_wkt::Any) -> Self {
54        self.full.details.details.push(detail);
55        self
56    }
57
58    /// Sets the internal `Vec<google_cloud_wkt::Any>` to `details`, discarding any previous vector.
59    #[cfg(feature = "use_any")]
60    pub fn details(mut self, details: Vec<google_cloud_wkt::Any>) -> Self {
61        self.full.details.details = details;
62        self
63    }
64
65    pub fn build(self) -> ThinStatus {
66        ThinStatus::from_builder(self)
67    }
68}
69
70impl From<ThinStatusBuilder<'_>> for ThinStatus {
71    fn from(builder: ThinStatusBuilder) -> Self {
72        builder.build()
73    }
74}
75
76/// Allows convenient appending to the text message. If it contains just a reference passed to
77/// `message`, the reference is copied into a new `String` that can be appended to.
78impl<'a> fmt::Write for ThinStatusBuilder<'a> {
79    fn write_str(&mut self, s: &str) -> fmt::Result {
80        self.message.to_mut().push_str(s);
81        Ok(())
82    }
83}