Skip to content

Commit c4724cb

Browse files
committed
add fromBigEndian
1 parent be77e72 commit c4724cb

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

source/mir/bignum/integer.d

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,59 @@ struct BigInt(uint size64)
185185
return this;
186186
}
187187

188+
///
189+
static BigInt fromBigEndian()(scope const(ubyte)[] data, bool sign = false)
190+
@trusted pure @nogc
191+
{
192+
BigInt ret = void;
193+
if (!ret.copyFromBigEndian(data, sign))
194+
static immutable bigIntOverflowException = new Exception("BigInt!" ~ size64.stringof ~ ".fromBigEndian: data overflow");
195+
return ret;
196+
}
197+
198+
///
199+
bool copyFromBigEndian()(scope const(ubyte)[] data, bool sign = false)
200+
@trusted pure @nogc
201+
{
202+
while(data.length && data[0] == 0)
203+
data = data[1 .. $];
204+
if (data.length == 0)
205+
{
206+
this.length = 0;
207+
this.sign = false;
208+
}
209+
else
210+
{
211+
if (data.length > this.data.sizeof)
212+
return false;
213+
this.sign = sign;
214+
this.length = cast(uint) (data.length / size_t.sizeof);
215+
foreach_reverse (ref c; this.coefficients)
216+
{
217+
size_t value;
218+
foreach (j; 0 .. size_t.sizeof)
219+
{
220+
value <<= 8;
221+
value |= data[0];
222+
data = data[1 .. $];
223+
}
224+
c = value;
225+
}
226+
if (data.length)
227+
{
228+
this.length++;
229+
size_t value;
230+
foreach (b; data)
231+
{
232+
value <<= 8;
233+
value |= b;
234+
}
235+
this.data[length - 1] = value;
236+
}
237+
}
238+
return true;
239+
}
240+
188241
/++
189242
Returns: false in case of overflow or incorrect string.
190243
Precondition: non-empty coefficients.

source/mir/bignum/internal/parse.d

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ template decimalFromStringImpl(alias mullAdd, W = size_t)
222222
IF:
223223
ulong multplier = 10;
224224
static if (is(C == char) && is(W == ulong))
225+
if (!__ctfe)
225226
{
226227
import mir.bignum.internal.parse: isMadeOfEightDigits, parseEightDigits;
227228
if (str.length >= 8 && isMadeOfEightDigits(str[0 .. 8]))

0 commit comments

Comments
 (0)