From 83e8c1a87463d90bd39e707ed710bddfbaa01890 Mon Sep 17 00:00:00 2001 From: Jorge Acereda Date: Sat, 9 May 2020 12:21:14 +0200 Subject: [PATCH] Fix Char_str(). --- core/carp_string.h | 12 ++++++++---- core/core.h | 1 + src/Emit.hs | 6 ++++-- test/char.carp | 12 ++++++++++++ 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/core/carp_string.h b/core/carp_string.h index b9b4a0bc..f729b638 100644 --- a/core/carp_string.h +++ b/core/carp_string.h @@ -23,7 +23,7 @@ void String_string_MINUS_set_BANG_(String *s, int i, char ch) { void String_string_MINUS_set_MINUS_at_BANG_(String *into, int i, const String *src) { char *dest = (*into) + i; - int lsrc = strlen(*src); + size_t lsrc = strlen(*src); /* given a string and indices * * 0 1 2 3 4 5 6 7 8 9 @@ -166,9 +166,13 @@ String Bool_format(const String *str, bool b) { return buffer; } -String Char_str(char c) { - String buffer = CARP_MALLOC(2); - sprintf(buffer, "%c", c); +String Char_str(int c) { + char buf[16]; + int sz = snprintf(buf, sizeof(buf), "%lc", c); + size_t nsz = sz + 1; + String buffer = CARP_MALLOC(nsz); + assert(sz > 0); + memcpy(buffer, buf, nsz); return buffer; } diff --git a/core/core.h b/core/core.h index 93bf81d7..2e40e185 100644 --- a/core/core.h +++ b/core/core.h @@ -8,6 +8,7 @@ typedef SSIZE_T ssize_t; #include #endif #include +#include typedef char *String; typedef char *Pattern; diff --git a/src/Emit.hs b/src/Emit.hs index 018813c5..f7c4edfe 100644 --- a/src/Emit.hs +++ b/src/Emit.hs @@ -110,7 +110,7 @@ toC toCMode (Binder meta root) = emitterSrc (execState (visit startingIndent roo '\t' -> "'\\t'" '\n' -> "'\\n'" '\\' -> "'\\\\'" - x -> ['\'', x, '\''] + x -> ['U', '\'', x, '\''] Closure elem _ -> visit indent elem Sym _ _ -> visitSymbol indent xobj (Defn _) -> error (show (DontVisitObj xobj)) @@ -915,7 +915,9 @@ wrapInInitFunction :: Bool -> String -> String wrapInInitFunction with_core src = "void carp_init_globals(int argc, char** argv) {\n" ++ (if with_core - then " System_args.len = argc;\n System_args.data = argv;\n" + then + " System_args.len = argc;\n System_args.data = argv;\n" ++ + " setlocale(LC_CTYPE, \"\");\n" else "") ++ src ++ "}" diff --git a/test/char.carp b/test/char.carp index f384a2ef..cf30c112 100644 --- a/test/char.carp +++ b/test/char.carp @@ -4,6 +4,18 @@ (use Test) (deftest test + (assert-equal test + "a" + &(str \a) + "str works with ASCII") + (assert-equal test + "ñ" + &(str \ñ) + "str works with Latin1") + (assert-equal test + "😲" + &(str \😲) + "str works with Emoji") (assert-true test (= \a \a) "char = works as expected I")