Skip to content

Commit 793d18d

Browse files
committed
feat: add a ctx_err util function
1 parent 7182760 commit 793d18d

File tree

2 files changed

+13
-16
lines changed

2 files changed

+13
-16
lines changed

src/items/primitive.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use winnow::{
77
ascii::{digit1, multispace0},
88
combinator::{alt, delimited, not, opt, peek, preceded, repeat, separated},
9-
error::ParserError,
9+
error::{ContextError, ParserError, StrContext, StrContextValue},
1010
stream::AsChar,
1111
token::{none_of, one_of, take_while},
1212
Parser,
@@ -130,3 +130,10 @@ where
130130
.verify_map(|s: &str| s.replace(",", ".").parse().ok())
131131
.parse_next(input)
132132
}
133+
134+
/// Create a context error with a reason.
135+
pub(super) fn ctx_err(reason: &'static str) -> ContextError {
136+
let mut err = ContextError::new();
137+
err.push(StrContext::Expected(StrContextValue::Description(reason)));
138+
err
139+
}

src/items/time.rs

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ use std::fmt::Display;
4242
use chrono::FixedOffset;
4343
use winnow::{
4444
combinator::{alt, opt, peek, preceded},
45-
error::{ContextError, ErrMode, StrContext, StrContextValue},
45+
error::{ContextError, ErrMode},
4646
seq,
4747
stream::AsChar,
4848
token::take_while,
@@ -52,7 +52,7 @@ use winnow::{
5252
use crate::ParseDateTimeError;
5353

5454
use super::{
55-
primitive::{dec_uint, float, s},
55+
primitive::{ctx_err, dec_uint, float, s},
5656
relative,
5757
};
5858

@@ -191,11 +191,9 @@ fn am_pm_time(input: &mut &str) -> ModalResult<Time> {
191191
.parse_next(input)?;
192192

193193
if h == 0 {
194-
let mut ctx_err = ContextError::new();
195-
ctx_err.push(StrContext::Expected(StrContextValue::Description(
194+
return Err(ErrMode::Cut(ctx_err(
196195
"hour must be greater than 0 when meridiem is specified",
197196
)));
198-
return Err(ErrMode::Cut(ctx_err));
199197
}
200198

201199
let mut h = h % 12;
@@ -261,19 +259,11 @@ fn timezone_num(input: &mut &str) -> ModalResult<Offset> {
261259
.parse_next(input)
262260
.and_then(|(negative, (hours, minutes))| {
263261
if !(0..=12).contains(&hours) {
264-
let mut ctx_err = ContextError::new();
265-
ctx_err.push(StrContext::Expected(StrContextValue::Description(
266-
"timezone hour between 0 and 12",
267-
)));
268-
return Err(ErrMode::Cut(ctx_err));
262+
return Err(ErrMode::Cut(ctx_err("timezone hour between 0 and 12")));
269263
}
270264

271265
if !(0..=60).contains(&minutes) {
272-
let mut ctx_err = ContextError::new();
273-
ctx_err.push(StrContext::Expected(StrContextValue::Description(
274-
"timezone minute between 0 and 60",
275-
)));
276-
return Err(ErrMode::Cut(ctx_err));
266+
return Err(ErrMode::Cut(ctx_err("timezone minute between 0 and 60")));
277267
}
278268

279269
Ok(Offset {

0 commit comments

Comments
 (0)