| 1 |
#include <mruby.h> |
| 2 |
|
| 3 |
#ifdef MRB_NO_STDIO |
| 4 |
# error print conflicts 'MRB_NO_STDIO' in your build configuration |
| 5 |
#endif |
| 6 |
|
| 7 |
#include <mruby/string.h> |
| 8 |
#include <string.h> |
| 9 |
#if defined(_WIN32) |
| 10 |
# include <windows.h> |
| 11 |
# include <io.h> |
| 12 |
#ifdef _MSC_VER |
| 13 |
# define isatty(x) _isatty(x) |
| 14 |
# define fileno(x) _fileno(x) |
| 15 |
#endif |
| 16 |
#else |
| 17 |
# include <unistd.h> |
| 18 |
#endif |
| 19 |
|
| 20 |
static void |
| 21 |
printstr(mrb_state *mrb, mrb_value s) |
| 22 |
{ |
| 23 |
if (mrb_string_p(s)) { |
| 24 |
const char *p = RSTRING_PTR(s); |
| 25 |
mrb_int len = RSTRING_LEN(s); |
| 26 |
|
| 27 |
#if defined(_WIN32) |
| 28 |
if (isatty(fileno(stdout))) { |
| 29 |
DWORD written; |
| 30 |
int wlen = MultiByteToWideChar(CP_UTF8, 0, p, (int)len, NULL, 0); |
| 31 |
wchar_t* utf16 = (wchar_t*)mrb_malloc(mrb, (wlen+1) * sizeof(wchar_t)); |
| 32 |
if (MultiByteToWideChar(CP_UTF8, 0, p, (int)len, utf16, wlen) > 0) { |
| 33 |
utf16[wlen] = 0; |
| 34 |
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), |
| 35 |
utf16, (DWORD)wlen, &written, NULL); |
| 36 |
} |
| 37 |
mrb_free(mrb, utf16); |
| 38 |
return; |
| 39 |
} |
| 40 |
#endif |
| 41 |
fwrite(p, (size_t)len, 1, stdout); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
// ISO 15.3.1.2.10 Kernel.print |
| 46 |
// ISO 15.3.1.3.35 Kernel#print |
| 47 |
static mrb_value |
| 48 |
mrb_print(mrb_state *mrb, mrb_value self) |
| 49 |
{ |
| 50 |
mrb_int argc = mrb_get_argc(mrb); |
| 51 |
const mrb_value *argv = mrb_get_argv(mrb); |
| 52 |
|
| 53 |
for (mrb_int i=0; i<argc; i++) { |
| 54 |
mrb_value str = mrb_obj_as_string(mrb, argv[i]); |
| 55 |
printstr(mrb, str); |
| 56 |
} |
| 57 |
if (isatty(fileno(stdout))) fflush(stdout); |
| 58 |
return mrb_nil_value(); |
| 59 |
} |
| 60 |
|
| 61 |
void |
| 62 |
mrb_mruby_print_gem_init(mrb_state* mrb) |
| 63 |
{ |
| 64 |
mrb_define_method(mrb, mrb->kernel_module, "print", mrb_print, MRB_ARGS_ANY()); /* 15.3.1.3.35 */ |
| 65 |
} |
| 66 |
|
| 67 |
void |
| 68 |
mrb_mruby_print_gem_final(mrb_state* mrb) |
| 69 |
{ |
| 70 |
} |