Module: CosmosIO

Included in:
IO, StringIO
Defined in:
lib/cosmos/core_ext/cosmos_io.rb,
ext/cosmos/ext/cosmos_io/cosmos_io.c

Overview

COSMOS specific additions to the Ruby IO and StringIO classes

Instance Method Summary collapse

Instance Method Details

#read_length_bytes(param_length_num_bytes) ⇒ String

Reads a length field and then return the String resulting from reading the number of bytes the length field indicates

For example:

io = StringIO.new
# where io is "\x02\x01\x02\x03\x04...."
result = io.read_length_bytes(1)
# result will be "\x01x02" because the length field was given
# to be 1 byte. We read 1 byte which is a 2. So we then read two
# bytes and return.

Parameters:

  • length_num_bytes (Integer)

    Number of bytes in the length field

Returns:

  • (String)

    A String of “length field” number of bytes



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'ext/cosmos/ext/cosmos_io/cosmos_io.c', line 37

static VALUE read_length_bytes(VALUE self, VALUE param_length_num_bytes)
{
  int length_num_bytes = FIX2INT(param_length_num_bytes);
  unsigned char* string = NULL;
  long string_length = 0;
  unsigned short short_length = 0;
  unsigned char* length_ptr = NULL;
  volatile VALUE temp_string = Qnil;
  volatile VALUE temp_string_length = Qnil;
  volatile VALUE return_value = Qnil;

  /* Read bytes for string length */
  temp_string = rb_funcall(self, id_method_read, 1, param_length_num_bytes);
  if (NIL_P(temp_string) || (RSTRING_LEN(temp_string) != length_num_bytes))
  {
    return Qnil;
  }

  string = (unsigned char*) RSTRING_PTR(temp_string);
  switch (length_num_bytes)
  {
    case 1:
      string_length = (unsigned int) string[0];
      break;
    case 2:
      length_ptr = (unsigned char*) &short_length;
      if (HOST_ENDIANNESS == COSMOS_BIG_ENDIAN)
      {
        length_ptr[1] = string[1];
        length_ptr[0] = string[0];
      }
      else
      {
        length_ptr[0] = string[1];
        length_ptr[1] = string[0];
      }
      string_length = short_length;
      break;
    case 4:
      length_ptr = (unsigned char*) &string_length;
      if (HOST_ENDIANNESS == COSMOS_BIG_ENDIAN)
      {
        length_ptr[3] = string[3];
        length_ptr[2] = string[2];
        length_ptr[1] = string[1];
        length_ptr[0] = string[0];
      }
      else
      {
        length_ptr[0] = string[3];
        length_ptr[1] = string[2];
        length_ptr[2] = string[1];
        length_ptr[3] = string[0];
      }
      break;
    default:
      return Qnil;
      break;
  };

  /* Read String */
  temp_string_length = UINT2NUM(string_length);
  return_value = rb_funcall(self, id_method_read, 1, temp_string_length);
  if (NIL_P(return_value) || (RSTRING_LEN(return_value) != string_length))
  {
    return Qnil;
  }

  return return_value;
}