NAME
Linux::Event::Stream::Codec - Framing/encoding contract for Linux::Event::Stream
SYNOPSIS
use v5.36;
use Linux::Event;
use Linux::Event::Stream;
# A codec is a (blessed) hashref with two coderefs:
my $codec = Linux::Event::Stream::Codec::make_codec(
name => 'MyApp::Codec::Nul',
decode => sub ($self, $inref, $outref) {
while (1) {
my $i = index($$inref, "\0");
last if $i < 0;
my $msg = substr($$inref, 0, $i, '');
substr($$inref, 0, 1, ''); # drop the NUL
push @$outref, $msg;
}
return 1;
},
encode => sub ($self, $msg) {
return $msg . "\0";
},
);
my $s = Linux::Event::Stream->new(
loop => $loop,
fh => $fh,
codec => $codec,
on_message => sub ($stream, $msg, $data) {
...
},
);
DESCRIPTION
This module documents the codec interface used by Linux::Event::Stream when operating in framed/message mode (codec + on_message). A codec answers exactly one question:
"Where does one message end and the next begin?"
In other words: this is framing + encoding/decoding, not an application protocol.
Codecs are intentionally lightweight: they are (blessed) hashrefs containing two coderefs. Linux::Event::Stream validates these once at construction time and then calls the coderefs directly in the hot path (no per-message method dispatch required).
CODEC CONTRACT
Structure
A codec is a hashref (or blessed hashref) with the following keys:
decode => CODE
encode => CODE
decode
my ($ok, $err) = $codec->{decode}->($codec, \$inbuf, \@out);
The decode callback:
receives the codec object, a reference to the input buffer string, and an arrayref to push decoded messages into
consumes complete messages from
$$inbuf(modify it in-place)pushes 0..N decoded messages onto
@outreturns
(1)on successreturns
(0, $error_string)on failure
If a message is incomplete, leave the remaining bytes in $$inbuf and return (1). Linux::Event::Stream will append more bytes and call decode again later.
encode
my $bytes = $codec->{encode}->($codec, $msg);
The encode callback returns the bytes to be written to the stream for the given message.
HELPERS
This module provides small helpers that are useful when writing your own codec. They are optional; Linux::Event::Stream does not require you to use them.
validate
Linux::Event::Stream::Codec::validate($codec);
Croaks unless $codec is a hashref (or blessed hashref) containing CODE refs at decode and encode.
make_codec
my $codec = Linux::Event::Stream::Codec::make_codec(
name => 'My::Codec',
decode => sub (...) { ...; return 1 },
encode => sub (...) { ... },
);
Creates and returns a blessed codec hashref. The name is optional; if provided, it is used as the blessing package.
SECURITY AND LIMITS
When framing untrusted input (e.g. TCP servers), always enforce reasonable limits.
Cap buffered undecoded bytes (Stream's
max_inbuf)Cap per-frame size (codec option like
max_frame/max_line)
Never allow a peer to grow memory without bound by sending an unterminated frame.