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
#[cfg(test)]
mod tests;
use crate::convert::From;
use crate::error;
use crate::fmt;
use crate::result;
use crate::sys;
/// I/O 操作的专用 [`Result`] 类型。
///
/// [`std::io`] 广泛使用此类型进行可能产生错误的任何操作。
///
/// 通常使用这种 typedef 来避免直接写出 [`io::Error`],否则直接映射到 [`Result`]。
///
/// 通常的 Rust 样式是直接导入类型,而 [`Result`] 的别名通常不是,以便于区分它们。
/// [`Result`] 通常被假定为 [`std::result::Result`][`Result`],因此这个别名的用户通常会使用 `io::Result` 而不是隐藏 [prelude] 对 [`std::result::Result`][`Result`] 的导入。
///
///
/// [`std::io`]: crate::io
/// [`io::Error`]: Error
/// [`Result`]: crate::result::Result
/// [prelude]: crate::prelude
///
/// # Examples
///
/// 一个方便的函数,将 `io::Result` 冒泡给其调用者:
///
/// ```
/// use std::io;
///
/// fn get_string() -> io::Result<String> {
/// let mut buffer = String::new();
///
/// io::stdin().read_line(&mut buffer)?;
///
/// Ok(buffer)
/// }
/// ```
///
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result<T> = result::Result<T, Error>;
/// [`Read`],[`Write`],[`Seek`] 和关联的 traits 的 I/O 操作的错误类型。
///
/// 错误主要来自底层操作系统,但可以使用精心制作的错误消息和特定的 [`ErrorKind`] 值来创建 `Error` 的自定义实例。
///
///
/// [`Read`]: crate::io::Read
/// [`Write`]: crate::io::Write
/// [`Seek`]: crate::io::Seek
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Error {
repr: Repr,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.repr, f)
}
}
enum Repr {
Os(i32),
Simple(ErrorKind),
// &str 是一个胖指针,而 &&str 是一个瘦指针。
SimpleMessage(ErrorKind, &'static &'static str),
Custom(Box<Custom>),
}
#[derive(Debug)]
struct Custom {
kind: ErrorKind,
error: Box<dyn error::Error + Send + Sync>,
}
/// 一个列表,指定 I/O 错误的常规类别。
///
/// 此列表旨在随着时间的增长而增长,不建议对其进行详尽的匹配。
///
///
/// 与 [`io::Error`] 类型一起使用。
///
/// [`io::Error`]: Error
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
#[non_exhaustive]
pub enum ErrorKind {
/// 找不到实体,通常是文件。
#[stable(feature = "rust1", since = "1.0.0")]
NotFound,
/// 该操作缺少完成操作所需的权限。
#[stable(feature = "rust1", since = "1.0.0")]
PermissionDenied,
/// 远程服务器拒绝了连接。
#[stable(feature = "rust1", since = "1.0.0")]
ConnectionRefused,
/// 连接已由远程服务器重置。
#[stable(feature = "rust1", since = "1.0.0")]
ConnectionReset,
/// 远程主机不可访问。
#[unstable(feature = "io_error_more", issue = "86442")]
HostUnreachable,
/// 无法访问包含远程主机的网络。
#[unstable(feature = "io_error_more", issue = "86442")]
NetworkUnreachable,
/// (terminated) 连接被远程服务器中止。
#[stable(feature = "rust1", since = "1.0.0")]
ConnectionAborted,
/// 网络操作失败,因为尚未连接。
#[stable(feature = "rust1", since = "1.0.0")]
NotConnected,
/// 无法绑定套接字地址,因为该地址已在其他地方使用。
///
#[stable(feature = "rust1", since = "1.0.0")]
AddrInUse,
/// 请求了不存在的接口,或者请求的地址不是本地的。
///
#[stable(feature = "rust1", since = "1.0.0")]
AddrNotAvailable,
/// 系统的网络已关闭。
#[unstable(feature = "io_error_more", issue = "86442")]
NetworkDown,
/// 操作失败,因为管道已关闭。
#[stable(feature = "rust1", since = "1.0.0")]
BrokenPipe,
/// 一个实体已经存在,通常是一个文件。
#[stable(feature = "rust1", since = "1.0.0")]
AlreadyExists,
/// 该操作需要阻止才能完成,但是请求阻止操作不会发生。
///
#[stable(feature = "rust1", since = "1.0.0")]
WouldBlock,
/// 出乎意料的是,文件系统对象不是目录。
///
/// 例如,指定了一个文件系统路径,其中一个中间目录组件实际上是一个普通文件。
///
#[unstable(feature = "io_error_more", issue = "86442")]
NotADirectory,
/// 出乎意料的是,文件系统对象是一个目录。
///
/// 当需要一个非目录时指定了一个目录。
#[unstable(feature = "io_error_more", issue = "86442")]
IsADirectory,
/// 在需要空目录的地方指定了一个非空目录。
#[unstable(feature = "io_error_more", issue = "86442")]
DirectoryNotEmpty,
/// 文件系统或存储介质是只读的,但尝试了写入操作。
#[unstable(feature = "io_error_more", issue = "86442")]
ReadOnlyFilesystem,
/// 在文件系统或 IO 子系统中循环; 通常,太多级别的符号链接。
///
/// 有一个循环 (或过长的链) 解析文件系统对象或文件 IO 对象。
///
/// 在 Unix 上,这通常是符号链接循环的结果; 或者,超过系统特定的符号链接遍历深度限制。
///
///
#[unstable(feature = "io_error_more", issue = "86442")]
FilesystemLoop,
/// 陈旧的网络文件句柄。
///
/// 对于某些网络文件系统,尤其是 NFS,打开的文件 (或目录) 可能会因网络或服务器问题而失效。
///
#[unstable(feature = "io_error_more", issue = "86442")]
StaleNetworkFileHandle,
/// 参数不正确。
#[stable(feature = "rust1", since = "1.0.0")]
InvalidInput,
/// 遇到对该操作无效的数据。
///
/// 与 [`InvalidInput`] 不同,这通常意味着操作参数有效,但是该错误是由格式错误的输入数据引起的。
///
///
/// 例如,如果文件的内容无效 UTF-8,则将文件读入字符串的函数将出现 `InvalidData` 错误。
///
/// [`InvalidInput`]: ErrorKind::InvalidInput
///
///
#[stable(feature = "io_invalid_data", since = "1.2.0")]
InvalidData,
/// I/O 操作的超时已到期,导致其被取消。
#[stable(feature = "rust1", since = "1.0.0")]
TimedOut,
/// 由于调用 [`write`] 返回 [`Ok(0)`] 而无法完成操作时,返回错误。
///
/// 这通常意味着操作只有在写入特定数量的字节后才能成功,但是只能写入较少的字节数才能成功。
///
///
/// [`write`]: crate::io::Write::write
/// [`Ok(0)`]: Ok
///
///
#[stable(feature = "rust1", since = "1.0.0")]
WriteZero,
/// 底层存储 (通常是文件系统) 已满。
///
/// 这不包括超出配额的错误。
#[unstable(feature = "io_error_more", issue = "86442")]
StorageFull,
/// Seek 在不可搜索的文件上。
///
/// 尝试在不适合搜索的打开文件句柄上进行搜索 - 例如,在 Unix 上,使用 `File::open` 打开的命名管道。
///
#[unstable(feature = "io_error_more", issue = "86442")]
NotSeekable,
/// 超出了文件系统配额。
#[unstable(feature = "io_error_more", issue = "86442")]
FilesystemQuotaExceeded,
/// 文件大于允许或支持。
///
/// 这可能源于底层文件系统或文件访问 API 的硬限制,或源于管理强加的资源限制。
/// 简单的磁盘已满,超出配额,都有自己的错误。
///
#[unstable(feature = "io_error_more", issue = "86442")]
FileTooLarge,
/// 资源繁忙。
#[unstable(feature = "io_error_more", issue = "86442")]
ResourceBusy,
/// 可执行文件正忙。
///
/// 试图写入一个文件,该文件也用作正在运行的程序。
/// (并非所有操作系统都检测到这种情况。)
#[unstable(feature = "io_error_more", issue = "86442")]
ExecutableFileBusy,
/// 死锁 (avoided)。
///
/// 文件锁定操作会导致死锁。
/// 这种情况通常是在尽力而为的基础上检测到的。
#[unstable(feature = "io_error_more", issue = "86442")]
Deadlock,
/// 跨设备或跨文件系统 (hard) 链接或重命名。
#[unstable(feature = "io_error_more", issue = "86442")]
CrossesDevices,
/// 太多 (hard) 链接到同一个文件系统对象。
///
/// 文件系统不支持对同一个文件建立如此多的硬链接。
#[unstable(feature = "io_error_more", issue = "86442")]
TooManyLinks,
/// 文件名太长。
///
/// 该限制可能来自底层文件系统或 API,或者是管理上强加的资源限制。
///
#[unstable(feature = "io_error_more", issue = "86442")]
FilenameTooLong,
/// 程序参数列表太长。
///
/// 尝试运行外部程序时,会超出系统或进程对参数大小的限制。
///
#[unstable(feature = "io_error_more", issue = "86442")]
ArgumentListTooLong,
/// 该操作被中断。
///
/// 通常可以重试中断的操作。
#[stable(feature = "rust1", since = "1.0.0")]
Interrupted,
/// 此平台不支持此操作。
///
/// 这意味着操作永远不会成功。
#[stable(feature = "unsupported_error", since = "1.53.0")]
Unsupported,
// ErrorKinds 主要是 OS 错误代码的分类应在上面添加。
//
//
/// 由于过早到达 "文件结尾" 而无法完成操作时,返回错误。
///
/// 通常,这意味着操作只有在读取特定数量的字节后才能成功,但是只能读取较少的字节。
///
///
///
#[stable(feature = "read_exact", since = "1.6.0")]
UnexpectedEof,
/// 操作无法完成,因为它未能分配足够的内存。
///
#[stable(feature = "out_of_memory_error", since = "1.54.0")]
OutOfMemory,
// "Unusual" 错误类型不只对应于 (组) 操作系统错误代码,应添加在这个注释的正上方。
//
// `Other` 和 `Uncategorised` 应保留在末尾:
//
/// 不属于任何其他 I/O 错误类型的自定义错误。
///
/// 这可用于构建您自己的不匹配任何 [`ErrorKind`] 的 [`Error`]。
///
/// 标准库不使用此 [`ErrorKind`]。
///
/// 标准库中不属于任何 I/O 错误类型的错误无法 `匹配`,并且只会匹配通配符 (`_`) 模式。
///
/// 可能会在 future 中为其中一些添加新的 [`ErrorKind`]。
///
#[stable(feature = "rust1", since = "1.0.0")]
Other,
/// 标准库中不属于此列表的任何 I/O 错误。
///
/// 现在 `Uncategorized` 的错误将来可能会转移到不同的或新的 [`ErrorKind`] 变体。
/// 不建议针对 `Uncategorized` 匹配错误; 改用通配符匹配 (`_`)。
///
#[unstable(feature = "io_error_uncategorized", issue = "none")]
#[doc(hidden)]
Uncategorized,
}
impl ErrorKind {
pub(crate) fn as_str(&self) -> &'static str {
use ErrorKind::*;
// 请严格按字母顺序排列。(遗憾的是 rustfmt 还不能做到这一点。)
match *self {
AddrInUse => "address in use",
AddrNotAvailable => "address not available",
AlreadyExists => "entity already exists",
ArgumentListTooLong => "argument list too long",
BrokenPipe => "broken pipe",
ConnectionAborted => "connection aborted",
ConnectionRefused => "connection refused",
ConnectionReset => "connection reset",
CrossesDevices => "cross-device link or rename",
Deadlock => "deadlock",
DirectoryNotEmpty => "directory not empty",
ExecutableFileBusy => "executable file busy",
FileTooLarge => "file too large",
FilenameTooLong => "filename too long",
FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
FilesystemQuotaExceeded => "filesystem quota exceeded",
HostUnreachable => "host unreachable",
Interrupted => "operation interrupted",
InvalidData => "invalid data",
InvalidInput => "invalid input parameter",
IsADirectory => "is a directory",
NetworkDown => "network down",
NetworkUnreachable => "network unreachable",
NotADirectory => "not a directory",
NotConnected => "not connected",
NotFound => "entity not found",
NotSeekable => "seek on unseekable file",
Other => "other error",
OutOfMemory => "out of memory",
PermissionDenied => "permission denied",
ReadOnlyFilesystem => "read-only filesystem or storage medium",
ResourceBusy => "resource busy",
StaleNetworkFileHandle => "stale network file handle",
StorageFull => "no storage space",
TimedOut => "timed out",
TooManyLinks => "too many links",
Uncategorized => "uncategorized error",
UnexpectedEof => "unexpected end of file",
Unsupported => "unsupported",
WouldBlock => "operation would block",
WriteZero => "write zero",
}
}
}
/// 旨在用于未暴露给用户的错误,因为分配到堆上 (通过 Error::new 进行常规构建) 的代价太高了。
///
#[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
impl From<ErrorKind> for Error {
/// 将 [`ErrorKind`] 转换为 [`Error`]。
///
/// 此转换使用错误类型的简单表示来分配新错误。
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// let not_found = ErrorKind::NotFound;
/// let error = Error::from(not_found);
/// assert_eq!("entity not found", format!("{}", error));
/// ```
#[inline]
fn from(kind: ErrorKind) -> Error {
Error { repr: Repr::Simple(kind) }
}
}
impl Error {
/// 根据已知的错误以及任意的错误有效载荷创建新的 I/O 错误。
///
/// 此函数通常用于创建 I/O 错误,这些错误并非源于操作系统本身。
/// `error` 参数是将包含在此 [`Error`] 中的任意有效载荷。
///
/// 如果不需要额外的有效载荷,请使用来自 `ErrorKind` 的 `From` 转换。
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// // 可以从字符串创建错误
/// let custom_error = Error::new(ErrorKind::Other, "oh no!");
///
/// // 错误也可以从其他错误中创建
/// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
///
/// // 在没有有效载荷的情况下创建错误
/// let eof_error = Error::from(ErrorKind::UnexpectedEof);
/// ```
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new<E>(kind: ErrorKind, error: E) -> Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Self::_new(kind, error.into())
}
/// 从任意错误有效载荷创建新的 I/O 错误。
///
/// 此函数通常用于创建 I/O 错误,这些错误并非源于操作系统本身。
/// 它是 [`Error::new`] 与 [`ErrorKind::Other`] 的快捷方式。
///
/// # Examples
///
/// ```
/// #![feature(io_error_other)]
///
/// use std::io::Error;
///
/// // 可以从字符串创建错误
/// let custom_error = Error::other("oh no!");
///
/// // 错误也可以从其他错误中创建
/// let custom_error2 = Error::other(custom_error);
/// ```
///
#[unstable(feature = "io_error_other", issue = "91946")]
pub fn other<E>(error: E) -> Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Self::_new(ErrorKind::Other, error.into())
}
fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
}
/// 从已知类型的错误以及恒定消息创建一个新的 I/O 错误。
///
///
/// 这个函数不分配。
///
/// 这个函数应该改成
/// `new_const<const MSG: &'static str>(kind: ErrorKind)`
/// 在 future 中,当 const 泛型允许时。
#[inline]
pub(crate) const fn new_const(kind: ErrorKind, message: &'static &'static str) -> Error {
Self { repr: Repr::SimpleMessage(kind, message) }
}
/// 返回代表最近发生的操作系统错误的错误。
///
/// 该函数读取目标平台的 `errno` 值 (例如,
/// Windows 上的 `GetLastError`) 并将为错误代码返回相应的 [`Error`] 实例。
///
/// 这应该在调用到平台函数之后立即调用,否则错误值的状态是不确定的。
/// 特别是,其他标准库函数可能会调用平台函数,即使它们成功也可能 (或可能不会) 重置错误值。
///
///
/// # Examples
///
/// ```
/// use std::io::Error;
///
/// let os_error = Error::last_os_error();
/// println!("last OS error: {:?}", os_error);
/// ```
///
///
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline]
pub fn last_os_error() -> Error {
Error::from_raw_os_error(sys::os::errno() as i32)
}
/// 根据特定的操作系统错误代码创建 [`Error`] 的新实例。
///
/// # Examples
///
/// 在 Linux 上:
///
/// ```
/// # if cfg!(target_os = "linux") {
/// use std::io;
///
/// let error = io::Error::from_raw_os_error(22);
/// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
/// # }
/// ```
///
/// 在 Windows 上:
///
/// ```
/// # if cfg!(windows) {
/// use std::io;
///
/// let error = io::Error::from_raw_os_error(10022);
/// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
/// # }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline]
pub fn from_raw_os_error(code: i32) -> Error {
Error { repr: Repr::Os(code) }
}
/// 返回此错误表示的操作系统错误 (如果有)。
///
/// 如果此 [`Error`] 是通过 [`last_os_error`] 或 [`from_raw_os_error`] 构造的,则此函数将返回 [`Some`],否则它将返回 [`None`]。
///
///
/// [`last_os_error`]: Error::last_os_error
/// [`from_raw_os_error`]: Error::from_raw_os_error
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// fn print_os_error(err: &Error) {
/// if let Some(raw_os_err) = err.raw_os_error() {
/// println!("raw OS error: {:?}", raw_os_err);
/// } else {
/// println!("Not an OS error");
/// }
/// }
///
/// fn main() {
/// // 将打印 "raw OS error: ..."。
/// print_os_error(&Error::last_os_error());
/// // 将打印 "Not an OS error"。
/// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
/// }
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline]
pub fn raw_os_error(&self) -> Option<i32> {
match self.repr {
Repr::Os(i) => Some(i),
Repr::Custom(..) => None,
Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
}
}
/// 返回对此错误包装的内部错误 (如果有) 的引用。
///
/// 如果此 [`Error`] 是通过 [`new`] 构造的,则此函数将返回 [`Some`],否则它将返回 [`None`]。
///
///
/// [`new`]: Error::new
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// fn print_error(err: &Error) {
/// if let Some(inner_err) = err.get_ref() {
/// println!("Inner error: {:?}", inner_err);
/// } else {
/// println!("No inner error");
/// }
/// }
///
/// fn main() {
/// // 将打印 "No inner error"。
/// print_error(&Error::last_os_error());
/// // 将打印 "Inner error: ..."。
/// print_error(&Error::new(ErrorKind::Other, "oh no!"));
/// }
/// ```
#[stable(feature = "io_error_inner", since = "1.3.0")]
#[must_use]
#[inline]
pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
match self.repr {
Repr::Os(..) => None,
Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref c) => Some(&*c.error),
}
}
/// 返回对此错误包装的内部错误的可变引用 (如果有)。
///
/// 如果此 [`Error`] 是通过 [`new`] 构造的,则此函数将返回 [`Some`],否则它将返回 [`None`]。
///
///
/// [`new`]: Error::new
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
/// use std::{error, fmt};
/// use std::fmt::Display;
///
/// #[derive(Debug)]
/// struct MyError {
/// v: String,
/// }
///
/// impl MyError {
/// fn new() -> MyError {
/// MyError {
/// v: "oh no!".to_string()
/// }
/// }
///
/// fn change_message(&mut self, new_message: &str) {
/// self.v = new_message.to_string();
/// }
/// }
///
/// impl error::Error for MyError {}
///
/// impl Display for MyError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "MyError: {}", &self.v)
/// }
/// }
///
/// fn change_error(mut err: Error) -> Error {
/// if let Some(inner_err) = err.get_mut() {
/// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
/// }
/// err
/// }
///
/// fn print_error(err: &Error) {
/// if let Some(inner_err) = err.get_ref() {
/// println!("Inner error: {}", inner_err);
/// } else {
/// println!("No inner error");
/// }
/// }
///
/// fn main() {
/// // 将打印 "No inner error"。
/// print_error(&change_error(Error::last_os_error()));
/// // 将打印 "Inner error: ..."。
/// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
/// }
/// ```
///
#[stable(feature = "io_error_inner", since = "1.3.0")]
#[must_use]
#[inline]
pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
match self.repr {
Repr::Os(..) => None,
Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref mut c) => Some(&mut *c.error),
}
}
/// 消耗 `Error`,并返回其内部错误 (如果有)。
///
/// 如果此 [`Error`] 是通过 [`new`] 构造的,则此函数将返回 [`Some`],否则它将返回 [`None`]。
///
///
/// [`new`]: Error::new
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// fn print_error(err: Error) {
/// if let Some(inner_err) = err.into_inner() {
/// println!("Inner error: {}", inner_err);
/// } else {
/// println!("No inner error");
/// }
/// }
///
/// fn main() {
/// // 将打印 "No inner error"。
/// print_error(Error::last_os_error());
/// // 将打印 "Inner error: ..."。
/// print_error(Error::new(ErrorKind::Other, "oh no!"));
/// }
/// ```
#[stable(feature = "io_error_inner", since = "1.3.0")]
#[must_use = "`self` will be dropped if the result is not used"]
#[inline]
pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
match self.repr {
Repr::Os(..) => None,
Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(c) => Some(c.error),
}
}
/// 返回与此错误对应的 [`ErrorKind`]。
///
/// # Examples
///
/// ```
/// use std::io::{Error, ErrorKind};
///
/// fn print_error(err: Error) {
/// println!("{:?}", err.kind());
/// }
///
/// fn main() {
/// // 将打印 "Uncategorized"。
/// print_error(Error::last_os_error());
/// // 将打印 "AddrInUse"。
/// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline]
pub fn kind(&self) -> ErrorKind {
match self.repr {
Repr::Os(code) => sys::decode_error_kind(code),
Repr::Custom(ref c) => c.kind,
Repr::Simple(kind) => kind,
Repr::SimpleMessage(kind, _) => kind,
}
}
}
impl fmt::Debug for Repr {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Repr::Os(code) => fmt
.debug_struct("Os")
.field("code", &code)
.field("kind", &sys::decode_error_kind(code))
.field("message", &sys::os::error_string(code))
.finish(),
Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
Repr::SimpleMessage(kind, &message) => {
fmt.debug_struct("Error").field("kind", &kind).field("message", &message).finish()
}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.repr {
Repr::Os(code) => {
let detail = sys::os::error_string(code);
write!(fmt, "{} (os error {})", detail, code)
}
Repr::Custom(ref c) => c.error.fmt(fmt),
Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
Repr::SimpleMessage(_, &msg) => msg.fmt(fmt),
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl error::Error for Error {
#[allow(deprecated, deprecated_in_future)]
fn description(&self) -> &str {
match self.repr {
Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
Repr::SimpleMessage(_, &msg) => msg,
Repr::Custom(ref c) => c.error.description(),
}
}
#[allow(deprecated)]
fn cause(&self) -> Option<&dyn error::Error> {
match self.repr {
Repr::Os(..) => None,
Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref c) => c.error.cause(),
}
}
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self.repr {
Repr::Os(..) => None,
Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref c) => c.error.source(),
}
}
}
fn _assert_error_is_sync_send() {
fn _is_sync_send<T: Sync + Send>() {}
_is_sync_send::<Error>();
}