diff --git a/labs/05/card/.formatter.exs b/labs/05/card/.formatter.exs new file mode 100644 index 0000000..d2cda26 --- /dev/null +++ b/labs/05/card/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/labs/05/card/.gitignore b/labs/05/card/.gitignore new file mode 100644 index 0000000..ff119b6 --- /dev/null +++ b/labs/05/card/.gitignore @@ -0,0 +1,26 @@ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where third-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +card-*.tar + +# Temporary files, for example, from tests. +/tmp/ diff --git a/labs/05/card/README.md b/labs/05/card/README.md new file mode 100644 index 0000000..4f4836e --- /dev/null +++ b/labs/05/card/README.md @@ -0,0 +1,21 @@ +# Card + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `card` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [ + {:card, "~> 0.1.0"} + ] +end +``` + +Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) +and published on [HexDocs](https://hexdocs.pm). Once published, the docs can +be found at . + diff --git a/labs/05/card/lib/card/application.ex b/labs/05/card/lib/card/application.ex new file mode 100644 index 0000000..69f2982 --- /dev/null +++ b/labs/05/card/lib/card/application.ex @@ -0,0 +1,22 @@ +defmodule Card.Application do + @moduledoc false + + @registry Card.Registry + @table Card.Table + + use Application + + @impl true + def start(_type, _args) do + children = [ + {Registry, name: @registry, keys: :unique}, + {PartitionSupervisor, + name: Card.DynamicSupervisors, partitions: 4, child_spec: Card.DynamicSupervisor} + ] + + :ets.new(@table, [:named_table, :public]) + + opts = [strategy: :one_for_one, name: Card.Supervisor] + Supervisor.start_link(children, opts) + end +end diff --git a/labs/05/card/lib/card/dynamic_supervisor.ex b/labs/05/card/lib/card/dynamic_supervisor.ex new file mode 100644 index 0000000..5696896 --- /dev/null +++ b/labs/05/card/lib/card/dynamic_supervisor.ex @@ -0,0 +1,20 @@ +defmodule Card.DynamicSupervisor do + use DynamicSupervisor + + def start_link(_) do + DynamicSupervisor.start_link(__MODULE__, nil) + end + + def start_worker(name) do + DynamicSupervisor.start_child( + {:via, PartitionSupervisor, {Card.DynamicSupervisors, self()}}, + {Card.Worker, name} + ) + end + + @impl true + def init(_) do + IO.puts("Card.DynamicSupervisor started/re-started with pid #{inspect(self())}") + DynamicSupervisor.init(strategy: :one_for_one) + end +end diff --git a/labs/05/card/lib/card/worker.ex b/labs/05/card/lib/card/worker.ex new file mode 100644 index 0000000..ab02880 --- /dev/null +++ b/labs/05/card/lib/card/worker.ex @@ -0,0 +1,97 @@ +defmodule Card.Worker do + use GenServer + + @registry Card.Registry + @table Card.Table + + ### Client API ### + def start_link(name) do + GenServer.start_link(__MODULE__, name, name: via(name)) + end + + def new(name) do + GenServer.cast(via(name), :new) + end + + def shuffle(name) do + GenServer.cast(via(name), :shuffle) + end + + def count(name) do + GenServer.call(via(name), :count) + end + + def deal(name, n \\ 1) do + GenServer.call(via(name), {:deal, n}) + end + + # wrap the name in a triple to use the Registry to get the + # process ID by name + defp via(name) do + {:via, Registry, {@registry, {__MODULE__, name}}} + end + + ### Server Impl ### + defp fresh() do + values = Enum.map(2..10, &Integer.to_string/1) ++ ["J", "Q", "K", "A"] + suits = ["♣", "♦", "♥", "♠"] + + for v <- values, f <- suits, do: v <> f + end + + @impl true + def init(arg) do + key = {__MODULE__, arg} + + deck = + case :ets.lookup(@table, key) do + [] -> fresh() + [{_, d}] -> d + end + + IO.puts("Card.Worker #{inspect(arg)} started/re-started with pid #{inspect(self())}") + {:ok, {key, deck}} + end + + @impl true + def handle_cast(:new, {key, _deck}) do + # {:noreply, new_state} + {:noreply, {key, fresh()}} + end + + @impl true + def handle_cast(:shuffle, {key, deck}) do + # {:noreply, new_state} + {:noreply, {key, Enum.shuffle(deck)}} + end + + @impl true + def handle_call(:count, _from, {_key, deck} = state) do + # {:reply, actual_reply, new_state} + {:reply, length(deck), state} + end + + @impl true + def handle_call({:deal, n}, _from, {key, deck}) when is_integer(n) do + case n do + _ when n < 0 -> + # {:reply, actual_reply, new_state} + {:reply, {:error, "Cannot deal negative number of cards"}, {key, deck}} + + _ when n > length(deck) -> + # {:reply, actual_reply, new_state} + {:reply, {:error, "Insufficient cards in deck to deal"}, {key, deck}} + + _ -> + {d, r} = Enum.split(deck, n) + # {:reply, actual_reply, new_state} + {:reply, {:ok, d}, {key, r}} + end + end + + # save state to the term table so a restart can recover it + @impl true + def terminate(_reason, state) do + :ets.insert(@table, state) + end +end diff --git a/labs/05/card/mix.exs b/labs/05/card/mix.exs new file mode 100644 index 0000000..3626383 --- /dev/null +++ b/labs/05/card/mix.exs @@ -0,0 +1,29 @@ +defmodule Card.MixProject do + use Mix.Project + + def project do + [ + app: :card, + version: "0.1.0", + elixir: "~> 1.17", + start_permanent: Mix.env() == :prod, + deps: deps() + ] + end + + # Run "mix help compile.app" to learn about applications. + def application do + [ + extra_applications: [:logger], + mod: {Card.Application, []} + ] + end + + # Run "mix help deps" to learn about dependencies. + defp deps do + [ + # {:dep_from_hexpm, "~> 0.3.0"}, + # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} + ] + end +end diff --git a/labs/05/card/test/test_helper.exs b/labs/05/card/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/labs/05/card/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start()