mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
fix(twitter): use Cow for tweet metadata to deserialize escaped JSON strings
When tweet text contains JSON escape sequences (such as newlines \n, escaped quotes \", or unicode escapes), serde_json cannot borrow a &str slice from the input string because unescaping requires allocation. Deserializing to borrowed &str returned an error which caused tweet_metadata_from_json to silently fall back to Default::default(), producing titles like "Thread by @unknown" or "Tweet — @unknown". Using std::borrow::Cow<\x27a, str> allows serde_json to borrow unescaped slices with zero allocation while cleanly allocating for strings with escaped characters.
This commit is contained in:
parent
8973a514cc
commit
f41697c800
1 changed files with 17 additions and 3 deletions
|
|
@ -971,7 +971,7 @@ struct TweetJsonMetadata<'a> {
|
|||
#[serde(borrow)]
|
||||
author: Option<TweetAuthorMetadata<'a>>,
|
||||
#[serde(borrow)]
|
||||
full_text: Option<&'a str>,
|
||||
full_text: Option<std::borrow::Cow<'a, str>>,
|
||||
#[serde(borrow)]
|
||||
article: Option<TweetArticleMetadata<'a>>,
|
||||
}
|
||||
|
|
@ -979,13 +979,13 @@ struct TweetJsonMetadata<'a> {
|
|||
#[derive(serde::Deserialize)]
|
||||
struct TweetAuthorMetadata<'a> {
|
||||
#[serde(borrow)]
|
||||
screen_name: Option<&'a str>,
|
||||
screen_name: Option<std::borrow::Cow<'a, str>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct TweetArticleMetadata<'a> {
|
||||
#[serde(borrow)]
|
||||
title: Option<&'a str>,
|
||||
title: Option<std::borrow::Cow<'a, str>>,
|
||||
}
|
||||
|
||||
fn tweet_metadata_from_json(json_str: &str) -> PlatformMetadata {
|
||||
|
|
@ -3776,6 +3776,20 @@ mod tests {
|
|||
);
|
||||
assert_eq!(meta.title, None);
|
||||
}
|
||||
#[test]
|
||||
fn tweet_title_extracted_from_json_with_escapes() {
|
||||
let json = r#"{
|
||||
"full_text": "First line\n\nSecond line with \"quotes\"",
|
||||
"author": { "screen_name": "rustacean", "name": "The Rustacean" }
|
||||
}"#;
|
||||
let meta = tweet_metadata_from_json(json);
|
||||
assert_eq!(meta.author, Some("rustacean".to_string()));
|
||||
assert_eq!(
|
||||
meta.caption,
|
||||
Some("First line\n\nSecond line with \"quotes\"".to_string())
|
||||
);
|
||||
assert_eq!(meta.title, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tweet_prefers_article_title() {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue