diff --git a/.gitignore b/.gitignore index 695c8ce01d9..2767cb72d25 100644 --- a/.gitignore +++ b/.gitignore @@ -81,6 +81,8 @@ cscope.*out /vmod/vcc_*_if.h /vmod/vmod_*.rst /vmod/vmod_vcs_version.txt +/vmod/vmod_math.vcc +/vmod/vmod_math.c # Man-files and binaries /man/*.1 diff --git a/doc/changes.rst b/doc/changes.rst index 0ced7059692..7e89c785f53 100644 --- a/doc/changes.rst +++ b/doc/changes.rst @@ -41,6 +41,8 @@ Vinyl-Cache NEXT (2026-03-15) .. PLEASE keep this roughly in commit order as shown by git-log / tig (new to old) +* Added vmod ``math``. + .. _4389: https://github.com/varnishcache/varnish-cache/issues/4389 * ``req.ttl`` has been renamed to ``req.max_age`` for clarity, with ``req.ttl`` diff --git a/doc/sphinx/Makefile.am b/doc/sphinx/Makefile.am index fac1fc7aaee..4f2291f476e 100644 --- a/doc/sphinx/Makefile.am +++ b/doc/sphinx/Makefile.am @@ -206,6 +206,10 @@ include/vmod_proxy.generated.rst: $(top_builddir)/vmod/vmod_proxy.rst cp $(top_builddir)/vmod/vmod_proxy.rst $@ BUILT_SOURCES += include/vmod_proxy.generated.rst +include/vmod_math.generated.rst: $(top_builddir)/vmod/vmod_math.rst + cp $(top_builddir)/vmod/vmod_math.rst $@ +BUILT_SOURCES += include/vmod_math.generated.rst + EXTRA_DIST += $(BUILT_SOURCES) CLEANFILES = $(BUILT_SOURCES) diff --git a/doc/sphinx/reference/index.rst b/doc/sphinx/reference/index.rst index 0d5dc065766..59120b0c3e3 100644 --- a/doc/sphinx/reference/index.rst +++ b/doc/sphinx/reference/index.rst @@ -37,6 +37,7 @@ Bundled VMODs vmod_cookie.rst vmod_directors.rst vmod_h2.rst + vmod_math.rst vmod_proxy.rst vmod_purge.rst vmod_std.rst diff --git a/doc/sphinx/reference/vmod_math.rst b/doc/sphinx/reference/vmod_math.rst new file mode 100644 index 00000000000..b5fe30d6200 --- /dev/null +++ b/doc/sphinx/reference/vmod_math.rst @@ -0,0 +1,7 @@ +.. + Copyright (c) 2019 Varnish Software AS + SPDX-License-Identifier: BSD-2-Clause + See LICENSE file for full text of license + + +.. include:: ../include/vmod_math.generated.rst diff --git a/man/Makefile.am b/man/Makefile.am index 436d7d255d1..c1a52b567e5 100644 --- a/man/Makefile.am +++ b/man/Makefile.am @@ -27,7 +27,8 @@ dist_man_MANS = \ vmod_blob.3 \ vmod_unix.3 \ vmod_proxy.3 \ - vmod_h2.3 + vmod_h2.3 \ + vmod_math.3 CLEANFILES = $(dist_man_MANS) @@ -146,4 +147,8 @@ vmod_proxy.3: $(top_builddir)/vmod/vmod_proxy.man.rst vmod_h2.3: $(top_builddir)/vmod/vmod_h2.man.rst $(BUILD_MAN) $? $@ +vmod_math.3: $(top_builddir)/vmod/vmod_math.man.rst + $(BUILD_MAN) $? $@ + + .NOPATH: $(dist_man_MANS) diff --git a/vmod/Makefile.am b/vmod/Makefile.am index 7608c0b5067..38c80990874 100644 --- a/vmod/Makefile.am +++ b/vmod/Makefile.am @@ -33,6 +33,7 @@ include $(srcdir)/automake_boilerplate_h2.am include $(srcdir)/automake_boilerplate_cookie.am include $(srcdir)/automake_boilerplate_debug.am include $(srcdir)/automake_boilerplate_directors.am +include $(srcdir)/automake_boilerplate_math.am include $(srcdir)/automake_boilerplate_proxy.am include $(srcdir)/automake_boilerplate_purge.am include $(srcdir)/automake_boilerplate_std.am @@ -55,3 +56,17 @@ vmod_debug_symbols_regex = 'Vmod_.*_Data' # not --strict, not installed vmodtoolargs_debug = --boilerplate --noinst -o vcc_debug_if + +### vmod_math specific +# the specs are deliberately checked in to not make the build +# dependend on external connectivity +vmod_math_spec.html: + curl -o $@ https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/math.h.html + +vmod_math.c: vmod_math.vcc + +vmod_math.vcc: vmod_math_spec.html vmod_math_gen.py + @PYTHON@ $(srcdir)/vmod_math_gen.py $< vmod_math.vcc vmod_math.c + +# avoid running curl when building from a dist +dist_noinst_SCRIPTS = vmod_math_gen.py vmod_math_spec.html diff --git a/vmod/automake_boilerplate_math.am b/vmod/automake_boilerplate_math.am new file mode 100644 index 00000000000..e6fa70fb415 --- /dev/null +++ b/vmod/automake_boilerplate_math.am @@ -0,0 +1,41 @@ +## Generated by vmodtool.py --boilerplate. + +vmod_LTLIBRARIES += libvmod_math.la +dist_vcc_DATA += $(srcdir)/vmod_math.vcc + +libvmod_math_la_SOURCES = \ + vmod_math.c \ + vmod_math_util.c + +libvmod_math_la_CFLAGS = + +vmodtoolargs_math ?= --strict --boilerplate -o vcc_math_if +vmod_math_symbols_regex ?= Vmod_math_Data + +libvmod_math_la_LDFLAGS = \ + -export-symbols-regex $(vmod_math_symbols_regex) \ + $(AM_LDFLAGS) \ + $(VMOD_LDFLAGS) \ + -rpath $(vmoddir) + +nodist_libvmod_math_la_SOURCES = vcc_math_if.c vcc_math_if.h + +EXTRA_libvmod_math_la_DEPENDENCIES = $(nodist_libvmod_math_la_SOURCES) + +EXTRA_DIST += automake_boilerplate_math.am + +$(libvmod_math_la_OBJECTS): vcc_math_if.h + +vcc_math_if.h vmod_math.rst vmod_math.man.rst: vcc_math_if.c + +# A doc-change will not update mtime on the .h and .c files, so a +# touch(1) is necessary to signal that vmodtool was in fact run. +vcc_math_if.c: $(VMODTOOL) $(srcdir)/vmod_math.vcc + @PYTHON@ $(VMODTOOL) $(vmodtoolargs_math) $(srcdir)/vmod_math.vcc + touch vcc_math_if.c + +clean-local: clean-vmod-math + +clean-vmod-math: + rm -f $(nodist_libvmod_math_la_SOURCES) + rm -f vmod_math.rst vmod_math.man.rst diff --git a/vmod/tests/math_b00000.vtc b/vmod/tests/math_b00000.vtc new file mode 100644 index 00000000000..10db4c5532a --- /dev/null +++ b/vmod/tests/math_b00000.vtc @@ -0,0 +1,78 @@ +varnishtest vmod_math + +varnish v1 -vcl { + import math; + + backend proforma none; + + sub vcl_recv { + return (synth(200)); + } + + sub vcl_synth { + if (req.http.strfromdfmt) { + set resp.http.result = math.strfromd(req.http.strfromdfmt, math.constant(M_PI)); + return (deliver); + } + + # formatting basics + set resp.http."n.v" = 0.1; + set resp.http."n.13a" = math.strfromd("%.13a", 0.1); + set resp.http."n.17e" = math.strfromd("%.17e", 0.1); + set resp.http."n.17f" = math.strfromd("%.17f", 0.1); + set resp.http."n.g" = math.strfromd("%g", 0.1); + + # edge cases where approx makes a difference + + set resp.http."sinpi.v" = math.sin(math.constant(M_PI)); + set resp.http."sinpi.17f" = math.strfromd("%.17f", math.sin(math.constant(M_PI))); + set resp.http."sinpi.0.equals" = math.sin(math.constant(M_PI)) == 0.0; + set resp.http."sinpi.0.approx" = math.approx(math.sin(math.constant(M_PI)), 0); + set resp.http."sinpi.0.zero" = + math.fpclassify(math.sin(math.constant(M_PI))) == + math.fpclass(FP_ZERO); + + # VRT_DECIMAL_MAX == 0x426d1a94a1fffff8 + set resp.http."some1.v" = 999999999999 + 0.999; + set resp.http."some1.f" = math.strfromd("%f", 999999999999 + 0.999); + # VRT_DECIMAL_MAX - ULP == 0x426d1a94a1fffff7 + set resp.http."some2.v" = 999999999999 + (9.989 / 10); + set resp.http."some2.f" = math.strfromd("%f", 999999999999 + (9.989 / 10)); + + set resp.http."some1.some2.equals" = + (999999999999 + 0.999) == (999999999999 + (9.989 / 10)); + set resp.http."some1.some2.approx" = + math.approx(999999999999 + 0.999, 999999999999 + (9.989 / 10)); + + return (deliver); + } +} -start + +client c1 { + txreq + rxresp + expect resp.status == 200 + + expect resp.http.n.v == 0.100 + expect resp.http.n.13a == 0x1.999999999999ap-4 + expect resp.http.n.17e == 1.00000000000000006e-01 + expect resp.http.n.17f == 0.10000000000000001 + expect resp.http.n.g == 0.1 + + expect resp.http.sinpi.v == 0.000 + expect resp.http.sinpi.17f == 0.00000000000000012 + expect resp.http.sinpi.0.equals == false + expect resp.http.sinpi.0.approx == true + expect resp.http.sinpi.0.zero == false + + expect resp.http.some1.v == 999999999999.999 + expect resp.http.some1.f == 999999999999.999023 + expect resp.http.some2.v == 999999999999.999 + expect resp.http.some2.f == 999999999999.998901 + expect resp.http.some1.some2.equals == false + expect resp.http.some1.some2.approx == true + + txreq -hdr "strfromdfmt: %5f" + rxresp + expect resp.status == 500 +} -run diff --git a/vmod/vmod_math_gen.py b/vmod/vmod_math_gen.py new file mode 100755 index 00000000000..2b1394c0639 --- /dev/null +++ b/vmod/vmod_math_gen.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 + +# Copyright 2025 UPLEX - Nils Goroll Systemoptimierung +# All rights reserved. +# +# Author: Nils Goroll +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. +# +# generate vmod_math vcc and c files from opengroup spec html + +import re +import sys + + +vcc_type_map = { + "int": "INT", + "double": "REAL", + "long": "INT", + "real-floating": "REAL", + "const char *": "STRING", +} + +def_arg_names = ["x", "y", "z"] +arg_names_map = { + "atan2": ["y", "x"], + "ldexp": ["x", "exp"], + "nan": ["tag"], + "scalbln": ["x", "exp"], + "yn": ["n", "x"], +} + +# type name +re_arg = re.compile(r"^(.+?)(\s+[xy])?$") +# argument separator +re_argsep = re.compile(r",\s*") + + +def vcc_arg(arg, n): + match = re_arg.search(arg) + if match is None: + print(f"Error: no re_arg match on '{arg}'") + sys.exit(1) + # print(match) + + atype = vcc_type_map[match.group(1)] + name = match.group(2) + + if name is None: + name = n + + return f"{atype} {name}" + + +def gen_func_vcc(match, vcc_fh): + rtype = match.group(1) + name = match.group(2) + args = match.group(3) + + # print(match) + + rtype = vcc_type_map[rtype] + args = re_argsep.split(args) + + argnames = def_arg_names[: len(args)] + if name in arg_names_map: + argnames = arg_names_map[name] + + args = ", ".join([vcc_arg(arg, name) for arg, name in zip(args, argnames)]) + + tpl = f""" +$Function {rtype} {name}({args}) +""" + + vcc_fh.write(tpl) + + +def c_arg(arg, n): + match = re_arg.search(arg) + if match is None: + print(f"Error: no re_arg match on '{arg}'") + sys.exit(1) + # print(match) + + atype = "VCL_" + vcc_type_map[match.group(1)] + name = match.group(2) + + if name is None: + name = n + + return f"{atype} {name}" + + +def gen_func_c(match, c_fh): + rtype = match.group(1) + name = match.group(2) + args = match.group(3) + + # print(match) + + rtype = "VCL_" + vcc_type_map[rtype] + args = re_argsep.split(args) + + argnames = def_arg_names[: len(args)] + if name in arg_names_map: + argnames = arg_names_map[name] + + args = ", ".join([c_arg(arg, name) for arg, name in zip(args, argnames)]) + argnames = ", ".join(argnames) + + tpl = f""" +{rtype} +vmod_{name}(VRT_CTX, {args}) +{{ + (void)ctx; + return ({name}({argnames})); +}} +""" + + c_fh.write(tpl) + + +def gen_func(func, vcc_fh, c_fh): + gen_func_vcc(func, vcc_fh) + gen_func_c(func, c_fh) + + +# rtype name (args...) +re_spec_funcs = re.compile(r"\b([a-z0-9 ]+?)\s+([a-z0-9]+)\((.*)\)(?=;)") +# disregard variants for types we do not need or can not support +# not support: frexp(double, int *) etc returning two values +re_func_disregard = re.compile(r"long double|float\b|long long|int \*|double \*") + + +def gen_funcs(spec, vcc_fh, c_fh): + header = """ + +math.h functions +---------------- + +The semantics of functions mapping directly to `math.h(7)` are not documented +herein, see the system documentation instead (for example using ``man +``). + +""" + vcc_fh.write(header) + + for match in re_spec_funcs.finditer(spec): + f = match.group(0) + # print("XXX " + match.group(0)) + if re_func_disregard.search(f): + # print(f"disregard: {f}") + continue + gen_func(match, vcc_fh, c_fh) + + +def gen_enumfunc(ret, func, enums, doc, vcc_fh, c_fh): + enumcomma = ", ".join(enums) + + tpl = f""" +$Function {ret} {func}(ENUM {{ {enumcomma} }} name) + +{doc} +""" + + vcc_fh.write(tpl) + + pre = f""" +VCL_{ret} +vmod_{func}(VRT_CTX, VCL_ENUM name) +{{ + (void)ctx; +""" + + post = f""" + WRONG("{func} enum"); +}} +""" + + c_fh.write(pre) + for enum in enums: + body = f""" + if (name == VENUM({enum})) return ({enum}); +""" + c_fh.write(body) + c_fh.write(post) + + +re_spec_const = re.compile(r">(M_[A-Z0-9_]+)<") +# Austin Group Defect 1503 - not yet available on Linux as of Debian 12.12 2025-12 +re_const_disregard = re.compile("^(M_1_SQRTPI|M_EGAMMA|M_PHI|M_SQRT1_3|M_SQRT3)$") + + +def gen_const(spec, vcc_fh, c_fh): + a = [ + # DBL_* from float.h + "DBL_MANT_DIG", + "DBL_DIG", + "DBL_MIN_EXP", + "DBL_MIN_10_EXP", + "DBL_MAX_EXP", + "DBL_MAX_10_EXP", + "DBL_MAX", + "DBL_EPSILON", + "DBL_MIN", + # HUGE_VAL not worth extracting from html + "HUGE_VAL", + ] + + for match in re_spec_const.finditer(spec): + m = match.group(1) + if re_const_disregard.search(m): + continue + a.append(m) + + doc = """ +Return the value of the named constant. For ``DBL_*`` see `float.h(7)`, +otherwise `math.h(7)` for details. +""" + gen_enumfunc("REAL", "constant", a, doc, vcc_fh, c_fh) + + +# not worth grepping the FP_ macros from the html +def gen_class(spec, vcc_fh, c_fh): + # not worth extracting from html + a = ["FP_INFINITE", "FP_NAN", "FP_NORMAL", "FP_SUBNORMAL", "FP_ZERO"] + + doc = """ +Return the value of the named constant for comparisons of `math.fpclassify()`_ +return values. + +""" + + gen_enumfunc("INT", "fpclass", a, doc, vcc_fh, c_fh) + + +vcc_top = """ +#- +# This document is licensed under the same conditions as Varnish-Cache itself. +# See LICENSE for details. +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Author: Nils Goroll + +$ABI vrt +$Module math 3 "VMOD wrapping math.h" + +.. THIS CODE IS AUTO-GENERATED. DO NOT EDIT HERE. see vmod_math_gen.py + +DESCRIPTION +=========== + +This VMOD wraps the functions in `math.h(7)`, provides additional utilities and +includes functions to access macros and constants from `math.h(7)` and +`float.h(7)`. + +Utility functions +----------------- + +.. source is in vmod_math_util.c + +$Function BOOL approx(REAL a, REAL b, REAL maxDiff = 0.0, REAL maxRelDiff = 0.0) + +.. _`Comparing Floating Point Numbers, 2012 Edition`: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + +Return true if the two numbers *a* and *b* are approximately equal per the +``AlmostEqualRelativeAndAbs`` function from `Comparing Floating Point Numbers, +2012 Edition`_ given the additional parameters *maxDiff* and *maxRelDiff*. Read +the blog post for details on why the seemingly simple question of two floating +point numbers being equal has no simple answers. + +For their default values of 0, the two additional parameters are initialized to: + +- *maxDiff*: ``4 * DBL_EPSILON`` +- *maxRelDiff*: ``DBL_EPSILON`` + +$Function STRING strfromd(STRING format, REAL fp) + +Convert the value *fp* into a string using *format*, see `strfromd(3)`. + +An invalid format string results in a VCL error and the ``NULL`` invalid string +returned. + +.. Internally, vsnprintf() is called via WS_Printf(). The difference to + VRT_REAL_string() is the free format and missing call to VRT_REAL_is_valid() + +Access to macros and constants +------------------------------ + +""" + +c_top = """ +/* this code is auto-generated. Do not edit */ +#include "config.h" + +#include +#include + +#include "vdef.h" +#include "vas.h" +#include "vrt.h" +#include "vcc_math_if.h" +""" + + +def main(): + # Check command line arguments + if len(sys.argv) != 4: + print("Usage: python3 script.py ") + sys.exit(1) + + spec_file = sys.argv[1] + vcc_file = sys.argv[2] + c_file = sys.argv[3] + + spec = "" + + try: + with open(spec_file, "r") as f: + spec = f.read() + except FileNotFoundError: + print(f"Error: Input file '{spec_file}' not found") + sys.exit(1) + + with open(vcc_file, "w") as vcc_fh: + vcc_fh.write(vcc_top) + with open(c_file, "w") as c_fh: + c_fh.write(c_top) + gen_const(spec, vcc_fh, c_fh) + gen_class(spec, vcc_fh, c_fh) + gen_funcs(spec, vcc_fh, c_fh) + print(f"Output written to '{vcc_file}' and '{c_file}'") + + +if __name__ == "__main__": + main() diff --git a/vmod/vmod_math_spec.html b/vmod/vmod_math_spec.html new file mode 100644 index 00000000000..5c70b06bc71 --- /dev/null +++ b/vmod/vmod_math_spec.html @@ -0,0 +1,696 @@ + + + + + + + + +<math.h> + + + + + + +
The Open Group Base Specifications Issue 8
+IEEE Std 1003.1-2024
+Copyright © 2001-2024 The IEEE and The Open Group
+
+ + +

