exercism / elixir-analyzer

GNU Affero General Public License v3.0
30 stars 32 forks source link

Analysis of File Sniffer #304

Closed snowfrogdev closed 2 years ago

snowfrogdev commented 2 years ago

Here is my solution:

defmodule FileSniffer do
  def type_from_extension(extension) do
    case extension do
      "exe" -> "application/octet-stream"
      "bmp" -> "image/bmp"
      "png" -> "image/png"
      "jpg" -> "image/jpg"
      "gif" -> "image/gif"
    end
  end

  def type_from_binary(<<0x7F, 0x45, 0x4C, 0x46, _rest::binary>>), do: "exe" |> type_from_extension
  def type_from_binary(<<0x42, 0x4D, _rest::binary>>), do: "bmp" |> type_from_extension
  def type_from_binary(<<0x89, 0x50, 0x4E, 0x47, _rest::binary>>), do: "png" |> type_from_extension
  def type_from_binary(<<0xFF, 0xD8, 0xFF, _rest::binary>>), do: "jpg" |> type_from_extension
  def type_from_binary(<<0x47, 0x49, 0x46, _rest::binary>>), do: "gif" |> type_from_extension

def verify(file_binary, extension) do
    type = extension |> type_from_extension
    if type === file_binary |> type_from_binary do
      {:ok, type}
    else
      {:error, "Warning, file format and file extension do not match."}
    end
  end
end

And here is the message I get from the analyzer:

Even though there could be other valid ways to solve this exercise, for the sake of mastering bitstrings please match the first few bytes of the argument of type_from_binary/1 with the special form <<>>.

It seems to me like that is exactly what I'm doing.

Lgdev07 commented 2 years ago

Hey @snowfrogdev

The problem is with your input on the png type.

Your input is

<<0x89, 0x50, 0x4E, 0x47, _rest::binary>>

But the analyser expects at least these hexadecimals

<<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A>>

You can see the test here: https://github.com/exercism/elixir-analyzer/blob/706843e21384efc6c2842dc6213d885d9d0ba63b/lib/elixir_analyzer/test_suite/file_sniffer.ex#L33

snowfrogdev commented 2 years ago

Yeah, I cheated there, for formatting purposes. I figured I didn't need all of it to pass the exercise tests. 😁 So maybe we should modify the exercise tests so that they fail if the entire set of hexadecimals is not used?

Lgdev07 commented 2 years ago

Ah, that makes sense, the problem is in the tests, I will take a look :smile:

angelikatyborska commented 2 years ago

Resolved in https://github.com/exercism/elixir/pull/1155