Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 16 May 2013 16:46:02 +0000 (UTC)
From:      Devin Teske <dteske@FreeBSD.org>
To:        src-committers@freebsd.org, svn-src-all@freebsd.org, svn-src-head@freebsd.org
Subject:   svn commit: r250701 - head/usr.sbin/bsdconfig/share
Message-ID:  <201305161646.r4GGk3em021564@svn.freebsd.org>

next in thread | raw e-mail | index | archive | help
Author: dteske
Date: Thu May 16 16:46:02 2013
New Revision: 250701
URL: http://svnweb.freebsd.org/changeset/base/250701

Log:
  Add a handy function for truncating variables to a specific byte-length. It
  should be noted that newlines are both preserved and included in said byte-
  count. If you want to truncate single-line values without regard to line
  termination, there's always f_substr() which already exists herein.

Modified:
  head/usr.sbin/bsdconfig/share/strings.subr

Modified: head/usr.sbin/bsdconfig/share/strings.subr
==============================================================================
--- head/usr.sbin/bsdconfig/share/strings.subr	Thu May 16 16:20:17 2013	(r250700)
+++ head/usr.sbin/bsdconfig/share/strings.subr	Thu May 16 16:46:02 2013	(r250701)
@@ -51,6 +51,26 @@ f_substr()
 	echo "$string" | awk "{ print substr(\$0, $start, $len) }"
 }
 
+# f_snprintf $var_to_set $size $format ...
+#
+# Similar to snprintf(3), write at most $size number of bytes into $var_to_set
+# using printf(1) syntax (`$format ...'). The value of $var_to_set is NULL
+# unless at-least one byte is stored from the output.
+#
+f_snprintf()
+{
+	local __var_to_set="$1" __size="$2"
+	shift 2 # var_to_set/size
+	eval "$__var_to_set"=\$\( printf \"\$@\" \| awk -v max=\"\$__size\" \''
+	{
+		len = length($0)
+		max -= len
+		print substr($0,0,(max > 0 ? len : max + len))
+		if ( max < 0 ) exit
+		max--
+	}'\' \)
+}
+
 # f_longest_line_length
 #
 # Simple wrapper to an awk(1) script to print the length of the longest line of



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?201305161646.r4GGk3em021564>