NAME

+
math.h — mathematical declarations
+

SYNOPSIS

+
+

#include <math.h>

+
+

DESCRIPTION

+
+
[CX] [Option Start] Some of the functionality described on this reference page extends the ISO C standard. Applications shall define +the appropriate feature test macro (see XSH 2.2 The Compilation +Environment) to enable the visibility of these symbols in this header. [Option End]
+

The <math.h> header shall define at least the following types:

+
+
+
float_t
+
A real-floating type at least as wide as float.
+
double_t
+
A real-floating type at least as wide as double, and at least as wide as float_t.
+
+

If FLT_EVAL_METHOD equals 0, float_t and double_t shall be float and double, respectively; if +FLT_EVAL_METHOD equals 1, they shall both be double; if FLT_EVAL_METHOD equals 2, they shall both be long double; for +other values of FLT_EVAL_METHOD, they are otherwise implementation-defined.

+

The <math.h> header shall define the following macros, where real-floating indicates that the argument shall be an +expression of real-floating type:

+
+int fpclassify(real-floating x);
+int isfinite(real-floating x);
+int isgreater(real-floating x, real-floating y);
+int isgreaterequal(real-floating x, real-floating y);
+int isinf(real-floating x);
+int isless(real-floating x, real-floating y);
+int islessequal(real-floating x, real-floating y);
+int islessgreater(real-floating x, real-floating y);
+int isnan(real-floating x);
+int isnormal(real-floating x);
+int isunordered(real-floating x, real-floating y);
+int signbit(real-floating x);
+
+

