# File lib/rack/utils/okjson.rb, line 451
  def strenc(s)
    t = StringIO.new
    t.putc(?")
    r = 0

    # In ruby >= 1.9, s[r] is a codepoint, not a byte.
    rubydoesenc = s.class.method_defined?(:encoding)

    while r < s.length
      case s[r]
      when ?"  then t.print('\\"')
      when ?\\ then t.print('\\\\')
      when ?\b then t.print('\\b')
      when ?\f then t.print('\\f')
      when ?\n then t.print('\\n')
      when ?\r then t.print('\\r')
      when ?\t then t.print('\\t')
      else
        c = s[r]
        case true
        when rubydoesenc
          begin
            c.ord # will raise an error if c is invalid UTF-8
            t.write(c)
          rescue
            t.write(Ustrerr)
          end
        when Spc <= c && c <= ?~
          t.putc(c)
        else
          n = ucharcopy(t, s, r) # ensure valid UTF-8 output
          r += n - 1 # r is incremented below
        end
      end
      r += 1
    end
    t.putc(?")
    t.string
  end