Sha256: 6b973bed99150527ccb2e1b64118e5ea1a53fa8ed97224b9d3fd4ed741451bb4

Contents?: true

Size: 710 Bytes

Versions: 5

Compression:

Stored size: 710 Bytes

Contents

module Fontist
  module Utils
    class FileMagic
      MAP_MAGIC_TO_TYPE = {
        "\x00\x01\x00\x00\x00" => :ttf,
        "\x4f\x54\x54\x4f" => :otf,
        "\x74\x74\x63\x66" => :ttc,
      }.freeze

      def self.detect(path)
        new(path).detect
      end

      def self.max_magic
        @max_magic ||= MAP_MAGIC_TO_TYPE.keys.map(&:bytesize).max
      end

      def initialize(path)
        @path = path
      end

      def detect
        beginning = File.binread(@path, self.class.max_magic)

        MAP_MAGIC_TO_TYPE.each do |magic, type|
          slice = beginning.byteslice(0, magic.bytesize)

          return type if slice == magic
        end

        nil
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
fontist-1.21.2 lib/fontist/utils/file_magic.rb
fontist-1.21.1 lib/fontist/utils/file_magic.rb
fontist-1.20.0 lib/fontist/utils/file_magic.rb
fontist-1.19.0 lib/fontist/utils/file_magic.rb
fontist-1.18.2 lib/fontist/utils/file_magic.rb