Module: TDriver::NativeExtensions::CRC

Defined in:
ext/native_extensions.c

Class Method Summary collapse

Class Method Details

.crc16_ibm(*args) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'ext/native_extensions.c', line 157

static VALUE crc16_ibm( int argc, VALUE* argv, VALUE self ) { 

/*

  # IBM-CRC-16: fallback when native extensions are not supported (e.g. jruby)
  def crc16_ibm( buf, crc = 0xffff )

    buf.each_byte do | c |

      crc = ( ( crc >> 4 ) & 0x0fff ) ^ @IBM_16[ ( ( crc ^ c ) & 15 ) ]

      crc = ( ( crc >> 4 ) & 0x0fff ) ^ @IBM_16[ ( ( crc ^ ( c >> 4 ) ) & 15 ) ]

    end

    # result
    ~crc & 0xffff

  end # crc16_ibm

*/

  // variables for arguments
  VALUE string, initial_crc;

  // retrieve arguments
  rb_scan_args(argc, argv, "11", &string, &initial_crc);

  unsigned int crc = 0xffff; 
  
  if (!NIL_P(initial_crc)){

    // verify initial crc value
    Check_Type( initial_crc, T_FIXNUM );
  
    crc = FIX2INT( initial_crc );
  
  }
  
  // verify argument type
  Check_Type( string, T_STRING );

  const unsigned char* data = RSTRING_PTR( string );
  
  unsigned int len = RSTRING_LEN( string );
  
  unsigned char c = 0;

  while( len-- ){

    c = *data++;

    crc = ( crc >> 4 ) ^ CRC_16[ ( crc ^ c ) & 15 ];
              
    crc = ( crc >> 4 ) ^ CRC_16[ ( crc ^ ( c >> 4 ) ) & 15 ];

  }

	return INT2FIX( ~crc & 0xffff );


}