web-infra-dev / rspack

The fast Rust-based web bundler with webpack-compatible API 🦀️
https://rspack.dev
MIT License
10.13k stars 575 forks source link

feat: rspack_cacheable support `as` attr #8521

Closed jerrykingxyz closed 23 hours ago

jerrykingxyz commented 1 day ago

Summary

This PR will:

  1. add Inline wrapper type, which can convert the cacheable data reference. Note that since the Inline does not implement the deserialize method, it cannot be used with from_bytes.
    
    use rspack_cacheable::{cacheable, to_bytes, with::Inline};

[cacheable]

struct Data { block1: String }

[cacheable]

struct DataRef<'a> {

[cacheable(with=Inline)]

block1: &'a String

}

let data = Data { block1: "block1".into() } let data_ref = DataRef { block1: &data.block1 } assert_eq!(to_bytes(&data, &()), to_bytes(&data_ref, &()));


2. add `as` attr in `#[cacheable]` when use at struct, and it is used to config the struct that deserialize converts to, requiring its memory layout to match the current structure.
``` rust
use rspack_cacheable::{
  cacheable, from_bytes, to_bytes,
  with::{AsTuple2, Inline},
};

#[cacheable]
#[derive(Debug, PartialEq, Eq)]
struct Person {
  name: String,
  content: (String, String),
}

#[cacheable(as=Person)]
struct PersonRef<'a> {
  #[rkyv(with=Inline)]
  name: &'a String,
  #[rkyv(with=AsTuple2<Inline, Inline>)]
  content: (&'a String, &'a String),
}

#[test]
fn as_attr() {
  let a = Person {
    name: "abc".into(),
    content: ("a".into(), "b".into()),
  };
  let a_ref = PersonRef {
    name: &a.name,
    content: (&a.content.0, &a.content.1),
  };
  // use a_ref to serialize
  let bytes = to_bytes(&a_ref, &()).unwrap();
  // deserialize to Person
  let deserialize_a: Person = from_bytes(&bytes, &()).unwrap();
  assert_eq!(a, deserialize_a);
}

Checklist

netlify[bot] commented 1 day ago

Deploy Preview for rspack canceled.

Name Link
Latest commit b0ab1c7792c1d547b538ec418d7444a30e8aa414
Latest deploy log https://app.netlify.com/sites/rspack/deploys/67442cc74cd71e0008b4607a
codspeed-hq[bot] commented 1 day ago

CodSpeed Performance Report

Merging #8521 will not alter performance

Comparing jerry/cacheable (b0ab1c7) with main (eb12150)

Summary

✅ 1 untouched benchmarks