From c54df81f05e622bd3ce6daa0bc4ba5d3999f958d Mon Sep 17 00:00:00 2001 From: Kaz Kylheku Date: Tue, 11 Jun 2019 19:47:32 -0700 Subject: buffers: allow sub operation. * buf.c (sub_buf): New function. * buf.h (sub_buf): Declared. * lib.c (sub): Hook in BUF type. (replace): Diagnose BUF specially as unsupported. --- buf.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'buf.c') diff --git a/buf.c b/buf.c index 5e5a5d66..06fb0abf 100644 --- a/buf.c +++ b/buf.c @@ -239,6 +239,38 @@ void buf_fill(val buf, mem_t *src, val self) memcpy(b->data, src, c_num(b->len)); } +val sub_buf(val buf, val from, val to) +{ + struct buf *b = buf_handle(buf, lit("sub")); + val len = b->len; + + if (null_or_missing_p(from)) + from = zero; + else if (from == t) + from = len; + else if (lt(from, zero)) { + from = plus(from, len); + if (to == zero) + to = len; + } + + if (null_or_missing_p(to) || to == t) + to = len; + else if (lt(to, zero)) + to = plus(to, len); + + from = max2(zero, min2(from, len)); + to = max2(zero, min2(to, len)); + + if (ge(from, to)) { + return make_buf(zero, nil, zero); + } else if (from == 0 && to == len) { + return buf; + } else { + return make_duplicate_buf(minus(to, from), b->data + c_num(from)); + } +} + static void buf_put_bytes(val buf, val pos, mem_t *ptr, cnum size, val self) { struct buf *b = buf_handle(buf, self); -- cgit v1.2.3