Skip to content

Commit

Permalink
packet: documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
astro committed Sep 14, 2009
1 parent 99712b4 commit b133f3b
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions lib/remcached/packet.rb
Expand Up @@ -2,6 +2,8 @@

module Memcached
class Packet
##
# Initialize with fields
def initialize(contents={})
@contents = contents
(self.class.fields +
Expand All @@ -10,40 +12,55 @@ def initialize(contents={})
end
end

##
# Get field
def [](field)
@contents[field]
end

##
# Set field
def []=(field, value)
@contents[field] = value
end

# Define fields for subclasses
##
# Define a field for subclasses
def self.field(name, packed, default=nil)
instance_eval do
@fields ||= []
@fields << [name, packed, default]
end
end

##
# Fields of parent and this class
def self.fields
parent_class = ancestors[1]
parent_fields = parent_class.respond_to?(:fields) ? parent_class.fields : []
class_fields = instance_eval { @fields || [] }
parent_fields + class_fields
end

##
# Define an extra for subclasses
def self.extra(name, packed, default=nil)
instance_eval do
@extras ||= []
@extras << [name, packed, default]
end
end

##
# Extras of this class
#
# TODO: add extras of parent class when needed
def self.extras
instance_eval { @extras || [] }
end

##
# Build a packet by parsing header fields
def self.parse_header(buf)
pack_fmt = fields.collect { |name,fmt,default| fmt }.join
values = PackArray.unpack(buf, pack_fmt)
Expand All @@ -56,7 +73,11 @@ def self.parse_header(buf)
new contents
end

# Return remaining bytes
##
# Parse body of packet when the +:total_body_length+ field is
# known by header. Pass it at least +total_body_length+ bytes.
#
# return:: [String] remaining bytes
def parse_body(buf)
buf, rest = buf[0..(self[:total_body_length] - 1)], buf[self[:total_body_length]..-1]

Expand All @@ -75,6 +96,8 @@ def parse_body(buf)
rest
end

##
# Serialize for wire
def to_s
extras_s = extras_to_s
key_s = self[:key].to_s
Expand Down

0 comments on commit b133f3b

Please sign in to comment.