当前位置: 首页 > news >正文

【time-rs】解释://! Error that occurred at some stage of parsing(error/parse.rs)

这段Rust代码定义了一个解析错误的通用枚举类型Parse,用于表示在时间解析过程中可能发生的各种错误。它是时间解析库中的核心错误类型。

枚举定义

#[non_exhaustive]#[allow(variant_size_differences, reason ="only triggers on some platforms")]#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumParse{TryFromParsed(TryFromParsed),ParseFromDescription(ParseFromDescription),#[non_exhaustive]#[deprecated( since ="0.3.28", note ="no longer output. moved to the `ParseFromDescription` variant")]UnexpectedTrailingCharacters{#[doc(hidden)]never:Infallible,},}

属性说明:

  1. #[non_exhaustive]

    • 表示枚举未来可能添加新变体
    • 强制用户代码使用穷尽匹配,保持向后兼容
  2. #[allow(variant_size_differences)]

    • 允许变体大小不同(因为包含Infallible类型)
    • reason属性说明:仅在某些平台上触发
  3. #[derive(...)]

    • 实现了DebugCloneCopyPartialEqEq等常见trait

变体详解

1.TryFromParsed(TryFromParsed)

  • 表示在从解析结果转换到目标类型时发生的错误
  • 例如:解析出的日期时间值超出目标类型的有效范围

2.ParseFromDescription(ParseFromDescription)

  • 表示根据格式描述进行解析时发生的错误
  • 例如:输入字符串与格式描述不匹配

3.UnexpectedTrailingCharacters(已弃用)

#[deprecated(since ="0.3.28", note ="...")]UnexpectedTrailingCharacters{#[doc(hidden)]never:Infallible,}
  • 已弃用:从 0.3.28 版本开始不再使用
  • 迁移:功能已移至ParseFromDescription变体
  • Infallible:永不实例化的类型,确保该变体无法构造
  • 设计目的:保持API兼容性,同时逐步移除旧功能

Display trait 实现

