Sha256: db1091e3f51e45791ee2b6617fd4bc0b9a3ad18d5cbf2286ac44ef86319798e0

Contents?: true

Size: 804 Bytes

Versions: 23

Compression:

Stored size: 804 Bytes

Contents

# -*- coding: utf-8 -*-
# Copyright (C) 2011 Rocky Bernstein <rockyb@rubyforge.net>
# Subsidiary routines used to "pack" and "unpack" TCP messages.

module Trepanning
  module TCPPacking

    unless defined?(TCP_MAX_PACKET)
      TCP_MAX_PACKET = 8192 # Largest size for a recv
      LOG_MAX_MSG    = Math.log10(TCP_MAX_PACKET).ceil
    end
      
    def pack_msg(msg)
      fmt = '%%%dd' % LOG_MAX_MSG # A funny way of writing: '%4d'
      (fmt % msg.size) + msg
    end

    def unpack_msg(buf)
      length  = Integer(buf[0...LOG_MAX_MSG])
      data    = buf[LOG_MAX_MSG..LOG_MAX_MSG+length]
      buf     = buf[LOG_MAX_MSG+length..-1]
      [buf, data]
    end
  end
end

# Demo
if __FILE__ == $0
  include Trepanning::TCPPacking
  msg = "Hi there!"
  puts unpack_msg(pack_msg(msg))[1] == msg
end

Version data entries

23 entries across 23 versions & 3 rubygems

Version Path
trepanning-2.15.35 io/tcpfns.rb
trepanning-1.93.35 io/tcpfns.rb
trepanning-2.15.33 io/tcpfns.rb
trepanning-1.93.32 io/tcpfns.rb
rbx-trepanning-0.2.1-universal-rubinius-2.0 io/tcpfns.rb
rbx-trepanning-0.2.1-universal-rubinius-1.2 io/tcpfns.rb
rbx-trepanning-0.2.0-universal-rubinius-2.0 io/tcpfns.rb
rb8-trepanning-0.1.6 io/tcpfns.rb
trepanning-0.1.6 io/tcpfns.rb
rb8-trepanning-0.1.5 io/tcpfns.rb
rbx-trepanning-0.1.0-universal-rubinius-1.2 io/tcpfns.rb
rb8-trepanning-0.1.4 io/tcpfns.rb
trepanning-0.1.4 io/tcpfns.rb
trepanning-0.1.3 io/tcpfns.rb
rb8-trepanning-0.1.3 io/tcpfns.rb
rb8-trepanning-0.1.3-universal-ruby-1.9.2 io/tcpfns.rb
rb8-trepanning-0.1.3-universal-ruby-1.8.7 io/tcpfns.rb
trepanning-0.1.2 io/tcpfns.rb
rbx-trepanning-0.0.8-universal-rubinius-1.2 io/tcpfns.rb
trepanning-0.1.1 io/tcpfns.rb