gdate: Comment that g_date_valid_dmy() does all necessary bounds checks

Make it more obvious that an explicit check isn’t needed for the upper
bound on years, since it’s limited by the type width.

Add a unit test to demonstrate this.

Signed-off-by: Philip Withnall <withnall@endlessm.com>

https://bugzilla.gnome.org/show_bug.cgi?id=540013
This commit is contained in:
Philip Withnall 2018-04-12 18:06:41 +01:00
parent f9ff79704c
commit 33749d837c
2 changed files with 45 additions and 0 deletions

View File

@ -494,6 +494,8 @@ g_date_valid_dmy (GDateDay d,
GDateMonth m, GDateMonth m,
GDateYear y) GDateYear y)
{ {
/* No need to check the upper bound of @y, because #GDateYear is 16 bits wide,
* just like #GDate.year. */
return ( (m > G_DATE_BAD_MONTH) && return ( (m > G_DATE_BAD_MONTH) &&
(m < 13) && (m < 13) &&
(d > G_DATE_BAD_DAY) && (d > G_DATE_BAD_DAY) &&

View File

@ -606,6 +606,48 @@ test_copy (void)
g_date_free (d); g_date_free (d);
} }
/* Check the results of g_date_valid_dmy() for various inputs. */
static void
test_valid_dmy (void)
{
const struct
{
GDateDay day;
GDateMonth month;
GDateYear year;
gboolean expected_valid;
}
vectors[] =
{
/* Lower bounds */
{ 0, 0, 0, FALSE },
{ 1, 1, 1, TRUE },
{ 1, 1, 0, FALSE },
/* Leap year month lengths */
{ 30, 2, 2000, FALSE },
{ 29, 2, 2000, TRUE },
{ 29, 2, 2001, FALSE },
/* Maximum year */
{ 1, 1, G_MAXUINT16, TRUE },
};
gsize i;
for (i = 0; i < G_N_ELEMENTS (vectors); i++)
{
gboolean valid;
g_test_message ("Vector %" G_GSIZE_FORMAT ": %04u-%02u-%02u, %s",
i, vectors[i].year, vectors[i].month, vectors[i].day,
vectors[i].expected_valid ? "valid" : "invalid");
valid = g_date_valid_dmy (vectors[i].day, vectors[i].month, vectors[i].year);
if (vectors[i].expected_valid)
g_assert_true (valid);
else
g_assert_false (valid);
}
}
int int
main (int argc, char** argv) main (int argc, char** argv)
{ {
@ -653,6 +695,7 @@ main (int argc, char** argv)
g_free (path); g_free (path);
} }
g_test_add_func ("/date/copy", test_copy); g_test_add_func ("/date/copy", test_copy);
g_test_add_func ("/date/valid-dmy", test_valid_dmy);
return g_test_run (); return g_test_run ();
} }