rune/runtime/
fmt.rs
1use core::ptr::NonNull;
2
3use crate::alloc::fmt::TryWrite;
4use crate::alloc::{self, String};
5use crate::runtime::VmResult;
6use crate::Any;
7
8#[derive(Any)]
16#[rune(crate, item = ::std::fmt)]
17pub struct Formatter {
18 pub(crate) out: NonNull<dyn TryWrite>,
19 pub(crate) buf: String,
20}
21
22impl Formatter {
23 pub(crate) fn format_with(
25 out: &mut String,
26 f: impl FnOnce(&mut Self) -> VmResult<()>,
27 ) -> VmResult<()> {
28 let mut fmt = Formatter {
31 out: NonNull::from(out),
32 buf: String::new(),
33 };
34 f(&mut fmt)
35 }
36
37 #[inline]
38 pub(crate) fn parts_mut(&mut self) -> (&mut dyn TryWrite, &str) {
39 (unsafe { self.out.as_mut() }, &self.buf)
41 }
42
43 #[inline]
44 pub(crate) fn buf_mut(&mut self) -> &mut String {
45 &mut self.buf
46 }
47}
48
49impl TryWrite for Formatter {
50 #[inline]
51 fn try_write_str(&mut self, s: &str) -> alloc::Result<()> {
52 unsafe { self.out.as_mut().try_write_str(s) }
54 }
55
56 #[inline]
57 fn try_write_char(&mut self, c: char) -> alloc::Result<()> {
58 unsafe { self.out.as_mut().try_write_char(c) }
60 }
61}