From 8e479ffead1e0e170be97054ff9aca16c8c41e24 Mon Sep 17 00:00:00 2001 From: Andrey Penechko Date: Tue, 3 Feb 2015 21:43:39 +0200 Subject: [PATCH] Fix static array encoding/decoding. --- cbor.d | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/cbor.d b/cbor.d index 8da1ae4..6a9a7ef 100644 --- a/cbor.d +++ b/cbor.d @@ -281,8 +281,14 @@ align(1) struct CborValue { if (type != Type.array) onCastErrorToFrom!T(type); - - V[] array = new V[via.array.length]; + static if (isDynamicArray!T) + { + V[] array = new V[via.array.length]; + } + else + { + T array = void; + } foreach (i, elem; via.array) array[i] = elem.as!(V); @@ -617,7 +623,7 @@ size_t encodeCbor(R, E)(auto ref R sink, E value) { return encodeCborNull(sink, value); } - else static if (isInputRange!E && is(ElementType!E == ubyte)) + else static if ((isArray!E || isInputRange!E) && is(ElementType!E == ubyte)) { return encodeCborRaw(sink, value); } @@ -731,18 +737,18 @@ size_t encodeCborBool(R, E)(auto ref R sink, E value) size_t encodeCborNull(R, E)(auto ref R sink, E value) if(isOutputRange!(R, ubyte) && is(E == typeof(null))) { - putChecked(sink, cast(ubyte)0xf6); return 1; } /// Encodes range of ubytes. size_t encodeCborRaw(R, E)(auto ref R sink, E value) - if(isOutputRange!(R, ubyte) && is(ElementType!E == ubyte)) + if(isOutputRange!(R, ubyte) && + (isArray!E || isInputRange!E) && is(ElementType!E == ubyte)) { auto size = encodeLongType(sink, 2, value.length); size += value.length; - putChecked(sink, value); + putChecked(sink, value[]); return size; } @@ -1152,6 +1158,7 @@ private template isEncodedField(T) enum isEncodedField = __traits(compiles, { encodeCbor((ubyte[]).init, T.init); }); } +/// Returns a number of aggregate members that will be encoded by cbor-d. template numEncodableMembers(alias T) { enum numEncodableMembers = numEncodableMembersImpl!(T.tupleof); @@ -1683,6 +1690,22 @@ unittest // decoding with dup // data = decodeCborSingle!(ubyte[])(buf1[0..size]); // CborException: Attempt to cast array to ubyte[] } +unittest // static arrays +{ + ubyte[128] buf; + size_t size; + + // raw static array + size = encodeCbor(buf[], cast(ubyte[6])[0, 1, 2, 3, 4, 5]); + ubyte[6] data1 = decodeCborSingle!(ubyte[6])(buf[0..size]); + assert(data1 == [0, 1, 2, 3, 4, 5]); + + // regular static array + size = encodeCbor(buf[], cast(int[6])[0, 1, 2, 3, 4, 5]); + int[6] data2 = decodeCborSingle!(int[6])(buf[0..size]); + assert(data2 == [0, 1, 2, 3, 4, 5]); +} + private: @safe pure