Conversation
|
Though of course rust-lang/const-eval#20 would make this much, much easier! |
Will be used at some point when generic constants are available, see #70
94ae38d to
05658b2
Compare
Will be used at some point when generic constants are available, see #70
1f7f189 to
2ae705f
Compare
&'static str from Encoding&'static str from Encoding
fdce3e9 to
bb0e66b
Compare
bb0e66b to
9c31a41
Compare
|
I tried with a design like: trait Encode {
// ...
#[doc(hidden)]
const __ENCODING_CSTR_LEN: usize = Self::ENCODING.static_encoding_str_len();
#[doc(hidden)]
const __ENCODING_CSTR_ARRAY: [u8; 128] = {
if Self::__ENCODING_CSTR_LEN >= 127 {
panic!("encoding string was too long! The maximum supported length is 127.");
}
Self::ENCODING.static_encoding_str_array()
};
/// The encoding as a static [`CStr`].
///
/// This has the same output as `Encoding::to_string`, but it is created
/// at compile-time instead.
///
/// The encoding is guaranteed to be a pure ASCII string.
#[cfg(feature = "std")]
const ENCODING_CSTR: &'static CStr = {
let mut slice: &[u8] = &Self::__ENCODING_CSTR_ARRAY;
// Cut down to desired size (length + 1 for NUL byte)
// Equivalent to:
// slice[0..Self::__ENCODING_CSTR_LEN + 1]
while slice.len() > Self::__ENCODING_CSTR_LEN + 1 {
if let Some(res) = slice.split_last() {
slice = res.1;
} else {
unreachable!();
}
}
unsafe { CStr::from_bytes_with_nul_unchecked(slice) }
};
}The idea being that hopefully, the compiler would be able to see that the rest of That doesn't seem to work though, the entire |
&'static str from Encoding&'static CStr from Encoding
9c31a41 to
c1b7666
Compare
|
I've gone with a different approach in this PR now: generate the static method encodings only inside A fully generic solution still requires |
Add `Encoding::str_len` and `Encoding::str_array`. Will probably be needed in this form, regardless of whether `generic_const_exprs` ever lands.
For optimization, and as a first step towards #604
c1b7666 to
ace5af3
Compare
Idea is that we generate an array in a
const fn, and then get a reference to that array and put it in aconst.Requires rust-lang/rust#76560.
Another approach would be to require
Encodeimplementors to add a macro to the end, like this: