rquickjs_extra_utils/
result.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// Copyright Emile Fugulin for modifications.
3// SPDX-License-Identifier: Apache-2.0
4// Source: https://github.com/awslabs/llrt/blob/07eb540a204dcdce44143220876630804f381ca6/llrt_utils/src/result.rs
5use std::{fmt::Write, result::Result as StdResult};
6
7use rquickjs::{Ctx, Exception, Result};
8
9#[allow(dead_code)]
10pub trait ResultExt<T> {
11    fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T>;
12    fn or_throw_range(self, ctx: &Ctx, msg: Option<&str>) -> Result<T>;
13    fn or_throw_type(self, ctx: &Ctx, msg: Option<&str>) -> Result<T>;
14    fn or_throw(self, ctx: &Ctx) -> Result<T>;
15}
16
17impl<T, E: std::fmt::Display> ResultExt<T> for StdResult<T, E> {
18    fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T> {
19        self.map_err(|e| {
20            let mut message = String::with_capacity(100);
21            message.push_str(msg);
22            message.push_str(". ");
23            write!(message, "{e}").unwrap();
24            Exception::throw_message(ctx, &message)
25        })
26    }
27
28    fn or_throw_range(self, ctx: &Ctx, msg: Option<&str>) -> Result<T> {
29        self.map_err(|e| {
30            let mut message = String::with_capacity(100);
31            if let Some(msg) = msg {
32                message.push_str(msg);
33                message.push_str(". ");
34            }
35            write!(message, "{e}").unwrap();
36            Exception::throw_range(ctx, &message)
37        })
38    }
39
40    fn or_throw_type(self, ctx: &Ctx, msg: Option<&str>) -> Result<T> {
41        self.map_err(|e| {
42            let mut message = String::with_capacity(100);
43            if let Some(msg) = msg {
44                message.push_str(msg);
45                message.push_str(". ");
46            }
47            write!(message, "{e}").unwrap();
48            Exception::throw_type(ctx, &message)
49        })
50    }
51
52    fn or_throw(self, ctx: &Ctx) -> Result<T> {
53        self.map_err(|err| Exception::throw_message(ctx, &err.to_string()))
54    }
55}
56
57impl<T> ResultExt<T> for Option<T> {
58    fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T> {
59        self.ok_or_else(|| Exception::throw_message(ctx, msg))
60    }
61
62    fn or_throw_range(self, ctx: &Ctx, msg: Option<&str>) -> Result<T> {
63        self.ok_or_else(|| Exception::throw_range(ctx, msg.unwrap_or("")))
64    }
65
66    fn or_throw_type(self, ctx: &Ctx, msg: Option<&str>) -> Result<T> {
67        self.ok_or_else(|| Exception::throw_type(ctx, msg.unwrap_or("")))
68    }
69
70    fn or_throw(self, ctx: &Ctx) -> Result<T> {
71        self.ok_or_else(|| Exception::throw_message(ctx, "Value is not present"))
72    }
73}