Kalleby SantosK
Denoβ€’12mo agoβ€’
1 reply
Kalleby Santos

How to extend `serde_v8` to handle custom logic?

Hi guys! I'm currently I have the following struct to represent my Tensor object:
// Type alias for TensorElementType (External lib proxy)
// https://serde.rs/remote-derive.html
#[derive(Debug, Serialize, Deserialize)]
#[serde(remote = "TensorElementType", rename_all = "lowercase")]
pub enum JsTensorType {
    /// 32-bit floating point number, equivalent to Rust's `f32`.
    Float32,
    /// Unsigned 8-bit integer, equivalent to Rust's `u8`.
    Uint8,
    /// String, equivalent to Rust's `String`.
    String,
    ...
}

#[derive(Serialize, Deserialize)]
struct JsTensorTypeSerdeHelper(#[serde(with = "JsTensorType")] TensorElementType);

#[derive(Debug, Serialize, Deserialize)]
pub struct JsTensor {
    #[serde(rename = "type", with = "JsTensorType")]
    data_type: TensorElementType,
    data: JsBuffer,
    dims: Vec<i64>,
}

It's working well with #[serde] attribute on my op function. The problem is that I need to extend it to also support string arrays like: ["foo", "bar"], and I can't handle it as JsBuffer so I need to explicit do pattern matching:

enum JsTensorData {
    StringArray(Vec<String>),
    TypedArrayBuffer(JsBuffer),
}

pub struct JsTensor {
    data_type: TensorElementType,
    data: JsTensorData,
    dims: Vec<i64>,
}

---
From the Js land I need to pass an object with the given format, where TypedArray could be any theses:
type Tensor = {
  type: 'float32' | 'uint8' | 'string' // etc...
  data: TypedArray | string[]
  dims: number[]
}


The problem is that even if I use #[serde(untagged)] :
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum JsTensorData {
    StringArray(Vec<String>),
    TypedArrayBuffer(JsBuffer),
}


I can't handle JsBuffer, cause of the following error:
TypeError: data did not match any variant of untagged enum JsTensorData
Was this page helpful?