Skip to content

Conversation

thekid
Copy link
Contributor

@thekid thekid commented Apr 27, 2025

Implements feature suggested in #64


Example

// compression
$resource = zstd_compress_init();
$compressed = '';
$compressed .= zstd_compress_add($resource, 'Hello, ', false);
$compressed .= zstd_compress_add($resource, 'World!', false);
$compressed .= zstd_compress_add($resource, '', true);

echo zstd_uncompress($compressed), PHP_EOL; // Hello, World!

// uncompression
$resource = zstd_uncompress_init();
$uncompressed = '';
$uncompressed .= zstd_uncompress_add($resource, substr($compressed, 0, 5));
$uncompressed .= zstd_uncompress_add($resource, substr($compressed, 5));

echo $uncompressed, PHP_EOL; // Hello, World!

Summary by CodeRabbit

  • New Features

    • Introduced incremental compression and decompression support, allowing data to be processed in chunks using new functions for initializing and updating compression/decompression contexts.
    • Added new functions and namespace aliases for incremental operations, enabling streaming workflows.
  • Documentation

    • Updated documentation to describe the new incremental compression and decompression functions, including detailed usage, parameters, and return values.
  • Tests

    • Added comprehensive tests to verify the correctness and consistency of incremental compression and decompression functionality across various chunk sizes and usage scenarios.

Copy link

coderabbitai bot commented Apr 27, 2025

Warning

Rate limit exceeded

@thekid has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 473b548 and cef80f0.

📒 Files selected for processing (1)
  • zstd.stub.php (3 hunks)

Walkthrough

The changes introduce incremental compression and decompression capabilities to the PHP Zstd extension. This is achieved by adding a new internal ZstdContext class and four new functions: zstd_compress_init, zstd_compress_add, zstd_uncompress_init, and zstd_uncompress_add, with equivalents in the Zstd namespace. These functions allow for streaming compression and decompression by managing state across multiple calls. The documentation and stubs are updated accordingly, and several new tests are added to verify the correct behavior of the incremental API.

Changes

File(s) Change Summary
README.md Updated documentation to describe new incremental compression/decompression functions and their usage.
zstd.c Implemented incremental compression/decompression logic, added ZstdContext class, registered new functions and aliases.
zstd.stub.php Added class and function declarations for incremental compression/decompression in both global and Zstd namespaces.
tests/inc.phpt, tests/inc_ns.phpt Added tests for basic incremental compression and decompression, including namespace usage.
tests/inc_comp.phpt Added test for incremental compression across various chunk sizes.
tests/inc_decomp.phpt Added test for incremental decompression across various chunk sizes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PHP_Extension
    participant ZstdContext

    User->>PHP_Extension: zstd_compress_init(level)
    PHP_Extension->>ZstdContext: Create compression context
    PHP_Extension-->>User: ZstdContext object

    User->>PHP_Extension: zstd_compress_add(ZstdContext, data, end)
    PHP_Extension->>ZstdContext: Feed data chunk
    ZstdContext-->>PHP_Extension: Compressed chunk
    PHP_Extension-->>User: Compressed data

    User->>PHP_Extension: zstd_uncompress_init()
    PHP_Extension->>ZstdContext: Create decompression context
    PHP_Extension-->>User: ZstdContext object

    User->>PHP_Extension: zstd_uncompress_add(ZstdContext, data)
    PHP_Extension->>ZstdContext: Feed compressed chunk
    ZstdContext-->>PHP_Extension: Decompressed chunk
    PHP_Extension-->>User: Decompressed data
Loading

Poem

🐇
With every chunk, a hop and skip,
Zstd streams now compress and unzip!
Contexts remember, data flows right,
In tests and docs, all shines bright.
From buffer to buffer, we leap and bound—
Incremental magic, streamingly profound!
—A rabbit coding, with joy unbound.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (11)
tests/inc.phpt (1)

1-28: LGTM! Good basic test for the incremental API

