| 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 | |
| 17 | |
| 18 | pub type BStr = [u8];
|
| 19 |
|
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | #[macro_export]
|
| 33 | macro_rules! b_str {
|
| 34 | ($str:literal) => {{
|
| 35 | const S: &'static str = $str;
|
| 36 | const C: &'static $crate::str::BStr = S.as_bytes();
|
| 37 | C
|
| 38 | }};
|
| 39 | }
|
| 40 |
|
| 41 | |
| 42 | #[derive(Debug, Clone, Copy)]
|
| 43 | pub enum CStrConvertError {
|
| 44 | |
| 45 | InteriorNul,
|
| 46 |
|
| 47 | |
| 48 | NotNulTerminated,
|
| 49 | }
|
| 50 |
|
| 51 | impl From<CStrConvertError> for Error {
|
| 52 | #[inline]
|
| 53 | fn from(_: CStrConvertError) -> Error {
|
| 54 | EINVAL
|
| 55 | }
|
| 56 | }
|
| 57 |
|
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | #[repr(transparent)]
|
| 63 | pub struct CStr([u8]);
|
| 64 |
|
| 65 | impl CStr {
|
| 66 | |
| 67 | #[inline]
|
| 68 | pub const fn len(&self) -> usize {
|
| 69 | self.len_with_nul() - 1
|
| 70 | }
|
| 71 |
|
| 72 | |
| 73 | #[inline]
|
| 74 | pub const fn len_with_nul(&self) -> usize {
|
| 75 | |
| 76 | |
| 77 | |
| 78 | if self.0.is_empty() {
|
| 79 | unsafe { core::hint::unreachable_unchecked() };
|
| 80 | }
|
| 81 | self.0.len()
|
| 82 | }
|
| 83 |
|
| 84 | |
| 85 | #[inline]
|
| 86 | pub const fn is_empty(&self) -> bool {
|
| 87 | self.len() == 0
|
| 88 | }
|
| 89 |
|
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | #[inline]
|
| 98 | pub unsafe fn from_char_ptr<'a>(ptr: *const core::ffi::c_char) -> &'a Self {
|
| 99 | |
| 100 | |
| 101 | let len = unsafe { bindings::strlen(ptr) } + 1;
|
| 102 | |
| 103 | let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) };
|
| 104 | |
| 105 | |
| 106 | unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
|
| 107 | }
|
| 108 |
|
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
|
| 114 | if bytes.is_empty() {
|
| 115 | return Err(CStrConvertError::NotNulTerminated);
|
| 116 | }
|
| 117 | if bytes[bytes.len() - 1] != 0 {
|
| 118 | return Err(CStrConvertError::NotNulTerminated);
|
| 119 | }
|
| 120 | let mut i = 0;
|
| 121 | |
| 122 | |
| 123 | while i + 1 < bytes.len() {
|
| 124 | if bytes[i] == 0 {
|
| 125 | return Err(CStrConvertError::InteriorNul);
|
| 126 | }
|
| 127 | i += 1;
|
| 128 | }
|
| 129 | |
| 130 | Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
|
| 131 | }
|
| 132 |
|
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | #[inline]
|
| 141 | pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
|
| 142 | |
| 143 | unsafe { core::mem::transmute(bytes) }
|
| 144 | }
|
| 145 |
|
| 146 | |
| 147 | #[inline]
|
| 148 | pub const fn as_char_ptr(&self) -> *const core::ffi::c_char {
|
| 149 | self.0.as_ptr() as _
|
| 150 | }
|
| 151 |
|
| 152 | |
| 153 | #[inline]
|
| 154 | pub fn as_bytes(&self) -> &[u8] {
|
| 155 | &self.0[..self.len()]
|
| 156 | }
|
| 157 |
|
| 158 | |
| 159 | #[inline]
|
| 160 | pub const fn as_bytes_with_nul(&self) -> &[u8] {
|
| 161 | &self.0
|
| 162 | }
|
| 163 |
|
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | #[inline]
|
| 178 | pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
|
| 179 | core::str::from_utf8(self.as_bytes())
|
| 180 | }
|
| 181 |
|
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | #[inline]
|
| 200 | pub unsafe fn as_str_unchecked(&self) -> &str {
|
| 201 | unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
|
| 202 | }
|
| 203 |
|
| 204 | |
| 205 | |
| 206 | pub fn to_cstring(&self) -> Result<CString, AllocError> {
|
| 207 | CString::try_from(self)
|
| 208 | }
|
| 209 | }
|
| 210 |
|
| 211 | impl fmt::Display for CStr {
|
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 227 | for &c in self.as_bytes() {
|
| 228 | if (0x20..0x7f).contains(&c) {
|
| 229 | |
| 230 | f.write_char(c as char)?;
|
| 231 | } else {
|
| 232 | write!(f, "\\x{:02x}", c)?;
|
| 233 | }
|
| 234 | }
|
| 235 | Ok(())
|
| 236 | }
|
| 237 | }
|
| 238 |
|
| 239 | impl fmt::Debug for CStr {
|
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 256 | f.write_str("\"")?;
|
| 257 | for &c in self.as_bytes() {
|
| 258 | match c {
|
| 259 | |
| 260 | b'\"' => f.write_str("\\\"")?,
|
| 261 | 0x20..=0x7e => f.write_char(c as char)?,
|
| 262 | _ => write!(f, "\\x{:02x}", c)?,
|
| 263 | }
|
| 264 | }
|
| 265 | f.write_str("\"")
|
| 266 | }
|
| 267 | }
|
| 268 |
|
| 269 | impl AsRef<BStr> for CStr {
|
| 270 | #[inline]
|
| 271 | fn as_ref(&self) -> &BStr {
|
| 272 | self.as_bytes()
|
| 273 | }
|
| 274 | }
|
| 275 |
|
| 276 | impl Deref for CStr {
|
| 277 | type Target = BStr;
|
| 278 |
|
| 279 | #[inline]
|
| 280 | fn deref(&self) -> &Self::Target {
|
| 281 | self.as_bytes()
|
| 282 | }
|
| 283 | }
|
| 284 |
|
| 285 | impl Index<ops::RangeFrom<usize>> for CStr {
|
| 286 | type Output = CStr;
|
| 287 |
|
| 288 | #[inline]
|
| 289 | fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
|
| 290 | |
| 291 | |
| 292 | let _ = &self.as_bytes()[index.start..];
|
| 293 | |
| 294 | unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
|
| 295 | }
|
| 296 | }
|
| 297 |
|
| 298 | impl Index<ops::RangeFull> for CStr {
|
| 299 | type Output = CStr;
|
| 300 |
|
| 301 | #[inline]
|
| 302 | fn index(&self, _index: ops::RangeFull) -> &Self::Output {
|
| 303 | self
|
| 304 | }
|
| 305 | }
|
| 306 |
|
| 307 | mod private {
|
| 308 | use core::ops;
|
| 309 |
|
| 310 | |
| 311 | pub trait CStrIndex {}
|
| 312 |
|
| 313 | impl CStrIndex for usize {}
|
| 314 | impl CStrIndex for ops::Range<usize> {}
|
| 315 | impl CStrIndex for ops::RangeInclusive<usize> {}
|
| 316 | impl CStrIndex for ops::RangeToInclusive<usize> {}
|
| 317 | }
|
| 318 |
|
| 319 | impl<Idx> Index<Idx> for CStr
|
| 320 | where
|
| 321 | Idx: private::CStrIndex,
|
| 322 | BStr: Index<Idx>,
|
| 323 | {
|
| 324 | type Output = <BStr as Index<Idx>>::Output;
|
| 325 |
|
| 326 | #[inline]
|
| 327 | fn index(&self, index: Idx) -> &Self::Output {
|
| 328 | &self.as_bytes()[index]
|
| 329 | }
|
| 330 | }
|
| 331 |
|
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | #[macro_export]
|
| 344 | macro_rules! c_str {
|
| 345 | ($str:expr) => {{
|
| 346 | const S: &str = concat!($str, "\0");
|
| 347 | const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
|
| 348 | Ok(v) => v,
|
| 349 | Err(_) => panic!("string contains interior NUL"),
|
| 350 | };
|
| 351 | C
|
| 352 | }};
|
| 353 | }
|
| 354 |
|
| 355 | #[cfg(test)]
|
| 356 | mod tests {
|
| 357 | use super::*;
|
| 358 |
|
| 359 | #[test]
|
| 360 | fn test_cstr_to_str() {
|
| 361 | let good_bytes = b"\xf0\x9f\xa6\x80\0";
|
| 362 | let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
|
| 363 | let checked_str = checked_cstr.to_str().unwrap();
|
| 364 | assert_eq!(checked_str, "🦀");
|
| 365 | }
|
| 366 |
|
| 367 | #[test]
|
| 368 | #[should_panic]
|
| 369 | fn test_cstr_to_str_panic() {
|
| 370 | let bad_bytes = b"\xc3\x28\0";
|
| 371 | let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap();
|
| 372 | checked_cstr.to_str().unwrap();
|
| 373 | }
|
| 374 |
|
| 375 | #[test]
|
| 376 | fn test_cstr_as_str_unchecked() {
|
| 377 | let good_bytes = b"\xf0\x9f\x90\xA7\0";
|
| 378 | let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
|
| 379 | let unchecked_str = unsafe { checked_cstr.as_str_unchecked() };
|
| 380 | assert_eq!(unchecked_str, "🐧");
|
| 381 | }
|
| 382 | }
|
| 383 |
|
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | pub(crate) struct RawFormatter {
|
| 394 | |
| 395 | beg: usize,
|
| 396 | pos: usize,
|
| 397 | end: usize,
|
| 398 | }
|
| 399 |
|
| 400 | impl RawFormatter {
|
| 401 | |
| 402 | fn new() -> Self {
|
| 403 | |
| 404 | Self {
|
| 405 | beg: 0,
|
| 406 | pos: 0,
|
| 407 | end: 0,
|
| 408 | }
|
| 409 | }
|
| 410 |
|
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self {
|
| 418 | |
| 419 | Self {
|
| 420 | beg: pos as _,
|
| 421 | pos: pos as _,
|
| 422 | end: end as _,
|
| 423 | }
|
| 424 | }
|
| 425 |
|
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
|
| 433 | let pos = buf as usize;
|
| 434 | |
| 435 | |
| 436 | Self {
|
| 437 | pos,
|
| 438 | beg: pos,
|
| 439 | end: pos.saturating_add(len),
|
| 440 | }
|
| 441 | }
|
| 442 |
|
| 443 | |
| 444 | |
| 445 | |
| 446 | pub(crate) fn pos(&self) -> *mut u8 {
|
| 447 | self.pos as _
|
| 448 | }
|
| 449 |
|
| 450 | |
| 451 | pub(crate) fn bytes_written(&self) -> usize {
|
| 452 | self.pos - self.beg
|
| 453 | }
|
| 454 | }
|
| 455 |
|
| 456 | impl fmt::Write for RawFormatter {
|
| 457 | fn write_str(&mut self, s: &str) -> fmt::Result {
|
| 458 | |
| 459 | |
| 460 | let pos_new = self.pos.saturating_add(s.len());
|
| 461 |
|
| 462 | |
| 463 | let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos);
|
| 464 |
|
| 465 | if len_to_copy > 0 {
|
| 466 | |
| 467 | |
| 468 | unsafe {
|
| 469 | core::ptr::copy_nonoverlapping(
|
| 470 | s.as_bytes().as_ptr(),
|
| 471 | self.pos as *mut u8,
|
| 472 | len_to_copy,
|
| 473 | )
|
| 474 | };
|
| 475 | }
|
| 476 |
|
| 477 | self.pos = pos_new;
|
| 478 | Ok(())
|
| 479 | }
|
| 480 | }
|
| 481 |
|
| 482 | |
| 483 | |
| 484 | |
| 485 | pub(crate) struct Formatter(RawFormatter);
|
| 486 |
|
| 487 | impl Formatter {
|
| 488 | |
| 489 | |
| 490 | |
| 491 | |
| 492 | |
| 493 | |
| 494 | pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
|
| 495 | |
| 496 | Self(unsafe { RawFormatter::from_buffer(buf, len) })
|
| 497 | }
|
| 498 | }
|
| 499 |
|
| 500 | impl Deref for Formatter {
|
| 501 | type Target = RawFormatter;
|
| 502 |
|
| 503 | fn deref(&self) -> &Self::Target {
|
| 504 | &self.0
|
| 505 | }
|
| 506 | }
|
| 507 |
|
| 508 | impl fmt::Write for Formatter {
|
| 509 | fn write_str(&mut self, s: &str) -> fmt::Result {
|
| 510 | self.0.write_str(s)?;
|
| 511 |
|
| 512 | |
| 513 | if self.0.pos > self.0.end {
|
| 514 | Err(fmt::Error)
|
| 515 | } else {
|
| 516 | Ok(())
|
| 517 | }
|
| 518 | }
|
| 519 | }
|
| 520 |
|
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | pub struct CString {
|
| 546 | buf: Vec<u8>,
|
| 547 | }
|
| 548 |
|
| 549 | impl CString {
|
| 550 | |
| 551 | pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
|
| 552 | |
| 553 | let mut f = RawFormatter::new();
|
| 554 | f.write_fmt(args)?;
|
| 555 | f.write_str("\0")?;
|
| 556 | let size = f.bytes_written();
|
| 557 |
|
| 558 | |
| 559 | let mut buf = Vec::try_with_capacity(size)?;
|
| 560 | |
| 561 | let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
|
| 562 | f.write_fmt(args)?;
|
| 563 | f.write_str("\0")?;
|
| 564 |
|
| 565 | |
| 566 | |
| 567 | unsafe { buf.set_len(f.bytes_written()) };
|
| 568 |
|
| 569 | |
| 570 | |
| 571 | |
| 572 | |
| 573 | let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) };
|
| 574 | if !ptr.is_null() {
|
| 575 | return Err(EINVAL);
|
| 576 | }
|
| 577 |
|
| 578 | |
| 579 | |
| 580 | Ok(Self { buf })
|
| 581 | }
|
| 582 | }
|
| 583 |
|
| 584 | impl Deref for CString {
|
| 585 | type Target = CStr;
|
| 586 |
|
| 587 | fn deref(&self) -> &Self::Target {
|
| 588 | |
| 589 | |
| 590 | unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
|
| 591 | }
|
| 592 | }
|
| 593 |
|
| 594 | impl<'a> TryFrom<&'a CStr> for CString {
|
| 595 | type Error = AllocError;
|
| 596 |
|
| 597 | fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
|
| 598 | let mut buf = Vec::new();
|
| 599 |
|
| 600 | buf.try_extend_from_slice(cstr.as_bytes_with_nul())
|
| 601 | .map_err(|_| AllocError)?;
|
| 602 |
|
| 603 | |
| 604 | |
| 605 | Ok(CString { buf })
|
| 606 | }
|
| 607 | }
|
| 608 |
|
| 609 | |
| 610 | #[macro_export]
|
| 611 | macro_rules! fmt {
|
| 612 | ($($f:tt)*) => ( core::format_args!($($f)*) )
|
| 613 | }
|