File: accept_charset.rb

package info (click to toggle)
ruby-protocol-http 0.55.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 840 kB
  • sloc: ruby: 6,904; makefile: 4
file content (45 lines) | stat: -rw-r--r-- 1,162 bytes parent folder | download
1
2
3
4
5
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
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2025, by Samuel Williams.

require_relative "split"
require_relative "../quoted_string"
require_relative "../error"

module Protocol
	module HTTP
		module Header
			# The `accept-charset` header represents a list of character sets that the client can accept.
			class AcceptCharset < Split
				ParseError = Class.new(Error)
				
				# https://tools.ietf.org/html/rfc7231#section-5.3.3
				CHARSET = /\A(?<name>#{TOKEN})(;q=(?<q>#{QVALUE}))?\z/
				
				Charset = Struct.new(:name, :q) do
					def quality_factor
						(q || 1.0).to_f
					end
					
					def <=> other
						other.quality_factor <=> self.quality_factor
					end
				end
				
				# Parse the `accept-charset` header value into a list of character sets.
				#
				# @returns [Array(Charset)] the list of character sets and their associated quality factors.
				def charsets
					self.map do |value|
						if match = value.match(CHARSET)
							Charset.new(match[:name], match[:q])
						else
							raise ParseError.new("Could not parse character set: #{value.inspect}")
						end
					end
				end
			end
		end
	end
end