Skip to main content

serde_v8/magic/
any_value.rs

1// Copyright 2018-2026 the Deno authors. MIT license.
2
3use num_bigint::BigInt;
4
5use super::buffer::JsBuffer;
6use super::transl8::FromV8;
7use super::transl8::ToV8;
8use crate::Error;
9use crate::ToJsBuffer;
10use crate::magic::transl8::impl_magic;
11
12/// An untagged enum type that can be any of number, string, bool, bigint, or
13/// buffer.
14#[derive(Debug)]
15pub enum AnyValue {
16  RustBuffer(ToJsBuffer),
17  V8Buffer(JsBuffer),
18  String(String),
19  Number(f64),
20  BigInt(BigInt),
21  Bool(bool),
22}
23
24impl_magic!(AnyValue);
25
26impl ToV8 for AnyValue {
27  fn to_v8<'scope, 'i>(
28    &self,
29    scope: &mut v8::PinScope<'scope, 'i>,
30  ) -> Result<v8::Local<'scope, v8::Value>, crate::Error> {
31    match self {
32      Self::RustBuffer(buf) => crate::to_v8(scope, buf),
33      Self::V8Buffer(_) => unreachable!(),
34      Self::String(s) => crate::to_v8(scope, s),
35      Self::Number(num) => crate::to_v8(scope, num),
36      Self::BigInt(bigint) => {
37        crate::to_v8(scope, crate::BigInt::from(bigint.clone()))
38      }
39      Self::Bool(b) => crate::to_v8(scope, b),
40    }
41  }
42}
43
44impl FromV8 for AnyValue {
45  fn from_v8<'scope, 'i>(
46    scope: &mut v8::PinScope<'scope, 'i>,
47    value: v8::Local<'scope, v8::Value>,
48  ) -> Result<Self, crate::Error> {
49    if value.is_string() {
50      let string = crate::from_v8(scope, value)?;
51      Ok(AnyValue::String(string))
52    } else if value.is_number() {
53      let string = crate::from_v8(scope, value)?;
54      Ok(AnyValue::Number(string))
55    } else if value.is_big_int() {
56      let bigint = crate::BigInt::from_v8(scope, value)?;
57      Ok(AnyValue::BigInt(bigint.into()))
58    } else if value.is_array_buffer_view() {
59      let buf = JsBuffer::from_v8(scope, value)?;
60      Ok(AnyValue::V8Buffer(buf))
61    } else if value.is_boolean() {
62      let string = crate::from_v8(scope, value)?;
63      Ok(AnyValue::Bool(string))
64    } else {
65      Err(Error::Message(
66        "expected string, number, bigint, ArrayBufferView, boolean".into(),
67      ))
68    }
69  }
70}