Skip to content

feat: add ZipFile::comment_raw, and raw copies keep the comment as stored - #1289

Merged
Its-Just-Nans merged 3 commits into
zip-rs:masterfrom
vdavid:feat/comment-raw
Nov 12, 2026
Merged

Its-Just-Nans merged 3 commits into
zip-rs:masterfrom
vdavid:feat/comment-raw

Conversation

@vdavid

@vdavid vdavid commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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. ZipFileData keeps only the decoded comment, so raw_copy_file writes 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_append and merge_archive rewrite 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:

  • New ZipFile::comment_raw(): the comment bytes as stored in the central directory, next to name_raw().
  • ZipFileData keeps those bytes in a crate-private file_comment_raw: Option<Box<[u8]>>, only when they differ from the decoded file_comment. So ASCII and UTF-8 comments (pretty much all of them) cost no extra allocation.
  • The central directory header writes the stored bytes. So raw_copy_file, raw_copy_file_touch, new_append, and merge_archive keep a comment as stored, under the entry's own flag.
  • Everything that names an entry anew (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.
  • An Info-ZIP Unicode Comment extra field still replaces comment(), and comment_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. So ZipFileData::flags only forces the UTF-8 flag for a comment that isn't kept as stored.

Tests (end of write.rs's tests module):

  • comment_raw() returns an unflagged Shift-JIS comment's bytes, and a written UTF-8 comment's.
  • raw_copy_file and raw_copy_file_touch keep a Shift-JIS comment byte for byte, with the flag still clear.
  • raw_copy_file_rename writes it as flagged UTF-8.
  • new_append keeps it as stored, and a deep_copy_file to a new name writes it as flagged UTF-8.

The raw_copy_file, raw_copy_file_touch, and new_append ones fail without the writer change.

cargo test (default, all, no-default, deflate-zopfli, and deflate-flate2-zlib-rs features), clippy, doc, and fmt pass, apart from clippy's field_reassign_with_default in extra_field.rs with --no-default-features, which fails on master too.

One thing I left alone: apply_extra_fields checks 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. With comment_raw around 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!

  • The PR title conforms to Conventional Commits and starts with an Angular type.

Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

@Its-Just-Nans

Copy link
Copy Markdown
Member

Hi

Thanks for the pull requests.

On my side, I think we should have either comment OR comment_raw, not both - possibly a breaking change (like we did for the name and name_raw)

What about doing for now something like

pub fn comment_raw(&self) -> &[u8] {
    self.get_metadata().file_comment.as_bytes()
}

@vdavid

vdavid commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks! Makes sense, and I do like that the name/name_raw model has one source of truth.

However, for file_comment.as_bytes(), it doesn't seem so simple: file_comment holds the already decoded text, so for an unflagged Shift-JIS comment it'd return the UTF-8 of the CP437 reading, not the stored bytes. So comment_raw() would be wrong in exactly the case it's for. It also wouldn't fix the actual bug (raw_copy_file writing mojibake under a clear flag).

How about we split it into two PRs?

  1. This PR: I remove the public comment_raw() and keep only the fix, with the raw bytes in a crate-private field. No API change, so it can go into 9.x.
  2. A future, breaking PR: store only the raw comment bytes, comment() decodes on read like name() does (so ZipResult<Cow<str>> or similar), and add comment_raw().

WDYT?

@Its-Just-Nans

Copy link
Copy Markdown
Member

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

@Pr0methean

Copy link
Copy Markdown
Member

@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.

@Pr0methean

Pr0methean commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

@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.

@Its-Just-Nans

Copy link
Copy Markdown
Member

You means, using an enum internally for the pub(crate) file_comment: Box<str> ? Internally it would be fine but I not sure about the implementation with an enum

My comment about the v10.x was about having this change (to have the same stuff as name and name_raw):

 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

Comment thread src/read/mod.rs Outdated
file_comment_raw.as_slice().from_cp437()?.into()
};
let file_comment_raw =
(*file_comment_raw != *file_comment.as_bytes()).then(|| file_comment_raw.into());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.)

Comment thread src/write.rs Outdated
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());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reuse the named constant instead of a magic literal.

Suggested change
assert_eq!(file.comment_raw(), "Äâ•ĐÉ^".as_bytes());
assert_eq!(file.comment_raw(), SHIFT_JIS_COMMENT);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, renamed to MOJIBAKE_COMMENT.

@Pr0methean

Pr0methean commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

@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.

@vdavid

vdavid commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Pushed the two review fixes.

On split vs. both: I'm happy either way.
One note for 9.x: comment() returns &str, so converting on demand isn't possible without changing its signature. That's why the PR stores the raw bytes next to the decoded text, and only when they differ (so ASCII and valid UTF-8 comments cost nothing extra).

Choose the solution for 10.x (enum or Box<[u8]>), then I can bring a PR for it if you'd like, otherwise feel free to handle it.

â€Ķ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
Comment thread src/read/mod.rs Outdated
Comment on lines +244 to +249
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(),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

â€Ķ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
@vdavid
vdavid requested a review from Pr0methean November 11, 2026 08:57
@Its-Just-Nans
Its-Just-Nans added this pull request to the merge queue Nov 12, 2026
Merged via the queue into zip-rs:master with commit e78bf5c Nov 12, 2026
129 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants