MatN work for versatile appimage creation for all types of os
[goodguy/cinelerra.git] / cinelerra-5.1 / tools / makeappimagetool / includes / desktopfile_util.h
1 #pragma once
2
3 // system headers
4 #include <algorithm>
5 #include <string>
6
7 // local headers
8 #include "desktopfile_exceptions.h"
9
10 namespace linuxdeploy {
11     namespace desktopfile {
12         /**
13          * Remove leading characters from string.
14          * @param s string to edit
15          * @param to_trim character to remove
16          */
17         static inline bool ltrim(std::string& s, char to_trim = ' ') {
18             // TODO: find more efficient way to check whether elements have been removed
19             size_t initialLength = s.length();
20             s.erase(s.begin(), std::find_if(s.begin(), s.end(), [to_trim](int ch) {
21                 return ch != to_trim;
22             }));
23             return s.length() < initialLength;
24         }
25
26         /**
27          * Remove trailing characters from string.
28          * @param s string to edit
29          * @param to_trim character to remove
30          */
31         static inline bool rtrim(std::string& s, char to_trim = ' ') {
32             // TODO: find more efficient way to check whether elements have been removed
33             auto initialLength = s.length();
34             s.erase(std::find_if(s.rbegin(), s.rend(), [to_trim](int ch) {
35                 return ch != to_trim;
36             }).base(), s.end());
37             return s.length() < initialLength;
38         }
39
40         /**
41          * Remove leading and trailing characters from string.
42          * @param s string to edit
43          * @param to_trim character to remove
44          */
45         static inline bool trim(std::string& s, char to_trim = ' ') {
46             // returns true if either modifies s
47             auto ltrim_result = ltrim(s, to_trim);
48             return rtrim(s, to_trim) && ltrim_result;
49         }
50
51         /**
52          * Relatively inefficient implementation of a C++ lexical cast.
53          * @tparam To type to convert to
54          * @tparam From input parameter type
55          * @param from value to convert
56          * @return converted value
57          * @throws BadLexicalCastError in case a type conversion is not possible
58          */
59         template<typename To, typename From>
60         To lexicalCast(From from) {
61             To to;
62
63             std::stringstream ss;
64             ss << from;
65
66             if (ss.fail())
67                 throw BadLexicalCastError();
68
69             ss >> to;
70
71             if (ss.fail())
72                 throw BadLexicalCastError();
73
74             return to;
75         }
76     }
77 }