[XSI] [Option Start] +The <math.h> header shall define the following symbolic constants. Where the constant name ends in 'l' (lower +case ell), the values shall have type long double; otherwise the values shall have type double. The values shall be +accurate to the precision of their type. If the implementation supports FLT_EVAL_METHOD values other than 0 or 1, the values shall +either include an explicit cast for that type, or be expressed as hexadecimal floating constants.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Double

+
+

Long Double

+
+

Value

+
+

M_E

+
+

M_El

+
+

Value of \(e\)

+
+

M_EGAMMA

+
+

M_EGAMMAl

+
+

Value of \(\gamma\), Euler-Mascheroni constant

+
+

M_LOG2E

+
+

M_LOG2El

+
+

Value of \(\log _2 e\)

+
+

M_LOG10E

+
+

M_LOG10El

+
+

Value of \(log _{10} e\)

+
+

M_LN2

+
+

M_LN2l

+
+

Value of \(log _e 2\)

+
+

M_LN10

+
+

M_LN10l

+
+

Value of \(log _e 10\)

+
+

M_PHI

+
+

M_PHIl

+
+

Value of \(\phi,(1+\sqrt{5}) / 2\) golden ratio constant, golden ratio constant

+
+

M_PI

+
+

M_PIl

+
+

Value of \(\pi\)

