1# frozen_string_literal: false
2#--
3# HTTPVersion.rb -- presentation of HTTP version
4#
5# Author: IPR -- Internet Programming with Ruby -- writers
6# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
7# reserved.
8#
9# $IPR: httpversion.rb,v 1.5 2002/09/21 12:23:37 gotoyuzo Exp $
10
11module WEBrick
12
13  ##
14  # Represents an HTTP protocol version
15
16  class HTTPVersion
17    include Comparable
18
19    ##
20    # The major protocol version number
21
22    attr_accessor :major
23
24    ##
25    # The minor protocol version number
26
27    attr_accessor :minor
28
29    ##
30    # Converts +version+ into an HTTPVersion
31
32    def self.convert(version)
33      version.is_a?(self) ? version : new(version)
34    end
35
36    ##
37    # Creates a new HTTPVersion from +version+.
38
39    def initialize(version)
40      case version
41      when HTTPVersion
42        @major, @minor = version.major, version.minor
43      when String
44        if /^(\d+)\.(\d+)$/ =~ version
45          @major, @minor = $1.to_i, $2.to_i
46        end
47      end
48      if @major.nil? || @minor.nil?
49        raise ArgumentError,
50          format("cannot convert %s into %s", version.class, self.class)
51      end
52    end
53
54    ##
55    # Compares this version with +other+ according to the HTTP specification
56    # rules.
57
58    def <=>(other)
59      unless other.is_a?(self.class)
60        other = self.class.new(other)
61      end
62      if (ret = @major <=> other.major) == 0
63        return @minor <=> other.minor
64      end
65      return ret
66    end
67
68    ##
69    # The HTTP version as show in the HTTP request and response.  For example,
70    # "1.1"
71
72    def to_s
73      format("%d.%d", @major, @minor)
74    end
75  end
76end
77