fast-proxy-status 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,654 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fast
4
+ class ProxyStatus
5
+ # RFC 9651 value shapes aliased here, private to this gem, so the
6
+ # checks and the walks read them by the short name.
7
+ Item = SFV::Item
8
+ Token = SFV::Token
9
+ private_constant :Item, :Token
10
+
11
+ # The Byte Sequence tag: a String tagged ASCII-8BIT IS the Byte
12
+ # Sequence on the wire (RFC 9651 §3.3.5 — the encoding is the
13
+ # wire-type tag), so the identifier constraint below reads the same
14
+ # fact, and a UTF-8 String would emit as a quoted sf-string.
15
+ BINARY = Encoding::ASCII_8BIT
16
+ private_constant :BINARY
17
+
18
+ # The shared engine of the gem's two List fields. Proxy-Status
19
+ # (RFC 9209 §2) and Cache-Status (RFC 9211 §2) are both RFC 9651
20
+ # Lists of parameterized Items whose members identify the
21
+ # intermediary or cache that inserted them, and both RFCs state the
22
+ # same member constraint (RFC 9209 §2: "this identifier MUST be a
23
+ # String or Token"; RFC 9211 §2: "this identifier MUST be a String
24
+ # or Token"), so the List machinery lives here once: the
25
+ # one-walk/two-policy parse, the positioning Scan, the frozen value
26
+ # object over the members, the append-yourself operation and the
27
+ # generic member construction boundary. A field class includes this
28
+ # module and answers three private class hooks — member_class,
29
+ # empty_value and field_label — while its member class subclasses
30
+ # ListField::Member with its own parameter table and typed readers.
31
+ # The RFC 9213 field is a Dictionary and does not include this
32
+ # module: its members are key-value and its leniency is
33
+ # per-directive, not whole-field.
34
+ #
35
+ # The engine raises the FIELD's errors: the class-level machinery
36
+ # resolves them as self::ParseError and the instance-level as
37
+ # self.class::SerializeError, because each field's error hierarchy
38
+ # nests in the field class (and every one of them descends from
39
+ # Fast::ProxyStatus::Error, so a caller can guard the whole gem
40
+ # with one rescue). The field's empty value is read through the
41
+ # empty_value hook for the same reason: a private constant of one
42
+ # field class is unreachable from another's scope, and a bare EMPTY
43
+ # in this module would resolve to the wrong field's value.
44
+ module ListField
45
+ # The class-level engine, extended into the field class by the
46
+ # include below: the two parses, the boolean mirror, the
47
+ # append-yourself class form, and the private one-walk/two-policy
48
+ # machinery they share.
49
+ module ClassMethods
50
+ # RFC 9651 §2.2, the recipient semantics — never raises on field
51
+ # content. A field whose syntax is not a Structured Field Value,
52
+ # or whose List carries ANY member that is not a String or Token,
53
+ # is the ENTIRE field ignored ("When field-specific constraints
54
+ # are violated, the entire field is also ignored, unless the
55
+ # field definition defines other handling requirements" — the
56
+ # field's own RFC defines no other handling for members): the
57
+ # shared frozen empty value, the same answer an absent field
58
+ # gives. Parameters NEVER fail the field: an unknown parameter
59
+ # is preserved in the member's data and ignored semantically,
60
+ # and a known parameter of a type the field's own sections do
61
+ # not allow is likewise preserved and ignored by the typed
62
+ # readers — the lenient parse is THIS walk with the parameter
63
+ # checks not applied, never the strict walk rescued, so a
64
+ # parameter violation can never drop the field while a member
65
+ # violation must. "" is the valid empty List (RFC 9651 §4.2.1)
66
+ # and parses to a fresh empty value. A String is one field
67
+ # value; an Array is the field's lines, combined with ", "
68
+ # (§4.2) — a List has no last-wins, the members concatenate.
69
+ # A wrong input type is a caller bug and raises TypeError.
70
+ def parse(input)
71
+ walk(input, false)
72
+ rescue self::ParseError
73
+ empty_value
74
+ end
75
+
76
+ # Strict truth. The RFC 9651 List failure is wrapped with its
77
+ # message and byte offset preserved; then the constraints, the
78
+ # FIRST offender in List order raised positioned: the member
79
+ # constraint (a member that is not a String or Token) at the
80
+ # member's identifier — its first non-OWS byte in the combined
81
+ # field value — and the field's own parameter constraints at the
82
+ # parameter's VALUE, just past the "=" (the key's end for the
83
+ # valueless form, the implicit Boolean true), the message naming
84
+ # the parameter and the type the field's section states.
85
+ # Unknown parameters are valid and preserved on the strict path.
86
+ # TypeError for a wrong input type, as parse.
87
+ def parse!(input)
88
+ walk(input, true)
89
+ end
90
+
91
+ # The boolean mirror: true exactly when parse! returns — false
92
+ # for malformed content, member violations, wrong-typed
93
+ # parameters and a wrong input type alike (a caller bug is not
94
+ # field content either). The empty value is true.
95
+ def valid?(input)
96
+ walk(input, true)
97
+ true
98
+ rescue TypeError, self::ParseError
99
+ false
100
+ end
101
+
102
+ # The append-yourself operation, the class form. +input+ is the
103
+ # field as received — a String, an Array of field lines, an
104
+ # existing value reused as held, or nil for a response bearing
105
+ # none — parsed leniently (a malformed upstream field is treated
106
+ # as absent: the sender starts a fresh list rather than failing
107
+ # the response); this sender's +member+ is appended as the LAST
108
+ # member (the field's RFC: closest to the user) with the
109
+ # received members preserved in order. Answers a NEW frozen
110
+ # value whose to_s re-emits the whole list canonically.
111
+ # TypeError for a wrong +input+ type (a caller bug);
112
+ # SerializeError for a wrong member or parameter (field
113
+ # content, the construction boundary).
114
+ def append(input, member, params = {})
115
+ held_value(input).append(member, params)
116
+ end
117
+
118
+ private
119
+
120
+ # The one walk behind parse and parse!: the RFC 9651 List parse,
121
+ # then the member constraint on every member in List order and —
122
+ # only when +strict+ — the field's parameter constraints, the
123
+ # first offender raised positioned. The lenient parse is THIS
124
+ # walk with the parameter checks not applied, never the strict
125
+ # walk rescued: a parameter violation must not drop the field
126
+ # while a member violation must (RFC 9651 §2.2), and the shared
127
+ # constraint predicates and Scan keep the two policies'
128
+ # semantics and offsets from drifting. The underlying List
129
+ # failure is wrapped with its message and offset.
130
+ def walk(input, strict)
131
+ members = SFV.parse_list(input)
132
+ from_members(members_from_items(members, combined(input), strict))
133
+ rescue SFV::ParseError => e
134
+ raise self::ParseError.new(e.message, e.offset)
135
+ end
136
+
137
+ # The field value the Scan positions into: the lines joined with
138
+ # ", " — the same RFC 9651 §4.2 combining Fast::SFV.parse_list
139
+ # applies — a String as given.
140
+ def combined(input)
141
+ input.is_a?(Array) ? input.join(", ") : input
142
+ end
143
+
144
+ # The member walk over a parsed List: the member constraint on
145
+ # every member, then the field's parameter checks (strict only),
146
+ # the first offender in List order raising positioned — a
147
+ # member's params are checked before the NEXT member, so
148
+ # "good; error=5, 5" raises at the parameter. A manual position
149
+ # counter: the member index the positioning Scan reads.
150
+ def members_from_items(members, field_value, strict)
151
+ index = 0
152
+ while index < members.size
153
+ member = members[index]
154
+ fail_member!(field_value, index, member) unless member_class.member_ok?(member)
155
+ check_params!(member, field_value, index) if strict
156
+ index += 1
157
+ end
158
+ members.map { |member| member_class.from_item(member) }
159
+ end
160
+
161
+ # The member constraint, positioned at the member's identifier.
162
+ def fail_member!(field_value, index, member)
163
+ offset = Scan.new(field_value).member_offset(index)
164
+ raise self::ParseError.new("a #{field_label} member is a String or Token (got #{shown(member)})", offset)
165
+ end
166
+
167
+ # The field's parameter constraints over one member, in the
168
+ # parameters' wire order: the first offender raises positioned
169
+ # at its VALUE. Unknown parameters are skipped — the field's own
170
+ # "unrecognised parameters MUST be ignored" rule — and
171
+ # preserved.
172
+ def check_params!(member, field_value, index)
173
+ member.params.each do |key, value|
174
+ rule = member_class.param_rule(key)
175
+ next if rule.nil? || member_class.param_ok?(key, value)
176
+
177
+ offset = Scan.new(field_value).param_offset(index, key)
178
+ raise self::ParseError.new("#{key}: the value is #{rule} (got #{value})", offset)
179
+ end
180
+ end
181
+
182
+ # What a member error shows of the offender: the bare value when
183
+ # it is an Item (a wrong type), the member's class when it is not
184
+ # an Item at all — an inner list.
185
+ def shown(member)
186
+ member.is_a?(Item) ? member.value : member.class
187
+ end
188
+
189
+ # A field argument as received, the value form: nil for the
190
+ # absent field (the empty value — a fresh list), an existing
191
+ # value reused as held, a String or Array of lines parsed
192
+ # leniently (a malformed field treated as absent). TypeError for
193
+ # anything else.
194
+ def held_value(input)
195
+ return empty_value if input.nil?
196
+ return input if input.is_a?(self)
197
+
198
+ parse(input)
199
+ end
200
+
201
+ # The value object behind members that already passed the
202
+ # checks: the members held as given, no re-validation (the parse
203
+ # path and append build members at their own boundaries).
204
+ def from_members(members)
205
+ field = allocate
206
+ field.send(:hold, members)
207
+ field
208
+ end
209
+ end
210
+
211
+ # Rides the include: the class-level engine above becomes the
212
+ # field class's class methods.
213
+ def self.included(base)
214
+ base.extend ClassMethods
215
+ end
216
+
217
+ # The first member of the List — the field's RFC: the member
218
+ # closest to the origin server. nil when nothing is held.
219
+ def first
220
+ @members.first
221
+ end
222
+
223
+ # The last member — the field's RFC: the member closest to the
224
+ # user. nil when nothing is held.
225
+ def last
226
+ @members.last
227
+ end
228
+
229
+ # How many members the field holds.
230
+ def size
231
+ @members.size
232
+ end
233
+
234
+ # No members held — an absent field, or one treated as absent.
235
+ def empty?
236
+ @members.empty?
237
+ end
238
+
239
+ # Yields each member in wire order.
240
+ def each(&block)
241
+ @members.each(&block)
242
+ end
243
+
244
+ # The member at +index+ — Array semantics (negative indices, nil
245
+ # beyond the ends).
246
+ def [](index)
247
+ @members[index]
248
+ end
249
+
250
+ # The append-yourself operation, the instance form: the received
251
+ # members preserved in order, this sender's member appended as the
252
+ # LAST (the field's RFC: closest to the user). Answers a NEW
253
+ # frozen value; self is never mutated, and to_s re-emits the whole
254
+ # list canonically (non-canonical spacing normalizes through the
255
+ # round-trip). +member+ is the identifier (a plain String emits
256
+ # quoted, a Token bare), +params+ the parameter Hash;
257
+ # SerializeError for a wrong member or parameter (the construction
258
+ # boundary).
259
+ def append(member, params = {})
260
+ members = @members.dup
261
+ members << self.class.send(:member_class).new(member, params)
262
+ self.class.send(:from_members, members)
263
+ end
264
+
265
+ # The canonical wire form: the RFC 9651 §4.1.1 List serialization
266
+ # of the held members, "" when none are held (a sender omits the
267
+ # field entirely — the same reason Fast::SFV.serialize_list
268
+ # answers nil for the empty List). Never raises: construction
269
+ # validated every member, and a parsed value re-emits its
270
+ # canonical form.
271
+ def to_s
272
+ SFV.serialize_list(@members) || ""
273
+ end
274
+
275
+ # Canonical-wire-form equality WITHIN the field class: two fields
276
+ # are the same when they serialize the same.
277
+ def ==(other)
278
+ other.instance_of?(self.class) && to_s == other.to_s
279
+ end
280
+ alias eql? ==
281
+
282
+ # Consistent with eql? — the canonical form's hash.
283
+ def hash
284
+ to_s.hash
285
+ end
286
+
287
+ def inspect
288
+ wire = to_s
289
+ wire.empty? ? "#<#{self.class.name}>" : "#<#{self.class.name} #{wire}>"
290
+ end
291
+
292
+ # Strict construction — a sender never puts garbage on the wire.
293
+ # +members+ is an Array of the field's member objects, each
294
+ # validated at its own construction (the member class's new is the
295
+ # boundary); the Array freezes IN PLACE. The empty Array builds
296
+ # the empty value: a sender omits the field entirely.
297
+ def initialize(members)
298
+ check_members!(members)
299
+ hold(members)
300
+ end
301
+
302
+ private
303
+
304
+ # The construction boundary: an Array of the field's members, each
305
+ # already validated at its own construction.
306
+ def check_members!(members)
307
+ klass = self.class.send(:member_class)
308
+ unless members.is_a?(Array)
309
+ raise self.class::SerializeError.new("members are an Array of #{klass} (got #{members.class})", 0)
310
+ end
311
+
312
+ members.each { |member| check_member!(member) }
313
+ end
314
+
315
+ # One member's boundary: a member of the field's member class —
316
+ # its own construction was its validation.
317
+ def check_member!(member)
318
+ klass = self.class.send(:member_class)
319
+ return if member.is_a?(klass)
320
+
321
+ raise self.class::SerializeError.new("a member is a #{klass} (got #{member.class})", 0)
322
+ end
323
+
324
+ # The one place the held state is written, then frozen: the
325
+ # members Array (frozen already on the parse path, frozen in place
326
+ # by a construction). Each field's public reader names it —
327
+ # ProxyStatus #hops, CacheStatus #caches.
328
+ def hold(members)
329
+ @members = members.freeze
330
+ freeze
331
+ end
332
+
333
+ # The member base of the two List fields: the generic half of the
334
+ # member value object, everything the two RFCs state identically.
335
+ # The subclass — Fast::ProxyStatus::Hop,
336
+ # Fast::CacheStatus::Cache — declares its own parameter table
337
+ # (param_rule/param_ok?, the field's own sections) and its typed
338
+ # readers, and answers the FIELD's SerializeError through the
339
+ # private serialize_error hook, because the error hierarchy nests
340
+ # in the field class, not in the member class. The base is an
341
+ # Fast::SFV::Item: #value, #params and the canonical strict #to_s
342
+ # are inherited and the member serializes inside
343
+ # Fast::SFV.serialize_list unchanged, while the base adds the raw
344
+ # #[] reader, the identifier and parameter construction boundary,
345
+ # and class-checked canonical equality (a Hop never equals a
346
+ # Cache, whatever their value and parameters — the class is the
347
+ # member's identity).
348
+ class Member < Item
349
+ # A 256-entry byte class: true for every byte of +spec+ — the
350
+ # byte-table shape the family's scanners walk with.
351
+ def self.byte_class(spec)
352
+ table = Array.new(256, false)
353
+ spec.each_byte { |byte| table[byte] = true }
354
+ table.freeze
355
+ end
356
+ private_class_method :byte_class
357
+
358
+ # A Structured Fields key's first byte: lcalpha or "*" (RFC 9651
359
+ # §4.2.3.3 step 1) — the grammar a parameter key must spell.
360
+ KEY_FIRST = byte_class("abcdefghijklmnopqrstuvwxyz*")
361
+ # A key's continuation: lcalpha, DIGIT, "_", "-", "." or "*"
362
+ # (§4.2.3.3) — the class the construction's key walk and the
363
+ # Scan's key walk read (the first byte is a member of it).
364
+ KEY_BODY = byte_class("abcdefghijklmnopqrstuvwxyz0123456789_-.*")
365
+
366
+ class << self
367
+ # The member constraint both List fields state: every member
368
+ # an Item whose value is a String or Token. A violation is the
369
+ # ENTIRE field ignored under the lenient parse (RFC 9651 §2.2
370
+ # — neither field defines other handling for members) and a
371
+ # positioned ParseError under the strict one.
372
+ def member_ok?(member)
373
+ member.is_a?(Item) && identifier_value?(member.value)
374
+ end
375
+
376
+ # The identifier's constraint: a Token, or a plain String —
377
+ # the class is the wire-type tag (a plain String emits
378
+ # quoted, a Token bare, and the content never decides which).
379
+ # A String tagged ASCII-8BIT is a Byte Sequence on the wire,
380
+ # not a String, so it fails here and the construction refuses
381
+ # it.
382
+ def identifier_value?(value)
383
+ value.is_a?(Token) || (value.is_a?(String) && value.encoding != BINARY)
384
+ end
385
+
386
+ # A bare Structured Fields type (RFC 9651 §3.3.1) — the value
387
+ # set an unknown parameter accepts at construction: Integer,
388
+ # Float, String (a Token is one, a binary-tagged one is a Byte
389
+ # Sequence), Boolean, Date or DisplayString. A Symbol or nil
390
+ # is wrong-typed input and never reaches the wire.
391
+ def bare_type?(value)
392
+ case value
393
+ when Integer, Float, String, true, false, SFV::Date, SFV::DisplayString then true
394
+ else false
395
+ end
396
+ end
397
+
398
+ # The parse-path constructor: no re-validation, the value and
399
+ # params held as parsed — the parser already guaranteed the
400
+ # wire grammar, and a wrong-typed parameter is diagnostic DATA
401
+ # the lenient parse preserves, never a construction failure.
402
+ def from_item(item)
403
+ member = allocate
404
+ member.send(:hold, item.value, item.params)
405
+ member
406
+ end
407
+ end
408
+
409
+ # Strict construction — a sender never puts garbage on the wire.
410
+ # +value+ is the member's identifier: a plain String (emits
411
+ # quoted) or a Fast::SFV::Token (emits bare) — the class is the
412
+ # wire-type tag; a String tagged ASCII-8BIT is refused (it would
413
+ # emit as a Byte Sequence). +params+ is a Hash of the field's
414
+ # parameters under Structured Fields keys: the ones the field's
415
+ # own sections define carry their sections' types, any other
416
+ # parameter any bare Structured Fields type. The value String
417
+ # and the params Hash are frozen IN PLACE as part of the value
418
+ # object — pass copies if the buffers are reused. Anything else
419
+ # raises SerializeError naming the parameter and the type;
420
+ # byte-level String validity stays the serializer's own check
421
+ # at #to_s, so a pathological hand-built value fails there — a
422
+ # parsed value can never reach it.
423
+ def initialize(value, params = {})
424
+ check_value!(value)
425
+ check_params!(params)
426
+ value.freeze
427
+ super(value, params)
428
+ end
429
+
430
+ # Any parameter's value, whatever type it arrived as — the
431
+ # diagnostic leniency's raw view: unknown parameters and
432
+ # wrong-typed ones are preserved in the data (#[], #params) and
433
+ # ignored by the typed readers.
434
+ def [](key)
435
+ @params[key]
436
+ end
437
+
438
+ # Canonical-wire-form equality WITHIN the member class: a
439
+ # member never equals a plain Item, or a member of the other
440
+ # field's class, whatever their value and parameters — the
441
+ # class is the member's identity.
442
+ def ==(other)
443
+ other.instance_of?(self.class) && to_s == other.to_s
444
+ end
445
+ alias eql? ==
446
+
447
+ # Consistent with eql? — the canonical form's hash.
448
+ def hash
449
+ to_s.hash
450
+ end
451
+
452
+ def inspect
453
+ "#<#{self.class.name} #{self}>"
454
+ end
455
+
456
+ private
457
+
458
+ # The one place the held state is written, then frozen: the
459
+ # parse path's already-frozen value and params, as parsed.
460
+ def hold(value, params)
461
+ @value = value
462
+ @params = params
463
+ freeze
464
+ end
465
+
466
+ # The identifier constraint at the boundary.
467
+ def check_value!(value)
468
+ return if self.class.identifier_value?(value)
469
+
470
+ raise self.class.send(:serialize_error, "a member identifier is a String or a Token (got #{value.inspect})")
471
+ end
472
+
473
+ # The params boundary: a Hash of Structured Fields keys, each
474
+ # value the type its key's section allows (any bare type for an
475
+ # unknown key), frozen IN PLACE.
476
+ def check_params!(params)
477
+ raise self.class.send(:serialize_error, "params are a Hash (got #{params.class})") unless params.is_a?(Hash)
478
+
479
+ params.each do |key, value|
480
+ check_key!(key)
481
+ check_param!(key, value)
482
+ end
483
+ params.freeze
484
+ end
485
+
486
+ # The parameter key grammar, RFC 9651 §4.2.3.3 read from the
487
+ # value side: a String whose first byte is lcalpha or "*" and
488
+ # whose bytes continue in lcalpha, DIGIT, "_", "-", "." or "*".
489
+ def check_key!(key)
490
+ return if valid_key?(key)
491
+
492
+ raise self.class.send(:serialize_error, "#{key.inspect} is not a Structured Fields key")
493
+ end
494
+
495
+ # The walk behind check_key! — manual and allocation-free, the
496
+ # shape the substrate's own key parse uses.
497
+ def valid_key?(key)
498
+ return false unless key.is_a?(String)
499
+
500
+ size = key.bytesize
501
+ return false if size.zero? || !KEY_FIRST[key.getbyte(0)]
502
+
503
+ index = 1
504
+ while index < size
505
+ return false unless KEY_BODY[key.getbyte(index)]
506
+
507
+ index += 1
508
+ end
509
+ true
510
+ end
511
+
512
+ # One parameter's value at the boundary: a key the field's own
513
+ # sections define carries its section's type, any other key any
514
+ # bare Structured Fields type.
515
+ def check_param!(key, value)
516
+ rule = self.class.param_rule(key)
517
+ if rule
518
+ return if self.class.param_ok?(key, value)
519
+
520
+ raise self.class.send(:serialize_error, "#{key}: the value is #{rule} (got #{value.inspect})")
521
+ end
522
+ return if self.class.bare_type?(value)
523
+
524
+ raise self.class.send(:serialize_error,
525
+ "#{key}: the value is a bare Structured Fields type (got #{value.inspect})")
526
+ end
527
+ end
528
+
529
+ # The strict parse's positioning walk: where a member's identifier
530
+ # and a parameter's VALUE sit in the combined field value — the
531
+ # byte offsets a member or parameter ParseError points at. The
532
+ # field value already parsed when this runs, so the walk only
533
+ # tracks the boundaries: members split on commas at inner-list
534
+ # depth zero outside quoted strings (RFC 9651 §4.2's separators);
535
+ # a semicolon at depth zero outside a string starts a parameter of
536
+ # the member's top-level item (tokens, byte sequences and numbers
537
+ # cannot carry one; a string's and a display string's semicolons
538
+ # are inside their quotes; an inner list's are inside its parens).
539
+ # The walk runs ONLY where an error needs an offset — the clean
540
+ # paths pay nothing for positioning.
541
+ class Scan
542
+ # A 256-entry byte class: true for every byte of +spec+ — the
543
+ # byte-table shape the family's scanners walk with.
544
+ def self.byte_class(spec)
545
+ table = Array.new(256, false)
546
+ spec.each_byte { |byte| table[byte] = true }
547
+ table.freeze
548
+ end
549
+
550
+ # A key's bytes (RFC 9651 §4.2.3.3) — the member's own grammar
551
+ # class, the same table the construction's key check reads.
552
+ KEY_BODY = Member::KEY_BODY
553
+ # The optional whitespace around a member separator (§4.2.1).
554
+ OWS = byte_class(" \t")
555
+
556
+ COMMA = 0x2C
557
+ SEMICOLON = 0x3B
558
+ EQUALS = 0x3D
559
+ LPAREN = 0x28
560
+ RPAREN = 0x29
561
+ DQUOTE = 0x22
562
+ BACKSLASH = 0x5C
563
+ SP = 0x20
564
+
565
+ def initialize(combined)
566
+ @combined = combined
567
+ @size = combined.bytesize
568
+ end
569
+
570
+ # The byte offset of member +index+'s identifier: its first
571
+ # non-OWS byte — where a member ParseError points.
572
+ def member_offset(index)
573
+ pos = skip_ows(0)
574
+ member = 0
575
+ while member < index
576
+ pos = boundary(pos, false) + 1
577
+ pos = skip_ows(pos)
578
+ member += 1
579
+ end
580
+ pos
581
+ end
582
+
583
+ # The byte offset of member +index+'s +key+ parameter VALUE:
584
+ # just past the "=" when the parameter carries one, the key's end
585
+ # for the valueless form (the implicit Boolean true, written
586
+ # where a value would be). The LAST occurrence of the key wins —
587
+ # the mirror of the parse's last-wins parameter Hash, whose
588
+ # effective value the check read.
589
+ def param_offset(index, key)
590
+ pos = boundary(member_offset(index), true)
591
+ offset = nil
592
+ while pos < @size && @combined.getbyte(pos) == SEMICOLON
593
+ pos += 1
594
+ pos += 1 while pos < @size && @combined.getbyte(pos) == SP
595
+ key_start = pos
596
+ pos += 1 while pos < @size && KEY_BODY[@combined.getbyte(pos)]
597
+ key_end = pos
598
+ value_offset = key_end
599
+ if pos < @size && @combined.getbyte(pos) == EQUALS
600
+ pos += 1
601
+ value_offset = pos
602
+ pos = boundary(pos, true)
603
+ end
604
+ offset = value_offset if @combined.byteslice(key_start, key_end - key_start) == key
605
+ end
606
+ offset
607
+ end
608
+
609
+ private
610
+
611
+ # Discards leading OWS.
612
+ def skip_ows(index)
613
+ index += 1 while index < @size && OWS[@combined.getbyte(index)]
614
+ index
615
+ end
616
+
617
+ # The index of the next boundary at inner-list depth zero outside
618
+ # a quoted string, starting at +index+: always the "," that ends
619
+ # a member, and — when +params_too+ — the ";" that starts the
620
+ # member's top-level parameters or follows one parameter's value,
621
+ # found first. A quoted string's separators are inside its quotes
622
+ # (§4.2.5, a backslash escapes the next byte), an inner list's
623
+ # are inside its parens (§4.2.1.1).
624
+ def boundary(index, params_too)
625
+ depth = 0
626
+ quoted = false
627
+ while index < @size
628
+ byte = @combined.getbyte(index)
629
+ if quoted
630
+ index += byte == BACKSLASH ? 2 : 1
631
+ quoted = false if byte == DQUOTE
632
+ else
633
+ case byte
634
+ when DQUOTE
635
+ quoted = true
636
+ when LPAREN
637
+ depth += 1
638
+ when RPAREN
639
+ depth -= 1
640
+ when SEMICOLON
641
+ return index if params_too && depth.zero?
642
+ when COMMA
643
+ return index if depth.zero?
644
+ end
645
+ index += 1
646
+ end
647
+ end
648
+ index
649
+ end
650
+ end
651
+ private_constant :Scan
652
+ end
653
+ end
654
+ end