From ff34744dc4b9610006e60e56aa3a41978489d126 Mon Sep 17 00:00:00 2001 From: hellerve Date: Sat, 30 Dec 2017 15:04:01 +0100 Subject: [PATCH] core: format works! --- core/Format.carp | 15 +++++++-------- core/core.h | 4 ++-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/core/Format.carp b/core/Format.carp index 1d18b644..4d73f5c3 100644 --- a/core/Format.carp +++ b/core/Format.carp @@ -1,10 +1,10 @@ (defdynamic fmt-internal [s args] (let [idx (String.index-of s \%) len (String.count s)] - (if (= idx -1) s ; no more splits found, just return string + (if (= idx -1) (list 'copy s) ; no more splits found, just return string (if (= \% (String.char-at s (inc idx))) ; this is an escaped % (list 'String.append - (String.substring s 0 (+ idx 2)) + (list 'copy (String.substring s 0 (+ idx 2))) (fmt-internal (String.substring s (+ idx 2) len))) (if (= 0 (count args)) ; we need to insert something, but have nothing (macro-error "error in format string: not enough arguments for format string") @@ -12,12 +12,11 @@ ; get the next % after our escaper (let [next (String.index-of (String.substring s (inc idx) len) \%)] (if (= 0 next) - (list 'fmt slice (car args)) - (let [offs (+ idx 2) - slice (String.substring s 0 (+ idx 2))] - (list 'String.append (list 'fmt slice (car args)) - (fmt-internal (String.substring s offs len) + (list 'format (list 'copy slice) (car args)) + (let [slice (String.substring s 0 (+ (inc idx) next))] + (list 'String.append (list 'format (list 'copy slice) (car args)) + (fmt-internal (String.substring s (+ (inc idx) next) len) (cdr args))))))))))) -(defmacro format [s :rest args] +(defmacro fmt [s :rest args] (fmt-internal s args)) diff --git a/core/core.h b/core/core.h index f5f93172..276b12cb 100644 --- a/core/core.h +++ b/core/core.h @@ -297,8 +297,8 @@ char String_char_MINUS_at(string* s, int i) { string String_format(string str, string s) { int n = strlen(s); - string buffer = CARP_MALLOC(n); - snprintf(buffer, n, str, *s); + string buffer = CARP_MALLOC(n+1); + snprintf(buffer, n+2, str, s); return buffer; }