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