+
+

M_PI_2

+
+

M_PI_2l

+
+

Value of \(\pi /2\)

+
+

M_PI_4

+
+

M_PI_4l

+
+

Value of \(\pi /4\)

+
+

M_1_PI

+
+

M_1_PIl

+
+

Value of \(1/ \pi\)

+
+

M_1_SQRTPI

+
+

M_1_SQRTPIl

+
+

Value of \(1/ \sqrt \pi\)

+
+

M_2_PI

+
+

M_2_PIl

+
+

Value of \(2/ \pi\)

+
+

M_2_SQRTPI

+
+

M_2_SQRTPIl

+
+

Value of \(2/ \sqrt \pi\)

+
+

M_SQRT2

+
+

M_SQRT2l

+
+

Value of \(\sqrt 2\)

+
+

M_SQRT3

+
+

M_SQRT3l

+
+

Value of \(\sqrt 3\)

+
+

M_SQRT1_2

+
+

M_SQRT1_2l

+
+

Value of \(1/ \sqrt 2\)

+
+

M_SQRT1_3

+
+

M_SQRT1_3l

+
+

Value of \(1/ \sqrt 3\)

+
+
+[Option End] +

The <math.h> header shall define the following macros:

+
+
+
HUGE_VAL
+
A positive double constant expression, not necessarily representable as a float. Used as an error value returned +by the mathematics library. HUGE_VAL evaluates to +infinity on systems supporting IEEE Std 754-1985.
+
HUGE_VALF
+
A positive float constant expression. Used as an error value returned by the mathematics library. HUGE_VALF evaluates to ++infinity on systems supporting IEEE Std 754-1985.
+
HUGE_VALL
+
A positive long double constant expression. Used as an error value returned by the mathematics library. HUGE_VALL +evaluates to +infinity on systems supporting IEEE Std 754-1985.
+
INFINITY
+
A constant expression of type float representing positive or unsigned infinity, if available; else a positive constant +of type float that overflows at translation time.
+
NAN
+
A constant expression of type float representing a quiet NaN. This macro is only defined if the implementation supports +quiet NaNs for the float type.
+
+

