1 /*
2  *  Copyright (C) 2004-2007 by Digital Mars, www.digitalmars.com
3  *  Written by Walter Bright
4  *
5  *  This software is provided 'as-is', without any express or implied
6  *  warranty. In no event will the authors be held liable for any damages
7  *  arising from the use of this software.
8  *
9  *  Permission is granted to anyone to use this software for any purpose,
10  *  including commercial applications, and to alter it and redistribute it
11  *  freely, in both source and binary form, subject to the following
12  *  restrictions:
13  *
14  *  o  The origin of this software must not be misrepresented; you must not
15  *     claim that you wrote the original software. If you use this software
16  *     in a product, an acknowledgment in the product documentation would be
17  *     appreciated but is not required.
18  *  o  Altered source versions must be plainly marked as such, and must not
19  *     be misrepresented as being the original software.
20  *  o  This notice may not be removed or altered from any source
21  *     distribution.
22  */
23 
24 /*
25  *  Modified by Sean Kelly <sean@f4.ca> for use with Tango.
26  */
27 module rt.compiler.gdc.rt.arraycast;
28 /******************************************
29  * Runtime helper to convert dynamic array of one
30  * type to dynamic array of another.
31  * Adjusts the length of the array.
32  * Throws exception if new length is not aligned.
33  */
34 
35 extern (C)
36 
37 void[] _d_arraycast(size_t tsize, size_t fsize, void[] a)
38 {
39     auto length = a.length;
40 
41     auto nbytes = length * fsize;
42     if (nbytes % tsize != 0)
43     {
44     throw new Exception("array cast misalignment");
45     }
46     length = nbytes / tsize;
47     *cast(size_t *)&a = length; // jam new length
48     return a;
49 }
50 
51 unittest
52 {
53     byte[int.sizeof * 3] b;
54     int[] i;
55     short[] s;
56 
57     i = cast(int[])b;
58     assert(i.length == 3);
59 
60     s = cast(short[])b;
61     assert(s.length == 6);
62 
63     s = cast(short[])i;
64     assert(s.length == 6);
65 }
66 
67 /******************************************
68  * Runtime helper to convert dynamic array of bits
69  * dynamic array of another.
70  * Adjusts the length of the array.
71  * Throws exception if new length is not aligned.
72  */
73 
74 version (none)
75 {
76 extern (C)
77 
78 void[] _d_arraycast_frombit(uint tsize, void[] a)
79 {
80     uint length = a.length;
81 
82     if (length & 7)
83     {
84     throw new Exception("bit[] array cast misalignment");
85     }
86     length /= 8 * tsize;
87     *cast(size_t *)&a = length; // jam new length
88     return a;
89 }
90 
91 unittest
92 {
93     version (D_Bits)
94     {
95     bit[int.sizeof * 3 * 8] b;
96     int[] i;
97     short[] s;
98 
99     i = cast(int[])b;
100     assert(i.length == 3);
101 
102     s = cast(short[])b;
103     assert(s.length == 6);
104     }
105 }
106 
107 }