Skip to content

Commit

Permalink
src: simplify and optimize GetOpenSSLVersion()
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
tniessen authored and juanarbol committed Oct 10, 2022
1 parent dd55299 commit 354fdb4
Showing 1 changed file with 6 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/node_metadata.cc
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,16 @@ Metadata metadata;
}

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

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

Expand Down

0 comments on commit 354fdb4

Please sign in to comment.