Method: DomainName::Punycode.encode

Defined in:
lib/domain_name/punycode.rb

.encode(string) ⇒ Object

Encode a string in Punycode



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
# File 'lib/domain_name/punycode.rb', line 101

def encode(string)
  input = string.unpack('U*')
  output = ''

  # Initialize the state
  n = INITIAL_N
  delta = 0
  bias = INITIAL_BIAS

  # Handle the basic code points
  input.each { |cp| output << cp.chr if cp < 0x80 }

  h = b = output.length

  # h is the number of code points that have been handled, b is the
  # number of basic code points, and out is the number of characters
  # that have been output.

  output << DELIMITER if b > 0

  # Main encoding loop

  while h < input.length
    # All non-basic code points < n have been handled already.  Find
    # the next larger one

    m = MAXINT
    input.each { |cp|
      m = cp if (n...m) === cp
    }

    # Increase delta enough to advance the decoder's <n,i> state to
    # <m,0>, but guard against overflow

    delta += (m - n) * (h + 1)
    raise BufferOverflowError if delta > MAXINT
    n = m

    input.each { |cp|
      # AMC-ACE-Z can use this simplified version instead
      if cp < n
        delta += 1
        raise BufferOverflowError if delta > MAXINT
      elsif cp == n
        # Represent delta as a generalized variable-length integer
        q = delta
        k = BASE
        loop {
          t = k <= bias ? TMIN : k - bias >= TMAX ? TMAX : k - bias
          break if q < t
          q, r = (q - t).divmod(BASE - t)
          output << ENCODE_DIGIT[t + r, false]
          k += BASE
        }

        output << ENCODE_DIGIT[q, false]

        # Adapt the bias
        delta = h == b ? delta / DAMP : delta >> 1
        delta += delta / (h + 1)
        bias = 0
        while delta > CUTOFF
          delta /= LOBASE
          bias += BASE
        end
        bias += (LOBASE + 1) * delta / (delta + SKEW)

        delta = 0
        h += 1
      end
    }

    delta += 1
    n += 1
  end

  output
end