From 9767ec6b865c35f68cb6642fefeacc009f17e638 Mon Sep 17 00:00:00 2001 From: Stefano Sabatini Date: Sun, 16 Dec 2012 12:17:23 +0100 Subject: lavu: add escape API The escape API will be useful to perform escaping programmatically, which is required when crafting argument strings, and will be used for context printing as well. This is based on the ffescape tool code, with a few extensions and fixes. --- libavutil/bprint.c | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'libavutil/bprint.c') diff --git a/libavutil/bprint.c b/libavutil/bprint.c index 4684ab4979..fd7611aaed 100644 --- a/libavutil/bprint.c +++ b/libavutil/bprint.c @@ -23,6 +23,7 @@ #include #include #include "avassert.h" +#include "avstring.h" #include "bprint.h" #include "common.h" #include "error.h" @@ -217,6 +218,50 @@ int av_bprint_finalize(AVBPrint *buf, char **ret_str) return ret; } +#define WHITESPACES " \n\t" + +void av_bprint_escape(AVBPrint *dstbuf, const char *src, const char *special_chars, + enum AVEscapeMode mode, int flags) +{ + const char *src0 = src; + + if (mode == AV_ESCAPE_MODE_AUTO) + mode = AV_ESCAPE_MODE_BACKSLASH; /* TODO: implement a heuristic */ + + switch (mode) { + case AV_ESCAPE_MODE_QUOTE: + /* enclose the string between '' */ + av_bprint_chars(dstbuf, '\'', 1); + for (; *src; src++) { + if (*src == '\'') + av_bprintf(dstbuf, "'\\''"); + else + av_bprint_chars(dstbuf, *src, 1); + } + av_bprint_chars(dstbuf, '\'', 1); + break; + + /* case AV_ESCAPE_MODE_BACKSLASH or unknown mode */ + default: + /* \-escape characters */ + for (; *src; src++) { + int is_first_last = src == src0 || !*(src+1); + int is_ws = !!strchr(WHITESPACES, *src); + int is_strictly_special = special_chars && strchr(special_chars, *src); + int is_special = + is_strictly_special || strchr("'\\", *src) || + (is_ws && (flags & AV_ESCAPE_FLAG_WHITESPACE)); + + if (is_strictly_special || + (!(flags & AV_ESCAPE_FLAG_STRICT) && + (is_special || (is_ws && is_first_last)))) + av_bprint_chars(dstbuf, '\\', 1); + av_bprint_chars(dstbuf, *src, 1); + } + break; + } +} + #ifdef TEST #undef printf -- cgit v1.2.3