ref: ed4a0c0642a2411f73f7ea9aff286fdf84710b22
parent: 5aa902c9535f4d52f8c941101e726f88a40e27e6
author: cinap_lenrek <cinap_lenrek@felloff.net>
date: Sun May 28 12:09:18 EDT 2023
libndb: add ndbvalfmt() formatter Some attributes such as vendor and txt require double-quoting to be parsable by libndb. Provide the fmtinstall(2) formatter ndbvalfmt for programs outputting ndb(6) format.
--- a/sys/include/ndb.h
+++ b/sys/include/ndb.h
@@ -151,3 +151,4 @@
Ndbtuple* ndbsubstitute(Ndbtuple*, Ndbtuple*, Ndbtuple*);
Ndbtuple* ndbdedup(Ndbtuple*);
void ndbsetmalloctag(Ndbtuple*, uintptr);
+int ndbvalfmt(Fmt*);
--- a/sys/man/2/ndb
+++ b/sys/man/2/ndb
@@ -1,6 +1,6 @@
.TH NDB 2
.SH NAME
-ndbopen, ndbcat, ndbchanged, ndbclose, ndbreopen, ndbsearch, ndbsnext, ndbgetvalue, ndbfree, ipattr, mkptrname, ndbgetipaddr, ndbipinfo, csipinfo, ndbhash, ndbparse, csgetvalue, ndbfindattr, dnsquery, ndbdiscard, ndbconcatenate, ndbreorder, ndbsubstitute, ndbdedup \- network database
+ndbopen, ndbcat, ndbchanged, ndbclose, ndbreopen, ndbsearch, ndbsnext, ndbgetvalue, ndbfree, ipattr, mkptrname, ndbgetipaddr, ndbipinfo, csipinfo, ndbhash, ndbparse, csgetvalue, ndbfindattr, dnsquery, ndbdiscard, ndbconcatenate, ndbreorder, ndbsubstitute, ndbdedup, ndbsetmalloctag, ndbvalfmt \- network database
.SH SYNOPSIS
.B #include <u.h>
.br
@@ -94,6 +94,9 @@
.PP
.B
void ndbsetmalloctag(Ndbtuple *t, uintptr tag)
+.PP
+.B
+int ndbvalfmt(Fmt*)
.SH DESCRIPTION
These routines are used by network administrative programs to search
the network database.
@@ -523,6 +526,27 @@
.I t
to
.IR tag .
+.PP
+.I Ndbvalfmt
+formats a
+.B char*
+string
+of a
+.I Ndbtuple
+val,
+adding " quoting if necessary.
+It is typically enabled by calling:
+.IP
+.EX
+fmtinstall('$', ndbvalfmt);
+.EE
+.PP
+And then used like:
+.IP
+.EX
+Ndbtuple *t = ...
+print("%s=%$", t->attr, t->val);
+.EE
.SH FILES
.BR /lib/ndb " directory of network database files
.SH SOURCE
--- a/sys/src/libndb/mkfile
+++ b/sys/src/libndb/mkfile
@@ -23,6 +23,7 @@
ndbreorder.$O\
ndbsubstitute.$O\
ndbdedup.$O\
+ ndbvalfmt.$O\
HFILES=\
/sys/include/ndb.h\
--- /dev/null
+++ b/sys/src/libndb/ndbvalfmt.c
@@ -1,0 +1,28 @@
+#include <u.h>
+#include <libc.h>
+#include <bio.h>
+#include <ndb.h>
+#include "ndbhf.h"
+
+static int
+needquote(char *s)
+{
+ int c;
+
+ while((c = *s++) != '\0'){
+ if(ISWHITE(c) || c == '#')
+ return 1;
+ }
+ return 0;
+}
+
+int
+ndbvalfmt(Fmt *f)
+{
+ char *s = va_arg(f->args, char*);
+ if(s == nil)
+ s = "";
+ if(needquote(s))
+ return fmtprint(f, "\"%s\"", s);
+ return fmtstrcpy(f, s);
+}