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

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

        input.each { |cp|
          # AMC-ACE-Z can use this simplified version instead
          if cp < n && (delta += 1) == 0
            raise BufferOverflowError
          end

          if 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
              output << encode_digit(t + (q - t) % (BASE - t), false)
              q = (q - t) / (BASE - t)
              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