diff --git a/src/core/buffer.c b/src/core/buffer.c index 07770964..16f20248 100644 --- a/src/core/buffer.c +++ b/src/core/buffer.c @@ -221,6 +221,20 @@ JANET_CORE_FN(cfun_buffer_new_filled, return janet_wrap_buffer(buffer); } +JANET_CORE_FN(cfun_buffer_frombytes, + "(buffer/from-bytes & byte-vals)", + "Creates a buffer from integer parameters with byte values. All integers " + "will be coerced to the range of 1 byte 0-255.") { + int32_t i; + JanetBuffer *buffer = janet_buffer(argc); + for (i = 0; i < argc; i++) { + int32_t c = janet_getinteger(argv, i); + buffer->data[i] = c & 0xFF; + } + buffer->count = argc; + return janet_wrap_buffer(buffer); +} + JANET_CORE_FN(cfun_buffer_fill, "(buffer/fill buffer &opt byte)", "Fill up a buffer with bytes, defaulting to 0s. Does not change the buffer's length. " @@ -509,6 +523,7 @@ void janet_lib_buffer(JanetTable *env) { JanetRegExt buffer_cfuns[] = { JANET_CORE_REG("buffer/new", cfun_buffer_new), JANET_CORE_REG("buffer/new-filled", cfun_buffer_new_filled), + JANET_CORE_REG("buffer/from-bytes", cfun_buffer_frombytes), JANET_CORE_REG("buffer/fill", cfun_buffer_fill), JANET_CORE_REG("buffer/trim", cfun_buffer_trim), JANET_CORE_REG("buffer/push-byte", cfun_buffer_u8), diff --git a/test/suite-buffer.janet b/test/suite-buffer.janet index 681ad29e..5e38ffbc 100644 --- a/test/suite-buffer.janet +++ b/test/suite-buffer.janet @@ -77,6 +77,14 @@ (buffer/push-string b5 "456" @"789") (assert (= "123456789" (string b5)) "buffer/push-buffer 2") +# Buffer from bytes +(assert (deep= @"" (buffer/from-bytes)) "buffer/from-bytes 1") +(assert (deep= @"ABC" (buffer/from-bytes 65 66 67)) "buffer/from-bytes 2") +(assert (deep= @"0123456789" (buffer/from-bytes ;(range 48 58))) "buffer/from-bytes 3") +(assert (= 0 (length (buffer/from-bytes))) "buffer/from-bytes 4") +(assert (= 5 (length (buffer/from-bytes ;(range 5)))) "buffer/from-bytes 5") +(assert-error "bad slot #1, expected 32 bit signed integer" (buffer/from-bytes :abc)) + # some tests for buffer/format # 029394d (assert (= (string (buffer/format @"" "pi = %6.3f" math/pi)) "pi = 3.142") @@ -114,8 +122,5 @@ (assert (deep= @"abc423" (buffer/push-at @"abc123" 3 "4")) "buffer/push-at 3") -# 4782a76 -(assert (= 10 (do (var x 10) (def y x) (++ x) y)) "no invalid aliasing") - (end-suite) diff --git a/test/suite-unknown.janet b/test/suite-unknown.janet index 58b6f9eb..9f034612 100644 --- a/test/suite-unknown.janet +++ b/test/suite-unknown.janet @@ -292,5 +292,8 @@ [2 6 4 'z]]) "arg & inner symbolmap") +# 4782a76 +(assert (= 10 (do (var x 10) (def y x) (++ x) y)) "no invalid aliasing") + (end-suite)