Euphoria
cypher.cc
Go to the documentation of this file.
1 #include "core/cypher.h"
2 
3 #include "assert/assert.h"
4 
5 #include "base/stringutils.h"
6 #include "base/range.h"
7 #include "base/stringbuilder.h"
8 
9 
10 
11 namespace eu::core
12 {
13 
14 
15 std::string
17 (
18  const std::string& input,
19  int steps,
20  const std::string& alphabet,
21  bool case_sensitive,
22  ActionWhenMissingInAlphabet missing_in_alphabet,
23  char invalid
24 )
25 {
26  ASSERT(steps > 0); // todo(Gustav): add support for negative steps
27  const auto alph = case_sensitive ? alphabet : to_lower(alphabet);
28  auto ret = StringBuilder{};
29 
30  for(const auto c: input)
31  {
32  const bool is_upper = c >= 'A' && c <= 'Z';
33  const auto fc = case_sensitive ? c : to_lower_char(c);
34 
35  const auto index = alph.find(fc);
36  if(index != std::string::npos)
37  {
38  const auto new_index = (static_cast<int>(index) + steps) % static_cast<int>(alph.size());
39  const auto new_char = alph[new_index];
40  const auto transformed_char = case_sensitive == false && is_upper
41  ? to_upper_char(new_char) : new_char;
42  ret.add_char(transformed_char);
43  }
44  else
45  {
46  switch(missing_in_alphabet)
47  {
49  continue;
51  ret.add_char(c);
52  break;
54  ret.add_char(invalid);
55  break;
56  default:
57  DIE("Unhandled case");
58  }
59  }
60  }
61 
62  return ret.to_string();
63 }
64 
65 
66 std::string get_rot13(const std::string& input)
67 {
68  return get_ceasar_cypher(input, 13, "abcdefghijklmnopqrstuvwxyz", false, ActionWhenMissingInAlphabet::pass_through, '?');
69 }
70 
71 
72 }
#define ASSERT(x)
Definition: assert.h:29
#define DIE(message)
Definition: assert.h:67
std::string to_lower(const std::string &str)
Generate a string containing only lower characters.
Definition: stringutils.cc:143
char to_upper_char(char b)
Definition: stringutils.cc:129
char to_lower_char(char b)
Definition: stringutils.cc:116
std::string get_ceasar_cypher(const std::string &input, int steps, const std::string &alphabet, bool case_sensitive, ActionWhenMissingInAlphabet missing_in_alphabet, char invalid)
Definition: cypher.cc:17
std::string get_rot13(const std::string &input)
Definition: cypher.cc:66
ActionWhenMissingInAlphabet
Definition: cypher.h:11
String utility functions.