From 2db4f2871a91f708154f4b13bf751a0a3fc96f61 Mon Sep 17 00:00:00 2001 From: "Yuto KAWAMURA(kawamuray)" Date: Tue, 28 Jan 2014 03:35:25 +0900 Subject: [PATCH] Make strptime() to check if date string is matching format completely. This patch makes strptime() to be croak "Error parsing time" if: - STRING is empty string but format is not (e.g, format: "%y" string: "") - STRING is not enough to match with format (e.g, format: "%Y%m" string: "2014") --- Piece.xs | 8 ++++++-- t/02core.t | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Piece.xs b/Piece.xs index 0798b34..42892e1 100644 --- a/Piece.xs +++ b/Piece.xs @@ -455,8 +455,12 @@ _strptime(pTHX_ const char *buf, const char *fmt, struct tm *tm, int *got_GMT) */ ptr = fmt; while (*ptr != 0) { - if (*buf == 0) - break; + if (*buf == 0) { + /* trailing whitespace is allowed */ + while (isspace((unsigned char)*ptr)) + ptr++; + return (*ptr == 0) ? (char *)buf : 0; + } c = *ptr++; diff --git a/t/02core.t b/t/02core.t index 3840e87..e09f925 100644 --- a/t/02core.t +++ b/t/02core.t @@ -1,4 +1,4 @@ -use Test::More tests => 96; +use Test::More tests => 98; my $is_win32 = ($^O =~ /Win32/); my $is_qnx = ($^O eq 'qnx'); @@ -227,3 +227,16 @@ cmp_ok( 951827696 ); +eval { Time::Piece->strptime("2014", '%Y%m') }; +like( + $@, + qr/Error parsing time/, + "croak if passed string wasn't enough to match with format" +); + +eval { Time::Piece->strptime("", '%y') }; +like( + $@, + qr/Error parsing time/, + "croak if empty string passed to strptime with non-empty format" +);