| 1 | |
| 2 |
|
| 3 | |
| 4 |
|
| 5 | use alloc::alloc::AllocError;
|
| 6 | use alloc::vec::Vec;
|
| 7 | use core::fmt::{self, Write};
|
| 8 | use core::ops::{self, Deref, Index};
|
| 9 |
|
| 10 | use crate::{
|
| 11 | bindings,
|
| 12 | error::{code::*, Error},
|
| 13 | };
|
| 14 |
|
| 15 | |
| 16 | #[repr(transparent)]
|
| 17 | pub struct BStr([u8]);
|
| 18 |
|
| 19 | impl BStr {
|
| 20 | |
| 21 | #[inline]
|
| 22 | pub const fn len(&self) -> usize {
|
| 23 | self.0.len()
|
| 24 | }
|
| 25 |
|
| 26 | |
| 27 | #[inline]
|
| 28 | pub const fn is_empty(&self) -> bool {
|
| 29 | self.len() == 0
|
| 30 | }
|
| 31 |
|
| 32 | |
| 33 | #[inline]
|
| 34 | pub const fn from_bytes(bytes: &[u8]) -> &Self {
|
| 35 | |
| 36 | unsafe { &*(bytes as *const [u8] as *const BStr) }
|
| 37 | }
|
| 38 | }
|
| 39 |
|
| 40 | impl fmt::Display for BStr {
|
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 54 | for &b in &self.0 {
|
| 55 | match b {
|
| 56 | |
| 57 | b'\t' => f.write_str("\\t")?,
|
| 58 | b'\n' => f.write_str("\\n")?,
|
| 59 | b'\r' => f.write_str("\\r")?,
|
| 60 | |
| 61 | 0x20..=0x7e => f.write_char(b as char)?,
|
| 62 | _ => write!(f, "\\x{:02x}", b)?,
|
| 63 | }
|
| 64 | }
|
| 65 | Ok(())
|
| 66 | }
|
| 67 | }
|
| 68 |
|
| 69 | impl fmt::Debug for BStr {
|
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 85 | f.write_char('"')?;
|
| 86 | for &b in &self.0 {
|
| 87 | match b {
|
| 88 | |
| 89 | b'\t' => f.write_str("\\t")?,
|
| 90 | b'\n' => f.write_str("\\n")?,
|
| 91 | b'\r' => f.write_str("\\r")?,
|
| 92 | |
| 93 | b'\"' => f.write_str("\\\"")?,
|
| 94 | b'\\' => f.write_str("\\\\")?,
|
| 95 | |
| 96 | 0x20..=0x7e => f.write_char(b as char)?,
|
| 97 | _ => write!(f, "\\x{:02x}", b)?,
|
| 98 | }
|
| 99 | }
|
| 100 | f.write_char('"')
|
| 101 | }
|
| 102 | }
|
| 103 |
|
| 104 | impl Deref for BStr {
|
| 105 | type Target = [u8];
|
| 106 |
|
| 107 | #[inline]
|
| 108 | fn deref(&self) -> &Self::Target {
|
| 109 | &self.0
|
| 110 | }
|
| 111 | }
|
| 112 |
|
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | #[macro_export]
|
| 126 | macro_rules! b_str {
|
| 127 | ($str:literal) => {{
|
| 128 | const S: &'static str = $str;
|
| 129 | const C: &'static $crate::str::BStr = $crate::str::BStr::from_bytes(S.as_bytes());
|
| 130 | C
|
| 131 | }};
|
| 132 | }
|
| 133 |
|
| 134 | |
| 135 | #[derive(Debug, Clone, Copy)]
|
| 136 | pub enum CStrConvertError {
|
| 137 | |
| 138 | InteriorNul,
|
| 139 |
|
| 140 | |
| 141 | NotNulTerminated,
|
| 142 | }
|
| 143 |
|
| 144 | impl From<CStrConvertError> for Error {
|
| 145 | #[inline]
|
| 146 | fn from(_: CStrConvertError) -> Error {
|
| 147 | EINVAL
|
| 148 | }
|
| 149 | }
|
| 150 |
|
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | #[repr(transparent)]
|
| 156 | pub struct CStr([u8]);
|
| 157 |
|
| 158 | impl CStr {
|
| 159 | |
| 160 | #[inline]
|
| 161 | pub const fn len(&self) -> usize {
|
| 162 | self.len_with_nul() - 1
|
| 163 | }
|
| 164 |
|
| 165 | |
| 166 | #[inline]
|
| 167 | pub const fn len_with_nul(&self) -> usize {
|
| 168 | |
| 169 | |
| 170 | |
| 171 | if self.0.is_empty() {
|
| 172 | unsafe { core::hint::unreachable_unchecked() };
|
| 173 | }
|
| 174 | self.0.len()
|
| 175 | }
|
| 176 |
|
| 177 | |
| 178 | #[inline]
|
| 179 | pub const fn is_empty(&self) -> bool {
|
| 180 | self.len() == 0
|
| 181 | }
|
| 182 |
|
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | #[inline]
|
| 191 | pub unsafe fn from_char_ptr<'a>(ptr: *const core::ffi::c_char) -> &'a Self {
|
| 192 | |
| 193 | |
| 194 | let len = unsafe { bindings::strlen(ptr) } + 1;
|
| 195 | |
| 196 | let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) };
|
| 197 | |
| 198 | |
| 199 | unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
|
| 200 | }
|
| 201 |
|
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
|
| 207 | if bytes.is_empty() {
|
| 208 | return Err(CStrConvertError::NotNulTerminated);
|
| 209 | }
|
| 210 | if bytes[bytes.len() - 1] != 0 {
|
| 211 | return Err(CStrConvertError::NotNulTerminated);
|
| 212 | }
|
| 213 | let mut i = 0;
|
| 214 | |
| 215 | |
| 216 | while i + 1 < bytes.len() {
|
| 217 | if bytes[i] == 0 {
|
| 218 | return Err(CStrConvertError::InteriorNul);
|
| 219 | }
|
| 220 | i += 1;
|
| 221 | }
|
| 222 | |
| 223 | Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
|
| 224 | }
|
| 225 |
|
| 226 | |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | #[inline]
|
| 234 | pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
|
| 235 | |
| 236 | unsafe { core::mem::transmute(bytes) }
|
| 237 | }
|
| 238 |
|
| 239 | |
| 240 | #[inline]
|
| 241 | pub const fn as_char_ptr(&self) -> *const core::ffi::c_char {
|
| 242 | self.0.as_ptr() as _
|
| 243 | }
|
| 244 |
|
| 245 | |
| 246 | #[inline]
|
| 247 | pub fn as_bytes(&self) -> &[u8] {
|
| 248 | &self.0[..self.len()]
|
| 249 | }
|
| 250 |
|
| 251 | |
| 252 | #[inline]
|
| 253 | pub const fn as_bytes_with_nul(&self) -> &[u8] {
|
| 254 | &self.0
|
| 255 | }
|
| 256 |
|
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | #[inline]
|
| 271 | pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
|
| 272 | core::str::from_utf8(self.as_bytes())
|
| 273 | }
|
| 274 |
|
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | #[inline]
|
| 293 | pub unsafe fn as_str_unchecked(&self) -> &str {
|
| 294 | unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
|
| 295 | }
|
| 296 |
|
| 297 | |
| 298 | |
| 299 | pub fn to_cstring(&self) -> Result<CString, AllocError> {
|
| 300 | CString::try_from(self)
|
| 301 | }
|
| 302 | }
|
| 303 |
|
| 304 | impl fmt::Display for CStr {
|
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 321 | for &c in self.as_bytes() {
|
| 322 | if (0x20..0x7f).contains(&c) {
|
| 323 | |
| 324 | f.write_char(c as char)?;
|
| 325 | } else {
|
| 326 | write!(f, "\\x{:02x}", c)?;
|
| 327 | }
|
| 328 | }
|
| 329 | Ok(())
|
| 330 | }
|
| 331 | }
|
| 332 |
|
| 333 | impl fmt::Debug for CStr {
|
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 351 | f.write_str("\"")?;
|
| 352 | for &c in self.as_bytes() {
|
| 353 | match c {
|
| 354 | |
| 355 | b'\"' => f.write_str("\\\"")?,
|
| 356 | 0x20..=0x7e => f.write_char(c as char)?,
|
| 357 | _ => write!(f, "\\x{:02x}", c)?,
|
| 358 | }
|
| 359 | }
|
| 360 | f.write_str("\"")
|
| 361 | }
|
| 362 | }
|
| 363 |
|
| 364 | impl AsRef<BStr> for CStr {
|
| 365 | #[inline]
|
| 366 | fn as_ref(&self) -> &BStr {
|
| 367 | BStr::from_bytes(self.as_bytes())
|
| 368 | }
|
| 369 | }
|
| 370 |
|
| 371 | impl Deref for CStr {
|
| 372 | type Target = BStr;
|
| 373 |
|
| 374 | #[inline]
|
| 375 | fn deref(&self) -> &Self::Target {
|
| 376 | self.as_ref()
|
| 377 | }
|
| 378 | }
|
| 379 |
|
| 380 | impl Index<ops::RangeFrom<usize>> for CStr {
|
| 381 | type Output = CStr;
|
| 382 |
|
| 383 | #[inline]
|
| 384 | fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
|
| 385 | |
| 386 | |
| 387 | let _ = &self.as_bytes()[index.start..];
|
| 388 | |
| 389 | unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
|
| 390 | }
|
| 391 | }
|
| 392 |
|
| 393 | impl Index<ops::RangeFull> for CStr {
|
| 394 | type Output = CStr;
|
| 395 |
|
| 396 | #[inline]
|
| 397 | fn index(&self, _index: ops::RangeFull) -> &Self::Output {
|
| 398 | self
|
| 399 | }
|
| 400 | }
|
| 401 |
|
| 402 | mod private {
|
| 403 | use core::ops;
|
| 404 |
|
| 405 | |
| 406 | pub trait CStrIndex {}
|
| 407 |
|
| 408 | impl CStrIndex for usize {}
|
| 409 | impl CStrIndex for ops::Range<usize> {}
|
| 410 | impl CStrIndex for ops::RangeInclusive<usize> {}
|
| 411 | impl CStrIndex for ops::RangeToInclusive<usize> {}
|
| 412 | }
|
| 413 |
|
| 414 | impl<Idx> Index<Idx> for CStr
|
| 415 | where
|
| 416 | Idx: private::CStrIndex,
|
| 417 | BStr: Index<Idx>,
|
| 418 | {
|
| 419 | type Output = <BStr as Index<Idx>>::Output;
|
| 420 |
|
| 421 | #[inline]
|
| 422 | fn index(&self, index: Idx) -> &Self::Output {
|
| 423 | &self.as_ref()[index]
|
| 424 | }
|
| 425 | }
|
| 426 |
|
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | #[macro_export]
|
| 439 | macro_rules! c_str {
|
| 440 | ($str:expr) => {{
|
| 441 | const S: &str = concat!($str, "\0");
|
| 442 | const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
|
| 443 | Ok(v) => v,
|
| 444 | Err(_) => panic!("string contains interior NUL"),
|
| 445 | };
|
| 446 | C
|
| 447 | }};
|
| 448 | }
|
| 449 |
|
| 450 | #[cfg(test)]
|
| 451 | mod tests {
|
| 452 | use super::*;
|
| 453 | use alloc::format;
|
| 454 |
|
| 455 | const ALL_ASCII_CHARS: &'static str =
|
| 456 | "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\
|
| 457 | \\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \
|
| 458 | !\"#$%&'()*+,-./0123456789:;<=>?@\
|
| 459 | ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f\
|
| 460 | \\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\
|
| 461 | \\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\
|
| 462 | \\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\
|
| 463 | \\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\
|
| 464 | \\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\
|
| 465 | \\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\
|
| 466 | \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\
|
| 467 | \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff";
|
| 468 |
|
| 469 | #[test]
|
| 470 | fn test_cstr_to_str() {
|
| 471 | let good_bytes = b"\xf0\x9f\xa6\x80\0";
|
| 472 | let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
|
| 473 | let checked_str = checked_cstr.to_str().unwrap();
|
| 474 | assert_eq!(checked_str, "🦀");
|
| 475 | }
|
| 476 |
|
| 477 | #[test]
|
| 478 | #[should_panic]
|
| 479 | fn test_cstr_to_str_panic() {
|
| 480 | let bad_bytes = b"\xc3\x28\0";
|
| 481 | let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap();
|
| 482 | checked_cstr.to_str().unwrap();
|
| 483 | }
|
| 484 |
|
| 485 | #[test]
|
| 486 | fn test_cstr_as_str_unchecked() {
|
| 487 | let good_bytes = b"\xf0\x9f\x90\xA7\0";
|
| 488 | let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
|
| 489 | let unchecked_str = unsafe { checked_cstr.as_str_unchecked() };
|
| 490 | assert_eq!(unchecked_str, "🐧");
|
| 491 | }
|
| 492 |
|
| 493 | #[test]
|
| 494 | fn test_cstr_display() {
|
| 495 | let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap();
|
| 496 | assert_eq!(format!("{}", hello_world), "hello, world!");
|
| 497 | let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap();
|
| 498 | assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a");
|
| 499 | let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap();
|
| 500 | assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu");
|
| 501 | let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap();
|
| 502 | assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80");
|
| 503 | }
|
| 504 |
|
| 505 | #[test]
|
| 506 | fn test_cstr_display_all_bytes() {
|
| 507 | let mut bytes: [u8; 256] = [0; 256];
|
| 508 | |
| 509 | for i in u8::MIN..=u8::MAX {
|
| 510 | bytes[i as usize] = i.wrapping_add(1);
|
| 511 | }
|
| 512 | let cstr = CStr::from_bytes_with_nul(&bytes).unwrap();
|
| 513 | assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS);
|
| 514 | }
|
| 515 |
|
| 516 | #[test]
|
| 517 | fn test_cstr_debug() {
|
| 518 | let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap();
|
| 519 | assert_eq!(format!("{:?}", hello_world), "\"hello, world!\"");
|
| 520 | let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap();
|
| 521 | assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\"");
|
| 522 | let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap();
|
| 523 | assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\"");
|
| 524 | let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap();
|
| 525 | assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\"");
|
| 526 | }
|
| 527 |
|
| 528 | #[test]
|
| 529 | fn test_bstr_display() {
|
| 530 | let hello_world = BStr::from_bytes(b"hello, world!");
|
| 531 | assert_eq!(format!("{}", hello_world), "hello, world!");
|
| 532 | let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_");
|
| 533 | assert_eq!(format!("{}", escapes), "_\\t_\\n_\\r_\\_'_\"_");
|
| 534 | let others = BStr::from_bytes(b"\x01");
|
| 535 | assert_eq!(format!("{}", others), "\\x01");
|
| 536 | let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu");
|
| 537 | assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu");
|
| 538 | let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80");
|
| 539 | assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80");
|
| 540 | }
|
| 541 |
|
| 542 | #[test]
|
| 543 | fn test_bstr_debug() {
|
| 544 | let hello_world = BStr::from_bytes(b"hello, world!");
|
| 545 | assert_eq!(format!("{:?}", hello_world), "\"hello, world!\"");
|
| 546 | let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_");
|
| 547 | assert_eq!(format!("{:?}", escapes), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\"");
|
| 548 | let others = BStr::from_bytes(b"\x01");
|
| 549 | assert_eq!(format!("{:?}", others), "\"\\x01\"");
|
| 550 | let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu");
|
| 551 | assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\"");
|
| 552 | let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80");
|
| 553 | assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\"");
|
| 554 | }
|
| 555 | }
|
| 556 |
|
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 562 | |
| 563 | |
| 564 | |
| 565 | |
| 566 | pub(crate) struct RawFormatter {
|
| 567 | |
| 568 | beg: usize,
|
| 569 | pos: usize,
|
| 570 | end: usize,
|
| 571 | }
|
| 572 |
|
| 573 | impl RawFormatter {
|
| 574 | |
| 575 | fn new() -> Self {
|
| 576 | |
| 577 | Self {
|
| 578 | beg: 0,
|
| 579 | pos: 0,
|
| 580 | end: 0,
|
| 581 | }
|
| 582 | }
|
| 583 |
|
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | |
| 590 | pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self {
|
| 591 | |
| 592 | Self {
|
| 593 | beg: pos as _,
|
| 594 | pos: pos as _,
|
| 595 | end: end as _,
|
| 596 | }
|
| 597 | }
|
| 598 |
|
| 599 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
|
| 606 | let pos = buf as usize;
|
| 607 | |
| 608 | |
| 609 | Self {
|
| 610 | pos,
|
| 611 | beg: pos,
|
| 612 | end: pos.saturating_add(len),
|
| 613 | }
|
| 614 | }
|
| 615 |
|
| 616 | |
| 617 | |
| 618 | |
| 619 | pub(crate) fn pos(&self) -> *mut u8 {
|
| 620 | self.pos as _
|
| 621 | }
|
| 622 |
|
| 623 | |
| 624 | pub(crate) fn bytes_written(&self) -> usize {
|
| 625 | self.pos - self.beg
|
| 626 | }
|
| 627 | }
|
| 628 |
|
| 629 | impl fmt::Write for RawFormatter {
|
| 630 | fn write_str(&mut self, s: &str) -> fmt::Result {
|
| 631 | |
| 632 | |
| 633 | let pos_new = self.pos.saturating_add(s.len());
|
| 634 |
|
| 635 | |
| 636 | let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos);
|
| 637 |
|
| 638 | if len_to_copy > 0 {
|
| 639 | |
| 640 | |
| 641 | unsafe {
|
| 642 | core::ptr::copy_nonoverlapping(
|
| 643 | s.as_bytes().as_ptr(),
|
| 644 | self.pos as *mut u8,
|
| 645 | len_to_copy,
|
| 646 | )
|
| 647 | };
|
| 648 | }
|
| 649 |
|
| 650 | self.pos = pos_new;
|
| 651 | Ok(())
|
| 652 | }
|
| 653 | }
|
| 654 |
|
| 655 | |
| 656 | |
| 657 | |
| 658 | pub(crate) struct Formatter(RawFormatter);
|
| 659 |
|
| 660 | impl Formatter {
|
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
|
| 668 | |
| 669 | Self(unsafe { RawFormatter::from_buffer(buf, len) })
|
| 670 | }
|
| 671 | }
|
| 672 |
|
| 673 | impl Deref for Formatter {
|
| 674 | type Target = RawFormatter;
|
| 675 |
|
| 676 | fn deref(&self) -> &Self::Target {
|
| 677 | &self.0
|
| 678 | }
|
| 679 | }
|
| 680 |
|
| 681 | impl fmt::Write for Formatter {
|
| 682 | fn write_str(&mut self, s: &str) -> fmt::Result {
|
| 683 | self.0.write_str(s)?;
|
| 684 |
|
| 685 | |
| 686 | if self.0.pos > self.0.end {
|
| 687 | Err(fmt::Error)
|
| 688 | } else {
|
| 689 | Ok(())
|
| 690 | }
|
| 691 | }
|
| 692 | }
|
| 693 |
|
| 694 | |
| 695 | |
| 696 | |
| 697 | |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | pub struct CString {
|
| 719 | buf: Vec<u8>,
|
| 720 | }
|
| 721 |
|
| 722 | impl CString {
|
| 723 | |
| 724 | pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
|
| 725 | |
| 726 | let mut f = RawFormatter::new();
|
| 727 | f.write_fmt(args)?;
|
| 728 | f.write_str("\0")?;
|
| 729 | let size = f.bytes_written();
|
| 730 |
|
| 731 | |
| 732 | let mut buf = Vec::try_with_capacity(size)?;
|
| 733 | |
| 734 | let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
|
| 735 | f.write_fmt(args)?;
|
| 736 | f.write_str("\0")?;
|
| 737 |
|
| 738 | |
| 739 | |
| 740 | unsafe { buf.set_len(f.bytes_written()) };
|
| 741 |
|
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) };
|
| 747 | if !ptr.is_null() {
|
| 748 | return Err(EINVAL);
|
| 749 | }
|
| 750 |
|
| 751 | |
| 752 | |
| 753 | Ok(Self { buf })
|
| 754 | }
|
| 755 | }
|
| 756 |
|
| 757 | impl Deref for CString {
|
| 758 | type Target = CStr;
|
| 759 |
|
| 760 | fn deref(&self) -> &Self::Target {
|
| 761 | |
| 762 | |
| 763 | unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
|
| 764 | }
|
| 765 | }
|
| 766 |
|
| 767 | impl<'a> TryFrom<&'a CStr> for CString {
|
| 768 | type Error = AllocError;
|
| 769 |
|
| 770 | fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
|
| 771 | let mut buf = Vec::new();
|
| 772 |
|
| 773 | buf.try_extend_from_slice(cstr.as_bytes_with_nul())
|
| 774 | .map_err(|_| AllocError)?;
|
| 775 |
|
| 776 | |
| 777 | |
| 778 | Ok(CString { buf })
|
| 779 | }
|
| 780 | }
|
| 781 |
|
| 782 | impl fmt::Debug for CString {
|
| 783 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 784 | fmt::Debug::fmt(&**self, f)
|
| 785 | }
|
| 786 | }
|
| 787 |
|
| 788 | |
| 789 | #[macro_export]
|
| 790 | macro_rules! fmt {
|
| 791 | ($($f:tt)*) => ( core::format_args!($($f)*) )
|
| 792 | }
|