mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-01-31 03:27:39 +00:00
e3d28de8a6
When reading hexadecimal floats, cosmopolitan would previously sometimes print a number of warnings relating to undefined behavior on left shift: third_party/gdtoa/gethex.c:172: ubsan warning: signed left shift changed sign bit or overflowed 12 'int' 28 'int' is undefined behavior This is because gdtoa assumes left shifts are safe when overflow happens even on signed integers - this is false: the C standard considers it UB. This is easy to fix, by simply casting the shifted value to unsigned, as doing so does not change the value or the semantics of the left shifting (except for avoiding the undefined behavior, as the C standard specifies that unsigned overflow yields wraparound, avoiding undefined behaviour). This commit does this, and adds a testcase that previously triggered UB. (this also adds test macros to test for exact float equality, instead of the existing {EXPECT,ASSERT}_FLOAT_EQ macros which only tests inputs for being "almost equal" (with a significant epsilon) whereas exact equality makes more sense for certain things such as reading floats from strings, and modifies other testcases for sscanf/fscanf of floats to utilize it).
35 lines
2.3 KiB
C
35 lines
2.3 KiB
C
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
|
|
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
|
|
╞══════════════════════════════════════════════════════════════════════════════╡
|
|
│ Copyright 2024 Justine Alexandra Roberts Tunney │
|
|
│ │
|
|
│ Permission to use, copy, modify, and/or distribute this software for │
|
|
│ any purpose with or without fee is hereby granted, provided that the │
|
|
│ above copyright notice and this permission notice appear in all copies. │
|
|
│ │
|
|
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
|
|
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
|
|
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
|
|
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
|
|
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
|
|
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
|
|
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
|
│ PERFORMANCE OF THIS SOFTWARE. │
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
|
#include "libc/math.h"
|
|
#include "libc/testlib/testlib.h"
|
|
|
|
bool testlib_exactlyequallongdouble(long double x, long double y) {
|
|
if (isnan(x) && isnan(y))
|
|
return true;
|
|
// Check that we don't have e.g. one input denormal and the other not
|
|
// (a denormal and a non-denormal can sometimes compare equal)
|
|
if (fpclassify(x) != fpclassify(y))
|
|
return false;
|
|
// Check that we don't have -0 and 0
|
|
if (signbit(x) != signbit(y))
|
|
return false;
|
|
if (x != y)
|
|
return false;
|
|
return true;
|
|
}
|