Skip to content

[ISSUE #5]✨Add cheetah string function🚀 #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "cheetah-string"
version = "0.1.0"
authors = ["mxsm <[email protected]>"]
edition = "2021"
homepage = "https://github.com/mxsm/cheetah-string"
repository = "https://github.com/mxsm/cheetah-string"
license = "MIT OR Apache-2.0"
keywords = ["fast", "fast-string", "bytes", "rust", "rocketmq-rust"]
categories = ["network-programming"]
readme = "README.md"
rust-version = "1.75.0"
description = """
A lightweight, high-performance string manipulation library optimized for speed-sensitive applications
"""

[dependencies]
bytes = "1.8.0"
serde = { version = "1.0", optional = true, default-features = false, features = ["alloc"] }

[features]
default = ["std"]
std = []
serde = ["serde/alloc"]
bytes = []
182 changes: 182 additions & 0 deletions src/cheetah_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use std::ops::Deref;
use std::sync::Arc;

#[derive(Clone)]
#[repr(transparent)]
pub struct CheetahString {
pub(super) inner: InnerString,
}

impl Default for CheetahString {
fn default() -> Self {
CheetahString {
inner: InnerString::Empty,
}
}
}

impl From<String> for CheetahString {
fn from(s: String) -> Self {
CheetahString::from_string(s)
}
}

impl From<Arc<String>> for CheetahString {
fn from(s: Arc<String>) -> Self {
CheetahString::from_arc_string(s)
}
}

impl From<&'static str> for CheetahString {
fn from(s: &'static str) -> Self {
CheetahString::from_static_str(s)
}
}

impl From<&[u8]> for CheetahString {
fn from(b: &[u8]) -> Self {
CheetahString::from_slice(unsafe { std::str::from_utf8_unchecked(b) })
}
}

#[cfg(feature = "bytes")]
impl From<bytes::Bytes> for CheetahString {
fn from(b: bytes::Bytes) -> Self {
CheetahString::from_bytes(b)
}
}

impl From<CheetahString> for String {
fn from(s: CheetahString) -> Self {
match s {
CheetahString {
inner: InnerString::ArcString(s),
} => s.as_ref().clone(),
CheetahString {
inner: InnerString::StaticStr(s),
} => s.to_string(),
#[cfg(feature = "bytes")]
CheetahString {
inner: InnerString::Bytes(b),
} => unsafe { String::from_utf8_unchecked(b.to_vec()) },
CheetahString {
inner: InnerString::Empty,
} => String::new(),
}
}
}

impl Deref for CheetahString {
type Target = str;

#[inline]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}

impl AsRef<str> for CheetahString {
fn as_ref(&self) -> &str {
self.as_str()
}
}

impl AsRef<[u8]> for CheetahString {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}

impl CheetahString {
#[inline]
pub fn new() -> Self {
CheetahString::default()
}

#[inline]
pub fn from_static_str(s: &'static str) -> Self {
CheetahString {
inner: InnerString::StaticStr(s),
}
}

#[inline]
pub fn from_slice(s: &str) -> Self {
CheetahString {
inner: InnerString::ArcString(Arc::new(s.to_owned())),
}
}

#[inline]
pub fn from_string(s: String) -> Self {
CheetahString {
inner: InnerString::ArcString(Arc::new(s)),
}
}
#[inline]
pub fn from_arc_string(s: Arc<String>) -> Self {
CheetahString {
inner: InnerString::ArcString(s),
}
}

#[inline]
#[cfg(feature = "bytes")]
pub fn from_bytes(b: bytes::Bytes) -> Self {
CheetahString {
inner: InnerString::Bytes(b),
}
}

#[inline]
pub fn as_str(&self) -> &str {
match &self.inner {
InnerString::ArcString(s) => s.as_str(),
InnerString::StaticStr(s) => s,
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => std::str::from_utf8(b.as_ref()).unwrap(),
InnerString::Empty => "",
}
}

#[inline]
pub fn as_bytes(&self) -> &[u8] {
match &self.inner {
InnerString::ArcString(s) => s.as_bytes(),
InnerString::StaticStr(s) => s.as_bytes(),
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => b.as_ref(),
InnerString::Empty => &[],
}
}

#[inline]
pub fn len(&self) -> usize {
match &self.inner {
InnerString::ArcString(s) => s.len(),
InnerString::StaticStr(s) => s.len(),
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => b.len(),
InnerString::Empty => 0,
}
}

pub fn is_empty(&self) -> bool {
match &self.inner {
InnerString::ArcString(s) => s.is_empty(),
InnerString::StaticStr(s) => s.is_empty(),
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => b.is_empty(),
InnerString::Empty => true,
}
}
}

#[derive(Clone)]
pub(super) enum InnerString {
ArcString(Arc<String>),
StaticStr(&'static str),
#[cfg(feature = "bytes")]
Bytes(bytes::Bytes),
Empty,
}
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#![cfg_attr(not(feature = "std"), no_std)]

mod cheetah_string;

#[cfg(feature = "serde")]
mod serde;

pub use cheetah_string::CheetahString;
93 changes: 93 additions & 0 deletions src/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
use crate::cheetah_string::InnerString;
use crate::CheetahString;
use serde::de::{Error, Unexpected, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for CheetahString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match &self.inner {
InnerString::ArcString(s) => serializer.serialize_str(s.as_str()),
InnerString::StaticStr(s) => serializer.serialize_str(s),
#[cfg(feature = "bytes")]
InnerString::Bytes(bytes) => serializer.serialize_bytes(bytes.as_ref()),
InnerString::Empty => Ok(()),
}
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn cheetah_string<'de: 'a, 'a, D>(deserializer: D) -> Result<CheetahString, D::Error>
where
D: Deserializer<'de>,
{
struct CheetahStringVisitor;

impl<'a> Visitor<'a> for CheetahStringVisitor {
type Value = CheetahString;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(CheetahString::from_slice(v))
}

fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(CheetahString::from_slice(v))
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(CheetahString::from_string(v))
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(CheetahString::from(v))
}

fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(CheetahString::from(v))
}

fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(CheetahString::from_string(s)),
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}
deserializer.deserialize_str(CheetahStringVisitor)
}

impl<'de> Deserialize<'de> for CheetahString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
cheetah_string(deserializer)
}
}