Skip to content

Commit 674a87c

Browse files
authored
make version a static
1 parent 32a8b78 commit 674a87c

File tree

2 files changed

+28
-24
lines changed

2 files changed

+28
-24
lines changed

sdk/cosmos/cosmosclient/src/lib.rs

Lines changed: 7 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,17 @@
33

44
use std::ffi::{c_char, CStr, CString};
55

6+
#[macro_use]
7+
mod macros;
8+
69
#[no_mangle] // Necessary to prevent the compiler from stripping it when optimizing
710
/// cbindgen:ignore
8-
pub static BUILD_IDENTIFIER: &CStr = const {
9-
// This does a few funky things to make sure we can stay in a const context
10-
// Which ensures the string is generated as a c-str at compile time
11-
// and thus appears properly if you run `strings [lib] | grep "\$Id:"`
12-
const BUILD_IDENTIFIER_STR: &str = env!("BUILD_IDENTIFIER");
13-
const BUILD_IDENTIFIER_BYTES: [u8; BUILD_IDENTIFIER_STR.len() + 1] = const {
14-
let mut cstrbuf: [u8; BUILD_IDENTIFIER_STR.len() + 1] = [0; BUILD_IDENTIFIER_STR.len() + 1];
15-
let mut i = 0;
16-
// For loops over ranges don't really work in const contexts.
17-
while i < BUILD_IDENTIFIER_STR.len() {
18-
cstrbuf[i] = BUILD_IDENTIFIER_STR.as_bytes()[i];
19-
i += 1;
20-
}
21-
cstrbuf
22-
};
23-
match CStr::from_bytes_with_nul(&BUILD_IDENTIFIER_BYTES) {
24-
Ok(cstr) => cstr,
25-
Err(_) => panic!("BUILD_IDENTIFIER is not a valid C string"),
26-
}
27-
};
11+
pub static BUILD_IDENTIFIER: &CStr = c_str!(env!("BUILD_IDENTIFIER"));
12+
13+
const VERSION: &CStr = c_str!(env!("CARGO_PKG_VERSION"));
2814

2915
#[no_mangle]
3016
/// Returns a constant C string containing the version of the Cosmos Client library.
3117
pub extern "C" fn cosmosclient_version() -> *const c_char {
32-
let version = env!("CARGO_PKG_VERSION");
33-
CString::new(version)
34-
.expect("failed to create CString from version")
35-
.into_raw()
18+
VERSION.as_ptr()
3619
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
macro_rules! c_str {
2+
($s:expr) => { const {
3+
// This does a few funky things to make sure we can stay in a const context
4+
// Which ensures the string is generated as a c-str at compile time
5+
const STR: &str = $s
6+
const BYTES: [u8; STR.len() + 1] = const {
7+
let mut cstrbuf: [u8; STR.len() + 1] = [0; STR.len() + 1];
8+
let mut i = 0;
9+
// For loops over ranges don't really work in const contexts.
10+
while i < STR.len() {
11+
cstrbuf[i] = STR.as_bytes()[i];
12+
i += 1;
13+
}
14+
cstrbuf
15+
};
16+
match CStr::from_bytes_with_nul(&BYTES) {
17+
Ok(cstr) => cstr,
18+
Err(_) => panic!("failed to convert value to C string"),
19+
}
20+
} },
21+
}

0 commit comments

Comments
 (0)