string.c (2744B)
1 /* zlib License 2 * 3 * Copyright (c) 2017-2022 Ed van Bruggen 4 * 5 * This software is provided 'as-is', without any express or implied 6 * warranty. In no event will the authors be held liable for any damages 7 * arising from the use of this software. 8 * 9 * Permission is granted to anyone to use this software for any purpose, 10 * including commercial applications, and to alter it and redistribute it 11 * freely, subject to the following restrictions: 12 * 13 * 1. The origin of this software must not be misrepresented; you must not 14 * claim that you wrote the original software. If you use this software 15 * in a product, an acknowledgment in the product documentation would be 16 * appreciated but is not required. 17 * 2. Altered source versions must be plainly marked as such, and must not be 18 * misrepresented as being the original software. 19 * 3. This notice may not be removed or altered from any source distribution. 20 */ 21 #include <string.h> 22 #include <stdio.h> 23 #include <stdlib.h> 24 25 #include "../tisp.h" 26 27 typedef Val (*MkFn)(Tsp, char*); 28 29 /* TODO string tib: lower upper capitalize strpos strsub (python: dir(str))*/ 30 31 /* TODO simplify by using fmemopen/funopen and tisp_print */ 32 /* TODO NULL check allocs */ 33 static Val 34 val_string(Tsp st, Val args, MkFn mk_fn) 35 { 36 Val v; 37 char s[43], *ret = calloc(1, sizeof(char)); 38 int len = 1; 39 for (; !nilp(args); args = cdr(args)) { 40 v = car(args); 41 switch (v->t) { 42 case TSP_NONE: 43 len += 5; 44 ret = realloc(ret, len*sizeof(char)); 45 strcat(ret, "Void"); 46 break; 47 case TSP_NIL: 48 len += 4; 49 ret = realloc(ret, len*sizeof(char)); 50 strcat(ret, "Nil"); 51 break; 52 case TSP_INT: 53 snprintf(s, 21, "%d", (int)v->v.n.num); 54 len += strlen(s); 55 s[len] = '\0'; 56 ret = realloc(ret, len*sizeof(char)); 57 strcat(ret, s); 58 break; 59 case TSP_DEC: 60 snprintf(s, 17, "%.15g", v->v.n.num); 61 len += strlen(s); 62 s[len] = '\0'; 63 ret = realloc(ret, len*sizeof(char)); 64 strcat(ret, s); 65 break; 66 case TSP_RATIO: 67 snprintf(s, 43, "%d/%d", (int)v->v.n.num, (int)v->v.n.den); 68 len += strlen(s); 69 s[len] = '\0'; 70 ret = realloc(ret, len*sizeof(char)); 71 strcat(ret, s); 72 break; 73 case TSP_STR: 74 case TSP_SYM: 75 len += strlen(v->v.s); 76 ret = realloc(ret, len*sizeof(char)); 77 strcat(ret, v->v.s); 78 break; 79 case TSP_PAIR: 80 default: 81 tsp_warnf("could not convert type %s into string", type_str(v->t)); 82 } 83 } 84 v = mk_fn(st, ret); 85 free(ret); 86 return v; 87 } 88 89 static Val 90 prim_Str(Tsp st, Hash env, Val args) 91 { 92 tsp_arg_min(args, "Str", 1); 93 return val_string(st, args, mk_str); 94 } 95 96 static Val 97 prim_Sym(Tsp st, Hash env, Val args) 98 { 99 tsp_arg_min(args, "Sym", 1); 100 return val_string(st, args, mk_sym); 101 } 102 103 void 104 tib_env_string(Tsp st) 105 { 106 tsp_env_prim(Sym); 107 tsp_env_prim(Str); 108 }