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