Skip to content

use ByteString toArrayUnsafe in new deflater code#1135

Draft
pjfanning wants to merge 5 commits into
apache:mainfrom
pjfanning:deflate-unsafe
Draft

use ByteString toArrayUnsafe in new deflater code#1135
pjfanning wants to merge 5 commits into
apache:mainfrom
pjfanning:deflate-unsafe

Conversation

@pjfanning

@pjfanning pjfanning commented Jul 6, 2026

Copy link
Copy Markdown
Member

Code looks like it should be ok to use toArrayUnsafe, that no other code should be able to modify the array data.

toArrayUnsafe() on ByteString is only really helpful for ByteStrings directly backed by 1 byte array with no offset. Otherwise, it gives you the same as toArray.

I don't know if the costs outweigh the benefits but if used an InflaterInputStream, we can get an InputStream from a ByteString that can avoid array copies for all ByteString types - but with extra expense to manage the stream, etc.

new InflaterInputStream(byteString.asInputStream)

@pjfanning pjfanning changed the title [WIP] use ByteString toArrayUnsafe in new deflater code use ByteString toArrayUnsafe in new deflater code Jul 6, 2026
@pjfanning pjfanning requested a review from He-Pin July 6, 2026 13:01
@pjfanning

Copy link
Copy Markdown
Member Author

@mkurz does this look ok?

try {
val input = if (appendTail) data ++ EmptyStoredBlock else data
inflater.setInput(input.toArray)
inflater.setInput(input.toArrayUnsafe())

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.

can we use the asInputStream here

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

would need something like new InflaterInputStream(byteString.asInputStream)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

actually it's CRC32 that is what uses the bytes from the ByteString not the Inflater directly

@pjfanning pjfanning marked this pull request as draft July 6, 2026 13:44
deflater.setInput(data.toArray)
val output = new ByteArrayOutputStream()
deflater.setInput(data.toArrayUnsafe())
val output = new ByteArrayOutputStream(1024)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ByteArrayOutputStream starts with 32 bytes by default and you can end up allocating multiple new arrays while you grow the data. Starting with a reasonable value can help.

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.

2 participants