Module: LZString::Base64
- Included in:
- LZString
- Defined in:
- lib/lzstring/base64.rb
Overview
Module for base64 encoding/decoding
Class Method Summary collapse
-
.compress_to_base64(input) ⇒ String
Compress a string to base64 encoding.
-
.decompress_from_base64(input) ⇒ String?
Decompress a string from base64 encoding.
-
.get_base_value(alphabet, character) ⇒ Integer
Get base value for a character using lookup string.
-
.key_str_base64 ⇒ Object
Map of Base64 characters for compression.
Class Method Details
.compress_to_base64(input) ⇒ String
Compress a string to base64 encoding
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 32 33 34 35 |
# File 'lib/lzstring/base64.rb', line 7 def self.compress_to_base64(input) return "" if input.nil? || input.empty? begin # Force input to UTF-8 encoding input = input.to_s.dup.force_encoding(Encoding::UTF_8) # Use the _compress function with Base64 parameters result = LZString._compress(input, 6) do |a| key_str_base64[a % key_str_base64.length] end # Handle padding for Base64 case result.length % 4 when 0 result when 1 "#{result}===" when 2 "#{result}==" when 3 "#{result}=" end rescue # Log error and return empty string on failure # STDERR.puts "Base64 compression error: #{e.message}" "" end end |
.decompress_from_base64(input) ⇒ String?
Decompress a string from base64 encoding
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/lzstring/base64.rb', line 40 def self.decompress_from_base64(input) return "" if input.nil? || input.empty? begin # Ensure input is properly encoded input = input.to_s.dup.force_encoding(Encoding::UTF_8) # Use the _decompress function with Base64 parameters result = LZString._decompress(input.length, 32) do |index| if index >= input.length 0 else get_base_value(key_str_base64, input[index]) end end # Ensure proper UTF-8 encoding of the result if result.is_a?(String) # Force UTF-8 encoding and replace invalid bytes result.force_encoding(Encoding::UTF_8) # Check if the result is valid UTF-8, if not try to repair unless result.valid_encoding? # Replace invalid sequences with a replacement character result = result.encode(Encoding::UTF_8, Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "?") end end result rescue # Log error and return nil on failure # STDERR.puts "Base64 decompression error: #{e.message}" nil end end |
.get_base_value(alphabet, character) ⇒ Integer
Get base value for a character using lookup string
89 90 91 |
# File 'lib/lzstring/base64.rb', line 89 def self.get_base_value(alphabet, character) alphabet.index(character) || 0 end |
.key_str_base64 ⇒ Object
Map of Base64 characters for compression
81 82 83 |
# File 'lib/lzstring/base64.rb', line 81 def self.key_str_base64 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" end |