Skip to content

Commit

Permalink
timezone_offset_internal and TimeZoneName::new parse by chars
Browse files Browse the repository at this point in the history
Function `timezone_offset_internal` and `TimeZoneName::new`
iterate over the input data by `chars()` instead of iterating
`as_bytes()`.
  • Loading branch information
jtmoon79 committed Jun 9, 2023
1 parent 978dfb8 commit b41f8db
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 16 deletions.
15 changes: 11 additions & 4 deletions src/format/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,13 +230,20 @@ where
Ok((b[0], b[1]))
}
}
let negative = match s.as_bytes().first() {
Some(&b'+') => false,
Some(&b'-') => true,
let negative = match s.chars().next() {
Some('+') => {
s = &s['+'.len_utf8()..];

false
}
Some('-') => {
s = &s['-'.len_utf8()..];

true
}
Some(_) => return Err(INVALID),
None => return Err(TOO_SHORT),
};
s = &s[1..];

// hours (00--99)
let hours = match digits(s)? {
Expand Down
32 changes: 20 additions & 12 deletions src/offset/local/tz_info/timezone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,28 +487,36 @@ struct TimeZoneName {
impl TimeZoneName {
/// Construct a time zone name
fn new(input: &[u8]) -> Result<Self, Error> {
let len = input.len();
let s = match str::from_utf8(input) {
Ok(s) => s,
Err(_err) => return Err(Error::LocalTimeType("invalid UTF-8")),
};
let schars = s.chars().count();

if !(3..=7).contains(&len) {
if !(3..=7).contains(&schars) {
return Err(Error::LocalTimeType(
"time zone name must have between 3 and 7 characters",
));
}

let mut bytes = [0; 8];
bytes[0] = input.len() as u8;

let mut i = 0;
while i < len {
let b = input[i];
match b {
b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-' => {}
let mut copied = 0;
for (i, c) in s.chars().enumerate() {
match c {
'0'..='9' | 'A'..='Z' | 'a'..='z'
// ISO 8601 / RFC 3339 proscribes use of `+` (U+2B) PLUS SIGN
// in timezone
| '+'
// ISO 8601 / RFC 3339 allows use of `-` HYPHEN-MINUS (U+2D)
// in timezone
| '-' => {
bytes[i + 1] = c as u8;
}
_ => return Err(Error::LocalTimeType("invalid characters in time zone name")),
}

bytes[i + 1] = b;
i += 1;
copied += 1;
}
bytes[0] = copied as u8;

Ok(Self { bytes })
}
Expand Down

0 comments on commit b41f8db

Please sign in to comment.