The following macros shall be defined for number classification. They represent the mutually-exclusive kinds of +floating-point values. They expand to integer constant expressions with distinct values. Additional implementation-defined +floating-point classifications, with macro definitions beginning with FP_ and an uppercase letter, may also be specified by the +implementation.

+
+
+FP_INFINITE
+FP_NAN
+FP_NORMAL
+FP_SUBNORMAL
+FP_ZERO
+
+

The following optional macros indicate whether the fma() family of +functions are fast compared with direct code:

+
+
+FP_FAST_FMA
+FP_FAST_FMAF
+FP_FAST_FMAL
+
+

If defined, the FP_FAST_FMA macro shall expand to the integer constant 1 and shall indicate that the fma() function generally executes about as fast as, or faster than, a multiply and an add of +double operands. If undefined, the speed of execution is unspecified. The other macros have the equivalent meaning for the +float and long double versions.

+

The following macros shall expand to integer constant expressions whose values are returned by ilogb( +x) if x is zero or NaN, respectively. The value of FP_ILOGB0 shall be either {INT_MIN} or - {INT_MAX}. The value of +FP_ILOGBNAN shall be either {INT_MAX} or {INT_MIN}.

+
+
+FP_ILOGB0
+FP_ILOGBNAN
+
+

The following macros shall expand to the integer constants 1 and 2, respectively;

