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