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