This test effectively validates the core functionality of the incremental compression and decompression API. It correctly tests:

  1. Initializing contexts
  2. Adding data incrementally
  3. Finalizing compression
  4. Verifying data integrity through decompression

If the API provides a way to explicitly close or free the context resources, consider adding that to the test to demonstrate proper resource management.

tests/inc_decomp.phpt (2)

5-5: Consider adding a comment explaining the included data

The test includes external data, but there's no indication of what data.inc contains.

-include(dirname(__FILE__) . '/data.inc');
+// Include test data - contains a sample string for compression testing
+include(dirname(__FILE__) . '/data.inc');

9-23: LGTM! Thorough testing of incremental decompression

This test effectively verifies that incremental decompression works correctly with various chunk sizes. Good job on testing with multiple chunk sizes and verifying data integrity.

Consider adding a test with a very small chunk size (e.g., 1 byte) to ensure the decompression context can handle extreme chunking.

tests/inc_comp.phpt (1)

5-5: Consider adding a comment explaining the included data

The test includes external data, but there's no indication of what data.inc contains.

-include(dirname(__FILE__) . '/data.inc');
+// Include test data - contains a sample string for compression testing
+include(dirname(__FILE__) . '/data.inc');
README.md (3)

107-111: Fix typos in newly-listed API names

zstd_compress_init / zstd_uncompress_init accidentally lost the second underscore before init.
This can be confusing for users who copy/paste the README examples and will also break Markdown autolinking.

-* zstd\_compress_\init — Initialize an incremental compress context
-* zstd\_uncompress_\init — Initialize an incremental uncompress context
+* zstd\_compress\_init — Initialize an incremental compress context
+* zstd\_uncompress\_init — Initialize an incremental uncompress context

229-235: Minor wording – missing preposition

The sentence reads “Returns a zstd context instance success”.
Add the preposition on for correct grammar.

-Returns a zstd context instance success, or FALSE on failure
+Returns a zstd context instance on success, or FALSE on failure

315-318: Synchronise namespace-alias list with corrected names

The namespace alias list still contains the single-underscore variants; adjust for consistency.

-`zstd_uncompress_init` and `zstd_uncompress_add` function alias.
+`zstd_uncompress_init` and `zstd_uncompress_add` function aliases.

(And ensure the function names contain both underscores.)

🧰 Tools
🪛 LanguageTool

[uncategorized] ~315-~315: Loose punctuation mark.
Context: ... $context, $data ) ``` zstd_compress, `zstd_uncompress`, `zstd_compress_dict`...

(UNLIKELY_OPENING_PUNCTUATION)

zstd.stub.php (2)

13-20: Declare the ZstdContext class in stubs to keep static analysers happy

Tools like Psalm / PHPStan will raise “unknown type” warnings for the ZstdContext parameter & return types.

+/** @generated-class */
+final class ZstdContext {}

Add this (preferably above the global‐namespace functions) so that IDEs recognise the symbol.


33-40: Uniform default-parameter spacing

Tiny consistency nit – other stubs use int $level = 3 (space on both sides of =).

-function compress_init(int $level= 3): ZstdContext|false {}
+function compress_init(int $level = 3): ZstdContext|false {}

Apply to all four signatures for visual consistency.

zstd.c (2)

118-126: Zero-initialisation of intern->ctx is currently implicit

zend_object_alloc() zeroes the memory, so intern->ctx starts as NULL, but adding an explicit assignment improves readability and guards against future refactors that might switch allocation helpers.

    object_properties_init(&intern->zo, class_type);
+    intern->ctx = NULL;

548-563: Return value size can explode for very large inputs

smart_string_appendl() reallocates aggressively; for huge streams a single zstd_compress_add() could allocate multi-GB buffers.

Consider limiting chunk size or streaming directly to a zend_string with incremental reallocation, similar to the pattern in php_zstd_output_handler_write(), to cap peak memory usage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdc42be and ef61a70.

📒 Files selected for processing (7)
  • README.md (3 hunks)
  • tests/inc.phpt (1 hunks)
  • tests/inc_comp.phpt (1 hunks)
  • tests/inc_decomp.phpt (1 hunks)
  • tests/inc_ns.phpt (1 hunks)
  • zstd.c (7 hunks)
  • zstd.stub.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
zstd.c (1)
zstd.stub.php (8)
  • zstd_compress_init (13-13)
  • zstd_compress_add (15-15)
  • zstd_uncompress_init (17-17)
  • zstd_uncompress_add (19-19)
  • compress_init (33-33)
  • compress_add (35-35)
  • uncompress_init (37-37)
  • uncompress_add (39-39)
zstd.stub.php (1)
zstd.c (4)
  • zstd_compress_init (491-523)
  • zstd_compress_add (525-566)
  • zstd_uncompress_init (568-588)
  • zstd_uncompress_add (590-634)
🪛 LanguageTool
README.md

[uncategorized] ~315-~315: Loose punctuation mark.
Context: ... $context, $data ) ``` zstd_compress, `zstd_uncompress`, `zstd_compress_dict`...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (3)
tests/inc_ns.phpt (1)

