Make a fmt::Write impl for pointer writes

This commit is contained in:
David Tolnay 2022-07-07 17:43:38 -07:00
parent eb854c860b
commit 17872c0728
No known key found for this signature in database
GPG key ID: F9BA143B95FF6D82
2 changed files with 32 additions and 3 deletions

View file

@ -1,4 +1,5 @@
use crate::externs::{memset, strcmp}; use crate::externs::{memset, strcmp};
use crate::fmt::WriteToPtr;
use crate::yaml::{ use crate::yaml::{
yaml_anchors_t, yaml_char_t, yaml_document_t, yaml_emitter_t, yaml_event_t, yaml_mark_t, 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, 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 crate::{libc, yaml_document_delete, yaml_emitter_emit, yaml_free, yaml_malloc, PointerExt};
use core::mem::{size_of, MaybeUninit}; use core::mem::{size_of, MaybeUninit};
use core::ptr::{self, addr_of_mut}; 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 { pub unsafe fn yaml_emitter_open(mut emitter: *mut yaml_emitter_t) -> libc::c_int {
let mut event = MaybeUninit::<yaml_event_t>::uninit(); let mut event = MaybeUninit::<yaml_event_t>::uninit();
let event = event.as_mut_ptr(); let event = event.as_mut_ptr();
@ -241,8 +241,7 @@ unsafe fn yaml_emitter_generate_anchor(
if anchor.is_null() { if anchor.is_null() {
return ptr::null_mut::<yaml_char_t>(); return ptr::null_mut::<yaml_char_t>();
} }
let mut buffer = slice::from_raw_parts_mut(anchor.cast(), 16); write!(WriteToPtr::new(anchor), "id{:03}\0", anchor_id);
let _ = write!(buffer, "id{:03}\0", anchor_id);
anchor anchor
} }
unsafe fn yaml_emitter_dump_node(emitter: *mut yaml_emitter_t, index: libc::c_int) -> libc::c_int { unsafe fn yaml_emitter_dump_node(emitter: *mut yaml_emitter_t, index: libc::c_int) -> libc::c_int {

View file

@ -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 { trait PointerExt: Sized {
fn c_offset_from(self, origin: Self) -> isize; fn c_offset_from(self, origin: Self) -> isize;
} }