Skip to content

Commit

Permalink
implemented safe printing for nonprintable characters
Browse files Browse the repository at this point in the history
  • Loading branch information
reginaldford committed Jun 30, 2024
1 parent 626b61f commit a145152
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/main/sm_common.c
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,20 @@ void sm_log(const char *format, ...) {
va_end(args);
fclose(fp);
}

void sm_print_string(sm_string *str) {
for (int i = 0; i < str->size; i++)
putc((&str->content)[i], stdout);
}

void sm_safe_print_string(sm_string *str) {
for (int i = 0; i < str->size; i++) {
char ch = (&str->content)[i];
if (isprint(ch) || isspace(ch))
putc(ch, stdout);
else
// Escape non-printable characters
printf("\\x%02X", (unsigned char)ch);
}
fflush(stdout);
}
5 changes: 5 additions & 0 deletions src/main/sm_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ bool sm_is_symbol_char(char c);
/// Write a log message to sms.log for debugging.
/// Works just like printf
void sm_log(const char *format, ...);

/// Print a string, only regarding string size, not NULL termination
void sm_print_string(struct sm_string *str);
/// Print a string, trusting string size, but replacing non-printables with hex
void sm_safe_print_string(struct sm_string *str);
5 changes: 3 additions & 2 deletions src/main/sm_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ void start_repl(sm_env *env) {
sm_object *result = sm_engine_eval(pr.parsed_object, *(sm_global_lex_stack(NULL)->top), NULL);
// Print
sm_string *result_str = sm_object_to_string(result);
printf("%s%s%s", sm_terminal_fg_color(SM_TERM_B_WHITE), &(result_str->content),
sm_terminal_reset());
printf("%s", sm_terminal_fg_color(SM_TERM_B_WHITE));
sm_safe_print_string(result_str);
printf("%s", sm_terminal_reset());
// Cleanup
sm_garbage_collect();
fflush(stdout);
Expand Down

0 comments on commit a145152

Please sign in to comment.