+
+
+MATH_ERRNO
+MATH_ERREXCEPT
+
+

The following macro shall expand to an expression that has type int and the value MATH_ERRNO, +MATH_ERREXCEPT, or the bitwise-inclusive OR of both:

+
+
+math_errhandling
+
+

The value of math_errhandling is constant for the duration of the program. It is unspecified whether +math_errhandling is a macro or an identifier with external linkage. If a macro definition is suppressed or a program defines an +identifier with the name math_errhandling , the behavior is undefined. If the expression (math_errhandling & MATH_ERREXCEPT) +can be non-zero, the implementation shall define the macros FE_DIVBYZERO, FE_INVALID, and FE_OVERFLOW in <fenv.h>.

+

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be +provided.

+
+double      acos(double);
+float       acosf(float);
+double      acosh(double);
+float       acoshf(float);
+long double acoshl(long double);
+long double acosl(long double);
+double      asin(double);
+float       asinf(float);
+double      asinh(double);
+float       asinhf(float);
+long double asinhl(long double);
+long double asinl(long double);
+double      atan(double);
+double      atan2(double, double);
+float       atan2f(float, float);
+long double atan2l(long double, long double);
+float       atanf(float);
+double      atanh(double);
+float       atanhf(float);
+long double atanhl(long double);
+long double atanl(long double);
+double      cbrt(double);
+float       cbrtf(float);
+long double cbrtl(long double);
+double      ceil(double);
+float       ceilf(float);
+long double ceill(long double);
+double      copysign(double, double);
+float       copysignf(float, float);
+long double copysignl(long double, long double);
+double      cos(double);
+float       cosf(float);
+double      cosh(double);
+float       coshf(float);
+long double coshl(long double);
+long double cosl(long double);
+double      erf(double);
+double      erfc(double);
+float       erfcf(float);
+long double erfcl(long double);
+float       erff(float);
+long double erfl(long double);
+double      exp(double);
+double      exp2(double);
+float       exp2f(float);
+long double exp2l(long double);
+float       expf(float);
+long double expl(long double);
+double      expm1(double);
+float       expm1f(float);
+long double expm1l(long double);
+double      fabs(double);
+float       fabsf(float);
+long double fabsl(long double);
+double      fdim(double, double);
+float       fdimf(float, float);
+long double fdiml(long double, long double);
+double      floor(double);
+float       floorf(float);
+long double floorl(long double);
+double      fma(double, double, double);
+float       fmaf(float, float, float);
+long double fmal(long double, long double, long double);
+double      fmax(double, double);
+float       fmaxf(float, float);
+long double fmaxl(long double, long double);
+double      fmin(double, double);
+float       fminf(float, float);
+long double fminl(long double, long double);
+double      fmod(double, double);
+float       fmodf(float, float);
+long double fmodl(long double, long double);
+double      frexp(double, int *);
+float       frexpf(float, int *);
+long double frexpl(long double, int *);
+double      hypot(double, double);
+float       hypotf(float, float);
+long double hypotl(long double, long double);
+int         ilogb(double);
+int         ilogbf(float);
+int         ilogbl(long double);
+[XSI][Option Start]
+double      j0(double);
+double      j1(double);
+double      jn(int, double);
+[Option End]
+double      ldexp(double, int);
+float       ldexpf(float, int);
+long double ldexpl(long double, int);
+double      lgamma(double);
+float       lgammaf(float);
+long double lgammal(long double);
+long long   llrint(double);
+long long   llrintf(float);
+long long   llrintl(long double);
+long long   llround(double);
+long long   llroundf(float);
+long long   llroundl(long double);
+double      log(double);
+double      log10(double);
+float       log10f(float);
+long double log10l(long double);
+double      log1p(double);
+float       log1pf(float);
+long double log1pl(long double);
+double      log2(double);
+float       log2f(float);
+long double log2l(long double);
+double      logb(double);
+float       logbf(float);
+long double logbl(long double);
+float       logf(float);
+long double logl(long double);
+long        lrint(double);
+long        lrintf(float);
+long        lrintl(long double);
+long        lround(double);
+long        lroundf(float);
+long        lroundl(long double);
+double      modf(double, double *);
+float       modff(float, float *);
+long double modfl(long double, long double *);
+double      nan(const char *);
+float       nanf(const char *);
+long double nanl(const char *);
+double      nearbyint(double);
+float       nearbyintf(float);
+long double nearbyintl(long double);
+double      nextafter(double, double);
+float       nextafterf(float, float);
+long double nextafterl(long double, long double);
+double      nexttoward(double, long double);
+float       nexttowardf(float, long double);
+long double nexttowardl(long double, long double);
+double      pow(double, double);
+float       powf(float, float);
+long double powl(long double, long double);
+double      remainder(double, double);
+float       remainderf(float, float);
+long double remainderl(long double, long double);
+double      remquo(double, double, int *);
+float       remquof(float, float, int *);
+long double remquol(long double, long double, int *);
+double      rint(double);
+float       rintf(float);
+long double rintl(long double);
+double      round(double);
+float       roundf(float);
+long double roundl(long double);
+double      scalbln(double, long);
+float       scalblnf(float, long);
+long double scalblnl(long double, long);
+double      scalbn(double, int);
+float       scalbnf(float, int);
+long double scalbnl(long double, int);
+double      sin(double);
+float       sinf(float);
+double      sinh(double);
+float       sinhf(float);
+long double sinhl(long double);
+long double sinl(long double);
+double      sqrt(double);
+float       sqrtf(float);
+long double sqrtl(long double);
+double      tan(double);
+float       tanf(float);
+double      tanh(double);
+float       tanhf(float);
+long double tanhl(long double);
+long double tanl(long double);
+double      tgamma(double);
+float       tgammaf(float);
+long double tgammal(long double);
+double      trunc(double);
+float       truncf(float);
+long double truncl(long double);
+[XSI][Option Start]
+double      y0(double);
+double      y1(double);
+double      yn(int, double);
+[Option End]
+
+

