# frozen_string_literal: true

# This file is part of RASN1
# See https://codeberg.org/lemontree55/rasn1 for more informations
# Copyright (C) 2016-2024 Sylvain Daubert <sylvain.daubert@laposte.net>
# Copyright (C) 2024 LemonTree55 <lenontree@proton.me>
# This program is published under MIT license.

module RASN1
  module Types
    # ASN.1 Printable String
    #
    # A PRINTABLE STRING is an {OctetString} limited to printable characters from ASCII table.
    # @author Sylvain Daubert
    # @author LemonTree55
    class PrintableString < OctetString
      # PrintableString id value
      ID = 19
      # Invalid characters in PrintableString
      INVALID_CHARS = %r{([^a-zA-Z0-9 '=()+,\-./:?])}

      # Get ASN.1 type
      # @return [String]
      def self.type
        'PrintableString'
      end

      # Make string value from +der+ string
      # @param der [String]
      # @param ber [::Boolean]
      # @return [void]
      # @raise [ASN1Error] invalid characters detected
      def der_to_value(der, ber: false)
        super
        check_characters
      end

      private

      # @return [String]
      # @raise [ASN1Error] invalid character in string
      def value_to_der
        check_characters
        @value.to_s.b
      end

      # @return [void]
      # @raise [ASN1Error] invalid character in string
      def check_characters
        m = @value.to_s.match(INVALID_CHARS)
        raise ASN1Error, "PRINTABLE STRING #{@name}: invalid character: '#{m[1]}'" if m
      end
    end
  end
end
