hypershell_components/providers/
convert.rs

1use alloc::borrow::ToOwned;
2use alloc::string::String;
3use core::fmt::Debug;
4use core::marker::PhantomData;
5use core::str::Utf8Error;
6
7use cgp::extra::handler::{Computer, ComputerComponent, Handler, HandlerComponent};
8use cgp::prelude::*;
9
10use crate::dsl::ConvertTo;
11
12#[cgp_new_provider]
13impl<Context, Input, Output> Computer<Context, ConvertTo<Output>, Input> for HandleConvert
14where
15    Input: Into<Output>,
16{
17    type Output = Output;
18
19    fn compute(_context: &Context, _tag: PhantomData<ConvertTo<Output>>, input: Input) -> Output {
20        input.into()
21    }
22}
23
24#[cgp_new_provider]
25impl<Context, Code, Input> Handler<Context, Code, Input> for DecodeUtf8Bytes
26where
27    Context: CanRaiseAsyncError<Utf8Error> + for<'a> CanWrapAsyncError<DecodeUtf8InputError<'a>>,
28    Code: Send,
29    Input: Send + AsRef<[u8]>,
30{
31    type Output = String;
32
33    async fn handle(
34        _context: &Context,
35        _tag: PhantomData<Code>,
36        input: Input,
37    ) -> Result<String, Context::Error> {
38        let raw_input = input.as_ref();
39
40        let parsed = str::from_utf8(raw_input)
41            .map_err(Context::raise_error)
42            .map_err(|e| Context::wrap_error(e, DecodeUtf8InputError { raw_input }))?;
43
44        Ok(parsed.to_owned())
45    }
46}
47
48pub struct DecodeUtf8InputError<'a> {
49    pub raw_input: &'a [u8],
50}
51
52impl<'a> Debug for DecodeUtf8InputError<'a> {
53    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
54        write!(f, "failed to decode input bytes as UTF-8 string")
55    }
56}