Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9963b85

Browse files
tniessentargos
authored andcommittedSep 16, 2022
src: simplify and optimize GetOpenSSLVersion()
The previous implementation was typically compiled to a fair amount of code even though all inputs are available at compile time. The fact that GetOpenSSLVersion() returns a std::string and used an uninitialized buffer with snprintf made it impossible to make GetOpenSSLVersion() a constexpr, and compilers would typically emit code to dynamically construct the resulting string. The simplified implementation usually boils down to a few mov instructions. (Ideally, this function could be a constexpr returning a std::string_view, but that does not have any advantage in the current design of node::Metadata::Versions which stores versions as std::string instances.) Also make the function static since it is not in an anonymous namespace and change the argument types and the return type of search() to types that are more appropriate, semantically. (The use of snprintf previously made this difficult.) Lastly, make the n argument of search() optional because the simplified implementation always sets it to 0 except during recursive calls within search() itself. PR-URL: #44395 Reviewed-By: Darshan Sen <[email protected]> Reviewed-By: Shelley Vohr <[email protected]> Reviewed-By: Minwoo Jung <[email protected]>
1 parent 49cd8e4 commit 9963b85

File tree

1 file changed

+6
-11
lines changed

1 file changed

+6
-11
lines changed
 

‎src/node_metadata.cc

+6-11
Original file line numberDiff line numberDiff line change
@@ -32,21 +32,16 @@ Metadata metadata;
3232
}
3333

3434
#if HAVE_OPENSSL
35-
constexpr int search(const char* s, int n, int c) {
36-
return *s == c ? n : search(s + 1, n + 1, c);
35+
static constexpr size_t search(const char* s, char c, size_t n = 0) {
36+
return *s == c ? n : search(s + 1, c, n + 1);
3737
}
3838

39-
std::string GetOpenSSLVersion() {
39+
static inline std::string GetOpenSSLVersion() {
4040
// sample openssl version string format
4141
// for reference: "OpenSSL 1.1.0i 14 Aug 2018"
42-
char buf[128];
43-
const char* etext = OPENSSL_VERSION_TEXT;
44-
const int start = search(etext, 0, ' ') + 1;
45-
etext += start;
46-
const int end = search(etext, start, ' ');
47-
const int len = end - start;
48-
snprintf(buf, sizeof(buf), "%.*s", len, &OPENSSL_VERSION_TEXT[start]);
49-
return std::string(buf);
42+
constexpr size_t start = search(OPENSSL_VERSION_TEXT, ' ') + 1;
43+
constexpr size_t len = search(&OPENSSL_VERSION_TEXT[start], ' ');
44+
return std::string(OPENSSL_VERSION_TEXT, start, len);
5045
}
5146
#endif // HAVE_OPENSSL
5247

0 commit comments

Comments
 (0)
Please sign in to comment.