feat: implement From<&CStr> for NvimStr (#239)

This commit is contained in:
Riccardo Mazzarini 2025-05-23 12:36:57 +02:00 committed by GitHub
parent 162e56f4a3
commit 3a22a7fba5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,11 +1,16 @@
use core::ffi::{self, CStr};
use core::marker::PhantomData;
use core::str::Utf8Error;
use core::{cmp, ffi, fmt, hash, slice};
use core::{cmp, fmt, hash, slice};
use std::borrow::Cow;
use crate::String as NvimString;
/// TODO: docs.
/// A borrowed version of [`NvimString`].
///
/// Values of this type can be created by calling
/// [`as_nvim_str`](NvimString::as_nvim_str) on a [`NvimString`] or by
/// converting a [`CStr`].
#[derive(Copy, Clone)]
#[repr(C)]
pub struct NvimStr<'a> {
@ -146,6 +151,13 @@ impl PartialEq for NvimStr<'_> {
}
}
impl PartialEq<&str> for NvimStr<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl Eq for NvimStr<'_> {}
impl PartialOrd for NvimStr<'_> {
@ -168,3 +180,33 @@ impl<'a> From<&'a NvimString> for NvimStr<'a> {
string.as_nvim_str()
}
}
impl<'a> From<&'a CStr> for NvimStr<'a> {
#[inline]
fn from(cstr: &'a CStr) -> Self {
Self {
data: cstr.as_ptr(),
len: cstr.to_bytes().len(),
_lifetime: PhantomData,
}
}
}
impl PartialEq<NvimStr<'_>> for &str {
#[inline]
fn eq(&self, other: &NvimStr<'_>) -> bool {
self.as_bytes() == other.as_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_cstr() {
let c_str = c"Hello, World!";
let nvim_str = NvimStr::from(c_str);
assert_eq!(nvim_str, "Hello, World!");
}
}