145
|
1 /**
|
|
2 * Implementation of array cast support routines.
|
|
3 *
|
|
4 * Copyright: Copyright Digital Mars 2004 - 2016.
|
|
5 * License: Distributed under the
|
|
6 * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
|
|
7 * Authors: Walter Bright, Sean Kelly
|
|
8 * Source: $(DRUNTIMESRC src/rt/_arraycast.d)
|
|
9 */
|
|
10
|
|
11 module rt.arraycast;
|
|
12
|
|
13 /******************************************
|
|
14 * Runtime helper to convert dynamic array of one
|
|
15 * type to dynamic array of another.
|
|
16 * Adjusts the length of the array.
|
|
17 * Throws an error if new length is not aligned.
|
|
18 */
|
|
19
|
|
20 extern (C)
|
|
21
|
|
22 @trusted nothrow
|
|
23 void[] _d_arraycast(size_t tsize, size_t fsize, void[] a)
|
|
24 {
|
|
25 auto length = a.length;
|
|
26
|
|
27 auto nbytes = length * fsize;
|
|
28 if (nbytes % tsize != 0)
|
|
29 {
|
|
30 throw new Error("array cast misalignment");
|
|
31 }
|
|
32 length = nbytes / tsize;
|
|
33 *cast(size_t *)&a = length; // jam new length
|
|
34 return a;
|
|
35 }
|
|
36
|
|
37 unittest
|
|
38 {
|
|
39 byte[int.sizeof * 3] b;
|
|
40 int[] i;
|
|
41 short[] s;
|
|
42
|
|
43 i = cast(int[])b;
|
|
44 assert(i.length == 3);
|
|
45
|
|
46 s = cast(short[])b;
|
|
47 assert(s.length == 6);
|
|
48
|
|
49 s = cast(short[])i;
|
|
50 assert(s.length == 6);
|
|
51 }
|
|
52
|