Class: CRC

Inherits:
Object
  • Object
show all
Extended by:
Utils
Defined in:
lib/crc/_byruby.rb,
lib/crc/acrc.rb,
lib/crc/finder.rb,
lib/crc/codegen.rb,
lib/crc/version.rb,
lib/crc/_combine.rb,
lib/crc/_modules.rb,
lib/crc.rb

Overview

This is a general CRC generator.

When you want to use CRC-32 module, there are following ways:

  1. Generate CRC-32’d value at direct:

    CRC.crc32("123456789") # => 3421780262
    
  2. Generate CRC-32’d hex-digest at direct:

    CRC::CRC32.hexdigest("123456789") # => "CBF43926"
    
  3. Streaming process:

    crc32 = CRC::CRC32.new  # => #<CRC::CRC32:00000000>
    IO.foreach("/boot/kernel/kernel", nil, 262144, mode: "rb") do |s|
      crc32 << s
    end
    p crc32           # => #<CRC::CRC32:6A632AA5>
    p crc32.crc       # => 1784883877
    p crc32.digest    # => "jc*\xA5"
    p crc32.hexdigest # => "6A632AA5"
    

Defined Under Namespace

Modules: Aux, ModuleClass, Utils

Constant Summary collapse

ALGORITHM_BITBYBIT =
-2
ALGORITHM_BITBYBIT_FAST =
-1
ALGORITHM_HALFBYTE_TABLE =
0
ALGORITHM_STANDARD_TABLE =
1
ALGORITHM_SLICING_BY_4 =
4
ALGORITHM_SLICING_BY_8 =
8
ALGORITHM_SLICING_BY_16 =
16
VERSION =
"0.3.1.1"
LIST =
[
  #
  # bit size,  polynomial,              initial crc,
  #                reflect input,                xor output,
  #                      reflect output,                       crc("123456789"), names...
  #
  [ 1,               0x01,  true,  true,          0,     ~0,               0x01, "CRC-1"],
  [ 3,               0x03,  true,  true,         ~0,      0,               0x06, "CRC-3-ROHC", "CRC-3-RFC 3095"],
  [ 4,               0x03, false, false,          0,     ~0,               0x0b, "CRC-4-INTERLAKEN"],
  [ 4,               0x03,  true,  true,          0,      0,               0x07, "CRC-4-ITU"],
  [ 5,               0x09, false, false,       0x09,      0,               0x00, "CRC-5-EPC"],
  [ 5,               0x15,  true,  true,          0,      0,               0x07, "CRC-5-ITU"],
  [ 5,               0x05,  true,  true,          0,     ~0,               0x19, "CRC-5-USB"],
  [ 6,               0x27, false, false,         ~0,      0,               0x0D, "CRC-6-CDMA2000-A"],
  [ 6,               0x07, false, false,         ~0,      0,               0x3B, "CRC-6-CDMA2000-B"],
  [ 6,               0x19,  true,  true,          0,      0,               0x26, "CRC-6-DARC"],
  [ 6,               0x03,  true,  true,          0,      0,               0x06, "CRC-6-ITU"],
  [ 7,               0x09, false, false,          0,      0,               0x75, "CRC-7", "CRC-7-JESD84-A441"],
  #[ 7,               0x65, false, false,          0,      0,                nil, "CRC-7-MVB"],
  [ 7,               0x4F,  true,  true,         ~0,      0,               0x53, "CRC-7-ROHC", "CRC-7-RFC 3095"],
  [ 7,               0x45, false, false,          0,      0,               0x61, "CRC-7-UMTS"],
  #[ 8,               0xD5, false, false,          0,      0,                nil, "CRC-8"],
  [ 8,               0x07, false, false,          0,      0,               0xF4, "CRC-8-CCITT", "CRC-8-SMBus"],
  [ 8,               0x31,  true,  true,          0,      0,               0xA1, "CRC-8-MAXIM", "CRC-8-Dallas/Maxim", "DOW-CRC"],
  [ 8,               0x39,  true,  true,          0,      0,               0x15, "CRC-8-DARC"],
  [ 8,               0x1D, false, false,          0,     ~0,               0x4B, "CRC-8-SAE", "CRC-8-SAE-J1850"],
  [ 8,               0x9B,  true,  true,          0,      0,               0x25, "CRC-8-WCDMA"],
  [ 8,               0x9B, false, false,         ~0,      0,               0xDA, "CRC-8-CDMA2000"],
  [ 8,               0xD5, false, false,          0,      0,               0xBC, "CRC-8-DVB-S2"],
  [ 8,               0x1D,  true,  true,         ~0,      0,               0x97, "CRC-8-EBU", "CRC-8-AES"],
  [ 8,               0x1D, false, false,       0xFD,      0,               0x7E, "CRC-8-I-CODE"],
  [ 8,               0x07, false, false,       0x55,   0x55,               0xA1, "CRC-8-ITU"],
  [ 8,               0x9B, false, false,          0,      0,               0xEA, "CRC-8-LTE"],
  [ 8,               0x07,  true,  true,         ~0,      0,               0xD0, "CRC-8-ROHC", "CRC-8-RFC 3095"],
  [10,             0x0233, false, false,          0,      0,             0x0199, "CRC-10"],
  [10,             0x03D9, false, false,         ~0,      0,             0x0233, "CRC-10-CDMA2000"],
  [11,             0x0385, false, false,     0x001A,      0,             0x05A3, "CRC-11"],
  [11,             0x0307, false, false,          0,      0,             0x0061, "CRC-11-UMTS"],
  [12,             0x0F13, false, false,         ~0,      0,             0x0D4D, "CRC-12-CDMA2000"],
  [12,             0x080F, false, false,          0,      0,             0x0F5B, "CRC-12-DECT", "X-CRC-12"],
  [12,             0x080F, false,  true,          0,      0,             0x0DAF, "CRC-12-UMTS", "CRC-12-3GPP"],
  [13,             0x1CF5, false, false,          0,      0,             0x04FA, "CRC-13-BBC"],
  [14,             0x0805,  true,  true,          0,      0,             0x082D, "CRC-14-DARC"],
  [15,             0x4599, false, false,          0,      0,             0x059E, "CRC-15", "CRC-15-CAN"],
  [15,             0x6815, false, false,          1,      1,             0x2566, "CRC-15-MPT1327"],
  #[16,             0x2F15, false, false,          0,      0,                nil, "Chakravarty"],
  [16,             0x8005,  true,  true,          0,      0,             0xBB3D, "CRC-16", "ARC", "CRC-IBM", "CRC-16-ARC", "CRC-16-LHA"],
  #[16,             0xA02B, false, false,          0,      0,                nil, "CRC-16-ARINC"],
  [16,             0x1021, false, false,     0x1D0F,      0,             0xE5CC, "CRC-16-AUG-CCITT", "CRC-16-SPI-FUJITSU"],
  [16,             0xC867, false, false,         ~0,      0,             0x4C06, "CRC-16-CDMA2000"],
  [16,             0x0589, false, false,          1,      1,             0x007E, "CRC-16-DECT-R", "R-CRC-16"],
  [16,             0x0589, false, false,          0,      0,             0x007F, "CRC-16-DECT-X", "X-CRC-16"],
  [16,             0x8BB7, false, false,          0,      0,             0xD0DB, "CRC-16-T10-DIF"],
  [16,             0x3D65,  true,  true,         ~0,     ~0,             0xEA82, "CRC-16-DNP"],
  [16,             0x8005, false, false,          0,      0,             0xFEE8, "CRC-16-BUYPASS", "CRC-16-VERIFONE", "CRC-16-UMTS"],
  [16,             0x1021, false, false,         ~0,      0,             0x29B1, "CRC-16-CCITT-FALSE"],
  [16,             0x8005, false, false,     0x800D,      0,             0x9ECF, "CRC-16-DDS-110"],
  [16,             0x3D65, false, false,         ~0,     ~0,             0xC2B7, "CRC-16-EN-13757"],
  [16,             0x1021, false, false,          0,     ~0,             0xD64E, "CRC-16-GENIBUS", "CRC-16-EPC", "CRC-16-I-CODE", "CRC-16-DARC"],
  [16,             0x6F63, false, false,          0,      0,             0xBDF4, "CRC-16-LJ1200"],
  [16,             0x8005,  true,  true,         ~0,     ~0,             0x44C2, "CRC-16-MAXIM"],
  [16,             0x1021,  true,  true,         ~0,      0,             0x6F91, "CRC-16-MCRF4XX"],
  [16,             0x1021,  true,  true,     0xB2AA,      0,             0x63D0, "CRC-16-RIELLO"],
  [16,             0xA097, false, false,          0,      0,             0x0FB3, "CRC-16-TELEDISK"],
  [16,             0x1021,  true,  true,     0x89EC,      0,             0x26B1, "CRC-16-TMS37157"],
  [16,             0x8005,  true,  true,          0,     ~0,             0xB4C8, "CRC-16-USB"],
  [16,             0x1021,  true,  true,     0xC6C6,      0,             0xBF05, "CRC-16-A", "CRC-A", "CRC-16-ISO/IEC FCD 14443-3"],
  [16,             0x1021,  true,  true,          0,      0,             0x2189, "CRC-16-KERMIT", "KERMIT", "CRC-16-CCITT", "CRC-16-CCITT-TRUE", "CRC-CCITT"],
  [16,             0x8005,  true,  true,         ~0,      0,             0x4B37, "CRC-16-MODBUS", "MODBUS"],
  [16,             0x1021,  true,  true,          0,     ~0,             0x906E, "CRC-16-X-25", "X-25", "CRC-16-IBM-SDLC", "CRC-16-ISO-HDLC", "CRC-16-CRC-B", "CRC-B"],
  [16,             0x1021, false, false,          0,      0,             0x31C3, "CRC-16-XMODEM", "XMODEM", "CRC-16-ZMODEM", "ZMODEM", "CRC-16-ACORN", "CRC-16-LTE"],
  #[17,         0x0001685B, false, false,          0,      0,                nil, "CRC-17-CAN"],
  #[21,         0x00102899, false, false,          0,      0,                nil, "CRC-21-CAN"],
  #[24,         0x005D6DCB, false, false,          0,      0,                nil, "CRC-24"],
  [24,         0x00864CFB, false, false,          0,      0,         0x00CDE703, "CRC-24-Radix-64"],
  [24,         0x00864CFB, false, false, 0x00B704CE,      0,         0x0021CF02, "CRC-24-OPENPGP"],
  [24,         0x0000065B,  true,  true, 0x00555555,      0,         0x00C25A56, "CRC-24-BLE"],
  [24,         0x005D6DCB, false, false, 0x00FEDCBA,      0,         0x007979BD, "CRC-24-FLEXRAY-A"],
  [24,         0x005D6DCB, false, false, 0x00ABCDEF,      0,         0x001F23B8, "CRC-24-FLEXRAY-B"],
  [24,         0x00328B63, false, false,          0,     ~0,         0x00B4F3E6, "CRC-24-INTERLAKEN"],
  [24,         0x00864CFB, false, false,          0,      0,         0x00CDE703, "CRC-24-LTE-A"],
  [24,         0x00800063, false, false,          0,      0,         0x0023EF52, "CRC-24-LTE-B"],
  #[30,         0x2030B9C7, false, false,          0,      0,                nil, "CRC-30"],
  [30,         0x2030B9C7, false, false,          0,     ~0,         0x04C34ABF, "CRC-30-CDMA"],
  [31,         0x04C11DB7, false, false,          0,     ~0,         0x0CE9E46C, "CRC-31-PHILIPS"],
  [32,         0x04C11DB7,  true,  true,          0,     ~0,         0xCBF43926, "CRC-32", "CRC-32-ADCCP", "CRC-32-PKZIP", "PKZIP"],
  [32,         0x04C11DB7, false, false,          0,     ~0,         0xFC891918, "CRC-32-BZIP2", "CRC-32-AAL5", "CRC-32-DECT-B", "B-CRC-32"],
  [32,         0x1EDC6F41,  true,  true,          0,     ~0,         0xE3069283, "CRC-32C", "CRC-32-ISCSI", "CRC-32-CASTAGNOLI", "CRC-32-INTERLAKEN"],
  [32,         0xa833982b,  true,  true,          0,     ~0,         0x87315576, "CRC-32D"],
  [32,         0x04C11DB7, false, false,         ~0,      0,         0x0376E6E7, "CRC-32-MPEG-2"],
  [32,         0x04C11DB7, false, false,         ~0,     ~0,         0x765E7680, "CRC-32-POSIX", "CKSUM"],
  #[32,         0x741B8CD7,  true,  true,          0,     ~0,                nil, "CRC-32K"],
  #[32,         0x32583499,  true,  true,          0,     ~0,                nil, "CRC-32K2"],
  [32,         0x814141AB, false, false,          0,      0,         0x3010BF7F, "CRC-32Q"],
  [32,         0x04C11DB7,  true,  true,         ~0,      0,         0x340BC6D9, "CRC-32-JAMCRC", "JAMCRC"],
  [32,         0x000000AF, false, false,          0,      0,         0xBD0BE338, "CRC-32-XFER", "XFER"],
  [40,       0x0004820009, false, false,         ~0,     ~0,       0xD4164FC646, "CRC-40-GSM"],
  [64, 0x42F0E1EBA9EA3693,  true,  true,          0,     ~0, 0x995DC9BBDF1939FA, "CRC-64-XZ", "CRC-64"],
  [64, 0xAD93D23594C935A9,  true,  true,         ~0,      0, 0xCAA717168609F281, "CRC-64-JONES"],
  [64, 0x42F0E1EBA9EA3693, false, false,          0,      0, 0x6C40DF5F0B497347, "CRC-64-ECMA", "CRC-64-ECMA-182"],
  [64, 0x42F0E1EBA9EA3693, false, false,          0,     ~0, 0x62EC59E3F1A4F00A, "CRC-64-WE"],
  [64, 0x000000000000001B,  true,  true,          0,      0, 0x46A5A9388A5BEFFE, "CRC-64-ISO", "CRC-64-ISO-3309"],
  # [82, 0x308C0111011401440411,  true,  true,          0,      0, 0x9EA83F625023801FD612, "CRC-82/DARC"],
]
IMPLEMENT =
:ruby
CRC =
self

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils

