File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66//!
77//! Reference: <https://www.kernel.org/doc/html/latest/core-api/printk-basics.html>
88
9- use core:: cmp;
109use core:: fmt;
1110
12- use crate :: bindings;
1311use crate :: c_types:: { c_char, c_void} ;
12+ use crate :: { bindings, str:: Formatter } ;
1413
1514// Called from `vsprintf` with format specifier `%pA`.
1615#[ no_mangle]
1716unsafe fn rust_fmt_argument ( buf : * mut c_char , end : * mut c_char , ptr : * const c_void ) -> * mut c_char {
1817 use fmt:: Write ;
1918
20- // Use `usize` to use `saturating_*` functions.
21- struct Writer {
22- buf : usize ,
23- end : usize ,
24- }
25-
26- impl Write for Writer {
27- fn write_str ( & mut self , s : & str ) -> fmt:: Result {
28- // `buf` value after writing `len` bytes. This does not have to be bounded
29- // by `end`, but we don't want it to wrap around to 0.
30- let buf_new = self . buf . saturating_add ( s. len ( ) ) ;
31-
32- // Amount that we can copy. `saturating_sub` ensures we get 0 if
33- // `buf` goes past `end`.
34- let len_to_copy = cmp:: min ( buf_new, self . end ) . saturating_sub ( self . buf ) ;
35-
36- // SAFETY: In any case, `buf` is non-null and properly aligned.
37- // If `len_to_copy` is non-zero, then we know `buf` has not past
38- // `end` yet and so is valid.
39- unsafe {
40- core:: ptr:: copy_nonoverlapping (
41- s. as_bytes ( ) . as_ptr ( ) ,
42- self . buf as * mut u8 ,
43- len_to_copy,
44- )
45- } ;
46-
47- self . buf = buf_new;
48- Ok ( ( ) )
49- }
50- }
51-
52- let mut w = Writer {
19+ let mut w = Formatter {
5320 buf : buf as _ ,
5421 end : end as _ ,
5522 } ;
Original file line number Diff line number Diff line change @@ -373,3 +373,29 @@ mod tests {
373373 assert_eq ! ( unchecked_str, "🐧" ) ;
374374 }
375375}
376+
377+ // Use `usize` to use `saturating_*` functions.
378+ pub ( crate ) struct Formatter {
379+ pub ( crate ) buf : usize ,
380+ pub ( crate ) end : usize ,
381+ }
382+
383+ impl fmt:: Write for Formatter {
384+ fn write_str ( & mut self , s : & str ) -> fmt:: Result {
385+ // `buf` value after writing `len` bytes. This does not have to be bounded by `end`, but we
386+ // don't want it to wrap around to 0.
387+ let buf_new = self . buf . saturating_add ( s. len ( ) ) ;
388+
389+ // Amount that we can copy. `saturating_sub` ensures we get 0 if `buf` goes past `end`.
390+ let len_to_copy = core:: cmp:: min ( buf_new, self . end ) . saturating_sub ( self . buf ) ;
391+
392+ // SAFETY: In any case, `buf` is non-null and properly aligned. If `len_to_copy` is
393+ // non-zero, then we know `buf` has not past `end` yet and so is valid.
394+ unsafe {
395+ core:: ptr:: copy_nonoverlapping ( s. as_bytes ( ) . as_ptr ( ) , self . buf as * mut u8 , len_to_copy)
396+ } ;
397+
398+ self . buf = buf_new;
399+ Ok ( ( ) )
400+ }
401+ }
You can’t perform that action at this time.
0 commit comments