Sha256: 34add2b0c9ca02bc40f005863243dc9d44c85517fb173a275942abcd855ebe9e

Contents?: true

Size: 1.41 KB

Versions: 7

Compression:

Stored size: 1.41 KB

Contents

# coding: utf-8
# This file is part of PacketGen
# See https://github.com/sdaubert/packetgen for more informations
# Copyright (C) 2016 Sylvain Daubert <sylvain.daubert@laposte.net>
# This program is published under MIT license.

# frozen_string_literal: true

module PacketGen
  module Types
    # This module is a mixin adding +length_from+ capacity to a type.
    # +length_from+ capacity is the capacity, for a type, to gets its
    # length from another object.
    # @author Sylvain Daubert
    # @since 3.0.0
    module LengthFrom
      # Initialize +length from+ capacity.
      # Should be call by extensed object's initialize.
      # @param [Hash] options
      # @option options [Types::Int,Proc] :length_from object or proc from which
      #   takes length when reading
      # @return [void]
      def initialize_length_from(options)
        @length_from = options[:length_from]
      end

      # Return a substring from +str+ of length given in another object.
      # @param [#to_s] str
      # @return [String]
      def read_with_length_from(str)
        s = PacketGen.force_binary(str.to_s)
        str_end = case @length_from
                  when Types::Int
                    @length_from.to_i
                  when Proc
                    @length_from.call
                  else
                    s.size
                  end
        str_end = 0 if str_end < 0
        s[0, str_end]
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
packetgen-3.1.3 lib/packetgen/types/length_from.rb
packetgen-3.1.2 lib/packetgen/types/length_from.rb
packetgen-3.1.1 lib/packetgen/types/length_from.rb
packetgen-3.1.0 lib/packetgen/types/length_from.rb
packetgen-3.0.2 lib/packetgen/types/length_from.rb
packetgen-3.0.1 lib/packetgen/types/length_from.rb
packetgen-3.0.0 lib/packetgen/types/length_from.rb