The short answer is that you can't. CqlString
contains a reference to other data, but FromStr
expects to create a fully-owned object that no longer needs to reference the &str
. These two concepts are incompatible.
The closest I can see is that you could create an OwnedCqlString
:
struct OwnedCqlString {
data: Vec<u8>,
}
impl OwnedCqlString {
fn as_cql_string(&self) -> CqlString { CqlString(self.data.as_slice()) }
}
impl FromStr for OwnedCqlString {
fn from_str(s: &str) -> Option<OwnedCqlString> {
// logic here
}
}
fn main() {
let ocs: OwnedCqlString = "hello".parse();
let cs = ocs.as_cql_string();
}
Ultimately, this comes down to two questions:
- Where are you going to store the bytes that represent the size?
- How do you ensure that those bytes immediately precede the string data in memory?
An alternate idea
If you didn't need to store the slice of bytes, but instead could have a "streaming" interface, then you could implement that directly on &str
:
trait WriteCqlStr {
fn write_to<W>(&self, &mut W)
where W: Writer;
}
impl WriteCqlStr for CqlStr {
// Straight-forward impl, write the bytes we refer to
}
impl<'a> WriteCqlStr for &'a str {
// Write the length, then write the bytes of the str
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…