# 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 Numeric String
    #
    # A NUMERIC STRING is an {OctetString} limited to numeric digit.
    # @example Numeric string
    #   ns = RASN1::Types::NumrericString.new(value: "123")
    #   ns.to_der                     #=> "\x12\x03123"
    #   RASN1.parse(ns.to_der).value  #=> "123"
    # @author Sylvain Daubert
    # @author LemonTree55
    class NumericString < OctetString
      # NumericString id value
      ID = 18
      # Invalid characters in NumericString
      INVALID_CHARS = /([^0-9 ])/

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

      # Make string value from +der+ string
      # @param der [String]
      # @param ber [::Boolean]
      # @return [void]
      # @raise [ASN1Error] invalid characters detected
      # @raise [ASN1Error] invalid character in string
      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
        raise ASN1Error, "NUMERIC STRING #{@name}: invalid character: '#{$1}'" if @value.to_s =~ INVALID_CHARS
      end
    end
  end
end