The following external variable shall be defined:

+
+[XSI][Option Start]
+extern int signgam;
+[Option End]
+
+

The behavior of each of the functions defined in <math.h> is specified in the System Interfaces volume +of POSIX.1-2024 for all representable values of its input arguments, except where stated otherwise. Each function shall execute as +if it were a single operation without generating any externally visible exceptional conditions.

+
+
+
The following sections are informative.
+

APPLICATION USAGE

+
+

The FP_CONTRACT pragma can be used to allow (if the state is on) or disallow (if the state is off) the implementation to +contract expressions. Each pragma can occur either outside external declarations or preceding all explicit declarations and +statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until +another FP_CONTRACT pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma +takes effect from its occurrence until another FP_CONTRACT pragma is encountered (including within a nested compound statement), or +until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition +just before the compound statement. If this pragma is used in any other context, the behavior is undefined. The default state (on +or off) for the pragma is implementation-defined.

+
+

RATIONALE

+
+

Before the ISO/IEC 9899:1999 standard, the math library was defined only for the floating type double. All the names +formed by appending 'f' or 'l' to a name in <math.h> were reserved to allow for the definition of +float and long double libraries; and the ISO/IEC 9899:1999 standard provided for all three versions of math +functions.

+

The functions ecvt(), fcvt(), and gcvt() have been dropped from the ISO C standard since +their capability is available through sprintf().

+

The requirement for an explicit cast or representation via hexadecimal floating constants is to guarantee that even +when FLT_EVAL_METHOD is neither 0 nor 1, the expression (double)M_PI == M_PI will always hold true. Earlier versions of +this standard did not make this requirement, because they lacked the 'l' (lower case ell) versions of the constants and +were allowed to provide M_PI with long double precision depending on FLT_EVAL_METHOD.

+
+

