55 lines
1.7 KiB
Clojure
55 lines
1.7 KiB
Clojure
(ns cipher-analytical-machine.parsers.simple-substitution
|
|
(:require
|
|
[cipher-analytical-machine.ciphers.simple-substitution :as ss]
|
|
[cipher-analytical-machine.parsers.parsers :as ps]
|
|
[clojure.set :as set]
|
|
[cheshire.core :as cc])
|
|
(:gen-class))
|
|
|
|
(defn encode-key-and-substitution-table-to-json
|
|
[key substitution-table]
|
|
(-> {"key" key}
|
|
(assoc "table" substitution-table)
|
|
(cc/generate-string)))
|
|
|
|
(defn decode-key
|
|
"Returns the first character if the string is a char. Return the number if the string is a number."
|
|
[str]
|
|
(if (ps/unsigned-int? str)
|
|
(Integer/parseInt str)
|
|
(first str)))
|
|
|
|
(defn decode-pair
|
|
"Decode a numbers as a string and a char as a string"
|
|
[acc [key value]]
|
|
(if (ps/unsigned-int? key)
|
|
(assoc acc (decode-key key) (decode-key value))
|
|
(assoc acc (decode-key key) value)))
|
|
|
|
(defn decode-substitution-table
|
|
[substitution-table-map-from-json]
|
|
(reduce decode-pair {} substitution-table-map-from-json))
|
|
|
|
(defn decode-key-and-substitution-table-from-json
|
|
[json]
|
|
(let [data (cc/parse-string json)]
|
|
(assoc data "table" (decode-substitution-table (get data "table")))))
|
|
|
|
(defn generate-table-or-decode-json
|
|
"It generate the table and return map with the key and the table if the argument is a key. Else it decode the json."
|
|
[key-or-json symbols]
|
|
(if (ps/unsigned-int? key-or-json)
|
|
(-> {"key" key-or-json}
|
|
(assoc "table" (ss/generate-substitution-table symbols)))
|
|
(decode-key-and-substitution-table-from-json key-or-json)))
|
|
|
|
(defn invert-table-in-map
|
|
"Invert the table in a decoded json (key, table)"
|
|
[decoded-json]
|
|
(->>
|
|
(-> decoded-json
|
|
(get "table")
|
|
(set/map-invert))
|
|
(assoc decoded-json "table")))
|
|
|