« lib/Devel/Trepan/CmdProcessor/Command/Finish.pm
↑ Summary
blib/lib/Devel/Trepan/CmdProcessor/Command/Show_Subcmd/Display_Subcmd/Eval.pm »
| 1 | # -*- coding: utf-8 -*- | ||
| 2 | # Copyright (C) 2011, 2014 Rocky Bernstein <rocky@cpan.org> | ||
| 3 | # Subsidiary routines used to "pack" and "unpack" TCP messages. | ||
| 4 | use strict; use warnings; no warnings 'redefine'; | ||
| 5 | |||
| 6 | package Devel::Trepan::IO::TCPPack; | ||
| 7 | use POSIX qw(ceil log10); | ||
| 8 | use Exporter; | ||
| 9 | our (@ISA, @EXPORT); | ||
| 10 | @ISA = qw(Exporter); | ||
| 11 | @EXPORT = qw(TCP_MAX_PACKET LOG_MAX_MSG pack_msg unpack_msg); | ||
| 12 | |||
| 13 | use constant TCP_MAX_PACKET => 8192; | ||
| 14 | use constant LOG_MAX_MSG => ceil(log10(TCP_MAX_PACKET)); | ||
| 15 | |||
| 16 | sub pack_msg($) | ||
| 17 | { | ||
| 18 | my $msg = shift; | ||
| 19 | # A funny way of writing: '%04d' | ||
| 20 | my $fmt = sprintf '%%0%dd' , LOG_MAX_MSG; | ||
| 21 | return sprintf($fmt, length($msg)) . $msg; | ||
| 22 | } | ||
| 23 | |||
| 24 | sub unpack_msg($) | ||
| 25 | { | ||
| 26 | my $buf = shift; | ||
| 27 | unless ($buf) { | ||
| 28 | die "Protocol error - no text" | ||
| 29 | } | ||
| 30 | |||
| 31 | my ($pkg, $filename, $line) = caller; | ||
| 32 | my $strnum = substr($buf, 0, LOG_MAX_MSG); | ||
| 33 | unless ($strnum =~ /^\d+$/) { | ||
| 34 | print STDERR "Protocol error - no length; got '$buf'\n"; | ||
| 35 | return ($buf, '#'); | ||
| 36 | } | ||
| 37 | my $length = int($strnum); | ||
| 38 | my $data = substr($buf, LOG_MAX_MSG, $length); | ||
| 39 | if (length($buf) > LOG_MAX_MSG + $length) { | ||
| 40 | $buf = substr($buf, LOG_MAX_MSG + $length); | ||
| 41 | } else { | ||
| 42 | $buf = ''; | ||
| 43 | } | ||
| 44 | return ($buf, $data); | ||
| 45 | } | ||
| 46 | |||
| 47 | # Demo | ||
| 48 | unless (caller) { | ||
| 49 | my $buf = "Hi there!"; | ||
| 50 | my $msg; | ||
| 51 | ($buf, $msg) = unpack_msg(pack_msg($buf)); | ||
| 52 | print "$msg\n"; | ||
| 53 | } | ||
| 54 | |||
| 55 | 1; |