bitreflect, bitreflect128, bitreflect16, bitreflect32, bitreflect64, bitreflect8, bitreflect_reference, build_reflect_table, build_table, export_table

Constructor Details

#initialize(*args) ⇒ CRC

call-seq:

initialize(initial_crc = nil, size = 0)
initialize(seq, initial_crc = nil, size = 0)


314
315
316
317
318
319
320
321
# File 'lib/crc.rb', line 314

def initialize(*args)
  initialize_args(args) do |seq, initial_crc, size|
    m = self.class
    @state = m.setup((initial_crc || m.initial_crc).to_i)
    @size = size.to_i
    update(seq) if seq
  end
end

Instance Attribute Details

#sizeObject

Returns the value of attribute size.



307
308
309
# File 'lib/crc.rb', line 307

def size
  @size
end

#stateObject

Returns the value of attribute state.



307
308
309
# File 'lib/crc.rb', line 307

def state
  @state
end

Class Method Details

.crc(modulename, seq, crc = nil) ⇒ Object



451
452
453
# File 'lib/crc.rb', line 451

def crc(modulename, seq, crc = nil)
  lookup(modulename).crc(seq, crc)
end

.digest(modulename, seq, crc = nil) ⇒ Object



455
456
457
# File 'lib/crc.rb', line 455

def digest(modulename, seq, crc = nil)
  lookup(modulename).digest(seq, crc)
end

.dump_to_c(func_name = nil, header_name = nil, source_name = nil, indent: 4, visible: true, algorithm: ALGORITHM_SLICING_BY_16) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/crc/codegen.rb', line 14

