Sha256: 8772624ef4dbacb3ef025ad1defc762b462208f06fddde3c69b2a96801e4bb32

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

require "hanami/router/node"

module Hanami
  class Router
    # Trie data structure to store routes
    #
    # @api private
    # @since 2.0.0
    class Trie
      # @api private
      # @since 2.0.0
      attr_reader :root

      # @api private
      # @since 2.0.0
      def initialize
        @root = Node.new
      end

      # @api private
      # @since 2.0.0
      def add(route, to, constraints)
        segments = segments_from(route)
        node = @root

        segments.each do |segment|
          node = node.put(segment)
        end

        node.leaf!(route, to, constraints)
      end

      # @api private
      # @since 2.0.0
      def find(path)
        segments = segments_from(path)
        node = @root

        return unless segments.all? { |segment| node = node.get(segment) }

        node.match(path)&.then { |found| [found.to, found.params] }
      end

      private

      # @api private
      # @since 2.0.0
      SEGMENT_SEPARATOR = /\//
      private_constant :SEGMENT_SEPARATOR

      # @api private
      # @since 2.2.0
      def segments_from(path)
        _, *segments = path.split(SEGMENT_SEPARATOR)

        segments
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hanami-router-2.2.0 lib/hanami/router/trie.rb