1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 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 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 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 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 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 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 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 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 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 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
#![deny(unsafe_op_in_unsafe_fn)]
#[cfg(test)]
mod tests;
use crate::ascii;
use crate::borrow::{Borrow, Cow};
use crate::cmp::Ordering;
use crate::error::Error;
use crate::fmt::{self, Write};
use crate::io;
use crate::mem;
use crate::num::NonZeroU8;
use crate::ops;
use crate::os::raw::c_char;
use crate::ptr;
use crate::rc::Rc;
use crate::slice;
use crate::str::{self, Utf8Error};
use crate::sync::Arc;
use crate::sys;
use crate::sys_common::memchr;
/// 一种类型,表示拥有的,C 兼容的,以 nul 终止的字符串,中间没有 nul 字节。
///
/// 此类型的目的是能够从 Rust 字节切片或 vector 安全地生成 C 兼容字符串。
/// 此类型的一个实例是静态保证,底层字节不包含内部 0 字节 (`nul 字符`),并且最后一个字节为 0 (`nul 终止符`)。
///
/// `CString` 到 <code>&[CStr]</code> 如同 [`String`] 到 <code>&[str]</code>: 每对中的前者是拥有所有权的字符串; 后者是借用的。
///
/// # 创建一个 `CString`
///
/// `CString` 是从字节切片、字节 vector 或任何实现 <code>[Into]<[Vec]<[u8]>></code> 创建的 (例如,您可以直接从 [`String`] 或 <code>&[str]</code>,因为两者都实现了该 trait)。
///
///
/// [`CString::new`] 方法实际上会检查提供的 <code>&[[u8]]</code> 中是否没有 0 个字节,如果找到一个,将返回一个错误。
///
/// # 将裸指针提取到整个 C 字符串
///
/// `CString` 通过 [`Deref`] trait 实现了一个 [`as_ptr`][`CStr::as_ptr`] 方法。此方法将为您提供 `*const c_char`,您可以直接将其输入期望包含以 N 结束的字符串的 extern 函数,例如 C 的 `strdup()`。
/// 注意,[`as_ptr`][`CStr::as_ptr`] 返回一个只读指针。如果 C 代码写入它,则会导致未定义的行为。
///
/// # 提取整个 C 字符串的切片
///
/// 或者,您可以使用 [`CString::as_bytes`] 方法从 `CString` 获取 <code>&[[u8]]</code> 切片。以这种方式产生的切片不包含尾随 nul 终止符。
/// 当您要调用带有 `*const u8` 参数 (不一定是 nul 终止) 的 extern 函数,以及带有字符串长度的另一个参数 (如 C 的 `strndup()`) 时,此功能很有用。
/// 当然,您可以使用 [`len`][slice::len] 方法获取切片的长度。
///
/// 如果您需要一个带 nul 终止符的 <code>&[[u8]]</code> 切片,您可以使用 [`CString::as_bytes_with_nul`] 代替。
///
/// 一旦有了所需的切片类型 (带或不带 nul 终止符),就可以调用切片自己的 [`as_ptr`][slice::as_ptr] 方法来获取只读的裸指针,以将其传递给 extern 函数。
/// 有关确保裸指针的生命周期的讨论,请参见该函数的文档。
///
/// [str]: prim@str "str"
/// [`Deref`]: ops::Deref
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
/// use std::ffi::CString;
/// use std::os::raw::c_char;
///
/// extern "C" {
/// fn my_printer(s: *const c_char);
/// }
///
/// // 我们确定我们的字符串中间没有 0 个字节,因此我们可以 .expect()
/////
/// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
/// unsafe {
/// my_printer(c_to_print.as_ptr());
/// }
/// # }
/// ```
///
/// # Safety
///
/// `CString` 旨在处理传统的 C 样式字符串 (由单个空字节终止的非空字节序列) ; 这些类型的字符串的主要用例是与类似 C 的代码进行互操作。
/// 通常,您将需要转让该外部代码的所有权 to/from。
/// 强烈建议您在使用 `CString` 之前通读 `CString` 文档,因为对 `CString` 实例的所有权管理不当会导致无效的内存访问,内存泄漏和其他内存错误。
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
#[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct CString {
// 不变量 1: 切片以零字节结尾,长度至少为一。
// 不变量 2: 切片仅包含一个零字节。
// 错误使用不安全的函数会破坏不变量 2,但不会破坏不变量 1。
inner: Box<[u8]>,
}
/// 借用的 C 字符串的表示形式。
///
/// 此类型表示对以 n 结尾的字节数组的引用。
/// 它可以从一个 <code>&[[u8]]</code> 切片安全地构建,或者从原始 `*const c_char` 不安全地构建。
/// 然后可以通过执行 UTF-8 验证将其转换为 Rust <code>&[str]</code>,或转换为拥有所有权的 [`CString`]。
///
/// `&CStr` 对 [`CString`] 如同 <code>&[str]</code> 对 [`String`]: 每对中的前者都是借用的引用; 后者是拥有的字符串。
///
///
/// 请注意,此结构体不是 `repr(C)`,不建议放置在 FFI 函数的签名中。
/// 而是,FFI 函数的安全包装程序可以利用不安全的 [`CStr::from_ptr`] 构造函数为其他使用者提供安全的接口。
///
/// # Examples
///
/// 检查外部 C 字符串:
///
/// ```ignore (extern-declaration)
/// use std::ffi::CStr;
/// use std::os::raw::c_char;
///
/// extern "C" { fn my_string() -> *const c_char; }
///
/// unsafe {
/// let slice = CStr::from_ptr(my_string());
/// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
/// }
/// ```
///
/// 传递源自 Rust 的 C 字符串:
///
/// ```ignore (extern-declaration)
/// use std::ffi::{CString, CStr};
/// use std::os::raw::c_char;
///
/// fn work(data: &CStr) {
/// extern "C" { fn work_with(data: *const c_char); }
///
/// unsafe { work_with(data.as_ptr()) }
/// }
///
/// let s = CString::new("data data data data").expect("CString::new failed");
/// work(&s);
/// ```
///
/// 将外部 C 字符串转换为 Rust [`String`]:
///
/// ```ignore (extern-declaration)
/// use std::ffi::CStr;
/// use std::os::raw::c_char;
///
/// extern "C" { fn my_string() -> *const c_char; }
///
/// fn my_string_safe() -> String {
/// unsafe {
/// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
/// }
/// }
///
/// println!("string: {}", my_string_safe());
/// ```
///
/// [str]: prim@str "str"
///
///
///
///
///
#[derive(Hash)]
#[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
#[stable(feature = "rust1", since = "1.0.0")]
// FIXME:
// `impl From<&CStr> for Box<CStr>` 当前实现中的 `fn from` 依赖于 `CStr` 与 `[u8]` 布局兼容。
// 实现属性隐私时,应将 `CStr` 注解为 `#[repr(transparent)]`。
// 无论如何,`CStr` 表示形式和布局被视为实现细节,没有文档记录,因此不能依赖。
//
//
pub struct CStr {
// FIXME: 这不应该用 DST 切片来表示,而只能用原始 `c_char` 以及某种形式的标记将其表示为未定义大小的类型。
// 本质上,`sizeof(&CStr)` 应该与 `sizeof(&c_char)` 相同,但是 `CStr` 应该是未定义大小的类型。
//
//
inner: [c_char],
}
/// 指示发现内部 nul 字节的错误。
///
/// 尽管 Rust 字符串的中间可能包含 nul 个字节,但 C 字符串却不能,因为该字节会有效地截断该字符串。
///
///
/// 该错误是由 [`CString`] 上的 [`new`][`CString::new`] 方法创建的。有关更多信息,请参见其文档。
///
/// # Examples
///
/// ```
/// use std::ffi::{CString, NulError};
///
/// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
/// ```
///
#[derive(Clone, PartialEq, Eq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct NulError(usize, Vec<u8>);
/// 指示 nul 字节不在预期位置中的错误。
///
/// 用于创建 [`CStr`] 的切片必须位于末尾且只有一个 nul 字节。
///
///
/// 此错误是由 [`CStr::from_bytes_with_nul`] 方法创建的。
/// 有关更多信息,请参见其文档。
///
/// # Examples
///
/// ```
/// use std::ffi::{CStr, FromBytesWithNulError};
///
/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
/// ```
#[derive(Clone, PartialEq, Eq, Debug)]
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
pub struct FromBytesWithNulError {
kind: FromBytesWithNulErrorKind,
}
/// 指示 nul 字节不在预期位置中的错误。
///
/// 用于创建 [`CString`] 的 vector 的末尾必须只有一个 nul 字节。
///
///
/// 此错误是由 [`CString::from_vec_with_nul`] 方法创建的。
/// 有关更多信息,请参见其文档。
///
/// # Examples
///
/// ```
/// use std::ffi::{CString, FromVecWithNulError};
///
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
/// ```
#[derive(Clone, PartialEq, Eq, Debug)]
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
pub struct FromVecWithNulError {
error_kind: FromBytesWithNulErrorKind,
bytes: Vec<u8>,
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum FromBytesWithNulErrorKind {
InteriorNul(usize),
NotNulTerminated,
}
impl FromBytesWithNulError {
fn interior_nul(pos: usize) -> FromBytesWithNulError {
FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
}
fn not_nul_terminated() -> FromBytesWithNulError {
FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
}
}
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
impl FromVecWithNulError {
/// 返回试图转换为 [`CString`] 的 [u8] 个字节的切片。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// use std::ffi::CString;
///
/// // vector 中的一些无效字节
/// let bytes = b"f\0oo".to_vec();
///
/// let value = CString::from_vec_with_nul(bytes.clone());
///
/// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
/// ```
#[must_use]
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..]
}
/// 返回尝试转换为 [`CString`] 的字节。
///
/// 精心构造此方法以避免分配。
/// 它将消耗错误,将字节移出,因此不需要制作字节的副本。
///
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// use std::ffi::CString;
///
/// // vector 中的一些无效字节
/// let bytes = b"f\0oo".to_vec();
///
/// let value = CString::from_vec_with_nul(bytes.clone());
///
/// assert_eq!(bytes, value.unwrap_err().into_bytes());
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
/// 将 [`CString`] 转换为 [`String`] 时,指示 UTF-8 无效的错误。
///
/// `CString` 只是一个带有 nul 终止符的字节缓冲区的包装器;
/// [`CString::into_string`] 对这些字节执行 UTF-8 验证,并可能返回此错误。
///
///
/// 该 `struct` 由 [`CString::into_string()`] 创建。有关更多信息,请参见其文档。
///
#[derive(Clone, PartialEq, Eq, Debug)]
#[stable(feature = "cstring_into", since = "1.7.0")]
pub struct IntoStringError {
inner: CString,
error: Utf8Error,
}
impl CString {
/// 从字节容器创建一个新的 C 兼容字符串。
///
/// 此函数将消费提供的数据,并使用底层字节构建新的字符串,从而确保有一个尾随的 0 字节。
///
/// 这个函数将追加这个尾随的 0 字节; 提供的数据不应包含任何 0 字节。
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// use std::ffi::CString;
/// use std::os::raw::c_char;
///
/// extern "C" { fn puts(s: *const c_char); }
///
/// let to_print = CString::new("Hello!").expect("CString::new failed");
/// unsafe {
/// puts(to_print.as_ptr());
/// }
/// ```
///
/// # Errors
///
/// 如果提供的字节包含内部 0 字节,则此函数将返回错误。
/// 返回的 [`NulError`] 将包含字节以及 nul 字节的位置。
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
trait SpecIntoVec {
fn into_vec(self) -> Vec<u8>;
}
impl<T: Into<Vec<u8>>> SpecIntoVec for T {
default fn into_vec(self) -> Vec<u8> {
self.into()
}
}
// 避免重新分配的专业化。
impl SpecIntoVec for &'_ [u8] {
fn into_vec(self) -> Vec<u8> {
let mut v = Vec::with_capacity(self.len() + 1);
v.extend(self);
v
}
}
impl SpecIntoVec for &'_ str {
fn into_vec(self) -> Vec<u8> {
let mut v = Vec::with_capacity(self.len() + 1);
v.extend(self.as_bytes());
v
}
}
Self::_new(SpecIntoVec::into_vec(t))
}
fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
match memchr::memchr(0, &bytes) {
Some(i) => Err(NulError(i, bytes)),
None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
}
}
/// 通过使用字节 vector 来创建 C 兼容字符串,而无需检查内部 0 字节。
///
/// 该函数将追加尾随的 0 字节。
///
/// 此方法等效于 [`CString::new`],除了不进行运行时断言,即 `v` 不包含 0 字节,并且它需要实际的字节 vector,而不是可以使用 Into 转换为 1 的任何内容。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let raw = b"foo".to_vec();
/// unsafe {
/// let c_string = CString::from_vec_unchecked(raw);
/// }
/// ```
///
///
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
v.reserve_exact(1);
v.push(0);
CString { inner: v.into_boxed_slice() }
}
/// 重新获得通过 [`CString::into_raw`] 转移到 C 的 `CString` 的所有权。
///
/// 此外,将根据指针重新计算字符串的长度。
///
/// # Safety
///
/// 仅应使用先前通过调用 [`CString::into_raw`] 获得的指针进行调用。
/// 其他用法 (例如,尝试获取由外部代码分配的字符串的所有权) 可能导致未定义的行为或分配器损坏。
///
/// 应该注意的是,长度不仅是 "recomputed,",而且重新计算的长度必须与 [`CString::into_raw`] 调用的原始长度匹配。
///
/// 这意味着在将字符串传递到可以修改字符串长度的 C 函数时,不应使用 [`CString::into_raw`]/`from_raw` 方法。
///
/// > **Note:** 如果您需要借用由分配的字符串
/// > 外部代码,请使用 [`CStr`]。如果您需要获得所有权从
/// > 由外部代码分配的字符串,您将需要
/// > 制定自己的规定以适当地,可能地释放它
/// > 使用外部代码的 API 来做到这一点。
///
/// # Examples
///
/// 创建一个 `CString`,将所有权传递给 `extern` 函数 (通过裸指针),然后使用 `from_raw` 重新获得所有权:
///
/// ```ignore (extern-declaration)
/// use std::ffi::CString;
/// use std::os::raw::c_char;
///
/// extern "C" {
/// fn some_extern_function(s: *mut c_char);
/// }
///
/// let c_string = CString::new("Hello!").expect("CString::new failed");
/// let raw = c_string.into_raw();
/// unsafe {
/// some_extern_function(raw);
/// let c_string = CString::from_raw(raw);
/// }
/// ```
///
///
///
///
///
///
#[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
#[stable(feature = "cstr_memory", since = "1.4.0")]
pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
// SAFETY: 这是通过从 `CString::into_raw` 调用获得的指针来调用的,并且长度没有被修改。
// 因此,我们知道在末尾有一个 NUL 字节 (只有一个),并且有关分配大小的信息在 Rust 侧是正确的。
//
//
//
unsafe {
let len = sys::strlen(ptr) + 1; // 包括 NUL 字节
let slice = slice::from_raw_parts_mut(ptr, len as usize);
CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
}
}
/// 消耗 `CString`,并将字符串的所有权转让给 C 调用者。
///
/// 此函数返回的指针必须返回到 Rust,并使用 [`CString::from_raw`] 进行重构以正确释放。
/// 具体来说,应该 *不要* 使用标准的 C `free()` 函数来释放该字符串。
///
/// 未能调用 [`CString::from_raw`] 将导致内存泄漏。
///
/// C 端必须**不**修改字符串的长度 (通过在字符串内某处写入 `null` 或删除最后一个),然后使用 [`CString::from_raw`] 将其返回到 Rust。
///
/// 请参见 [`CString::from_raw`] 中的安全性部分。
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
///
/// let ptr = c_string.into_raw();
///
/// unsafe {
/// assert_eq!(b'f', *ptr as u8);
/// assert_eq!(b'o', *ptr.offset(1) as u8);
/// assert_eq!(b'o', *ptr.offset(2) as u8);
/// assert_eq!(b'\0', *ptr.offset(3) as u8);
///
/// // 重新获得指向空闲内存的指针
/// let _ = CString::from_raw(ptr);
/// }
/// ```
///
///
///
#[inline]
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "cstr_memory", since = "1.4.0")]
pub fn into_raw(self) -> *mut c_char {
Box::into_raw(self.into_inner()) as *mut c_char
}
/// 如果 `CString` 包含有效的 UTF-8 数据,则将其转换为 [`String`]。
///
/// 失败时,将返回原始 `CString` 的所有权。
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let valid_utf8 = vec![b'f', b'o', b'o'];
/// let cstring = CString::new(valid_utf8).expect("CString::new failed");
/// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
///
/// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
/// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
/// let err = cstring.into_string().err().expect("into_string().err() failed");
/// assert_eq!(err.utf8_error().valid_up_to(), 1);
/// ```
#[stable(feature = "cstring_into", since = "1.7.0")]
pub fn into_string(self) -> Result<String, IntoStringError> {
String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
error: e.utf8_error(),
inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
})
}
/// 消耗 `CString` 并返回底层的字节缓冲区。
///
/// 返回的缓冲区不包含尾随 nul 终止符,并且保证不包含任何内部 nul 字节。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let bytes = c_string.into_bytes();
/// assert_eq!(bytes, vec![b'f', b'o', b'o']);
/// ```
///
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "cstring_into", since = "1.7.0")]
pub fn into_bytes(self) -> Vec<u8> {
let mut vec = self.into_inner().into_vec();
let _nul = vec.pop();
debug_assert_eq!(_nul, Some(0u8));
vec
}
/// 等效于 [`CString::into_bytes()`],除了返回的 vector 包括结尾的 nul 终止符。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let bytes = c_string.into_bytes_with_nul();
/// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "cstring_into", since = "1.7.0")]
pub fn into_bytes_with_nul(self) -> Vec<u8> {
self.into_inner().into_vec()
}
/// 以字节片形式返回此 `CString` 的内容。
///
/// 返回的切片不包含尾随 nul 终止符,并且保证不包含任何内部 nul 字节。
/// 如果需要 nul 终止符,请改用 [`CString::as_bytes_with_nul`]。
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let bytes = c_string.as_bytes();
/// assert_eq!(bytes, &[b'f', b'o', b'o']);
/// ```
///
///
#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_bytes(&self) -> &[u8] {
// SAFETY: CString 的长度至少为 1
unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
}
/// 等效于 [`CString::as_bytes()`],但返回的切片包括结尾的 nul 终止符。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let bytes = c_string.as_bytes_with_nul();
/// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
/// ```
#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_bytes_with_nul(&self) -> &[u8] {
&self.inner
}
/// 提取包含整个字符串的 [`CStr`] 切片。
///
/// # Examples
///
/// ```
/// use std::ffi::{CString, CStr};
///
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
/// let cstr = c_string.as_c_str();
/// assert_eq!(cstr,
/// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
/// ```
#[inline]
#[must_use]
#[stable(feature = "as_c_str", since = "1.20.0")]
pub fn as_c_str(&self) -> &CStr {
&*self
}
/// 将此 `CString` 转换为 boxed [`CStr`]。
///
/// # Examples
///
/// ```
/// use std::ffi::{CString, CStr};
///
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
/// let boxed = c_string.into_boxed_c_str();
/// assert_eq!(&*boxed,
/// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
pub fn into_boxed_c_str(self) -> Box<CStr> {
unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
}
/// 绕过 "move out of struct which implements [`Drop`] trait" 的限制。
#[inline]
fn into_inner(self) -> Box<[u8]> {
// 理由: `mem::forget(self)` 使对 `ptr::read(&self.inner)` 的先前调用无效,因此我们使用 `ManuallyDrop` 来确保不删除 `self`。
//
// 然后我们可以直接返回 box 而不会使其无效。请参见 https://github.com/rust-lang/rust/issues/62553。
//
let this = mem::ManuallyDrop::new(self);
unsafe { ptr::read(&this.inner) }
}
/// 将 <code>[Vec]<[u8]></code> 转换为 [`CString`],而不检查给定的 [`Vec`] 上的不变量。
///
///
/// # Safety
///
/// 给定的 [`Vec`] 必须最后一个元素为一个 nul 字节。
/// 这意味着它不能为空,也不能在其他任何地方有任何其他 nul 字节。
///
/// # Example
///
/// ```
/// use std::ffi::CString;
/// assert_eq!(
/// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
/// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
/// );
/// ```
#[must_use]
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
Self { inner: v.into_boxed_slice() }
}
/// 尝试将 <code>[Vec]<[u8]></code> 转换为 [`CString`]。
///
/// 存在运行时检查以确保 [`Vec`] (它的最后一个元素) 中只有一个 nul 字节。
///
/// # Errors
///
/// 如果存在 nul 字节而不是最后一个元素,或者不存在 nul 字节,则将返回错误。
///
/// # Examples
///
/// 如果调用成功而没有结尾的 nul 字节,则转换将产生与 [`CString::new`] 相同的结果。
///
///
/// ```
/// use std::ffi::CString;
/// assert_eq!(
/// CString::from_vec_with_nul(b"abc\0".to_vec())
/// .expect("CString::from_vec_with_nul failed"),
/// CString::new(b"abc".to_vec()).expect("CString::new failed")
/// );
/// ```
///
/// 格式不正确的 [`Vec`] 会产生错误。
///
/// ```
/// use std::ffi::{CString, FromVecWithNulError};
/// // 内部 nul 字节
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
/// // 无空字节
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
/// ```
///
///
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
let nul_pos = memchr::memchr(0, &v);
match nul_pos {
Some(nul_pos) if nul_pos + 1 == v.len() => {
// SAFETY: 我们知道在 vec 的末尾只有一个 nul 字节。
//
Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
}
Some(nul_pos) => Err(FromVecWithNulError {
error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
bytes: v,
}),
None => Err(FromVecWithNulError {
error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
bytes: v,
}),
}
}
}
// 将此 `CString` 转换为空字符串,以防止意外执行内存不安全代码。
// 内联以防止 LLVM 在调试版本中进行优化。
//
#[stable(feature = "cstring_drop", since = "1.13.0")]
impl Drop for CString {
#[inline]
fn drop(&mut self) {
unsafe {
*self.inner.get_unchecked_mut(0) = 0;
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for CString {
type Target = CStr;
#[inline]
fn deref(&self) -> &CStr {
unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for CString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "cstring_into", since = "1.7.0")]
impl From<CString> for Vec<u8> {
/// 将 [`CString`] 转换为 <code>[Vec]<[u8]></code>。
///
/// 转换消耗 [`CString`],并删除终止的 NUL 字节。
#[inline]
fn from(s: CString) -> Vec<u8> {
s.into_bytes()
}
}
#[stable(feature = "cstr_debug", since = "1.3.0")]
impl fmt::Debug for CStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"")?;
for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
f.write_char(byte as char)?;
}
write!(f, "\"")
}
}
#[stable(feature = "cstr_default", since = "1.10.0")]
impl Default for &CStr {
fn default() -> Self {
const SLICE: &[c_char] = &[0];
unsafe { CStr::from_ptr(SLICE.as_ptr()) }
}
}
#[stable(feature = "cstr_default", since = "1.10.0")]
impl Default for CString {
/// 创建一个空的 `CString`。
fn default() -> CString {
let a: &CStr = Default::default();
a.to_owned()
}
}
#[stable(feature = "cstr_borrow", since = "1.3.0")]
impl Borrow<CStr> for CString {
#[inline]
fn borrow(&self) -> &CStr {
self
}
}
#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
impl<'a> From<Cow<'a, CStr>> for CString {
#[inline]
fn from(s: Cow<'a, CStr>) -> Self {
s.into_owned()
}
}
#[stable(feature = "box_from_c_str", since = "1.17.0")]
impl From<&CStr> for Box<CStr> {
fn from(s: &CStr) -> Box<CStr> {
let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
}
}
#[stable(feature = "box_from_cow", since = "1.45.0")]
impl From<Cow<'_, CStr>> for Box<CStr> {
#[inline]
fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
match cow {
Cow::Borrowed(s) => Box::from(s),
Cow::Owned(s) => Box::from(s),
}
}
}
#[stable(feature = "c_string_from_box", since = "1.18.0")]
impl From<Box<CStr>> for CString {
/// 将 <code>[Box]<[CStr]></code> 转换为 [`CString`],无需复制或分配。
#[inline]
fn from(s: Box<CStr>) -> CString {
s.into_c_string()
}
}
#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
impl From<Vec<NonZeroU8>> for CString {
/// 将 <code>[Vec]<[NonZeroU8]></code> 转换为 [`CString`],无需复制或检查内部空字节。
///
#[inline]
fn from(v: Vec<NonZeroU8>) -> CString {
unsafe {
// 将 `Vec<NonZeroU8>` 转换为 `Vec<u8>`。
let v: Vec<u8> = {
// SAFETY:
// - `NonZeroU8` 和 `u8` 之间的转换是声音;
// - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
};
// SAFETY: 给定 `NonZeroU8` 的类型级别不变性,`v` 不能包含空字节。
//
CString::from_vec_unchecked(v)
}
}
}
#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
impl Clone for Box<CStr> {
#[inline]
fn clone(&self) -> Self {
(**self).into()
}
}
#[stable(feature = "box_from_c_string", since = "1.20.0")]
impl From<CString> for Box<CStr> {
/// 将 [`CString`] 转换为 <code>[Box]<[CStr]></code>,无需复制或分配。
#[inline]
fn from(s: CString) -> Box<CStr> {
s.into_boxed_c_str()
}
}
#[stable(feature = "cow_from_cstr", since = "1.28.0")]
impl<'a> From<CString> for Cow<'a, CStr> {
/// 无需复制或分配即可将 [`CString`] 转换为拥有所有权的 [`Cow`]。
#[inline]
fn from(s: CString) -> Cow<'a, CStr> {
Cow::Owned(s)
}
}
#[stable(feature = "cow_from_cstr", since = "1.28.0")]
impl<'a> From<&'a CStr> for Cow<'a, CStr> {
/// 将 [`CStr`] 转换为借用的 [`Cow`],无需复制或分配。
#[inline]
fn from(s: &'a CStr) -> Cow<'a, CStr> {
Cow::Borrowed(s)
}
}
#[stable(feature = "cow_from_cstr", since = "1.28.0")]
impl<'a> From<&'a CString> for Cow<'a, CStr> {
/// 将 `&`[`CString`] 转换为借用的 [`Cow`],无需复制或分配。
#[inline]
fn from(s: &'a CString) -> Cow<'a, CStr> {
Cow::Borrowed(s.as_c_str())
}
}
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
impl From<CString> for Arc<CStr> {
/// 将 [`CString`] 转换为 <code>[Arc]<[CStr]></code>,无需复制或分配。
#[inline]
fn from(s: CString) -> Arc<CStr> {
let arc: Arc<[u8]> = Arc::from(s.into_inner());
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
}
}
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
impl From<&CStr> for Arc<CStr> {
#[inline]
fn from(s: &CStr) -> Arc<CStr> {
let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
}
}
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
impl From<CString> for Rc<CStr> {
/// 将 [`CString`] 转换为 <code>[Rc]<[CStr]></code>,无需复制或分配。
#[inline]
fn from(s: CString) -> Rc<CStr> {
let rc: Rc<[u8]> = Rc::from(s.into_inner());
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
}
}
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
impl From<&CStr> for Rc<CStr> {
#[inline]
fn from(s: &CStr) -> Rc<CStr> {
let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
}
}
#[stable(feature = "default_box_extra", since = "1.17.0")]
impl Default for Box<CStr> {
fn default() -> Box<CStr> {
let boxed: Box<[u8]> = Box::from([0]);
unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
}
}
impl NulError {
/// 返回导致 [`CString::new`] 失败的切片中 nul 字节的位置。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let nul_error = CString::new("foo\0bar").unwrap_err();
/// assert_eq!(nul_error.nul_position(), 3);
///
/// let nul_error = CString::new("foo bar\0").unwrap_err();
/// assert_eq!(nul_error.nul_position(), 7);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn nul_position(&self) -> usize {
self.0
}
/// 消耗此错误,返回底层的 vector 字节,该字节首先生成错误。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let nul_error = CString::new("foo\0bar").unwrap_err();
/// assert_eq!(nul_error.into_vec(), b"foo\0bar");
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_vec(self) -> Vec<u8> {
self.1
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for NulError {
#[allow(deprecated)]
fn description(&self) -> &str {
"nul byte found in data"
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for NulError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "nul byte found in provided data at position: {}", self.0)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl From<NulError> for io::Error {
/// 将 [`NulError`] 转换为 [`io::Error`]。
fn from(_: NulError) -> io::Error {
io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
}
}
#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
impl Error for FromBytesWithNulError {
#[allow(deprecated)]
fn description(&self) -> &str {
match self.kind {
FromBytesWithNulErrorKind::InteriorNul(..) => {
"data provided contains an interior nul byte"
}
FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
}
}
}
#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
impl fmt::Display for FromBytesWithNulError {
#[allow(deprecated, deprecated_in_future)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.description())?;
if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
write!(f, " at byte pos {}", pos)?;
}
Ok(())
}
}
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
impl Error for FromVecWithNulError {}
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
impl fmt::Display for FromVecWithNulError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.error_kind {
FromBytesWithNulErrorKind::InteriorNul(pos) => {
write!(f, "data provided contains an interior nul byte at pos {}", pos)
}
FromBytesWithNulErrorKind::NotNulTerminated => {
write!(f, "data provided is not nul terminated")
}
}
}
}
impl IntoStringError {
/// 消耗此错误,返回产生错误的原始 [`CString`]。
///
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "cstring_into", since = "1.7.0")]
pub fn into_cstring(self) -> CString {
self.inner
}
/// 访问根本的 UTF-8 错误,该错误是引起此错误的原因。
#[must_use]
#[stable(feature = "cstring_into", since = "1.7.0")]
pub fn utf8_error(&self) -> Utf8Error {
self.error
}
}
#[stable(feature = "cstring_into", since = "1.7.0")]
impl Error for IntoStringError {
#[allow(deprecated)]
fn description(&self) -> &str {
"C string contained non-utf8 bytes"
}
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.error)
}
}
#[stable(feature = "cstring_into", since = "1.7.0")]
impl fmt::Display for IntoStringError {
#[allow(deprecated, deprecated_in_future)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.description().fmt(f)
}
}
impl CStr {
/// 用安全的 C 字符串包装器包装原始 C 字符串。
///
/// 此函数将使用 `CStr` 包装器包装提供的 `ptr`,从而允许检查和互操作非所有的 C 字符串。
/// 由于调用了 `slice::from_raw_parts` 函数,原始 C 字符串的总大小必须小于 `isize::MAX` 字节` 在内存中。
///
/// 由于多种原因,此方法不安全:
///
/// * 不能保证 `ptr` 的有效性。
/// * 不能保证返回的生命周期是 `ptr` 的实际生命周期。
/// * 不能保证 `ptr` 指向的内存在字符串末尾包含有效的 nul 终止符字节。
/// * 不能保证 `ptr` 指向的内存在 `CStr` 被销毁之前不会改变。
///
/// > **Note**: 该操作原定为零成本投放,但
/// > 目前已通过预先计算长度来实现
/// > 字符串。不能保证总是这样。
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// # fn main() {
/// use std::ffi::CStr;
/// use std::os::raw::c_char;
///
/// extern "C" {
/// fn my_string() -> *const c_char;
/// }
///
/// unsafe {
/// let slice = CStr::from_ptr(my_string());
/// println!("string returned: {}", slice.to_str().unwrap());
/// }
/// # }
/// ```
///
///
///
///
#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
// SAFETY: 调用者提供了一个指针,该指针指向大小小于 `isize::MAX` 的 NUL 终止符的有效 C 字符串,其内容保持有效,并且对于返回的 `CStr` 的生命周期不会更改。
//
//
// 这样计算长度就可以了 (存在一个 NUL 字节),对 from_raw_parts 的调用是安全的,因为我们知道长度最多为 `isize::MAX`,这意味着对 `from_bytes_with_nul_unchecked` 的调用是正确的。
//
// 从 c_char 到 u8 的转换是可以的,因为 c_char 始终是一个字节。
//
//
//
//
unsafe {
let len = sys::strlen(ptr);
let ptr = ptr as *const u8;
CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
}
}
/// 从字节切片创建 C 字符串包装器。
///
/// 在确保字节切片以 nul 终止并且不包含任何内部 nul 字节之后,此函数会将提供的 `bytes` 强制转换为 `CStr` 包装器。
///
///
/// # Examples
///
/// ```
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"hello\0");
/// assert!(cstr.is_ok());
/// ```
///
/// 创建没有尾随 nul 终止符的 `CStr` 是错误的:
///
/// ```
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"hello");
/// assert!(cstr.is_err());
/// ```
///
/// 使用内部 nul 字节创建 `CStr` 是错误的:
///
/// ```
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
/// assert!(cstr.is_err());
/// ```
///
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
let nul_pos = memchr::memchr(0, bytes);
if let Some(nul_pos) = nul_pos {
if nul_pos + 1 != bytes.len() {
return Err(FromBytesWithNulError::interior_nul(nul_pos));
}
Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
} else {
Err(FromBytesWithNulError::not_nul_terminated())
}
}
/// 从字节切片不安全地创建 C 字符串包装器。
///
/// 此函数会将提供的 `bytes` 强制转换为 `CStr` 包装器,而无需执行任何健全性检查。
/// 所提供的切片必须以 nul 结尾,并且不包含任何内部 nul 字节。
///
/// # Examples
///
/// ```
/// use std::ffi::{CStr, CString};
///
/// unsafe {
/// let cstring = CString::new("hello").expect("CString::new failed");
/// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
/// assert_eq!(cstr, &*cstring);
/// }
/// ```
///
#[inline]
#[must_use]
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
#[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
// SAFETY: 强制转换为 CStr 是安全的,因为其内部表示形式也是 [u8] (仅在 std 内部安全)。
//
// 解引用获得的指针是安全的,因为它来自引用。
// 这样,进行引用是安全的,因为其生命周期受给定 `bytes` 的生命周期的约束。
//
unsafe { &*(bytes as *const [u8] as *const CStr) }
}
/// 返回此 C 字符串的内部指针。
///
/// 返回的指针在 `self` 内一直有效,并且指向以 0 字节结尾的连续区域,以表示字符串的结尾。
///
/// **WARNING**
///
/// 返回的指针是只读的; 对其进行写入 (包括将其传递给进行写入的 C 代码) 会导致未定义的行为。
///
/// 您有责任确保底层内存不会过早释放。例如,当在 `unsafe` 块中使用 `ptr` 时,以下代码将导致未定义的行为:
///
/// ```no_run
/// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
/// use std::ffi::CString;
///
/// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
/// unsafe {
/// // `ptr` 是悬垂的
/// *ptr;
/// }
/// ```
///
/// 发生这种情况是因为 `as_ptr` 返回的指针不携带任何生命周期信息,并且在评估 `CString::new("Hello").expect("CString::new failed").as_ptr()` 表达式后立即释放了 [`CString`]。
///
/// 要解决此问题,请将 `CString` 绑定到本地变量:
///
/// ```no_run
/// # #![allow(unused_must_use)]
/// use std::ffi::CString;
///
/// let hello = CString::new("Hello").expect("CString::new failed");
/// let ptr = hello.as_ptr();
/// unsafe {
/// // `ptr` 有效,因为 `hello` 在作用域内
/// *ptr;
/// }
/// ```
///
/// 这样,`hello` 中 [`CString`] 的生命周期包含 `ptr` 和 `unsafe` 块的生命周期。
///
///
///
///
///
///
///
///
#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
pub const fn as_ptr(&self) -> *const c_char {
self.inner.as_ptr()
}
/// 将此 C 字符串转换为字节片。
///
/// 返回的切片将不包含此 C 字符串具有的尾随 nul 终止符。
///
///
/// > **Note**: 该方法当前被实现为恒定时间
/// > 强制转换,但计划将其在 future 中的定义更改为
/// > 每当调用此方法时,都要执行长度计算。
///
/// # Examples
///
/// ```
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
/// assert_eq!(cstr.to_bytes(), b"foo");
/// ```
#[inline]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_bytes(&self) -> &[u8] {
let bytes = self.to_bytes_with_nul();
// SAFETY: to_bytes_with_nul 返回长度至少为 1 的字节
unsafe { bytes.get_unchecked(..bytes.len() - 1) }
}
/// 将此 C 字符串转换为包含尾随 0 字节的字节切片。
///
/// 此函数与 [`CStr::to_bytes`] 等效,除了保留尾随的 nul 终止符而不是将其截断之外。
///
///
/// > **Note**: 目前,此方法已实现为零费用强制转换,但是
/// > 计划在 future 中更改其定义以执行
/// > 每次调用此方法时的长度计算。
///
/// # Examples
///
/// ```
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
/// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
/// ```
#[inline]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_bytes_with_nul(&self) -> &[u8] {
unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
}
/// 如果 `CStr` 包含有效的 UTF-8,则产生 <code>&[str]</code> 切片。
///
/// 如果 `CStr` 的内容是有效的 UTF-8 数据,该函数将返回相应的 <code>&[str]</code> 切片。
///
/// 否则,它将返回错误,并详细说明 UTF-8 验证失败的位置。
///
/// [str]: prim@str "str"
///
/// # Examples
///
/// ```
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
/// assert_eq!(cstr.to_str(), Ok("foo"));
/// ```
#[stable(feature = "cstr_to_str", since = "1.4.0")]
pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
// 注意,将 `CStr` 更改为在 `.to_bytes()` 中而不是 `from_ptr()` 中执行长度检查时,可能值得考虑是否应该重写此代码,以便在进行长度计算时内联 UTF-8 检查,而不是随后进行。
//
//
//
str::from_utf8(self.to_bytes())
}
/// 将 `CStr` 转换为 <code>[Cow]<[str]></code>。
///
/// 如果 `CStr` 的内容是有效的 UTF-8 数据,该函数将返回一个 <code>[Cow]::[Borrowed]\(&[str])</code> 和相应的 <code>&[str]</code> 切片。
/// 否则,它将用 [`U+FFFD 替换字符`][U+FFFD] 替换任何无效的 UTF-8 序列,并返回 <code>[Cow]::[Owned]\(&[str])</code> 作为结果。
///
/// [str]: prim@str "str"
/// [Borrowed]: Cow::Borrowed
/// [Owned]: Cow::Owned
/// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER "std::char::REPLACEMENT_CHARACTER"
///
/// # Examples
///
/// 在包含有效 UTF-8 的 `CStr` 上调用 `to_string_lossy`:
///
/// ```
/// use std::borrow::Cow;
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
/// .expect("CStr::from_bytes_with_nul failed");
/// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
/// ```
///
/// 在包含无效 UTF-8 的 `CStr` 上调用 `to_string_lossy`:
///
/// ```
/// use std::borrow::Cow;
/// use std::ffi::CStr;
///
/// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
/// .expect("CStr::from_bytes_with_nul failed");
/// assert_eq!(
/// cstr.to_string_lossy(),
/// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
/// );
/// ```
///
///
///
///
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[stable(feature = "cstr_to_str", since = "1.4.0")]
pub fn to_string_lossy(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.to_bytes())
}
/// 将 <code>[Box]<[CStr]></code> 转换为 [`CString`],无需复制或分配。
///
/// # Examples
///
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
/// let boxed = c_string.into_boxed_c_str();
/// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
pub fn into_c_string(self: Box<CStr>) -> CString {
let raw = Box::into_raw(self) as *mut [u8];
CString { inner: unsafe { Box::from_raw(raw) } }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for CStr {
fn eq(&self, other: &CStr) -> bool {
self.to_bytes().eq(other.to_bytes())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for CStr {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for CStr {
fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
self.to_bytes().partial_cmp(&other.to_bytes())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for CStr {
fn cmp(&self, other: &CStr) -> Ordering {
self.to_bytes().cmp(&other.to_bytes())
}
}
#[stable(feature = "cstr_borrow", since = "1.3.0")]
impl ToOwned for CStr {
type Owned = CString;
fn to_owned(&self) -> CString {
CString { inner: self.to_bytes_with_nul().into() }
}
fn clone_into(&self, target: &mut CString) {
let mut b = Vec::from(mem::take(&mut target.inner));
self.to_bytes_with_nul().clone_into(&mut b);
target.inner = b.into_boxed_slice();
}
}
#[stable(feature = "cstring_asref", since = "1.7.0")]
impl From<&CStr> for CString {
fn from(s: &CStr) -> CString {
s.to_owned()
}
}
#[stable(feature = "cstring_asref", since = "1.7.0")]
impl ops::Index<ops::RangeFull> for CString {
type Output = CStr;
#[inline]
fn index(&self, _index: ops::RangeFull) -> &CStr {
self
}
}
#[stable(feature = "cstr_range_from", since = "1.47.0")]
impl ops::Index<ops::RangeFrom<usize>> for CStr {
type Output = CStr;
fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
let bytes = self.to_bytes_with_nul();
// 我们需要手动检查起始索引来说明空字节,因为否则我们会得到一个不以空结尾的空字符串。
//
//
if index.start < bytes.len() {
unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
} else {
panic!(
"index out of bounds: the len is {} but the index is {}",
bytes.len(),
index.start
);
}
}
}
#[stable(feature = "cstring_asref", since = "1.7.0")]
impl AsRef<CStr> for CStr {
#[inline]
fn as_ref(&self) -> &CStr {
self
}
}
#[stable(feature = "cstring_asref", since = "1.7.0")]
impl AsRef<CStr> for CString {
#[inline]
fn as_ref(&self) -> &CStr {
self
}
}