Skip to content

Commit ee77d2d

Browse files
stepanchegfacebook-github-bot
authored andcommitted
ValueTyped::new_err
Summary: Like `ValueTyped::new`, but returns `Err` instead of `None`. Reviewed By: cjhopman Differential Revision: D48932840 fbshipit-source-id: 2c50851662eb7c1de1310e25da9a314a46b91fd8
1 parent f99611a commit ee77d2d

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

starlark/src/values/layout/typed/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,13 @@ impl<'v, T: StarlarkValue<'v>> ValueTyped<'v, T> {
146146
Some(ValueTyped(value, marker::PhantomData))
147147
}
148148

149+
/// Downcast.
150+
#[inline]
151+
pub fn new_err(value: Value<'v>) -> anyhow::Result<ValueTyped<'v, T>> {
152+
value.downcast_ref_err::<T>()?;
153+
Ok(ValueTyped(value, marker::PhantomData))
154+
}
155+
149156
/// Construct typed value without checking the value is of type `<T>`.
150157
#[inline]
151158
pub unsafe fn new_unchecked(value: Value<'v>) -> ValueTyped<'v, T> {

starlark/src/values/layout/value.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,13 @@ use crate::values::UnpackValue;
119119
use crate::values::ValueError;
120120
use crate::values::ValueIdentity;
121121

122+
// We already import another `ValueError`, hence the odd name.
123+
#[derive(Debug, thiserror::Error)]
124+
enum ValueValueError {
125+
#[error("Value is of type `{0}` but `{1}` was expected")]
126+
WrongType(&'static str, &'static str),
127+
}
128+
122129
/// A Starlark value. The lifetime argument `'v` corresponds to the [`Heap`](crate::values::Heap) it is stored on.
123130
///
124131
/// Many of the methods simply forward to the underlying [`StarlarkValue`](crate::values::StarlarkValue).
@@ -1168,6 +1175,15 @@ pub trait ValueLike<'v>:
11681175
/// Get a reference to underlying data or [`None`]
11691176
/// if contained object has different type than requested.
11701177
fn downcast_ref<T: StarlarkValue<'v>>(self) -> Option<&'v T>;
1178+
1179+
/// Get a reference to underlying data or [`Err`]
1180+
/// if contained object has different type than requested.
1181+
fn downcast_ref_err<T: StarlarkValue<'v>>(self) -> anyhow::Result<&'v T> {
1182+
match self.downcast_ref() {
1183+
Some(v) => Ok(v),
1184+
None => Err(ValueValueError::WrongType(self.to_value().get_type(), T::TYPE).into()),
1185+
}
1186+
}
11711187
}
11721188

11731189
#[derive(Debug, thiserror::Error)]

0 commit comments

Comments
 (0)