1-28: LGTM! Good verification of namespace versions

This test properly validates that the namespace versions of the incremental API functions work correctly.

tests/inc_comp.phpt (2)

7-23: LGTM! Well-structured incremental compression test

This test thoroughly validates the incremental compression functionality with different chunk sizes. Good job on verifying:

  1. Proper context initialization
  2. Chunk-by-chunk compression
  3. Compression finalization
  4. Compression efficiency (compressed size < original size)
  5. Data integrity through decompression

19-19: Good explicit finalization of the compression stream

Correctly demonstrates finalizing the compression by adding an empty chunk with the end flag set to true.

Comment on lines +610 to +630
ZSTD_inBuffer in = { in_buf, in_size, 0 };
size_t res = 1;
const size_t grow = ZSTD_DStreamOutSize();

while (in.pos < in.size && res > 0) {
if (ctx->output.pos == ctx->output.size) {
ctx->output.size += grow;
ctx->output.dst = erealloc(ctx->output.dst, ctx->output.size);
}

ctx->output.pos = 0;
res = ZSTD_decompressStream(ctx->dctx, &ctx->output, &in);
if (ZSTD_isError(res)) {
php_error_docref(NULL, E_WARNING,
"libzstd error %s\n", ZSTD_getErrorName(res));
smart_string_free(&out);
RETURN_FALSE;
}

smart_string_appendl(&out, ctx->output.dst, ctx->output.pos);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential unbounded growth of ctx->output.dst

zstd_uncompress_add() keeps growing ctx->output.dst with erealloc() but never shrinks it.
A long-lived context processing a single large packet followed by many tiny packets will hold on to the peak allocation.

A simple mitigation is to cap the buffer at, say, twice the maximum chunk size or free & re-malloc when it exceeds a threshold.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 901c587 and 473b548.

📒 Files selected for processing (2)
  • README.md (3 hunks)
  • zstd.c (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • zstd.c
🧰 Additional context used
🪛 LanguageTool
README.md

[uncategorized] ~315-~315: Loose punctuation mark.
Context: ... $context, $data ) ``` zstd_compress, `zstd_uncompress`, `zstd_compress_dict`...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (4)
README.md (4)

107-110: Functions list updated correctly.
The incremental API functions (zstd_compress_init, zstd_compress_add, zstd_uncompress_init, zstd_uncompress_add) are now listed alongside the existing one-shot functions as expected.


236-261: Docs for zstd_compress_add are clear.
The signature, description, parameters, and return values accurately reflect the implementation.


276-297: Docs for zstd_uncompress_add look good.
Signature and descriptions match the implementation.


315-318: Alias summary is accurate.
The list of function aliases is correctly enumerated.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~315-~315: Loose punctuation mark.
Context: ... $context, $data ) ``` zstd_compress, `zstd_uncompress`, `zstd_compress_dict`...

(UNLIKELY_OPENING_PUNCTUATION)

Comment on lines +308 to +312
function compress_init ( [ $level = 3 ] )
function compress_add ( $context, $data [, $end = false ] )
function uncompress_init ()
function uncompress_add ( $context, $data )

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Align namespace alias default parameter.
The namespaced compress_init alias currently defaults to 3, but the core docs and implementation use ZSTD_COMPRESS_LEVEL_DEFAULT. For consistency, reference the constant here as well.

- function compress_init ( [ $level = 3 ] )
+ function compress_init ( [ $level = ZSTD_COMPRESS_LEVEL_DEFAULT ] )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function compress_init ( [ $level = 3 ] )
function compress_add ( $context, $data [, $end = false ] )
function uncompress_init ()
function uncompress_add ( $context, $data )
function compress_init ( [ $level = ZSTD_COMPRESS_LEVEL_DEFAULT ] )
function compress_add ( $context, $data [, $end = false ] )
function uncompress_init ()
function uncompress_add ( $context, $data )

Comment on lines +217 to +224
### zstd\_compress\_init — Initialize an incremental compress context

#### Description

resource **zstd\_compress\_init** ( [ int _$level_ = ZSTD_COMPRESS_LEVEL_DEFAULT ] )

Initialize an incremental compress context

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update return type and wording for zstd_compress_init.
The docs still say resource **zstd_compress_init**, but the implementation now returns a ZstdContext object—not a resource. Also consider using the noun “compression” instead of the verb “compress.”

Apply this diff:

- resource **zstd_compress_init** ( [ int _$level_ = ZSTD_COMPRESS_LEVEL_DEFAULT ] )
- Initialize an incremental compress context
+ ZstdContext **zstd_compress_init** ( [ int _$level_ = ZSTD_COMPRESS_LEVEL_DEFAULT ] )
+ Initialize an incremental compression context
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
### zstd\_compress\_init — Initialize an incremental compress context
#### Description
resource **zstd\_compress\_init** ( [ int _$level_ = ZSTD_COMPRESS_LEVEL_DEFAULT ] )
Initialize an incremental compress context
### zstd\_compress\_init — Initialize an incremental compress context
#### Description
ZstdContext **zstd\_compress\_init** ( [ int _$level_ = ZSTD_COMPRESS_LEVEL_DEFAULT ] )
Initialize an incremental compression context

Comment on lines +263 to +274
### zstd\_uncompress\_init — Initialize an incremental uncompress context

#### Description

resource **zstd\_uncompress\_init** ( void )

Initialize an incremental uncompress context

#### Return Values

Returns a zstd context instance on success, or FALSE on failure

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update return type for zstd_uncompress_init.
Similar to zstd_compress_init, this function returns a ZstdContext object. Update the docs accordingly:

- resource **zstd_uncompress_init** ( void )
- Initialize an incremental uncompress context
+ ZstdContext **zstd_uncompress_init** ( void )
+ Initialize an incremental uncompress context
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
### zstd\_uncompress\_init — Initialize an incremental uncompress context
#### Description
resource **zstd\_uncompress\_init** ( void )
Initialize an incremental uncompress context
#### Return Values
Returns a zstd context instance on success, or FALSE on failure
### zstd\_uncompress\_init — Initialize an incremental uncompress context
#### Description
ZstdContext **zstd_uncompress_init** ( void )
Initialize an incremental uncompress context
#### Return Values
Returns a zstd context instance on success, or FALSE on failure

@kjdev kjdev merged commit 0f2d08b into kjdev:master May 20, 2025
@thekid thekid deleted the feature/incremental-obj branch June 22, 2025 11:38
This was referenced Jul 18, 2025
thekid added a commit to xp-forge/compression that referenced this pull request Jul 29, 2025
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