[4.0] b61800b Add a string to real conversion function

Federico G. Schwindt fgsch at lodoss.net
Tue Jun 24 11:31:57 CEST 2014


commit b61800b639eb853faeebb3587592eb37006df199
Author: Federico G. Schwindt <fgsch at lodoss.net>
Date:   Sun Jun 22 09:49:35 2014 +0100

    Add a string to real conversion function
    
    As discussed on the latest vdd.

diff --git a/bin/varnishtest/tests/m00015.vtc b/bin/varnishtest/tests/m00015.vtc
new file mode 100644
index 0000000..077bbaf
--- /dev/null
+++ b/bin/varnishtest/tests/m00015.vtc
@@ -0,0 +1,23 @@
+varnishtest "Test vmod_std.real conversion"
+
+server s1 {
+	rxreq
+	txresp
+} -start
+
+varnish v1 -vcl+backend {
+	import ${vmod_std};
+
+	sub vcl_deliver {
+		set resp.http.x-real = std.real(req.http.foo, 0.0);
+		set resp.http.x-fallback = std.real(req.http.bar, 0.0);
+	}
+} -start
+
+client c1 {
+	txreq -hdr "foo: 1.00"
+	rxresp
+	expect resp.status == 200
+	expect resp.http.x-real == 1.000
+	expect resp.http.x-fallback == 0.000
+} -run
diff --git a/lib/libvmod_std/vmod.vcc b/lib/libvmod_std/vmod.vcc
index 0be272e..cc3eb43 100644
--- a/lib/libvmod_std/vmod.vcc
+++ b/lib/libvmod_std/vmod.vcc
@@ -135,6 +135,14 @@ Description
 Example
 	if (std.ip(req.http.X-forwarded-for, "0.0.0.0") ~ my_acl) { ... }
 
+$Function REAL real(STRING, REAL)
+
+Description
+	Converts the string *s* to a real.  If *s* fails to parse,
+	*fallback* will be returned.
+Example
+	set req.http.x-real = std.real(req.http.x-foo, 0.0);
+
 $Function BOOL healthy(BACKEND)
 
 Description
diff --git a/lib/libvmod_std/vmod_std_conversions.c b/lib/libvmod_std/vmod_std_conversions.c
index f98b5fb..7c1ac08 100644
--- a/lib/libvmod_std/vmod_std_conversions.c
+++ b/lib/libvmod_std/vmod_std_conversions.c
@@ -168,3 +168,33 @@ vmod_ip(const struct vrt_ctx *ctx, VCL_STRING s, VCL_IP d)
 		freeaddrinfo(res0);
 	return (r);
 }
+
+VCL_REAL __match_proto__()
+vmod_real(const struct vrt_ctx *ctx, VCL_STRING p, VCL_REAL d)
+{
+	char *e;
+	double r;
+
+	CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);
+
+	if (p == NULL)
+		return (d);
+
+	while (isspace(*p))
+		p++;
+
+	if (*p != '+' && *p != '-' && !isdigit(*p))
+		return (d);
+
+	e = NULL;
+
+	r = strtod(p, &e);
+
+	if (!isfinite(r))
+		return (d);
+
+	if (e == NULL || *e != '\0')
+		return (d);
+
+	return (r);
+}



More information about the varnish-commit mailing list