implfmt::DisplayforParse{fnfmt(&self,f:&mutfmt::Formatter<'_>)->fmt::Result{matchself{Self::TryFromParsed(err)=>err.fmt(f),Self::ParseFromDescription(err)=>err.fmt(f),#[allow(deprecated)]Self::UnexpectedTrailingCharacters{never}=>match*never{},}}}

实现特点

  • 委托给内部错误的Display实现
  • 对于已弃用变体,使用match *never {}保证编译通过
  • #[allow(deprecated)]允许使用已弃用的变体模式

Error trait 实现

implcore::error::ErrorforParse{fnsource(&self)->Option<&(dyncore::error::Error+'static)>{matchself{Self::TryFromParsed(err)=>Some(err),Self::ParseFromDescription(err)=>Some(err),#[allow(deprecated)]Self::UnexpectedTrailingCharacters{never}=>match*never{},}}}

特点

  • 实现source()方法,提供错误的根本原因
  • 支持错误链(error chain)
  • 同样处理了已弃用变体

与内部错误类型的转换

TryFromParsed转换到Parse

implFrom<TryFromParsed>forParse{fnfrom(err:TryFromParsed)->Self{Self::TryFromParsed(err)}}

Parse尝试转换到TryFromParsed

implTryFrom<Parse>forTryFromParsed{typeError=error::DifferentVariant;fntry_from(err:Parse)->Result<Self,Self::Error>{matcherr{Parse::TryFromParsed(err)=>Ok(err),_=>Err(error::DifferentVariant),}}}

ParseFromDescription转换到Parse

implFrom<ParseFromDescription>forParse{fnfrom(err:ParseFromDescription)->Self{Self::ParseFromDescription(err)}}

Parse尝试转换到ParseFromDescription

implTryFrom<Parse>forParseFromDescription{typeError=error::DifferentVariant;fntry_from(err:Parse)->Result<Self,Self::Error>{matcherr{Parse::ParseFromDescription(err)=>Ok(err),_=>Err(error::DifferentVariant),}}}

转换模式总结

  • From<T>:总是成功,向上转换
  • TryFrom<Parse>:可能失败,向下转换
  • DifferentVariant:当错误类型不匹配时返回

与 crate::Error 的转换

向上转换:Parsecrate::Error

implFrom<Parse>forcrate::Error{fnfrom(err:Parse)->Self{matcherr{Parse::TryFromParsed(err)=>Self::TryFromParsed(err),Parse::ParseFromDescription(err)=>Self::ParseFromDescription(err),#[allow(deprecated)]Parse::UnexpectedTrailingCharacters{never}=>matchnever{},}}}

处理已弃用变体

  • 对于UnexpectedTrailingCharacters,使用match never {}保证不会执行
  • 确保编译通过,即使变体已弃用

向下转换:crate::ErrorParse

implTryFrom<crate::Error>forParse{typeError=error::DifferentVariant;fntry_from(err:crate::Error)->Result<Self,Self::Error>{matcherr{crate::Error::ParseFromDescription(err)=>Ok(Self::ParseFromDescription(err)),#[allow(deprecated)]crate::Error::UnexpectedTrailingCharacters{never}=>matchnever{},crate::Error::TryFromParsed(err)=>Ok(Self::TryFromParsed(err)),_=>Err(error::DifferentVariant),}}}

使用场景示例

解析时间字符串

usetime::format_description;usetime::parsing::Parse;fnparse_datetime(input:&str)->Result<OffsetDateTime,Parse>{letformat=format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")?;letparsed=PrimitiveDateTime::parse(input,&format)?;Ok(parsed.into())}

错误处理

matchparse_datetime("2023-13-01 25:00:00"){Ok(dt)=>println!("解析成功: {}",dt),Err(Parse::ParseFromDescription(err))=>{eprintln!("格式解析错误: {}",err);}Err(Parse::TryFromParsed(err))=>{eprintln!("类型转换错误: {}",err);}}

设计特点

1. 分层错误处理

crate::Error ├── Parse │ ├── TryFromParsed │ └── ParseFromDescription └── Other errors...

2. 向后兼容性

  • 使用#[deprecated]Infallible平滑过渡
  • #[non_exhaustive]保护未来扩展

3. 类型安全

  • 双向转换确保类型安全
  • 使用TryFrom进行安全的错误类型提取

4. 性能优化

  • #[inline]提示内联优化
  • 大部分类型实现Copy,减少分配

与其他错误类型的关系

错误类型层级用途
crate::Error顶级所有错误的容器
Parse中间层解析相关错误
TryFromParsed具体层转换错误
ParseFromDescription具体层格式解析错误

这种设计提供了灵活的错误处理机制,既支持通用的错误处理,也支持精确的错误类型匹配。

http://www.cnnetsun.cn/news/100234.html

相关文章:

  • 启天 M 系列 Smart Power On/Fast boot 置灰?2 步解锁修改权限!
  • 告别繁琐问卷设计!百考通AI智能助手,5分钟生成专业调研问卷
  • 百考通AI:你的智能学术助手,让毕业论文写作化繁为简
  • IntelliJ IDEA 2025.3 正式发布
  • MyBatis-Flex 来了!完爆MyBatis-Plus?
  • 神经紧张素受体SORT1
  • 高盐高铵根工业废水去除重金属
  • 某211高校讲师晒工资条,网友:公积金数额令人瞩目...
  • Nature Electronics 一种用于多模态皮肤信号监测的柔性触觉接口
  • 小鼠T细胞激活:如何系统解析其发育分化与免疫功能表征?
  • 基于springboot和vue的民航飞机票务管理系统设计与实现
  • 2025年12月-2026年4月,计算机领域涵盖的前言学术会议推荐!
  • 基于单片机的智能镜子系统设计(有完整资料)
  • 国产化替代SSD的标杆之路:天硕TOPSSD以自主可控存储解决方案重塑高端工业存储格局
  • EmotiVoice本地化部署优势:数据安全与响应效率兼得
  • 【Java毕设全套源码+文档】基于springboot的数据库课程在线教学系统设计与实现(丰富项目+远程调试+讲解+定制)
  • 【Java毕设全套源码+文档】基于springboot的实验室安全考试系统设计与实现(丰富项目+远程调试+讲解+定制)
  • 基于QT(C++)实现的翻金币游戏
  • 基于 Spring·Boot和 Vue 框架的校园快递代领系统设计与实现
  • NVIDIA设置疑难杂症诊所:万字终极实战指南
  • 边缘Agent的Docker监控实践(资源利用率提升90%的秘密)
  • 揭秘Docker Scout漏洞导出功能:如何快速获取镜像安全报告
  • 【云原生Agent资源调度实战】:Docker环境下高效分配CPU与内存的5大黄金法则
  • 增长有毒?流血三闯港股!希迪智驾带病叩钟:115亿市值撑得住“白条狂欢”吗?
  • 多模态Agent性能骤降?可能是Docker网络隔离没做好(附诊断清单)
  • 为什么你的Docker镜像总被攻破?:可能是扫描频率设置错了
  • 背胶条分类识别:基于计算机视觉的修复状态差异检测与质量评估系统
  • 【新】基于SSM的高校实验室管理系统【包括源码+文档+调试】
  • Python 爬虫实战:沪深 300 股票(下)—— 适当进阶!爬取往期批量数据
  • 超声波传感器:无人机低空飞行的“隐形守护者”