Skip to content

Commit d214858

Browse files
committed
fix: let bytes_to_string() return Cow to avoid unnecessary copy
1 parent 177bf2d commit d214858

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

src/base/value.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,12 @@ impl From<String> for KeyPart {
115115
}
116116
}
117117

118+
impl From<Cow<'_, str>> for KeyPart {
119+
fn from(value: Cow<'_, str>) -> Self {
120+
KeyPart::Str(Arc::from(value))
121+
}
122+
}
123+
118124
impl From<bool> for KeyPart {
119125
fn from(value: bool) -> Self {
120126
KeyPart::Bool(value)
@@ -522,6 +528,12 @@ impl From<String> for BasicValue {
522528
}
523529
}
524530

531+
impl From<Cow<'_, str>> for BasicValue {
532+
fn from(value: Cow<'_, str>) -> Self {
533+
BasicValue::Str(Arc::from(value))
534+
}
535+
}
536+
525537
impl From<bool> for BasicValue {
526538
fn from(value: bool) -> Self {
527539
BasicValue::Bool(value)

src/ops/sources/google_drive.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,8 @@ impl SourceExecutor for Executor {
400400
if self.binary {
401401
content.to_bytes().to_vec().into()
402402
} else {
403-
let (s, _) = utils::bytes_decode::bytes_to_string(&content.to_bytes());
403+
let bytes = content.to_bytes();
404+
let (s, _) = utils::bytes_decode::bytes_to_string(&bytes);
404405
s.into()
405406
},
406407
];

src/utils/bytes_decode.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
use encoding_rs::Encoding;
22

3-
pub fn bytes_to_string(bytes: &[u8]) -> (String, bool) {
3+
pub fn bytes_to_string<'a>(bytes: &'a [u8]) -> (std::borrow::Cow<'a, str>, bool) {
44
// 1) BOM sniff first (definitive for UTF-8/16; UTF-32 is not supported here).
55
if let Some((enc, bom_len)) = Encoding::for_bom(bytes) {
66
let (cow, had_errors) = enc.decode_without_bom_handling(&bytes[bom_len..]);
7-
return (cow.into_owned(), had_errors);
7+
return (cow, had_errors);
88
}
99
// 2) Otherwise, try UTF-8 (accepts input with or without a UTF-8 BOM).
1010
let (cow, had_errors) = encoding_rs::UTF_8.decode_with_bom_removal(bytes);
11-
(cow.into_owned(), had_errors)
11+
(cow, had_errors)
1212
}

0 commit comments

Comments
 (0)