Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Buffers Laravel Package

charcoal-dev/buffers

Laravel/PHP package providing buffer utilities for handling and transforming data streams in memory. Useful for queueing, chunking, and processing data efficiently with a simple API, supporting common buffer operations for custom workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require charcoal-dev/buffers
    

    No additional configuration is required for basic usage.

  2. First Use Case: Create a buffer from a string or byte array:

    use Charcoal\Buffers\Buffer;
    
    // From a string
    $buffer = Buffer::fromString('Hello, Charcoal!');
    
    // From a byte array
    $buffer = Buffer::fromBytes([0x48, 0x65, 0x6C, 0x6C, 0x6F]);
    
  3. Key Classes:

    • Buffer: Core class for immutable byte buffers.
    • MutableBuffer: For in-place modifications (if needed).
    • BufferCollection: For managing multiple buffers.
  4. Where to Look First:

    • Buffer API Docs (hypothetical link)
    • src/Buffer.php for core methods.
    • tests/ for usage examples.

Implementation Patterns

Common Workflows

1. Data Transformation

// Convert to/from common formats
$buffer = Buffer::fromString('data');
$hex = $buffer->toHex(); // "64617461"
$base64 = $buffer->toBase64(); // "ZGF0YQ=="

2. Binary Operations

// Concatenate buffers
$buffer1 = Buffer::fromString('hello');
$buffer2 = Buffer::fromString('world');
$combined = $buffer1->concat($buffer2); // "helloworld"

// Slice buffers
$slice = $buffer->slice(0, 5); // First 5 bytes

3. Integration with Charcoal Apps

// Use with Charcoal's HTTP layer
$responseBody = Buffer::fromString($rawResponse);
$json = json_decode($responseBody->toString(), true);

// Stream buffers in responses
return response()->stream(function () use ($buffer) {
    echo $buffer->toString();
});

4. Efficient Binary Handling

// Avoid string conversion overhead
$buffer = Buffer::fromBytes([...]);
$processed = $buffer->map(fn($byte) => $byte + 1); // Increment each byte

5. Memory Management

// Release memory explicitly (if needed)
$buffer->release();

Integration Tips

  1. Laravel Service Providers: Bind the buffer classes for dependency injection:

    $this->app->bind(Buffer::class, fn() => new Buffer());
    
  2. Request/Response Handling: Use buffers for binary payloads (e.g., file downloads, WebSocket messages):

    return response()->make($buffer->toBytes(), 200, [
        'Content-Type' => 'application/octet-stream',
    ]);
    
  3. Caching: Serialize buffers for caching:

    Cache::put('buffer_key', $buffer->toBytes(), $minutes);
    $buffer = Buffer::fromBytes(Cache::get('buffer_key'));
    
  4. Event Payloads: Use buffers for binary event payloads in Laravel Echo/Pusher:

    broadcast(new BinaryEvent($buffer->toBytes()));
    

Gotchas and Tips

Pitfalls

  1. Immutability:

    • Buffer is immutable. Use MutableBuffer for in-place modifications or create new buffers via methods like slice(), map(), etc.
    • Fix: Prefer functional operations over mutation:
      // Bad: Trying to modify directly
      $buffer->offsetSet(0, 0xAA); // Throws Error
      
      // Good:
      $newBuffer = $buffer->withByte(0, 0xAA);
      
  2. Memory Leaks:

    • Buffers hold references to underlying byte arrays. Forgetting to release large buffers can cause memory bloat.
    • Fix: Use release() for large buffers or rely on PHP’s garbage collection:
      $largeBuffer = Buffer::fromBytes($hugeArray);
      // ... use $largeBuffer ...
      $largeBuffer->release(); // Explicit cleanup
      
  3. String vs. Bytes:

    • toString() and fromString() handle encoding/decoding. Ensure consistency:
      // May throw EncodingError if bytes aren't valid UTF-8
      $buffer->toString();
      
    • Fix: Use toBytes() for raw binary data or specify encoding:
      $buffer->toString('ISO-8859-1');
      
  4. Thread Safety:

    • Buffers are not thread-safe by design. Avoid sharing mutable buffers across threads.
    • Fix: Use immutable buffers or synchronize access.

Debugging Tips

  1. Inspect Buffers:

    $buffer->dump(); // Pretty-print bytes/hex/string
    $buffer->hexDump(); // Detailed hex view
    
  2. Validate Input:

    • Use isValid() to check if bytes form a valid string:
      if (!$buffer->isValid()) {
          throw new \InvalidArgumentException('Invalid UTF-8 bytes');
      }
      
  3. Performance Profiling:

    • Compare Buffer vs. native PHP strings/arrays for hot paths:
      $time = microtime(true);
      $buffer->map(fn($byte) => $byte * 2);
      $elapsed = microtime(true) - $time;
      

Extension Points

  1. Custom Encodings: Extend Buffer to support custom encodings:

    class CustomBuffer extends Buffer {
        public function toCustomEncoding(): string {
            // Implement custom logic
        }
    }
    
  2. Buffer Factories: Create domain-specific factories:

    class ImageBufferFactory {
        public static function fromImage(string $path): Buffer {
            return Buffer::fromBytes(file_get_contents($path));
        }
    }
    
  3. Event Listeners: Listen for buffer events (if the package emits them):

    Buffer::listen('created', function ($buffer) {
        Log::debug("Buffer created with size: {$buffer->length()}");
    });
    
  4. Testing Helpers: Add custom assertions for testing:

    $this->assertBufferEquals($expectedBuffer, $actualBuffer);
    

Config Quirks

  1. Default Encoding: The package defaults to UTF-8 for string operations. Override globally:

    Buffer::setDefaultEncoding('ISO-8859-1');
    
  2. Chunk Size: For large buffers, operations like toHex() may chunk data. Adjust if needed:

    $buffer->toHex(16); // Custom chunk size
    
  3. Environment-Specific Behavior: Use Laravel’s config to customize buffer behavior:

    // config/buffers.php
    return [
        'default_encoding' => env('BUFFER_ENCODING', 'UTF-8'),
        'max_buffer_size' => env('MAX_BUFFER_SIZE', 1024 * 1024), // 1MB
    ];
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment