Created
November 22, 2024 01:15
-
-
Save phase/8e3e69a61ebe3c4f9d58f9ae5b7602b6 to your computer and use it in GitHub Desktop.
yokeable ident. thinking about swapping to just use Ustr and not borrow any data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{ops::Deref, sync::Arc}; | |
use rustix::path::Arg; | |
use stable_deref_trait::StableDeref; | |
use ustr::{Ustr, ustr}; | |
use yoke::Yoke; | |
use yoke_derive::Yokeable; | |
mod access; | |
mod descriptor; | |
/// Like a Cow<'a, str> but you can plug in your own Owned type. | |
#[derive(Yokeable)] | |
pub enum Ident<'a, O> { | |
Owned(O), | |
Borrowed(&'a str), | |
} | |
impl<'a, O: Clone + From<&'a str>> Ident<'a, O> { | |
pub fn new(s: &'a str) -> Self { | |
Ident::Borrowed(s) | |
} | |
pub fn as_owned(&self) -> O { | |
match self { | |
Ident::Owned(s) => s.clone(), | |
Ident::Borrowed(s) => (*s).into(), | |
} | |
} | |
/// Any lifetime 'b is fine here because we're always returning an owned ustr. | |
pub fn mutate<'b>(&mut self, f: impl FnOnce(&mut O)) -> Ident<'b, O> { | |
let mut owned = self.as_owned(); | |
f(&mut owned); | |
Ident::Owned(owned) | |
} | |
} | |
pub trait ValidCart: Deref<Target=[u8]> + StableDeref {} | |
impl ValidCart for DefaultCart {} | |
/// C is our cart, could be an Arc<\[u8\]> or something. | |
pub struct ID<C: ValidCart = DefaultCart>(Yoke<Ident<'static, Ustr>, C>); | |
impl<C: ValidCart> ID<C> { | |
pub fn new(s: &str, cart: C) -> Self { | |
ID(Yoke::attach_to_cart(cart, |data| { | |
let str = std::str::from_utf8(data).expect("failed to validate utf-8 string"); | |
Ident::Borrowed(str) | |
})) | |
} | |
pub fn as_str(&self) -> &str { | |
let ident = self.0.get(); | |
match ident { | |
Ident::Owned(s) => s.as_str(), | |
Ident::Borrowed(s) => s, | |
} | |
} | |
pub fn mutate(&mut self, f: impl FnOnce(&str) -> String) { | |
let u = ustr(&f(self.as_str())); | |
self.0.with_mut(move |s| *s = Ident::Owned(u)); | |
} | |
} | |
impl<C: Deref<Target=[u8]> + StableDeref> ID<C> { | |
} | |
pub type DefaultCart = Arc<[u8]>; | |
pub struct ClassFile<C: ValidCart = DefaultCart> { | |
name: ID<C>, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment