75 lines
1.9 KiB
C++
75 lines
1.9 KiB
C++
#include "star_code.h"
|
|
|
|
#include <vector>
|
|
#include <algorithm>
|
|
#include <string.h>
|
|
#include <stdint.h>
|
|
|
|
static std::vector<StarCodeEntry> star_codes;
|
|
|
|
/// Checks if a triggered code matches an expected code.
|
|
/// @return true iff the codes match, where '*'s in the expected code can match any character in the triggered code
|
|
static bool check_code_match(const char* triggered, const char* expected) {
|
|
size_t triggered_len = strlen(triggered);
|
|
size_t match_len = strlen(triggered);
|
|
|
|
if (triggered_len != match_len)
|
|
return false;
|
|
|
|
for (int i = 0; i < triggered_len; i++) {
|
|
if (!(expected[i] == '*' || expected[i] == triggered[i])) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool add_star_code(StarCodeEntry code) {
|
|
if (code.code == nullptr || strlen(code.code) > 8) {
|
|
return false;
|
|
}
|
|
if (code.display_text != nullptr && strlen(code.display_text) > 9) {
|
|
return false;
|
|
}
|
|
|
|
// check for a existing entry
|
|
auto it = std::find_if(star_codes.begin(), star_codes.end(), [&](const StarCodeEntry& other) {
|
|
return check_code_match(code.code, other.code);
|
|
});
|
|
|
|
if (it != star_codes.end()) {
|
|
// existing star code found!
|
|
return false;
|
|
}
|
|
|
|
star_codes.push_back(code);
|
|
return true;
|
|
}
|
|
|
|
bool rm_star_code(char* code){
|
|
auto it = std::find_if(star_codes.begin(), star_codes.end(), [&](const StarCodeEntry& star_code) {
|
|
return strcmp(code, star_code.code) == 0;
|
|
});
|
|
|
|
if (it == star_codes.end()) {
|
|
return false;
|
|
}
|
|
|
|
star_codes.erase(it);
|
|
return true;
|
|
}
|
|
|
|
bool trigger_star_code(char* code) {
|
|
auto it = std::find_if(star_codes.begin(), star_codes.end(), [&](const StarCodeEntry& other) {
|
|
return check_code_match(code, other.code);
|
|
});
|
|
|
|
if (it == star_codes.end()) {
|
|
return false;
|
|
}
|
|
|
|
(it->callback)();
|
|
return true;
|
|
}
|