Skip to content
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

[feature request] #![no_std] support #10

Open
3 tasks
rowan-sl opened this issue Nov 23, 2022 · 0 comments
Open
3 tasks

[feature request] #![no_std] support #10

rowan-sl opened this issue Nov 23, 2022 · 0 comments

Comments

@rowan-sl
Copy link

Although this would be less future-proof than the current implementation, a #![no_std] compatable backend for this crate could be provided by a transmute implementation like this one (using fake_static)

#![forbid(unsafe_code)]
#![no_std]

use core::cell::{Cell,UnsafeCell};

// may want to just depend on fake_static? instead of re-defining

fn helper<'a, 'b, T>(_: &'a &'b (), v: &'b T) -> &'a T { v }

/// Use black magic fuckery to turn any `&T` into a `&'static T`.
/// May introduce undefined behavior.
pub fn make_static<'a, T>(input: &'a T) -> &'static T {
    let f: fn(_, &'a T) -> &'static T = helper;
    f(&&(), input)
}

pub fn transmute<T, U: 'static>(e: T) -> U {
    // Store a None `U` value and get a reference to it:
    let mut value: Result<Cell<Option<UnsafeCell<U>>>, Cell<Option<UnsafeCell<T>>>> = Ok(Cell::new(None));
    let u_ref: &Cell<Option<UnsafeCell<U>>> = if let Ok(v) = &value { make_static(v) } else { unreachable!() };
    // Store a Some `T` value:
    value = Err(Cell::new(Some(UnsafeCell::new(e))));
    // Use our previous `U` reference to access the stored `T` value:
    u_ref.take().unwrap().into_inner()
}

concerns

  • too powerfull to be left alive
  • may require the addition of a MSRV (maximum supported rust version)
  • code readability
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant