File: key_regularizer.rb

package info (click to toggle)
ruby-dalli 3.2.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 684 kB
  • sloc: ruby: 6,552; sh: 20; makefile: 4
file content (31 lines) | stat: -rw-r--r-- 965 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
# frozen_string_literal: true

module Dalli
  module Protocol
    class Meta
      ##
      # The meta protocol requires that keys be ASCII only, so Unicode keys are
      # not supported.  In addition, the use of whitespace in the key is not
      # allowed.
      # memcached supports the use of base64 hashes for keys containing
      # whitespace or non-ASCII characters, provided the 'b' flag is included in the request.
      class KeyRegularizer
        WHITESPACE = /\s/.freeze

        def self.encode(key)
          return [key, false] if key.ascii_only? && !WHITESPACE.match(key)

          strict_base64_encoded = [key].pack('m0')
          [strict_base64_encoded, true]
        end

        def self.decode(encoded_key, base64_encoded)
          return encoded_key unless base64_encoded

          strict_base64_decoded = encoded_key.unpack1('m0')
          strict_base64_decoded.force_encoding(Encoding::UTF_8)
        end
      end
    end
  end
end