ArkScript
A small, fast, functional and scripting language for video games
Utils.hpp
Go to the documentation of this file.
1/**
2 * @file Utils.hpp
3 * @author Alexandre Plateau ([email protected])
4 * @brief Lots of utilities about string, filesystem and more
5 * @version 0.3
6 * @date 2020-10-27
7 *
8 * @copyright Copyright (c) 2020-2021
9 *
10 */
11
12#ifndef INCLUDE_ARK_UTILS_HPP
13#define INCLUDE_ARK_UTILS_HPP
14
15#include <algorithm> // std::min
16#include <string>
17#include <iostream>
18#include <fstream>
19#include <vector>
20
21#include <cmath>
22
23#include <Ark/Constants.hpp>
24
25namespace Ark::Utils
26{
27 /**
28 * @brief Cut a string into pieces, given a character separator
29 *
30 * @param source
31 * @param sep
32 * @return std::vector<std::string>
33 */
34 inline std::vector<std::string> splitString(const std::string& source, char sep)
35 {
36 std::vector<std::string> output;
37 output.emplace_back();
38
39 for (char c : source)
40 {
41 if (c != sep)
42 output.back() += c;
43 else
44 output.emplace_back(); // add empty string
45 }
46
47 return output;
48 }
49
50 /**
51 * @brief Checks if a string is a valid double
52 *
53 * @param s the string
54 * @param output optional pointer to the output to avoid 2 conversions
55 * @return true on success
56 * @return false on failure
57 */
58 inline bool isDouble(const std::string& s, double* output = nullptr)
59 {
60 char* end = 0;
61 double val = strtod(s.c_str(), &end);
62 if (output != nullptr)
63 *output = val;
64 return end != s.c_str() && *end == '\0' && val != HUGE_VAL;
65 }
66
67 /**
68 * @brief Count the number of decimals for a double
69 * @todo remove when migrating to libfmt
70 *
71 * @param d
72 * @return int
73 */
74 int decPlaces(double d);
75
76 /**
77 * @brief Count the number of digits for a double
78 * @todo remove when migrating to libfmt
79 *
80 * @param d
81 * @return int
82 */
83 int digPlaces(double d);
84
85 /**
86 * @brief Calculate the Levenshtein distance between two strings
87 *
88 * @param str1
89 * @param str2
90 * @return int
91 */
92 int levenshteinDistance(const std::string& str1, const std::string& str2);
93}
94
95#endif
Constants used by ArkScript.
std::vector< std::string > splitString(const std::string &source, char sep)
Cut a string into pieces, given a character separator.
Definition: Utils.hpp:34
int decPlaces(double d)
Count the number of decimals for a double.
Definition: Utils.cpp:5
int digPlaces(double d)
Count the number of digits for a double.
Definition: Utils.cpp:21
int levenshteinDistance(const std::string &str1, const std::string &str2)
Calculate the Levenshtein distance between two strings.
Definition: Utils.cpp:33
bool isDouble(const std::string &s, double *output=nullptr)
Checks if a string is a valid double.
Definition: Utils.hpp:58