File: priority.rb

package info (click to toggle)
ruby-protocol-http 0.59.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 864 kB
  • sloc: ruby: 7,612; makefile: 4
file content (72 lines) | stat: -rw-r--r-- 2,503 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
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
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2024-2026, by Samuel Williams.

require_relative "split"

module Protocol
	module HTTP
		module Header
			# Represents the `priority` header, used to indicate the relative importance of an HTTP request.
			#
			# The `priority` header allows clients to express their preference for how resources should be prioritized by the server. It supports directives like `u=` to specify the urgency level of a request, and `i` to indicate whether a response can be delivered incrementally. The urgency levels range from 0 (highest priority) to 7 (lowest priority), while the `i` directive is a boolean flag.
			class Priority < Split
				# Parses a raw header value.
				#
				# @parameter value [String] a raw header value containing comma-separated directives.
				# @returns [Priority] a new instance with normalized (lowercase) directives.
				def self.parse(value)
					self.new(value.downcase.split(COMMA))
				end
				
				# Coerces a value into a parsed header object.
				#
				# @parameter value [String | Array] the value to coerce.
				# @returns [Priority] a parsed header object with normalized values.
				def self.coerce(value)
					case value
					when Array
						self.new(value.map(&:downcase))
					else
						self.parse(value.to_s)
					end
				end
				
				# Add a value to the priority header.
				#
				# @parameter value [String] a raw header value containing directives to add to the header.
				def << value
					super(value.downcase)
				end
				
				# The default urgency level if not specified.
				DEFAULT_URGENCY = 3
				
				# The urgency level, if specified using `u=`. 0 is the highest priority, and 7 is the lowest.
				#
				# Note that when duplicate Dictionary keys are encountered, all but the last instance are ignored.
				#
				# @returns [Integer | Nil] the urgency level if specified, or `nil` if not present.
				def urgency(default = DEFAULT_URGENCY)
					if value = self.reverse_find{|value| value.start_with?("u=")}
						_, level = value.split("=", 2)
						return Integer(level)
					end
					
					return default
				end
				
				# Checks if the response should be delivered incrementally.
				#
				# The `i` directive, when present, indicates that the response can be delivered incrementally as data becomes available.
				#
				# @returns [Boolean] whether the request should be delivered incrementally.
				def incremental?
					self.include?("i")
				end
			end
		end
	end
end