Repository navigation
feat: add ZipFile::comment_raw, and raw copies keep the comment as stored - #1289
Conversation
|
Hi Thanks for the pull requests. On my side, I think we should have either What about doing for now something like pub fn comment_raw(&self) -> &[u8] {
self.get_metadata().file_comment.as_bytes()
} |
|
Thanks! Makes sense, and I do like that the However, for How about we split it into two PRs?
WDYT? |
|
Since the next breaking (10.x) is not done nor ready. I think the best options right now, would be to split like you said @Pr0methean for validation |
|
@Its-Just-Nans Why do you not want both? As I understand it, we don't know whether the non-Unicode comment is CP437 or not, so we don't know whether the user wants a CP437-to-UTF8 conversion; but since non-Unicode comments are usually CP437, and comments that are explicitly UTF8 are often present, it would be inconvenient to not have the best-effort UTF-8-comment method. Maybe we don't need to store both though; we could convert on demand. |
|
@Its-Just-Nans If you really want to replace them with one method in 10.x, how about we return an enum? enum EncodedString {
Utf8(Box<str>),
Legacy(Box<[u8]>)
}That type would then have an as_utf8_assuming_cp437 method returning Cow. We could make it the stored type as well. |
|
You means, using an enum internally for the My comment about the v10.x was about having this change (to have the same stuff as pub struct ZipFileData {
...
/// File comment
- pub file_comment: Box<str>,
+ pub file_comment: Box<[u8]>,
}
// file comment will always be treated as [u8]
/// Get the comment of the file
-pub fn comment(&self) -> &str {
+pub fn comment(&self) -> ZipResult<Cow<'_, str>> {
+ /// try to self.get_metadata().file_comment to a str
}
+pub fn comment_raw(&self) -> Result<&str, Utf8Error> {
+ &self.get_metadata().file_comment
+}If we directly handle comment as [u8], it will simplify the code in this MR |
| file_comment_raw.as_slice().from_cp437()?.into() | ||
| }; | ||
| let file_comment_raw = | ||
| (*file_comment_raw != *file_comment.as_bytes()).then(|| file_comment_raw.into()); |
There was a problem hiding this comment.
Do this in the above if-else instead and replace from_utf8_lossy with from_utf8. That way we can skip comparing the two potentially long strings if we already know the comment is valid UTF-8. Also check if from_cp437 returned Borrowed, since then the comment is ASCII-only and we can again skip the comparison.
There was a problem hiding this comment.
Good call, done: from_utf8 succeeding or from_cp437 returning Borrowed now skips the comparison. (Invalid UTF-8 under the flag still falls back to the lossy decode and keeps the bytes.)
| drop(file); | ||
| // A copy under a new name writes its comment as UTF-8, like its name. | ||
| let file = archive.by_name("b.txt")?; | ||
| assert_eq!(file.comment_raw(), "ÃâĐÃ^".as_bytes()); |
There was a problem hiding this comment.
Reuse the named constant instead of a magic literal.
| assert_eq!(file.comment_raw(), "ÃâĐÃ^".as_bytes()); | |
| assert_eq!(file.comment_raw(), SHIFT_JIS_COMMENT); |
There was a problem hiding this comment.
No, this one's on purpose. b.txt is the copy under a new name, so its comment is stored as the UTF-8 of the CP437 reading, not the Shift-JIS bytes. SHIFT_JIS_COMMENT would fail here. I added a SHIFT_JIS_COMMENT_AS_CP437 constant for "ÃâĐÃ^" instead and used it in all three places.
There was a problem hiding this comment.
Then use a separate named constant e.g. MOJIBAKE_COMMENT, with a comment explaining how it was generated (stored as Shift-JIS, reinterpreted as CP437 and then converted to UTF-8).
There was a problem hiding this comment.
Done, renamed to MOJIBAKE_COMMENT.
|
@Its-Just-Nans We also need to keep track of whether the comment we're storing was declared to be UTF-8 (either with the flag or by coming from the extra field) or not. I guess actually we need a third enum variant for when it claims to be UTF-8 but isn't valid. We could have two to-UTF8-best-effort methods, one that assumes legacy means CP437 and one under an optional feature that takes an encoding_rs::Decoder parameter. |
|
Pushed the two review fixes. On split vs. both: I'm happy either way. Choose the solution for 10.x (enum or |
âĶes when it's valid UTF-8 or ASCII - `central_header_to_zip_file_inner` now decides whether to keep `file_comment_raw` inside the decode branches: a valid UTF-8 comment (`String::from_utf8` succeeds) and an ASCII-only CP437 one (`from_cp437` returns `Cow::Borrowed`) keep nothing, without comparing two possibly long strings - Invalid UTF-8 under the language encoding flag still decodes lossily and keeps the stored bytes; non-ASCII CP437 always keeps them - Tests name the CP437 reading of the Shift-JIS comment as `SHIFT_JIS_COMMENT_AS_CP437` in place of the repeated literal
0d59712 to
019bc7a
Compare
| match String::from_utf8(file_comment_raw) { | ||
| Ok(file_comment) => (file_comment.into_boxed_str(), None), | ||
| Err(e) => { | ||
| let file_comment_raw = e.into_bytes(); | ||
| ( | ||
| String::from_utf8_lossy(&file_comment_raw).into(), |
There was a problem hiding this comment.
This attempts the conversion twice, which is unnecessary. Use from_utf8_lossy for the outer match and check whether the result is Owned or Borrowed to decide whether we need the raw copy.
âĶys whether to keep its stored bytes - `central_header_to_zip_file_inner` decodes a flagged comment with one `String::from_utf8_lossy` (no separate `from_utf8` pass), and both branches share one match: `Cow::Borrowed` keeps nothing, `Cow::Owned` (invalid UTF-8, or non-ASCII CP437) keeps the stored bytes - Tests name the CP437 reading of the Shift-JIS comment `MOJIBAKE_COMMENT`, with a doc comment on how it's derived
Hi!
(AI use disclosure: Claude-generated PR description that's wordy but okay so I didn't edit it. The code changes are also Claude-created, I've reviewed them and it looks good.)
Here's the
comment_raw()follow-up I promised in #1124. :)The problem: same as names before #1124, for entry comments.
ZipFileDatakeeps only the decoded comment, soraw_copy_filewrites the CP437 reading of a Shift-JIS, GBK, or CP866 comment as UTF-8, under a clear flag. Every tool reads mojibake after that.new_appendandmerge_archiverewrite the central directory from the decoded comment too (since #1160 under a set flag, so the text survives there, but the original bytes don't).What the PR changes:
ZipFile::comment_raw(): the comment bytes as stored in the central directory, next toname_raw().ZipFileDatakeeps those bytes in a crate-privatefile_comment_raw: Option<Box<[u8]>>, only when they differ from the decodedfile_comment. So ASCII and UTF-8 comments (pretty much all of them) cost no extra allocation.raw_copy_file,raw_copy_file_touch,new_append, andmerge_archivekeep a comment as stored, under the entry's own flag.raw_copy_file_rename,deep_copy_file,shallow_copy_file) writes the comment as UTF-8 as before, to match the flag it derives from the new name.comment(), andcomment_raw()keeps the stored bytes.reopening_keeps_a_unicode_comment_extra_field_comment_unchanged(fix(write): flag a non-ASCII file comment as UTF-8 when writing it #1160) still passes, now because the copy writes the original comment back with its extra field and the next read applies it again. SoZipFileData::flagsonly forces the UTF-8 flag for a comment that isn't kept as stored.Tests (end of
write.rs'stestsmodule):comment_raw()returns an unflagged Shift-JIS comment's bytes, and a written UTF-8 comment's.raw_copy_fileandraw_copy_file_touchkeep a Shift-JIS comment byte for byte, with the flag still clear.raw_copy_file_renamewrites it as flagged UTF-8.new_appendkeeps it as stored, and adeep_copy_fileto a new name writes it as flagged UTF-8.The
raw_copy_file,raw_copy_file_touch, andnew_appendones fail without the writer change.cargo test(default, all, no-default,deflate-zopfli, anddeflate-flate2-zlib-rsfeatures), clippy, doc, and fmt pass, apart from clippy'sfield_reassign_with_defaultinextra_field.rswith--no-default-features, which fails onmastertoo.One thing I left alone:
apply_extra_fieldschecks the Unicode Comment extra field's CRC against the decoded comment, but APPNOTE 4.6.8 defines it over the stored comment field. So for a non-ASCII CP437 comment, a valid field never matches. Withcomment_rawaround that's a one-line fix, happy to send it as a separate PR.(FYI, this and #ENCRYPTED_PR both add a field to
ZipRawValues, so whichever lands second gets a tiny conflict in its two struct literals. Happy to rebase.)Thanks!
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.