quickjs_jit_stdlib/llrt/llrt_utils/
result.rs1#![allow(clippy::uninlined_format_args)]
6
7use std::{fmt::Write, result::Result as StdResult};
8
9use rquickjs::{Ctx, Exception, Result};
10
11pub trait ResultExt<T> {
12 fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T>;
13 fn or_throw_range(self, ctx: &Ctx, msg: &str) -> Result<T>;
14 fn or_throw_type(self, ctx: &Ctx, msg: &str) -> Result<T>;
15 fn or_throw(self, ctx: &Ctx) -> Result<T>;
16}
17
18pub trait OptionExt<T> {
19 fn and_then_ok<U, E, F>(self, f: F) -> StdResult<Option<U>, E>
20 where
21 F: FnOnce(T) -> StdResult<Option<U>, E>;
22
23 fn unwrap_or_else_ok<E, F>(self, f: F) -> StdResult<T, E>
24 where
25 F: FnOnce() -> StdResult<T, E>;
26}
27
28impl<T, E: std::fmt::Display> ResultExt<T> for StdResult<T, E> {
29 fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T> {
30 self.map_err(|e| {
31 let mut message = String::with_capacity(100);
32 message.push_str(msg);
33 message.push_str(". ");
34 write!(message, "{}", e).unwrap();
35 Exception::throw_message(ctx, &message)
36 })
37 }
38
39 fn or_throw_range(self, ctx: &Ctx, msg: &str) -> Result<T> {
40 self.map_err(|e| {
41 let mut message = String::with_capacity(100);
42 if !message.is_empty() {
43 message.push_str(msg);
44 message.push_str(". ");
45 }
46 write!(message, "{}", e).unwrap();
47 Exception::throw_range(ctx, &message)
48 })
49 }
50
51 fn or_throw_type(self, ctx: &Ctx, msg: &str) -> Result<T> {
52 self.map_err(|e| {
53 let mut message = String::with_capacity(100);
54 if !msg.is_empty() {
55 message.push_str(msg);
56 message.push_str(". ");
57 }
58 write!(message, "{}", e).unwrap();
59 Exception::throw_type(ctx, &message)
60 })
61 }
62
63 fn or_throw(self, ctx: &Ctx) -> Result<T> {
64 self.map_err(|err| Exception::throw_message(ctx, &err.to_string()))
65 }
66}
67
68impl<T> ResultExt<T> for Option<T> {
69 fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T> {
70 self.ok_or_else(|| Exception::throw_message(ctx, msg))
71 }
72
73 fn or_throw_range(self, ctx: &Ctx, msg: &str) -> Result<T> {
74 self.ok_or_else(|| Exception::throw_range(ctx, msg))
75 }
76
77 fn or_throw_type(self, ctx: &Ctx, msg: &str) -> Result<T> {
78 self.ok_or_else(|| Exception::throw_type(ctx, msg))
79 }
80
81 fn or_throw(self, ctx: &Ctx) -> Result<T> {
82 self.ok_or_else(|| Exception::throw_message(ctx, "Value is not present"))
83 }
84}
85
86impl<T> OptionExt<T> for Option<T> {
87 fn and_then_ok<U, E, F>(self, f: F) -> StdResult<Option<U>, E>
88 where
89 F: FnOnce(T) -> StdResult<Option<U>, E>,
90 {
91 match self {
92 Some(v) => f(v),
93 None => Ok(None),
94 }
95 }
96
97 fn unwrap_or_else_ok<E, F>(self, f: F) -> StdResult<T, E>
98 where
99 F: FnOnce() -> StdResult<T, E>,
100 {
101 match self {
102 Some(v) => Ok(v),
103 None => f(),
104 }
105 }
106}