diff --git a/src/dumper.rs b/src/dumper.rs index 58d3481..11b4a0e 100644 --- a/src/dumper.rs +++ b/src/dumper.rs @@ -1,4 +1,5 @@ use crate::externs::{memset, strcmp}; +use crate::fmt::WriteToPtr; use crate::yaml::{ yaml_anchors_t, yaml_char_t, yaml_document_t, yaml_emitter_t, yaml_event_t, yaml_mark_t, yaml_node_item_t, yaml_node_pair_t, yaml_node_t, YAML_ALIAS_EVENT, YAML_ANY_ENCODING, @@ -9,7 +10,6 @@ use crate::yaml::{ use crate::{libc, yaml_document_delete, yaml_emitter_emit, yaml_free, yaml_malloc, PointerExt}; use core::mem::{size_of, MaybeUninit}; use core::ptr::{self, addr_of_mut}; -use core::slice; pub unsafe fn yaml_emitter_open(mut emitter: *mut yaml_emitter_t) -> libc::c_int { let mut event = MaybeUninit::::uninit(); let event = event.as_mut_ptr(); @@ -241,8 +241,7 @@ unsafe fn yaml_emitter_generate_anchor( if anchor.is_null() { return ptr::null_mut::(); } - let mut buffer = slice::from_raw_parts_mut(anchor.cast(), 16); - let _ = write!(buffer, "id{:03}\0", anchor_id); + write!(WriteToPtr::new(anchor), "id{:03}\0", anchor_id); anchor } unsafe fn yaml_emitter_dump_node(emitter: *mut yaml_emitter_t, index: libc::c_int) -> libc::c_int { diff --git a/src/lib.rs b/src/lib.rs index 114df3b..b877d4c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -182,6 +182,36 @@ pub mod externs { } } +mod fmt { + use crate::yaml_char_t; + use core::fmt::{self, Write}; + use core::ptr; + + pub struct WriteToPtr { + ptr: *mut yaml_char_t, + } + + impl WriteToPtr { + pub unsafe fn new(ptr: *mut yaml_char_t) -> Self { + WriteToPtr { ptr } + } + + pub fn write_fmt(&mut self, args: fmt::Arguments) { + let _ = Write::write_fmt(self, args); + } + } + + impl Write for WriteToPtr { + fn write_str(&mut self, s: &str) -> fmt::Result { + unsafe { + ptr::copy_nonoverlapping(s.as_ptr(), self.ptr, s.len()); + self.ptr = self.ptr.add(s.len()); + } + Ok(()) + } + } +} + trait PointerExt: Sized { fn c_offset_from(self, origin: Self) -> isize; }