Skip to content

Commit a036c7c

Browse files
Claudeandrzejressel
andcommitted
Modify from_base64 to return String with UTF-8 validation
Co-authored-by: andrzejressel <1307829+andrzejressel@users.noreply.github.com> Agent-Logs-Url: https://github.com/andrzejressel/pulumi-gestalt/sessions/329159bc-f7a3-4bf3-97ae-b3304adcc8ca
1 parent 3e3cb20 commit a036c7c

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
type: Changed
22
title: Add `pulumi_gestalt_rust::stdlib::to_base64` and `pulumi_gestalt_rust::stdlib::from_base64`
3+
description: |
4+
- `to_base64`: Encodes bytes to base64 string
5+
- `from_base64`: Decodes base64 string to UTF-8 string. Returns an error with a helpful message if the decoded data is not valid UTF-8 (e.g., binary data).

crates/rust/src/stdlib.rs

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,15 @@ pub fn to_base64(input: impl AsRef<[u8]>) -> String {
66
STANDARD.encode(input)
77
}
88

9-
pub fn from_base64(input: impl AsRef<str>) -> Result<Vec<u8>> {
10-
STANDARD
9+
pub fn from_base64(input: impl AsRef<str>) -> Result<String> {
10+
let bytes = STANDARD
1111
.decode(input.as_ref())
12-
.context("Failed to decode base64 data")
12+
.context("Failed to decode base64 data")?;
13+
14+
String::from_utf8(bytes).context(
15+
"Decoded base64 data is not valid UTF-8 string. \
16+
The data may be binary content that cannot be represented as a string.",
17+
)
1318
}
1419

1520
#[cfg(test)]
@@ -23,16 +28,29 @@ mod tests {
2328

2429
#[test]
2530
fn from_base64_decodes_known_text() {
26-
assert_eq!(from_base64("aGVsbG8=").unwrap(), b"hello");
31+
assert_eq!(from_base64("aGVsbG8=").unwrap(), "hello");
2732
}
2833

2934
#[test]
30-
fn roundtrip_binary_data() {
35+
fn roundtrip_text_data() {
36+
let text = "Hello, World! 🌍";
37+
let encoded = to_base64(text);
38+
let decoded = from_base64(encoded).unwrap();
39+
40+
assert_eq!(decoded, text);
41+
}
42+
43+
#[test]
44+
fn from_base64_binary_data_returns_error() {
45+
// Binary data with invalid UTF-8 sequence
3146
let payload = vec![0x00, 0xff, 0x10, 0x41];
3247
let encoded = to_base64(&payload);
33-
let decoded = from_base64(encoded).unwrap();
48+
let result = from_base64(encoded);
3449

35-
assert_eq!(decoded, payload);
50+
assert!(result.is_err());
51+
let error_msg = result.unwrap_err().to_string();
52+
assert!(error_msg.contains("not valid UTF-8"));
53+
assert!(error_msg.contains("binary content"));
3654
}
3755

3856
#[test]

0 commit comments

Comments
 (0)