summaryrefslogtreecommitdiffstats
path: root/Spline/Netstring.pm
diff options
context:
space:
mode:
Diffstat (limited to 'Spline/Netstring.pm')
-rw-r--r--Spline/Netstring.pm42
1 files changed, 42 insertions, 0 deletions
diff --git a/Spline/Netstring.pm b/Spline/Netstring.pm
new file mode 100644
index 0000000..e7e649f
--- /dev/null
+++ b/Spline/Netstring.pm
@@ -0,0 +1,42 @@
+package Spline::Netstring;
+
+use strict;
+use warnings;
+
+our @EXPORT = qw(
+ netstring_read
+ netstring_write
+);
+
+sub read_length($) {
+ my $fd = shift;
+ my $length;
+
+ local $/ = ':';
+ $length = <$fd>;
+ die "Cannot read netstring length" unless defined($length);
+ chomp $length;
+
+ return $length;
+}
+
+sub netstring_read($) {
+ my $fd = shift;
+ my ($length, $data);
+
+ $length = read_length($fd);
+ if (read($fd, $data, $length) == $length) {
+ (getc() eq ',') or die "Closing , missing";
+ }
+ else {
+ die 'Received only ' . length($data) . " of $length bytes";
+ }
+
+ return $data;
+}
+
+sub netstring_write($$) {
+ my ($fd, $data) = @_;
+
+ print $fd length($data).':'.$data.',';
+}