Skip to content

Commit

Permalink
Add module to generate transition tables
Browse files Browse the repository at this point in the history
  • Loading branch information
philipbrown committed Jun 19, 2023
1 parent 3c902aa commit 47218fa
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 268 deletions.
17 changes: 5 additions & 12 deletions lib/nilsimsa.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,14 @@ defmodule Nilsimsa do
|> String.split("<!-- MDOC !-->")
|> Enum.fetch!(1)

use Bitwise, skip_operators: true
import Bitwise

import Enum, only: [at: 2]

@tran3 :nilsimsa
|> Application.app_dir("priv/tran3")
|> File.read!()
|> String.split("\n")
|> Enum.map(&String.to_integer(&1))

@popc :nilsimsa
|> Application.app_dir("priv/popc")
|> File.read!()
|> String.split("\n")
|> Enum.map(&String.to_integer(&1))
alias Nilsimsa.{Hamming, Transition}

@tran3 Transition.generate(53)
@popc Hamming.generate()

@type t :: %__MODULE__{
acc: list(integer()),
Expand Down
43 changes: 43 additions & 0 deletions lib/nilsimsa/transition.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
defmodule Nilsimsa.Transition do
@moduledoc """
A module for generating transition tables.
A transition table provides a deterministic, yet pseudorandom, way of mapping
input bytes to output hash chunks.
"""

import Bitwise

@doc """
Generate a transition table.
iex> Transition.generate(53) |> Enum.take(3)
[2, 214, 158]
"""
def generate(target),
do: build(target, 0, 0, [])

# Private

defp build(_target, 256, _j, tran),
do: Enum.reverse(tran)

defp build(target, i, j, tran) do
j = band(j * target + 1, 255)
j = if j * 2 > 255, do: j * 2 - 255, else: j * 2
j = handle_collision(j, tran, 0)

build(target, i + 1, j, [j | tran])
end

defp handle_collision(j, _tran, 256),
do: j

defp handle_collision(j, tran, i) do
case Enum.at(tran, i) do
^j -> handle_collision(band(j + 1, 255), tran, 0)
_ -> handle_collision(j, tran, i + 1)
end
end
end
256 changes: 0 additions & 256 deletions priv/tran3

This file was deleted.

17 changes: 17 additions & 0 deletions test/nilsimsa/transition_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
defmodule Nilsimsa.TransitionTest do
use ExUnit.Case, async: true

import Bitwise

alias Nilsimsa.Transition

doctest Nilsimsa.Transition

test "should xor to 0" do
[v | rest] = Transition.generate(53)

v = Enum.reduce(rest, v, &bxor(&2, &1))

assert v == 0
end
end

0 comments on commit 47218fa

Please sign in to comment.