Skip to content

Commit ad12101

Browse files
authored
feat: support creating RawSource from static &str (#129)
* feat: support creating `RawSource` from static str * feat: assert * feat: rename
1 parent 7917de9 commit ad12101

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ dashmap = "5"
3838
memchr = "2.6.4"
3939

4040
codspeed-criterion-compat = { version = "2.3.3", default-features = false, optional = true }
41+
static_assertions = "1.1.0"
4142
simd-json = "=0.14.0-rc.2"
4243

4344
[dev-dependencies]

src/raw_source.rs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ use crate::{
1515
#[derive(Clone, PartialEq, Eq)]
1616
enum RawValue {
1717
Buffer(Vec<u8>),
18-
String(String),
18+
String(Cow<'static, str>),
1919
}
2020

21+
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
22+
static_assertions::assert_eq_size!(RawValue, [u8; 32]);
23+
2124
/// Represents source code without source map, it will not create source map for the source code.
2225
///
2326
/// - [webpack-sources docs](https://github.com/webpack/webpack-sources/#rawsource).
@@ -36,6 +39,24 @@ pub struct RawSource {
3639
value_as_string: OnceLock<String>,
3740
}
3841

42+
impl RawSource {
43+
/// Create a new [RawSource] from a static &str.
44+
///
45+
/// ```
46+
/// use rspack_sources::{RawSource, Source};
47+
///
48+
/// let code = "some source code";
49+
/// let s = RawSource::from_static(code);
50+
/// assert_eq!(s.source(), code);
51+
/// ```
52+
pub fn from_static(s: &'static str) -> Self {
53+
Self {
54+
value: RawValue::String(Cow::Borrowed(s)),
55+
value_as_string: Default::default(),
56+
}
57+
}
58+
}
59+
3960
impl Clone for RawSource {
4061
fn clone(&self) -> Self {
4162
Self {
@@ -57,7 +78,7 @@ impl RawSource {
5778
impl From<String> for RawSource {
5879
fn from(value: String) -> Self {
5980
Self {
60-
value: RawValue::String(value),
81+
value: RawValue::String(value.into()),
6182
value_as_string: Default::default(),
6283
}
6384
}
@@ -75,7 +96,7 @@ impl From<Vec<u8>> for RawSource {
7596
impl From<&str> for RawSource {
7697
fn from(value: &str) -> Self {
7798
Self {
78-
value: RawValue::String(value.to_string()),
99+
value: RawValue::String(value.to_string().into()),
79100
value_as_string: Default::default(),
80101
}
81102
}

0 commit comments

Comments
 (0)