def self.dump_to_c(func_name = nil, header_name = nil, source_name = nil, indent: 4, visible: true, algorithm: ALGORITHM_SLICING_BY_16)
  func_name ||= self.to_s.slice(/\w+$/).downcase
  #func_name ||= self.name.gsub(/[\W]+/, "_").gsub(/_{2,}/, "_").gsub(/^_|_$/, "").downcase
  header_name ||= "#{func_name}.h"
  source_name ||= "#{func_name}.c"
  indentunit = " " * Integer(indent.to_i)
  indent = ->(level) { indentunit * level }
  visibility = visible ? "" : "static "

  case
  when bitsize <= 8
    type = "uint8_t"
    sizeof = 1
    suffix = "u"
  when bitsize <= 16
    type = "uint16_t"
    sizeof = 2
    suffix = "u"
  when bitsize <= 32
    type = "uint32_t"
    sizeof = 4
    suffix = "ul"
  else
    type = "uint64_t"
    sizeof = 8
    suffix = "ull"
  end

  typesize = sizeof * 8
  alignedbytes = (bitsize + 7) / 8
  alignedbits = (bitsize + 7) & ~0x07 # 8 bit alignmented bitsize
  bitreflect = func_name + "_bitreflect"
  hexnum = ->(n) { "0x%0#{sizeof * 2}X%s" % [n, suffix] }
  hexbyte = ->(n) { "0x%02Xu" % n }

  if reflect_input?
    getleadbyte = ->(expr, off = 0) { "(uint8_t)(#{expr} >> %2d)" % (off * 8) }
    getheadbit_from_byte = ->(expr, off = 0) { "((#{expr} >> #{off}) & 1)" }
    getleadbit = ->(expr, off = 0, width = 1) { "((%s >> %2d) & 0x%02X)" % [expr, off, ~(~0 << width)] }
    slideinput = ->(expr) { "#{expr}" }
    slidestate1 = ->(expr) { "(#{expr} >> 1)" }
    slidestate4 = ->(expr) { "(#{expr} >> 4)" }
    slidestate8 = ->(expr) { "(#{expr} >> 8)" }
    slideslicing = ->(expr) { "(#{expr} >> #{algorithm * 8})" }
    padding = depadding = nil
    workpoly = hexnum[Utils.bitreflect(polynomial, bitsize)]
    if algorithm >= 0
      table = Utils.build_reflect_table(bitsize, polynomial, true, slice: (algorithm < 1 ? 1 : algorithm))
    end
  else
    getleadbyte = ->(expr, off = 0) { "(uint8_t)(#{expr} >> %2d)" % (alignedbits - (off + 1) * 8) }
    getheadbit_from_byte = ->(expr, off = 0) { "((#{expr} >> #{8 - (off + 1)}) & 1)" }
    getleadbit = ->(expr, off = 0, width = 1) { "((%s >> %2d) & 0x%02X)" % [expr, (alignedbits - (off + 1) - (width - 1)), ~(~0 << width)] }
    slideinput = ->(expr) { "((#{type})#{expr} << #{alignedbits - 8})" }
    slidestate1 = ->(expr) { "(#{expr} << 1)" }
    slidestate4 = ->(expr) { "(#{expr} << 4)" }
    slidestate8 = ->(expr) { "(#{expr} << 8)" }
    slideslicing = ->(expr) { "(#{expr} << #{algorithm * 8})" }
    if (pad = (alignedbits - bitsize)) > 0
      padding = " << #{pad}"
      depadding = " >> #{pad}"
      workpoly = "#{func_name.upcase}_POLYNOMIAL << #{pad}"
    else
      padding = depadding = nil
      workpoly = "#{func_name.upcase}_POLYNOMIAL"
    end
    if algorithm >= 0
      table = Utils.build_table(bitsize, polynomial, true, slice: (algorithm < 1 ? 1 : algorithm))
    end
  end

  case algorithm
  when ALGORITHM_BITBYBIT
    comment = " /* bit reflected */" if reflect_input?
    prepare = <<-PREPARE_BITBYBIT
  static const #{type} workpoly = #{workpoly};#{comment}
    PREPARE_BITBYBIT
    update = <<-UPDATE_BITBYBIT
  for (; p < pp; p ++) {
      int i;
      s ^= #{slideinput["*p"]};
      for (i = 0; i < 8; i ++) {
          s = #{slidestate1["s"]} ^ (workpoly & -(#{type})#{getleadbit["s"]});
      }
  }
    UPDATE_BITBYBIT
  when ALGORITHM_BITBYBIT_FAST
    comment = " /* bit reflected */" if reflect_input?
    tspc = " " * type.size
    prepare = <<-PREPARE_BITBYBIT_FAST
  static const #{type} workpoly = #{workpoly};#{comment}
  static const #{type} g0 = workpoly,
               #{tspc} g1 = #{slidestate1["g0"]} ^ (workpoly & -(#{type})#{getleadbit["g0"]}),
               #{tspc} g2 = #{slidestate1["g1"]} ^ (workpoly & -(#{type})#{getleadbit["g1"]}),
               #{tspc} g3 = #{slidestate1["g2"]} ^ (workpoly & -(#{type})#{getleadbit["g2"]}),
               #{tspc} g4 = #{slidestate1["g3"]} ^ (workpoly & -(#{type})#{getleadbit["g3"]}),
               #{tspc} g5 = #{slidestate1["g4"]} ^ (workpoly & -(#{type})#{getleadbit["g4"]}),
               #{tspc} g6 = #{slidestate1["g5"]} ^ (workpoly & -(#{type})#{getleadbit["g5"]}),
               #{tspc} g7 = #{slidestate1["g6"]} ^ (workpoly & -(#{type})#{getleadbit["g6"]});
    PREPARE_BITBYBIT_FAST
    update = <<-UPDATE_BITBYBIT_FAST
  for (; p < pp; p ++) {
      const uint8_t s1 = #{getleadbit["s", 0, 8]} ^ *p;
      s = #{slidestate8["s"]} ^
          (g7 & -(#{type})#{getheadbit_from_byte["s1", 0]}) ^
          (g6 & -(#{type})#{getheadbit_from_byte["s1", 1]}) ^
          (g5 & -(#{type})#{getheadbit_from_byte["s1", 2]}) ^
          (g4 & -(#{type})#{getheadbit_from_byte["s1", 3]}) ^
          (g3 & -(#{type})#{getheadbit_from_byte["s1", 4]}) ^
          (g2 & -(#{type})#{getheadbit_from_byte["s1", 5]}) ^
          (g1 & -(#{type})#{getheadbit_from_byte["s1", 6]}) ^
          (g0 & -(#{type})#{getheadbit_from_byte["s1", 7]});
  }
    UPDATE_BITBYBIT_FAST
  when ALGORITHM_HALFBYTE_TABLE
    table = table[0]
    if reflect_input?
      table = 16.times.map { |i| table[i * 16] }
    else
      table = 16.times.map { |i| table[i] }
    end
    prepare = <<-PREPARE_HALFBYTE_TABLE
  static const #{type} table[16] = {
#{Aux.export_slicing_table(table, "    ", 4, nil, nil, nil, nil, sizeof > 2 ? 4 : 8, &hexnum)}
  };
    PREPARE_HALFBYTE_TABLE
    update = <<-UPDATE_HALFBYTE_TABLE
  for (; p < pp; p ++) {
      s ^= #{slideinput["(#{type})*p"]};
      s = table[#{getleadbit["s", 0, 4]}] ^ #{slidestate4["s"]};
      s = table[#{getleadbit["s", 0, 4]}] ^ #{slidestate4["s"]};
  }
    UPDATE_HALFBYTE_TABLE
  when ALGORITHM_STANDARD_TABLE
    prepare = <<-PREPARE_STANDARD_TABLE
  static const #{type} table[256] = {
#{Aux.export_slicing_table(table[0], "    ", 4, nil, nil, nil, nil, sizeof > 2 ? 4 : 8, &hexnum)}
  };
    PREPARE_STANDARD_TABLE
    update = <<-UPDATE_STANDARD_TABLE
  for (; p < pp; p ++) {
      s ^= #{slideinput["(#{type})*p"]};
      s = table[(uint8_t)#{getleadbit["s", 0, 8]}] ^ #{slidestate8["s"]};
  }
    UPDATE_STANDARD_TABLE
  when ALGORITHM_SLICING_BY_4,
       ALGORITHM_SLICING_BY_8,
       ALGORITHM_SLICING_BY_16
    slicing = algorithm.times.map { |off|
      ioff = (algorithm - 1) - off
      "table[%2d][p[%2d] %20s]" % [
        off, ioff,
        ioff >= alignedbytes ? nil : "^ #{getleadbyte["s", ioff]}"]
    }
    if algorithm < alignedbytes
      slicing.insert 0, slideslicing["s"]
    end
    slicing = slicing.join(" ^\n            ")

    prepare = <<-PREPARE_SLICING_TABLE
  static const #{type} table[#{algorithm}][256] = {
#{Aux.export_slicing_table(table, "    ", 4, nil, nil, "{", "}", sizeof > 2 ? 4 : 8, &hexnum)}
  };
    PREPARE_SLICING_TABLE
    update = <<-UPDATE_SLICING_TABLE
  const uint8_t *ppby = p + (len / #{algorithm} * #{algorithm});
  for (; p < ppby; p += #{algorithm}) {
      s = #{slicing};
  }

  for (; p < pp; p ++) {
      s = table[0][*p ^ #{getleadbyte["s"]}] ^ #{slidestate8["s"]};
  }
    UPDATE_SLICING_TABLE
  else
    raise ArgumentError, "wrong algorithm code - #{algorithm}"
  end

  if reflect_output? ^ reflect_input?
    slideleft = (typesize == bitsize) ? nil : "\n" << <<-SLIDELEFT.chomp!
  n <<= #{typesize - bitsize};
    SLIDELEFT
    swapby32 = (sizeof < 8) ? nil : "\n" << <<-SWAPBY32.chomp!
  n = ((n & 0X00000000FFFFFFFF#{suffix}) << 32) |  (n >> 32);
    SWAPBY32
    swapby16 = (sizeof < 4) ? nil : "\n" << <<-SWAPBY16.chomp!
  n = ((n & 0x#{"0000FFFF" * (sizeof / 4)}#{suffix}) << 16) | ((n >> 16) & 0x#{"0000FFFF" * (sizeof / 4)}#{suffix});
    SWAPBY16
    swapby8 = (sizeof < 2) ? nil : "\n" << <<-SWAPBY8.chomp!
  n = ((n & 0x#{"00FF" * (sizeof / 2)}#{suffix}) <<  8) | ((n >>  8) & 0x#{"00FF" * (sizeof / 2)}#{suffix});
    SWAPBY8

    func_bitreflect = "\n" << <<-BITREFLECT
static #{type}
#{bitreflect}(#{type} n)
{#{slideleft}#{swapby32}#{swapby16}#{swapby8}
  n = ((n & 0x#{"0F" * sizeof}#{suffix}) <<  4) | ((n >>  4) & 0x#{"0F" * sizeof}#{suffix});
  n = ((n & 0x#{"33" * sizeof}#{suffix}) <<  2) | ((n >>  2) & 0x#{"33" * sizeof}#{suffix});
  n = ((n & 0x#{"55" * sizeof}#{suffix}) <<  1) | ((n >>  1) & 0x#{"55" * sizeof}#{suffix});
  return n;
}
    BITREFLECT
  else
    bitreflect = nil
  end

  { header: <<-CHEADER, source: <<-CSOURCE }
/*
#{Aux.dump_banner(" *", "#{self.name}{#{to_str}}", algorithm)}
 */

#include "#{header_name}"
#{func_bitreflect}
#{visibility}#{type}
#{func_name}(const void *ptr, size_t len, #{type} crc)
{
#{prepare}
  #{type} s = ((#{bitreflect}(crc) & #{func_name.upcase}_BITMASK) ^ #{func_name.upcase}_XOR_OUTPUT)#{padding};
  const uint8_t *p = (const uint8_t *)ptr;
  const uint8_t *pp = p + len;

#{update}
  return #{bitreflect}((s#{depadding}) & #{func_name.upcase}_BITMASK) ^ #{func_name.upcase}_XOR_OUTPUT;
}
  CSOURCE
end

.dump_to_javascript(class_name = nil) ⇒ Object



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
# File 'lib/crc/codegen.rb', line 549

def self.dump_to_javascript(class_name = nil)
  class_name ||= self.to_s.slice(/\w+$/).downcase
  name = class_name.split("::")
  name.map! { |nm| nm.gsub!(/[\W]+/m, "_"); nm.sub!(/^_+/, ""); nm }
  case
  when bitsize <= 8
    sizeof = 1
  when bitsize <= 16
    sizeof = 2
  when bitsize <= 32
    sizeof = 4
  else
    sizeof = 8
  end

  pack = ""

  typebits = sizeof * 8
  hexnum = ->(n) { "0x%0*X" % [sizeof * 2, n] }
  if reflect_input?
    table1 = Utils.build_reflect_table(bitsize, polynomial, slice: 16)
    headstate = "(s & 0xFF)"
    slidestate = "(s >>> 8)"
    slicing = ->(off) {
      t = "t%X" % (15 - off)
      getbyte = off > 0 ? "+ %2d" % off : ""
      shiftstate = off < sizeof ? "^ (s %6s) & 0xFF" % (off > 0 ? ">>> %2d" % (off * 8) : "") : ""
      "%s[(0xFF & seq.charCodeAt(i %4s)) %19s]" % [t, getbyte, shiftstate]
    }
  else
    table1 = Utils.build_table(bitsize, polynomial, true, slice: 16)
    bitpad = typebits - bitsize
    #table1.each { |t| t.map! { |tt| tt << bitpad } }
    headstate = "((s >>> #{typebits - 8}) & 0xFF)"
    slidestate = "((s & #{hexnum[~(~0 << typebits) >> 8]}) << 8)"
    slicing = ->(off) {
      t = "t%X" % (15 - off)
      getbyte = off > 0 ? "+ %2d" % off : ""
      shiftstate = off < sizeof ? "^ (s %6s) & 0xFF" % (off + 1 < sizeof ? ">>> %2d" % ((sizeof - off) * 8 - 8) : "") : ""
      "%s[(0xFF & seq.charCodeAt(i %4s)) %19s]" % [t, getbyte, shiftstate]
    }
  end

  typename = name.join(".")

  code = <<-EOS
/*
#{Aux.dump_banner(" *", "#{self.name}{#{to_str}}", ALGORITHM_SLICING_BY_16)}
 * * Required ECMASCript version: 6th edition
 *
 * *** IMPORTANT BUG! ***
 *
 * This can not be calculated correctly,
 * if string included with 0x100+ codepointed character.
 */

"use strict";

/*
 * #{typename}(prevcrc = null)
 * #{typename}(seq, prevcrc = null)
 * new #{typename}(prevcrc = null)
 * new #{typename}(seq, prevcrc = null)
 */
(function(root, undefined) {
if (typeof(module) != "undefined") {
  // case node-js
  root = global;
}

var BITSIZE         = #{bitsize};
var BITMASK         = #{hexnum[bitmask]} >>> 0;
var POLYNOMIAL      = #{hexnum[polynomial]} >>> 0;
var INITIAL_CRC     = #{hexnum[initial_crc]} >>> 0;
var REFLECT_INPUT   = #{reflect_input?.inspect};
var REFLECT_OUTPUT  = #{reflect_output?.inspect};
var XOR_OUTPUT      = #{hexnum[xor_output]} >>> 0;

var #{typename} = function() {
  if(!(this instanceof #{typename})) {
      return new #{typename}(...arguments).crc;
  }

  var seq, prevcrc;

  switch (arguments.length) {
  case 0:
    seq = null;
    prevcrc = null;
    break;
  case 1:
    if (typeof(arguments[0]) == "string") {
      seq = arguments[0];
    } else {
      prevcrc = arguments[0];
    }
    break;
  case 2:
    seq = arguments[0];
    prevcrc = arguments[1];
    break;
  default:
    throw `wrong number of argument (given ${arguments.size}, expect 0..2)`;
  }

  this.reset(prevcrc);
  if (seq) { this.update(seq); }
};

var proto = #{typename}.prototype;

proto.reset = function(prevcrc = null) {
  this.state = #{typename}.setup(prevcrc || INITIAL_CRC);
  return this;
};

proto.update = function(seq) {
  this.state = #{typename}.update(seq, this.state);
  return this;
};

// proto.operator << = proto.update;

proto.finish = function() {
  return #{typename}.finish(this.state);
};

Object.defineProperty(proto, "crc", {
  get: proto.finish
});

Object.defineProperty(proto, "hexdigest", {
  get: function() {
    var s = this.crc.toString(16);
    for (var i = s.length; i < #{sizeof * 2}; i ++) {
      s = "0" + s;
    }
    return s;
  }
});

proto.toString = function() {
  return `#<#{typename}:${this.hexdigest}>`;
};

#{typename}.setup = function(crc = INITIAL_CRC) {
  return #{
    s = "(BITMASK & crc ^ XOR_OUTPUT)"

    if reflect_output? ^ reflect_input?
      s = "bitreflect#{s}"
    end

    if !reflect_input? && typebits > bitsize
      s << " << #{typebits - bitsize}"
    end

    s
  };
};

#{typename}.init = #{typename}.setup;

#{typename}.finish = function(state) {
  return (#{
    if !reflect_input? && typebits > bitsize
      state = "(state >>> #{typebits - bitsize})"
    else
      state = "state"
    end

    if reflect_output? ^ reflect_input?
      "bitreflect(BITMASK & #{state} ^ XOR_OUTPUT)"
    else
      "BITMASK & #{state} ^ XOR_OUTPUT"
    end
  }) >>> 0;
};

/*
 * update(seq, state) -> state
 */
#{typename}.update = function(seq, s) {
  var i = 0;
  var ii = seq.length;
  var ii16 = ii & ~15;
  var t0 = TABLE[ 0], t1 = TABLE[ 1], t2 = TABLE[ 2], t3 = TABLE[ 3],
      t4 = TABLE[ 4], t5 = TABLE[ 5], t6 = TABLE[ 6], t7 = TABLE[ 7],
      t8 = TABLE[ 8], t9 = TABLE[ 9], tA = TABLE[10], tB = TABLE[11],
      tC = TABLE[12], tD = TABLE[13], tE = TABLE[14], tF = TABLE[15];
  for (; i < ii16; i += 16) {
    s = #{slicing[ 0]} ^
        #{slicing[ 1]} ^
        #{slicing[ 2]} ^
        #{slicing[ 3]} ^
        #{slicing[ 4]} ^
        #{slicing[ 5]} ^
        #{slicing[ 6]} ^
        #{slicing[ 7]} ^
        #{slicing[ 8]} ^
        #{slicing[ 9]} ^
        #{slicing[10]} ^
        #{slicing[11]} ^
        #{slicing[12]} ^
        #{slicing[13]} ^
        #{slicing[14]} ^
        #{slicing[15]};
  }

  for (; i < ii; i ++) {
    s = t0[(0xFF & seq.charCodeAt(i)) ^ #{headstate}] ^ #{slidestate}
  }

  return s;
}

#{typename}.crc = function(seq, initcrc = INITIAL_CRC) {
  return #{typename}.finish(#{typename}.update(seq, #{typename}.setup(initcrc)));
};

#{typename}.hexdigest = function(seq, initcrc = INITIAL_CRC) {
  var s = #{typename}.crc(seq, initcrc).toString(16);
  for (var i = s.length; i < #{sizeof * 2}; i ++) {
    s = "0" + s;
  }
  return s;
};
  EOS

  if reflect_output? ^ reflect_input?
    code << <<-EOS

#{typename}.bitreflect = function(n) {
    EOS

    if typebits > bitsize
      code << <<-EOS
  n <<= #{typebits - bitsize}
      EOS
    end

    if typebits > 32
      code << <<-EOS
  n = ((n >>> 32) & 0x00000000ffffffff) | ((n & 0x00000000ffffffff) << 32)
      EOS
    end

    if typebits > 16
      code << <<-EOS
  n = ((n >>> 16) & 0x#{"0000ffff" * (sizeof / 4)}) | ((n & 0x#{"0000ffff" * (sizeof / 4)}) << 16)
      EOS
    end

    if typebits > 8
      code << <<-EOS
  n = ((n >>>  8) & 0x#{"00ff" * (sizeof / 2)}) | ((n & 0x#{"00ff" * (sizeof / 2)}) <<  8)
      EOS
    end

    code << <<-EOS
  n = ((n >>>  4) & 0x#{"0f" * sizeof}) | ((n & 0x#{"0f" * sizeof}) <<  4)
  n = ((n >>>  2) & 0x#{"33" * sizeof}) | ((n & 0x#{"33" * sizeof}) <<  2)
  n = ((n >>>  1) & 0x#{"55" * sizeof}) | ((n & 0x#{"55" * sizeof}) <<  1)
  return n;
}
    EOS
  end

  code << <<-EOS

var TABLE = [
#{Aux.export_slicing_table(table1, "  ", 2, nil, nil, "[", "]", sizeof > 2 ? 4 : 8, &hexnum)}
];

root.#{typename} = #{typename};

Object.defineProperty(#{typename}, "BITSIZE", { get: function() { return BITSIZE } });
Object.defineProperty(#{typename}, "BITMASK", { get: function() { return BITMASK } });
Object.defineProperty(#{typename}, "POLYNOMIAL", { get: function() { return POLYNOMIAL } });
Object.defineProperty(#{typename}, "INITIAL_CRC", { get: function() { return INITIAL_CRC } });
Object.defineProperty(#{typename}, "REFLECT_INPUT", { get: function() { return REFLECT_INPUT } });
Object.defineProperty(#{typename}, "REFLECT_OUTPUT", { get: function() { return REFLECT_OUTPUT } });
Object.defineProperty(#{typename}, "XOR_OUTPUT", { get: function() { return XOR_OUTPUT } });

return #{typename};
})(this);
  EOS

  ({ source: code })
end

.dump_to_ruby(class_name = nil) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/crc/codegen.rb', line 269

def self.dump_to_ruby(class_name = nil)
  class_name ||= self.to_s.slice(/\w+$/)
  name = class_name.split("::")
  name.map! { |nm| nm.gsub!(/[\W]+/m, "_"); nm.sub!(/^_+/, ""); nm.sub!(/^[a-z]/) { |m| m.upcase! }; nm }
  case
  when bitsize <= 8
    sizeof = 1
    pack = "C"
  when bitsize <= 16
    sizeof = 2
    pack = "n"
  when bitsize <= 32
    sizeof = 4
    pack = "N"
  else
    sizeof = 8
    pack = "Q>"
  end

  typebits = sizeof * 8
  hexnum = ->(n) { "0x%0*X" % [sizeof * 2, n] }
  if reflect_input?
    table1 = Utils.build_reflect_table(bitsize, polynomial, slice: 16)
    headstate = "(s & 0xFF)"
    slidestate = "(s >> 8)"
    slicing = ->(off) {
      t = "t%X" % (15 - off)
      getbyte = off > 0 ? "+ %2d" % off : ""
      shiftstate = off < sizeof ? "^ (s %5s) & 0xFF" % (off > 0 ? ">> %2d" % (off * 8) : "") : ""
      "%s[seq.getbyte(i %4s) %18s]" % [t, getbyte, shiftstate]
    }
  else
    table1 = Utils.build_table(bitsize, polynomial, true, slice: 16)
    bitpad = typebits - bitsize
    headstate = "((s >> #{typebits - 8}) & 0xFF)"
    slidestate = "((s & #{hexnum[~(~0 << typebits) >> 8]}) << 8)"
    slicing = ->(off) {
      t = "t%X" % (15 - off)
      getbyte = off > 0 ? "+ %2d" % off : ""
      shiftstate = off < sizeof ? "^ (s %5s) & 0xFF" % (off + 1 < sizeof ? ">> %2d" % ((sizeof - off) * 8 - 8) : "") : ""
      "%s[seq.getbyte(i %4s) %18s]" % [t, getbyte, shiftstate]
    }
  end

  code = <<-EOS
#!ruby

#
#{Aux.dump_banner("#", "#{self.name}{#{to_str}}", ALGORITHM_SLICING_BY_16)}
#

# for ruby-1.8
unless "".respond_to?(:getbyte)
class String
  alias getbyte []
end
end

# for mruby
unless [].respond_to?(:freeze)
class Array
  def freeze
    self
  end
end
end

class #{name.join("::")}
BITSIZE         = #{bitsize}
BITMASK         = #{hexnum[bitmask]}
POLYNOMIAL      = #{hexnum[polynomial]}
INITIAL_CRC     = #{hexnum[initial_crc]}
REFLECT_INPUT   = #{reflect_input?.inspect}
REFLECT_OUTPUT  = #{reflect_output?.inspect}
XOR_OUTPUT      = #{hexnum[xor_output]}

attr_accessor :state

#
# call-seq:
#   initialize(prevcrc = nil)
#   initialize(seq, prevcrc = nil)
#
def initialize(*args)
  case args.size
  when 0
    seq = nil
    prevcrc = nil
  when 1
    if args[0].kind_of?(String)
      seq = args[0]
    else
      prevcrc = args[0]
    end
  when 2
    (seq, prevcrc) = args
  else
    raise ArgumentError, "wrong number of argument (given \#{args.size}, expect 0..2)"
  end

  reset(prevcrc)
  update(seq) if seq
end

def reset(prevcrc = nil)
  @state = self.class.setup(prevcrc || INITIAL_CRC)
  self
end

def update(seq)
  @state = self.class.update(seq, state)
  self
end

alias << update

def crc
  self.class.finish(state)
end

alias finish crc

def digest
  [crc].pack(#{pack.inspect})
end

def hexdigest
  "%0#{sizeof * 2}X" % crc
end

def inspect
  "#<\#{self.class}:\#{hexdigest}>"
end

def pretty_print(q)
  q.text inspect
end

class << self
  def [](seq, prevcrc = nil)
    new(seq, prevcrc)
  end

  def setup(crc = INITIAL_CRC)
    #{
      s = "(BITMASK & crc ^ XOR_OUTPUT)"

      if reflect_output? ^ reflect_input?
        s = "bitreflect#{s}"
      end

      if !reflect_input? && typebits > bitsize
        s << " << #{typebits - bitsize}"
      end

      s
    }
  end

  alias init setup

  def finish(state)
    #{
      if !reflect_input? && typebits > bitsize
        state = "(state >> #{typebits - bitsize})"
      else
        state = "state"
      end

      if reflect_output? ^ reflect_input?
        "bitreflect(BITMASK & #{state} ^ XOR_OUTPUT)"
      else
        "BITMASK & #{state} ^ XOR_OUTPUT"
      end
    }
  end

  #
  # call-seq:
  #   update(seq, state) -> state
  #
  def update(seq, s)
    i = 0
    ii = seq.bytesize
    ii16 = ii & ~15
    t0 = TABLE[ 0]; t1 = TABLE[ 1]; t2 = TABLE[ 2]; t3 = TABLE[ 3]
    t4 = TABLE[ 4]; t5 = TABLE[ 5]; t6 = TABLE[ 6]; t7 = TABLE[ 7]
    t8 = TABLE[ 8]; t9 = TABLE[ 9]; tA = TABLE[10]; tB = TABLE[11]
    tC = TABLE[12]; tD = TABLE[13]; tE = TABLE[14]; tF = TABLE[15]
    while i < ii16
      s = #{slicing[ 0]} ^
          #{slicing[ 1]} ^
          #{slicing[ 2]} ^
          #{slicing[ 3]} ^
          #{slicing[ 4]} ^
          #{slicing[ 5]} ^
          #{slicing[ 6]} ^
          #{slicing[ 7]} ^
          #{slicing[ 8]} ^
          #{slicing[ 9]} ^
          #{slicing[10]} ^
          #{slicing[11]} ^
          #{slicing[12]} ^
          #{slicing[13]} ^
          #{slicing[14]} ^
          #{slicing[15]}
      i += 16
    end

    while i < ii
      s = t0[seq.getbyte(i) ^ #{headstate}] ^ #{slidestate}
      i += 1
    end

    s
  end

  def crc(seq, initcrc = INITIAL_CRC)
    finish(update(seq, setup(initcrc)))
  end

  def digest(seq, initcrc = INITIAL_CRC)
    [crc(seq, initcrc)].pack(#{pack.inspect})
  end

  def hexdigest(seq, initcrc = INITIAL_CRC)
    "%0#{sizeof * 2}X" % crc(seq, initcrc)
  end
    EOS

    if reflect_output? ^ reflect_input?
    code << <<-EOS

  def bitreflect(n)
    EOS

    if typebits > bitsize
      code << <<-EOS
    n <<= #{typebits - bitsize}
      EOS
    end

    if typebits > 32
      code << <<-EOS
    n = ((n >> 32) & 0x00000000ffffffff) | ((n & 0x00000000ffffffff) << 32)
      EOS
    end

    if typebits > 16
      code << <<-EOS
    n = ((n >> 16) & 0x#{"0000ffff" * (sizeof / 4)}) | ((n & 0x#{"0000ffff" * (sizeof / 4)}) << 16)
      EOS
    end

    if typebits > 8
      code << <<-EOS
    n = ((n >>  8) & 0x#{"00ff" * (sizeof / 2)}) | ((n & 0x#{"00ff" * (sizeof / 2)}) <<  8)
      EOS
    end

    code << <<-EOS
    n = ((n >>  4) & 0x#{"0f" * sizeof}) | ((n & 0x#{"0f" * sizeof}) <<  4)
    n = ((n >>  2) & 0x#{"33" * sizeof}) | ((n & 0x#{"33" * sizeof}) <<  2)
    n = ((n >>  1) & 0x#{"55" * sizeof}) | ((n & 0x#{"55" * sizeof}) <<  1)
  end
    EOS
  end

  code << <<-EOS
end

TABLE = [
#{Aux.export_slicing_table(table1, "  ", 2, nil, nil, "[", "].freeze", sizeof > 2 ? 4 : 8, &hexnum)}
].freeze
end
  EOS

  ({ source: code })
end

.find(crc, seq, bitsize, polynomial, initstate = [0, ~0, 1], xor = [0, ~0, 1]) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/crc/finder.rb', line 6

def self.find(crc, seq, bitsize, polynomial, initstate = [0, ~0, 1], xor = [0, ~0, 1])
  bitsize0 = bitsize.to_i
  if bitsize0 < 1 || bitsize0 > 128
    raise ArgumentError, "wrong bitsize (expect 1..128, but given #{bitsize})"
  end
  bitmask = ~(~0 << bitsize0)
  crc &= bitmask
  results = []
  poly = Array(polynomial)
  poly.each do |poly|
    poly &= bitmask
    [false, true].each do |refin|
      [false, true].each do |refout|
        Array(xor).each do |xormask|
          xormask &= bitmask
          Array(initstate).each do |init|
            init &= bitmask
            mod = CRC.new(bitsize0, poly, init, refin, refout, xormask)
            results << mod if mod.crc(seq) == crc
          end
        end
      end
    end
  end

  results
end

.hexdigest(modulename, seq, crc = nil) ⇒ Object



459
460
461
# File 'lib/crc.rb', line 459

def hexdigest(modulename, seq, crc = nil)
  lookup(modulename).hexdigest(seq, crc)
end

.lookup(modulename) ⇒ Object Also known as: []



443
444
445
446
447
# File 'lib/crc.rb', line 443

def lookup(modulename)
  modulename1 = modulename.to_s.gsub(/[\W_]+/, "")
  modulename1.downcase!
  MODULE_TABLE[modulename1] or raise NameError, "modulename is not matched (for #{modulename})"
end

.new(bitsize, polynomial, initial_crc = 0, reflect_input = true, reflect_output = true, xor_output = ~0,, name = nil) ⇒ Object

call-seq:

new(bitsize, polynomial, initial_crc = 0, reflect_input = true, reflect_output = true, xor_output = ~0, name = nil) -> new crc module class (CRC based class)
new(initial_crc = nil, size = 0) -> new crc generator (CRC instance)
new(seq, initial_crc = nil, size = 0) -> new crc generator (CRC instance)


34
35
36
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
# File 'lib/crc/_byruby.rb', line 34

def new(bitsize, polynomial, initial_crc = 0, reflect_input = true, reflect_output = true, xor_output = ~0, name = nil)
  bitsize = bitsize.to_i
  if bitsize < 1 || bitsize > 64
    raise ArgumentError, "wrong bitsize (except 1..64, but given #{bitsize})"
  end

  bitmask = ~(~0 << bitsize)
  polynomial = bitmask & polynomial
  initial_crc = bitmask & initial_crc
  xor_output = bitmask & xor_output
  name = (name.nil? || ((name = String(name)).empty?)) ? nil : name

  ::Class.new(self) do
    @bitsize = bitsize
    @bitmask = bitmask
    @polynomial = polynomial
    @initial_crc = initial_crc
    @table = nil
    @reflect_input = !!reflect_input
    @reflect_output = !!reflect_output
    @xor_output = xor_output
    @name = name

    # CRC クラスを普通に派生させた場合でも、CRC.new の基底メソッドが呼ばれるための細工
    define_singleton_method(:new, &Class.instance_method(:new).bind(self))

    singleton_class.class_eval do
      alias_method :[], :new
    end

    extend CRC::ModuleClass
  end
end

.tableObject



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/crc/_byruby.rb', line 233

def table
  if SLICING_SIZE
    if reflect_input
      @table = CRC.build_reflect_table(bitsize, polynomial, slice: SLICING_SIZE)
    else
      @table = CRC.build_table(bitsize, polynomial, slice: SLICING_SIZE)
    end
  else
    @table = nil
  end

  singleton_class.class_eval "attr_reader :table"

  @table
end

.update_with_lookup_table(seq, state) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/crc/_byruby.rb', line 92

def update_with_lookup_table(seq, state)
  t = table[0]

  if reflect_input
    String(seq).each_byte do |ch|
      state = t[state & 0xff ^ ch] ^ (state >> 8)
    end
    state
  else
    Aux.slide_to_head(bitsize, state, polynomial, bitmask) do |s, poly, csh, head, carries|
      carries8 = carries >> 7
      String(seq).each_byte do |ch|
        s = t[(s >> csh) ^ ch] ^ ((carries8 & s) << 8)
      end
      s
    end
  end
end

.update_with_reference(seq, state) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/crc/_byruby.rb', line 68

def update_with_reference(seq, state)
  if reflect_input
    poly = CRC.bitreflect(polynomial, bitsize)
    seq.each_byte do |ch|
      state ^= ch
      8.times { state = (state[0] == 0) ? (state >> 1) : ((state >> 1) ^ poly) }

      # 8.times { state = (state >> 1) ^ (poly & -state[0]) }
      # NOTE: ruby だと、分岐したほうが2割くらい高速
    end

    state
  else
    Aux.slide_to_head(bitsize, state, polynomial, bitmask) do |s, poly, csh, head, carries|
      seq.each_byte do |ch|
        s ^= ch << csh
        8.times { s = (s[head] == 0) ? (s << 1) : (((carries & s) << 1) ^ poly) }
      end

      s
    end
  end
end

.update_with_slice_by_16(seq, s) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/crc/_byruby.rb', line 111

def update_with_slice_by_16(seq, s)
  tX = table
  t0 = tX[ 0]; t1 = tX[ 1]; t2 = tX[ 2]; t3 = tX[ 3]
  t4 = tX[ 4]; t5 = tX[ 5]; t6 = tX[ 6]; t7 = tX[ 7]
  t8 = tX[ 8]; t9 = tX[ 9]; tA = tX[10]; tB = tX[11]
  tC = tX[12]; tD = tX[13]; tE = tX[14]; tF = tX[15]

  i = 0
  ii = seq.bytesize
  ii16 = ii & ~15

  if reflect_input
    case
    when bitsize > 32
      i = 0
      while i < ii16
        s = tF[seq.getbyte(i     ) ^ (s      ) & 0xff] ^ tE[seq.getbyte(i +  1) ^ (s >>  8) & 0xff] ^
            tD[seq.getbyte(i +  2) ^ (s >> 16) & 0xff] ^ tC[seq.getbyte(i +  3) ^ (s >> 24) & 0xff] ^
            tB[seq.getbyte(i +  4) ^ (s >> 32) & 0xff] ^ tA[seq.getbyte(i +  5) ^ (s >> 40) & 0xff] ^
            t9[seq.getbyte(i +  6) ^ (s >> 48) & 0xff] ^ t8[seq.getbyte(i +  7) ^ (s >> 56)       ] ^
            t7[seq.getbyte(i +  8)                   ] ^ t6[seq.getbyte(i +  9)                   ] ^
            t5[seq.getbyte(i + 10)                   ] ^ t4[seq.getbyte(i + 11)                   ] ^
            t3[seq.getbyte(i + 12)                   ] ^ t2[seq.getbyte(i + 13)                   ] ^
            t1[seq.getbyte(i + 14)                   ] ^ t0[seq.getbyte(i + 15)                   ]
        i += 16
      end
    when bitsize > 16
      # speed improvement for 32-bits CRC
      i = 0
      while i < ii16
        s = tF[seq.getbyte(i     ) ^ (s      ) & 0xff] ^ tE[seq.getbyte(i +  1) ^ (s >>  8) & 0xff] ^
            tD[seq.getbyte(i +  2) ^ (s >> 16) & 0xff] ^ tC[seq.getbyte(i +  3) ^ (s >> 24)       ] ^
            tB[seq.getbyte(i +  4)                   ] ^ tA[seq.getbyte(i +  5)                   ] ^
            t9[seq.getbyte(i +  6)                   ] ^ t8[seq.getbyte(i +  7)                   ] ^
            t7[seq.getbyte(i +  8)                   ] ^ t6[seq.getbyte(i +  9)                   ] ^
            t5[seq.getbyte(i + 10)                   ] ^ t4[seq.getbyte(i + 11)                   ] ^
            t3[seq.getbyte(i + 12)                   ] ^ t2[seq.getbyte(i + 13)                   ] ^
            t1[seq.getbyte(i + 14)                   ] ^ t0[seq.getbyte(i + 15)                   ]
        i += 16
      end
    else # when bitsize <= 16
      # speed improvement for 16-bits CRC
      i = 0
      while i < ii16
        s = tF[seq.getbyte(i     ) ^ (s      ) & 0xff] ^ tE[seq.getbyte(i +  1) ^ (s >>  8)       ] ^
            tD[seq.getbyte(i +  2)                   ] ^ tC[seq.getbyte(i +  3)                   ] ^
            tB[seq.getbyte(i +  4)                   ] ^ tA[seq.getbyte(i +  5)                   ] ^
            t9[seq.getbyte(i +  6)                   ] ^ t8[seq.getbyte(i +  7)                   ] ^
            t7[seq.getbyte(i +  8)                   ] ^ t6[seq.getbyte(i +  9)                   ] ^
            t5[seq.getbyte(i + 10)                   ] ^ t4[seq.getbyte(i + 11)                   ] ^
            t3[seq.getbyte(i + 12)                   ] ^ t2[seq.getbyte(i + 13)                   ] ^
            t1[seq.getbyte(i + 14)                   ] ^ t0[seq.getbyte(i + 15)                   ]
        i += 16
      end
    end

    (i...ii).each do |n|
      s = t0[seq.getbyte(n) ^ s & 0xff] ^ (s >> 8)
    end

    s
  else
    Aux.slide_to_head(bitsize, s, polynomial, bitmask) do |s, poly, csh, head, carries|
      case
      when bitsize > 32
        sh = 64 - (head + 1)

        while i < ii16
          s <<= sh
          s = tF[seq.getbyte(i     ) ^ (s >> 56)       ] ^ tE[seq.getbyte(i +  1) ^ (s >> 48) & 0xff] ^
              tD[seq.getbyte(i +  2) ^ (s >> 40) & 0xff] ^ tC[seq.getbyte(i +  3) ^ (s >> 32) & 0xff] ^
              tB[seq.getbyte(i +  4) ^ (s >> 24) & 0xff] ^ tA[seq.getbyte(i +  5) ^ (s >> 16) & 0xff] ^
              t9[seq.getbyte(i +  6) ^ (s >>  8) & 0xff] ^ t8[seq.getbyte(i +  7) ^ (s      ) & 0xff] ^
              t7[seq.getbyte(i +  8)                   ] ^ t6[seq.getbyte(i +  9)                   ] ^
              t5[seq.getbyte(i + 10)                   ] ^ t4[seq.getbyte(i + 11)                   ] ^
              t3[seq.getbyte(i + 12)                   ] ^ t2[seq.getbyte(i + 13)                   ] ^
              t1[seq.getbyte(i + 14)                   ] ^ t0[seq.getbyte(i + 15)                   ]
          i += 16
        end
      when bitsize > 16
        # speed improvement for 32-bits CRC
        sh = 32 - (head + 1)

        while i < ii16
          s <<= sh
          s = tF[seq.getbyte(i     ) ^ (s >> 24)       ] ^ tE[seq.getbyte(i +  1) ^ (s >> 16) & 0xff] ^
              tD[seq.getbyte(i +  2) ^ (s >>  8) & 0xff] ^ tC[seq.getbyte(i +  3) ^ (s      ) & 0xff] ^
              tB[seq.getbyte(i +  4)                   ] ^ tA[seq.getbyte(i +  5)                   ] ^
              t9[seq.getbyte(i +  6)                   ] ^ t8[seq.getbyte(i +  7)                   ] ^
              t7[seq.getbyte(i +  8)                   ] ^ t6[seq.getbyte(i +  9)                   ] ^
              t5[seq.getbyte(i + 10)                   ] ^ t4[seq.getbyte(i + 11)                   ] ^
              t3[seq.getbyte(i + 12)                   ] ^ t2[seq.getbyte(i + 13)                   ] ^
              t1[seq.getbyte(i + 14)                   ] ^ t0[seq.getbyte(i + 15)                   ]
          i += 16
        end
      else # when bitsize <= 16
        # speed improvement for 16-bits CRC
        sh = 16 - (head + 1)

        while i < ii16
          s <<= sh
          s = tF[seq.getbyte(i     ) ^ (s >>  8)       ] ^ tE[seq.getbyte(i +  1) ^ (s      ) & 0xff] ^
              tD[seq.getbyte(i +  2)                   ] ^ tC[seq.getbyte(i +  3)                   ] ^
              tB[seq.getbyte(i +  4)                   ] ^ tA[seq.getbyte(i +  5)                   ] ^
              t9[seq.getbyte(i +  6)                   ] ^ t8[seq.getbyte(i +  7)                   ] ^
              t7[seq.getbyte(i +  8)                   ] ^ t6[seq.getbyte(i +  9)                   ] ^
              t5[seq.getbyte(i + 10)                   ] ^ t4[seq.getbyte(i + 11)                   ] ^
              t3[seq.getbyte(i + 12)                   ] ^ t2[seq.getbyte(i + 13)                   ] ^
              t1[seq.getbyte(i + 14)                   ] ^ t0[seq.getbyte(i + 15)                   ]
          i += 16
        end
      end

      carries8 = carries >> 7
      (i...ii).each do |n|
        s = t0[(s >> csh) ^ seq.getbyte(n)] ^ ((carries8 & s) << 8)
      end
      s
    end
  end
end

Instance Method Details

#+(crc2) ⇒ Object

Raises:

  • (ArgumentError)


342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/crc.rb', line 342

def +(crc2)
  raise ArgumentError, "not a CRC instance (#{crc2.inspect})" unless crc2.kind_of?(CRC)
  m1 = self.class
  m2 = crc2.class
  unless m1.bitsize == m2.bitsize &&
         m1.polynomial == m2.polynomial &&
         m1.reflect_input? == m2.reflect_input? &&
         m1.reflect_output? == m2.reflect_output? &&
         # m1.initial_crc == m2.initial_crc &&
         m1.xor_output == m2.xor_output
    raise ArgumentError, "different CRC module (#{m1.inspect} and #{m2.inspect})"
  end
  m1.new(m1.combine(crc, crc2.crc, crc2.size), size + crc2.size)
end

#==(a) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/crc.rb', line 357

def ==(a)
  case a
  when CRC
    m1 = self.class
    m2 = a.class
    if m1.bitsize == m2.bitsize &&
       m1.polynomial == m2.polynomial &&
       m1.reflect_input? == m2.reflect_input? &&
       m1.reflect_output? == m2.reflect_output? &&
       # m1.initial_crc == m2.initial_crc &&
       m1.xor_output == m2.xor_output &&
       state == a.state
      true
    else
      false
    end
  when Integer
    crc == a
  else
    super
  end
end

#crcObject



338
339
340
# File 'lib/crc.rb', line 338

def crc
  self.class.finish(state)
end

#digestObject



387
388
389
# File 'lib/crc.rb', line 387

def digest
  Aux.digest(crc, self.class.bitsize)
end

#digest!Object

return digest as internal state



392
393
394
# File 'lib/crc.rb', line 392

def digest!
  Aux.digest(state, self.class.bitsize)
end

#hexdigestObject



396
397
398
# File 'lib/crc.rb', line 396

def hexdigest
  Aux.hexdigest(crc, self.class.bitsize)
end

#hexdigest!Object

return hex-digest as internal state



401
402
403
# File 'lib/crc.rb', line 401

def hexdigest!
  Aux.hexdigest(state, self.class.bitsize)
end

#inspectObject



408
409
410
# File 'lib/crc.rb', line 408

def inspect
  "\#<#{self.class}:#{hexdigest}>"
end

#pretty_inspect(q) ⇒ Object



412
413
414
# File 'lib/crc.rb', line 412

def pretty_inspect(q)
  q.text inspect
end

#reset(initial_crc = nil, size = 0) ⇒ Object



323
324
325
326
327
328
# File 'lib/crc.rb', line 323

def reset(initial_crc = nil, size = 0)
  m = self.class
  @state = m.setup((initial_crc || m.initial_crc).to_i)
  @size = size.to_i
  self
end

#to_aObject



383
384
385
# File 'lib/crc.rb', line 383

def to_a
  [crc]
end

#to_iObject



380
381
382
# File 'lib/crc.rb', line 380

def crc
  self.class.finish(state)
end

#to_intObject



381
382
383
# File 'lib/crc.rb', line 381

def crc
  self.class.finish(state)
end

#to_sObject



406
407
408
# File 'lib/crc.rb', line 406

def hexdigest
  Aux.hexdigest(crc, self.class.bitsize)
end

#to_strObject



405
406
407
# File 'lib/crc.rb', line 405

def hexdigest
  Aux.hexdigest(crc, self.class.bitsize)
end

#update(seq) ⇒ Object Also known as: <<



330
331
332
333
334
# File 'lib/crc.rb', line 330

def update(seq)
  @state = self.class.update(seq, state)
  @size += seq.bytesize
  self
end