FUTURE DIRECTIONS

+
+

None.

+
+

SEE ALSO

+
+

<float.h>, <stddef.h> +, <sys/types.h>

+

XSH 2.2 The Compilation Environment, acos, acosh, asin, asinh, atan, atan2, atanh, cbrt, ceil, copysign, cos, cosh, erf, erfc, exp, exp2, expm1, fabs, fdim, floor, fma, fmax, fmin, fmod, fpclassify, frexp, hypot, ilogb, isfinite, isgreater, isinf, isnan, isnormal, isunordered, j0, ldexp, lgamma, llrint, llround, log, log10, log1p, log2, logb, lrint, lround, modf, nan, nearbyint, nextafter, pow, remainder, remquo, rint, round, scalbln, signbit, sin, sinh, sqrt, tan, tanh, tgamma, trunc, y0

+
+

CHANGE HISTORY

+
+

First released in Issue 1.

+
+

Issue 6

+
+

This reference page is updated to align with the ISO/IEC 9899:1999 standard.

+

IEEE Std 1003.1-2001/Cor 2-2004, item XBD/TC2/D6/21 is applied, making it clear that the meaning of +the FP_FAST_FMA macro is unspecified if the macro is undefined.

+
+

Issue 7

+
+

ISO/IEC 9899:1999 standard, Technical Corrigendum 2 #47 (SD5-XBD-ERN-52) is applied, clarifying the wording of the +FP_FAST_FMA macro.

+

The MAXFLOAT constant is marked obsolescent.

+

This reference page is clarified with respect to macros and symbolic constants.

+

POSIX.1-2008, Technical Corrigendum 2, XBD/TC2-2008/0063 [801] and XBD/TC2-2008/0064 [801] are applied.

+
+

Issue 8

+
+

Austin Group Defect 828 is applied, adding long double counterparts with names ending in 'l' to the +double constants whose names begin with "M_" , and changing the representation requirements for those +constants.

+

Austin Group Defect 1302 is applied, changing "provides" to "provided".

+

Austin Group Defect 1330 is applied, removing the obsolescent MAXFLOAT.

+

Austin Group Defect 1503 is applied, adding M_1_SQRTPI, M_EGAMMA, M_PHI, M_SQRT1_3, and M_SQRT3.

+
+
End of informative text.
+

 

+return to top of page
+
+
UNIX® is a registered Trademark of The Open Group.
+POSIX™ is a Trademark of The IEEE.
+Copyright © 2001-2024 The IEEE and The Open Group, All Rights Reserved
+[ Main Index | XBD | XSH | XCU | XRAT +]
+
+ + + diff --git a/vmod/vmod_math_util.c b/vmod/vmod_math_util.c new file mode 100644 index 00000000000..74787bc0847 --- /dev/null +++ b/vmod/vmod_math_util.c @@ -0,0 +1,109 @@ +/*- + * Copyright 2025 UPLEX - Nils Goroll Systemoptimierung + * All rights reserved. + * + * Author: Nils Goroll + * + * Includes code by Bruce Dawson + * + * SPDX-License-Identifier: BSD-2-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "config.h" + +#include +#include + +#include "miniobj.h" +#include "cache/cache.h" +#include "vcc_math_if.h" + +/* + * this is AlmostEqualRelativeAndAbs() by Bruce Dawson + * https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + */ +VCL_BOOL +vmod_approx(VRT_CTX, VCL_REAL a, VCL_REAL b, VCL_REAL maxDiff, VCL_REAL maxRelDiff) +{ + (void)ctx; + + if (fpclassify(maxDiff) == FP_ZERO) + maxDiff = 4 * DBL_EPSILON; + + if (fpclassify(maxRelDiff) == FP_ZERO) + maxRelDiff = DBL_EPSILON; + + VCL_REAL diff = fabs(a - b); + if (diff <= maxDiff) + return (1); + + a = fabs(a); + b = fabs(b); + VCL_REAL largest = (b > a) ? b : a; + + if (diff <= largest * maxRelDiff) + return (1); + + return (0); +} + +static int +valid_fmt(VCL_STRING fmt) +{ + if (fmt == NULL || *fmt != '%') + return (0); + fmt++; + if (*fmt == '.') { + fmt++; + while (*fmt >= '0' && *fmt <= '9') + fmt++; + } + switch (*fmt) { + case 'a': + case 'A': + case 'e': + case 'E': + case 'f': + case 'F': + case 'g': + case 'G': + return (1); + default: + return (0); + } +} + +VCL_STRING +vmod_strfromd(VRT_CTX, VCL_STRING fmt, VCL_REAL fp) +{ + CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC); + + if (! valid_fmt(fmt)) { + VRT_fail(ctx, "math.strfromd(\"%s\", ...): Invalid format", + fmt ? fmt : ""); + return (NULL); + } + + return (WS_Printf(ctx->ws, fmt, fp)); +}