From 04e851716edab2a429d7de8c7ea12ae291ba37af Mon Sep 17 00:00:00 2001 From: Walter Bright Date: Sat, 22 May 2010 21:04:09 +0000 Subject: [PATCH] tabs to spaces --- etc/gamma.d | 484 ++--- internal/aApply.d | 422 ++-- internal/aApplyR.d | 1072 +++++------ internal/aaA.d | 1088 +++++------ internal/adi.d | 604 +++--- internal/arraybyte.d | 2606 ++++++++++++------------- internal/arraycast.d | 8 +- internal/arraycat.d | 12 +- internal/arraydouble.d | 1992 +++++++++---------- internal/arrayint.d | 3172 +++++++++++++++---------------- internal/arrayreal.d | 188 +- internal/arrayshort.d | 2976 ++++++++++++++--------------- internal/cast.d | 134 +- internal/dmain2.d | 132 +- internal/invariant.d | 12 +- internal/qsort.d | 98 +- internal/switch.d | 568 +++--- std/array.d | 12 +- std/asserterror.d | 60 +- std/base64.d | 362 ++-- std/bind.d | 1542 +++++++-------- std/bitarray.d | 982 +++++----- std/boxer.d | 224 +-- std/c/stdarg.d | 10 +- std/c/windows/com.d | 106 +- std/c/windows/windows.d | 2298 +++++++++++----------- std/c/windows/winsock.d | 588 +++--- std/compiler.d | 6 +- std/conv.d | 724 +++---- std/cover.d | 152 +- std/cpuid.d | 512 ++--- std/cstream.d | 22 +- std/ctype.d | 66 +- std/dateparse.d | 1096 +++++------ std/demangle.d | 706 +++---- std/file.d | 832 ++++---- std/format.d | 1648 ++++++++-------- std/loader.d | 186 +- std/math.d | 114 +- std/math2.d | 826 ++++---- std/md5.d | 200 +- std/mmfile.d | 994 +++++----- std/moduleinit.d | 228 +-- std/openrj.d | 20 +- std/outbuffer.d | 306 +-- std/outofmemory.d | 14 +- std/path.d | 714 +++---- std/perf.d | 1446 +++++++------- std/random.d | 58 +- std/regexp.d | 3694 ++++++++++++++++++------------------ std/signals.d | 274 +-- std/socket.d | 2408 +++++++++++------------ std/socketstream.d | 220 +-- std/stdio.d | 770 ++++---- std/stream.d | 1168 ++++++------ std/string.d | 2582 ++++++++++++------------- std/switcherr.d | 12 +- std/system.d | 50 +- std/thread.d | 932 ++++----- std/thread_helper.d | 158 +- std/traits.d | 60 +- std/typeinfo/ti_AC.d | 112 +- std/typeinfo/ti_Acdouble.d | 84 +- std/typeinfo/ti_Acfloat.d | 80 +- std/typeinfo/ti_Acreal.d | 86 +- std/typeinfo/ti_Adouble.d | 82 +- std/typeinfo/ti_Afloat.d | 80 +- std/typeinfo/ti_Ag.d | 182 +- std/typeinfo/ti_Aint.d | 90 +- std/typeinfo/ti_Along.d | 92 +- std/typeinfo/ti_Areal.d | 84 +- std/typeinfo/ti_Ashort.d | 110 +- std/typeinfo/ti_C.d | 46 +- std/typeinfo/ti_byte.d | 16 +- std/typeinfo/ti_cdouble.d | 44 +- std/typeinfo/ti_cfloat.d | 42 +- std/typeinfo/ti_char.d | 20 +- std/typeinfo/ti_creal.d | 46 +- std/typeinfo/ti_dchar.d | 20 +- std/typeinfo/ti_delegate.d | 18 +- std/typeinfo/ti_double.d | 44 +- std/typeinfo/ti_float.d | 44 +- std/typeinfo/ti_int.d | 24 +- std/typeinfo/ti_long.d | 24 +- std/typeinfo/ti_ptr.d | 18 +- std/typeinfo/ti_real.d | 44 +- std/typeinfo/ti_short.d | 16 +- std/typeinfo/ti_ubyte.d | 16 +- std/typeinfo/ti_uint.d | 24 +- std/typeinfo/ti_ulong.d | 24 +- std/typeinfo/ti_ushort.d | 16 +- std/typeinfo/ti_void.d | 18 +- std/typeinfo/ti_wchar.d | 20 +- std/typetuple.d | 74 +- std/uni.d | 1016 +++++----- std/uri.d | 368 ++-- std/utf.d | 656 +++---- std/windows/charset.d | 78 +- std/windows/iunknown.d | 46 +- std/windows/registry.d | 58 +- std/windows/syserror.d | 22 +- std/zip.d | 638 +++---- win32.mak | 3 + 103 files changed, 24789 insertions(+), 24786 deletions(-) diff --git a/etc/gamma.d b/etc/gamma.d index ec70aa1de..55f60142d 100644 --- a/etc/gamma.d +++ b/etc/gamma.d @@ -16,86 +16,86 @@ private import std.stdio; //------------------------------------------------------------------ const real SQRT2PI = 2.50662827463100050242E0L; // sqrt(2pi) -const real MAXGAMMA = 1755.455L; // exp(tgamma(x)) == inf if x>MAXGAMMA +const real MAXGAMMA = 1755.455L; // exp(tgamma(x)) == inf if x>MAXGAMMA // Polynomial approximations for gamma and loggamma. static real GammaNumeratorCoeffs[] = [ - 0x1p+0, // 1 - 0x1.acf42d903366539ep-1, // 0.83780043015731267283 - 0x1.73a991c8475f1aeap-2, // 0.36295154366402391688 - 0x1.c7e918751d6b2a92p-4, // 0.1113062816019361559 - 0x1.86d162cca32cfe86p-6, // 0.023853632434611082525 - 0x1.0c378e2e6eaf7cd8p-8, // 0.0040926668283940355009 - 0x1.dc5c66b7d05feb54p-12, // 0.00045429319606080091555 - 0x1.616457b47e448694p-15 // 4.2127604874716220134e-05 + 0x1p+0, // 1 + 0x1.acf42d903366539ep-1, // 0.83780043015731267283 + 0x1.73a991c8475f1aeap-2, // 0.36295154366402391688 + 0x1.c7e918751d6b2a92p-4, // 0.1113062816019361559 + 0x1.86d162cca32cfe86p-6, // 0.023853632434611082525 + 0x1.0c378e2e6eaf7cd8p-8, // 0.0040926668283940355009 + 0x1.dc5c66b7d05feb54p-12, // 0.00045429319606080091555 + 0x1.616457b47e448694p-15 // 4.2127604874716220134e-05 ]; static real GammaDenominatorCoeffs[] = [ - 0x1p+0, // 1 - 0x1.a8f9faae5d8fc8b0p-2, // 0.41501609505884554346 - -0x1.cb7895a6756eebdep-3, // -0.22435109056703291645 - -0x1.7b9bab006d30652ap-5, // -0.046338876712445342138 - 0x1.c671af78f312082ep-6, // 0.027737065658400729792 - -0x1.a11ebbfaf96252dcp-11, // -0.00079559336824947383209 - -0x1.447b4d2230a77ddap-10, // -0.0012377992466531522311 - 0x1.ec1d45bb85e06696p-13, // 0.00023465840591606352443 - -0x1.d4ce24d05bd0a8e6p-17 // -1.3971485174761704409e-05 + 0x1p+0, // 1 + 0x1.a8f9faae5d8fc8b0p-2, // 0.41501609505884554346 + -0x1.cb7895a6756eebdep-3, // -0.22435109056703291645 + -0x1.7b9bab006d30652ap-5, // -0.046338876712445342138 + 0x1.c671af78f312082ep-6, // 0.027737065658400729792 + -0x1.a11ebbfaf96252dcp-11, // -0.00079559336824947383209 + -0x1.447b4d2230a77ddap-10, // -0.0012377992466531522311 + 0x1.ec1d45bb85e06696p-13, // 0.00023465840591606352443 + -0x1.d4ce24d05bd0a8e6p-17 // -1.3971485174761704409e-05 ]; static real GammaSmallCoeffs[] = [ - 0x1p+0, // 1 - 0x1.2788cfc6fb618f52p-1, // 0.57721566490153286082 - -0x1.4fcf4026afa2f7ecp-1, // -0.65587807152025406846 - -0x1.5815e8fa24d7e306p-5, // -0.042002635034033440541 - 0x1.5512320aea2ad71ap-3, // 0.16653861137208052067 - -0x1.59af0fb9d82e2160p-5, // -0.042197733607059154702 - -0x1.3b4b61d3bfdf244ap-7, // -0.0096220233604062716456 - 0x1.d9358e9d9d69fd34p-8, // 0.0072205994780369096722 - -0x1.38fc4bcbada775d6p-10 // -0.0011939450513815100956 + 0x1p+0, // 1 + 0x1.2788cfc6fb618f52p-1, // 0.57721566490153286082 + -0x1.4fcf4026afa2f7ecp-1, // -0.65587807152025406846 + -0x1.5815e8fa24d7e306p-5, // -0.042002635034033440541 + 0x1.5512320aea2ad71ap-3, // 0.16653861137208052067 + -0x1.59af0fb9d82e2160p-5, // -0.042197733607059154702 + -0x1.3b4b61d3bfdf244ap-7, // -0.0096220233604062716456 + 0x1.d9358e9d9d69fd34p-8, // 0.0072205994780369096722 + -0x1.38fc4bcbada775d6p-10 // -0.0011939450513815100956 ]; static real GammaSmallNegCoeffs[] = [ - -0x1p+0, // -1 - 0x1.2788cfc6fb618f54p-1, // 0.57721566490153286086 - 0x1.4fcf4026afa2bc4cp-1, // 0.65587807152025365473 - -0x1.5815e8fa2468fec8p-5, // -0.042002635034021129105 - -0x1.5512320baedaf4b6p-3, // -0.16653861139444135193 - -0x1.59af0fa283baf07ep-5, // -0.042197733437311917216 - 0x1.3b4a70de31e05942p-7, // 0.0096219111550359767339 - 0x1.d9398be3bad13136p-8, // 0.0072208372618931703258 - 0x1.291b73ee05bcbba2p-10 // 0.001133374167243894382 + -0x1p+0, // -1 + 0x1.2788cfc6fb618f54p-1, // 0.57721566490153286086 + 0x1.4fcf4026afa2bc4cp-1, // 0.65587807152025365473 + -0x1.5815e8fa2468fec8p-5, // -0.042002635034021129105 + -0x1.5512320baedaf4b6p-3, // -0.16653861139444135193 + -0x1.59af0fa283baf07ep-5, // -0.042197733437311917216 + 0x1.3b4a70de31e05942p-7, // 0.0096219111550359767339 + 0x1.d9398be3bad13136p-8, // 0.0072208372618931703258 + 0x1.291b73ee05bcbba2p-10 // 0.001133374167243894382 ]; static real logGammaStirlingCoeffs[] = [ - 0x1.5555555555553f98p-4, // 0.083333333333333314473 - -0x1.6c16c16c07509b10p-9, // -0.0027777777777503496034 - 0x1.a01a012461cbf1e4p-11, // 0.00079365077958550707556 - -0x1.3813089d3f9d1640p-11, // -0.00059523458517656885149 - 0x1.b911a92555a277b8p-11, // 0.00084127232973224980805 - -0x1.ed0a7b4206087b22p-10, // -0.0018808019381193769072 - 0x1.402523859811b308p-8 // 0.0048850261424322707812 + 0x1.5555555555553f98p-4, // 0.083333333333333314473 + -0x1.6c16c16c07509b10p-9, // -0.0027777777777503496034 + 0x1.a01a012461cbf1e4p-11, // 0.00079365077958550707556 + -0x1.3813089d3f9d1640p-11, // -0.00059523458517656885149 + 0x1.b911a92555a277b8p-11, // 0.00084127232973224980805 + -0x1.ed0a7b4206087b22p-10, // -0.0018808019381193769072 + 0x1.402523859811b308p-8 // 0.0048850261424322707812 ]; static real logGammaNumerator[] = [ - -0x1.0edd25913aaa40a2p+23, // -8875666.7836507038022 - -0x1.31c6ce2e58842d1ep+24, // -20039374.181038151756 - -0x1.f015814039477c3p+23, // -16255680.62543700591 - -0x1.74ffe40c4b184b34p+22, // -6111225.0120052143001 - -0x1.0d9c6d08f9eab55p+20, // -1104326.8146914642612 - -0x1.54c6b71935f1fc88p+16, // -87238.715228435114593 - -0x1.0e761b42932b2aaep+11 // -2163.6908276438128575 + -0x1.0edd25913aaa40a2p+23, // -8875666.7836507038022 + -0x1.31c6ce2e58842d1ep+24, // -20039374.181038151756 + -0x1.f015814039477c3p+23, // -16255680.62543700591 + -0x1.74ffe40c4b184b34p+22, // -6111225.0120052143001 + -0x1.0d9c6d08f9eab55p+20, // -1104326.8146914642612 + -0x1.54c6b71935f1fc88p+16, // -87238.715228435114593 + -0x1.0e761b42932b2aaep+11 // -2163.6908276438128575 ]; static real logGammaDenominator[] = [ - -0x1.4055572d75d08c56p+24, // -20993367.177578958762 - -0x1.deeb6013998e4d76p+24, // -31386464.076561826621 - -0x1.106f7cded5dcc79ep+24, // -17854332.870450781569 - -0x1.25e17184848c66d2p+22, // -4814940.3794118821866 - -0x1.301303b99a614a0ap+19, // -622744.11640662195015 - -0x1.09e76ab41ae965p+15, // -34035.708405343046707 - -0x1.00f95ced9e5f54eep+9, // -513.94814844353701437 - 0x1p+0 // 1 + -0x1.4055572d75d08c56p+24, // -20993367.177578958762 + -0x1.deeb6013998e4d76p+24, // -31386464.076561826621 + -0x1.106f7cded5dcc79ep+24, // -17854332.870450781569 + -0x1.25e17184848c66d2p+22, // -4814940.3794118821866 + -0x1.301303b99a614a0ap+19, // -622744.11640662195015 + -0x1.09e76ab41ae965p+15, // -34035.708405343046707 + -0x1.00f95ced9e5f54eep+9, // -513.94814844353701437 + 0x1p+0 // 1 ]; /* **************************************************** @@ -121,29 +121,29 @@ private real gammaStirling(real x) ]; static real LargeStirlingCoeffs[] = [ - 1.0L, - 8.33333333333333333333E-2L, - 3.47222222222222222222E-3L, - -2.68132716049382716049E-3L, - -2.29472093621399176955E-4L, - 7.84039221720066627474E-4L, - 6.97281375836585777429E-5L + 1.0L, + 8.33333333333333333333E-2L, + 3.47222222222222222222E-3L, + -2.68132716049382716049E-3L, + -2.29472093621399176955E-4L, + 7.84039221720066627474E-4L, + 6.97281375836585777429E-5L ]; real w = 1.0L / x; real y = exp(x); if (x > 1024.0L) { - // For large x, use rational coefficients from the analytical expansion. - w = poly(w, LargeStirlingCoeffs); - // Avoid overflow in pow() - real v = pow( x, 0.5L * x - 0.25L ); - y = v * (v / y); + // For large x, use rational coefficients from the analytical expansion. + w = poly(w, LargeStirlingCoeffs); + // Avoid overflow in pow() + real v = pow( x, 0.5L * x - 0.25L ); + y = v * (v / y); } else { - w = 1.0L + w * poly(w, SmallStirlingCoeffs); - y = pow( x, x - 0.5L ) / y; + w = 1.0L + w * poly(w, SmallStirlingCoeffs); + y = pow( x, x - 0.5L ) / y; } y = SQRT2PI * y * w; return y; @@ -160,16 +160,16 @@ private real gammaStirling(real x) * * This function is equivalent to tgamma() in the C programming language. * - * - * - *
Special Values
x $(GAMMA)(x) invalid? - *
NAN NAN yes - *
±0.0 ±∞ yes - *
integer > 0 (x-1)! no - *
integer < 0 NAN yes - *
+∞ +∞ no - *
-∞ NAN yes - *
+ * + * + *
Special Values
x $(GAMMA)(x) invalid? + *
NAN NAN yes + *
±0.0 ±∞ yes + *
integer > 0 (x-1)! no + *
integer < 0 NAN yes + *
+∞ +∞ no + *
-∞ NAN yes + *
* * References: * cephes, http://en.wikipedia.org/wiki/Gamma_function @@ -183,53 +183,53 @@ real tgamma(real x) * approximated by a rational function of degree 7/8 in the * interval (2,3). Large arguments are handled by Stirling's * formula. Large negative arguments are made positive using - * a reflection formula. - */ + * a reflection formula. + */ real q, z; if (isnan(x)) - return x; + return x; if (x == -x.infinity) - return real.nan; + return real.nan; if ( fabs(x) > MAXGAMMA ) - return real.infinity; + return real.infinity; if (x == 0) - return 1.0 / x; // +- infinity depending on sign of x, create an exception. - + return 1.0 / x; // +- infinity depending on sign of x, create an exception. + q = fabs(x); - + if ( q > 13.0L ) { - // Large arguments are handled by Stirling's - // formula. Large negative arguments are made positive using - // the reflection formula. + // Large arguments are handled by Stirling's + // formula. Large negative arguments are made positive using + // the reflection formula. - if ( x < 0.0L ) - { - int sgngam = 1; // sign of gamma. - real p = floor(q); - if ( p == q ) - return real.nan; // poles for all integers <0. - int intpart = cast(int)(p); - if ( (intpart & 1) == 0 ) - sgngam = -1; - z = q - p; - if ( z > 0.5L ) - { - p += 1.0L; - z = q - p; - } - z = q * sin( PI * z ); - z = fabs(z) * gammaStirling(q); - if ( z <= PI / real.max ) - return sgngam * real.infinity; - return sgngam * PI / z; - } - else - return gammaStirling(x); + if ( x < 0.0L ) + { + int sgngam = 1; // sign of gamma. + real p = floor(q); + if ( p == q ) + return real.nan; // poles for all integers <0. + int intpart = cast(int)(p); + if ( (intpart & 1) == 0 ) + sgngam = -1; + z = q - p; + if ( z > 0.5L ) + { + p += 1.0L; + z = q - p; + } + z = q * sin( PI * z ); + z = fabs(z) * gammaStirling(q); + if ( z <= PI / real.max ) + return sgngam * real.infinity; + return sgngam * PI / z; + } + else + return gammaStirling(x); } - + // Arguments |x| <= 13 are reduced by recurrence and the function // approximated by a rational function of degree 7/8 in the // interval (2,3). @@ -237,39 +237,39 @@ real tgamma(real x) z = 1.0L; while ( x >= 3.0L ) { - x -= 1.0L; - z *= x; + x -= 1.0L; + z *= x; } - + while ( x < -0.03125L ) { - z /= x; - x += 1.0L; + z /= x; + x += 1.0L; } - + if ( x <= 0.03125L ) { - if ( x == 0.0L ) - return real.nan; - else if ( x < 0.0L ) - { - x = -x; - return z / (x * poly( x, GammaSmallNegCoeffs )); - } - else - { - return z / (x * poly( x, GammaSmallCoeffs )); - } + if ( x == 0.0L ) + return real.nan; + else if ( x < 0.0L ) + { + x = -x; + return z / (x * poly( x, GammaSmallNegCoeffs )); + } + else + { + return z / (x * poly( x, GammaSmallCoeffs )); + } } - + while ( x < 2.0L ) { - z /= x; - x += 1.0L; + z /= x; + x += 1.0L; } if ( x == 2.0L ) - return z; - + return z; + x -= 2.0L; return z * poly( x, GammaNumeratorCoeffs ) / poly( x, GammaDenominatorCoeffs ); } @@ -280,12 +280,12 @@ unittest double fact = 1.0L; for (int i = 1; fact < real.max; ++i) { - // Require exact equality for small factorials - if (i < 14) - assert(tgamma(i * 1.0L)==fact); - assert(feqrel(tgamma(i * 1.0L), cast(real)fact) > real.mant_dig - 15); - //writefln(i, " %a ---> %a %a ", i*1.0L, tgamma(i * 1.0L), fact, feqrel(tgamma(i*1.0L), fact)); - fact *= (i * 1.0L); + // Require exact equality for small factorials + if (i < 14) + assert(tgamma(i * 1.0L)==fact); + assert(feqrel(tgamma(i * 1.0L), cast(real)fact) > real.mant_dig - 15); + //writefln(i, " %a ---> %a %a ", i*1.0L, tgamma(i * 1.0L), fact, feqrel(tgamma(i*1.0L), fact)); + fact *= (i * 1.0L); } assert(tgamma(0.0) == real.infinity); assert(tgamma(-0.0) == -real.infinity); @@ -306,15 +306,15 @@ unittest * * For reals, lgamma is equivalent to log(fabs(tgamma(x)). * - * - * - *
Special Values
x log$(GAMMA)(x) invalid? - *
NaN NaN yes - *
integer <= 0 +∞ yes - *
1, 2 +0.0 no - *
±∞ +∞ no - *
- * + * + * + *
Special Values
x log$(GAMMA)(x) invalid? + *
NaN NaN yes + *
integer <= 0 +∞ yes + *
1, 2 +0.0 no + *
±∞ +∞ no + *
+ * */ real lgamma(real x) { @@ -329,81 +329,81 @@ real lgamma(real x) * less than -33. */ real q, w, z, f, nx; - + if (isnan(x)) - return x; + return x; if (fabs(x) == x.infinity) - return x.infinity; - + return x.infinity; + if ( x < -34.0L ) { - q = -x; - w = lgamma(q); - real p = floor(q); - if ( p == q ) - return real.infinity; - int intpart = cast(int)(p); - real sgngam = 1; - if ( (intpart & 1) == 0 ) - sgngam = -1; - z = q - p; - if ( z > 0.5L ) - { - p += 1.0L; - z = p - q; - } - z = q * sin( PI * z ); - if ( z == 0.0L ) - return sgngam * real.infinity; - /* z = LOGPI - logl( z ) - w; */ - z = log( PI / z ) - w; - return z; + q = -x; + w = lgamma(q); + real p = floor(q); + if ( p == q ) + return real.infinity; + int intpart = cast(int)(p); + real sgngam = 1; + if ( (intpart & 1) == 0 ) + sgngam = -1; + z = q - p; + if ( z > 0.5L ) + { + p += 1.0L; + z = p - q; + } + z = q * sin( PI * z ); + if ( z == 0.0L ) + return sgngam * real.infinity; + /* z = LOGPI - logl( z ) - w; */ + z = log( PI / z ) - w; + return z; } if ( x < 13.0L ) { - z = 1.0L; - nx = floor( x + 0.5L ); - f = x - nx; - while ( x >= 3.0L ) - { - nx -= 1.0L; - x = nx + f; - z *= x; - } - while ( x < 2.0L ) - { - if( fabs(x) <= 0.03125 ) - { - if ( x == 0.0L ) - return real.infinity; - if ( x < 0.0L ) - { - x = -x; - q = z / (x * poly( x, GammaSmallNegCoeffs)); - } - else - q = z / (x * poly( x, GammaSmallCoeffs)); - return log( fabs(q) ); - } - z /= nx + f; - nx += 1.0L; - x = nx + f; - } - z = fabs(z); - if ( x == 2.0L ) - return log(z); - x = (nx - 2.0L) + f; - real p = x * poly( x, logGammaNumerator ) / poly( x, logGammaDenominator); - return ( log(z) + p ); + z = 1.0L; + nx = floor( x + 0.5L ); + f = x - nx; + while ( x >= 3.0L ) + { + nx -= 1.0L; + x = nx + f; + z *= x; + } + while ( x < 2.0L ) + { + if( fabs(x) <= 0.03125 ) + { + if ( x == 0.0L ) + return real.infinity; + if ( x < 0.0L ) + { + x = -x; + q = z / (x * poly( x, GammaSmallNegCoeffs)); + } + else + q = z / (x * poly( x, GammaSmallCoeffs)); + return log( fabs(q) ); + } + z /= nx + f; + nx += 1.0L; + x = nx + f; + } + z = fabs(z); + if ( x == 2.0L ) + return log(z); + x = (nx - 2.0L) + f; + real p = x * poly( x, logGammaNumerator ) / poly( x, logGammaDenominator); + return ( log(z) + p ); } - + //const real MAXLGM = 1.04848146839019521116e+4928L; //if ( x > MAXLGM ) return sgngaml * real.infinity; /* log( sqrt( 2*pi ) ) */ const real LOGSQRT2PI = 0.91893853320467274178L; - + q = ( x - 0.5L ) * log(x) - x + LOGSQRT2PI; if (x > 1.0e10L) return q; real p = 1.0L/(x*x); @@ -425,54 +425,54 @@ unittest assert(lgamma(0.0) == real.infinity); assert(isPosZero(lgamma(1.0L))); assert(isPosZero(lgamma(2.0L))); - + // x, correct loggamma(x), correct d/dx loggamma(x). static real[] testpoints = - [ - 8.0L, 8.525146484375L + 1.48766904143001655310E-5, 2.01564147795560999654E0L, - 8.99993896484375e-1L, 6.6375732421875e-2L + 5.11505711292524166220E-6L, -7.54938684259372234258E-1, - 7.31597900390625e-1L, 2.2369384765625e-1 + 5.21506341809849792422E-6L, -1.13355566660398608343E0L, - 2.31639862060546875e-1L, 1.3686676025390625L + 1.12609441752996145670E-5L, -4.56670961813812679012E0, - 1.73162841796875L, -8.88214111328125e-2L + 3.36207740803753034508E-6L, 2.33339034686200586920E-1L, - 1.23162841796875L, -9.3902587890625e-2L + 1.28765089229009648104E-5L, -2.49677345775751390414E-1L, - 7.3786976294838206464e19L, 3.301798506038663053312e21L - 1.656137564136932662487046269677E5L, + [ + 8.0L, 8.525146484375L + 1.48766904143001655310E-5, 2.01564147795560999654E0L, + 8.99993896484375e-1L, 6.6375732421875e-2L + 5.11505711292524166220E-6L, -7.54938684259372234258E-1, + 7.31597900390625e-1L, 2.2369384765625e-1 + 5.21506341809849792422E-6L, -1.13355566660398608343E0L, + 2.31639862060546875e-1L, 1.3686676025390625L + 1.12609441752996145670E-5L, -4.56670961813812679012E0, + 1.73162841796875L, -8.88214111328125e-2L + 3.36207740803753034508E-6L, 2.33339034686200586920E-1L, + 1.23162841796875L, -9.3902587890625e-2L + 1.28765089229009648104E-5L, -2.49677345775751390414E-1L, + 7.3786976294838206464e19L, 3.301798506038663053312e21L - 1.656137564136932662487046269677E5L, 4.57477139169563904215E1L, - 1.08420217248550443401E-19L, 4.36682586669921875e1L + 1.37082843669932230418E-5L, + 1.08420217248550443401E-19L, 4.36682586669921875e1L + 1.37082843669932230418E-5L, -9.22337203685477580858E18L, -// 1.0L, 0.0L, -5.77215664901532860607E-1L, -// 2.0L, 0.0L, 4.22784335098467139393E-1L, - -0.5L, 1.2655029296875L + 9.19379714539648894580E-6L, 3.64899739785765205590E-2L, - -1.5L, 8.6004638671875e-1L + 6.28657731014510932682E-7L, 7.03156640645243187226E-1L, - -2.5L, -5.6243896484375E-2L + 1.79986700949327405470E-7, 1.10315664064524318723E0L, - -3.5L, -1.30902099609375L + 1.43111007079536392848E-5L, 1.38887092635952890151E0L +// 1.0L, 0.0L, -5.77215664901532860607E-1L, +// 2.0L, 0.0L, 4.22784335098467139393E-1L, + -0.5L, 1.2655029296875L + 9.19379714539648894580E-6L, 3.64899739785765205590E-2L, + -1.5L, 8.6004638671875e-1L + 6.28657731014510932682E-7L, 7.03156640645243187226E-1L, + -2.5L, -5.6243896484375E-2L + 1.79986700949327405470E-7, 1.10315664064524318723E0L, + -3.5L, -1.30902099609375L + 1.43111007079536392848E-5L, 1.38887092635952890151E0L ]; // TODO: test derivatives as well. for (int i=0; i real.mant_dig-5); + //writefln("%a %a ", lgamma(testpoints[i]), testpoints[i+1], feqrel(lgamma(testpoints[i]), testpoints[i+1])); + assert( feqrel(lgamma(testpoints[i]), testpoints[i+1]) > real.mant_dig-5); } static real logabsgamma(real x) { - // For poles, tgamma(x) returns nan, but lgamma() returns infinity. - if (x < 0 && x == floor(x)) - return real.infinity; - return log(fabs(tgamma(x))); + // For poles, tgamma(x) returns nan, but lgamma() returns infinity. + if (x < 0 && x == floor(x)) + return real.infinity; + return log(fabs(tgamma(x))); } static real exploggamma(real x) { - return exp(lgamma(x)); + return exp(lgamma(x)); } static real absgamma(real x) { - if (x < 0 && x == floor(x)) - return real.infinity; - return fabs(tgamma(x)); + if (x < 0 && x == floor(x)) + return real.infinity; + return fabs(tgamma(x)); } // Check that loggamma(x) = log(gamma(x)) provided x is not -1, -2, -3, ... @@ -480,4 +480,4 @@ unittest //assert(consistencyTwoFuncs(&exploggamma, &absgamma, -2000, real.infinity) > real.mant_dig-16); } - + diff --git a/internal/aApply.d b/internal/aApply.d index 019b47817..4f4934aab 100644 --- a/internal/aApply.d +++ b/internal/aApply.d @@ -48,16 +48,16 @@ extern (C) int _aApplycd1(char[] aa, dg_t dg) debug(apply) printf("_aApplycd1(), len = %d\n", len); for (i = 0; i < len; ) - { dchar d; + { dchar d; - d = aa[i]; - if (d & 0x80) - d = std.utf.decode(aa, i); - else - i++; - result = dg(cast(void *)&d); - if (result) - break; + d = aa[i]; + if (d & 0x80) + d = std.utf.decode(aa, i); + else + i++; + result = dg(cast(void *)&d); + if (result) + break; } return result; } @@ -69,16 +69,16 @@ extern (C) int _aApplywd1(wchar[] aa, dg_t dg) debug(apply) printf("_aApplywd1(), len = %d\n", len); for (i = 0; i < len; ) - { dchar d; + { dchar d; - d = aa[i]; - if (d & ~0x7F) - d = std.utf.decode(aa, i); - else - i++; - result = dg(cast(void *)&d); - if (result) - break; + d = aa[i]; + if (d & ~0x7F) + d = std.utf.decode(aa, i); + else + i++; + result = dg(cast(void *)&d); + if (result) + break; } return result; } @@ -90,28 +90,28 @@ extern (C) int _aApplycw1(char[] aa, dg_t dg) debug(apply) printf("_aApplycw1(), len = %d\n", len); for (i = 0; i < len; ) - { dchar d; - wchar w; + { dchar d; + wchar w; - w = aa[i]; - if (w & 0x80) - { d = std.utf.decode(aa, i); - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar)((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(cast(void *)&w); - if (result) - break; - w = cast(wchar)(((d - 0x10000) & 0x3FF) + 0xDC00); - } - } - else - i++; - result = dg(cast(void *)&w); - if (result) - break; + w = aa[i]; + if (w & 0x80) + { d = std.utf.decode(aa, i); + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar)((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(cast(void *)&w); + if (result) + break; + w = cast(wchar)(((d - 0x10000) & 0x3FF) + 0xDC00); + } + } + else + i++; + result = dg(cast(void *)&w); + if (result) + break; } return result; } @@ -123,33 +123,33 @@ extern (C) int _aApplywc1(wchar[] aa, dg_t dg) debug(apply) printf("_aApplywc1(), len = %d\n", len); for (i = 0; i < len; ) - { dchar d; - wchar w; - char c; + { dchar d; + wchar w; + char c; - w = aa[i]; - if (w & ~0x7F) - { - char[4] buf; - char[] b; + w = aa[i]; + if (w & ~0x7F) + { + char[4] buf; + char[] b; - d = std.utf.decode(aa, i); - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(cast(void *)&c2); - if (result) - return result; - } - continue; - } - else - { c = cast(char)w; - i++; - } - result = dg(cast(void *)&c); - if (result) - break; + d = std.utf.decode(aa, i); + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(cast(void *)&c2); + if (result) + return result; + } + continue; + } + else + { c = cast(char)w; + i++; + } + result = dg(cast(void *)&c); + if (result) + break; } return result; } @@ -160,29 +160,29 @@ extern (C) int _aApplydc1(dchar[] aa, dg_t dg) debug(apply) printf("_aApplydc1(), len = %d\n", aa.length); foreach (dchar d; aa) { - char c; + char c; - if (d & ~0x7F) - { - char[4] buf; - char[] b; + if (d & ~0x7F) + { + char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(cast(void *)&c2); - if (result) - return result; - } - continue; - } - else - { - c = cast(char)d; - } - result = dg(cast(void *)&c); - if (result) - break; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(cast(void *)&c2); + if (result) + return result; + } + continue; + } + else + { + c = cast(char)d; + } + result = dg(cast(void *)&c); + if (result) + break; } return result; } @@ -193,21 +193,21 @@ extern (C) int _aApplydw1(dchar[] aa, dg_t dg) debug(apply) printf("_aApplydw1(), len = %d\n", aa.length); foreach (dchar d; aa) { - wchar w; + wchar w; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar)((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(cast(void *)&w); - if (result) - break; - w = cast(wchar)(((d - 0x10000) & 0x3FF) + 0xDC00); - } - result = dg(cast(void *)&w); - if (result) - break; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar)((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(cast(void *)&w); + if (result) + break; + w = cast(wchar)(((d - 0x10000) & 0x3FF) + 0xDC00); + } + result = dg(cast(void *)&w); + if (result) + break; } return result; } @@ -226,20 +226,20 @@ extern (C) int _aApplycd2(char[] aa, dg2_t dg) debug(apply) printf("_aApplycd2(), len = %d\n", len); for (i = 0; i < len; i += n) - { dchar d; + { dchar d; - d = aa[i]; - if (d & 0x80) - { - n = i; - d = std.utf.decode(aa, n); - n -= i; - } - else - n = 1; - result = dg(&i, cast(void *)&d); - if (result) - break; + d = aa[i]; + if (d & 0x80) + { + n = i; + d = std.utf.decode(aa, n); + n -= i; + } + else + n = 1; + result = dg(&i, cast(void *)&d); + if (result) + break; } return result; } @@ -252,20 +252,20 @@ extern (C) int _aApplywd2(wchar[] aa, dg2_t dg) debug(apply) printf("_aApplywd2(), len = %d\n", len); for (i = 0; i < len; i += n) - { dchar d; + { dchar d; - d = aa[i]; - if (d & ~0x7F) - { - n = i; - d = std.utf.decode(aa, n); - n -= i; - } - else - n = 1; - result = dg(&i, cast(void *)&d); - if (result) - break; + d = aa[i]; + if (d & ~0x7F) + { + n = i; + d = std.utf.decode(aa, n); + n -= i; + } + else + n = 1; + result = dg(&i, cast(void *)&d); + if (result) + break; } return result; } @@ -278,30 +278,30 @@ extern (C) int _aApplycw2(char[] aa, dg2_t dg) debug(apply) printf("_aApplycw2(), len = %d\n", len); for (i = 0; i < len; i += n) - { dchar d; - wchar w; + { dchar d; + wchar w; - w = aa[i]; - if (w & 0x80) - { n = i; - d = std.utf.decode(aa, n); - n -= i; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(&i, cast(void *)&w); - if (result) - break; - w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); - } - } - else - n = 1; - result = dg(&i, cast(void *)&w); - if (result) - break; + w = aa[i]; + if (w & 0x80) + { n = i; + d = std.utf.decode(aa, n); + n -= i; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(&i, cast(void *)&w); + if (result) + break; + w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); + } + } + else + n = 1; + result = dg(&i, cast(void *)&w); + if (result) + break; } return result; } @@ -314,35 +314,35 @@ extern (C) int _aApplywc2(wchar[] aa, dg2_t dg) debug(apply) printf("_aApplywc2(), len = %d\n", len); for (i = 0; i < len; i += n) - { dchar d; - wchar w; - char c; + { dchar d; + wchar w; + char c; - w = aa[i]; - if (w & ~0x7F) - { - char[4] buf; - char[] b; + w = aa[i]; + if (w & ~0x7F) + { + char[4] buf; + char[] b; - n = i; - d = std.utf.decode(aa, n); - n -= i; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(&i, cast(void *)&c2); - if (result) - return result; - } - continue; - } - else - { c = cast(char)w; - n = 1; - } - result = dg(&i, cast(void *)&c); - if (result) - break; + n = i; + d = std.utf.decode(aa, n); + n -= i; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(&i, cast(void *)&c2); + if (result) + return result; + } + continue; + } + else + { c = cast(char)w; + n = 1; + } + result = dg(&i, cast(void *)&c); + if (result) + break; } return result; } @@ -354,30 +354,30 @@ extern (C) int _aApplydc2(dchar[] aa, dg2_t dg) debug(apply) printf("_aApplydc2(), len = %d\n", len); for (i = 0; i < len; i++) - { dchar d; - char c; + { dchar d; + char c; - d = aa[i]; - if (d & ~0x7F) - { - char[4] buf; - char[] b; + d = aa[i]; + if (d & ~0x7F) + { + char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(&i, cast(void *)&c2); - if (result) - return result; - } - continue; - } - else - { c = cast(char)d; - } - result = dg(&i, cast(void *)&c); - if (result) - break; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(&i, cast(void *)&c2); + if (result) + return result; + } + continue; + } + else + { c = cast(char)d; + } + result = dg(&i, cast(void *)&c); + if (result) + break; } return result; } @@ -388,21 +388,21 @@ extern (C) int _aApplydw2(dchar[] aa, dg2_t dg) debug(apply) printf("_aApplydw2(), len = %d\n", aa.length); foreach (size_t i, dchar d; aa) { - wchar w; + wchar w; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(&i, cast(void *)&w); - if (result) - break; - w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); - } - result = dg(&i, cast(void *)&w); - if (result) - break; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(&i, cast(void *)&w); + if (result) + break; + w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); + } + result = dg(&i, cast(void *)&w); + if (result) + break; } return result; } diff --git a/internal/aApplyR.d b/internal/aApplyR.d index c419ab843..60958e1f1 100644 --- a/internal/aApplyR.d +++ b/internal/aApplyR.d @@ -46,29 +46,29 @@ extern (C) int _aApplyRcd1(char[] aa, dg_t dg) debug(apply) printf("_aApplyRcd1(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; + { dchar d; - i--; - d = aa[i]; - if (d & 0x80) - { char c = cast(char)d; - uint j; - uint m = 0x3F; - d = 0; - while ((c & 0xC0) != 0xC0) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); - i--; - d |= (c & 0x3F) << j; - j += 6; - m >>= 1; - c = aa[i]; - } - d |= (c & m) << j; - } - result = dg(cast(void *)&d); - if (result) - break; + i--; + d = aa[i]; + if (d & 0x80) + { char c = cast(char)d; + uint j; + uint m = 0x3F; + d = 0; + while ((c & 0xC0) != 0xC0) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); + i--; + d |= (c & 0x3F) << j; + j += 6; + m >>= 1; + c = aa[i]; + } + d |= (c & m) << j; + } + result = dg(cast(void *)&d); + if (result) + break; } return result; } @@ -82,16 +82,16 @@ unittest foreach_reverse(dchar d; s) { - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -99,16 +99,16 @@ unittest i = 0; foreach_reverse(dchar d; s) { - //printf("i = %d, d = %x\n", i, d); - switch (i) - { - case 0: assert(d == 'b'); break; - case 1: assert(d == '\U00100456'); break; - case 2: assert(d == '\u1234'); break; - case 3: assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, d = %x\n", i, d); + switch (i) + { + case 0: assert(d == 'b'); break; + case 1: assert(d == '\U00100456'); break; + case 2: assert(d == '\u1234'); break; + case 3: assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 4); } @@ -120,19 +120,19 @@ extern (C) int _aApplyRwd1(wchar[] aa, dg_t dg) debug(apply) printf("_aApplyRwd1(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; + { dchar d; - i--; - d = aa[i]; - if (d >= 0xDC00 && d <= 0xDFFF) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); - i--; - d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); - } - result = dg(cast(void *)&d); - if (result) - break; + i--; + d = aa[i]; + if (d >= 0xDC00 && d <= 0xDFFF) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); + i--; + d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); + } + result = dg(cast(void *)&d); + if (result) + break; } return result; } @@ -146,16 +146,16 @@ unittest foreach_reverse(dchar d; s) { - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -163,16 +163,16 @@ unittest i = 0; foreach_reverse(dchar d; s) { - //printf("i = %d, d = %x\n", i, d); - switch (i) - { - case 0: assert(d == 'b'); break; - case 1: assert(d == '\U00100456'); break; - case 2: assert(d == '\u1234'); break; - case 3: assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, d = %x\n", i, d); + switch (i) + { + case 0: assert(d == 'b'); break; + case 1: assert(d == '\U00100456'); break; + case 2: assert(d == '\u1234'); break; + case 3: assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 4); } @@ -184,41 +184,41 @@ extern (C) int _aApplyRcw1(char[] aa, dg_t dg) debug(apply) printf("_aApplyRcw1(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; - wchar w; + { dchar d; + wchar w; - i--; - w = aa[i]; - if (w & 0x80) - { char c = cast(char)w; - uint j; - uint m = 0x3F; - d = 0; - while ((c & 0xC0) != 0xC0) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); - i--; - d |= (c & 0x3F) << j; - j += 6; - m >>= 1; - c = aa[i]; - } - d |= (c & m) << j; + i--; + w = aa[i]; + if (w & 0x80) + { char c = cast(char)w; + uint j; + uint m = 0x3F; + d = 0; + while ((c & 0xC0) != 0xC0) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); + i--; + d |= (c & 0x3F) << j; + j += 6; + m >>= 1; + c = aa[i]; + } + d |= (c & m) << j; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(cast(void *)&w); - if (result) - break; - w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); - } - } - result = dg(cast(void *)&w); - if (result) - break; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(cast(void *)&w); + if (result) + break; + w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); + } + } + result = dg(cast(void *)&w); + if (result) + break; } return result; } @@ -232,16 +232,16 @@ unittest foreach_reverse(wchar d; s) { - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -249,17 +249,17 @@ unittest i = 0; foreach_reverse(wchar d; s) { - //printf("i = %d, d = %x\n", i, d); - switch (i) - { - case 0: assert(d == 'b'); break; - case 1: assert(d == 0xDBC1); break; - case 2: assert(d == 0xDC56); break; - case 3: assert(d == 0x1234); break; - case 4: assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, d = %x\n", i, d); + switch (i) + { + case 0: assert(d == 'b'); break; + case 1: assert(d == 0xDBC1); break; + case 2: assert(d == 0xDC56); break; + case 3: assert(d == 0x1234); break; + case 4: assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 5); } @@ -271,36 +271,36 @@ extern (C) int _aApplyRwc1(wchar[] aa, dg_t dg) debug(apply) printf("_aApplyRwc1(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; - char c; + { dchar d; + char c; - i--; - d = aa[i]; - if (d >= 0xDC00 && d <= 0xDFFF) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); - i--; - d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); - } + i--; + d = aa[i]; + if (d >= 0xDC00 && d <= 0xDFFF) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); + i--; + d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); + } - if (d & ~0x7F) - { - char[4] buf; - char[] b; + if (d & ~0x7F) + { + char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(cast(void *)&c2); - if (result) - return result; - } - continue; - } - c = cast(char)d; - result = dg(cast(void *)&c); - if (result) - break; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(cast(void *)&c2); + if (result) + return result; + } + continue; + } + c = cast(char)d; + result = dg(cast(void *)&c); + if (result) + break; } return result; } @@ -314,16 +314,16 @@ unittest foreach_reverse(char d; s) { - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -331,21 +331,21 @@ unittest i = 0; foreach_reverse(char d; s) { - //printf("i = %d, d = %x\n", i, d); - switch (i) - { - case 0: assert(d == 'b'); break; - case 1: assert(d == 0xF4); break; - case 2: assert(d == 0x80); break; - case 3: assert(d == 0x91); break; - case 4: assert(d == 0x96); break; - case 5: assert(d == 0xE1); break; - case 6: assert(d == 0x88); break; - case 7: assert(d == 0xB4); break; - case 8: assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, d = %x\n", i, d); + switch (i) + { + case 0: assert(d == 'b'); break; + case 1: assert(d == 0xF4); break; + case 2: assert(d == 0x80); break; + case 3: assert(d == 0x91); break; + case 4: assert(d == 0x96); break; + case 5: assert(d == 0xE1); break; + case 6: assert(d == 0x88); break; + case 7: assert(d == 0xB4); break; + case 8: assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 9); } @@ -357,30 +357,30 @@ extern (C) int _aApplyRdc1(dchar[] aa, dg_t dg) debug(apply) printf("_aApplyRdc1(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0;) - { dchar d = aa[--i]; - char c; + { dchar d = aa[--i]; + char c; - if (d & ~0x7F) - { - char[4] buf; - char[] b; + if (d & ~0x7F) + { + char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(cast(void *)&c2); - if (result) - return result; - } - continue; - } - else - { - c = cast(char)d; - } - result = dg(cast(void *)&c); - if (result) - break; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(cast(void *)&c2); + if (result) + return result; + } + continue; + } + else + { + c = cast(char)d; + } + result = dg(cast(void *)&c); + if (result) + break; } return result; } @@ -394,16 +394,16 @@ unittest foreach_reverse(char d; s) { - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -411,21 +411,21 @@ unittest i = 0; foreach_reverse(char d; s) { - //printf("i = %d, d = %x\n", i, d); - switch (i) - { - case 0: assert(d == 'b'); break; - case 1: assert(d == 0xF4); break; - case 2: assert(d == 0x80); break; - case 3: assert(d == 0x91); break; - case 4: assert(d == 0x96); break; - case 5: assert(d == 0xE1); break; - case 6: assert(d == 0x88); break; - case 7: assert(d == 0xB4); break; - case 8: assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, d = %x\n", i, d); + switch (i) + { + case 0: assert(d == 'b'); break; + case 1: assert(d == 0xF4); break; + case 2: assert(d == 0x80); break; + case 3: assert(d == 0x91); break; + case 4: assert(d == 0x96); break; + case 5: assert(d == 0xE1); break; + case 6: assert(d == 0x88); break; + case 7: assert(d == 0xB4); break; + case 8: assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 9); } @@ -437,22 +437,22 @@ extern (C) int _aApplyRdw1(dchar[] aa, dg_t dg) debug(apply) printf("_aApplyRdw1(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d = aa[--i]; - wchar w; + { dchar d = aa[--i]; + wchar w; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(cast(void *)&w); - if (result) - break; - w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); - } - result = dg(cast(void *)&w); - if (result) - break; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(cast(void *)&w); + if (result) + break; + w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); + } + result = dg(cast(void *)&w); + if (result) + break; } return result; } @@ -466,16 +466,16 @@ unittest foreach_reverse(wchar d; s) { - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -483,17 +483,17 @@ unittest i = 0; foreach_reverse(wchar d; s) { - //printf("i = %d, d = %x\n", i, d); - switch (i) - { - case 0: assert(d == 'b'); break; - case 1: assert(d == 0xDBC1); break; - case 2: assert(d == 0xDC56); break; - case 3: assert(d == 0x1234); break; - case 4: assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, d = %x\n", i, d); + switch (i) + { + case 0: assert(d == 'b'); break; + case 1: assert(d == 0xDBC1); break; + case 2: assert(d == 0xDC56); break; + case 3: assert(d == 0x1234); break; + case 4: assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 5); } @@ -512,29 +512,29 @@ extern (C) int _aApplyRcd2(char[] aa, dg2_t dg) debug(apply) printf("_aApplyRcd2(), len = %d\n", len); for (i = len; i != 0; ) - { dchar d; + { dchar d; - i--; - d = aa[i]; - if (d & 0x80) - { char c = cast(char)d; - uint j; - uint m = 0x3F; - d = 0; - while ((c & 0xC0) != 0xC0) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); - i--; - d |= (c & 0x3F) << j; - j += 6; - m >>= 1; - c = aa[i]; - } - d |= (c & m) << j; - } - result = dg(&i, cast(void *)&d); - if (result) - break; + i--; + d = aa[i]; + if (d & 0x80) + { char c = cast(char)d; + uint j; + uint m = 0x3F; + d = 0; + while ((c & 0xC0) != 0xC0) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); + i--; + d |= (c & 0x3F) << j; + j += 6; + m >>= 1; + c = aa[i]; + } + d |= (c & m) << j; + } + result = dg(&i, cast(void *)&d); + if (result) + break; } return result; } @@ -548,17 +548,17 @@ unittest foreach_reverse(k, dchar d; s) { - assert(k == 4 - i); - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + assert(k == 4 - i); + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -566,16 +566,16 @@ unittest i = 0; foreach_reverse(k, dchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - switch (i) - { - case 0: assert(d == 'b'); assert(k == 8); break; - case 1: assert(d == '\U00100456'); assert(k == 4); break; - case 2: assert(d == '\u1234'); assert(k == 1); break; - case 3: assert(d == 'a'); assert(k == 0); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + switch (i) + { + case 0: assert(d == 'b'); assert(k == 8); break; + case 1: assert(d == '\U00100456'); assert(k == 4); break; + case 2: assert(d == '\u1234'); assert(k == 1); break; + case 3: assert(d == 'a'); assert(k == 0); break; + default: assert(0); + } + i++; } assert(i == 4); } @@ -587,19 +587,19 @@ extern (C) int _aApplyRwd2(wchar[] aa, dg2_t dg) debug(apply) printf("_aApplyRwd2(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; + { dchar d; - i--; - d = aa[i]; - if (d >= 0xDC00 && d <= 0xDFFF) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); - i--; - d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); - } - result = dg(&i, cast(void *)&d); - if (result) - break; + i--; + d = aa[i]; + if (d >= 0xDC00 && d <= 0xDFFF) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); + i--; + d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); + } + result = dg(&i, cast(void *)&d); + if (result) + break; } return result; } @@ -613,18 +613,18 @@ unittest foreach_reverse(k, dchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - assert(k == 4 - i); - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + assert(k == 4 - i); + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -632,16 +632,16 @@ unittest i = 0; foreach_reverse(k, dchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - switch (i) - { - case 0: assert(k == 4); assert(d == 'b'); break; - case 1: assert(k == 2); assert(d == '\U00100456'); break; - case 2: assert(k == 1); assert(d == '\u1234'); break; - case 3: assert(k == 0); assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + switch (i) + { + case 0: assert(k == 4); assert(d == 'b'); break; + case 1: assert(k == 2); assert(d == '\U00100456'); break; + case 2: assert(k == 1); assert(d == '\u1234'); break; + case 3: assert(k == 0); assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 4); } @@ -653,41 +653,41 @@ extern (C) int _aApplyRcw2(char[] aa, dg2_t dg) debug(apply) printf("_aApplyRcw2(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; - wchar w; + { dchar d; + wchar w; - i--; - w = aa[i]; - if (w & 0x80) - { char c = cast(char)w; - uint j; - uint m = 0x3F; - d = 0; - while ((c & 0xC0) != 0xC0) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); - i--; - d |= (c & 0x3F) << j; - j += 6; - m >>= 1; - c = aa[i]; - } - d |= (c & m) << j; + i--; + w = aa[i]; + if (w & 0x80) + { char c = cast(char)w; + uint j; + uint m = 0x3F; + d = 0; + while ((c & 0xC0) != 0xC0) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-8 sequence", 0); + i--; + d |= (c & 0x3F) << j; + j += 6; + m >>= 1; + c = aa[i]; + } + d |= (c & m) << j; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(&i, cast(void *)&w); - if (result) - break; - w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); - } - } - result = dg(&i, cast(void *)&w); - if (result) - break; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(&i, cast(void *)&w); + if (result) + break; + w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); + } + } + result = dg(&i, cast(void *)&w); + if (result) + break; } return result; } @@ -701,18 +701,18 @@ unittest foreach_reverse(k, wchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - assert(k == 4 - i); - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + assert(k == 4 - i); + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -720,17 +720,17 @@ unittest i = 0; foreach_reverse(k, wchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - switch (i) - { - case 0: assert(k == 8); assert(d == 'b'); break; - case 1: assert(k == 4); assert(d == 0xDBC1); break; - case 2: assert(k == 4); assert(d == 0xDC56); break; - case 3: assert(k == 1); assert(d == 0x1234); break; - case 4: assert(k == 0); assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + switch (i) + { + case 0: assert(k == 8); assert(d == 'b'); break; + case 1: assert(k == 4); assert(d == 0xDBC1); break; + case 2: assert(k == 4); assert(d == 0xDC56); break; + case 3: assert(k == 1); assert(d == 0x1234); break; + case 4: assert(k == 0); assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 5); } @@ -742,36 +742,36 @@ extern (C) int _aApplyRwc2(wchar[] aa, dg2_t dg) debug(apply) printf("_aApplyRwc2(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d; - char c; + { dchar d; + char c; - i--; - d = aa[i]; - if (d >= 0xDC00 && d <= 0xDFFF) - { if (i == 0) - throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); - i--; - d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); - } + i--; + d = aa[i]; + if (d >= 0xDC00 && d <= 0xDFFF) + { if (i == 0) + throw new std.utf.UtfException("Invalid UTF-16 sequence", 0); + i--; + d = ((aa[i] - 0xD7C0) << 10) + (d - 0xDC00); + } - if (d & ~0x7F) - { - char[4] buf; - char[] b; + if (d & ~0x7F) + { + char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(&i, cast(void *)&c2); - if (result) - return result; - } - continue; - } - c = cast(char)d; - result = dg(&i, cast(void *)&c); - if (result) - break; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(&i, cast(void *)&c2); + if (result) + return result; + } + continue; + } + c = cast(char)d; + result = dg(&i, cast(void *)&c); + if (result) + break; } return result; } @@ -785,18 +785,18 @@ unittest foreach_reverse(k, char d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - assert(k == 4 - i); - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + assert(k == 4 - i); + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -804,21 +804,21 @@ unittest i = 0; foreach_reverse(k, char d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - switch (i) - { - case 0: assert(k == 4); assert(d == 'b'); break; - case 1: assert(k == 2); assert(d == 0xF4); break; - case 2: assert(k == 2); assert(d == 0x80); break; - case 3: assert(k == 2); assert(d == 0x91); break; - case 4: assert(k == 2); assert(d == 0x96); break; - case 5: assert(k == 1); assert(d == 0xE1); break; - case 6: assert(k == 1); assert(d == 0x88); break; - case 7: assert(k == 1); assert(d == 0xB4); break; - case 8: assert(k == 0); assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + switch (i) + { + case 0: assert(k == 4); assert(d == 'b'); break; + case 1: assert(k == 2); assert(d == 0xF4); break; + case 2: assert(k == 2); assert(d == 0x80); break; + case 3: assert(k == 2); assert(d == 0x91); break; + case 4: assert(k == 2); assert(d == 0x96); break; + case 5: assert(k == 1); assert(d == 0xE1); break; + case 6: assert(k == 1); assert(d == 0x88); break; + case 7: assert(k == 1); assert(d == 0xB4); break; + case 8: assert(k == 0); assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 9); } @@ -830,29 +830,29 @@ extern (C) int _aApplyRdc2(dchar[] aa, dg2_t dg) debug(apply) printf("_aApplyRdc2(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d = aa[--i]; - char c; + { dchar d = aa[--i]; + char c; - if (d & ~0x7F) - { - char[4] buf; - char[] b; + if (d & ~0x7F) + { + char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, d); - foreach (char c2; b) - { - result = dg(&i, cast(void *)&c2); - if (result) - return result; - } - continue; - } - else - { c = cast(char)d; - } - result = dg(&i, cast(void *)&c); - if (result) - break; + b = std.utf.toUTF8(buf, d); + foreach (char c2; b) + { + result = dg(&i, cast(void *)&c2); + if (result) + return result; + } + continue; + } + else + { c = cast(char)d; + } + result = dg(&i, cast(void *)&c); + if (result) + break; } return result; } @@ -866,18 +866,18 @@ unittest foreach_reverse(k, char d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - assert(k == 4 - i); - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + assert(k == 4 - i); + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -885,21 +885,21 @@ unittest i = 0; foreach_reverse(k, char d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - switch (i) - { - case 0: assert(k == 3); assert(d == 'b'); break; - case 1: assert(k == 2); assert(d == 0xF4); break; - case 2: assert(k == 2); assert(d == 0x80); break; - case 3: assert(k == 2); assert(d == 0x91); break; - case 4: assert(k == 2); assert(d == 0x96); break; - case 5: assert(k == 1); assert(d == 0xE1); break; - case 6: assert(k == 1); assert(d == 0x88); break; - case 7: assert(k == 1); assert(d == 0xB4); break; - case 8: assert(k == 0); assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + switch (i) + { + case 0: assert(k == 3); assert(d == 'b'); break; + case 1: assert(k == 2); assert(d == 0xF4); break; + case 2: assert(k == 2); assert(d == 0x80); break; + case 3: assert(k == 2); assert(d == 0x91); break; + case 4: assert(k == 2); assert(d == 0x96); break; + case 5: assert(k == 1); assert(d == 0xE1); break; + case 6: assert(k == 1); assert(d == 0x88); break; + case 7: assert(k == 1); assert(d == 0xB4); break; + case 8: assert(k == 0); assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 9); } @@ -911,22 +911,22 @@ extern (C) int _aApplyRdw2(dchar[] aa, dg2_t dg) debug(apply) printf("_aApplyRdw2(), len = %d\n", aa.length); for (size_t i = aa.length; i != 0; ) - { dchar d = aa[--i]; - wchar w; + { dchar d = aa[--i]; + wchar w; - if (d <= 0xFFFF) - w = cast(wchar) d; - else - { - w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); - result = dg(&i, cast(void *)&w); - if (result) - break; - w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); - } - result = dg(&i, cast(void *)&w); - if (result) - break; + if (d <= 0xFFFF) + w = cast(wchar) d; + else + { + w = cast(wchar) ((((d - 0x10000) >> 10) & 0x3FF) + 0xD800); + result = dg(&i, cast(void *)&w); + if (result) + break; + w = cast(wchar) (((d - 0x10000) & 0x3FF) + 0xDC00); + } + result = dg(&i, cast(void *)&w); + if (result) + break; } return result; } @@ -940,18 +940,18 @@ unittest foreach_reverse(k, wchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - assert(k == 4 - i); - switch (i) - { - case 0: assert(d == 'o'); break; - case 1: assert(d == 'l'); break; - case 2: assert(d == 'l'); break; - case 3: assert(d == 'e'); break; - case 4: assert(d == 'h'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + assert(k == 4 - i); + switch (i) + { + case 0: assert(d == 'o'); break; + case 1: assert(d == 'l'); break; + case 2: assert(d == 'l'); break; + case 3: assert(d == 'e'); break; + case 4: assert(d == 'h'); break; + default: assert(0); + } + i++; } assert(i == 5); @@ -959,17 +959,17 @@ unittest i = 0; foreach_reverse(k, wchar d; s) { - //printf("i = %d, k = %d, d = %x\n", i, k, d); - switch (i) - { - case 0: assert(k == 3); assert(d == 'b'); break; - case 1: assert(k == 2); assert(d == 0xDBC1); break; - case 2: assert(k == 2); assert(d == 0xDC56); break; - case 3: assert(k == 1); assert(d == 0x1234); break; - case 4: assert(k == 0); assert(d == 'a'); break; - default: assert(0); - } - i++; + //printf("i = %d, k = %d, d = %x\n", i, k, d); + switch (i) + { + case 0: assert(k == 3); assert(d == 'b'); break; + case 1: assert(k == 2); assert(d == 0xDBC1); break; + case 2: assert(k == 2); assert(d == 0xDC56); break; + case 3: assert(k == 1); assert(d == 0x1234); break; + case 4: assert(k == 0); assert(d == 'a'); break; + default: assert(0); + } + i++; } assert(i == 5); } diff --git a/internal/aaA.d b/internal/aaA.d index 9b7e800d6..3f1818c95 100644 --- a/internal/aaA.d +++ b/internal/aaA.d @@ -76,7 +76,7 @@ struct aaA struct BB { aaA*[] b; - size_t nodes; // total number of aaA nodes + size_t nodes; // total number of aaA nodes } /* This is the type actually seen by the programmer, although @@ -111,8 +111,8 @@ void _aaInvAh(aaA*[] aa) { for (size_t i = 0; i < aa.length; i++) { - if (aa[i]) - _aaInvAh_x(aa[i]); + if (aa[i]) + _aaInvAh_x(aa[i]); } } @@ -122,9 +122,9 @@ private int _aaCmpAh_x(aaA *e1, aaA *e2) c = e1.hash - e2.hash; if (c == 0) { - c = e1.key.length - e2.key.length; - if (c == 0) - c = memcmp((char *)e1.key, (char *)e2.key, e1.key.length); + c = e1.key.length - e2.key.length; + if (c == 0) + c = memcmp((char *)e1.key, (char *)e2.key, e1.key.length); } return c; } @@ -141,31 +141,31 @@ private void _aaInvAh_x(aaA *e) while (1) { int c; - e1 = e.left; - if (e1) - { - _aaInvAh_x(e1); // ordinary recursion - do - { - c = _aaCmpAh_x(e1, e); - assert(c < 0); - e1 = e1.right; - } while (e1 != null); - } + e1 = e.left; + if (e1) + { + _aaInvAh_x(e1); // ordinary recursion + do + { + c = _aaCmpAh_x(e1, e); + assert(c < 0); + e1 = e1.right; + } while (e1 != null); + } - e2 = e.right; - if (e2) - { - do - { - c = _aaCmpAh_x(e, e2); - assert(c < 0); - e2 = e2.left; - } while (e2 != null); - e = e.right; // tail recursion - } - else - break; + e2 = e.right; + if (e2) + { + do + { + c = _aaCmpAh_x(e, e2); + assert(c < 0); + e2 = e2.left; + } while (e2 != null); + e = e.right; // tail recursion + } + else + break; } } +/ @@ -177,44 +177,44 @@ private void _aaInvAh_x(aaA *e) size_t _aaLen(AA aa) in { - //printf("_aaLen()+\n"); - //_aaInv(aa); + //printf("_aaLen()+\n"); + //_aaInv(aa); } out (result) { - size_t len = 0; + size_t len = 0; - void _aaLen_x(aaA* ex) - { - auto e = ex; - len++; + void _aaLen_x(aaA* ex) + { + auto e = ex; + len++; - while (1) - { - if (e.right) - _aaLen_x(e.right); - e = e.left; - if (!e) - break; - len++; - } - } + while (1) + { + if (e.right) + _aaLen_x(e.right); + e = e.left; + if (!e) + break; + len++; + } + } - if (aa.a) - { - foreach (e; aa.a.b) - { - if (e) - _aaLen_x(e); - } - } - assert(len == result); + if (aa.a) + { + foreach (e; aa.a.b) + { + if (e) + _aaLen_x(e); + } + } + assert(len == result); - //printf("_aaLen()-\n"); + //printf("_aaLen()-\n"); } body { - return aa.a ? aa.a.nodes : 0; + return aa.a ? aa.a.nodes : 0; } @@ -226,70 +226,70 @@ size_t _aaLen(AA aa) void* _aaGet(AA* aa, TypeInfo keyti, size_t valuesize, ...) in { - assert(aa); + assert(aa); } out (result) { - assert(result); - assert(aa.a); - assert(aa.a.b.length); - //assert(_aaInAh(*aa.a, key)); + assert(result); + assert(aa.a); + assert(aa.a.b.length); + //assert(_aaInAh(*aa.a, key)); } body { - //printf("aaGet()\n"); - auto pkey = cast(void *)(&valuesize + 1); - size_t i; - aaA* e; - auto keysize = aligntsize(keyti.tsize()); - //printf("keysize = %d\n", keysize); + //printf("aaGet()\n"); + auto pkey = cast(void *)(&valuesize + 1); + size_t i; + aaA* e; + auto keysize = aligntsize(keyti.tsize()); + //printf("keysize = %d\n", keysize); - if (!aa.a) - aa.a = new BB(); + if (!aa.a) + aa.a = new BB(); - if (!aa.a.b.length) - { - alias aaA *pa; - auto len = prime_list[0]; + if (!aa.a.b.length) + { + alias aaA *pa; + auto len = prime_list[0]; - aa.a.b = new pa[len]; - } + aa.a.b = new pa[len]; + } - auto key_hash = keyti.getHash(pkey); - //printf("hash = %d\n", key_hash); - i = key_hash % aa.a.b.length; - auto pe = &aa.a.b[i]; - while ((e = *pe) !is null) - { - if (key_hash == e.hash) - { - auto c = keyti.compare(pkey, e + 1); - if (c == 0) - goto Lret; - pe = (c < 0) ? &e.left : &e.right; - } - else - pe = (key_hash < e.hash) ? &e.left : &e.right; - } + auto key_hash = keyti.getHash(pkey); + //printf("hash = %d\n", key_hash); + i = key_hash % aa.a.b.length; + auto pe = &aa.a.b[i]; + while ((e = *pe) !is null) + { + if (key_hash == e.hash) + { + auto c = keyti.compare(pkey, e + 1); + if (c == 0) + goto Lret; + pe = (c < 0) ? &e.left : &e.right; + } + else + pe = (key_hash < e.hash) ? &e.left : &e.right; + } - // Not found, create new elem - //printf("create new one\n"); - std.gc.disable(); - e = cast(aaA *) cast(void*) new void[aaA.sizeof + keysize + valuesize]; - std.gc.enable(); - memcpy(e + 1, pkey, keysize); - e.hash = key_hash; - *pe = e; + // Not found, create new elem + //printf("create new one\n"); + std.gc.disable(); + e = cast(aaA *) cast(void*) new void[aaA.sizeof + keysize + valuesize]; + std.gc.enable(); + memcpy(e + 1, pkey, keysize); + e.hash = key_hash; + *pe = e; - auto nodes = ++aa.a.nodes; - //printf("length = %d, nodes = %d\n", (*aa.a).length, nodes); - if (nodes > aa.a.b.length * 4) - { - _aaRehash(aa,keyti); - } + auto nodes = ++aa.a.nodes; + //printf("length = %d, nodes = %d\n", (*aa.a).length, nodes); + if (nodes > aa.a.b.length * 4) + { + _aaRehash(aa,keyti); + } Lret: - return cast(void *)(e + 1) + keysize; + return cast(void *)(e + 1) + keysize; } @@ -300,42 +300,42 @@ void* _aaGet(AA* aa, TypeInfo keyti, size_t valuesize, ...) void* _aaGetRvalue(AA aa, TypeInfo keyti, size_t valuesize, ...) { - //printf("_aaGetRvalue(valuesize = %u)\n", valuesize); - if (!aa.a) - return null; + //printf("_aaGetRvalue(valuesize = %u)\n", valuesize); + if (!aa.a) + return null; - auto pkey = cast(void *)(&valuesize + 1); - auto keysize = aligntsize(keyti.tsize()); - auto len = aa.a.b.length; + auto pkey = cast(void *)(&valuesize + 1); + auto keysize = aligntsize(keyti.tsize()); + auto len = aa.a.b.length; - if (len) - { - auto key_hash = keyti.getHash(pkey); - //printf("hash = %d\n", key_hash); - size_t i = key_hash % len; - auto e = aa.a.b[i]; - while (e !is null) - { - if (key_hash == e.hash) - { - auto c = keyti.compare(pkey, e + 1); - if (c == 0) - return cast(void *)(e + 1) + keysize; - e = (c < 0) ? e.left : e.right; - } - else - e = (key_hash < e.hash) ? e.left : e.right; - } - } - return null; // not found, caller will throw exception + if (len) + { + auto key_hash = keyti.getHash(pkey); + //printf("hash = %d\n", key_hash); + size_t i = key_hash % len; + auto e = aa.a.b[i]; + while (e !is null) + { + if (key_hash == e.hash) + { + auto c = keyti.compare(pkey, e + 1); + if (c == 0) + return cast(void *)(e + 1) + keysize; + e = (c < 0) ? e.left : e.right; + } + else + e = (key_hash < e.hash) ? e.left : e.right; + } + } + return null; // not found, caller will throw exception } /************************************************* * Determine if key is in aa. * Returns: - * null not in aa - * !=null in aa, return pointer to value + * null not in aa + * !=null in aa, return pointer to value */ void* _aaIn(AA aa, TypeInfo keyti, ...) @@ -344,40 +344,40 @@ void* _aaIn(AA aa, TypeInfo keyti, ...) } out (result) { - //assert(result == 0 || result == 1); + //assert(result == 0 || result == 1); } body { - if (aa.a) - { - auto pkey = cast(void *)(&keyti + 1); + if (aa.a) + { + auto pkey = cast(void *)(&keyti + 1); - //printf("_aaIn(), .length = %d, .ptr = %x\n", aa.a.length, cast(uint)aa.a.ptr); - auto len = aa.a.b.length; + //printf("_aaIn(), .length = %d, .ptr = %x\n", aa.a.length, cast(uint)aa.a.ptr); + auto len = aa.a.b.length; - if (len) - { - auto key_hash = keyti.getHash(pkey); - //printf("hash = %d\n", key_hash); - size_t i = key_hash % len; - auto e = aa.a.b[i]; - while (e !is null) - { - if (key_hash == e.hash) - { - auto c = keyti.compare(pkey, e + 1); - if (c == 0) - return cast(void *)(e + 1) + aligntsize(keyti.tsize()); - e = (c < 0) ? e.left : e.right; - } - else - e = (key_hash < e.hash) ? e.left : e.right; - } - } - } + if (len) + { + auto key_hash = keyti.getHash(pkey); + //printf("hash = %d\n", key_hash); + size_t i = key_hash % len; + auto e = aa.a.b[i]; + while (e !is null) + { + if (key_hash == e.hash) + { + auto c = keyti.compare(pkey, e + 1); + if (c == 0) + return cast(void *)(e + 1) + aligntsize(keyti.tsize()); + e = (c < 0) ? e.left : e.right; + } + else + e = (key_hash < e.hash) ? e.left : e.right; + } + } + } - // Not found - return null; + // Not found + return null; } @@ -388,59 +388,59 @@ void* _aaIn(AA aa, TypeInfo keyti, ...) void _aaDel(AA aa, TypeInfo keyti, ...) { - auto pkey = cast(void *)(&keyti + 1); - aaA* e; + auto pkey = cast(void *)(&keyti + 1); + aaA* e; - if (aa.a && aa.a.b.length) - { - auto key_hash = keyti.getHash(pkey); - //printf("hash = %d\n", key_hash); - size_t i = key_hash % aa.a.b.length; - auto pe = &aa.a.b[i]; - while ((e = *pe) !is null) // null means not found - { - if (key_hash == e.hash) - { - auto c = keyti.compare(pkey, e + 1); - if (c == 0) - { - if (!e.left && !e.right) - { - *pe = null; - } - else if (e.left && !e.right) - { - *pe = e.left; - e.left = null; - } - else if (!e.left && e.right) - { - *pe = e.right; - e.right = null; - } - else - { - *pe = e.left; - e.left = null; - do - pe = &(*pe).right; - while (*pe); - *pe = e.right; - e.right = null; - } + if (aa.a && aa.a.b.length) + { + auto key_hash = keyti.getHash(pkey); + //printf("hash = %d\n", key_hash); + size_t i = key_hash % aa.a.b.length; + auto pe = &aa.a.b[i]; + while ((e = *pe) !is null) // null means not found + { + if (key_hash == e.hash) + { + auto c = keyti.compare(pkey, e + 1); + if (c == 0) + { + if (!e.left && !e.right) + { + *pe = null; + } + else if (e.left && !e.right) + { + *pe = e.left; + e.left = null; + } + else if (!e.left && e.right) + { + *pe = e.right; + e.right = null; + } + else + { + *pe = e.left; + e.left = null; + do + pe = &(*pe).right; + while (*pe); + *pe = e.right; + e.right = null; + } - aa.a.nodes--; + aa.a.nodes--; - // Should notify GC that e can be free'd now - delete e; - break; - } - pe = (c < 0) ? &e.left : &e.right; - } - else - pe = (key_hash < e.hash) ? &e.left : &e.right; - } - } + // Should notify GC that e can be free'd now + delete e; + break; + } + pe = (c < 0) ? &e.left : &e.right; + } + else + pe = (key_hash < e.hash) ? &e.left : &e.right; + } + } } @@ -451,45 +451,45 @@ void _aaDel(AA aa, TypeInfo keyti, ...) ArrayRet_t _aaValues(AA aa, size_t keysize, size_t valuesize) in { - assert(keysize == aligntsize(keysize)); + assert(keysize == aligntsize(keysize)); } body { - size_t resi; - Array a; + size_t resi; + Array a; - void _aaValues_x(aaA* e) - { - do - { - memcpy(a.ptr + resi * valuesize, - cast(byte*)e + aaA.sizeof + keysize, - valuesize); - resi++; - if (e.left) - { if (!e.right) - { e = e.left; - continue; - } - _aaValues_x(e.left); - } - e = e.right; - } while (e !is null); - } + void _aaValues_x(aaA* e) + { + do + { + memcpy(a.ptr + resi * valuesize, + cast(byte*)e + aaA.sizeof + keysize, + valuesize); + resi++; + if (e.left) + { if (!e.right) + { e = e.left; + continue; + } + _aaValues_x(e.left); + } + e = e.right; + } while (e !is null); + } - if (aa.a) - { - a.length = _aaLen(aa); - a.ptr = (new void[a.length * valuesize]).ptr; - resi = 0; - foreach (e; aa.a.b) - { - if (e) - _aaValues_x(e); - } - assert(resi == a.length); - } - return *cast(ArrayRet_t*)(&a); + if (aa.a) + { + a.length = _aaLen(aa); + a.ptr = (new void[a.length * valuesize]).ptr; + resi = 0; + foreach (e; aa.a.b) + { + if (e) + _aaValues_x(e); + } + assert(resi == a.length); + } + return *cast(ArrayRet_t*)(&a); } @@ -500,92 +500,92 @@ ArrayRet_t _aaValues(AA aa, size_t keysize, size_t valuesize) void* _aaRehash(AA* paa, TypeInfo keyti) in { - //_aaInvAh(paa); + //_aaInvAh(paa); } out (result) { - //_aaInvAh(result); + //_aaInvAh(result); } body { - BB newb; + BB newb; - void _aaRehash_x(aaA* olde) - { - while (1) - { - auto left = olde.left; - auto right = olde.right; - olde.left = null; - olde.right = null; + void _aaRehash_x(aaA* olde) + { + while (1) + { + auto left = olde.left; + auto right = olde.right; + olde.left = null; + olde.right = null; - aaA* e; + aaA* e; - //printf("rehash %p\n", olde); - auto key_hash = olde.hash; - size_t i = key_hash % newb.b.length; - auto pe = &newb.b[i]; - while ((e = *pe) !is null) - { - //printf("\te = %p, e.left = %p, e.right = %p\n", e, e.left, e.right); - assert(e.left != e); - assert(e.right != e); - if (key_hash == e.hash) - { - auto c = keyti.compare(olde + 1, e + 1); - assert(c != 0); - pe = (c < 0) ? &e.left : &e.right; - } - else - pe = (key_hash < e.hash) ? &e.left : &e.right; - } - *pe = olde; + //printf("rehash %p\n", olde); + auto key_hash = olde.hash; + size_t i = key_hash % newb.b.length; + auto pe = &newb.b[i]; + while ((e = *pe) !is null) + { + //printf("\te = %p, e.left = %p, e.right = %p\n", e, e.left, e.right); + assert(e.left != e); + assert(e.right != e); + if (key_hash == e.hash) + { + auto c = keyti.compare(olde + 1, e + 1); + assert(c != 0); + pe = (c < 0) ? &e.left : &e.right; + } + else + pe = (key_hash < e.hash) ? &e.left : &e.right; + } + *pe = olde; - if (right) - { - if (!left) - { olde = right; - continue; - } - _aaRehash_x(right); - } - if (!left) - break; - olde = left; - } - } + if (right) + { + if (!left) + { olde = right; + continue; + } + _aaRehash_x(right); + } + if (!left) + break; + olde = left; + } + } - //printf("Rehash\n"); - if (paa.a) - { - auto aa = paa.a; - auto len = _aaLen(*paa); - if (len) - { size_t i; + //printf("Rehash\n"); + if (paa.a) + { + auto aa = paa.a; + auto len = _aaLen(*paa); + if (len) + { size_t i; - for (i = 0; i < prime_list.length - 1; i++) - { - if (len <= prime_list[i]) - break; - } - //printf("rehash %d x%x\n", len, len); - len = prime_list[i]; - newb.b = new aaA*[len]; + for (i = 0; i < prime_list.length - 1; i++) + { + if (len <= prime_list[i]) + break; + } + //printf("rehash %d x%x\n", len, len); + len = prime_list[i]; + newb.b = new aaA*[len]; - foreach (e; aa.b) - { - if (e) - _aaRehash_x(e); - } - delete aa.b; + foreach (e; aa.b) + { + if (e) + _aaRehash_x(e); + } + delete aa.b; - newb.nodes = aa.nodes; - } + newb.nodes = aa.nodes; + } - *paa.a = newb; - _aaBalance(paa); - } - return (*paa).a; + *paa.a = newb; + _aaBalance(paa); + } + return (*paa).a; } /******************************************** @@ -597,48 +597,48 @@ void _aaBalance(AA* paa) //printf("_aaBalance()\n"); if (paa.a) { - aaA*[16] tmp; - aaA*[] array = tmp; + aaA*[16] tmp; + aaA*[] array = tmp; - auto aa = paa.a; - foreach (j, e; aa.b) - { - /* Temporarily store contents of bucket in array[] - */ - size_t k = 0; + auto aa = paa.a; + foreach (j, e; aa.b) + { + /* Temporarily store contents of bucket in array[] + */ + size_t k = 0; - void addToArray(aaA* e) - { - while (e) - { addToArray(e.left); - if (k == array.length) - array.length = array.length * 2; - array[k++] = e; - e = e.right; - } - } + void addToArray(aaA* e) + { + while (e) + { addToArray(e.left); + if (k == array.length) + array.length = array.length * 2; + array[k++] = e; + e = e.right; + } + } - addToArray(e); + addToArray(e); - /* The contents of the bucket are now sorted into array[]. - * Rebuild the tree. - */ + /* The contents of the bucket are now sorted into array[]. + * Rebuild the tree. + */ - void buildTree(aaA** p, size_t x1, size_t x2) - { - if (x1 >= x2) - *p = null; - else - { auto mid = (x1 + x2) >> 1; - *p = array[mid]; - buildTree(&(*p).left, x1, mid); - buildTree(&(*p).right, mid + 1, x2); - } - } + void buildTree(aaA** p, size_t x1, size_t x2) + { + if (x1 >= x2) + *p = null; + else + { auto mid = (x1 + x2) >> 1; + *p = array[mid]; + buildTree(&(*p).left, x1, mid); + buildTree(&(*p).right, mid + 1, x2); + } + } - auto p = &aa.b[j]; - buildTree(p, 0, k); - } + auto p = &aa.b[j]; + buildTree(p, 0, k); + } } } @@ -648,42 +648,42 @@ void _aaBalance(AA* paa) ArrayRet_t _aaKeys(AA aa, size_t keysize) { - byte[] res; - size_t resi; + byte[] res; + size_t resi; - void _aaKeys_x(aaA* e) - { - do - { - memcpy(&res[resi * keysize], cast(byte*)(e + 1), keysize); - resi++; - if (e.left) - { if (!e.right) - { e = e.left; - continue; - } - _aaKeys_x(e.left); - } - e = e.right; - } while (e !is null); - } + void _aaKeys_x(aaA* e) + { + do + { + memcpy(&res[resi * keysize], cast(byte*)(e + 1), keysize); + resi++; + if (e.left) + { if (!e.right) + { e = e.left; + continue; + } + _aaKeys_x(e.left); + } + e = e.right; + } while (e !is null); + } - auto len = _aaLen(aa); - if (!len) - return 0; - res = cast(byte[])new void[len * keysize]; - resi = 0; - foreach (e; aa.a.b) - { - if (e) - _aaKeys_x(e); - } - assert(resi == len); + auto len = _aaLen(aa); + if (!len) + return 0; + res = cast(byte[])new void[len * keysize]; + resi = 0; + foreach (e; aa.a.b) + { + if (e) + _aaKeys_x(e); + } + assert(resi == len); - Array a; - a.length = len; - a.ptr = res.ptr; - return *cast(ArrayRet_t*)(&a); + Array a; + a.length = len; + a.ptr = res.ptr; + return *cast(ArrayRet_t*)(&a); } @@ -705,41 +705,41 @@ body //printf("_aaApply(aa = x%llx, keysize = %d, dg = x%llx)\n", aa.a, keysize, dg); int treewalker(aaA* e) - { int result; + { int result; - do - { - //printf("treewalker(e = %p, dg = x%llx)\n", e, dg); - result = dg(cast(void *)(e + 1) + keysize); - if (result) - break; - if (e.right) - { if (!e.left) - { - e = e.right; - continue; - } - result = treewalker(e.right); - if (result) - break; - } - e = e.left; - } while (e); + do + { + //printf("treewalker(e = %p, dg = x%llx)\n", e, dg); + result = dg(cast(void *)(e + 1) + keysize); + if (result) + break; + if (e.right) + { if (!e.left) + { + e = e.right; + continue; + } + result = treewalker(e.right); + if (result) + break; + } + e = e.left; + } while (e); - return result; + return result; } if (aa.a) { - foreach (e; aa.a.b) - { - if (e) - { - result = treewalker(e); - if (result) - break; - } - } + foreach (e; aa.a.b) + { + if (e) + { + result = treewalker(e); + if (result) + break; + } + } } return result; } @@ -758,41 +758,41 @@ body //printf("_aaApply(aa = x%llx, keysize = %d, dg = x%llx)\n", aa.a, keysize, dg); int treewalker(aaA* e) - { int result; + { int result; - do - { - //printf("treewalker(e = %p, dg = x%llx)\n", e, dg); - result = dg(cast(void *)(e + 1), cast(void *)(e + 1) + keysize); - if (result) - break; - if (e.right) - { if (!e.left) - { - e = e.right; - continue; - } - result = treewalker(e.right); - if (result) - break; - } - e = e.left; - } while (e); + do + { + //printf("treewalker(e = %p, dg = x%llx)\n", e, dg); + result = dg(cast(void *)(e + 1), cast(void *)(e + 1) + keysize); + if (result) + break; + if (e.right) + { if (!e.left) + { + e = e.right; + continue; + } + result = treewalker(e.right); + if (result) + break; + } + e = e.left; + } while (e); - return result; + return result; } if (aa.a) { - foreach (e; aa.a.b) - { - if (e) - { - result = treewalker(e); - if (result) - break; - } - } + foreach (e; aa.a.b) + { + if (e) + { + result = treewalker(e); + if (result) + break; + } + } } return result; } @@ -806,77 +806,77 @@ body extern (C) BB* _d_assocarrayliteralT(TypeInfo_AssociativeArray ti, size_t length, ...) { - auto valuesize = ti.next.tsize(); // value size + auto valuesize = ti.next.tsize(); // value size auto keyti = ti.key; - auto keysize = keyti.tsize(); // key size + auto keysize = keyti.tsize(); // key size BB* result; //printf("_d_assocarrayliteralT(keysize = %d, valuesize = %d, length = %d)\n", keysize, valuesize, length); //printf("tivalue = %.*s\n", ti.next.classinfo.name); if (length == 0 || valuesize == 0 || keysize == 0) { - ; + ; } else { - va_list q; - va_start!(size_t)(q, length); + va_list q; + va_start!(size_t)(q, length); - result = new BB(); - size_t i; + result = new BB(); + size_t i; - for (i = 0; i < prime_list.length - 1; i++) - { - if (length <= prime_list[i]) - break; - } - auto len = prime_list[i]; - result.b = new aaA*[len]; + for (i = 0; i < prime_list.length - 1; i++) + { + if (length <= prime_list[i]) + break; + } + auto len = prime_list[i]; + result.b = new aaA*[len]; - size_t keystacksize = (keysize + int.sizeof - 1) & ~(int.sizeof - 1); - size_t valuestacksize = (valuesize + int.sizeof - 1) & ~(int.sizeof - 1); + size_t keystacksize = (keysize + int.sizeof - 1) & ~(int.sizeof - 1); + size_t valuestacksize = (valuesize + int.sizeof - 1) & ~(int.sizeof - 1); - size_t keytsize = aligntsize(keysize); + size_t keytsize = aligntsize(keysize); - for (size_t j = 0; j < length; j++) - { void* pkey = q; - q += keystacksize; - void* pvalue = q; - q += valuestacksize; - aaA* e; + for (size_t j = 0; j < length; j++) + { void* pkey = q; + q += keystacksize; + void* pvalue = q; + q += valuestacksize; + aaA* e; - auto key_hash = keyti.getHash(pkey); - //printf("hash = %d\n", key_hash); - i = key_hash % len; - auto pe = &result.b[i]; - while (1) - { - e = *pe; - if (!e) - { - // Not found, create new elem - //printf("create new one\n"); - e = cast(aaA *) cast(void*) new void[aaA.sizeof + keytsize + valuesize]; - memcpy(e + 1, pkey, keysize); - e.hash = key_hash; - *pe = e; - result.nodes++; - break; - } - if (key_hash == e.hash) - { - auto c = keyti.compare(pkey, e + 1); - if (c == 0) - break; - pe = (c < 0) ? &e.left : &e.right; - } - else - pe = (key_hash < e.hash) ? &e.left : &e.right; - } - memcpy(cast(void *)(e + 1) + keytsize, pvalue, valuesize); - } + auto key_hash = keyti.getHash(pkey); + //printf("hash = %d\n", key_hash); + i = key_hash % len; + auto pe = &result.b[i]; + while (1) + { + e = *pe; + if (!e) + { + // Not found, create new elem + //printf("create new one\n"); + e = cast(aaA *) cast(void*) new void[aaA.sizeof + keytsize + valuesize]; + memcpy(e + 1, pkey, keysize); + e.hash = key_hash; + *pe = e; + result.nodes++; + break; + } + if (key_hash == e.hash) + { + auto c = keyti.compare(pkey, e + 1); + if (c == 0) + break; + pe = (c < 0) ? &e.left : &e.right; + } + else + pe = (key_hash < e.hash) ? &e.left : &e.right; + } + memcpy(cast(void *)(e + 1) + keytsize, pvalue, valuesize); + } - va_end(q); + va_end(q); } return result; } @@ -885,8 +885,8 @@ BB* _d_assocarrayliteralT(TypeInfo_AssociativeArray ti, size_t length, ...) /*********************************** * Compare AA contents for equality. * Returns: - * 1 equal - * 0 not equal + * 1 equal + * 0 not equal */ int _aaEqual(TypeInfo_AssociativeArray ti, AA e1, AA e2) { @@ -895,11 +895,11 @@ int _aaEqual(TypeInfo_AssociativeArray ti, AA e1, AA e2) //printf("valueti = %.*s\n", ti.next.classinfo.name); if (e1.a is e2.a) - return 1; + return 1; size_t len = _aaLen(e1); if (len != _aaLen(e2)) - return 0; + return 0; /* Algorithm: Visit each key/value pair in e1. If that key doesn't exist * in e2, or if the value in e1 doesn't match the one in e2, the arrays @@ -916,65 +916,65 @@ int _aaEqual(TypeInfo_AssociativeArray ti, AA e1, AA e2) { do { - auto pkey = cast(void*)(e + 1); - auto pvalue = pkey + keysize; - //printf("key = %d, value = %g\n", *cast(int*)pkey, *cast(double*)pvalue); + auto pkey = cast(void*)(e + 1); + auto pvalue = pkey + keysize; + //printf("key = %d, value = %g\n", *cast(int*)pkey, *cast(double*)pvalue); - // We have key/value for e1. See if they exist in e2 + // We have key/value for e1. See if they exist in e2 - auto key_hash = keyti.getHash(pkey); - //printf("hash = %d\n", key_hash); - auto i = key_hash % len2; - auto f = e2.a.b[i]; - while (1) - { - //printf("f is %p\n", f); - if (f is null) - return 0; // key not found, so AA's are not equal - if (key_hash == f.hash) - { - //printf("hash equals\n"); - auto c = keyti.compare(pkey, f + 1); - if (c == 0) - { // Found key in e2. Compare values - //printf("key equals\n"); - auto pvalue2 = cast(void *)(f + 1) + keysize; - if (valueti.equals(pvalue, pvalue2)) - { - //printf("value equals\n"); - break; - } - else - return 0; // values don't match, so AA's are not equal - } - f = (c < 0) ? f.left : f.right; - } - else - f = (key_hash < f.hash) ? f.left : f.right; - } + auto key_hash = keyti.getHash(pkey); + //printf("hash = %d\n", key_hash); + auto i = key_hash % len2; + auto f = e2.a.b[i]; + while (1) + { + //printf("f is %p\n", f); + if (f is null) + return 0; // key not found, so AA's are not equal + if (key_hash == f.hash) + { + //printf("hash equals\n"); + auto c = keyti.compare(pkey, f + 1); + if (c == 0) + { // Found key in e2. Compare values + //printf("key equals\n"); + auto pvalue2 = cast(void *)(f + 1) + keysize; + if (valueti.equals(pvalue, pvalue2)) + { + //printf("value equals\n"); + break; + } + else + return 0; // values don't match, so AA's are not equal + } + f = (c < 0) ? f.left : f.right; + } + else + f = (key_hash < f.hash) ? f.left : f.right; + } - // Look at next entry in e1 + // Look at next entry in e1 if (e.left) { if (!e.right) { e = e.left; continue; } if (_aaKeys_x(e.left) == 0) - return 0; + return 0; } e = e.right; } while (e !is null); - return 1; // this subtree matches + return 1; // this subtree matches } foreach (e; e1.a.b) { if (e) { if (_aaKeys_x(e) == 0) - return 0; - } + return 0; + } } - return 1; // equal + return 1; // equal } diff --git a/internal/adi.d b/internal/adi.d index bcff82f15..8fd331281 100644 --- a/internal/adi.d +++ b/internal/adi.d @@ -28,7 +28,7 @@ * distribution. */ -//debug=adi; // uncomment to turn on debugging printf's +//debug=adi; // uncomment to turn on debugging printf's import std.stdio; import std.c.stdio; @@ -54,61 +54,61 @@ extern (C) long _adReverseChar(char[] a) { if (a.length > 1) { - char[6] tmp; - char[6] tmplo; - char* lo = a.ptr; - char* hi = &a[length - 1]; + char[6] tmp; + char[6] tmplo; + char* lo = a.ptr; + char* hi = &a[length - 1]; - while (lo < hi) - { auto clo = *lo; - auto chi = *hi; + while (lo < hi) + { auto clo = *lo; + auto chi = *hi; - //printf("lo = %d, hi = %d\n", lo, hi); - if (clo <= 0x7F && chi <= 0x7F) - { - //printf("\tascii\n"); - *lo = chi; - *hi = clo; - lo++; - hi--; - continue; - } + //printf("lo = %d, hi = %d\n", lo, hi); + if (clo <= 0x7F && chi <= 0x7F) + { + //printf("\tascii\n"); + *lo = chi; + *hi = clo; + lo++; + hi--; + continue; + } - uint stridelo = std.utf.UTF8stride[clo]; + uint stridelo = std.utf.UTF8stride[clo]; - uint stridehi = 1; - while ((chi & 0xC0) == 0x80) - { - chi = *--hi; - stridehi++; - assert(hi >= lo); - } - if (lo == hi) - break; + uint stridehi = 1; + while ((chi & 0xC0) == 0x80) + { + chi = *--hi; + stridehi++; + assert(hi >= lo); + } + if (lo == hi) + break; - //printf("\tstridelo = %d, stridehi = %d\n", stridelo, stridehi); - if (stridelo == stridehi) - { + //printf("\tstridelo = %d, stridehi = %d\n", stridelo, stridehi); + if (stridelo == stridehi) + { - memcpy(tmp.ptr, lo, stridelo); - memcpy(lo, hi, stridelo); - memcpy(hi, tmp.ptr, stridelo); - lo += stridelo; - hi--; - continue; - } + memcpy(tmp.ptr, lo, stridelo); + memcpy(lo, hi, stridelo); + memcpy(hi, tmp.ptr, stridelo); + lo += stridelo; + hi--; + continue; + } - /* Shift the whole array. This is woefully inefficient - */ - memcpy(tmp.ptr, hi, stridehi); - memcpy(tmplo.ptr, lo, stridelo); - memmove(lo + stridehi, lo + stridelo , (hi - lo) - stridelo); - memcpy(lo, tmp.ptr, stridehi); - memcpy(hi + stridehi - stridelo, tmplo.ptr, stridelo); + /* Shift the whole array. This is woefully inefficient + */ + memcpy(tmp.ptr, hi, stridehi); + memcpy(tmplo.ptr, lo, stridelo); + memmove(lo + stridehi, lo + stridelo , (hi - lo) - stridelo); + memcpy(lo, tmp.ptr, stridehi); + memcpy(hi + stridehi - stridelo, tmplo.ptr, stridelo); - lo += stridehi; - hi = hi - 1 + (stridehi - stridelo); - } + lo += stridehi; + hi = hi - 1 + (stridehi - stridelo); + } } return *cast(long*)(&a); } @@ -150,59 +150,59 @@ extern (C) long _adReverseWchar(wchar[] a) { if (a.length > 1) { - wchar[2] tmp; - wchar* lo = a.ptr; - wchar* hi = &a[length - 1]; + wchar[2] tmp; + wchar* lo = a.ptr; + wchar* hi = &a[length - 1]; - while (lo < hi) - { auto clo = *lo; - auto chi = *hi; + while (lo < hi) + { auto clo = *lo; + auto chi = *hi; - if ((clo < 0xD800 || clo > 0xDFFF) && - (chi < 0xD800 || chi > 0xDFFF)) - { - *lo = chi; - *hi = clo; - lo++; - hi--; - continue; - } + if ((clo < 0xD800 || clo > 0xDFFF) && + (chi < 0xD800 || chi > 0xDFFF)) + { + *lo = chi; + *hi = clo; + lo++; + hi--; + continue; + } - int stridelo = 1 + (clo >= 0xD800 && clo <= 0xDBFF); + int stridelo = 1 + (clo >= 0xD800 && clo <= 0xDBFF); - int stridehi = 1; - if (chi >= 0xDC00 && chi <= 0xDFFF) - { - chi = *--hi; - stridehi++; - assert(hi >= lo); - } - if (lo == hi) - break; + int stridehi = 1; + if (chi >= 0xDC00 && chi <= 0xDFFF) + { + chi = *--hi; + stridehi++; + assert(hi >= lo); + } + if (lo == hi) + break; - if (stridelo == stridehi) - { int stmp; + if (stridelo == stridehi) + { int stmp; - assert(stridelo == 2); - assert(stmp.sizeof == 2 * (*lo).sizeof); - stmp = *cast(int*)lo; - *cast(int*)lo = *cast(int*)hi; - *cast(int*)hi = stmp; - lo += stridelo; - hi--; - continue; - } + assert(stridelo == 2); + assert(stmp.sizeof == 2 * (*lo).sizeof); + stmp = *cast(int*)lo; + *cast(int*)lo = *cast(int*)hi; + *cast(int*)hi = stmp; + lo += stridelo; + hi--; + continue; + } - /* Shift the whole array. This is woefully inefficient - */ - memcpy(tmp.ptr, hi, stridehi * wchar.sizeof); - memcpy(hi + stridehi - stridelo, lo, stridelo * wchar.sizeof); - memmove(lo + stridehi, lo + stridelo , (hi - (lo + stridelo)) * wchar.sizeof); - memcpy(lo, tmp.ptr, stridehi * wchar.sizeof); + /* Shift the whole array. This is woefully inefficient + */ + memcpy(tmp.ptr, hi, stridehi * wchar.sizeof); + memcpy(hi + stridehi - stridelo, lo, stridelo * wchar.sizeof); + memmove(lo + stridehi, lo + stridelo , (hi - (lo + stridelo)) * wchar.sizeof); + memcpy(lo, tmp.ptr, stridehi * wchar.sizeof); - lo += stridehi; - hi = hi - 1 + (stridehi - stridelo); - } + lo += stridehi; + hi = hi - 1 + (stridehi - stridelo); + } } return *cast(long*)(&a); } @@ -232,46 +232,46 @@ unittest extern (C) long _adReverse(Array a, size_t szelem) out (result) { - assert(result is *cast(long*)(&a)); + assert(result is *cast(long*)(&a)); } body { - if (a.length >= 2) - { - byte* tmp; - byte[16] buffer; + if (a.length >= 2) + { + byte* tmp; + byte[16] buffer; - void* lo = a.ptr; - void* hi = a.ptr + (a.length - 1) * szelem; + void* lo = a.ptr; + void* hi = a.ptr + (a.length - 1) * szelem; - tmp = buffer.ptr; - if (szelem > 16) - { - //version (Win32) - tmp = cast(byte*) alloca(szelem); - //else - //tmp = new byte[szelem]; - } + tmp = buffer.ptr; + if (szelem > 16) + { + //version (Win32) + tmp = cast(byte*) alloca(szelem); + //else + //tmp = new byte[szelem]; + } - for (; lo < hi; lo += szelem, hi -= szelem) - { - memcpy(tmp, lo, szelem); - memcpy(lo, hi, szelem); - memcpy(hi, tmp, szelem); - } + for (; lo < hi; lo += szelem, hi -= szelem) + { + memcpy(tmp, lo, szelem); + memcpy(lo, hi, szelem); + memcpy(hi, tmp, szelem); + } - version (Win32) - { - } - else - { - //if (szelem > 16) - // BUG: bad code is generate for delete pointer, tries - // to call delclass. - //delete tmp; - } - } - return *cast(long*)(&a); + version (Win32) + { + } + else + { + //if (szelem > 16) + // BUG: bad code is generate for delete pointer, tries + // to call delclass. + //delete tmp; + } + } + return *cast(long*)(&a); } unittest @@ -283,31 +283,31 @@ unittest size_t i; for (i = 0; i < 5; i++) - a[i] = i; + a[i] = i; b = a.reverse; assert(b is a); for (i = 0; i < 5; i++) - assert(a[i] == 4 - i); + assert(a[i] == 4 - i); struct X20 - { // More than 16 bytes in size - int a; - int b, c, d, e; + { // More than 16 bytes in size + int a; + int b, c, d, e; } X20[] c = new X20[5]; X20[] d; for (i = 0; i < 5; i++) - { c[i].a = i; - c[i].e = 10; + { c[i].a = i; + c[i].e = 10; } d = c.reverse; assert(d is c); for (i = 0; i < 5; i++) { - assert(c[i].a == 4 - i); - assert(c[i].e == 10); + assert(c[i].a == 4 - i); + assert(c[i].e == 10); } } @@ -320,25 +320,25 @@ version (none) extern (C) bit[] _adReverseBit(bit[] a) out (result) { - assert(result is a); + assert(result is a); } body { - if (a.length >= 2) - { - bit t; - int lo, hi; + if (a.length >= 2) + { + bit t; + int lo, hi; - lo = 0; - hi = a.length - 1; - for (; lo < hi; lo++, hi--) - { - t = a[lo]; - a[lo] = a[hi]; - a[hi] = t; - } - } - return a; + lo = 0; + hi = a.length - 1; + for (; lo < hi; lo++, hi--) + { + t = a[lo]; + a[lo] = a[hi]; + a[hi] = t; + } + } + return a; } unittest @@ -354,7 +354,7 @@ unittest b.reverse; for (i = 0; i < 5; i++) { - assert(b[i] == data[4 - i]); + assert(b[i] == data[4 - i]); } } } @@ -367,16 +367,16 @@ extern (C) long _adSortChar(char[] a) { if (a.length > 1) { - dstring da = toUTF32(a); - da.sort; - size_t i = 0; - foreach (dchar d; da) - { char[4] buf; - string t = toUTF8(buf, d); - a[i .. i + t.length] = t[]; - i += t.length; - } - delete da; + dstring da = toUTF32(a); + da.sort; + size_t i = 0; + foreach (dchar d; da) + { char[4] buf; + string t = toUTF8(buf, d); + a[i .. i + t.length] = t[]; + i += t.length; + } + delete da; } return *cast(long*)(&a); } @@ -389,16 +389,16 @@ extern (C) long _adSortWchar(wchar[] a) { if (a.length > 1) { - dstring da = toUTF32(a); - da.sort; - size_t i = 0; - foreach (dchar d; da) - { wchar[2] buf; - wstring t = toUTF16(buf, d); - a[i .. i + t.length] = t[]; - i += t.length; - } - delete da; + dstring da = toUTF32(a); + da.sort; + size_t i = 0; + foreach (dchar d; da) + { wchar[2] buf; + wstring t = toUTF16(buf, d); + a[i .. i + t.length] = t[]; + i += t.length; + } + delete da; } return *cast(long*)(&a); } @@ -412,46 +412,46 @@ version (none) extern (C) bit[] _adSortBit(bit[] a) out (result) { - assert(result is a); + assert(result is a); } body { - if (a.length >= 2) - { - size_t lo, hi; + if (a.length >= 2) + { + size_t lo, hi; - lo = 0; - hi = a.length - 1; - while (1) - { - while (1) - { - if (lo >= hi) - goto Ldone; - if (a[lo] == true) - break; - lo++; - } + lo = 0; + hi = a.length - 1; + while (1) + { + while (1) + { + if (lo >= hi) + goto Ldone; + if (a[lo] == true) + break; + lo++; + } - while (1) - { - if (lo >= hi) - goto Ldone; - if (a[hi] == false) - break; - hi--; - } + while (1) + { + if (lo >= hi) + goto Ldone; + if (a[hi] == false) + break; + hi--; + } - a[lo] = false; - a[hi] = true; + a[lo] = false; + a[hi] = true; - lo++; - hi--; - } - Ldone: - ; - } - return a; + lo++; + hi--; + } + Ldone: + ; + } + return a; } unittest @@ -463,15 +463,15 @@ unittest /*************************************** * Support for array equality test. * Returns: - * 1 equal - * 0 not equal + * 1 equal + * 0 not equal */ extern (C) int _adEq(Array a1, Array a2, TypeInfo ti) { //printf("_adEq(a1.length = %d, a2.length = %d)\n", a1.length, a2.length); if (a1.length != a2.length) - return 0; // not equal + return 0; // not equal auto sz = ti.tsize(); auto p1 = a1.ptr; auto p2 = a2.ptr; @@ -479,29 +479,29 @@ extern (C) int _adEq(Array a1, Array a2, TypeInfo ti) /+ for (int i = 0; i < a1.length; i++) { - printf("%4x %4x\n", (cast(short*)p1)[i], (cast(short*)p2)[i]); + printf("%4x %4x\n", (cast(short*)p1)[i], (cast(short*)p2)[i]); } +/ if (sz == 1) - // We should really have a ti.isPOD() check for this - return (memcmp(p1, p2, a1.length) == 0); + // We should really have a ti.isPOD() check for this + return (memcmp(p1, p2, a1.length) == 0); for (size_t i = 0; i < a1.length; i++) { - if (!ti.equals(p1 + i * sz, p2 + i * sz)) - return 0; // not equal + if (!ti.equals(p1 + i * sz, p2 + i * sz)) + return 0; // not equal } - return 1; // equal + return 1; // equal } extern (C) int _adEq2(Array a1, Array a2, TypeInfo ti) { //printf("_adEq2(a1.length = %d, a2.length = %d)\n", a1.length, a2.length); if (a1.length != a2.length) - return 0; // not equal + return 0; // not equal if (!ti.equals(&a1, &a2)) - return 0; + return 0; return 1; } @@ -528,14 +528,14 @@ extern (C) int _adEqBit(Array a1, Array a2) { size_t i; if (a1.length != a2.length) - return 0; // not equal + return 0; // not equal auto p1 = cast(byte*)a1.ptr; auto p2 = cast(byte*)a2.ptr; auto n = a1.length / 8; for (i = 0; i < n; i++) { - if (p1[i] != p2[i]) - return 0; // not equal + if (p1[i] != p2[i]) + return 0; // not equal } ubyte mask; @@ -572,28 +572,28 @@ extern (C) int _adCmp(Array a1, Array a2, TypeInfo ti) //printf("adCmp()\n"); auto len = a1.length; if (a2.length < len) - len = a2.length; + len = a2.length; auto sz = ti.tsize(); void *p1 = a1.ptr; void *p2 = a2.ptr; if (sz == 1) - { // We should really have a ti.isPOD() check for this - auto c = memcmp(p1, p2, len); - if (c) - return c; + { // We should really have a ti.isPOD() check for this + auto c = memcmp(p1, p2, len); + if (c) + return c; } else { - for (size_t i = 0; i < len; i++) - { - auto c = ti.compare(p1 + i * sz, p2 + i * sz); - if (c) - return c; - } + for (size_t i = 0; i < len; i++) + { + auto c = ti.compare(p1 + i * sz, p2 + i * sz); + if (c) + return c; + } } if (a1.length == a2.length) - return 0; + return 0; return (a1.length > a2.length) ? 1 : -1; } @@ -629,108 +629,108 @@ extern (C) int _adCmpChar(Array a1, Array a2) version (X86) { asm - { naked ; + { naked ; - push EDI ; - push ESI ; + push EDI ; + push ESI ; - mov ESI,a1+4[4+ESP] ; - mov EDI,a2+4[4+ESP] ; + mov ESI,a1+4[4+ESP] ; + mov EDI,a2+4[4+ESP] ; - mov ECX,a1[4+ESP] ; - mov EDX,a2[4+ESP] ; + mov ECX,a1[4+ESP] ; + mov EDX,a2[4+ESP] ; - cmp ECX,EDX ; - jb GotLength ; + cmp ECX,EDX ; + jb GotLength ; - mov ECX,EDX ; + mov ECX,EDX ; GotLength: - cmp ECX,4 ; - jb DoBytes ; + cmp ECX,4 ; + jb DoBytes ; // Do alignment if neither is dword aligned - test ESI,3 ; - jz Aligned ; + test ESI,3 ; + jz Aligned ; - test EDI,3 ; - jz Aligned ; + test EDI,3 ; + jz Aligned ; DoAlign: - mov AL,[ESI] ; //align ESI to dword bounds - mov DL,[EDI] ; + mov AL,[ESI] ; //align ESI to dword bounds + mov DL,[EDI] ; - cmp AL,DL ; - jnz Unequal ; + cmp AL,DL ; + jnz Unequal ; - inc ESI ; - inc EDI ; + inc ESI ; + inc EDI ; - test ESI,3 ; + test ESI,3 ; - lea ECX,[ECX-1] ; - jnz DoAlign ; + lea ECX,[ECX-1] ; + jnz DoAlign ; Aligned: - mov EAX,ECX ; + mov EAX,ECX ; - // do multiple of 4 bytes at a time + // do multiple of 4 bytes at a time - shr ECX,2 ; - jz TryOdd ; + shr ECX,2 ; + jz TryOdd ; - repe ; - cmpsd ; + repe ; + cmpsd ; - jnz UnequalQuad ; + jnz UnequalQuad ; TryOdd: - mov ECX,EAX ; + mov ECX,EAX ; DoBytes: - // if still equal and not end of string, do up to 3 bytes slightly - // slower. + // if still equal and not end of string, do up to 3 bytes slightly + // slower. - and ECX,3 ; - jz Equal ; + and ECX,3 ; + jz Equal ; - repe ; - cmpsb ; + repe ; + cmpsb ; - jnz Unequal ; + jnz Unequal ; Equal: - mov EAX,a1[4+ESP] ; - mov EDX,a2[4+ESP] ; + mov EAX,a1[4+ESP] ; + mov EDX,a2[4+ESP] ; - sub EAX,EDX ; - pop ESI ; + sub EAX,EDX ; + pop ESI ; - pop EDI ; - ret ; + pop EDI ; + ret ; UnequalQuad: - mov EDX,[EDI-4] ; - mov EAX,[ESI-4] ; + mov EDX,[EDI-4] ; + mov EAX,[ESI-4] ; - cmp AL,DL ; - jnz Unequal ; + cmp AL,DL ; + jnz Unequal ; - cmp AH,DH ; - jnz Unequal ; + cmp AH,DH ; + jnz Unequal ; - shr EAX,16 ; + shr EAX,16 ; - shr EDX,16 ; + shr EDX,16 ; - cmp AL,DL ; - jnz Unequal ; + cmp AL,DL ; + jnz Unequal ; - cmp AH,DH ; + cmp AH,DH ; Unequal: - sbb EAX,EAX ; - pop ESI ; + sbb EAX,EAX ; + pop ESI ; - or EAX,1 ; - pop EDI ; + or EAX,1 ; + pop EDI ; - ret ; + ret ; } } else @@ -741,10 +741,10 @@ else //printf("adCmpChar()\n"); len = a1.length; if (a2.length < len) - len = a2.length; + len = a2.length; c = string.memcmp(cast(char *)a1.ptr, cast(char *)a2.ptr, len); if (!c) - c = cast(int)a1.length - cast(int)a2.length; + c = cast(int)a1.length - cast(int)a2.length; return c; } } @@ -779,22 +779,22 @@ extern (C) int _adCmpBit(Array a1, Array a2) len = a1.length; if (a2.length < len) - len = a2.length; + len = a2.length; ubyte *p1 = cast(ubyte*)a1.ptr; ubyte *p2 = cast(ubyte*)a2.ptr; uint n = len / 8; for (i = 0; i < n; i++) { - if (p1[i] != p2[i]) - break; // not equal + if (p1[i] != p2[i]) + break; // not equal } for (uint j = i * 8; j < len; j++) - { ubyte mask = cast(ubyte)(1 << j); - int c; + { ubyte mask = cast(ubyte)(1 << j); + int c; - c = cast(int)(p1[i] & mask) - cast(int)(p2[i] & mask); - if (c) - return c; + c = cast(int)(p1[i] & mask) - cast(int)(p2[i] & mask); + if (c) + return c; } return cast(int)a1.length - cast(int)a2.length; } diff --git a/internal/arraybyte.d b/internal/arraybyte.d index e939d9c4b..1d7dfd558 100644 --- a/internal/arraybyte.d +++ b/internal/arraybyte.d @@ -47,7 +47,7 @@ extern (C): /*********************** * Computes: - * a[] = b[] + value + * a[] = b[] + value */ T[] _arraySliceExpAddSliceAssign_a(T[] a, T value, T[] b) @@ -75,163 +75,163 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 1088% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 1088% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - uint l = cast(ubyte) value; - l |= (l << 8); - l |= (l << 16); + uint l = cast(ubyte) value; + l |= (l << 8); + l |= (l << 16); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startaddsse2u: - add ESI, 64; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - movdqu XMM2, [EAX+32]; - movdqu XMM3, [EAX+48]; - add EAX, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM4; - paddb XMM2, XMM4; - paddb XMM3, XMM4; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddsse2u; + align 8; + startaddsse2u: + add ESI, 64; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + movdqu XMM2, [EAX+32]; + movdqu XMM3, [EAX+48]; + add EAX, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM4; + paddb XMM2, XMM4; + paddb XMM3, XMM4; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startaddsse2a: - add ESI, 64; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - movdqa XMM2, [EAX+32]; - movdqa XMM3, [EAX+48]; - add EAX, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM4; - paddb XMM2, XMM4; - paddb XMM3, XMM4; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddsse2a; + align 8; + startaddsse2a: + add ESI, 64; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + movdqa XMM2, [EAX+32]; + movdqa XMM3, [EAX+48]; + add EAX, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM4; + paddb XMM2, XMM4; + paddb XMM3, XMM4; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 1000% faster - if (mmx() && a.length >= 32) - { - auto n = aptr + (a.length & ~31); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 1000% faster + if (mmx() && a.length >= 32) + { + auto n = aptr + (a.length & ~31); - uint l = cast(ubyte) value; - l |= (l << 8); + uint l = cast(ubyte) value; + l |= (l << 8); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM4, l; - pshufw MM4, MM4, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM4, l; + pshufw MM4, MM4, 0; - align 4; - startaddmmx: - add ESI, 32; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - movq MM2, [EAX+16]; - movq MM3, [EAX+24]; - add EAX, 32; - paddb MM0, MM4; - paddb MM1, MM4; - paddb MM2, MM4; - paddb MM3, MM4; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startaddmmx; + align 4; + startaddmmx: + add ESI, 32; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + movq MM2, [EAX+16]; + movq MM3, [EAX+24]; + add EAX, 32; + paddb MM0, MM4; + paddb MM1, MM4; + paddb MM2, MM4; + paddb MM3, MM4; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startaddmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } - /* trying to be fair and treat normal 32-bit cpu the same way as we do - * the SIMD units, with unrolled asm. There's not enough registers, - * really. - */ - else - if (a.length >= 4) - { - - auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov CL, value; + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } + /* trying to be fair and treat normal 32-bit cpu the same way as we do + * the SIMD units, with unrolled asm. There's not enough registers, + * really. + */ + else + if (a.length >= 4) + { - align 4; - startadd386: - add ESI, 4; - mov DX, [EAX]; - mov BX, [EAX+2]; - add EAX, 4; - add BL, CL; - add BH, CL; - add DL, CL; - add DH, CL; - mov [ESI -4], DX; - mov [ESI+2 -4], BX; - cmp ESI, EDI; - jb startadd386; + auto n = aptr + (a.length & ~3); + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov CL, value; - mov aptr, ESI; - mov bptr, EAX; - } - - } + align 4; + startadd386: + add ESI, 4; + mov DX, [EAX]; + mov BX, [EAX+2]; + add EAX, 4; + add BL, CL; + add BH, CL; + add DL, CL; + add DH, CL; + mov [ESI -4], DX; + mov [ESI+2 -4], BX; + cmp ESI, EDI; + jb startadd386; + + mov aptr, ESI; + mov bptr, EAX; + } + + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ + value); + *aptr++ = cast(T)(*bptr++ + value); return a; } @@ -242,35 +242,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + 6; + c[] = a[] + 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + 6)) - { - printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + 6)) + { + printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -279,7 +279,7 @@ unittest /*********************** * Computes: - * a[] = b[] + c[] + * a[] = b[] + c[] */ T[] _arraySliceSliceAddSliceAssign_a(T[] a, T[] c, T[] b) @@ -295,10 +295,10 @@ T[] _arraySliceSliceAddSliceAssign_h(T[] a, T[] c, T[] b) T[] _arraySliceSliceAddSliceAssign_g(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -310,139 +310,139 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 5739% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 5739% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - version (log) printf("\tsse2 unaligned\n"); - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + version (log) printf("\tsse2 unaligned\n"); + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 8; - startaddlsse2u: - add ESI, 64; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - movdqu XMM2, [EAX+32]; - movdqu XMM3, [EAX+48]; - add EAX, 64; - movdqu XMM4, [ECX]; - movdqu XMM5, [ECX+16]; - movdqu XMM6, [ECX+32]; - movdqu XMM7, [ECX+48]; - add ECX, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM5; - paddb XMM2, XMM6; - paddb XMM3, XMM7; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddlsse2u; + align 8; + startaddlsse2u: + add ESI, 64; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + movdqu XMM2, [EAX+32]; + movdqu XMM3, [EAX+48]; + add EAX, 64; + movdqu XMM4, [ECX]; + movdqu XMM5, [ECX+16]; + movdqu XMM6, [ECX+32]; + movdqu XMM7, [ECX+48]; + add ECX, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM5; + paddb XMM2, XMM6; + paddb XMM3, XMM7; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddlsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - version (log) printf("\tsse2 aligned\n"); - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + version (log) printf("\tsse2 aligned\n"); + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 8; - startaddlsse2a: - add ESI, 64; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - movdqa XMM2, [EAX+32]; - movdqa XMM3, [EAX+48]; - add EAX, 64; - movdqa XMM4, [ECX]; - movdqa XMM5, [ECX+16]; - movdqa XMM6, [ECX+32]; - movdqa XMM7, [ECX+48]; - add ECX, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM5; - paddb XMM2, XMM6; - paddb XMM3, XMM7; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddlsse2a; + align 8; + startaddlsse2a: + add ESI, 64; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + movdqa XMM2, [EAX+32]; + movdqa XMM3, [EAX+48]; + add EAX, 64; + movdqa XMM4, [ECX]; + movdqa XMM5, [ECX+16]; + movdqa XMM6, [ECX+32]; + movdqa XMM7, [ECX+48]; + add ECX, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM5; + paddb XMM2, XMM6; + paddb XMM3, XMM7; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddlsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 4428% faster - if (mmx() && a.length >= 32) - { - version (log) printf("\tmmx\n"); - auto n = aptr + (a.length & ~31); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 4428% faster + if (mmx() && a.length >= 32) + { + version (log) printf("\tmmx\n"); + auto n = aptr + (a.length & ~31); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startaddlmmx: - add ESI, 32; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - movq MM2, [EAX+16]; - movq MM3, [EAX+24]; - add EAX, 32; - movq MM4, [ECX]; - movq MM5, [ECX+8]; - movq MM6, [ECX+16]; - movq MM7, [ECX+24]; - add ECX, 32; - paddb MM0, MM4; - paddb MM1, MM5; - paddb MM2, MM6; - paddb MM3, MM7; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startaddlmmx; + align 4; + startaddlmmx: + add ESI, 32; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + movq MM2, [EAX+16]; + movq MM3, [EAX+24]; + add EAX, 32; + movq MM4, [ECX]; + movq MM5, [ECX+8]; + movq MM6, [ECX+16]; + movq MM7, [ECX+24]; + add ECX, 32; + paddb MM0, MM4; + paddb MM1, MM5; + paddb MM2, MM6; + paddb MM3, MM7; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startaddlmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } version (log) if (aptr < aend) printf("\tbase\n"); while (aptr < aend) - *aptr++ = cast(T)(*bptr++ + *cptr++); + *aptr++ = cast(T)(*bptr++ + *cptr++); return a; } @@ -453,35 +453,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + b[]; + c[] = a[] + b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -490,7 +490,7 @@ unittest /*********************** * Computes: - * a[] += value + * a[] += value */ T[] _arrayExpSliceAddass_a(T[] a, T value) @@ -511,119 +511,119 @@ T[] _arrayExpSliceAddass_g(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 1578% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 1578% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - uint l = cast(ubyte) value; - l |= (l << 8); - l |= (l << 16); + uint l = cast(ubyte) value; + l |= (l << 8); + l |= (l << 16); - if (((cast(uint) aptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startaddasssse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - movdqu XMM2, [ESI+32]; - movdqu XMM3, [ESI+48]; - add ESI, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM4; - paddb XMM2, XMM4; - paddb XMM3, XMM4; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddasssse2u; + align 8; + startaddasssse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + movdqu XMM2, [ESI+32]; + movdqu XMM3, [ESI+48]; + add ESI, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM4; + paddb XMM2, XMM4; + paddb XMM3, XMM4; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddasssse2u; - mov aptr, ESI; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + mov aptr, ESI; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startaddasssse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - movdqa XMM2, [ESI+32]; - movdqa XMM3, [ESI+48]; - add ESI, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM4; - paddb XMM2, XMM4; - paddb XMM3, XMM4; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddasssse2a; + align 8; + startaddasssse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + movdqa XMM2, [ESI+32]; + movdqa XMM3, [ESI+48]; + add ESI, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM4; + paddb XMM2, XMM4; + paddb XMM3, XMM4; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddasssse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 1721% faster - if (mmx() && a.length >= 32) - { + mov aptr, ESI; + } + } + } + else + // MMX version is 1721% faster + if (mmx() && a.length >= 32) + { - auto n = aptr + (a.length & ~31); + auto n = aptr + (a.length & ~31); - uint l = cast(ubyte) value; - l |= (l << 8); + uint l = cast(ubyte) value; + l |= (l << 8); - asm - { - mov ESI, aptr; - mov EDI, n; - movd MM4, l; - pshufw MM4, MM4, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + movd MM4, l; + pshufw MM4, MM4, 0; - align 8; - startaddassmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - movq MM2, [ESI+16]; - movq MM3, [ESI+24]; - add ESI, 32; - paddb MM0, MM4; - paddb MM1, MM4; - paddb MM2, MM4; - paddb MM3, MM4; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startaddassmmx; + align 8; + startaddassmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + movq MM2, [ESI+16]; + movq MM3, [ESI+24]; + add ESI, 32; + paddb MM0, MM4; + paddb MM1, MM4; + paddb MM2, MM4; + paddb MM3, MM4; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startaddassmmx; - emms; - mov aptr, ESI; - } - } + emms; + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ += value; + *aptr++ += value; return a; } @@ -634,36 +634,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] += 6; + a[] = c[]; + c[] += 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + 6)) - { - printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + 6)) + { + printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -672,7 +672,7 @@ unittest /*********************** * Computes: - * a[] += b[] + * a[] += b[] */ T[] _arraySliceSliceAddass_a(T[] a, T[] b) @@ -700,127 +700,127 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 4727% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 4727% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 8; - startaddasslsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - movdqu XMM2, [ESI+32]; - movdqu XMM3, [ESI+48]; - add ESI, 64; - movdqu XMM4, [ECX]; - movdqu XMM5, [ECX+16]; - movdqu XMM6, [ECX+32]; - movdqu XMM7, [ECX+48]; - add ECX, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM5; - paddb XMM2, XMM6; - paddb XMM3, XMM7; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddasslsse2u; + align 8; + startaddasslsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + movdqu XMM2, [ESI+32]; + movdqu XMM3, [ESI+48]; + add ESI, 64; + movdqu XMM4, [ECX]; + movdqu XMM5, [ECX+16]; + movdqu XMM6, [ECX+32]; + movdqu XMM7, [ECX+48]; + add ECX, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM5; + paddb XMM2, XMM6; + paddb XMM3, XMM7; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddasslsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 8; - startaddasslsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - movdqa XMM2, [ESI+32]; - movdqa XMM3, [ESI+48]; - add ESI, 64; - movdqa XMM4, [ECX]; - movdqa XMM5, [ECX+16]; - movdqa XMM6, [ECX+32]; - movdqa XMM7, [ECX+48]; - add ECX, 64; - paddb XMM0, XMM4; - paddb XMM1, XMM5; - paddb XMM2, XMM6; - paddb XMM3, XMM7; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startaddasslsse2a; + align 8; + startaddasslsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + movdqa XMM2, [ESI+32]; + movdqa XMM3, [ESI+48]; + add ESI, 64; + movdqa XMM4, [ECX]; + movdqa XMM5, [ECX+16]; + movdqa XMM6, [ECX+32]; + movdqa XMM7, [ECX+48]; + add ECX, 64; + paddb XMM0, XMM4; + paddb XMM1, XMM5; + paddb XMM2, XMM6; + paddb XMM3, XMM7; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startaddasslsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 3059% faster - if (mmx() && a.length >= 32) - { + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 3059% faster + if (mmx() && a.length >= 32) + { - auto n = aptr + (a.length & ~31); + auto n = aptr + (a.length & ~31); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 8; - startaddasslmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - movq MM2, [ESI+16]; - movq MM3, [ESI+24]; - add ESI, 32; - movq MM4, [ECX]; - movq MM5, [ECX+8]; - movq MM6, [ECX+16]; - movq MM7, [ECX+24]; - add ECX, 32; - paddb MM0, MM4; - paddb MM1, MM5; - paddb MM2, MM6; - paddb MM3, MM7; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startaddasslmmx; + align 8; + startaddasslmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + movq MM2, [ESI+16]; + movq MM3, [ESI+24]; + add ESI, 32; + movq MM4, [ECX]; + movq MM5, [ECX+8]; + movq MM6, [ECX+16]; + movq MM7, [ECX+24]; + add ECX, 32; + paddb MM0, MM4; + paddb MM1, MM5; + paddb MM2, MM6; + paddb MM3, MM7; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startaddasslmmx; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ += *bptr++; + *aptr++ += *bptr++; return a; } @@ -831,36 +831,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] += b[]; + a[] = c[]; + c[] += b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -870,7 +870,7 @@ unittest /*********************** * Computes: - * a[] = b[] - value + * a[] = b[] - value */ T[] _arraySliceExpMinSliceAssign_a(T[] a, T value, T[] b) @@ -898,158 +898,158 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 1189% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 1189% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - uint l = cast(ubyte) value; - l |= (l << 8); - l |= (l << 16); + uint l = cast(ubyte) value; + l |= (l << 8); + l |= (l << 16); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startsubsse2u: - add ESI, 64; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - movdqu XMM2, [EAX+32]; - movdqu XMM3, [EAX+48]; - add EAX, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM4; - psubb XMM2, XMM4; - psubb XMM3, XMM4; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsubsse2u; + align 8; + startsubsse2u: + add ESI, 64; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + movdqu XMM2, [EAX+32]; + movdqu XMM3, [EAX+48]; + add EAX, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM4; + psubb XMM2, XMM4; + psubb XMM3, XMM4; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsubsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startsubsse2a: - add ESI, 64; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - movdqa XMM2, [EAX+32]; - movdqa XMM3, [EAX+48]; - add EAX, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM4; - psubb XMM2, XMM4; - psubb XMM3, XMM4; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsubsse2a; + align 8; + startsubsse2a: + add ESI, 64; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + movdqa XMM2, [EAX+32]; + movdqa XMM3, [EAX+48]; + add EAX, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM4; + psubb XMM2, XMM4; + psubb XMM3, XMM4; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsubsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 1079% faster - if (mmx() && a.length >= 32) - { - auto n = aptr + (a.length & ~31); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 1079% faster + if (mmx() && a.length >= 32) + { + auto n = aptr + (a.length & ~31); - uint l = cast(ubyte) value; - l |= (l << 8); + uint l = cast(ubyte) value; + l |= (l << 8); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM4, l; - pshufw MM4, MM4, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM4, l; + pshufw MM4, MM4, 0; - align 4; - startsubmmx: - add ESI, 32; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - movq MM2, [EAX+16]; - movq MM3, [EAX+24]; - add EAX, 32; - psubb MM0, MM4; - psubb MM1, MM4; - psubb MM2, MM4; - psubb MM3, MM4; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startsubmmx; + align 4; + startsubmmx: + add ESI, 32; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + movq MM2, [EAX+16]; + movq MM3, [EAX+24]; + add EAX, 32; + psubb MM0, MM4; + psubb MM1, MM4; + psubb MM2, MM4; + psubb MM3, MM4; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startsubmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } - // trying to be fair and treat normal 32-bit cpu the same way as we do the SIMD units, with unrolled asm. There's not enough registers, really. - else - if (a.length >= 4) - { - auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov CL, value; + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } + // trying to be fair and treat normal 32-bit cpu the same way as we do the SIMD units, with unrolled asm. There's not enough registers, really. + else + if (a.length >= 4) + { + auto n = aptr + (a.length & ~3); + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov CL, value; - align 4; - startsub386: - add ESI, 4; - mov DX, [EAX]; - mov BX, [EAX+2]; - add EAX, 4; - sub BL, CL; - sub BH, CL; - sub DL, CL; - sub DH, CL; - mov [ESI -4], DX; - mov [ESI+2 -4], BX; - cmp ESI, EDI; - jb startsub386; + align 4; + startsub386: + add ESI, 4; + mov DX, [EAX]; + mov BX, [EAX+2]; + add EAX, 4; + sub BL, CL; + sub BH, CL; + sub DL, CL; + sub DH, CL; + mov [ESI -4], DX; + mov [ESI+2 -4], BX; + cmp ESI, EDI; + jb startsub386; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ - value); + *aptr++ = cast(T)(*bptr++ - value); return a; } @@ -1060,36 +1060,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] = b[] - 6; + a[] = c[]; + c[] = b[] - 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(b[i] - 6)) - { - printf("[%d]: %d != %d - 6\n", i, c[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(b[i] - 6)) + { + printf("[%d]: %d != %d - 6\n", i, c[i], b[i]); + assert(0); + } + } + } } } @@ -1098,7 +1098,7 @@ unittest /*********************** * Computes: - * a[] = value - b[] + * a[] = value - b[] */ T[] _arrayExpSliceMinSliceAssign_a(T[] a, T[] b, T value) @@ -1126,140 +1126,140 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 8748% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 8748% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - uint l = cast(ubyte) value; - l |= (l << 8); - l |= (l << 16); + uint l = cast(ubyte) value; + l |= (l << 8); + l |= (l << 16); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startsubrsse2u: - add ESI, 64; - movdqa XMM5, XMM4; - movdqa XMM6, XMM4; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - psubb XMM5, XMM0; - psubb XMM6, XMM1; - movdqu [ESI -64], XMM5; - movdqu [ESI+16-64], XMM6; - movdqa XMM5, XMM4; - movdqa XMM6, XMM4; - movdqu XMM2, [EAX+32]; - movdqu XMM3, [EAX+48]; - add EAX, 64; - psubb XMM5, XMM2; - psubb XMM6, XMM3; - movdqu [ESI+32-64], XMM5; - movdqu [ESI+48-64], XMM6; - cmp ESI, EDI; - jb startsubrsse2u; + align 8; + startsubrsse2u: + add ESI, 64; + movdqa XMM5, XMM4; + movdqa XMM6, XMM4; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + psubb XMM5, XMM0; + psubb XMM6, XMM1; + movdqu [ESI -64], XMM5; + movdqu [ESI+16-64], XMM6; + movdqa XMM5, XMM4; + movdqa XMM6, XMM4; + movdqu XMM2, [EAX+32]; + movdqu XMM3, [EAX+48]; + add EAX, 64; + psubb XMM5, XMM2; + psubb XMM6, XMM3; + movdqu [ESI+32-64], XMM5; + movdqu [ESI+48-64], XMM6; + cmp ESI, EDI; + jb startsubrsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startsubrsse2a: - add ESI, 64; - movdqa XMM5, XMM4; - movdqa XMM6, XMM4; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - psubb XMM5, XMM0; - psubb XMM6, XMM1; - movdqa [ESI -64], XMM5; - movdqa [ESI+16-64], XMM6; - movdqa XMM5, XMM4; - movdqa XMM6, XMM4; - movdqa XMM2, [EAX+32]; - movdqa XMM3, [EAX+48]; - add EAX, 64; - psubb XMM5, XMM2; - psubb XMM6, XMM3; - movdqa [ESI+32-64], XMM5; - movdqa [ESI+48-64], XMM6; - cmp ESI, EDI; - jb startsubrsse2a; + align 8; + startsubrsse2a: + add ESI, 64; + movdqa XMM5, XMM4; + movdqa XMM6, XMM4; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + psubb XMM5, XMM0; + psubb XMM6, XMM1; + movdqa [ESI -64], XMM5; + movdqa [ESI+16-64], XMM6; + movdqa XMM5, XMM4; + movdqa XMM6, XMM4; + movdqa XMM2, [EAX+32]; + movdqa XMM3, [EAX+48]; + add EAX, 64; + psubb XMM5, XMM2; + psubb XMM6, XMM3; + movdqa [ESI+32-64], XMM5; + movdqa [ESI+48-64], XMM6; + cmp ESI, EDI; + jb startsubrsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 7397% faster - if (mmx() && a.length >= 32) - { - auto n = aptr + (a.length & ~31); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 7397% faster + if (mmx() && a.length >= 32) + { + auto n = aptr + (a.length & ~31); - uint l = cast(ubyte) value; - l |= (l << 8); + uint l = cast(ubyte) value; + l |= (l << 8); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM4, l; - pshufw MM4, MM4, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM4, l; + pshufw MM4, MM4, 0; - align 4; - startsubrmmx: - add ESI, 32; - movq MM5, MM4; - movq MM6, MM4; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - psubb MM5, MM0; - psubb MM6, MM1; - movq [ESI -32], MM5; - movq [ESI+8 -32], MM6; - movq MM5, MM4; - movq MM6, MM4; - movq MM2, [EAX+16]; - movq MM3, [EAX+24]; - add EAX, 32; - psubb MM5, MM2; - psubb MM6, MM3; - movq [ESI+16-32], MM5; - movq [ESI+24-32], MM6; - cmp ESI, EDI; - jb startsubrmmx; + align 4; + startsubrmmx: + add ESI, 32; + movq MM5, MM4; + movq MM6, MM4; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + psubb MM5, MM0; + psubb MM6, MM1; + movq [ESI -32], MM5; + movq [ESI+8 -32], MM6; + movq MM5, MM4; + movq MM6, MM4; + movq MM2, [EAX+16]; + movq MM3, [EAX+24]; + add EAX, 32; + psubb MM5, MM2; + psubb MM6, MM3; + movq [ESI+16-32], MM5; + movq [ESI+24-32], MM6; + cmp ESI, EDI; + jb startsubrmmx; + + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } - } while (aptr < aend) - *aptr++ = cast(T)(value - *bptr++); + *aptr++ = cast(T)(value - *bptr++); return a; } @@ -1270,36 +1270,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] = 6 - b[]; + a[] = c[]; + c[] = 6 - b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(6 - b[i])) - { - printf("[%d]: %d != 6 - %d\n", i, c[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(6 - b[i])) + { + printf("[%d]: %d != 6 - %d\n", i, c[i], b[i]); + assert(0); + } + } + } } } @@ -1308,7 +1308,7 @@ unittest /*********************** * Computes: - * a[] = b[] - c[] + * a[] = b[] - c[] */ T[] _arraySliceSliceMinSliceAssign_a(T[] a, T[] c, T[] b) @@ -1324,10 +1324,10 @@ T[] _arraySliceSliceMinSliceAssign_h(T[] a, T[] c, T[] b) T[] _arraySliceSliceMinSliceAssign_g(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -1338,135 +1338,135 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 5756% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 5756% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 8; - startsublsse2u: - add ESI, 64; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - movdqu XMM2, [EAX+32]; - movdqu XMM3, [EAX+48]; - add EAX, 64; - movdqu XMM4, [ECX]; - movdqu XMM5, [ECX+16]; - movdqu XMM6, [ECX+32]; - movdqu XMM7, [ECX+48]; - add ECX, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM5; - psubb XMM2, XMM6; - psubb XMM3, XMM7; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsublsse2u; + align 8; + startsublsse2u: + add ESI, 64; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + movdqu XMM2, [EAX+32]; + movdqu XMM3, [EAX+48]; + add EAX, 64; + movdqu XMM4, [ECX]; + movdqu XMM5, [ECX+16]; + movdqu XMM6, [ECX+32]; + movdqu XMM7, [ECX+48]; + add ECX, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM5; + psubb XMM2, XMM6; + psubb XMM3, XMM7; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsublsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 8; - startsublsse2a: - add ESI, 64; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - movdqa XMM2, [EAX+32]; - movdqa XMM3, [EAX+48]; - add EAX, 64; - movdqa XMM4, [ECX]; - movdqa XMM5, [ECX+16]; - movdqa XMM6, [ECX+32]; - movdqa XMM7, [ECX+48]; - add ECX, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM5; - psubb XMM2, XMM6; - psubb XMM3, XMM7; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsublsse2a; + align 8; + startsublsse2a: + add ESI, 64; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + movdqa XMM2, [EAX+32]; + movdqa XMM3, [EAX+48]; + add EAX, 64; + movdqa XMM4, [ECX]; + movdqa XMM5, [ECX+16]; + movdqa XMM6, [ECX+32]; + movdqa XMM7, [ECX+48]; + add ECX, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM5; + psubb XMM2, XMM6; + psubb XMM3, XMM7; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsublsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 4428% faster - if (mmx() && a.length >= 32) - { - auto n = aptr + (a.length & ~31); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 4428% faster + if (mmx() && a.length >= 32) + { + auto n = aptr + (a.length & ~31); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 8; - startsublmmx: - add ESI, 32; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - movq MM2, [EAX+16]; - movq MM3, [EAX+24]; - add EAX, 32; - movq MM4, [ECX]; - movq MM5, [ECX+8]; - movq MM6, [ECX+16]; - movq MM7, [ECX+24]; - add ECX, 32; - psubb MM0, MM4; - psubb MM1, MM5; - psubb MM2, MM6; - psubb MM3, MM7; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startsublmmx; + align 8; + startsublmmx: + add ESI, 32; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + movq MM2, [EAX+16]; + movq MM3, [EAX+24]; + add EAX, 32; + movq MM4, [ECX]; + movq MM5, [ECX+8]; + movq MM6, [ECX+16]; + movq MM7, [ECX+24]; + add ECX, 32; + psubb MM0, MM4; + psubb MM1, MM5; + psubb MM2, MM6; + psubb MM3, MM7; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startsublmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ - *cptr++); + *aptr++ = cast(T)(*bptr++ - *cptr++); return a; } @@ -1477,35 +1477,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - b[]; + c[] = a[] - b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - b[i])) - { - printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - b[i])) + { + printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -1514,7 +1514,7 @@ unittest /*********************** * Computes: - * a[] -= value + * a[] -= value */ T[] _arrayExpSliceMinass_a(T[] a, T value) @@ -1535,119 +1535,119 @@ T[] _arrayExpSliceMinass_g(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 1577% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 1577% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - uint l = cast(ubyte) value; - l |= (l << 8); - l |= (l << 16); + uint l = cast(ubyte) value; + l |= (l << 8); + l |= (l << 16); - if (((cast(uint) aptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startsubasssse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - movdqu XMM2, [ESI+32]; - movdqu XMM3, [ESI+48]; - add ESI, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM4; - psubb XMM2, XMM4; - psubb XMM3, XMM4; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsubasssse2u; + align 8; + startsubasssse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + movdqu XMM2, [ESI+32]; + movdqu XMM3, [ESI+48]; + add ESI, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM4; + psubb XMM2, XMM4; + psubb XMM3, XMM4; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsubasssse2u; - mov aptr, ESI; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + mov aptr, ESI; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 8; - startsubasssse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - movdqa XMM2, [ESI+32]; - movdqa XMM3, [ESI+48]; - add ESI, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM4; - psubb XMM2, XMM4; - psubb XMM3, XMM4; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsubasssse2a; + align 8; + startsubasssse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + movdqa XMM2, [ESI+32]; + movdqa XMM3, [ESI+48]; + add ESI, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM4; + psubb XMM2, XMM4; + psubb XMM3, XMM4; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsubasssse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 1577% faster - if (mmx() && a.length >= 32) - { + mov aptr, ESI; + } + } + } + else + // MMX version is 1577% faster + if (mmx() && a.length >= 32) + { - auto n = aptr + (a.length & ~31); + auto n = aptr + (a.length & ~31); - uint l = cast(ubyte) value; - l |= (l << 8); + uint l = cast(ubyte) value; + l |= (l << 8); - asm - { - mov ESI, aptr; - mov EDI, n; - movd MM4, l; - pshufw MM4, MM4, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + movd MM4, l; + pshufw MM4, MM4, 0; - align 8; - startsubassmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - movq MM2, [ESI+16]; - movq MM3, [ESI+24]; - add ESI, 32; - psubb MM0, MM4; - psubb MM1, MM4; - psubb MM2, MM4; - psubb MM3, MM4; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startsubassmmx; + align 8; + startsubassmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + movq MM2, [ESI+16]; + movq MM3, [ESI+24]; + add ESI, 32; + psubb MM0, MM4; + psubb MM1, MM4; + psubb MM2, MM4; + psubb MM3, MM4; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startsubassmmx; - emms; - mov aptr, ESI; - } - } + emms; + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ -= value; + *aptr++ -= value; return a; } @@ -1658,36 +1658,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] -= 6; + a[] = c[]; + c[] -= 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - 6)) - { - printf("[%d]: %d != %d - 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - 6)) + { + printf("[%d]: %d != %d - 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1696,7 +1696,7 @@ unittest /*********************** * Computes: - * a[] -= b[] + * a[] -= b[] */ T[] _arraySliceSliceMinass_a(T[] a, T[] b) @@ -1724,127 +1724,127 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 4800% faster - if (sse2() && a.length >= 64) - { - auto n = aptr + (a.length & ~63); + // SSE2 aligned version is 4800% faster + if (sse2() && a.length >= 64) + { + auto n = aptr + (a.length & ~63); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 8; - startsubasslsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - movdqu XMM2, [ESI+32]; - movdqu XMM3, [ESI+48]; - add ESI, 64; - movdqu XMM4, [ECX]; - movdqu XMM5, [ECX+16]; - movdqu XMM6, [ECX+32]; - movdqu XMM7, [ECX+48]; - add ECX, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM5; - psubb XMM2, XMM6; - psubb XMM3, XMM7; - movdqu [ESI -64], XMM0; - movdqu [ESI+16-64], XMM1; - movdqu [ESI+32-64], XMM2; - movdqu [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsubasslsse2u; + align 8; + startsubasslsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + movdqu XMM2, [ESI+32]; + movdqu XMM3, [ESI+48]; + add ESI, 64; + movdqu XMM4, [ECX]; + movdqu XMM5, [ECX+16]; + movdqu XMM6, [ECX+32]; + movdqu XMM7, [ECX+48]; + add ECX, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM5; + psubb XMM2, XMM6; + psubb XMM3, XMM7; + movdqu [ESI -64], XMM0; + movdqu [ESI+16-64], XMM1; + movdqu [ESI+32-64], XMM2; + movdqu [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsubasslsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 8; - startsubasslsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - movdqa XMM2, [ESI+32]; - movdqa XMM3, [ESI+48]; - add ESI, 64; - movdqa XMM4, [ECX]; - movdqa XMM5, [ECX+16]; - movdqa XMM6, [ECX+32]; - movdqa XMM7, [ECX+48]; - add ECX, 64; - psubb XMM0, XMM4; - psubb XMM1, XMM5; - psubb XMM2, XMM6; - psubb XMM3, XMM7; - movdqa [ESI -64], XMM0; - movdqa [ESI+16-64], XMM1; - movdqa [ESI+32-64], XMM2; - movdqa [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsubasslsse2a; + align 8; + startsubasslsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + movdqa XMM2, [ESI+32]; + movdqa XMM3, [ESI+48]; + add ESI, 64; + movdqa XMM4, [ECX]; + movdqa XMM5, [ECX+16]; + movdqa XMM6, [ECX+32]; + movdqa XMM7, [ECX+48]; + add ECX, 64; + psubb XMM0, XMM4; + psubb XMM1, XMM5; + psubb XMM2, XMM6; + psubb XMM3, XMM7; + movdqa [ESI -64], XMM0; + movdqa [ESI+16-64], XMM1; + movdqa [ESI+32-64], XMM2; + movdqa [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsubasslsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 3107% faster - if (mmx() && a.length >= 32) - { + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 3107% faster + if (mmx() && a.length >= 32) + { - auto n = aptr + (a.length & ~31); + auto n = aptr + (a.length & ~31); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 8; - startsubasslmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - movq MM2, [ESI+16]; - movq MM3, [ESI+24]; - add ESI, 32; - movq MM4, [ECX]; - movq MM5, [ECX+8]; - movq MM6, [ECX+16]; - movq MM7, [ECX+24]; - add ECX, 32; - psubb MM0, MM4; - psubb MM1, MM5; - psubb MM2, MM6; - psubb MM3, MM7; - movq [ESI -32], MM0; - movq [ESI+8 -32], MM1; - movq [ESI+16-32], MM2; - movq [ESI+24-32], MM3; - cmp ESI, EDI; - jb startsubasslmmx; + align 8; + startsubasslmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + movq MM2, [ESI+16]; + movq MM3, [ESI+24]; + add ESI, 32; + movq MM4, [ECX]; + movq MM5, [ECX+8]; + movq MM6, [ECX+16]; + movq MM7, [ECX+24]; + add ECX, 32; + psubb MM0, MM4; + psubb MM1, MM5; + psubb MM2, MM6; + psubb MM3, MM7; + movq [ESI -32], MM0; + movq [ESI+8 -32], MM1; + movq [ESI+16-32], MM2; + movq [ESI+24-32], MM3; + cmp ESI, EDI; + jb startsubasslmmx; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ -= *bptr++; + *aptr++ -= *bptr++; return a; } @@ -1855,36 +1855,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] -= b[]; + a[] = c[]; + c[] -= b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - b[i])) - { - printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - b[i])) + { + printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } diff --git a/internal/arraycast.d b/internal/arraycast.d index a3c463d1d..98b33c0e3 100644 --- a/internal/arraycast.d +++ b/internal/arraycast.d @@ -39,10 +39,10 @@ void[] _d_arraycast(size_t tsize, size_t fsize, void[] a) auto nbytes = length * fsize; if (nbytes % tsize != 0) { - throw new Error("array cast misalignment"); + throw new Error("array cast misalignment"); } length = nbytes / tsize; - *cast(size_t *)&a = length; // jam new length + *cast(size_t *)&a = length; // jam new length return a; } @@ -79,10 +79,10 @@ void[] _d_arraycast_frombit(uint tsize, void[] a) if (length & 7) { - throw new Error("bit[] array cast misalignment"); + throw new Error("bit[] array cast misalignment"); } length /= 8 * tsize; - *cast(size_t *)&a = length; // jam new length + *cast(size_t *)&a = length; // jam new length return a; } diff --git a/internal/arraycat.d b/internal/arraycat.d index 61345df91..dd127c014 100644 --- a/internal/arraycat.d +++ b/internal/arraycat.d @@ -21,20 +21,20 @@ void[] _d_arraycopy(uint size, void[] from, void[] to) if (to.length != from.length) { - //throw new Error(std.string.format("lengths don't match for array copy, %s = %s", to.length, from.length)); - throw new Error(cast(string) ("lengths don't match for array copy," ~ + //throw new Error(std.string.format("lengths don't match for array copy, %s = %s", to.length, from.length)); + throw new Error(cast(string) ("lengths don't match for array copy," ~ toString(to.length) ~ " = " ~ toString(from.length))); } else if (to.ptr + to.length * size <= from.ptr || - from.ptr + from.length * size <= to.ptr) + from.ptr + from.length * size <= to.ptr) { - memcpy(to.ptr, from.ptr, to.length * size); + memcpy(to.ptr, from.ptr, to.length * size); } else { - throw new Error("overlapping array copy"); - //memmove(to.ptr, from.ptr, to.length * size); + throw new Error("overlapping array copy"); + //memmove(to.ptr, from.ptr, to.length * size); } return to; } diff --git a/internal/arraydouble.d b/internal/arraydouble.d index 8087571f3..79b46af0e 100644 --- a/internal/arraydouble.d +++ b/internal/arraydouble.d @@ -46,16 +46,16 @@ extern (C): /*********************** * Computes: - * a[] = b[] + c[] + * a[] = b[] + c[] */ T[] _arraySliceSliceAddSliceAssign_d(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -66,53 +66,53 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 333% faster - if (sse2() && b.length >= 16) - { - auto n = aptr + (b.length & ~15); + // SSE2 version is 333% faster + if (sse2() && b.length >= 16) + { + auto n = aptr + (b.length & ~15); - // Unaligned case - asm - { - mov EAX, bptr; // left operand - mov ECX, cptr; // right operand - mov ESI, aptr; // destination operand - mov EDI, n; // end comparison + // Unaligned case + asm + { + mov EAX, bptr; // left operand + mov ECX, cptr; // right operand + mov ESI, aptr; // destination operand + mov EDI, n; // end comparison - align 8; - startsseloopb: - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - movupd XMM4, [ECX]; - movupd XMM5, [ECX+16]; - movupd XMM6, [ECX+32]; - movupd XMM7, [ECX+48]; - add ESI, 64; - addpd XMM0, XMM4; - addpd XMM1, XMM5; - addpd XMM2, XMM6; - addpd XMM3, XMM7; - add ECX, 64; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopb; + align 8; + startsseloopb: + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + movupd XMM4, [ECX]; + movupd XMM5, [ECX+16]; + movupd XMM6, [ECX+32]; + movupd XMM7, [ECX+48]; + add ESI, 64; + addpd XMM0, XMM4; + addpd XMM1, XMM5; + addpd XMM2, XMM6; + addpd XMM3, XMM7; + add ECX, 64; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopb; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } // Handle remainder while (aptr < aend) - *aptr++ = *bptr++ + *cptr++; + *aptr++ = *bptr++ + *cptr++; return a; } @@ -123,35 +123,35 @@ unittest printf("_arraySliceSliceAddSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + b[]; + c[] = a[] + b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %g != %g + %g\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %g != %g + %g\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -159,16 +159,16 @@ unittest /*********************** * Computes: - * a[] = b[] - c[] + * a[] = b[] - c[] */ T[] _arraySliceSliceMinSliceAssign_d(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -179,53 +179,53 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 324% faster - if (sse2() && b.length >= 8) - { - auto n = aptr + (b.length & ~7); + // SSE2 version is 324% faster + if (sse2() && b.length >= 8) + { + auto n = aptr + (b.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; // left operand - mov ECX, cptr; // right operand - mov ESI, aptr; // destination operand - mov EDI, n; // end comparison + // Unaligned case + asm + { + mov EAX, bptr; // left operand + mov ECX, cptr; // right operand + mov ESI, aptr; // destination operand + mov EDI, n; // end comparison - align 8; - startsseloopb: - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - movupd XMM4, [ECX]; - movupd XMM5, [ECX+16]; - movupd XMM6, [ECX+32]; - movupd XMM7, [ECX+48]; - add ESI, 64; - subpd XMM0, XMM4; - subpd XMM1, XMM5; - subpd XMM2, XMM6; - subpd XMM3, XMM7; - add ECX, 64; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopb; + align 8; + startsseloopb: + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + movupd XMM4, [ECX]; + movupd XMM5, [ECX+16]; + movupd XMM6, [ECX+32]; + movupd XMM7, [ECX+48]; + add ESI, 64; + subpd XMM0, XMM4; + subpd XMM1, XMM5; + subpd XMM2, XMM6; + subpd XMM3, XMM7; + add ECX, 64; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopb; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } // Handle remainder while (aptr < aend) - *aptr++ = *bptr++ - *cptr++; + *aptr++ = *bptr++ - *cptr++; return a; } @@ -236,35 +236,35 @@ unittest printf("_arraySliceSliceMinSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - b[]; + c[] = a[] - b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - b[i])) - { - printf("[%d]: %g != %g - %g\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - b[i])) + { + printf("[%d]: %g != %g - %g\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -273,7 +273,7 @@ unittest /*********************** * Computes: - * a[] = b[] + value + * a[] = b[] + value */ T[] _arraySliceExpAddSliceAssign_d(T[] a, T value, T[] b) @@ -291,47 +291,47 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 305% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 305% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov EAX, bptr; + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloop: - add ESI, 64; - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - addpd XMM0, XMM4; - addpd XMM1, XMM4; - addpd XMM2, XMM4; - addpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloop; + align 8; + startsseloop: + add ESI, 64; + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + addpd XMM0, XMM4; + addpd XMM1, XMM4; + addpd XMM2, XMM4; + addpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloop; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ + value; + *aptr++ = *bptr++ + value; return a; } @@ -341,35 +341,35 @@ unittest printf("_arraySliceExpAddSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + 6; + c[] = a[] + 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + 6)) - { - printf("[%d]: %g != %g + 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + 6)) + { + printf("[%d]: %g != %g + 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -377,7 +377,7 @@ unittest /*********************** * Computes: - * a[] += value + * a[] += value */ T[] _arrayExpSliceAddass_d(T[] a, T value) @@ -388,45 +388,45 @@ T[] _arrayExpSliceAddass_d(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 version is 114% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); - if (aptr < n) + // SSE2 version is 114% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); + if (aptr < n) - // Unaligned case - asm - { - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloopa: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - addpd XMM0, XMM4; - addpd XMM1, XMM4; - addpd XMM2, XMM4; - addpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopa; + align 8; + startsseloopa: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + addpd XMM0, XMM4; + addpd XMM1, XMM4; + addpd XMM2, XMM4; + addpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopa; - mov aptr, ESI; - } - } + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ += value; + *aptr++ += value; return a; } @@ -436,36 +436,36 @@ unittest printf("_arrayExpSliceAddass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] += 6; + a[] = c[]; + c[] += 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + 6)) - { - printf("[%d]: %g != %g + 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + 6)) + { + printf("[%d]: %g != %g + 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -473,7 +473,7 @@ unittest /*********************** * Computes: - * a[] += b[] + * a[] += b[] */ T[] _arraySliceSliceAddass_d(T[] a, T[] b) @@ -491,49 +491,49 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 183% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 183% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov ECX, bptr; // right operand - mov ESI, aptr; // destination operand - mov EDI, n; // end comparison + // Unaligned case + asm + { + mov ECX, bptr; // right operand + mov ESI, aptr; // destination operand + mov EDI, n; // end comparison - align 8; - startsseloopb: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - movupd XMM4, [ECX]; - movupd XMM5, [ECX+16]; - movupd XMM6, [ECX+32]; - movupd XMM7, [ECX+48]; - add ECX, 64; - addpd XMM0, XMM4; - addpd XMM1, XMM5; - addpd XMM2, XMM6; - addpd XMM3, XMM7; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopb; + align 8; + startsseloopb: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + movupd XMM4, [ECX]; + movupd XMM5, [ECX+16]; + movupd XMM6, [ECX+32]; + movupd XMM7, [ECX+48]; + add ECX, 64; + addpd XMM0, XMM4; + addpd XMM1, XMM5; + addpd XMM2, XMM6; + addpd XMM3, XMM7; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopb; - mov aptr, ESI; - mov bptr, ECX; - } - } + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ += *bptr++; + *aptr++ += *bptr++; return a; } @@ -543,36 +543,36 @@ unittest printf("_arraySliceSliceAddass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] += b[]; + a[] = c[]; + c[] += b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %g != %g + %g\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %g != %g + %g\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -580,7 +580,7 @@ unittest /*********************** * Computes: - * a[] = b[] - value + * a[] = b[] - value */ T[] _arraySliceExpMinSliceAssign_d(T[] a, T value, T[] b) @@ -598,47 +598,47 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 305% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 305% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov EAX, bptr; + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloop: - add ESI, 64; - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - subpd XMM0, XMM4; - subpd XMM1, XMM4; - subpd XMM2, XMM4; - subpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloop; + align 8; + startsseloop: + add ESI, 64; + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + subpd XMM0, XMM4; + subpd XMM1, XMM4; + subpd XMM2, XMM4; + subpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloop; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ - value; + *aptr++ = *bptr++ - value; return a; } @@ -648,35 +648,35 @@ unittest printf("_arraySliceExpMinSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - 6; + c[] = a[] - 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - 6)) - { - printf("[%d]: %g != %g - 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - 6)) + { + printf("[%d]: %g != %g - 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -684,7 +684,7 @@ unittest /*********************** * Computes: - * a[] = value - b[] + * a[] = value - b[] */ T[] _arrayExpSliceMinSliceAssign_d(T[] a, T[] b, T value) @@ -702,51 +702,51 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 66% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 66% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov EAX, bptr; + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloop: - add ESI, 64; - movapd XMM5, XMM4; - movapd XMM6, XMM4; - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - subpd XMM5, XMM0; - subpd XMM6, XMM1; - movupd [ESI+ 0-64], XMM5; - movupd [ESI+16-64], XMM6; - movapd XMM5, XMM4; - movapd XMM6, XMM4; - subpd XMM5, XMM2; - subpd XMM6, XMM3; - movupd [ESI+32-64], XMM5; - movupd [ESI+48-64], XMM6; - cmp ESI, EDI; - jb startsseloop; + align 8; + startsseloop: + add ESI, 64; + movapd XMM5, XMM4; + movapd XMM6, XMM4; + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + subpd XMM5, XMM0; + subpd XMM6, XMM1; + movupd [ESI+ 0-64], XMM5; + movupd [ESI+16-64], XMM6; + movapd XMM5, XMM4; + movapd XMM6, XMM4; + subpd XMM5, XMM2; + subpd XMM6, XMM3; + movupd [ESI+32-64], XMM5; + movupd [ESI+48-64], XMM6; + cmp ESI, EDI; + jb startsseloop; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = value - *bptr++; + *aptr++ = value - *bptr++; return a; } @@ -756,35 +756,35 @@ unittest printf("_arrayExpSliceMinSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = 6 - a[]; + c[] = 6 - a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(6 - a[i])) - { - printf("[%d]: %g != 6 - %g\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(6 - a[i])) + { + printf("[%d]: %g != 6 - %g\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -792,7 +792,7 @@ unittest /*********************** * Computes: - * a[] -= value + * a[] -= value */ T[] _arrayExpSliceMinass_d(T[] a, T value) @@ -803,45 +803,45 @@ T[] _arrayExpSliceMinass_d(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 version is 115% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); - if (aptr < n) + // SSE2 version is 115% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); + if (aptr < n) - // Unaligned case - asm - { - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloopa: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - subpd XMM0, XMM4; - subpd XMM1, XMM4; - subpd XMM2, XMM4; - subpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopa; + align 8; + startsseloopa: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + subpd XMM0, XMM4; + subpd XMM1, XMM4; + subpd XMM2, XMM4; + subpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopa; - mov aptr, ESI; - } - } + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ -= value; + *aptr++ -= value; return a; } @@ -851,36 +851,36 @@ unittest printf("_arrayExpSliceMinass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] -= 6; + a[] = c[]; + c[] -= 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - 6)) - { - printf("[%d]: %g != %g - 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - 6)) + { + printf("[%d]: %g != %g - 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -888,7 +888,7 @@ unittest /*********************** * Computes: - * a[] -= b[] + * a[] -= b[] */ T[] _arraySliceSliceMinass_d(T[] a, T[] b) @@ -906,49 +906,49 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 183% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 183% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov ECX, bptr; // right operand - mov ESI, aptr; // destination operand - mov EDI, n; // end comparison + // Unaligned case + asm + { + mov ECX, bptr; // right operand + mov ESI, aptr; // destination operand + mov EDI, n; // end comparison - align 8; - startsseloopb: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - movupd XMM4, [ECX]; - movupd XMM5, [ECX+16]; - movupd XMM6, [ECX+32]; - movupd XMM7, [ECX+48]; - add ECX, 64; - subpd XMM0, XMM4; - subpd XMM1, XMM5; - subpd XMM2, XMM6; - subpd XMM3, XMM7; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopb; + align 8; + startsseloopb: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + movupd XMM4, [ECX]; + movupd XMM5, [ECX+16]; + movupd XMM6, [ECX+32]; + movupd XMM7, [ECX+48]; + add ECX, 64; + subpd XMM0, XMM4; + subpd XMM1, XMM5; + subpd XMM2, XMM6; + subpd XMM3, XMM7; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopb; - mov aptr, ESI; - mov bptr, ECX; - } - } + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ -= *bptr++; + *aptr++ -= *bptr++; return a; } @@ -958,36 +958,36 @@ unittest printf("_arrayExpSliceMinass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] -= 6; + a[] = c[]; + c[] -= 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - 6)) - { - printf("[%d]: %g != %g - 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - 6)) + { + printf("[%d]: %g != %g - 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -995,7 +995,7 @@ unittest /*********************** * Computes: - * a[] = b[] * value + * a[] = b[] * value */ T[] _arraySliceExpMulSliceAssign_d(T[] a, T value, T[] b) @@ -1013,47 +1013,47 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 304% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 304% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov EAX, bptr; + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloop: - add ESI, 64; - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - mulpd XMM0, XMM4; - mulpd XMM1, XMM4; - mulpd XMM2, XMM4; - mulpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloop; + align 8; + startsseloop: + add ESI, 64; + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + mulpd XMM0, XMM4; + mulpd XMM1, XMM4; + mulpd XMM2, XMM4; + mulpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloop; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ * value; + *aptr++ = *bptr++ * value; return a; } @@ -1063,35 +1063,35 @@ unittest printf("_arraySliceExpMulSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] * 6; + c[] = a[] * 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * 6)) - { - printf("[%d]: %g != %g * 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * 6)) + { + printf("[%d]: %g != %g * 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1099,16 +1099,16 @@ unittest /*********************** * Computes: - * a[] = b[] * c[] + * a[] = b[] * c[] */ T[] _arraySliceSliceMulSliceAssign_d(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -1120,52 +1120,52 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 329% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 329% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; // left operand - mov ECX, cptr; // right operand - mov ESI, aptr; // destination operand - mov EDI, n; // end comparison + // Unaligned case + asm + { + mov EAX, bptr; // left operand + mov ECX, cptr; // right operand + mov ESI, aptr; // destination operand + mov EDI, n; // end comparison - align 8; - startsseloopb: - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add ESI, 64; - movupd XMM4, [ECX]; - movupd XMM5, [ECX+16]; - movupd XMM6, [ECX+32]; - movupd XMM7, [ECX+48]; - add EAX, 64; - mulpd XMM0, XMM4; - mulpd XMM1, XMM5; - mulpd XMM2, XMM6; - mulpd XMM3, XMM7; - add ECX, 64; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopb; + align 8; + startsseloopb: + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add ESI, 64; + movupd XMM4, [ECX]; + movupd XMM5, [ECX+16]; + movupd XMM6, [ECX+32]; + movupd XMM7, [ECX+48]; + add EAX, 64; + mulpd XMM0, XMM4; + mulpd XMM1, XMM5; + mulpd XMM2, XMM6; + mulpd XMM3, XMM7; + add ECX, 64; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopb; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ * *cptr++; + *aptr++ = *bptr++ * *cptr++; return a; } @@ -1175,35 +1175,35 @@ unittest printf("_arraySliceSliceMulSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] * b[]; + c[] = a[] * b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * b[i])) - { - printf("[%d]: %g != %g * %g\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * b[i])) + { + printf("[%d]: %g != %g * %g\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -1211,7 +1211,7 @@ unittest /*********************** * Computes: - * a[] *= value + * a[] *= value */ T[] _arrayExpSliceMulass_d(T[] a, T value) @@ -1222,45 +1222,45 @@ T[] _arrayExpSliceMulass_d(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 version is 109% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); - if (aptr < n) + // SSE2 version is 109% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); + if (aptr < n) - // Unaligned case - asm - { - mov ESI, aptr; - mov EDI, n; - movsd XMM4, value; - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov ESI, aptr; + mov EDI, n; + movsd XMM4, value; + shufpd XMM4, XMM4, 0; - align 8; - startsseloopa: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - mulpd XMM0, XMM4; - mulpd XMM1, XMM4; - mulpd XMM2, XMM4; - mulpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopa; + align 8; + startsseloopa: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + mulpd XMM0, XMM4; + mulpd XMM1, XMM4; + mulpd XMM2, XMM4; + mulpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopa; - mov aptr, ESI; - } - } + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ *= value; + *aptr++ *= value; return a; } @@ -1270,36 +1270,36 @@ unittest printf("_arrayExpSliceMulass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] *= 6; + a[] = c[]; + c[] *= 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * 6)) - { - printf("[%d]: %g != %g * 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * 6)) + { + printf("[%d]: %g != %g * 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1307,7 +1307,7 @@ unittest /*********************** * Computes: - * a[] *= b[] + * a[] *= b[] */ T[] _arraySliceSliceMulass_d(T[] a, T[] b) @@ -1325,49 +1325,49 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 205% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 205% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov ECX, bptr; // right operand - mov ESI, aptr; // destination operand - mov EDI, n; // end comparison + // Unaligned case + asm + { + mov ECX, bptr; // right operand + mov ESI, aptr; // destination operand + mov EDI, n; // end comparison - align 8; - startsseloopb: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - movupd XMM4, [ECX]; - movupd XMM5, [ECX+16]; - movupd XMM6, [ECX+32]; - movupd XMM7, [ECX+48]; - add ECX, 64; - mulpd XMM0, XMM4; - mulpd XMM1, XMM5; - mulpd XMM2, XMM6; - mulpd XMM3, XMM7; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopb; + align 8; + startsseloopb: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + movupd XMM4, [ECX]; + movupd XMM5, [ECX+16]; + movupd XMM6, [ECX+32]; + movupd XMM7, [ECX+48]; + add ECX, 64; + mulpd XMM0, XMM4; + mulpd XMM1, XMM5; + mulpd XMM2, XMM6; + mulpd XMM3, XMM7; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopb; - mov aptr, ESI; - mov bptr, ECX; - } - } + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ *= *bptr++; + *aptr++ *= *bptr++; return a; } @@ -1377,36 +1377,36 @@ unittest printf("_arrayExpSliceMulass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] *= 6; + a[] = c[]; + c[] *= 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * 6)) - { - printf("[%d]: %g != %g * 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * 6)) + { + printf("[%d]: %g != %g * 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1414,7 +1414,7 @@ unittest /*********************** * Computes: - * a[] = b[] / value + * a[] = b[] / value */ T[] _arraySliceExpDivSliceAssign_d(T[] a, T value, T[] b) @@ -1437,55 +1437,55 @@ body version (D_InlineAsm_X86) { - // SSE2 version is 299% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 299% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov EAX, bptr; - mov ESI, aptr; - mov EDI, n; - movsd XMM4, recip; - //movsd XMM4, value - //rcpsd XMM4, XMM4 - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov EAX, bptr; + mov ESI, aptr; + mov EDI, n; + movsd XMM4, recip; + //movsd XMM4, value + //rcpsd XMM4, XMM4 + shufpd XMM4, XMM4, 0; - align 8; - startsseloop: - add ESI, 64; - movupd XMM0, [EAX]; - movupd XMM1, [EAX+16]; - movupd XMM2, [EAX+32]; - movupd XMM3, [EAX+48]; - add EAX, 64; - mulpd XMM0, XMM4; - mulpd XMM1, XMM4; - mulpd XMM2, XMM4; - mulpd XMM3, XMM4; - //divpd XMM0, XMM4; - //divpd XMM1, XMM4; - //divpd XMM2, XMM4; - //divpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloop; + align 8; + startsseloop: + add ESI, 64; + movupd XMM0, [EAX]; + movupd XMM1, [EAX+16]; + movupd XMM2, [EAX+32]; + movupd XMM3, [EAX+48]; + add EAX, 64; + mulpd XMM0, XMM4; + mulpd XMM1, XMM4; + mulpd XMM2, XMM4; + mulpd XMM3, XMM4; + //divpd XMM0, XMM4; + //divpd XMM1, XMM4; + //divpd XMM2, XMM4; + //divpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloop; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) { - *aptr++ = *bptr++ / value; - //*aptr++ = *bptr++ * recip; + *aptr++ = *bptr++ / value; + //*aptr++ = *bptr++ * recip; } return a; @@ -1496,36 +1496,36 @@ unittest printf("_arraySliceExpDivSliceAssign_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] / 8; + c[] = a[] / 8; - for (int i = 0; i < dim; i++) - { - //printf("[%d]: %g ?= %g / 8\n", i, c[i], a[i]); - if (c[i] != cast(T)(a[i] / 8)) - { - printf("[%d]: %g != %g / 8\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + //printf("[%d]: %g ?= %g / 8\n", i, c[i], a[i]); + if (c[i] != cast(T)(a[i] / 8)) + { + printf("[%d]: %g != %g / 8\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1533,7 +1533,7 @@ unittest /*********************** * Computes: - * a[] /= value + * a[] /= value */ T[] _arrayExpSliceDivass_d(T[] a, T value) @@ -1549,50 +1549,50 @@ T[] _arrayExpSliceDivass_d(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 version is 65% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 version is 65% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - // Unaligned case - asm - { - mov ESI, aptr; - mov EDI, n; - movsd XMM4, recip; - //movsd XMM4, value - //rcpsd XMM4, XMM4 - shufpd XMM4, XMM4, 0; + // Unaligned case + asm + { + mov ESI, aptr; + mov EDI, n; + movsd XMM4, recip; + //movsd XMM4, value + //rcpsd XMM4, XMM4 + shufpd XMM4, XMM4, 0; - align 8; - startsseloopa: - movupd XMM0, [ESI]; - movupd XMM1, [ESI+16]; - movupd XMM2, [ESI+32]; - movupd XMM3, [ESI+48]; - add ESI, 64; - mulpd XMM0, XMM4; - mulpd XMM1, XMM4; - mulpd XMM2, XMM4; - mulpd XMM3, XMM4; - //divpd XMM0, XMM4; - //divpd XMM1, XMM4; - //divpd XMM2, XMM4; - //divpd XMM3, XMM4; - movupd [ESI+ 0-64], XMM0; - movupd [ESI+16-64], XMM1; - movupd [ESI+32-64], XMM2; - movupd [ESI+48-64], XMM3; - cmp ESI, EDI; - jb startsseloopa; + align 8; + startsseloopa: + movupd XMM0, [ESI]; + movupd XMM1, [ESI+16]; + movupd XMM2, [ESI+32]; + movupd XMM3, [ESI+48]; + add ESI, 64; + mulpd XMM0, XMM4; + mulpd XMM1, XMM4; + mulpd XMM2, XMM4; + mulpd XMM3, XMM4; + //divpd XMM0, XMM4; + //divpd XMM1, XMM4; + //divpd XMM2, XMM4; + //divpd XMM3, XMM4; + movupd [ESI+ 0-64], XMM0; + movupd [ESI+16-64], XMM1; + movupd [ESI+32-64], XMM2; + movupd [ESI+48-64], XMM3; + cmp ESI, EDI; + jb startsseloopa; - mov aptr, ESI; - } - } + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ *= recip; + *aptr++ *= recip; return a; } @@ -1603,36 +1603,36 @@ unittest printf("_arrayExpSliceDivass_d unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - c[] /= 8; + a[] = c[]; + c[] /= 8; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] / 8)) - { - printf("[%d]: %g != %g / 8\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] / 8)) + { + printf("[%d]: %g != %g / 8\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1641,7 +1641,7 @@ unittest /*********************** * Computes: - * a[] -= b[] * value + * a[] -= b[] * value */ T[] _arraySliceExpMulSliceMinass_d(T[] a, T value, T[] b) @@ -1651,14 +1651,14 @@ T[] _arraySliceExpMulSliceMinass_d(T[] a, T value, T[] b) /*********************** * Computes: - * a[] += b[] * value + * a[] += b[] * value */ T[] _arraySliceExpMulSliceAddass_d(T[] a, T value, T[] b) in { - assert(a.length == b.length); - assert(disjoint(a, b)); + assert(a.length == b.length); + assert(disjoint(a, b)); } body { @@ -1668,7 +1668,7 @@ body // Handle remainder while (aptr < aend) - *aptr++ += *bptr++ * value; + *aptr++ += *bptr++ * value; return a; } @@ -1679,37 +1679,37 @@ unittest cpuid = 1; { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 1; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 1; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = c[]; - c[] += a[] * 6; + b[] = c[]; + c[] += a[] * 6; - for (int i = 0; i < dim; i++) - { - //printf("[%d]: %g ?= %g + %g * 6\n", i, c[i], b[i], a[i]); - if (c[i] != cast(T)(b[i] + a[i] * 6)) - { - printf("[%d]: %g ?= %g + %g * 6\n", i, c[i], b[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + //printf("[%d]: %g ?= %g + %g * 6\n", i, c[i], b[i], a[i]); + if (c[i] != cast(T)(b[i] + a[i] * 6)) + { + printf("[%d]: %g ?= %g + %g * 6\n", i, c[i], b[i], a[i]); + assert(0); + } + } + } } } diff --git a/internal/arrayint.d b/internal/arrayint.d index 32eaf88fa..90742a0fa 100644 --- a/internal/arrayint.d +++ b/internal/arrayint.d @@ -46,7 +46,7 @@ extern (C): /*********************** * Computes: - * a[] = b[] + value + * a[] = b[] + value */ T[] _arraySliceExpAddSliceAssign_w(T[] a, T value, T[] b) @@ -74,134 +74,134 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 380% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 380% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 298% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 298% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movq MM2, l; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movq MM2, l; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - paddd MM0, MM2; - paddd MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + paddd MM0, MM2; + paddd MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - if (a.length >= 2) - { - auto n = aptr + (a.length & ~1); + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + if (a.length >= 2) + { + auto n = aptr + (a.length & ~1); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov EDX, value; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov EDX, value; - align 4; - start386: - add ESI, 8; - mov EBX, [EAX]; - mov ECX, [EAX+4]; - add EAX, 8; - add EBX, EDX; - add ECX, EDX; - mov [ESI -8], EBX; - mov [ESI+4-8], ECX; - cmp ESI, EDI; - jb start386; + align 4; + start386: + add ESI, 8; + mov EBX, [EAX]; + mov ECX, [EAX+4]; + add EAX, 8; + add EBX, EDX; + add ECX, EDX; + mov [ESI -8], EBX; + mov [ESI+4-8], ECX; + cmp ESI, EDI; + jb start386; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ + value; + *aptr++ = *bptr++ + value; return a; } @@ -212,35 +212,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + 6; + c[] = a[] + 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + 6)) - { - printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + 6)) + { + printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -249,7 +249,7 @@ unittest /*********************** * Computes: - * a[] = b[] + c[] + * a[] = b[] + c[] */ T[] _arraySliceSliceAddSliceAssign_w(T[] a, T[] c, T[] b) @@ -265,10 +265,10 @@ T[] _arraySliceSliceAddSliceAssign_k(T[] a, T[] c, T[] b) T[] _arraySliceSliceAddSliceAssign_i(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -280,112 +280,112 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 1710% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 1710% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM2, [ECX]; - movdqu XMM1, [EAX+16]; - movdqu XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM2, [ECX]; + movdqu XMM1, [EAX+16]; + movdqu XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM2, [ECX]; - movdqa XMM1, [EAX+16]; - movdqa XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM2, [ECX]; + movdqa XMM1, [EAX+16]; + movdqa XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 995% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 995% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM2, [ECX]; - movq MM1, [EAX+8]; - movq MM3, [ECX+8]; - add EAX, 16; - add ECX, 16; - paddd MM0, MM2; - paddd MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM2, [ECX]; + movq MM1, [EAX+8]; + movq MM3, [ECX+8]; + add EAX, 16; + add ECX, 16; + paddd MM0, MM2; + paddd MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } normal: while (aptr < aend) - *aptr++ = *bptr++ + *cptr++; + *aptr++ = *bptr++ + *cptr++; return a; } @@ -396,35 +396,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + b[]; + c[] = a[] + b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -433,7 +433,7 @@ unittest /*********************** * Computes: - * a[] += value + * a[] += value */ T[] _arrayExpSliceAddass_w(T[] a, T value) @@ -454,122 +454,122 @@ T[] _arrayExpSliceAddass_i(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 83% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 83% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 81% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + } + } + } + else + // MMX version is 81% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - movq MM2, l; + asm + { + mov ESI, aptr; + mov EDI, n; + movq MM2, l; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - paddd MM0, MM2; - paddd MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + paddd MM0, MM2; + paddd MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - } - } - else - if (a.length >= 2) - { - auto n = aptr + (a.length & ~1); + emms; + mov aptr, ESI; + } + } + else + if (a.length >= 2) + { + auto n = aptr + (a.length & ~1); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EDX, value; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EDX, value; - align 4; - start386: - mov EBX, [ESI]; - mov ECX, [ESI+4]; - add ESI, 8; - add EBX, EDX; - add ECX, EDX; - mov [ESI -8], EBX; - mov [ESI+4-8], ECX; - cmp ESI, EDI; - jb start386; + align 4; + start386: + mov EBX, [ESI]; + mov ECX, [ESI+4]; + add ESI, 8; + add EBX, EDX; + add ECX, EDX; + mov [ESI -8], EBX; + mov [ESI+4-8], ECX; + cmp ESI, EDI; + jb start386; - mov aptr, ESI; - } - } + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ += value; + *aptr++ += value; return a; } @@ -580,36 +580,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - a[] += 6; + a[] = c[]; + a[] += 6; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(c[i] + 6)) - { - printf("[%d]: %d != %d + 6\n", i, a[i], c[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(c[i] + 6)) + { + printf("[%d]: %d != %d + 6\n", i, a[i], c[i]); + assert(0); + } + } + } } } @@ -618,7 +618,7 @@ unittest /*********************** * Computes: - * a[] += b[] + * a[] += b[] */ T[] _arraySliceSliceAddass_w(T[] a, T[] b) @@ -646,103 +646,103 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 695% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 695% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM2, [ECX]; - movdqu XMM1, [ESI+16]; - movdqu XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM2, [ECX]; + movdqu XMM1, [ESI+16]; + movdqu XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM2, [ECX]; - movdqa XMM1, [ESI+16]; - movdqa XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - paddd XMM0, XMM2; - paddd XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM2, [ECX]; + movdqa XMM1, [ESI+16]; + movdqa XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + paddd XMM0, XMM2; + paddd XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 471% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 471% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM2, [ECX]; - movq MM1, [ESI+8]; - movq MM3, [ECX+8]; - add ESI, 16; - add ECX, 16; - paddd MM0, MM2; - paddd MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM2, [ECX]; + movq MM1, [ESI+8]; + movq MM3, [ECX+8]; + add ESI, 16; + add ECX, 16; + paddd MM0, MM2; + paddd MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } normal: while (aptr < aend) - *aptr++ += *bptr++; + *aptr++ += *bptr++; return a; } @@ -753,36 +753,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = c[]; - c[] += a[]; + b[] = c[]; + c[] += a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(b[i] + a[i])) - { - printf("[%d]: %d != %d + %d\n", i, c[i], b[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(b[i] + a[i])) + { + printf("[%d]: %d != %d + %d\n", i, c[i], b[i], a[i]); + assert(0); + } + } + } } } @@ -791,7 +791,7 @@ unittest /*********************** * Computes: - * a[] = b[] - value + * a[] = b[] - value */ T[] _arraySliceExpMinSliceAssign_w(T[] a, T value, T[] b) @@ -819,134 +819,134 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 400% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 400% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 315% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 315% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movq MM2, l; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movq MM2, l; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - psubd MM0, MM2; - psubd MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + psubd MM0, MM2; + psubd MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - if (a.length >= 2) - { - auto n = aptr + (a.length & ~1); + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + if (a.length >= 2) + { + auto n = aptr + (a.length & ~1); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov EDX, value; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov EDX, value; - align 4; - start386: - add ESI, 8; - mov EBX, [EAX]; - mov ECX, [EAX+4]; - add EAX, 8; - sub EBX, EDX; - sub ECX, EDX; - mov [ESI -8], EBX; - mov [ESI+4-8], ECX; - cmp ESI, EDI; - jb start386; + align 4; + start386: + add ESI, 8; + mov EBX, [EAX]; + mov ECX, [EAX+4]; + add EAX, 8; + sub EBX, EDX; + sub ECX, EDX; + mov [ESI -8], EBX; + mov [ESI+4-8], ECX; + cmp ESI, EDI; + jb start386; - mov aptr, ESI; - mov bptr, EAX; - } - } + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ - value; + *aptr++ = *bptr++ - value; return a; } @@ -957,35 +957,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - 6; + c[] = a[] - 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - 6)) - { - printf("[%d]: %d != %d - 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - 6)) + { + printf("[%d]: %d != %d - 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -994,7 +994,7 @@ unittest /*********************** * Computes: - * a[] = value - b[] + * a[] = value - b[] */ T[] _arrayExpSliceMinSliceAssign_w(T[] a, T[] b, T value) @@ -1022,111 +1022,111 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 1812% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 1812% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 4; - startaddsse2u: - add ESI, 32; - movdqu XMM2, [EAX]; - movdqu XMM3, [EAX+16]; - movdqa XMM0, XMM4; - movdqa XMM1, XMM4; - add EAX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + add ESI, 32; + movdqu XMM2, [EAX]; + movdqu XMM3, [EAX+16]; + movdqa XMM0, XMM4; + movdqa XMM1, XMM4; + add EAX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM4, l; - pshufd XMM4, XMM4, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM4, l; + pshufd XMM4, XMM4, 0; - align 4; - startaddsse2a: - add ESI, 32; - movdqa XMM2, [EAX]; - movdqa XMM3, [EAX+16]; - movdqa XMM0, XMM4; - movdqa XMM1, XMM4; - add EAX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + add ESI, 32; + movdqa XMM2, [EAX]; + movdqa XMM3, [EAX+16]; + movdqa XMM0, XMM4; + movdqa XMM1, XMM4; + add EAX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 1077% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 1077% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movq MM4, l; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movq MM4, l; - align 4; - startmmx: - add ESI, 16; - movq MM2, [EAX]; - movq MM3, [EAX+8]; - movq MM0, MM4; - movq MM1, MM4; - add EAX, 16; - psubd MM0, MM2; - psubd MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM2, [EAX]; + movq MM3, [EAX+8]; + movq MM0, MM4; + movq MM1, MM4; + add EAX, 16; + psubd MM0, MM2; + psubd MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = value - *bptr++; + *aptr++ = value - *bptr++; return a; } @@ -1137,35 +1137,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = 6 - a[]; + c[] = 6 - a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(6 - a[i])) - { - printf("[%d]: %d != 6 - %d\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(6 - a[i])) + { + printf("[%d]: %d != 6 - %d\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1174,7 +1174,7 @@ unittest /*********************** * Computes: - * a[] = b[] - c[] + * a[] = b[] - c[] */ T[] _arraySliceSliceMinSliceAssign_w(T[] a, T[] c, T[] b) @@ -1190,10 +1190,10 @@ T[] _arraySliceSliceMinSliceAssign_k(T[] a, T[] c, T[] b) T[] _arraySliceSliceMinSliceAssign_i(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -1204,111 +1204,111 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 1721% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 1721% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM2, [ECX]; - movdqu XMM1, [EAX+16]; - movdqu XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM2, [ECX]; + movdqu XMM1, [EAX+16]; + movdqu XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM2, [ECX]; - movdqa XMM1, [EAX+16]; - movdqa XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM2, [ECX]; + movdqa XMM1, [EAX+16]; + movdqa XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 1002% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 1002% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM2, [ECX]; - movq MM1, [EAX+8]; - movq MM3, [ECX+8]; - add EAX, 16; - add ECX, 16; - psubd MM0, MM2; - psubd MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM2, [ECX]; + movq MM1, [EAX+8]; + movq MM3, [ECX+8]; + add EAX, 16; + add ECX, 16; + psubd MM0, MM2; + psubd MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } while (aptr < aend) - *aptr++ = *bptr++ - *cptr++; + *aptr++ = *bptr++ - *cptr++; return a; } @@ -1319,35 +1319,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - b[]; + c[] = a[] - b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - b[i])) - { - printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - b[i])) + { + printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -1356,7 +1356,7 @@ unittest /*********************** * Computes: - * a[] -= value + * a[] -= value */ T[] _arrayExpSliceMinass_w(T[] a, T value) @@ -1377,122 +1377,122 @@ T[] _arrayExpSliceMinass_i(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 81% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 81% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 81% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + } + } + } + else + // MMX version is 81% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - movq MM2, l; + asm + { + mov ESI, aptr; + mov EDI, n; + movq MM2, l; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - psubd MM0, MM2; - psubd MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + psubd MM0, MM2; + psubd MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - } - } - else - if (a.length >= 2) - { - auto n = aptr + (a.length & ~1); + emms; + mov aptr, ESI; + } + } + else + if (a.length >= 2) + { + auto n = aptr + (a.length & ~1); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EDX, value; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EDX, value; - align 4; - start386: - mov EBX, [ESI]; - mov ECX, [ESI+4]; - add ESI, 8; - sub EBX, EDX; - sub ECX, EDX; - mov [ESI -8], EBX; - mov [ESI+4-8], ECX; - cmp ESI, EDI; - jb start386; + align 4; + start386: + mov EBX, [ESI]; + mov ECX, [ESI+4]; + add ESI, 8; + sub EBX, EDX; + sub ECX, EDX; + mov [ESI -8], EBX; + mov [ESI+4-8], ECX; + cmp ESI, EDI; + jb start386; - mov aptr, ESI; - } - } + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ -= value; + *aptr++ -= value; return a; } @@ -1503,36 +1503,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - a[] -= 6; + a[] = c[]; + a[] -= 6; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(c[i] - 6)) - { - printf("[%d]: %d != %d - 6\n", i, a[i], c[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(c[i] - 6)) + { + printf("[%d]: %d != %d - 6\n", i, a[i], c[i]); + assert(0); + } + } + } } } @@ -1541,7 +1541,7 @@ unittest /*********************** * Computes: - * a[] -= b[] + * a[] -= b[] */ T[] _arraySliceSliceMinass_w(T[] a, T[] b) @@ -1569,102 +1569,102 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 731% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 731% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM2, [ECX]; - movdqu XMM1, [ESI+16]; - movdqu XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM2, [ECX]; + movdqu XMM1, [ESI+16]; + movdqu XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM2, [ECX]; - movdqa XMM1, [ESI+16]; - movdqa XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - psubd XMM0, XMM2; - psubd XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM2, [ECX]; + movdqa XMM1, [ESI+16]; + movdqa XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + psubd XMM0, XMM2; + psubd XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 441% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 441% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM2, [ECX]; - movq MM1, [ESI+8]; - movq MM3, [ECX+8]; - add ESI, 16; - add ECX, 16; - psubd MM0, MM2; - psubd MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM2, [ECX]; + movq MM1, [ESI+8]; + movq MM3, [ECX+8]; + add ESI, 16; + add ECX, 16; + psubd MM0, MM2; + psubd MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ -= *bptr++; + *aptr++ -= *bptr++; return a; } @@ -1675,36 +1675,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = c[]; - c[] -= a[]; + b[] = c[]; + c[] -= a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(b[i] - a[i])) - { - printf("[%d]: %d != %d - %d\n", i, c[i], b[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(b[i] - a[i])) + { + printf("[%d]: %d != %d - %d\n", i, c[i], b[i], a[i]); + assert(0); + } + } + } } } @@ -1713,7 +1713,7 @@ unittest /*********************** * Computes: - * a[] = b[] * value + * a[] = b[] * value */ T[] _arraySliceExpMulSliceAssign_w(T[] a, T value, T[] b) @@ -1739,112 +1739,112 @@ body auto aend = aptr + a.length; auto bptr = b.ptr; - version (none) // multiplying a pair is not supported by MMX + version (none) // multiplying a pair is not supported by MMX { version (D_InlineAsm_X86) { - // SSE2 aligned version is 1380% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 1380% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - { - // MMX version is 1380% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + { + // MMX version is 1380% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movq MM2, l; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movq MM2, l; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - pmuludq MM0, MM2; // only multiplies low 32 bits - pmuludq MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + pmuludq MM0, MM2; // only multiplies low 32 bits + pmuludq MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } } - } + } } while (aptr < aend) - *aptr++ = *bptr++ * value; + *aptr++ = *bptr++ * value; return a; } @@ -1855,36 +1855,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] * 6; + c[] = a[] * 6; - for (int i = 0; i < dim; i++) - { - //printf("[%d]: %d ?= %d * 6\n", i, c[i], a[i]); - if (c[i] != cast(T)(a[i] * 6)) - { - printf("[%d]: %d != %d * 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + //printf("[%d]: %d ?= %d * 6\n", i, c[i], a[i]); + if (c[i] != cast(T)(a[i] * 6)) + { + printf("[%d]: %d != %d * 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1893,7 +1893,7 @@ unittest /*********************** * Computes: - * a[] = b[] * c[] + * a[] = b[] * c[] */ T[] _arraySliceSliceMulSliceAssign_w(T[] a, T[] c, T[] b) @@ -1909,10 +1909,10 @@ T[] _arraySliceSliceMulSliceAssign_k(T[] a, T[] c, T[] b) T[] _arraySliceSliceMulSliceAssign_i(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -1926,112 +1926,112 @@ body { version (D_InlineAsm_X86) { - // SSE2 aligned version is 1407% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 1407% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM2, [ECX]; - movdqu XMM1, [EAX+16]; - movdqu XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM2, [ECX]; + movdqu XMM1, [EAX+16]; + movdqu XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM2, [ECX]; - movdqa XMM1, [EAX+16]; - movdqa XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM2, [ECX]; + movdqa XMM1, [EAX+16]; + movdqa XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 1029% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 1029% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM2, [ECX]; - movq MM1, [EAX+8]; - movq MM3, [ECX+8]; - add EAX, 16; - add ECX, 16; - pmuludq MM0, MM2; - pmuludq MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM2, [ECX]; + movq MM1, [EAX+8]; + movq MM3, [ECX+8]; + add EAX, 16; + add ECX, 16; + pmuludq MM0, MM2; + pmuludq MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } } while (aptr < aend) - *aptr++ = *bptr++ * *cptr++; + *aptr++ = *bptr++ * *cptr++; return a; } @@ -2042,35 +2042,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] * b[]; + c[] = a[] * b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * b[i])) - { - printf("[%d]: %d != %d * %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * b[i])) + { + printf("[%d]: %d != %d * %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -2079,7 +2079,7 @@ unittest /*********************** * Computes: - * a[] *= value + * a[] *= value */ T[] _arrayExpSliceMulass_w(T[] a, T value) @@ -2102,97 +2102,97 @@ T[] _arrayExpSliceMulass_i(T[] a, T value) { version (D_InlineAsm_X86) { - // SSE2 aligned version is 400% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 400% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = value; + uint l = value; - if (((cast(uint) aptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 402% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + mov aptr, ESI; + } + } + } + else + // MMX version is 402% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); + ulong l = cast(uint) value | (cast(ulong)cast(uint) value << 32); - asm - { - mov ESI, aptr; - mov EDI, n; - movq MM2, l; + asm + { + mov ESI, aptr; + mov EDI, n; + movq MM2, l; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - pmuludq MM0, MM2; - pmuludq MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + pmuludq MM0, MM2; + pmuludq MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - } - } + emms; + mov aptr, ESI; + } + } } } while (aptr < aend) - *aptr++ *= value; + *aptr++ *= value; return a; } @@ -2203,36 +2203,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = a[]; - a[] *= 6; + b[] = a[]; + a[] *= 6; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(b[i] * 6)) - { - printf("[%d]: %d != %d * 6\n", i, a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(b[i] * 6)) + { + printf("[%d]: %d != %d * 6\n", i, a[i], b[i]); + assert(0); + } + } + } } } @@ -2241,7 +2241,7 @@ unittest /*********************** * Computes: - * a[] *= b[] + * a[] *= b[] */ T[] _arraySliceSliceMulass_w(T[] a, T[] b) @@ -2271,117 +2271,117 @@ body { version (D_InlineAsm_X86) { - // SSE2 aligned version is 873% faster - if (sse2() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + // SSE2 aligned version is 873% faster + if (sse2() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM2, [ECX]; - movdqu XMM1, [ESI+16]; - movdqu XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM2, [ECX]; + movdqu XMM1, [ESI+16]; + movdqu XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM2, [ECX]; - movdqa XMM1, [ESI+16]; - movdqa XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - pmuludq XMM0, XMM2; - pmuludq XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM2, [ECX]; + movdqa XMM1, [ESI+16]; + movdqa XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + pmuludq XMM0, XMM2; + pmuludq XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } + mov aptr, ESI; + mov bptr, ECX; + } + } + } /+ BUG: comment out this section until we figure out what is going wrong with the invalid pshufd instructions. - else - // MMX version is 573% faster - if (mmx() && a.length >= 4) - { - auto n = aptr + (a.length & ~3); + else + // MMX version is 573% faster + if (mmx() && a.length >= 4) + { + auto n = aptr + (a.length & ~3); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM2, [ECX]; - movq MM1, [ESI+8]; - movq MM3, [ECX+8]; - pxor MM4, MM4; - pxor MM5, MM5; - punpckldq MM4, MM0; - punpckldq MM5, MM2; - add ESI, 16; - add ECX, 16; - pmuludq MM4, MM5; - pshufd MM4, MM4, 8; // ? - movq [ESI -16], MM4; - pxor MM4, MM4; - pxor MM5, MM5; - punpckldq MM4, MM1; - punpckldq MM5, MM3; - pmuludq MM4, MM5; - pshufd MM4, MM4, 8; // ? - movq [ESI+8-16], MM4; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM2, [ECX]; + movq MM1, [ESI+8]; + movq MM3, [ECX+8]; + pxor MM4, MM4; + pxor MM5, MM5; + punpckldq MM4, MM0; + punpckldq MM5, MM2; + add ESI, 16; + add ECX, 16; + pmuludq MM4, MM5; + pshufd MM4, MM4, 8; // ? + movq [ESI -16], MM4; + pxor MM4, MM4; + pxor MM5, MM5; + punpckldq MM4, MM1; + punpckldq MM5, MM3; + pmuludq MM4, MM5; + pshufd MM4, MM4, 8; // ? + movq [ESI+8-16], MM4; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } +/ } } while (aptr < aend) - *aptr++ *= *bptr++; + *aptr++ *= *bptr++; return a; } @@ -2392,36 +2392,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = a[]; - a[] *= c[]; + b[] = a[]; + a[] *= c[]; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(b[i] * c[i])) - { - printf("[%d]: %d != %d * %d\n", i, a[i], b[i], c[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(b[i] * c[i])) + { + printf("[%d]: %d != %d * %d\n", i, a[i], b[i], c[i]); + assert(0); + } + } + } } } diff --git a/internal/arrayreal.d b/internal/arrayreal.d index 8f16e4bf2..587c00bd0 100644 --- a/internal/arrayreal.d +++ b/internal/arrayreal.d @@ -42,21 +42,21 @@ extern (C): /*********************** * Computes: - * a[] = b[] + c[] + * a[] = b[] + c[] */ T[] _arraySliceSliceAddSliceAssign_r(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { for (int i = 0; i < a.length; i++) - a[i] = b[i] + c[i]; + a[i] = b[i] + c[i]; return a; } @@ -65,35 +65,35 @@ unittest printf("_arraySliceSliceAddSliceAssign_r unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + b[]; + c[] = a[] + b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %Lg != %Lg + %Lg\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %Lg != %Lg + %Lg\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -101,21 +101,21 @@ unittest /*********************** * Computes: - * a[] = b[] - c[] + * a[] = b[] - c[] */ T[] _arraySliceSliceMinSliceAssign_r(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { for (int i = 0; i < a.length; i++) - a[i] = b[i] - c[i]; + a[i] = b[i] - c[i]; return a; } @@ -125,35 +125,35 @@ unittest printf("_arraySliceSliceMinSliceAssign_r unittest\n"); for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - b[]; + c[] = a[] - b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - b[i])) - { - printf("[%d]: %Lg != %Lg - %Lg\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - b[i])) + { + printf("[%d]: %Lg != %Lg - %Lg\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -161,7 +161,7 @@ unittest /*********************** * Computes: - * a[] -= b[] * value + * a[] -= b[] * value */ T[] _arraySliceExpMulSliceMinass_r(T[] a, T value, T[] b) @@ -171,14 +171,14 @@ T[] _arraySliceExpMulSliceMinass_r(T[] a, T value, T[] b) /*********************** * Computes: - * a[] += b[] * value + * a[] += b[] * value */ T[] _arraySliceExpMulSliceAddass_r(T[] a, T value, T[] b) in { - assert(a.length == b.length); - assert(disjoint(a, b)); + assert(a.length == b.length); + assert(disjoint(a, b)); } body { @@ -188,7 +188,7 @@ body // Handle remainder while (aptr < aend) - *aptr++ += *bptr++ * value; + *aptr++ += *bptr++ * value; return a; } @@ -199,37 +199,37 @@ unittest cpuid = 1; { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 1; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 1; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = c[]; - c[] += a[] * 6; + b[] = c[]; + c[] += a[] * 6; - for (int i = 0; i < dim; i++) - { - //printf("[%d]: %Lg ?= %Lg + %Lg * 6\n", i, c[i], b[i], a[i]); - if (c[i] != cast(T)(b[i] + a[i] * 6)) - { - printf("[%d]: %Lg ?= %Lg + %Lg * 6\n", i, c[i], b[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + //printf("[%d]: %Lg ?= %Lg + %Lg * 6\n", i, c[i], b[i], a[i]); + if (c[i] != cast(T)(b[i] + a[i] * 6)) + { + printf("[%d]: %Lg ?= %Lg + %Lg * 6\n", i, c[i], b[i], a[i]); + assert(0); + } + } + } } } diff --git a/internal/arrayshort.d b/internal/arrayshort.d index 581cf87bf..c9fb2ecce 100644 --- a/internal/arrayshort.d +++ b/internal/arrayshort.d @@ -46,7 +46,7 @@ extern (C): /*********************** * Computes: - * a[] = b[] + value + * a[] = b[] + value */ T[] _arraySliceExpAddSliceAssign_u(T[] a, T value, T[] b) @@ -74,107 +74,107 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 3343% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 3343% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= (l << 16); + uint l = cast(ushort) value; + l |= (l << 16); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 3343% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 3343% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM2, l; - pshufw MM2, MM2, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM2, l; + pshufw MM2, MM2, 0; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - paddw MM0, MM2; - paddw MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + paddw MM0, MM2; + paddw MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ + value); + *aptr++ = cast(T)(*bptr++ + value); return a; } @@ -185,35 +185,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + 6; + c[] = a[] + 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + 6)) - { - printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + 6)) + { + printf("[%d]: %d != %d + 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -222,7 +222,7 @@ unittest /*********************** * Computes: - * a[] = b[] + c[] + * a[] = b[] + c[] */ T[] _arraySliceSliceAddSliceAssign_u(T[] a, T[] c, T[] b) @@ -238,10 +238,10 @@ T[] _arraySliceSliceAddSliceAssign_t(T[] a, T[] c, T[] b) T[] _arraySliceSliceAddSliceAssign_s(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -253,111 +253,111 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 3777% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 3777% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - movdqu XMM2, [ECX]; - movdqu XMM3, [ECX+16]; - add ECX, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + movdqu XMM2, [ECX]; + movdqu XMM3, [ECX+16]; + add ECX, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - movdqa XMM2, [ECX]; - movdqa XMM3, [ECX+16]; - add ECX, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + movdqa XMM2, [ECX]; + movdqa XMM3, [ECX+16]; + add ECX, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 2068% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 2068% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - movq MM2, [ECX]; - movq MM3, [ECX+8]; - add ECX, 16; - paddw MM0, MM2; - paddw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + movq MM2, [ECX]; + movq MM3, [ECX+8]; + add ECX, 16; + paddw MM0, MM2; + paddw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ + *cptr++); + *aptr++ = cast(T)(*bptr++ + *cptr++); return a; } @@ -368,35 +368,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] + b[]; + c[] = a[] + b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] + b[i])) - { - printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] + b[i])) + { + printf("[%d]: %d != %d + %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -405,7 +405,7 @@ unittest /*********************** * Computes: - * a[] += value + * a[] += value */ T[] _arrayExpSliceAddass_u(T[] a, T value) @@ -426,98 +426,98 @@ T[] _arrayExpSliceAddass_s(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 832% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 832% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= (l << 16); + uint l = cast(ushort) value; + l |= (l << 16); - if (((cast(uint) aptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 826% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + } + } + } + else + // MMX version is 826% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - movd MM2, l; - pshufw MM2, MM2, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + movd MM2, l; + pshufw MM2, MM2, 0; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - paddw MM0, MM2; - paddw MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + paddw MM0, MM2; + paddw MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - } - } + emms; + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ += value; + *aptr++ += value; return a; } @@ -528,36 +528,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - a[] += 6; + a[] = c[]; + a[] += 6; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(c[i] + 6)) - { - printf("[%d]: %d != %d + 6\n", i, a[i], c[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(c[i] + 6)) + { + printf("[%d]: %d != %d + 6\n", i, a[i], c[i]); + assert(0); + } + } + } } } @@ -566,7 +566,7 @@ unittest /*********************** * Computes: - * a[] += b[] + * a[] += b[] */ T[] _arraySliceSliceAddass_u(T[] a, T[] b) @@ -594,102 +594,102 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 2085% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 2085% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - movdqu XMM2, [ECX]; - movdqu XMM3, [ECX+16]; - add ECX, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + movdqu XMM2, [ECX]; + movdqu XMM3, [ECX+16]; + add ECX, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - movdqa XMM2, [ECX]; - movdqa XMM3, [ECX+16]; - add ECX, 32; - paddw XMM0, XMM2; - paddw XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + movdqa XMM2, [ECX]; + movdqa XMM3, [ECX+16]; + add ECX, 32; + paddw XMM0, XMM2; + paddw XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 1022% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 1022% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - start: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - movq MM2, [ECX]; - movq MM3, [ECX+8]; - add ECX, 16; - paddw MM0, MM2; - paddw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb start; + align 4; + start: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + movq MM2, [ECX]; + movq MM3, [ECX+8]; + add ECX, 16; + paddw MM0, MM2; + paddw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb start; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ += *bptr++; + *aptr++ += *bptr++; return a; } @@ -700,36 +700,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = c[]; - c[] += a[]; + b[] = c[]; + c[] += a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(b[i] + a[i])) - { - printf("[%d]: %d != %d + %d\n", i, c[i], b[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(b[i] + a[i])) + { + printf("[%d]: %d != %d + %d\n", i, c[i], b[i], a[i]); + assert(0); + } + } + } } } @@ -738,7 +738,7 @@ unittest /*********************** * Computes: - * a[] = b[] - value + * a[] = b[] - value */ T[] _arraySliceExpMinSliceAssign_u(T[] a, T value, T[] b) @@ -766,107 +766,107 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 3695% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 3695% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= (l << 16); + uint l = cast(ushort) value; + l |= (l << 16); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 3049% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 3049% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM2, l; - pshufw MM2, MM2, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM2, l; + pshufw MM2, MM2, 0; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - psubw MM0, MM2; - psubw MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + psubw MM0, MM2; + psubw MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ - value); + *aptr++ = cast(T)(*bptr++ - value); return a; } @@ -877,35 +877,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - 6; + c[] = a[] - 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - 6)) - { - printf("[%d]: %d != %d - 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - 6)) + { + printf("[%d]: %d != %d - 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -914,7 +914,7 @@ unittest /*********************** * Computes: - * a[] = value - b[] + * a[] = value - b[] */ T[] _arrayExpSliceMinSliceAssign_u(T[] a, T[] b, T value) @@ -942,113 +942,113 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 4995% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 4995% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= (l << 16); + uint l = cast(ushort) value; + l |= (l << 16); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; - align 4; - startaddsse2u: - movd XMM2, l; - pshufd XMM2, XMM2, 0; - movd XMM3, l; - pshufd XMM3, XMM3, 0; - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - psubw XMM2, XMM0; - psubw XMM3, XMM1; - movdqu [ESI -32], XMM2; - movdqu [ESI+16-32], XMM3; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + movd XMM2, l; + pshufd XMM2, XMM2, 0; + movd XMM3, l; + pshufd XMM3, XMM3, 0; + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + psubw XMM2, XMM0; + psubw XMM3, XMM1; + movdqu [ESI -32], XMM2; + movdqu [ESI+16-32], XMM3; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; - align 4; - startaddsse2a: - movd XMM2, l; - pshufd XMM2, XMM2, 0; - movd XMM3, l; - pshufd XMM3, XMM3, 0; - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - psubw XMM2, XMM0; - psubw XMM3, XMM1; - movdqa [ESI -32], XMM2; - movdqa [ESI+16-32], XMM3; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + movd XMM2, l; + pshufd XMM2, XMM2, 0; + movd XMM3, l; + pshufd XMM3, XMM3, 0; + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + psubw XMM2, XMM0; + psubw XMM3, XMM1; + movdqa [ESI -32], XMM2; + movdqa [ESI+16-32], XMM3; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 4562% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 4562% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM4, l; - pshufw MM4, MM4, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM4, l; + pshufw MM4, MM4, 0; - align 4; - startmmx: - add ESI, 16; - movq MM2, [EAX]; - movq MM3, [EAX+8]; - movq MM0, MM4; - movq MM1, MM4; - add EAX, 16; - psubw MM0, MM2; - psubw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM2, [EAX]; + movq MM3, [EAX+8]; + movq MM0, MM4; + movq MM1, MM4; + add EAX, 16; + psubw MM0, MM2; + psubw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(value - *bptr++); + *aptr++ = cast(T)(value - *bptr++); return a; } @@ -1059,35 +1059,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = 6 - a[]; + c[] = 6 - a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(6 - a[i])) - { - printf("[%d]: %d != 6 - %d\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(6 - a[i])) + { + printf("[%d]: %d != 6 - %d\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1096,7 +1096,7 @@ unittest /*********************** * Computes: - * a[] = b[] - c[] + * a[] = b[] - c[] */ T[] _arraySliceSliceMinSliceAssign_u(T[] a, T[] c, T[] b) @@ -1112,10 +1112,10 @@ T[] _arraySliceSliceMinSliceAssign_t(T[] a, T[] c, T[] b) T[] _arraySliceSliceMinSliceAssign_s(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -1126,111 +1126,111 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 4129% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 4129% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - movdqu XMM2, [ECX]; - movdqu XMM3, [ECX+16]; - add ECX, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + movdqu XMM2, [ECX]; + movdqu XMM3, [ECX+16]; + add ECX, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - movdqa XMM2, [ECX]; - movdqa XMM3, [ECX+16]; - add ECX, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + movdqa XMM2, [ECX]; + movdqa XMM3, [ECX+16]; + add ECX, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 2018% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 2018% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - movq MM2, [ECX]; - movq MM3, [ECX+8]; - add ECX, 16; - psubw MM0, MM2; - psubw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + movq MM2, [ECX]; + movq MM3, [ECX+8]; + add ECX, 16; + psubw MM0, MM2; + psubw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ - *cptr++); + *aptr++ = cast(T)(*bptr++ - *cptr++); return a; } @@ -1241,35 +1241,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] - b[]; + c[] = a[] - b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] - b[i])) - { - printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] - b[i])) + { + printf("[%d]: %d != %d - %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -1278,7 +1278,7 @@ unittest /*********************** * Computes: - * a[] -= value + * a[] -= value */ T[] _arrayExpSliceMinass_u(T[] a, T value) @@ -1299,98 +1299,98 @@ T[] _arrayExpSliceMinass_s(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 835% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 835% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= (l << 16); + uint l = cast(ushort) value; + l |= (l << 16); - if (((cast(uint) aptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2u; + align 4; + startaddsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2u; - mov aptr, ESI; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startaddsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startaddsse2a; + align 4; + startaddsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startaddsse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 835% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + } + } + } + else + // MMX version is 835% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - movd MM2, l; - pshufw MM2, MM2, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + movd MM2, l; + pshufw MM2, MM2, 0; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - psubw MM0, MM2; - psubw MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + psubw MM0, MM2; + psubw MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - } - } + emms; + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ -= value; + *aptr++ -= value; return a; } @@ -1401,36 +1401,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - a[] = c[]; - a[] -= 6; + a[] = c[]; + a[] -= 6; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(c[i] - 6)) - { - printf("[%d]: %d != %d - 6\n", i, a[i], c[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(c[i] - 6)) + { + printf("[%d]: %d != %d - 6\n", i, a[i], c[i]); + assert(0); + } + } + } } } @@ -1439,7 +1439,7 @@ unittest /*********************** * Computes: - * a[] -= b[] + * a[] -= b[] */ T[] _arraySliceSliceMinass_u(T[] a, T[] b) @@ -1467,102 +1467,102 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 2121% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 2121% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm // unaligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm // unaligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - movdqu XMM2, [ECX]; - movdqu XMM3, [ECX+16]; - add ECX, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + movdqu XMM2, [ECX]; + movdqu XMM3, [ECX+16]; + add ECX, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm // aligned case - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm // aligned case + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - movdqa XMM2, [ECX]; - movdqa XMM3, [ECX+16]; - add ECX, 32; - psubw XMM0, XMM2; - psubw XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + movdqa XMM2, [ECX]; + movdqa XMM3, [ECX+16]; + add ECX, 32; + psubw XMM0, XMM2; + psubw XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 1116% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 1116% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - start: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - movq MM2, [ECX]; - movq MM3, [ECX+8]; - add ECX, 16; - psubw MM0, MM2; - psubw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb start; + align 4; + start: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + movq MM2, [ECX]; + movq MM3, [ECX+8]; + add ECX, 16; + psubw MM0, MM2; + psubw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb start; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ -= *bptr++; + *aptr++ -= *bptr++; return a; } @@ -1573,36 +1573,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = c[]; - c[] -= a[]; + b[] = c[]; + c[] -= a[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(b[i] - a[i])) - { - printf("[%d]: %d != %d - %d\n", i, c[i], b[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(b[i] - a[i])) + { + printf("[%d]: %d != %d - %d\n", i, c[i], b[i], a[i]); + assert(0); + } + } + } } } @@ -1611,7 +1611,7 @@ unittest /*********************** * Computes: - * a[] = b[] * value + * a[] = b[] * value */ T[] _arraySliceExpMulSliceAssign_u(T[] a, T value, T[] b) @@ -1639,107 +1639,107 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 3733% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 3733% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= l << 16; + uint l = cast(ushort) value; + l |= l << 16; - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM1, [EAX+16]; - add EAX, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM1, [EAX+16]; + add EAX, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + mov bptr, EAX; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM1, [EAX+16]; - add EAX, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM1, [EAX+16]; + add EAX, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - } - } - } - else - // MMX version is 3733% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + } + } + } + else + // MMX version is 3733% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - movd MM2, l; - pshufw MM2, MM2, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + movd MM2, l; + pshufw MM2, MM2, 0; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM1, [EAX+8]; - add EAX, 16; - pmullw MM0, MM2; - pmullw MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM1, [EAX+8]; + add EAX, 16; + pmullw MM0, MM2; + pmullw MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ * value); + *aptr++ = cast(T)(*bptr++ * value); return a; } @@ -1750,35 +1750,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] * 6; + c[] = a[] * 6; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * 6)) - { - printf("[%d]: %d != %d * 6\n", i, c[i], a[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * 6)) + { + printf("[%d]: %d != %d * 6\n", i, c[i], a[i]); + assert(0); + } + } + } } } @@ -1787,7 +1787,7 @@ unittest /*********************** * Computes: - * a[] = b[] * c[] + * a[] = b[] * c[] */ T[] _arraySliceSliceMulSliceAssign_u(T[] a, T[] c, T[] b) @@ -1803,10 +1803,10 @@ T[] _arraySliceSliceMulSliceAssign_t(T[] a, T[] c, T[] b) T[] _arraySliceSliceMulSliceAssign_s(T[] a, T[] c, T[] b) in { - assert(a.length == b.length && b.length == c.length); - assert(disjoint(a, b)); - assert(disjoint(a, c)); - assert(disjoint(b, c)); + assert(a.length == b.length && b.length == c.length); + assert(disjoint(a, b)); + assert(disjoint(a, c)); + assert(disjoint(b, c)); } body { @@ -1818,111 +1818,111 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 2515% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 2515% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + if (((cast(uint) aptr | cast(uint) bptr | cast(uint) cptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2u: - add ESI, 32; - movdqu XMM0, [EAX]; - movdqu XMM2, [ECX]; - movdqu XMM1, [EAX+16]; - movdqu XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + add ESI, 32; + movdqu XMM0, [EAX]; + movdqu XMM2, [ECX]; + movdqu XMM1, [EAX+16]; + movdqu XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startsse2a: - add ESI, 32; - movdqa XMM0, [EAX]; - movdqa XMM2, [ECX]; - movdqa XMM1, [EAX+16]; - movdqa XMM3, [ECX+16]; - add EAX, 32; - add ECX, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + add ESI, 32; + movdqa XMM0, [EAX]; + movdqa XMM2, [ECX]; + movdqa XMM1, [EAX+16]; + movdqa XMM3, [ECX+16]; + add EAX, 32; + add ECX, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } - } - else - // MMX version is 2515% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } + } + else + // MMX version is 2515% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - asm - { - mov ESI, aptr; - mov EDI, n; - mov EAX, bptr; - mov ECX, cptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov EAX, bptr; + mov ECX, cptr; - align 4; - startmmx: - add ESI, 16; - movq MM0, [EAX]; - movq MM2, [ECX]; - movq MM1, [EAX+8]; - movq MM3, [ECX+8]; - add EAX, 16; - add ECX, 16; - pmullw MM0, MM2; - pmullw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + add ESI, 16; + movq MM0, [EAX]; + movq MM2, [ECX]; + movq MM1, [EAX+8]; + movq MM3, [ECX+8]; + add EAX, 16; + add ECX, 16; + pmullw MM0, MM2; + pmullw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, EAX; - mov cptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, EAX; + mov cptr, ECX; + } + } } while (aptr < aend) - *aptr++ = cast(T)(*bptr++ * *cptr++); + *aptr++ = cast(T)(*bptr++ * *cptr++); return a; } @@ -1933,35 +1933,35 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - c[] = a[] * b[]; + c[] = a[] * b[]; - for (int i = 0; i < dim; i++) - { - if (c[i] != cast(T)(a[i] * b[i])) - { - printf("[%d]: %d != %d * %d\n", i, c[i], a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (c[i] != cast(T)(a[i] * b[i])) + { + printf("[%d]: %d != %d * %d\n", i, c[i], a[i], b[i]); + assert(0); + } + } + } } } @@ -1970,7 +1970,7 @@ unittest /*********************** * Computes: - * a[] *= value + * a[] *= value */ T[] _arrayExpSliceMulass_u(T[] a, T value) @@ -1991,98 +1991,98 @@ T[] _arrayExpSliceMulass_s(T[] a, T value) version (D_InlineAsm_X86) { - // SSE2 aligned version is 2044% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 2044% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - uint l = cast(ushort) value; - l |= l << 16; + uint l = cast(ushort) value; + l |= l << 16; - if (((cast(uint) aptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + if (((cast(uint) aptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM1, [ESI+16]; - add ESI, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM2; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM1, [ESI+16]; + add ESI, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM2; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - movd XMM2, l; - pshufd XMM2, XMM2, 0; + mov aptr, ESI; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + movd XMM2, l; + pshufd XMM2, XMM2, 0; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM1, [ESI+16]; - add ESI, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM2; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM1, [ESI+16]; + add ESI, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM2; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - } - } - } - else - // MMX version is 2056% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + } + } + } + else + // MMX version is 2056% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - uint l = cast(ushort) value; + uint l = cast(ushort) value; - asm - { - mov ESI, aptr; - mov EDI, n; - movd MM2, l; - pshufw MM2, MM2, 0; + asm + { + mov ESI, aptr; + mov EDI, n; + movd MM2, l; + pshufw MM2, MM2, 0; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM1, [ESI+8]; - add ESI, 16; - pmullw MM0, MM2; - pmullw MM1, MM2; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM1, [ESI+8]; + add ESI, 16; + pmullw MM0, MM2; + pmullw MM1, MM2; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - } - } + emms; + mov aptr, ESI; + } + } } while (aptr < aend) - *aptr++ *= value; + *aptr++ *= value; return a; } @@ -2093,36 +2093,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = a[]; - a[] *= 6; + b[] = a[]; + a[] *= 6; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(b[i] * 6)) - { - printf("[%d]: %d != %d * 6\n", i, a[i], b[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(b[i] * 6)) + { + printf("[%d]: %d != %d * 6\n", i, a[i], b[i]); + assert(0); + } + } + } } } @@ -2131,7 +2131,7 @@ unittest /*********************** * Computes: - * a[] *= b[] + * a[] *= b[] */ T[] _arraySliceSliceMulass_u(T[] a, T[] b) @@ -2159,102 +2159,102 @@ body version (D_InlineAsm_X86) { - // SSE2 aligned version is 2519% faster - if (sse2() && a.length >= 16) - { - auto n = aptr + (a.length & ~15); + // SSE2 aligned version is 2519% faster + if (sse2() && a.length >= 16) + { + auto n = aptr + (a.length & ~15); - if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + if (((cast(uint) aptr | cast(uint) bptr) & 15) != 0) + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2u: - movdqu XMM0, [ESI]; - movdqu XMM2, [ECX]; - movdqu XMM1, [ESI+16]; - movdqu XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM3; - movdqu [ESI -32], XMM0; - movdqu [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2u; + align 4; + startsse2u: + movdqu XMM0, [ESI]; + movdqu XMM2, [ECX]; + movdqu XMM1, [ESI+16]; + movdqu XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM3; + movdqu [ESI -32], XMM0; + movdqu [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2u; - mov aptr, ESI; - mov bptr, ECX; - } - } - else - { - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + mov aptr, ESI; + mov bptr, ECX; + } + } + else + { + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startsse2a: - movdqa XMM0, [ESI]; - movdqa XMM2, [ECX]; - movdqa XMM1, [ESI+16]; - movdqa XMM3, [ECX+16]; - add ESI, 32; - add ECX, 32; - pmullw XMM0, XMM2; - pmullw XMM1, XMM3; - movdqa [ESI -32], XMM0; - movdqa [ESI+16-32], XMM1; - cmp ESI, EDI; - jb startsse2a; + align 4; + startsse2a: + movdqa XMM0, [ESI]; + movdqa XMM2, [ECX]; + movdqa XMM1, [ESI+16]; + movdqa XMM3, [ECX+16]; + add ESI, 32; + add ECX, 32; + pmullw XMM0, XMM2; + pmullw XMM1, XMM3; + movdqa [ESI -32], XMM0; + movdqa [ESI+16-32], XMM1; + cmp ESI, EDI; + jb startsse2a; - mov aptr, ESI; - mov bptr, ECX; - } - } - } - else - // MMX version is 1712% faster - if (mmx() && a.length >= 8) - { - auto n = aptr + (a.length & ~7); + mov aptr, ESI; + mov bptr, ECX; + } + } + } + else + // MMX version is 1712% faster + if (mmx() && a.length >= 8) + { + auto n = aptr + (a.length & ~7); - asm - { - mov ESI, aptr; - mov EDI, n; - mov ECX, bptr; + asm + { + mov ESI, aptr; + mov EDI, n; + mov ECX, bptr; - align 4; - startmmx: - movq MM0, [ESI]; - movq MM2, [ECX]; - movq MM1, [ESI+8]; - movq MM3, [ECX+8]; - add ESI, 16; - add ECX, 16; - pmullw MM0, MM2; - pmullw MM1, MM3; - movq [ESI -16], MM0; - movq [ESI+8-16], MM1; - cmp ESI, EDI; - jb startmmx; + align 4; + startmmx: + movq MM0, [ESI]; + movq MM2, [ECX]; + movq MM1, [ESI+8]; + movq MM3, [ECX+8]; + add ESI, 16; + add ECX, 16; + pmullw MM0, MM2; + pmullw MM1, MM3; + movq [ESI -16], MM0; + movq [ESI+8-16], MM1; + cmp ESI, EDI; + jb startmmx; - emms; - mov aptr, ESI; - mov bptr, ECX; - } - } + emms; + mov aptr, ESI; + mov bptr, ECX; + } + } } while (aptr < aend) - *aptr++ *= *bptr++; + *aptr++ *= *bptr++; return a; } @@ -2265,36 +2265,36 @@ unittest for (cpuid = 0; cpuid < CPUID_MAX; cpuid++) { - version (log) printf(" cpuid %d\n", cpuid); + version (log) printf(" cpuid %d\n", cpuid); - for (int j = 0; j < 2; j++) - { - const int dim = 67; - T[] a = new T[dim + j]; // aligned on 16 byte boundary - a = a[j .. dim + j]; // misalign for second iteration - T[] b = new T[dim + j]; - b = b[j .. dim + j]; - T[] c = new T[dim + j]; - c = c[j .. dim + j]; + for (int j = 0; j < 2; j++) + { + const int dim = 67; + T[] a = new T[dim + j]; // aligned on 16 byte boundary + a = a[j .. dim + j]; // misalign for second iteration + T[] b = new T[dim + j]; + b = b[j .. dim + j]; + T[] c = new T[dim + j]; + c = c[j .. dim + j]; - for (int i = 0; i < dim; i++) - { a[i] = cast(T)i; - b[i] = cast(T)(i + 7); - c[i] = cast(T)(i * 2); - } + for (int i = 0; i < dim; i++) + { a[i] = cast(T)i; + b[i] = cast(T)(i + 7); + c[i] = cast(T)(i * 2); + } - b[] = a[]; - a[] *= c[]; + b[] = a[]; + a[] *= c[]; - for (int i = 0; i < dim; i++) - { - if (a[i] != cast(T)(b[i] * c[i])) - { - printf("[%d]: %d != %d * %d\n", i, a[i], b[i], c[i]); - assert(0); - } - } - } + for (int i = 0; i < dim; i++) + { + if (a[i] != cast(T)(b[i] * c[i])) + { + printf("[%d]: %d != %d * %d\n", i, a[i], b[i], c[i]); + assert(0); + } + } + } } } diff --git a/internal/cast.d b/internal/cast.d index 802ae3c8f..3fd805963 100644 --- a/internal/cast.d +++ b/internal/cast.d @@ -29,10 +29,10 @@ extern (C): /****************************************** * Given a pointer: - * If it is an Object, return that Object. - * If it is an interface, return the Object implementing the interface. - * If it is null, return null. - * Else, undefined crash + * If it is an Object, return that Object. + * If it is an interface, return the Object implementing the interface. + * If it is null, return null. + * Else, undefined crash */ Object _d_toObject(void* p) @@ -40,19 +40,19 @@ Object _d_toObject(void* p) if (p) { - o = cast(Object)p; - ClassInfo oc = o.classinfo; - Interface *pi = **cast(Interface ***)p; + o = cast(Object)p; + ClassInfo oc = o.classinfo; + Interface *pi = **cast(Interface ***)p; - /* Interface.offset lines up with ClassInfo.name.ptr, - * so we rely on pointers never being less than 64K, - * and Objects never being greater. - */ - if (pi.offset < 0x10000) - { - //printf("\tpi.offset = %d\n", pi.offset); - o = cast(Object)(p - pi.offset); - } + /* Interface.offset lines up with ClassInfo.name.ptr, + * so we rely on pointers never being less than 64K, + * and Objects never being greater. + */ + if (pi.offset < 0x10000) + { + //printf("\tpi.offset = %d\n", pi.offset); + o = cast(Object)(p - pi.offset); + } } return o; } @@ -69,11 +69,11 @@ Object _d_interface_cast(void* p, ClassInfo c) //printf("_d_interface_cast(p = %p, c = '%.*s')\n", p, c.name); if (p) { - Interface *pi = **cast(Interface ***)p; + Interface *pi = **cast(Interface ***)p; - //printf("\tpi.offset = %d\n", pi.offset); - o = cast(Object)(p - pi.offset); - return _d_dynamic_cast(o, c); + //printf("\tpi.offset = %d\n", pi.offset); + o = cast(Object)(p - pi.offset); + return _d_dynamic_cast(o, c); } return o; } @@ -86,14 +86,14 @@ Object _d_dynamic_cast(Object o, ClassInfo c) if (o) { - oc = o.classinfo; - if (_d_isbaseof2(oc, c, offset)) - { - //printf("\toffset = %d\n", offset); - o = cast(Object)(cast(void*)o + offset); - } - else - o = null; + oc = o.classinfo; + if (_d_isbaseof2(oc, c, offset)) + { + //printf("\toffset = %d\n", offset); + o = cast(Object)(cast(void*)o + offset); + } + else + o = null; } //printf("\tresult = %p\n", o); return o; @@ -103,32 +103,32 @@ int _d_isbaseof2(ClassInfo oc, ClassInfo c, inout uint offset) { int i; if (oc is c) - return 1; + return 1; do { - if (oc.base is c) - return 1; - for (i = 0; i < oc.interfaces.length; i++) - { - ClassInfo ic; + if (oc.base is c) + return 1; + for (i = 0; i < oc.interfaces.length; i++) + { + ClassInfo ic; - ic = oc.interfaces[i].classinfo; - if (ic is c) - { offset = oc.interfaces[i].offset; - return 1; - } - } - for (i = 0; i < oc.interfaces.length; i++) - { - ClassInfo ic; + ic = oc.interfaces[i].classinfo; + if (ic is c) + { offset = oc.interfaces[i].offset; + return 1; + } + } + for (i = 0; i < oc.interfaces.length; i++) + { + ClassInfo ic; - ic = oc.interfaces[i].classinfo; - if (_d_isbaseof2(ic, c, offset)) - { offset = oc.interfaces[i].offset; - return 1; - } - } - oc = oc.base; + ic = oc.interfaces[i].classinfo; + if (_d_isbaseof2(ic, c, offset)) + { offset = oc.interfaces[i].offset; + return 1; + } + } + oc = oc.base; } while (oc); return 0; } @@ -137,20 +137,20 @@ int _d_isbaseof(ClassInfo oc, ClassInfo c) { int i; if (oc is c) - return 1; + return 1; do { - if (oc.base is c) - return 1; - for (i = 0; i < oc.interfaces.length; i++) - { - ClassInfo ic; + if (oc.base is c) + return 1; + for (i = 0; i < oc.interfaces.length; i++) + { + ClassInfo ic; - ic = oc.interfaces[i].classinfo; - if (ic is c || _d_isbaseof(ic, c)) - return 1; - } - oc = oc.base; + ic = oc.interfaces[i].classinfo; + if (ic is c || _d_isbaseof(ic, c)) + return 1; + } + oc = oc.base; } while (oc); return 0; } @@ -170,13 +170,13 @@ void *_d_interface_vtbl(ClassInfo ic, Object o) oc = o.classinfo; for (i = 0; i < oc.interfaces.length; i++) { - ClassInfo oic; + ClassInfo oic; - oic = oc.interfaces[i].classinfo; - if (oic is ic) - { - return cast(void *)oc.interfaces[i].vtbl; - } + oic = oc.interfaces[i].classinfo; + if (oic is ic) + { + return cast(void *)oc.interfaces[i].vtbl; + } } assert(0); } diff --git a/internal/dmain2.d b/internal/dmain2.d index e01145b7b..6665e2423 100644 --- a/internal/dmain2.d +++ b/internal/dmain2.d @@ -61,102 +61,102 @@ extern (C) int main(size_t argc, char **argv) int myebx; version (OSX) - { /* OSX does not provide a way to get at the top of the - * stack, except for the magic value 0xC0000000. - * But as far as the gc is concerned, argv is at the top - * of the main thread's stack, so save the address of that. - */ - __osx_stack_end = cast(void*)&argv; + { /* OSX does not provide a way to get at the top of the + * stack, except for the magic value 0xC0000000. + * But as far as the gc is concerned, argv is at the top + * of the main thread's stack, so save the address of that. + */ + __osx_stack_end = cast(void*)&argv; } version (FreeBSD) - { /* FreeBSD does not provide a way to get at the top of the - * stack. - * But as far as the gc is concerned, argv is at the top - * of the main thread's stack, so save the address of that. - */ - __libc_stack_end = cast(void*)&argv; + { /* FreeBSD does not provide a way to get at the top of the + * stack. + * But as far as the gc is concerned, argv is at the top + * of the main thread's stack, so save the address of that. + */ + __libc_stack_end = cast(void*)&argv; } version (Solaris) - { /* As far as the gc is concerned, argv is at the top - * of the main thread's stack, so save the address of that. - */ - __libc_stack_end = cast(void*)&argv; + { /* As far as the gc is concerned, argv is at the top + * of the main thread's stack, so save the address of that. + */ + __libc_stack_end = cast(void*)&argv; } version (Posix) { - _STI_monitor_staticctor(); - _STI_critical_init(); - gc_init(); - am = cast(char[] *) malloc(argc * (char[]).sizeof); - // BUG: alloca() conflicts with try-catch-finally stack unwinding - //am = (char[] *) alloca(argc * (char[]).sizeof); + _STI_monitor_staticctor(); + _STI_critical_init(); + gc_init(); + am = cast(char[] *) malloc(argc * (char[]).sizeof); + // BUG: alloca() conflicts with try-catch-finally stack unwinding + //am = (char[] *) alloca(argc * (char[]).sizeof); } version (Win32) { - gc_init(); - _minit(); - am = cast(char[] *) alloca(argc * (char[]).sizeof); + gc_init(); + _minit(); + am = cast(char[] *) alloca(argc * (char[]).sizeof); } if (no_catch_exceptions) { - _moduleCtor(); - _moduleUnitTests(); + _moduleCtor(); + _moduleUnitTests(); - for (size_t i = 0; i < argc; i++) - { - auto len = strlen(argv[i]); - am[i] = argv[i][0 .. len]; - } + for (size_t i = 0; i < argc; i++) + { + auto len = strlen(argv[i]); + am[i] = argv[i][0 .. len]; + } - args = am[0 .. argc]; + args = am[0 .. argc]; - result = main(args); - _moduleDtor(); - gc_term(); + result = main(args); + _moduleDtor(); + gc_term(); } else { - try - { - _moduleCtor(); - _moduleUnitTests(); + try + { + _moduleCtor(); + _moduleUnitTests(); - for (size_t i = 0; i < argc; i++) - { - auto len = strlen(argv[i]); - am[i] = argv[i][0 .. len]; - } + for (size_t i = 0; i < argc; i++) + { + auto len = strlen(argv[i]); + am[i] = argv[i][0 .. len]; + } - args = am[0 .. argc]; + args = am[0 .. argc]; - result = main(args); - _moduleDtor(); - gc_term(); - } - catch (Object o) - { - version (none) - { - printf("Error: "); - o.print(); - } - else - { - fprintf(stderr, "Error: %.*s\n", o.toString()); - } - exit(EXIT_FAILURE); - } + result = main(args); + _moduleDtor(); + gc_term(); + } + catch (Object o) + { + version (none) + { + printf("Error: "); + o.print(); + } + else + { + fprintf(stderr, "Error: %.*s\n", o.toString()); + } + exit(EXIT_FAILURE); + } } version (Posix) { - free(am); - _STD_critical_term(); - _STD_monitor_staticdtor(); + free(am); + _STD_critical_term(); + _STD_monitor_staticdtor(); } return result; } diff --git a/internal/invariant.d b/internal/invariant.d index f83afc94b..45f9ad399 100644 --- a/internal/invariant.d +++ b/internal/invariant.d @@ -11,15 +11,15 @@ void _d_invariant(Object o) //printf("__d_invariant(%p)\n", o); // BUG: needs to be filename/line of caller, not library routine - assert(o !is null); // just do null check, not invariant check + assert(o !is null); // just do null check, not invariant check c = o.classinfo; do { - if (c.classInvariant) - { - (*c.classInvariant)(o); - } - c = c.base; + if (c.classInvariant) + { + (*c.classInvariant)(o); + } + c = c.base; } while (c); } diff --git a/internal/qsort.d b/internal/qsort.d index 6e537593a..bd2a3919e 100644 --- a/internal/qsort.d +++ b/internal/qsort.d @@ -1,16 +1,16 @@ /* - Portions of this file are: - Copyright Prototronics, 1987 - Totem Lake P.O. 8117 - Kirkland, Washington 98034 - (206) 820-1972 - Licensed to Digital Mars. + Portions of this file are: + Copyright Prototronics, 1987 + Totem Lake P.O. 8117 + Kirkland, Washington 98034 + (206) 820-1972 + Licensed to Digital Mars. - June 11, 1987 from Ray Gardner's - Denver, Colorado) public domain version + June 11, 1987 from Ray Gardner's + Denver, Colorado) public domain version - Use qsort2.d instead of this file if a redistributable version of - _adSort() is required. + Use qsort2.d instead of this file if a redistributable version of + _adSort() is required. */ @@ -24,7 +24,7 @@ ** Oct. 1978, and Corrigendum, Comm. ACM, June 1979. */ -//debug=qsort; // uncomment to turn on debugging printf's +//debug=qsort; // uncomment to turn on debugging printf's import std.c.stdio; import std.c.stdlib; @@ -38,28 +38,28 @@ struct Array } -private const int _maxspan = 7; // subarrays of _maxspan or fewer elements - // will be sorted by a simple insertion sort +private const int _maxspan = 7; // subarrays of _maxspan or fewer elements + // will be sorted by a simple insertion sort -/* Adjust _maxspan according to relative cost of a swap and a compare. Reduce -_maxspan (not less than 1) if a swap is very expensive such as when you have -an array of large structures to be sorted, rather than an array of pointers to -structures. The default value is optimized for a high cost for compares. */ +/* Adjust _maxspan according to relative cost of a swap and a compare. Reduce +_maxspan (not less than 1) if a swap is very expensive such as when you have +an array of large structures to be sorted, rather than an array of pointers to +structures. The default value is optimized for a high cost for compares. */ extern (C) long _adSort(Array a, TypeInfo ti) { byte* base; - byte*[40] stack; // stack - byte** sp; // stack pointer - byte* i, j, limit; // scan and limit pointers + byte*[40] stack; // stack + byte** sp; // stack pointer + byte* i, j, limit; // scan and limit pointers uint thresh; // size of _maxspan elements in bytes uint width = ti.tsize(); base = cast(byte *)a.ptr; thresh = _maxspan * width; // init threshold sp = stack.ptr; // init stack pointer - limit = base + a.length * width; // pointer past end of array + limit = base + a.length * width; // pointer past end of array while (1) // repeat until done then return { while (limit - base > thresh) // if more than _maxspan elements @@ -68,42 +68,42 @@ extern (C) long _adSort(Array a, TypeInfo ti) ti.swap((cast(uint)(limit - base) >> 1) - (((cast(uint)(limit - base) >> 1)) % width) + base, base); - i = base + width; // i scans from left to right - j = limit - width; // j scans from right to left + i = base + width; // i scans from left to right + j = limit - width; // j scans from right to left - if (ti.compare(i, j) > 0) // Sedgewick's - ti.swap(i, j); // three-element sort - if (ti.compare(base, j) > 0) // sets things up - ti.swap(base, j); // so that - if (ti.compare(i, base) > 0) // *i <= *base <= *j - ti.swap(i, base); // *base is the pivot element + if (ti.compare(i, j) > 0) // Sedgewick's + ti.swap(i, j); // three-element sort + if (ti.compare(base, j) > 0) // sets things up + ti.swap(base, j); // so that + if (ti.compare(i, base) > 0) // *i <= *base <= *j + ti.swap(i, base); // *base is the pivot element while (1) { - do // move i right until *i >= pivot + do // move i right until *i >= pivot i += width; while (ti.compare(i, base) < 0); - do // move j left until *j <= pivot + do // move j left until *j <= pivot j -= width; while (ti.compare(j, base) > 0); - if (i > j) // break loop if pointers crossed + if (i > j) // break loop if pointers crossed break; - ti.swap(i, j); // else swap elements, keep scanning + ti.swap(i, j); // else swap elements, keep scanning } - ti.swap(base, j); // move pivot into correct place - if (j - base > limit - i) // if left subarray is larger... + ti.swap(base, j); // move pivot into correct place + if (j - base > limit - i) // if left subarray is larger... { - sp[0] = base; // stack left subarray base - sp[1] = j; // and limit - base = i; // sort the right subarray + sp[0] = base; // stack left subarray base + sp[1] = j; // and limit + base = i; // sort the right subarray } - else // else right subarray is larger + else // else right subarray is larger { - sp[0] = i; // stack right subarray base - sp[1] = limit; // and limit - limit = j; // sort the left subarray + sp[0] = i; // stack right subarray base + sp[1] = limit; // and limit + limit = j; // sort the left subarray } - sp += 2; // increment stack pointer + sp += 2; // increment stack pointer assert(sp < cast(byte**)stack + stack.length); } @@ -120,13 +120,13 @@ extern (C) long _adSort(Array a, TypeInfo ti) i += width; } - if (sp > stack.ptr) // if any entries on stack... + if (sp > stack.ptr) // if any entries on stack... { - sp -= 2; // pop the base and limit + sp -= 2; // pop the base and limit base = sp[0]; limit = sp[1]; } - else // else stack empty, all done + else // else stack empty, all done return *cast(long*)(&a); } assert(0); @@ -154,9 +154,9 @@ unittest for (int i = 0; i < a.length - 1; i++) { - //printf("i = %d", i); - //printf(" %d %d\n", a[i], a[i + 1]); - assert(a[i] <= a[i + 1]); + //printf("i = %d", i); + //printf(" %d %d\n", a[i], a[i + 1]); + assert(a[i] <= a[i + 1]); } } diff --git a/internal/switch.d b/internal/switch.d index ee09871c0..5197d3922 100644 --- a/internal/switch.d +++ b/internal/switch.d @@ -29,11 +29,11 @@ import std.string; /****************************************************** * Support for switch statements switching on strings. * Input: - * table[] sorted array of strings generated by compiler - * ca string to look up in table + * table[] sorted array of strings generated by compiler + * ca string to look up in table * Output: - * result index of match in table[] - * -1 if not in table + * result index of match in table[] + * -1 if not in table */ extern (C): @@ -41,126 +41,126 @@ extern (C): int _d_switch_string(char[][] table, char[] ca) in { - //printf("in _d_switch_string()\n"); - assert(table.length >= 0); - assert(ca.length >= 0); + //printf("in _d_switch_string()\n"); + assert(table.length >= 0); + assert(ca.length >= 0); - // Make sure table[] is sorted correctly - int j; + // Make sure table[] is sorted correctly + int j; - for (j = 1; j < table.length; j++) - { - int len1 = table[j - 1].length; - int len2 = table[j].length; + for (j = 1; j < table.length; j++) + { + int len1 = table[j - 1].length; + int len2 = table[j].length; - assert(len1 <= len2); - if (len1 == len2) - { - int ci; + assert(len1 <= len2); + if (len1 == len2) + { + int ci; - ci = memcmp(table[j - 1].ptr, table[j].ptr, len1); - assert(ci < 0); // ci==0 means a duplicate - } - } + ci = memcmp(table[j - 1].ptr, table[j].ptr, len1); + assert(ci < 0); // ci==0 means a duplicate + } + } } out (result) { - int i; - int cj; + int i; + int cj; - //printf("out _d_switch_string()\n"); - if (result == -1) - { - // Not found - for (i = 0; i < table.length; i++) - { - if (table[i].length == ca.length) - { cj = memcmp(table[i].ptr, ca.ptr, ca.length); - assert(cj != 0); - } - } - } - else - { - assert(0 <= result && result < table.length); - for (i = 0; 1; i++) - { - assert(i < table.length); - if (table[i].length == ca.length) - { - cj = memcmp(table[i].ptr, ca.ptr, ca.length); - if (cj == 0) - { - assert(i == result); - break; - } - } - } - } + //printf("out _d_switch_string()\n"); + if (result == -1) + { + // Not found + for (i = 0; i < table.length; i++) + { + if (table[i].length == ca.length) + { cj = memcmp(table[i].ptr, ca.ptr, ca.length); + assert(cj != 0); + } + } + } + else + { + assert(0 <= result && result < table.length); + for (i = 0; 1; i++) + { + assert(i < table.length); + if (table[i].length == ca.length) + { + cj = memcmp(table[i].ptr, ca.ptr, ca.length); + if (cj == 0) + { + assert(i == result); + break; + } + } + } + } } body { - //printf("body _d_switch_string(%.*s)\n", ca); - int low; - int high; - int mid; - int c; - char[] pca; + //printf("body _d_switch_string(%.*s)\n", ca); + int low; + int high; + int mid; + int c; + char[] pca; - low = 0; - high = table.length; + low = 0; + high = table.length; - version (none) - { - // Print table - printf("ca[] = '%s'\n", cast(char *)ca); - for (mid = 0; mid < high; mid++) - { - pca = table[mid]; - printf("table[%d] = %d, '%.*s'\n", mid, pca.length, pca); - } - } - if (high && - ca.length >= table[0].length && - ca.length <= table[high - 1].length) - { - // Looking for 0 length string, which would only be at the beginning - if (ca.length == 0) - return 0; + version (none) + { + // Print table + printf("ca[] = '%s'\n", cast(char *)ca); + for (mid = 0; mid < high; mid++) + { + pca = table[mid]; + printf("table[%d] = %d, '%.*s'\n", mid, pca.length, pca); + } + } + if (high && + ca.length >= table[0].length && + ca.length <= table[high - 1].length) + { + // Looking for 0 length string, which would only be at the beginning + if (ca.length == 0) + return 0; - char c1 = ca[0]; + char c1 = ca[0]; - // Do binary search - while (low < high) - { - mid = (low + high) >> 1; - pca = table[mid]; - c = ca.length - pca.length; - if (c == 0) - { - c = cast(ubyte)c1 - cast(ubyte)pca[0]; - if (c == 0) - { - c = memcmp(ca.ptr, pca.ptr, ca.length); - if (c == 0) - { //printf("found %d\n", mid); - return mid; - } - } - } - if (c < 0) - { - high = mid; - } - else - { - low = mid + 1; - } - } - } + // Do binary search + while (low < high) + { + mid = (low + high) >> 1; + pca = table[mid]; + c = ca.length - pca.length; + if (c == 0) + { + c = cast(ubyte)c1 - cast(ubyte)pca[0]; + if (c == 0) + { + c = memcmp(ca.ptr, pca.ptr, ca.length); + if (c == 0) + { //printf("found %d\n", mid); + return mid; + } + } + } + if (c < 0) + { + high = mid; + } + else + { + low = mid + 1; + } + } + } - //printf("not found\n"); - return -1; // not found + //printf("not found\n"); + return -1; // not found } unittest @@ -180,110 +180,110 @@ unittest int _d_switch_ustring(wchar[][] table, wchar[] ca) in { - //printf("in _d_switch_ustring()\n"); - assert(table.length >= 0); - assert(ca.length >= 0); + //printf("in _d_switch_ustring()\n"); + assert(table.length >= 0); + assert(ca.length >= 0); - // Make sure table[] is sorted correctly - int j; + // Make sure table[] is sorted correctly + int j; - for (j = 1; j < table.length; j++) - { - int len1 = table[j - 1].length; - int len2 = table[j].length; + for (j = 1; j < table.length; j++) + { + int len1 = table[j - 1].length; + int len2 = table[j].length; - assert(len1 <= len2); - if (len1 == len2) - { - int c; + assert(len1 <= len2); + if (len1 == len2) + { + int c; - c = memcmp(table[j - 1].ptr, table[j].ptr, len1 * wchar.sizeof); - assert(c < 0); // c==0 means a duplicate - } - } + c = memcmp(table[j - 1].ptr, table[j].ptr, len1 * wchar.sizeof); + assert(c < 0); // c==0 means a duplicate + } + } } out (result) { - int i; - int c; + int i; + int c; - //printf("out _d_switch_string()\n"); - if (result == -1) - { - // Not found - for (i = 0; i < table.length; i++) - { - if (table[i].length == ca.length) - { c = memcmp(table[i].ptr, ca.ptr, ca.length * wchar.sizeof); - assert(c != 0); - } - } - } - else - { - assert(0 <= result && result < table.length); - for (i = 0; 1; i++) - { - assert(i < table.length); - if (table[i].length == ca.length) - { - c = memcmp(table[i].ptr, ca.ptr, ca.length * wchar.sizeof); - if (c == 0) - { - assert(i == result); - break; - } - } - } - } + //printf("out _d_switch_string()\n"); + if (result == -1) + { + // Not found + for (i = 0; i < table.length; i++) + { + if (table[i].length == ca.length) + { c = memcmp(table[i].ptr, ca.ptr, ca.length * wchar.sizeof); + assert(c != 0); + } + } + } + else + { + assert(0 <= result && result < table.length); + for (i = 0; 1; i++) + { + assert(i < table.length); + if (table[i].length == ca.length) + { + c = memcmp(table[i].ptr, ca.ptr, ca.length * wchar.sizeof); + if (c == 0) + { + assert(i == result); + break; + } + } + } + } } body { - //printf("body _d_switch_ustring()\n"); - int low; - int high; - int mid; - int c; - wchar[] pca; + //printf("body _d_switch_ustring()\n"); + int low; + int high; + int mid; + int c; + wchar[] pca; - low = 0; - high = table.length; + low = 0; + high = table.length; /* - // Print table - wprintf("ca[] = '%.*s'\n", ca); - for (mid = 0; mid < high; mid++) - { - pca = table[mid]; - wprintf("table[%d] = %d, '%.*s'\n", mid, pca.length, pca); - } + // Print table + wprintf("ca[] = '%.*s'\n", ca); + for (mid = 0; mid < high; mid++) + { + pca = table[mid]; + wprintf("table[%d] = %d, '%.*s'\n", mid, pca.length, pca); + } */ - // Do binary search - while (low < high) - { - mid = (low + high) >> 1; - pca = table[mid]; - c = ca.length - pca.length; - if (c == 0) - { - c = memcmp(ca.ptr, pca.ptr, ca.length * wchar.sizeof); - if (c == 0) - { //printf("found %d\n", mid); - return mid; - } - } - if (c < 0) - { - high = mid; - } - else - { - low = mid + 1; - } - } - //printf("not found\n"); - return -1; // not found + // Do binary search + while (low < high) + { + mid = (low + high) >> 1; + pca = table[mid]; + c = ca.length - pca.length; + if (c == 0) + { + c = memcmp(ca.ptr, pca.ptr, ca.length * wchar.sizeof); + if (c == 0) + { //printf("found %d\n", mid); + return mid; + } + } + if (c < 0) + { + high = mid; + } + else + { + low = mid + 1; + } + } + //printf("not found\n"); + return -1; // not found } @@ -305,110 +305,110 @@ unittest int _d_switch_dstring(dchar[][] table, dchar[] ca) in { - //printf("in _d_switch_dstring()\n"); - assert(table.length >= 0); - assert(ca.length >= 0); + //printf("in _d_switch_dstring()\n"); + assert(table.length >= 0); + assert(ca.length >= 0); - // Make sure table[] is sorted correctly - int j; + // Make sure table[] is sorted correctly + int j; - for (j = 1; j < table.length; j++) - { - int len1 = table[j - 1].length; - int len2 = table[j].length; + for (j = 1; j < table.length; j++) + { + int len1 = table[j - 1].length; + int len2 = table[j].length; - assert(len1 <= len2); - if (len1 == len2) - { - int c; + assert(len1 <= len2); + if (len1 == len2) + { + int c; - c = memcmp(table[j - 1].ptr, table[j].ptr, len1 * dchar.sizeof); - assert(c < 0); // c==0 means a duplicate - } - } + c = memcmp(table[j - 1].ptr, table[j].ptr, len1 * dchar.sizeof); + assert(c < 0); // c==0 means a duplicate + } + } } out (result) { - int i; - int c; + int i; + int c; - //printf("out _d_switch_string()\n"); - if (result == -1) - { - // Not found - for (i = 0; i < table.length; i++) - { - if (table[i].length == ca.length) - { c = memcmp(table[i].ptr, ca.ptr, ca.length * dchar.sizeof); - assert(c != 0); - } - } - } - else - { - assert(0 <= result && result < table.length); - for (i = 0; 1; i++) - { - assert(i < table.length); - if (table[i].length == ca.length) - { - c = memcmp(table[i].ptr, ca.ptr, ca.length * dchar.sizeof); - if (c == 0) - { - assert(i == result); - break; - } - } - } - } + //printf("out _d_switch_string()\n"); + if (result == -1) + { + // Not found + for (i = 0; i < table.length; i++) + { + if (table[i].length == ca.length) + { c = memcmp(table[i].ptr, ca.ptr, ca.length * dchar.sizeof); + assert(c != 0); + } + } + } + else + { + assert(0 <= result && result < table.length); + for (i = 0; 1; i++) + { + assert(i < table.length); + if (table[i].length == ca.length) + { + c = memcmp(table[i].ptr, ca.ptr, ca.length * dchar.sizeof); + if (c == 0) + { + assert(i == result); + break; + } + } + } + } } body { - //printf("body _d_switch_ustring()\n"); - int low; - int high; - int mid; - int c; - dchar[] pca; + //printf("body _d_switch_ustring()\n"); + int low; + int high; + int mid; + int c; + dchar[] pca; - low = 0; - high = table.length; + low = 0; + high = table.length; /* - // Print table - wprintf("ca[] = '%.*s'\n", ca); - for (mid = 0; mid < high; mid++) - { - pca = table[mid]; - wprintf("table[%d] = %d, '%.*s'\n", mid, pca.length, pca); - } + // Print table + wprintf("ca[] = '%.*s'\n", ca); + for (mid = 0; mid < high; mid++) + { + pca = table[mid]; + wprintf("table[%d] = %d, '%.*s'\n", mid, pca.length, pca); + } */ - // Do binary search - while (low < high) - { - mid = (low + high) >> 1; - pca = table[mid]; - c = ca.length - pca.length; - if (c == 0) - { - c = memcmp(ca.ptr, pca.ptr, ca.length * dchar.sizeof); - if (c == 0) - { //printf("found %d\n", mid); - return mid; - } - } - if (c < 0) - { - high = mid; - } - else - { - low = mid + 1; - } - } - //printf("not found\n"); - return -1; // not found + // Do binary search + while (low < high) + { + mid = (low + high) >> 1; + pca = table[mid]; + c = ca.length - pca.length; + if (c == 0) + { + c = memcmp(ca.ptr, pca.ptr, ca.length * dchar.sizeof); + if (c == 0) + { //printf("found %d\n", mid); + return mid; + } + } + if (c < 0) + { + high = mid; + } + else + { + low = mid + 1; + } + } + //printf("not found\n"); + return -1; // not found } diff --git a/std/array.d b/std/array.d index c3af5e44a..297dff100 100644 --- a/std/array.d +++ b/std/array.d @@ -13,13 +13,13 @@ class ArrayBoundsError : Error public: this(char[] filename, uint linnum) { - this.linnum = linnum; - this.filename = filename; + this.linnum = linnum; + this.filename = filename; - char[] buffer = new char[19 + filename.length + linnum.sizeof * 3 + 1]; - int len; - len = sprintf(buffer.ptr, "ArrayBoundsError %.*s(%u)", filename, linnum); - super(buffer[0..len]); + char[] buffer = new char[19 + filename.length + linnum.sizeof * 3 + 1]; + int len; + len = sprintf(buffer.ptr, "ArrayBoundsError %.*s(%u)", filename, linnum); + super(buffer[0..len]); } } diff --git a/std/asserterror.d b/std/asserterror.d index 9fdd527a6..02811b848 100644 --- a/std/asserterror.d +++ b/std/asserterror.d @@ -11,47 +11,47 @@ class AssertError : Error this(char[] filename, uint linnum) { - this(filename, linnum, null); + this(filename, linnum, null); } this(char[] filename, uint linnum, char[] msg) { - this.linnum = linnum; - this.filename = filename; + this.linnum = linnum; + this.filename = filename; - char* buffer; - size_t len; - int count; + char* buffer; + size_t len; + int count; - /* This code is careful to not use gc allocated memory, - * as that may be the source of the problem. - * Instead, stick with C functions. - */ + /* This code is careful to not use gc allocated memory, + * as that may be the source of the problem. + * Instead, stick with C functions. + */ - len = 23 + filename.length + uint.sizeof * 3 + msg.length + 1; - buffer = cast(char*)std.c.stdlib.malloc(len); - if (buffer == null) - super("AssertError no memory"); - else - { - version (Win32) alias _snprintf snprintf; - count = snprintf(buffer, len, "AssertError Failure %.*s(%u) %.*s", - filename, linnum, msg); - if (count >= len || count == -1) - { super("AssertError internal failure"); - std.c.stdlib.free(buffer); - } - else - super(buffer[0 .. count]); - } + len = 23 + filename.length + uint.sizeof * 3 + msg.length + 1; + buffer = cast(char*)std.c.stdlib.malloc(len); + if (buffer == null) + super("AssertError no memory"); + else + { + version (Win32) alias _snprintf snprintf; + count = snprintf(buffer, len, "AssertError Failure %.*s(%u) %.*s", + filename, linnum, msg); + if (count >= len || count == -1) + { super("AssertError internal failure"); + std.c.stdlib.free(buffer); + } + else + super(buffer[0 .. count]); + } } ~this() { - if (msg.ptr && msg[12] == 'F') // if it was allocated with malloc() - { std.c.stdlib.free(msg.ptr); - msg = null; - } + if (msg.ptr && msg[12] == 'F') // if it was allocated with malloc() + { std.c.stdlib.free(msg.ptr); + msg = null; + } } } diff --git a/std/base64.d b/std/base64.d index a907374dc..6852bdc47 100644 --- a/std/base64.d +++ b/std/base64.d @@ -2,10 +2,10 @@ * Encodes/decodes MIME base64 data. * * Macros: - * WIKI=Phobos/StdBase64 + * WIKI=Phobos/StdBase64 * References: - * Wikipedia Base64$(BR) - * RFC 2045$(BR) + * Wikipedia Base64$(BR) + * RFC 2045$(BR) */ @@ -14,23 +14,23 @@ */ /* - Copyright (C) 2004 Christopher E. Miller - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. + Copyright (C) 2004 Christopher E. Miller + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. */ module std.base64; @@ -40,10 +40,10 @@ module std.base64; class Base64Exception: Exception { - this(char[] msg) - { - super(msg); - } + this(char[] msg) + { + super(msg); + } } @@ -52,10 +52,10 @@ class Base64Exception: Exception class Base64CharException: Base64Exception { - this(char[] msg) - { - super(msg); - } + this(char[] msg) + { + super(msg); + } } @@ -68,77 +68,77 @@ const char[] array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345 uint encodeLength(uint slen) { - uint result; - result = slen / 3; - if(slen % 3) - result++; - return result * 4; + uint result; + result = slen / 3; + if(slen % 3) + result++; + return result * 4; } /** * Encodes str[] and places the result in buf[]. * Params: - * str = string to encode - * buf = destination buffer, must be large enough for the result. + * str = string to encode + * buf = destination buffer, must be large enough for the result. * Returns: - * slice into buf[] representing encoded result + * slice into buf[] representing encoded result */ char[] encode(char[] str, char[] buf) in { - assert(buf.length >= encodeLength(str.length)); + assert(buf.length >= encodeLength(str.length)); } body { - if(!str.length) - return buf[0 .. 0]; - - uint stri; - uint strmax = str.length / 3; - uint strleft = str.length % 3; - uint x; - char* sp, bp; - - bp = &buf[0]; - sp = &str[0]; - for(stri = 0; stri != strmax; stri++) - { - x = (sp[0] << 16) | (sp[1] << 8) | (sp[2]); - sp+= 3; - *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; - *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; - *bp++ = array[(x & 0b00000000_00001111_11000000) >> 6]; - *bp++ = array[(x & 0b00000000_00000000_00111111)]; - } - - switch(strleft) - { - case 2: - x = (sp[0] << 16) | (sp[1] << 8); - sp += 2; - *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; - *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; - *bp++ = array[(x & 0b00000000_00001111_11000000) >> 6]; - *bp++ = '='; - break; - - case 1: - x = *sp++ << 16; - *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; - *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; - *bp++ = '='; - *bp++ = '='; - break; - - case 0: - break; + if(!str.length) + return buf[0 .. 0]; - default: - assert(0); - } - - return buf[0 .. (bp - &buf[0])]; + uint stri; + uint strmax = str.length / 3; + uint strleft = str.length % 3; + uint x; + char* sp, bp; + + bp = &buf[0]; + sp = &str[0]; + for(stri = 0; stri != strmax; stri++) + { + x = (sp[0] << 16) | (sp[1] << 8) | (sp[2]); + sp+= 3; + *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; + *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; + *bp++ = array[(x & 0b00000000_00001111_11000000) >> 6]; + *bp++ = array[(x & 0b00000000_00000000_00111111)]; + } + + switch(strleft) + { + case 2: + x = (sp[0] << 16) | (sp[1] << 8); + sp += 2; + *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; + *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; + *bp++ = array[(x & 0b00000000_00001111_11000000) >> 6]; + *bp++ = '='; + break; + + case 1: + x = *sp++ << 16; + *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; + *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; + *bp++ = '='; + *bp++ = '='; + break; + + case 0: + break; + + default: + assert(0); + } + + return buf[0 .. (bp - &buf[0])]; } @@ -148,17 +148,17 @@ body char[] encode(char[] str) { - return encode(str, new char[encodeLength(str.length)]); + return encode(str, new char[encodeLength(str.length)]); } unittest { - assert(encode("f") == "Zg=="); - assert(encode("fo") == "Zm8="); - assert(encode("foo") == "Zm9v"); - assert(encode("foos") == "Zm9vcw=="); - assert(encode("all your base64 are belong to foo") == "YWxsIHlvdXIgYmFzZTY0IGFyZSBiZWxvbmcgdG8gZm9v"); + assert(encode("f") == "Zg=="); + assert(encode("fo") == "Zm8="); + assert(encode("foo") == "Zm9v"); + assert(encode("foos") == "Zm9vcw=="); + assert(encode("all your base64 are belong to foo") == "YWxsIHlvdXIgYmFzZTY0IGFyZSBiZWxvbmcgdG8gZm9v"); } @@ -168,126 +168,126 @@ unittest */ uint decodeLength(uint elen) { - return elen / 4 * 3; + return elen / 4 * 3; } /** * Decodes str[] and places the result in buf[]. * Params: - * str = string to encode - * buf = destination buffer, must be large enough for the result. + * str = string to encode + * buf = destination buffer, must be large enough for the result. * Returns: - * slice into buf[] representing encoded result + * slice into buf[] representing encoded result * Errors: - * Throws Base64Exception on invalid base64 encoding in estr[]. - * Throws Base64CharException on invalid base64 character in estr[]. + * Throws Base64Exception on invalid base64 encoding in estr[]. + * Throws Base64CharException on invalid base64 character in estr[]. */ char[] decode(char[] estr, char[] buf) in { - assert(buf.length + 2 >= decodeLength(estr.length)); //account for '=' padding + assert(buf.length + 2 >= decodeLength(estr.length)); //account for '=' padding } body { - void badc(char ch) - { - throw new Base64CharException("Invalid base64 character '" ~ (&ch)[0 .. 1] ~ "'"); - } - - - uint arrayIndex(char ch) - out(result) - { - assert(ch == array[result]); - } - body - { - if(ch >= 'A' && ch <= 'Z') - return ch - 'A'; - if(ch >= 'a' && ch <= 'z') - return 'Z' - 'A' + 1 + ch - 'a'; - if(ch >= '0' && ch <= '9') - return 'Z' - 'A' + 1 + 'z' - 'a' + 1 + ch - '0'; - if(ch == '+') - return 'Z' - 'A' + 1 + 'z' - 'a' + 1 + '9' - '0' + 1; - if(ch == '/') - return 'Z' - 'A' + 1 + 'z' - 'a' + 1 + '9' - '0' + 1 + 1; - badc(ch); - assert(0); - } - - - if(!estr.length) - return buf[0 .. 0]; - - if(estr.length % 4) - throw new Base64Exception("Invalid encoded base64 string"); - - uint estri; - uint estrmax = estr.length / 4; - uint x; - char* sp, bp; - char ch; - - sp = &estr[0]; - bp = &buf[0]; - for(estri = 0; estri != estrmax; estri++) - { - x = arrayIndex(sp[0]) << 18 | arrayIndex(sp[1]) << 12; - sp += 2; + void badc(char ch) + { + throw new Base64CharException("Invalid base64 character '" ~ (&ch)[0 .. 1] ~ "'"); + } - ch = *sp++; - if(ch == '=') - { - if(*sp++ != '=') - badc('='); - *bp++ = cast(char) (x >> 16); - break; - } - x |= arrayIndex(ch) << 6; - - ch = *sp++; - if(ch == '=') - { - *bp++ = cast(char) (x >> 16); - *bp++ = cast(char) ((x >> 8) & 0xFF); - break; - } - x |= arrayIndex(ch); - - *bp++ = cast(char) (x >> 16); - *bp++ = cast(char) ((x >> 8) & 0xFF); - *bp++ = cast(char) (x & 0xFF); - } - - return buf[0 .. (bp - &buf[0])]; + + uint arrayIndex(char ch) + out(result) + { + assert(ch == array[result]); + } + body + { + if(ch >= 'A' && ch <= 'Z') + return ch - 'A'; + if(ch >= 'a' && ch <= 'z') + return 'Z' - 'A' + 1 + ch - 'a'; + if(ch >= '0' && ch <= '9') + return 'Z' - 'A' + 1 + 'z' - 'a' + 1 + ch - '0'; + if(ch == '+') + return 'Z' - 'A' + 1 + 'z' - 'a' + 1 + '9' - '0' + 1; + if(ch == '/') + return 'Z' - 'A' + 1 + 'z' - 'a' + 1 + '9' - '0' + 1 + 1; + badc(ch); + assert(0); + } + + + if(!estr.length) + return buf[0 .. 0]; + + if(estr.length % 4) + throw new Base64Exception("Invalid encoded base64 string"); + + uint estri; + uint estrmax = estr.length / 4; + uint x; + char* sp, bp; + char ch; + + sp = &estr[0]; + bp = &buf[0]; + for(estri = 0; estri != estrmax; estri++) + { + x = arrayIndex(sp[0]) << 18 | arrayIndex(sp[1]) << 12; + sp += 2; + + ch = *sp++; + if(ch == '=') + { + if(*sp++ != '=') + badc('='); + *bp++ = cast(char) (x >> 16); + break; + } + x |= arrayIndex(ch) << 6; + + ch = *sp++; + if(ch == '=') + { + *bp++ = cast(char) (x >> 16); + *bp++ = cast(char) ((x >> 8) & 0xFF); + break; + } + x |= arrayIndex(ch); + + *bp++ = cast(char) (x >> 16); + *bp++ = cast(char) ((x >> 8) & 0xFF); + *bp++ = cast(char) (x & 0xFF); + } + + return buf[0 .. (bp - &buf[0])]; } /** * Decodes estr[] and returns the result. * Errors: - * Throws Base64Exception on invalid base64 encoding in estr[]. - * Throws Base64CharException on invalid base64 character in estr[]. + * Throws Base64Exception on invalid base64 encoding in estr[]. + * Throws Base64CharException on invalid base64 character in estr[]. */ char[] decode(char[] estr) { - return decode(estr, new char[decodeLength(estr.length)]); + return decode(estr, new char[decodeLength(estr.length)]); } unittest { - assert(decode(encode("f")) == "f"); - assert(decode(encode("fo")) == "fo"); - assert(decode(encode("foo")) == "foo"); - assert(decode(encode("foos")) == "foos"); - assert(decode(encode("all your base64 are belong to foo")) == "all your base64 are belong to foo"); - - assert(decode(encode("testing some more")) == "testing some more"); - assert(decode(encode("asdf jkl;")) == "asdf jkl;"); - assert(decode(encode("base64 stuff")) == "base64 stuff"); - assert(decode(encode("\1\2\3\4\5\6\7foo\7\6\5\4\3\2\1!")) == "\1\2\3\4\5\6\7foo\7\6\5\4\3\2\1!"); + assert(decode(encode("f")) == "f"); + assert(decode(encode("fo")) == "fo"); + assert(decode(encode("foo")) == "foo"); + assert(decode(encode("foos")) == "foos"); + assert(decode(encode("all your base64 are belong to foo")) == "all your base64 are belong to foo"); + + assert(decode(encode("testing some more")) == "testing some more"); + assert(decode(encode("asdf jkl;")) == "asdf jkl;"); + assert(decode(encode("base64 stuff")) == "base64 stuff"); + assert(decode(encode("\1\2\3\4\5\6\7foo\7\6\5\4\3\2\1!")) == "\1\2\3\4\5\6\7foo\7\6\5\4\3\2\1!"); } diff --git a/std/bind.d b/std/bind.d index 81927fc0e..209a74620 100644 --- a/std/bind.d +++ b/std/bind.d @@ -4,13 +4,13 @@ * Bind function arguments to functions. * * References: - * $(LINK2 http://www.boost.org/libs/bind/bind.html, boost::bind) + * $(LINK2 http://www.boost.org/libs/bind/bind.html, boost::bind) * Authors: Tomasz Stachowiak * Date: November 28, 2006 * Macros: - * WIKI = Phobos/StdBind + * WIKI = Phobos/StdBind * Copyright: - * Public Domain + * Public Domain */ module std.bind; @@ -24,272 +24,272 @@ import std.typetuple; struct DynArg(int i) { - static assert (i >= 0); - - alias i argNr; + static assert (i >= 0); + + alias i argNr; } /** - When passed to the 'bind' function, they will mark dynamic params - ones that aren't statically bound - In boost, they're called __1, __2, __3, etc.. here __0, __1, __2, ... + When passed to the 'bind' function, they will mark dynamic params - ones that aren't statically bound + In boost, they're called __1, __2, __3, etc.. here __0, __1, __2, ... */ const DynArg!(0) _0; -const DynArg!(1) _1; /// ditto -const DynArg!(2) _2; /// ditto -const DynArg!(3) _3; /// ditto -const DynArg!(4) _4; /// ditto -const DynArg!(5) _5; /// ditto -const DynArg!(6) _6; /// ditto -const DynArg!(7) _7; /// ditto -const DynArg!(8) _8; /// ditto -const DynArg!(9) _9; /// ditto +const DynArg!(1) _1; /// ditto +const DynArg!(2) _2; /// ditto +const DynArg!(3) _3; /// ditto +const DynArg!(4) _4; /// ditto +const DynArg!(5) _5; /// ditto +const DynArg!(6) _6; /// ditto +const DynArg!(7) _7; /// ditto +const DynArg!(8) _8; /// ditto +const DynArg!(9) _9; /// ditto /* - Detect if a given type is a DynArg of any index + Detect if a given type is a DynArg of any index */ template isDynArg(T) { - static if (is(typeof(T.argNr))) { // must have the argNr field - static if(is(T : DynArg!(T.argNr))) { // now check the exact type - static const bool isDynArg = true; - } else static const bool isDynArg = false; - } else static const bool isDynArg = false; + static if (is(typeof(T.argNr))) { // must have the argNr field + static if(is(T : DynArg!(T.argNr))) { // now check the exact type + static const bool isDynArg = true; + } else static const bool isDynArg = false; + } else static const bool isDynArg = false; } /* - Detect if a given type is a DynArg of the specified index + Detect if a given type is a DynArg of the specified index */ template isDynArg(T, int i) { - static const bool isDynArg = is(T : DynArg!(i)); + static const bool isDynArg = is(T : DynArg!(i)); } /* - Converts a static array type to a dynamic array type + Converts a static array type to a dynamic array type */ template DynamicArrayType(T) { - alias typeof(T[0])[] DynamicArrayType; + alias typeof(T[0])[] DynamicArrayType; } /* - Assigns one entity to another. As static arrays don't like normal assignment, slice assignment is used for them. - - Params: - a = destination - b = source + Assigns one entity to another. As static arrays don't like normal assignment, slice assignment is used for them. + + Params: + a = destination + b = source */ template _assign(T) { - static if (isStaticArray!(T)) { - void _assign(DynamicArrayType!(T) a, DynamicArrayType!(T) b) { - a[] = b[]; - } - } else { - void _assign(inout T a, inout T b) { - a = b; - } - } + static if (isStaticArray!(T)) { + void _assign(DynamicArrayType!(T) a, DynamicArrayType!(T) b) { + a[] = b[]; + } + } else { + void _assign(inout T a, inout T b) { + a = b; + } + } } /* - Assigns and potentially converts one entity to another - - Normally, only implicit conversion is used, but when both operands are numeric types, an explicit cast is performed on them. - - Params: - T = destination type - a = destination - Y = source type - b = source - copyStaticArrays = when a static array is assigned to a dynamic one, it sometimes has to be .dup'ed as the storage may exist in volatile locations + Assigns and potentially converts one entity to another + + Normally, only implicit conversion is used, but when both operands are numeric types, an explicit cast is performed on them. + + Params: + T = destination type + a = destination + Y = source type + b = source + copyStaticArrays = when a static array is assigned to a dynamic one, it sometimes has to be .dup'ed as the storage may exist in volatile locations */ template _assign(T, Y, bool copyStaticArrays = true) { - static if (isStaticArray!(T)) { - - // if the destination is a static array, copy each element from the source to the destination by a foreach - void _assign(DynamicArrayType!(T) a, DynamicArrayType!(Y) b) { - foreach (i, x; b) { - _assign!(typeof(a[i]), typeof(x))(a[i], x); - } - } - } else static if (!isStaticArray!(T) && isStaticArray!(Y)) { - - // the destination is a dynamic array and the source is a static array. this sometimes needs a .dup - void _assign(inout T a, DynamicArrayType!(Y) b) { - static if (copyStaticArrays) { - a = b.dup; - } else { - a = b; - } - } - } else { - - // none of the items is a static array - void _assign(inout T a, inout Y b) { - static if (IndexOf!(T, NumericTypes.type) != -1 && IndexOf!(Y, NumericTypes.type) != -1) { - a = cast(T)b; - } else { - a = b; - } - } - } + static if (isStaticArray!(T)) { + + // if the destination is a static array, copy each element from the source to the destination by a foreach + void _assign(DynamicArrayType!(T) a, DynamicArrayType!(Y) b) { + foreach (i, x; b) { + _assign!(typeof(a[i]), typeof(x))(a[i], x); + } + } + } else static if (!isStaticArray!(T) && isStaticArray!(Y)) { + + // the destination is a dynamic array and the source is a static array. this sometimes needs a .dup + void _assign(inout T a, DynamicArrayType!(Y) b) { + static if (copyStaticArrays) { + a = b.dup; + } else { + a = b; + } + } + } else { + + // none of the items is a static array + void _assign(inout T a, inout Y b) { + static if (IndexOf!(T, NumericTypes.type) != -1 && IndexOf!(Y, NumericTypes.type) != -1) { + a = cast(T)b; + } else { + a = b; + } + } + } } /** - A simple tuple struct with some basic operations + A simple tuple struct with some basic operations */ struct Tuple(T ...) { - alias Tuple meta; - const bool expressionTuple = isExpressionTuple!(T); - - static if (!expressionTuple) { - alias T type; // a built-in tuple - T value; // a built-in tuple instance - } else { - alias T value; - } - - - const int length = value.length; - + alias Tuple meta; + const bool expressionTuple = isExpressionTuple!(T); - /** - Statically yields a tuple type with an extra element added at its end - */ - template appendT(X) { - alias .Tuple!(T, X) appendT; - } + static if (!expressionTuple) { + alias T type; // a built-in tuple + T value; // a built-in tuple instance + } else { + alias T value; + } - /** - Yields a tuple with an extra element added at its end - */ - appendT!(X) append(X)(X x) { - appendT!(X) res; - foreach (i, y; value) { - _assign!(typeof(y))(res.value[i], y); - } - _assign!(typeof(x))(res.value[$-1], x); - return res; - } - - - /** - Statically yields a tuple type with an extra element added at its beginning - */ - template prependT(X) { - alias .Tuple!(X, T) prependT; - } + const int length = value.length; - /** - Yields a tuple with an extra element added at its beginning - */ - prependT!(X) prepend(X)(X x) { - prependT!(X) res; - foreach (i, y; value) { - _assign!(typeof(y))(res.value[i+1], y); - } - _assign!(typeof(x))(res.value[0], x); - return res; - } - - - /** - Statically concatenates this tuple type with another tuple type - */ - template concatT(T ...) { - static if (expressionTuple) { - alias .Tuple!(value, T) concatT; - } else { - alias .Tuple!(type, T) concatT; - } - } - - - string toString() { - auto res = "(" ~ stdFormat(value[0]); - foreach (x; value[1..$]) { - res ~= stdFormat(", ", x); - } - return res ~ ")"; - } + /** + Statically yields a tuple type with an extra element added at its end + */ + template appendT(X) { + alias .Tuple!(T, X) appendT; + } + + + /** + Yields a tuple with an extra element added at its end + */ + appendT!(X) append(X)(X x) { + appendT!(X) res; + foreach (i, y; value) { + _assign!(typeof(y))(res.value[i], y); + } + _assign!(typeof(x))(res.value[$-1], x); + return res; + } + + + /** + Statically yields a tuple type with an extra element added at its beginning + */ + template prependT(X) { + alias .Tuple!(X, T) prependT; + } + + + /** + Yields a tuple with an extra element added at its beginning + */ + prependT!(X) prepend(X)(X x) { + prependT!(X) res; + foreach (i, y; value) { + _assign!(typeof(y))(res.value[i+1], y); + } + _assign!(typeof(x))(res.value[0], x); + return res; + } + + + /** + Statically concatenates this tuple type with another tuple type + */ + template concatT(T ...) { + static if (expressionTuple) { + alias .Tuple!(value, T) concatT; + } else { + alias .Tuple!(type, T) concatT; + } + } + + + string toString() { + auto res = "(" ~ stdFormat(value[0]); + foreach (x; value[1..$]) { + res ~= stdFormat(", ", x); + } + return res ~ ")"; + } } /** - An empty tuple struct + An empty tuple struct */ struct Tuple() { - alias Tuple meta; + alias Tuple meta; - template EmptyTuple_(T ...) { - alias T EmptyTuple_; - } - - - alias EmptyTuple_!() type; /// an empty built-in tuple - alias EmptyTuple_!() value; /// an empty built-in tuple - - const bool expressionTuple = false; - const int length = 0; + template EmptyTuple_(T ...) { + alias T EmptyTuple_; + } - template appendT(X) { - alias .Tuple!(X) appendT; - } - alias appendT prependT; + alias EmptyTuple_!() type; /// an empty built-in tuple + alias EmptyTuple_!() value; /// an empty built-in tuple + + const bool expressionTuple = false; + const int length = 0; - appendT!(X) append(X)(X x) { - appendT!(X) res; - foreach (i, y; value) { - _assign!(typeof(y))(res.value[i], y); - } - return res; - } - alias append prepend; - - - // T - other tuple - template concatT(T ...) { - alias .Tuple!(T) concatT; - } - - - char[] toString() { - return "()"; - } + template appendT(X) { + alias .Tuple!(X) appendT; + } + alias appendT prependT; + + + appendT!(X) append(X)(X x) { + appendT!(X) res; + foreach (i, y; value) { + _assign!(typeof(y))(res.value[i], y); + } + return res; + } + alias append prepend; + + + // T - other tuple + template concatT(T ...) { + alias .Tuple!(T) concatT; + } + + + char[] toString() { + return "()"; + } } /** - Dynamically create a tuple from the given items + Dynamically create a tuple from the given items */ Tuple!(T) tuple(T ...)(T t) { - Tuple!(T) res; - foreach (i, x; t) { - _assign!(typeof(x))(res.value[i], x); - } - return res; + Tuple!(T) res; + foreach (i, x; t) { + _assign!(typeof(x))(res.value[i], x); + } + return res; } /** - Checks whether a given type is the Tuple struct of any length + Checks whether a given type is the Tuple struct of any length */ template isTypeTuple(T) { - static if (is(T.type)) { - static if (is(T == Tuple!(T.type))) { - const bool isTypeTuple = true; - } else const bool isTypeTuple = false; - } else const bool isTypeTuple = false; + static if (is(T.type)) { + static if (is(T == Tuple!(T.type))) { + const bool isTypeTuple = true; + } else const bool isTypeTuple = false; + } else const bool isTypeTuple = false; } static assert(isTypeTuple!(Tuple!(int))); @@ -303,354 +303,354 @@ static assert(!isTypeTuple!(int)); template minNumArgs_impl(alias fn, fnT) { - alias ParameterTypeTuple!(fnT) Params; - Params params = void; - - template loop(int i = 0) { - static assert (i <= Params.length); - - static if (is(typeof(fn(params[0..i])))) { - const int res = i; - } else { - alias loop!(i+1).res res; - } - } - - alias loop!().res res; + alias ParameterTypeTuple!(fnT) Params; + Params params = void; + + template loop(int i = 0) { + static assert (i <= Params.length); + + static if (is(typeof(fn(params[0..i])))) { + const int res = i; + } else { + alias loop!(i+1).res res; + } + } + + alias loop!().res res; } /** - Finds the minimal number of arguments a given function needs to be provided + Finds the minimal number of arguments a given function needs to be provided */ template minNumArgs(alias fn, fnT = typeof(&fn)) { - const int minNumArgs = minNumArgs_impl!(fn, fnT).res; + const int minNumArgs = minNumArgs_impl!(fn, fnT).res; } // mixed into BoundFunc struct/class template MBoundFunc() { - // meta - alias FAlias_ FAlias; - alias FT FuncType; - alias AllBoundArgs_ AllBoundArgs; // all arguments given to bind() or bindAlias() - - static if (!is(typeof(FAlias) == EmptySlot)) { - alias Tuple!(ParameterTypeTuple!(FT)) RealFuncParams; // the parameters of the bound function - alias FuncReferenceParamsAsPointers!(FAlias) FuncParams; // references converted to pointers - } else { - alias Tuple!(ParameterTypeTuple!(FT)) FuncParams; // the parameters of the bound function - } - - alias ReturnType!(FT) RetType; // the return type of the bound function - alias ExtractedBoundArgs!(AllBoundArgs.type) BoundArgs; // 'saved' arguments. this includes nested/composed functions - - - // if bindAlias was used, we can detect default arguments and only demand the non-default arguments to be specified - static if (!is(typeof(FAlias) == EmptySlot)) { - const int minFuncArgs = minNumArgs!(FAlias); - - alias ParamsPassMethodTuple!(FAlias) ParamPassingMethods; // find out whether the function expects parameters by value or reference - } else { - const int minFuncArgs = FuncParams.length; - } - - // the parameters that our wrapper function must get - alias getDynArgTypes!(FuncParams, AllBoundArgs, minFuncArgs).res.type DynParams; - - // data - FuncType fp; - BoundArgs boundArgs; + // meta + alias FAlias_ FAlias; + alias FT FuncType; + alias AllBoundArgs_ AllBoundArgs; // all arguments given to bind() or bindAlias() - // yields the number of bound-function parameters that are covered by the binding. takes tuple expansion into account - template numFuncArgsReallyBound(int argI = 0, int fargI = 0, int bargI = 0) { - - // walk though all of AllBoundArgs - static if (argI < AllBoundArgs.length) { - - // the argI-th arg is a composed/nested function - static if (isBoundFunc!(AllBoundArgs.type[argI])) { - alias DerefFunc!(AllBoundArgs.type[argI]).RetType FuncRetType; - const int argLen = getArgLen!(FuncParams.type[fargI], FuncRetType); - const int bargInc = 1; - } - - // the argI-th arg is a dynamic argument whose value we will get in the call to func() - else static if (isDynArg!(AllBoundArgs.type[argI])) { - const int argLen = getArgLen!(FuncParams.type[fargI], DynParams[AllBoundArgs.type[argI].argNr]); - const int bargInc = 0; - } - - // the argI-th arg is a statically bound argument - else { - const int argLen = getArgLen!(FuncParams.type[fargI], BoundArgs.type[bargI]); - const int bargInc = 1; - } - - // iterate - const int res = numFuncArgsReallyBound!(argI+1, fargI+argLen, bargI+bargInc).res; - } else { - // last iteration - - // the number of bound args is the number of arguments we've detected in this template loop - const int res = fargI; + static if (!is(typeof(FAlias) == EmptySlot)) { + alias Tuple!(ParameterTypeTuple!(FT)) RealFuncParams; // the parameters of the bound function + alias FuncReferenceParamsAsPointers!(FAlias) FuncParams; // references converted to pointers + } else { + alias Tuple!(ParameterTypeTuple!(FT)) FuncParams; // the parameters of the bound function + } - // make sure we'll copy all args the function is going to need - static assert (res >= minFuncArgs); - } - } - - const int numSpecifiedParams = numFuncArgsReallyBound!().res; - - // it's a tuple type whose instance will be applied to the bound function - alias Tuple!(FuncParams.type[0 .. numSpecifiedParams]) SpecifiedParams; - - - // argI = indexes AllBoundArgs - // fargI = indexes funcArgs - // bargI = indexes boundArgs - void copyArgs(int argI = 0, int fargI = 0, int bargI = 0)(inout SpecifiedParams funcArgs, DynParams dynArgs) { - static if (argI < AllBoundArgs.length) { - - // the argI-th arg is a composed/nested function - static if (isBoundFunc!(AllBoundArgs.type[argI])) { - alias DerefFunc!(AllBoundArgs.type[argI]).RetType FuncRetType; - alias DerefFunc!(AllBoundArgs.type[argI]).DynParams FuncDynParams; - - // if FuncDynParams contains an empty slot, e.g. as in the case bind(&f, bind(&g, _1), _0) - // then we cannot just apply the dynArgs tuple to the nested/composed function because it will have EmptySlot params - // while our dynArgs tuple will contain ordinary types - static if (ContainsEmptySlotType!(FuncDynParams)) { - - FuncDynParams funcParams; // we'll fill it with values in a bit - - foreach (i, dummy_; dynArgs) { - static if (!is(typeof(FuncDynParams[i] == EmptySlot))) { - - // 3rd param is false because there is no need to .dup static arrays just for the function below this foreach - // the storage exists in the whole copyArgs function - // dynArgs[i] is used instead of dummy_ so that loop-local data isn't referenced in any dynamic arrays after the loop - _assign!(typeof(funcParams[i]), typeof(dummy_), false)(funcParams[i], dynArgs[i]); - } - } - - FuncRetType funcRet = boundArgs.value[bargI].func(funcParams); - } else { - FuncRetType funcRet = boundArgs.value[bargI].func(dynArgs[0..FuncDynParams.length]); // only give it as many dynParams as it needs - } - - // we'll take data from the returned value - auto srcItem = &funcRet; - - const int bargInc = 1; // nested/composed functions belong to the boundArgs tuple - const bool dupStaticArrays = true; // because the function's return value is stored locally - } - - // the argI-th arg is a dynamic argument whose value we will get in the call to func() - else static if (isDynArg!(AllBoundArgs.type[argI])) { - - // we'll take data from dynArgs - auto srcItem = &dynArgs[AllBoundArgs.type[argI].argNr]; - - const int bargInc = 0; // dynamic args don't belond to the boundArgs tuple - const bool dupStaticArrays = true; // because we get dynArgs on stack - } - - // the argI-th arg is a statically bound argument - else { - - // we'll take data directly from boundArgs - auto srcItem = &boundArgs.value[bargI]; - - const int bargInc = 1; // statically bound args belong to the boundArgs tuple - const bool dupStaticArrays = false; // because the storage exists in boundArgs - } - - // the number of bound-function parameters this argument will cover after tuple expansion - const int argLen = getArgLen!(funcArgs.type[fargI], typeof(*srcItem)); - - static if (isTypeTuple!(typeof(*srcItem)) && !isTypeTuple!(funcArgs.type[fargI])) { - foreach (i, x; srcItem.value) { - _assign!(funcArgs.type[fargI + i], typeof(x), dupStaticArrays)(funcArgs.value[fargI + i], x); - } - } else { - static assert (1 == argLen); - _assign!(funcArgs.type[fargI], typeof(*srcItem), dupStaticArrays)(funcArgs.value[fargI], *srcItem); - } - - // because we might've just expended a tuple, this may be larger than one - static assert (argLen >= 1); - - // we could've just used a dynamic arg (0) or a statically bound arg(1) - static assert (bargInc == 0 || bargInc == 1); - - - return copyArgs!(argI+1, fargI+argLen, bargI+bargInc)(funcArgs, dynArgs); - } else { - // last iteration - - // make sure we've copied all args the function will need - static assert (fargI >= minFuncArgs); - } - } + alias ReturnType!(FT) RetType; // the return type of the bound function + alias ExtractedBoundArgs!(AllBoundArgs.type) BoundArgs; // 'saved' arguments. this includes nested/composed functions - static if (SpecifiedParams.length > 0) { - /// The final wrapped function - RetType func(DynParams dynArgs) { - SpecifiedParams funcArgs; - copyArgs!()(funcArgs, dynArgs); - - // if the function expects any parameters passed by reference, we'll have to use the ptrApply template - // and convert pointers back to references by hand - static if (!is(typeof(FAlias) == EmptySlot) && IndexOf!(PassByRef, ParamPassingMethods.type) != -1) { - - // function parameter type pointers (int, float*, inout char) -> (int*, float*, char*) - PointerTuple!(Tuple!(RealFuncParams.type[0 .. SpecifiedParams.length])) ptrs; - - // initialize the 'ptrs' tuple instance - foreach (i, dummy_; funcArgs.value) { - static if (is(ParamPassingMethods.type[i] == PassByRef)) { - - version (BindNoNullCheck) {} - else { - assert (funcArgs.value[i], "references cannot be null"); - } - - ptrs.value[i] = funcArgs.value[i]; - } else { - ptrs.value[i] = &funcArgs.value[i]; - } - } - - // and call the function :) - ptrApply!(RetType, FuncType, ptrs.type)(fp, ptrs.value); - } else { - - // ordinary call-by-tuple - return fp(funcArgs.value); - } - } - } else { - /// The final wrapped function - RetType func() { - return fp(); - } - } - - /// The final wrapped function - alias func call; - - - /// The final wrapped function - alias func opCall; - - - /** - The type of the delegate that may be returned from this object - */ - template PtrType() { - alias typeof(&(new BoundFunc).call) PtrType; - } - - /** - Get a delegate. Equivalent to getting it thru &foo.call - */ - PtrType!() ptr() { - return &this.func; - } + // if bindAlias was used, we can detect default arguments and only demand the non-default arguments to be specified + static if (!is(typeof(FAlias) == EmptySlot)) { + const int minFuncArgs = minNumArgs!(FAlias); + + alias ParamsPassMethodTuple!(FAlias) ParamPassingMethods; // find out whether the function expects parameters by value or reference + } else { + const int minFuncArgs = FuncParams.length; + } + + // the parameters that our wrapper function must get + alias getDynArgTypes!(FuncParams, AllBoundArgs, minFuncArgs).res.type DynParams; + + // data + FuncType fp; + BoundArgs boundArgs; + + // yields the number of bound-function parameters that are covered by the binding. takes tuple expansion into account + template numFuncArgsReallyBound(int argI = 0, int fargI = 0, int bargI = 0) { + + // walk though all of AllBoundArgs + static if (argI < AllBoundArgs.length) { + + // the argI-th arg is a composed/nested function + static if (isBoundFunc!(AllBoundArgs.type[argI])) { + alias DerefFunc!(AllBoundArgs.type[argI]).RetType FuncRetType; + const int argLen = getArgLen!(FuncParams.type[fargI], FuncRetType); + const int bargInc = 1; + } + + // the argI-th arg is a dynamic argument whose value we will get in the call to func() + else static if (isDynArg!(AllBoundArgs.type[argI])) { + const int argLen = getArgLen!(FuncParams.type[fargI], DynParams[AllBoundArgs.type[argI].argNr]); + const int bargInc = 0; + } + + // the argI-th arg is a statically bound argument + else { + const int argLen = getArgLen!(FuncParams.type[fargI], BoundArgs.type[bargI]); + const int bargInc = 1; + } + + // iterate + const int res = numFuncArgsReallyBound!(argI+1, fargI+argLen, bargI+bargInc).res; + } else { + // last iteration + + // the number of bound args is the number of arguments we've detected in this template loop + const int res = fargI; + + // make sure we'll copy all args the function is going to need + static assert (res >= minFuncArgs); + } + } + + const int numSpecifiedParams = numFuncArgsReallyBound!().res; + + // it's a tuple type whose instance will be applied to the bound function + alias Tuple!(FuncParams.type[0 .. numSpecifiedParams]) SpecifiedParams; + + + // argI = indexes AllBoundArgs + // fargI = indexes funcArgs + // bargI = indexes boundArgs + void copyArgs(int argI = 0, int fargI = 0, int bargI = 0)(inout SpecifiedParams funcArgs, DynParams dynArgs) { + static if (argI < AllBoundArgs.length) { + + // the argI-th arg is a composed/nested function + static if (isBoundFunc!(AllBoundArgs.type[argI])) { + alias DerefFunc!(AllBoundArgs.type[argI]).RetType FuncRetType; + alias DerefFunc!(AllBoundArgs.type[argI]).DynParams FuncDynParams; + + // if FuncDynParams contains an empty slot, e.g. as in the case bind(&f, bind(&g, _1), _0) + // then we cannot just apply the dynArgs tuple to the nested/composed function because it will have EmptySlot params + // while our dynArgs tuple will contain ordinary types + static if (ContainsEmptySlotType!(FuncDynParams)) { + + FuncDynParams funcParams; // we'll fill it with values in a bit + + foreach (i, dummy_; dynArgs) { + static if (!is(typeof(FuncDynParams[i] == EmptySlot))) { + + // 3rd param is false because there is no need to .dup static arrays just for the function below this foreach + // the storage exists in the whole copyArgs function + // dynArgs[i] is used instead of dummy_ so that loop-local data isn't referenced in any dynamic arrays after the loop + _assign!(typeof(funcParams[i]), typeof(dummy_), false)(funcParams[i], dynArgs[i]); + } + } + + FuncRetType funcRet = boundArgs.value[bargI].func(funcParams); + } else { + FuncRetType funcRet = boundArgs.value[bargI].func(dynArgs[0..FuncDynParams.length]); // only give it as many dynParams as it needs + } + + // we'll take data from the returned value + auto srcItem = &funcRet; + + const int bargInc = 1; // nested/composed functions belong to the boundArgs tuple + const bool dupStaticArrays = true; // because the function's return value is stored locally + } + + // the argI-th arg is a dynamic argument whose value we will get in the call to func() + else static if (isDynArg!(AllBoundArgs.type[argI])) { + + // we'll take data from dynArgs + auto srcItem = &dynArgs[AllBoundArgs.type[argI].argNr]; + + const int bargInc = 0; // dynamic args don't belond to the boundArgs tuple + const bool dupStaticArrays = true; // because we get dynArgs on stack + } + + // the argI-th arg is a statically bound argument + else { + + // we'll take data directly from boundArgs + auto srcItem = &boundArgs.value[bargI]; + + const int bargInc = 1; // statically bound args belong to the boundArgs tuple + const bool dupStaticArrays = false; // because the storage exists in boundArgs + } + + // the number of bound-function parameters this argument will cover after tuple expansion + const int argLen = getArgLen!(funcArgs.type[fargI], typeof(*srcItem)); + + static if (isTypeTuple!(typeof(*srcItem)) && !isTypeTuple!(funcArgs.type[fargI])) { + foreach (i, x; srcItem.value) { + _assign!(funcArgs.type[fargI + i], typeof(x), dupStaticArrays)(funcArgs.value[fargI + i], x); + } + } else { + static assert (1 == argLen); + _assign!(funcArgs.type[fargI], typeof(*srcItem), dupStaticArrays)(funcArgs.value[fargI], *srcItem); + } + + // because we might've just expended a tuple, this may be larger than one + static assert (argLen >= 1); + + // we could've just used a dynamic arg (0) or a statically bound arg(1) + static assert (bargInc == 0 || bargInc == 1); + + + return copyArgs!(argI+1, fargI+argLen, bargI+bargInc)(funcArgs, dynArgs); + } else { + // last iteration + + // make sure we've copied all args the function will need + static assert (fargI >= minFuncArgs); + } + } + + + static if (SpecifiedParams.length > 0) { + /// The final wrapped function + RetType func(DynParams dynArgs) { + SpecifiedParams funcArgs; + copyArgs!()(funcArgs, dynArgs); + + // if the function expects any parameters passed by reference, we'll have to use the ptrApply template + // and convert pointers back to references by hand + static if (!is(typeof(FAlias) == EmptySlot) && IndexOf!(PassByRef, ParamPassingMethods.type) != -1) { + + // function parameter type pointers (int, float*, inout char) -> (int*, float*, char*) + PointerTuple!(Tuple!(RealFuncParams.type[0 .. SpecifiedParams.length])) ptrs; + + // initialize the 'ptrs' tuple instance + foreach (i, dummy_; funcArgs.value) { + static if (is(ParamPassingMethods.type[i] == PassByRef)) { + + version (BindNoNullCheck) {} + else { + assert (funcArgs.value[i], "references cannot be null"); + } + + ptrs.value[i] = funcArgs.value[i]; + } else { + ptrs.value[i] = &funcArgs.value[i]; + } + } + + // and call the function :) + ptrApply!(RetType, FuncType, ptrs.type)(fp, ptrs.value); + } else { + + // ordinary call-by-tuple + return fp(funcArgs.value); + } + } + } else { + /// The final wrapped function + RetType func() { + return fp(); + } + } + + /// The final wrapped function + alias func call; + + + /// The final wrapped function + alias func opCall; + + + /** + The type of the delegate that may be returned from this object + */ + template PtrType() { + alias typeof(&(new BoundFunc).call) PtrType; + } + + /** + Get a delegate. Equivalent to getting it thru &foo.call + */ + PtrType!() ptr() { + return &this.func; + } } version (BindUseStruct) { - template DerefFunc(T) { - alias typeof(*T) DerefFunc; - } + template DerefFunc(T) { + alias typeof(*T) DerefFunc; + } - /** - A context for bound/curried functions - */ - struct BoundFunc(FT, alias FAlias_, AllBoundArgs_) { - mixin MBoundFunc; - } + /** + A context for bound/curried functions + */ + struct BoundFunc(FT, alias FAlias_, AllBoundArgs_) { + mixin MBoundFunc; + } } else { - template DerefFunc(T) { - alias T DerefFunc; - } + template DerefFunc(T) { + alias T DerefFunc; + } - /** - A context for bound/curried functions - */ - class BoundFunc(FT, alias FAlias_, AllBoundArgs_) { - mixin MBoundFunc; - } + /** + A context for bound/curried functions + */ + class BoundFunc(FT, alias FAlias_, AllBoundArgs_) { + mixin MBoundFunc; + } } /** - bind() can curry or "bind" arguments of a function, producing a different function which requires less parameters, - or a different order of parameters. It also allows function composition. - - The syntax of a bind() call is: - - bind(function or delegate pointer { , argument }); - - argument can be one of: - - - The result is a function object, which can be called using call(), func() or opCall(). - There also exists a convenience function, ptr() which returns a delegate to call/func/opCall - - The resulting delegate accepts exactly as many parameters as many distinct dynamic arguments were used. + bind() can curry or "bind" arguments of a function, producing a different function which requires less parameters, + or a different order of parameters. It also allows function composition. + + The syntax of a bind() call is: + + bind(function or delegate pointer { , argument }); + + argument can be one of: + + + The result is a function object, which can be called using call(), func() or opCall(). + There also exists a convenience function, ptr() which returns a delegate to call/func/opCall + + The resulting delegate accepts exactly as many parameters as many distinct dynamic arguments were used. --- - bind(&foo, _0, _1) // will yield a delegate accepting two parameters - bind(&foo, _1, _0) // will yield a delegate accepting two parameters - bind(&bar, _0, _1, _2, _0) // will yield a delegate accepting three parameters --- - -
-
- The types of dynamic parameters are extracted from the bound function itself and when necessary, type negotiation - is performed. For example, binding a function + +
+
+ The types of dynamic parameters are extracted from the bound function itself and when necessary, type negotiation + is performed. For example, binding a function --- void foo(int a, long b) // with: bind(&foo, _0, _0) --- - will result in a delegate accepting a single, optimal parameter type. The best type is computed - using std.typetuple.DerivedToFront, so in case of an int and a long, long will be selected. Generally, bind will try to find - a type that can be implicitly converted to all the other types a given dynamic parameter uses. - Note: in case of numeric types, an explicit, but transparent (to the user) cast will be performed - -
- Function composition works intuitively: + will result in a delegate accepting a single, optimal parameter type. The best type is computed + using std.typetuple.DerivedToFront, so in case of an int and a long, long will be selected. Generally, bind will try to find + a type that can be implicitly converted to all the other types a given dynamic parameter uses. + Note: in case of numeric types, an explicit, but transparent (to the user) cast will be performed + +
+ Function composition works intuitively: --- bind(&f1, bind(&f2, _0)) --- - - which will yield a delegate, that takes the argument, calls f2, then uses the return value of f2 to call f1. Mathematically - speaking, it will yield a function composition: + + which will yield a delegate, that takes the argument, calls f2, then uses the return value of f2 to call f1. Mathematically + speaking, it will yield a function composition: --- f1(f2(_0)) --- - - When one function is composed multiple times, it will be called multiple times - Bind does no lazy evaluation, so + + When one function is composed multiple times, it will be called multiple times - Bind does no lazy evaluation, so --- bind(&f3, bind(&f4, _0), bind(&f4, _0)) --- - will produce a delegate, which, upon calling, will invoke f4 two times to evaluate the arguments for f3 and then call f3 - - - One another feature that bind() supports is automatic tuple expansion. It means that having functions: + will produce a delegate, which, upon calling, will invoke f4 two times to evaluate the arguments for f3 and then call f3 + + + One another feature that bind() supports is automatic tuple expansion. It means that having functions: --- void foo(int a, int b) Tuple!(int, int) bar() --- - - Allows them to be bound by writing: + + Allows them to be bound by writing: --- bind(&foo, bind(&bar)) // or @@ -658,45 +658,45 @@ bind(&foo, tuple(23, 45)) --- */ typeof(new BoundFunc!(FT, NullAlias, Tuple!(ArgList))) bind(FT, ArgList...)(FT fp, ArgList args) { - auto res = new DerefFunc!(ReturnType!(bind)); - res.fp = fp; - extractBoundArgs!(0, 0, ArgList)(res.boundArgs, args); - return res; + auto res = new DerefFunc!(ReturnType!(bind)); + res.fp = fp; + extractBoundArgs!(0, 0, ArgList)(res.boundArgs, args); + return res; } /** - bindAlias() is similar to bind(), but it's more powerful. Use bindAlias() rather than bind() where possible.
+ bindAlias() is similar to bind(), but it's more powerful. Use bindAlias() rather than bind() where possible.
- The syntax is: - - bindAlias!(Function)(argument, argument, argument, argument, ...); - - bindAlias takes advantage of using aliases directly, thus being able to extract default values from functions and not forcing the user - to bind them. It doesn't, however mean that the resulting delegate can be called, omitting some of its parameters. It only means that these - arguments that have default values in the function provided to bindAlias don't have to be bound explicitly. - - Additionally, bindAlias takes care of functions with out/inout parameters, by converting them to pointers internally. A function like: + The syntax is: + + bindAlias!(Function)(argument, argument, argument, argument, ...); + + bindAlias takes advantage of using aliases directly, thus being able to extract default values from functions and not forcing the user + to bind them. It doesn't, however mean that the resulting delegate can be called, omitting some of its parameters. It only means that these + arguments that have default values in the function provided to bindAlias don't have to be bound explicitly. + + Additionally, bindAlias takes care of functions with out/inout parameters, by converting them to pointers internally. A function like: --- void foo(inout a) ---- - can be bound using: +--- + can be bound using: --- int x; bindAlias!(foo)(&x); --- - - Note: there is no bind-time check for reference nullness, there is however a call-time check on all references which can be disabled - by using version=BindNoNullCheck or compiling in release mode. + + Note: there is no bind-time check for reference nullness, there is however a call-time check on all references which can be disabled + by using version=BindNoNullCheck or compiling in release mode. */ template bindAlias(alias FT) { - typeof(new BoundFunc!(typeof(&FT), FT, Tuple!(ArgList))) bindAlias(ArgList...)(ArgList args) { - auto res = new DerefFunc!(ReturnType!(bindAlias)); - res.fp = &FT; - extractBoundArgs!(0, 0, ArgList)(res.boundArgs, args); - return res; - } + typeof(new BoundFunc!(typeof(&FT), FT, Tuple!(ArgList))) bindAlias(ArgList...)(ArgList args) { + auto res = new DerefFunc!(ReturnType!(bindAlias)); + res.fp = &FT; + extractBoundArgs!(0, 0, ArgList)(res.boundArgs, args); + return res; + } } @@ -704,18 +704,18 @@ template bindAlias(alias FT) { /* - Tells whether the specified type is a bound function + Tells whether the specified type is a bound function */ template isBoundFunc(T) { - static if (is(DerefFunc!(T).FuncType)) { - static if (is(DerefFunc!(T).BoundArgs)) { - static if (is(typeof(DerefFunc!(T).FAlias))) { - static if (is(DerefFunc!(T) : BoundFunc!(DerefFunc!(T).FuncType, DerefFunc!(T).FAlias, DerefFunc!(T).AllBoundArgs))) { - static const bool isBoundFunc = true; - } else static const bool isBoundFunc = false; - } else static const bool isBoundFunc = false; - } else static const bool isBoundFunc = false; - } else static const bool isBoundFunc = false; + static if (is(DerefFunc!(T).FuncType)) { + static if (is(DerefFunc!(T).BoundArgs)) { + static if (is(typeof(DerefFunc!(T).FAlias))) { + static if (is(DerefFunc!(T) : BoundFunc!(DerefFunc!(T).FuncType, DerefFunc!(T).FAlias, DerefFunc!(T).AllBoundArgs))) { + static const bool isBoundFunc = true; + } else static const bool isBoundFunc = false; + } else static const bool isBoundFunc = false; + } else static const bool isBoundFunc = false; + } else static const bool isBoundFunc = false; } @@ -725,216 +725,216 @@ alias Tuple!(byte, ubyte, short, ushort, int, uint, long, ulong, /+cent, ucent, /* - Gather all types that a given (i-th) dynamic arg uses. - The types will be inserted into a tuple + Gather all types that a given (i-th) dynamic arg uses. + The types will be inserted into a tuple */ template dynArgTypes(int i, FuncParams, BoundArgs, int minParamsLeft) { - - // performs slicing on the tuple ... tuple[i .. length] - template sliceOffTuple(T, int i) { - alias Tuple!(T.type[i..length]) res; - } - - // prepends a T to the resulting tuple - // SkipType - the type in BoundArgs that we're just processing - template prependType(T, SkipType) { - static if (isTypeTuple!(SkipType) && !isTypeTuple!(FuncParams.type[0])) { - // perform tuple decomposition - // e.g. if a function being bound is accepting (int, int) and the current type is a Tuple!(int, int), - // then skip just one tuple in the bound args and the length of the tuple in func args - // - skips two ints and one tuple in the example - alias dynArgTypes!( - i, - sliceOffTuple!(FuncParams, SkipType.length).res, - Tuple!(BoundArgs.type[1..$]), - minParamsLeft - SkipType.length - ).res tmp; - - } else { - // just advance by one type - alias dynArgTypes!( - i, - sliceOffTuple!(FuncParams, 1).res, - Tuple!(BoundArgs.type[1..$]), - minParamsLeft-1 - ).res tmp; - } - - static if (is(T == void)) { // void means that we aren't adding anything - alias tmp res; - } else { - alias tmp.meta.prependT!(T) res; - } - } - - // iteration end detector - static if (is(BoundArgs == Tuple!())) { - static assert (minParamsLeft <= 0, "there are still unbound function parameters"); - alias Tuple!() res; - } - else { - - // w00t, detected a regular dynamic arg - static if (isDynArg!(BoundArgs.type[0], i)) { - alias prependType!(FuncParams.type[0], BoundArgs.type[0]).res res; - } - - // the arg is a bound function, extract info from it. we will be evaluating it later - else static if (isBoundFunc!(BoundArgs.type[0])) { - alias DerefFunc!(BoundArgs.type[0]) BoundFunc; // the bound function is a struct pointer, we have to derefernce its type - - // does that function even have any dynamic params ? - static if (BoundFunc.DynParams.length > i) { - alias prependType!(BoundFunc.DynParams[i], BoundFunc.RetType).res res; - } - // it doesn't - else { - alias prependType!(void, BoundFunc.RetType).res res; - } - } - - // a static arg, just skip it since we want to find all types a given DynArg uses. static args <> dyn args - else alias prependType!(void, BoundArgs.type[0]).res res; - } + + // performs slicing on the tuple ... tuple[i .. length] + template sliceOffTuple(T, int i) { + alias Tuple!(T.type[i..length]) res; + } + + // prepends a T to the resulting tuple + // SkipType - the type in BoundArgs that we're just processing + template prependType(T, SkipType) { + static if (isTypeTuple!(SkipType) && !isTypeTuple!(FuncParams.type[0])) { + // perform tuple decomposition + // e.g. if a function being bound is accepting (int, int) and the current type is a Tuple!(int, int), + // then skip just one tuple in the bound args and the length of the tuple in func args + // - skips two ints and one tuple in the example + alias dynArgTypes!( + i, + sliceOffTuple!(FuncParams, SkipType.length).res, + Tuple!(BoundArgs.type[1..$]), + minParamsLeft - SkipType.length + ).res tmp; + + } else { + // just advance by one type + alias dynArgTypes!( + i, + sliceOffTuple!(FuncParams, 1).res, + Tuple!(BoundArgs.type[1..$]), + minParamsLeft-1 + ).res tmp; + } + + static if (is(T == void)) { // void means that we aren't adding anything + alias tmp res; + } else { + alias tmp.meta.prependT!(T) res; + } + } + + // iteration end detector + static if (is(BoundArgs == Tuple!())) { + static assert (minParamsLeft <= 0, "there are still unbound function parameters"); + alias Tuple!() res; + } + else { + + // w00t, detected a regular dynamic arg + static if (isDynArg!(BoundArgs.type[0], i)) { + alias prependType!(FuncParams.type[0], BoundArgs.type[0]).res res; + } + + // the arg is a bound function, extract info from it. we will be evaluating it later + else static if (isBoundFunc!(BoundArgs.type[0])) { + alias DerefFunc!(BoundArgs.type[0]) BoundFunc; // the bound function is a struct pointer, we have to derefernce its type + + // does that function even have any dynamic params ? + static if (BoundFunc.DynParams.length > i) { + alias prependType!(BoundFunc.DynParams[i], BoundFunc.RetType).res res; + } + // it doesn't + else { + alias prependType!(void, BoundFunc.RetType).res res; + } + } + + // a static arg, just skip it since we want to find all types a given DynArg uses. static args <> dyn args + else alias prependType!(void, BoundArgs.type[0]).res res; + } } // just a simple util private template maxInt(int a, int b) { - static if (a > b) static const int maxInt = a; - else static const int maxInt = b; + static if (a > b) static const int maxInt = a; + else static const int maxInt = b; } /* - Given a list of BoundArgs, it returns the nuber of args that should be specified dynamically + Given a list of BoundArgs, it returns the nuber of args that should be specified dynamically */ template numDynArgs(BoundArgs) { - static if (BoundArgs.length == 0) { - // received an EmptyTuple - static const int res = 0; - } else { - // ordinary dynamic arg - static if (isDynArg!(BoundArgs.type[0])) { - static const int res = maxInt!(BoundArgs.type[0].argNr+1, numDynArgs!(Tuple!(BoundArgs.type[1..$])).res); - } - - // count the args in nested / composed functions - else static if (isBoundFunc!(BoundArgs.type[0])) { - static const int res = maxInt!(DerefFunc!(BoundArgs.type[0]).DynParams.length, numDynArgs!(Tuple!(BoundArgs.type[1..$])).res); - } - - // statically bound arg, skip it - else { - static const int res = numDynArgs!(Tuple!(BoundArgs.type[1..$])).res; - } - } + static if (BoundArgs.length == 0) { + // received an EmptyTuple + static const int res = 0; + } else { + // ordinary dynamic arg + static if (isDynArg!(BoundArgs.type[0])) { + static const int res = maxInt!(BoundArgs.type[0].argNr+1, numDynArgs!(Tuple!(BoundArgs.type[1..$])).res); + } + + // count the args in nested / composed functions + else static if (isBoundFunc!(BoundArgs.type[0])) { + static const int res = maxInt!(DerefFunc!(BoundArgs.type[0]).DynParams.length, numDynArgs!(Tuple!(BoundArgs.type[1..$])).res); + } + + // statically bound arg, skip it + else { + static const int res = numDynArgs!(Tuple!(BoundArgs.type[1..$])).res; + } + } } /* - Used internally to mark a parameter which is a dummy placeholder - E.g. when using bind(&f, bind(&g, _1), _0), then the inner bound function will use an EmptySlot for its 0-th parameter + Used internally to mark a parameter which is a dummy placeholder + E.g. when using bind(&f, bind(&g, _1), _0), then the inner bound function will use an EmptySlot for its 0-th parameter */ struct EmptySlot { - string toString( ) { - return "_"; - } + string toString( ) { + return "_"; + } } /* - Get a tuple of all dynamic args a function binding will need - take nested/composed functions as well as tuple decomposition into account + Get a tuple of all dynamic args a function binding will need + take nested/composed functions as well as tuple decomposition into account */ template getDynArgTypes(FuncParams, BoundArgs, int minFuncArgs) { - template loop(int i) { - static if (i < numDynArgs!(BoundArgs).res) { - alias dynArgTypes!(i, FuncParams, BoundArgs, minFuncArgs).res.type dirtyArgTypeList; - - // 'clean' the type list, erasing all NoTypes from it that could've been added there from composed functions - // if the arg is not used, we'll mark it as NoType anyway, but for now, we only want 'real' types so the most derived one can be found - alias Tuple!(EraseAll!(EmptySlot, dirtyArgTypeList)) argTypeList; - - - // make sure the arg is used - static if(!is(argTypeList == Tuple!())) { - alias DerivedToFront!(argTypeList.type)[0] argType; - } else { - //static assert(false, i); - alias EmptySlot argType; - } + template loop(int i) { + static if (i < numDynArgs!(BoundArgs).res) { + alias dynArgTypes!(i, FuncParams, BoundArgs, minFuncArgs).res.type dirtyArgTypeList; - alias loop!(i+1).res.meta.prependT!(argType) res; - } else { - alias Tuple!() res; - } - } - - alias loop!(0).res res; + // 'clean' the type list, erasing all NoTypes from it that could've been added there from composed functions + // if the arg is not used, we'll mark it as NoType anyway, but for now, we only want 'real' types so the most derived one can be found + alias Tuple!(EraseAll!(EmptySlot, dirtyArgTypeList)) argTypeList; + + + // make sure the arg is used + static if(!is(argTypeList == Tuple!())) { + alias DerivedToFront!(argTypeList.type)[0] argType; + } else { + //static assert(false, i); + alias EmptySlot argType; + } + + alias loop!(i+1).res.meta.prependT!(argType) res; + } else { + alias Tuple!() res; + } + } + + alias loop!(0).res res; } /* - Given a tuple that bind() was called with, it will detect which types need to be stored in a BoundFunc object + Given a tuple that bind() was called with, it will detect which types need to be stored in a BoundFunc object */ template ExtractedBoundArgs(BoundArgs ...) { - static if (BoundArgs.length == 0) { - alias Tuple!() ExtractedBoundArgs; - } - - // we'll store all non-dynamic arguments... - else static if (!isDynArg!(BoundArgs[0])) { - alias ExtractedBoundArgs!(BoundArgs[1..$]).meta.prependT!(BoundArgs[0]) ExtractedBoundArgs; - } - - // ... and we're going to leave the dynamic ones for later - else { - alias ExtractedBoundArgs!(BoundArgs[1..$]) ExtractedBoundArgs; - } + static if (BoundArgs.length == 0) { + alias Tuple!() ExtractedBoundArgs; + } + + // we'll store all non-dynamic arguments... + else static if (!isDynArg!(BoundArgs[0])) { + alias ExtractedBoundArgs!(BoundArgs[1..$]).meta.prependT!(BoundArgs[0]) ExtractedBoundArgs; + } + + // ... and we're going to leave the dynamic ones for later + else { + alias ExtractedBoundArgs!(BoundArgs[1..$]) ExtractedBoundArgs; + } } /* - Given a tuple that bind() was called with, it will copy all data that a BoundFunc object will store into an ExtractedBoundArgs tuple + Given a tuple that bind() was called with, it will copy all data that a BoundFunc object will store into an ExtractedBoundArgs tuple */ void extractBoundArgs(int dst, int src, BoundArgs ...)(inout ExtractedBoundArgs!(BoundArgs) result, BoundArgs boundArgs) { - static if (dst < result.length) { - // again, we only want non-dynamic arguments here - static if (!isDynArg!(BoundArgs[src])) { - _assign!(typeof(result.value[dst]), typeof(boundArgs[src]))(result.value[dst], boundArgs[src]); - return extractBoundArgs!(dst+1, src+1, BoundArgs)(result, boundArgs); - } - - // the dynamic ones will be specified at the time BoundFunc.call() is invoked - else { - return extractBoundArgs!(dst, src+1, BoundArgs)(result, boundArgs); - } - } + static if (dst < result.length) { + // again, we only want non-dynamic arguments here + static if (!isDynArg!(BoundArgs[src])) { + _assign!(typeof(result.value[dst]), typeof(boundArgs[src]))(result.value[dst], boundArgs[src]); + return extractBoundArgs!(dst+1, src+1, BoundArgs)(result, boundArgs); + } + + // the dynamic ones will be specified at the time BoundFunc.call() is invoked + else { + return extractBoundArgs!(dst, src+1, BoundArgs)(result, boundArgs); + } + } } /* - Number of args in the bound function that this Src arg will cover + Number of args in the bound function that this Src arg will cover */ template getArgLen(Dst, Src) { - // if the arg is a tuple and the target isn't one, it will be expanded/decomposed to the tuple's length - static if (isTypeTuple!(Src) && !isTypeTuple!(Dst)) { - static const int getArgLen = Src.length; - } - - // plain arg - it will use 1:1 mapping of functioni params to bound params - else { - static const int getArgLen = 1; - } + // if the arg is a tuple and the target isn't one, it will be expanded/decomposed to the tuple's length + static if (isTypeTuple!(Src) && !isTypeTuple!(Dst)) { + static const int getArgLen = Src.length; + } + + // plain arg - it will use 1:1 mapping of functioni params to bound params + else { + static const int getArgLen = 1; + } } /* - Tell whether a parameter type tuple contains an EmptySlot struct + Tell whether a parameter type tuple contains an EmptySlot struct */ template ContainsEmptySlotType(ParamList ...) { - const bool ContainsEmptySlotType = -1 != IndexOf!(EmptySlot, ParamList); + const bool ContainsEmptySlotType = -1 != IndexOf!(EmptySlot, ParamList); } @@ -944,112 +944,112 @@ const EmptySlot NullAlias; -struct PassByCopy {} -struct PassByRef {} +struct PassByCopy {} +struct PassByRef {} template ParamsPassMethodTuple_impl(alias Func, int i = 0) { - alias Tuple!(ParameterTypeTuple!(typeof(&Func))) Params; - - static if (Params.length == i) { - alias Tuple!() res; - } else { - Params params = void; - const params.type[i] constParam; - - // if the function expects references, it won't like our const. - static if (is(typeof(Func(params.value[0..i], constParam, params.value[i+1..$])))) { - alias ParamsPassMethodTuple_impl!(Func, i+1).res.meta.prependT!(PassByCopy) res; - } else { - alias ParamsPassMethodTuple_impl!(Func, i+1).res.meta.prependT!(PassByRef) res; - } - } + alias Tuple!(ParameterTypeTuple!(typeof(&Func))) Params; + + static if (Params.length == i) { + alias Tuple!() res; + } else { + Params params = void; + const params.type[i] constParam; + + // if the function expects references, it won't like our const. + static if (is(typeof(Func(params.value[0..i], constParam, params.value[i+1..$])))) { + alias ParamsPassMethodTuple_impl!(Func, i+1).res.meta.prependT!(PassByCopy) res; + } else { + alias ParamsPassMethodTuple_impl!(Func, i+1).res.meta.prependT!(PassByRef) res; + } + } } /* - Detect parameter passing methods: PassByCopy or PassByRef[erence] + Detect parameter passing methods: PassByCopy or PassByRef[erence] */ template ParamsPassMethodTuple(alias Func) { - alias ParamsPassMethodTuple_impl!(Func).res ParamsPassMethodTuple; + alias ParamsPassMethodTuple_impl!(Func).res ParamsPassMethodTuple; } template FuncReferenceParamsAsPointers_impl(alias Func) { - alias Tuple!(ParameterTypeTuple!(typeof(&Func))) Params; - alias ParamsPassMethodTuple!(Func) PassMethods; - - template loop(int i) { - static if (i == Params.length) { - alias Tuple!() res; - } else { - static if (is(PassMethods.type[i] == PassByRef)) { - alias Params.type[i]* type; - } else { - alias Params.type[i] type; - } - - alias loop!(i+1).res.meta.prependT!(type) res; - } - } - - alias loop!(0).res res; + alias Tuple!(ParameterTypeTuple!(typeof(&Func))) Params; + alias ParamsPassMethodTuple!(Func) PassMethods; + + template loop(int i) { + static if (i == Params.length) { + alias Tuple!() res; + } else { + static if (is(PassMethods.type[i] == PassByRef)) { + alias Params.type[i]* type; + } else { + alias Params.type[i] type; + } + + alias loop!(i+1).res.meta.prependT!(type) res; + } + } + + alias loop!(0).res res; } /* - Takes a function/delegate alias and converts its refence parameters to pointers. E.g. - - void function(int, inout char, float*) -> (int, char*, float*) + Takes a function/delegate alias and converts its refence parameters to pointers. E.g. + + void function(int, inout char, float*) -> (int, char*, float*) */ template FuncReferenceParamsAsPointers(alias Func) { - alias FuncReferenceParamsAsPointers_impl!(Func).res FuncReferenceParamsAsPointers; + alias FuncReferenceParamsAsPointers_impl!(Func).res FuncReferenceParamsAsPointers; } /* - Converts a tuple of types to a tuple containing pointer types of the original types + Converts a tuple of types to a tuple containing pointer types of the original types */ template PointerTuple(T) { - static if (T.length > 0) { - alias PointerTuple!(Tuple!(T.type[1..$])).meta.prependT!(T.type[0]*) PointerTuple; - } else { - alias Tuple!() PointerTuple; - } + static if (T.length > 0) { + alias PointerTuple!(Tuple!(T.type[1..$])).meta.prependT!(T.type[0]*) PointerTuple; + } else { + alias Tuple!() PointerTuple; + } } /* - Calls a function, dereferencing a pointer tuple for each argument + Calls a function, dereferencing a pointer tuple for each argument */ RetType ptrApply(RetType, FN, T ...)(FN fn, T t) { - static if (1 == T.length) { - return fn(*t[0]); - } - else static if (2 == T.length) { - return fn(*t[0], *t[1]); - } - else static if (3 == T.length) { - return fn(*t[0], *t[1], *t[2]); - } - else static if (4 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3]); - } - else static if (5 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3], *t[4]); - } - else static if (6 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5]); - } - else static if (7 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6]); - } - else static if (8 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6], *t[7]); - } - else static if (9 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6], *t[7], *t[8]); - } - else static if (10 == T.length) { - return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6], *t[7], *t[8], *t[9]); - } + static if (1 == T.length) { + return fn(*t[0]); + } + else static if (2 == T.length) { + return fn(*t[0], *t[1]); + } + else static if (3 == T.length) { + return fn(*t[0], *t[1], *t[2]); + } + else static if (4 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3]); + } + else static if (5 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3], *t[4]); + } + else static if (6 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5]); + } + else static if (7 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6]); + } + else static if (8 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6], *t[7]); + } + else static if (9 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6], *t[7], *t[8]); + } + else static if (10 == T.length) { + return fn(*t[0], *t[1], *t[2], *t[3], *t[4], *t[5], *t[6], *t[7], *t[8], *t[9]); + } } diff --git a/std/bitarray.d b/std/bitarray.d index d37930d72..51d7537db 100644 --- a/std/bitarray.d +++ b/std/bitarray.d @@ -1,11 +1,11 @@ /*********************** * Macros: - * WIKI = StdBitarray + * WIKI = StdBitarray */ module std.bitarray; -//debug = bitarray; // uncomment to turn on debugging printf's +//debug = bitarray; // uncomment to turn on debugging printf's private import std.intrinsic; @@ -20,35 +20,35 @@ struct BitArray size_t dim() { - return (len + 31) / 32; + return (len + 31) / 32; } size_t length() { - return len; + return len; } void length(size_t newlen) { - if (newlen != len) - { - size_t olddim = dim(); - size_t newdim = (newlen + 31) / 32; + if (newlen != len) + { + size_t olddim = dim(); + size_t newdim = (newlen + 31) / 32; - if (newdim != olddim) - { - // Create a fake array so we can use D's realloc machinery - uint[] b = ptr[0 .. olddim]; - b.length = newdim; // realloc - ptr = b.ptr; - if (newdim & 31) - { // Set any pad bits to 0 - ptr[newdim - 1] &= ~(~0 << (newdim & 31)); - } - } + if (newdim != olddim) + { + // Create a fake array so we can use D's realloc machinery + uint[] b = ptr[0 .. olddim]; + b.length = newdim; // realloc + ptr = b.ptr; + if (newdim & 31) + { // Set any pad bits to 0 + ptr[newdim - 1] &= ~(~0 << (newdim & 31)); + } + } - len = newlen; - } + len = newlen; + } } /********************************************** @@ -57,26 +57,26 @@ struct BitArray bool opIndex(size_t i) in { - assert(i < len); + assert(i < len); } body { - return cast(bool)bt(ptr, i); + return cast(bool)bt(ptr, i); } /** ditto */ bool opIndexAssign(bool b, size_t i) in { - assert(i < len); + assert(i < len); } body { - if (b) - bts(ptr, i); - else - btr(ptr, i); - return b; + if (b) + bts(ptr, i); + else + btr(ptr, i); + return b; } /********************************************** @@ -84,30 +84,30 @@ struct BitArray */ BitArray dup() { - BitArray ba; + BitArray ba; - uint[] b = ptr[0 .. dim].dup; - ba.len = len; - ba.ptr = b.ptr; - return ba; + uint[] b = ptr[0 .. dim].dup; + ba.len = len; + ba.ptr = b.ptr; + return ba; } unittest { - BitArray a; - BitArray b; - int i; + BitArray a; + BitArray b; + int i; - debug(bitarray) printf("BitArray.dup.unittest\n"); + debug(bitarray) printf("BitArray.dup.unittest\n"); - a.length = 3; - a[0] = 1; a[1] = 0; a[2] = 1; - b = a.dup; - assert(b.length == 3); - for (i = 0; i < 3; i++) - { debug(bitarray) printf("b[%d] = %d\n", i, b[i]); - assert(b[i] == (((i ^ 1) & 1) ? true : false)); - } + a.length = 3; + a[0] = 1; a[1] = 0; a[2] = 1; + b = a.dup; + assert(b.length == 3); + for (i = 0; i < 3; i++) + { debug(bitarray) printf("b[%d] = %d\n", i, b[i]); + assert(b[i] == (((i ^ 1) & 1) ? true : false)); + } } /********************************************** @@ -115,62 +115,62 @@ struct BitArray */ int opApply(int delegate(inout bool) dg) { - int result; + int result; - for (size_t i = 0; i < len; i++) - { bool b = opIndex(i); - result = dg(b); - (*this)[i] = b; - if (result) - break; - } - return result; + for (size_t i = 0; i < len; i++) + { bool b = opIndex(i); + result = dg(b); + (*this)[i] = b; + if (result) + break; + } + return result; } /** ditto */ int opApply(int delegate(inout size_t, inout bool) dg) { - int result; + int result; - for (size_t i = 0; i < len; i++) - { bool b = opIndex(i); - result = dg(i, b); - (*this)[i] = b; - if (result) - break; - } - return result; + for (size_t i = 0; i < len; i++) + { bool b = opIndex(i); + result = dg(i, b); + (*this)[i] = b; + if (result) + break; + } + return result; } unittest { - debug(bitarray) printf("BitArray.opApply unittest\n"); + debug(bitarray) printf("BitArray.opApply unittest\n"); - static bool[] ba = [1,0,1]; + static bool[] ba = [1,0,1]; - BitArray a; a.init(ba); + BitArray a; a.init(ba); - int i; - foreach (b;a) - { - switch (i) - { case 0: assert(b == true); break; - case 1: assert(b == false); break; - case 2: assert(b == true); break; - default: assert(0); - } - i++; - } + int i; + foreach (b;a) + { + switch (i) + { case 0: assert(b == true); break; + case 1: assert(b == false); break; + case 2: assert(b == true); break; + default: assert(0); + } + i++; + } - foreach (j,b;a) - { - switch (j) - { case 0: assert(b == true); break; - case 1: assert(b == false); break; - case 2: assert(b == true); break; - default: assert(0); - } - } + foreach (j,b;a) + { + switch (j) + { case 0: assert(b == true); break; + case 1: assert(b == false); break; + case 2: assert(b == true); break; + default: assert(0); + } + } } @@ -179,43 +179,43 @@ struct BitArray */ BitArray reverse() - out (result) - { - assert(result == *this); - } - body - { - if (len >= 2) - { - bool t; - size_t lo, hi; + out (result) + { + assert(result == *this); + } + body + { + if (len >= 2) + { + bool t; + size_t lo, hi; - lo = 0; - hi = len - 1; - for (; lo < hi; lo++, hi--) - { - t = (*this)[lo]; - (*this)[lo] = (*this)[hi]; - (*this)[hi] = t; - } - } - return *this; - } + lo = 0; + hi = len - 1; + for (; lo < hi; lo++, hi--) + { + t = (*this)[lo]; + (*this)[lo] = (*this)[hi]; + (*this)[hi] = t; + } + } + return *this; + } unittest { - debug(bitarray) printf("BitArray.reverse.unittest\n"); + debug(bitarray) printf("BitArray.reverse.unittest\n"); - BitArray b; - static bool[5] data = [1,0,1,1,0]; - int i; + BitArray b; + static bool[5] data = [1,0,1,1,0]; + int i; - b.init(data); - b.reverse; - for (i = 0; i < data.length; i++) - { - assert(b[i] == data[4 - i]); - } + b.init(data); + b.reverse; + for (i = 0; i < data.length; i++) + { + assert(b[i] == data[4 - i]); + } } @@ -224,61 +224,61 @@ struct BitArray */ BitArray sort() - out (result) - { - assert(result == *this); - } - body - { - if (len >= 2) - { - size_t lo, hi; + out (result) + { + assert(result == *this); + } + body + { + if (len >= 2) + { + size_t lo, hi; - lo = 0; - hi = len - 1; - while (1) - { - while (1) - { - if (lo >= hi) - goto Ldone; - if ((*this)[lo] == true) - break; - lo++; - } + lo = 0; + hi = len - 1; + while (1) + { + while (1) + { + if (lo >= hi) + goto Ldone; + if ((*this)[lo] == true) + break; + lo++; + } - while (1) - { - if (lo >= hi) - goto Ldone; - if ((*this)[hi] == false) - break; - hi--; - } + while (1) + { + if (lo >= hi) + goto Ldone; + if ((*this)[hi] == false) + break; + hi--; + } - (*this)[lo] = false; - (*this)[hi] = true; + (*this)[lo] = false; + (*this)[hi] = true; - lo++; - hi--; - } - Ldone: - ; - } - return *this; - } + lo++; + hi--; + } + Ldone: + ; + } + return *this; + } unittest { - debug(bitarray) printf("BitArray.sort.unittest\n"); + debug(bitarray) printf("BitArray.sort.unittest\n"); - static uint x = 0b1100011000; - static BitArray ba = { 10, &x }; - ba.sort; - for (size_t i = 0; i < 6; i++) - assert(ba[i] == false); - for (size_t i = 6; i < 10; i++) - assert(ba[i] == true); + static uint x = 0b1100011000; + static BitArray ba = { 10, &x }; + ba.sort; + for (size_t i = 0; i < 6; i++) + assert(ba[i] == false); + for (size_t i = 6; i < 10; i++) + assert(ba[i] == true); } @@ -289,45 +289,45 @@ struct BitArray int opEquals(BitArray a2) { int i; - if (this.length != a2.length) - return 0; // not equal - byte *p1 = cast(byte*)this.ptr; - byte *p2 = cast(byte*)a2.ptr; - uint n = this.length / 8; - for (i = 0; i < n; i++) - { - if (p1[i] != p2[i]) - return 0; // not equal - } + if (this.length != a2.length) + return 0; // not equal + byte *p1 = cast(byte*)this.ptr; + byte *p2 = cast(byte*)a2.ptr; + uint n = this.length / 8; + for (i = 0; i < n; i++) + { + if (p1[i] != p2[i]) + return 0; // not equal + } - ubyte mask; + ubyte mask; - n = this.length & 7; - mask = cast(ubyte)((1 << n) - 1); - //printf("i = %d, n = %d, mask = %x, %x, %x\n", i, n, mask, p1[i], p2[i]); - return (mask == 0) || (p1[i] & mask) == (p2[i] & mask); + n = this.length & 7; + mask = cast(ubyte)((1 << n) - 1); + //printf("i = %d, n = %d, mask = %x, %x, %x\n", i, n, mask, p1[i], p2[i]); + return (mask == 0) || (p1[i] & mask) == (p2[i] & mask); } unittest { - debug(bitarray) printf("BitArray.opEquals unittest\n"); + debug(bitarray) printf("BitArray.opEquals unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1]; - static bool[] bc = [1,0,1,0,1,0,1]; - static bool[] bd = [1,0,1,1,1]; - static bool[] be = [1,0,1,0,1]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1]; + static bool[] bc = [1,0,1,0,1,0,1]; + static bool[] bd = [1,0,1,1,1]; + static bool[] be = [1,0,1,0,1]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); - BitArray c; c.init(bc); - BitArray d; d.init(bd); - BitArray e; e.init(be); + BitArray a; a.init(ba); + BitArray b; b.init(bb); + BitArray c; c.init(bc); + BitArray d; d.init(bd); + BitArray e; e.init(be); - assert(a != b); - assert(a != c); - assert(a != d); - assert(a == e); + assert(a != b); + assert(a != c); + assert(a != d); + assert(a == e); } /*************************************** @@ -336,56 +336,56 @@ struct BitArray int opCmp(BitArray a2) { - uint len; - uint i; + uint len; + uint i; - len = this.length; - if (a2.length < len) - len = a2.length; - ubyte* p1 = cast(ubyte*)this.ptr; - ubyte* p2 = cast(ubyte*)a2.ptr; - uint n = len / 8; - for (i = 0; i < n; i++) - { - if (p1[i] != p2[i]) - break; // not equal - } - for (uint j = i * 8; j < len; j++) - { ubyte mask = cast(ubyte)(1 << j); - int c; + len = this.length; + if (a2.length < len) + len = a2.length; + ubyte* p1 = cast(ubyte*)this.ptr; + ubyte* p2 = cast(ubyte*)a2.ptr; + uint n = len / 8; + for (i = 0; i < n; i++) + { + if (p1[i] != p2[i]) + break; // not equal + } + for (uint j = i * 8; j < len; j++) + { ubyte mask = cast(ubyte)(1 << j); + int c; - c = cast(int)(p1[i] & mask) - cast(int)(p2[i] & mask); - if (c) - return c; - } - return cast(int)this.len - cast(int)a2.length; + c = cast(int)(p1[i] & mask) - cast(int)(p2[i] & mask); + if (c) + return c; + } + return cast(int)this.len - cast(int)a2.length; } unittest { - debug(bitarray) printf("BitArray.opCmp unittest\n"); + debug(bitarray) printf("BitArray.opCmp unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1]; - static bool[] bc = [1,0,1,0,1,0,1]; - static bool[] bd = [1,0,1,1,1]; - static bool[] be = [1,0,1,0,1]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1]; + static bool[] bc = [1,0,1,0,1,0,1]; + static bool[] bd = [1,0,1,1,1]; + static bool[] be = [1,0,1,0,1]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); - BitArray c; c.init(bc); - BitArray d; d.init(bd); - BitArray e; e.init(be); + BitArray a; a.init(ba); + BitArray b; b.init(bb); + BitArray c; c.init(bc); + BitArray d; d.init(bd); + BitArray e; e.init(be); - assert(a > b); - assert(a >= b); - assert(a < c); - assert(a <= c); - assert(a < d); - assert(a <= d); - assert(a == e); - assert(a <= e); - assert(a >= e); + assert(a > b); + assert(a >= b); + assert(a < c); + assert(a <= c); + assert(a < d); + assert(a <= d); + assert(a == e); + assert(a <= e); + assert(a >= e); } /*************************************** @@ -394,11 +394,11 @@ struct BitArray void init(bool[] ba) { - length = ba.length; - foreach (i, b; ba) - { - (*this)[i] = b; - } + length = ba.length; + foreach (i, b; ba) + { + (*this)[i] = b; + } } @@ -411,38 +411,38 @@ struct BitArray void init(void[] v, size_t numbits) in { - assert(numbits <= v.length * 8); - assert((v.length & 3) == 0); + assert(numbits <= v.length * 8); + assert((v.length & 3) == 0); } body { - ptr = cast(uint*)v.ptr; - len = numbits; + ptr = cast(uint*)v.ptr; + len = numbits; } unittest { - debug(bitarray) printf("BitArray.init unittest\n"); + debug(bitarray) printf("BitArray.init unittest\n"); - static bool[] ba = [1,0,1,0,1]; + static bool[] ba = [1,0,1,0,1]; - BitArray a; a.init(ba); - BitArray b; - void[] v; + BitArray a; a.init(ba); + BitArray b; + void[] v; - v = cast(void[])a; - b.init(v, a.length); + v = cast(void[])a; + b.init(v, a.length); - assert(b[0] == 1); - assert(b[1] == 0); - assert(b[2] == 1); - assert(b[3] == 0); - assert(b[4] == 1); + assert(b[0] == 1); + assert(b[1] == 0); + assert(b[2] == 1); + assert(b[3] == 0); + assert(b[4] == 1); - a[0] = 0; - assert(b[0] == 0); + a[0] = 0; + assert(b[0] == 0); - assert(a == b); + assert(a == b); } /*************************************** @@ -450,19 +450,19 @@ struct BitArray */ void[] opCast() { - return cast(void[])ptr[0 .. dim]; + return cast(void[])ptr[0 .. dim]; } unittest { - debug(bitarray) printf("BitArray.opCast unittest\n"); + debug(bitarray) printf("BitArray.opCast unittest\n"); - static bool[] ba = [1,0,1,0,1]; + static bool[] ba = [1,0,1,0,1]; - BitArray a; a.init(ba); - void[] v = cast(void[])a; + BitArray a; a.init(ba); + void[] v = cast(void[])a; - assert(v.length == a.dim * uint.sizeof); + assert(v.length == a.dim * uint.sizeof); } /*************************************** @@ -470,32 +470,32 @@ struct BitArray */ BitArray opCom() { - auto dim = this.dim(); + auto dim = this.dim(); - BitArray result; + BitArray result; - result.length = len; - for (size_t i = 0; i < dim; i++) - result.ptr[i] = ~this.ptr[i]; - if (len & 31) - result.ptr[dim - 1] &= ~(~0 << (len & 31)); - return result; + result.length = len; + for (size_t i = 0; i < dim; i++) + result.ptr[i] = ~this.ptr[i]; + if (len & 31) + result.ptr[dim - 1] &= ~(~0 << (len & 31)); + return result; } unittest { - debug(bitarray) printf("BitArray.opCom unittest\n"); + debug(bitarray) printf("BitArray.opCom unittest\n"); - static bool[] ba = [1,0,1,0,1]; + static bool[] ba = [1,0,1,0,1]; - BitArray a; a.init(ba); - BitArray b = ~a; + BitArray a; a.init(ba); + BitArray b = ~a; - assert(b[0] == 0); - assert(b[1] == 1); - assert(b[2] == 0); - assert(b[3] == 1); - assert(b[4] == 0); + assert(b[0] == 0); + assert(b[1] == 1); + assert(b[2] == 0); + assert(b[3] == 1); + assert(b[4] == 0); } @@ -505,37 +505,37 @@ struct BitArray BitArray opAnd(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - BitArray result; + BitArray result; - result.length = len; - for (size_t i = 0; i < dim; i++) - result.ptr[i] = this.ptr[i] & e2.ptr[i]; - return result; + result.length = len; + for (size_t i = 0; i < dim; i++) + result.ptr[i] = this.ptr[i] & e2.ptr[i]; + return result; } unittest { - debug(bitarray) printf("BitArray.opAnd unittest\n"); + debug(bitarray) printf("BitArray.opAnd unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - BitArray c = a & b; + BitArray c = a & b; - assert(c[0] == 1); - assert(c[1] == 0); - assert(c[2] == 1); - assert(c[3] == 0); - assert(c[4] == 0); + assert(c[0] == 1); + assert(c[1] == 0); + assert(c[2] == 1); + assert(c[3] == 0); + assert(c[4] == 0); } @@ -545,37 +545,37 @@ struct BitArray BitArray opOr(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - BitArray result; + BitArray result; - result.length = len; - for (size_t i = 0; i < dim; i++) - result.ptr[i] = this.ptr[i] | e2.ptr[i]; - return result; + result.length = len; + for (size_t i = 0; i < dim; i++) + result.ptr[i] = this.ptr[i] | e2.ptr[i]; + return result; } unittest { - debug(bitarray) printf("BitArray.opOr unittest\n"); + debug(bitarray) printf("BitArray.opOr unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - BitArray c = a | b; + BitArray c = a | b; - assert(c[0] == 1); - assert(c[1] == 0); - assert(c[2] == 1); - assert(c[3] == 1); - assert(c[4] == 1); + assert(c[0] == 1); + assert(c[1] == 0); + assert(c[2] == 1); + assert(c[3] == 1); + assert(c[4] == 1); } @@ -585,37 +585,37 @@ struct BitArray BitArray opXor(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - BitArray result; + BitArray result; - result.length = len; - for (size_t i = 0; i < dim; i++) - result.ptr[i] = this.ptr[i] ^ e2.ptr[i]; - return result; + result.length = len; + for (size_t i = 0; i < dim; i++) + result.ptr[i] = this.ptr[i] ^ e2.ptr[i]; + return result; } unittest { - debug(bitarray) printf("BitArray.opXor unittest\n"); + debug(bitarray) printf("BitArray.opXor unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - BitArray c = a ^ b; + BitArray c = a ^ b; - assert(c[0] == 0); - assert(c[1] == 0); - assert(c[2] == 0); - assert(c[3] == 1); - assert(c[4] == 1); + assert(c[0] == 0); + assert(c[1] == 0); + assert(c[2] == 0); + assert(c[3] == 1); + assert(c[4] == 1); } @@ -627,37 +627,37 @@ struct BitArray BitArray opSub(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - BitArray result; + BitArray result; - result.length = len; - for (size_t i = 0; i < dim; i++) - result.ptr[i] = this.ptr[i] & ~e2.ptr[i]; - return result; + result.length = len; + for (size_t i = 0; i < dim; i++) + result.ptr[i] = this.ptr[i] & ~e2.ptr[i]; + return result; } unittest { - debug(bitarray) printf("BitArray.opSub unittest\n"); + debug(bitarray) printf("BitArray.opSub unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - BitArray c = a - b; + BitArray c = a - b; - assert(c[0] == 0); - assert(c[1] == 0); - assert(c[2] == 0); - assert(c[3] == 0); - assert(c[4] == 1); + assert(c[0] == 0); + assert(c[1] == 0); + assert(c[2] == 0); + assert(c[3] == 0); + assert(c[4] == 1); } @@ -667,33 +667,33 @@ struct BitArray BitArray opAndAssign(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - for (size_t i = 0; i < dim; i++) - ptr[i] &= e2.ptr[i]; - return *this; + for (size_t i = 0; i < dim; i++) + ptr[i] &= e2.ptr[i]; + return *this; } unittest { - debug(bitarray) printf("BitArray.opAndAssign unittest\n"); + debug(bitarray) printf("BitArray.opAndAssign unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - a &= b; - assert(a[0] == 1); - assert(a[1] == 0); - assert(a[2] == 1); - assert(a[3] == 0); - assert(a[4] == 0); + a &= b; + assert(a[0] == 1); + assert(a[1] == 0); + assert(a[2] == 1); + assert(a[3] == 0); + assert(a[4] == 0); } @@ -703,33 +703,33 @@ struct BitArray BitArray opOrAssign(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - for (size_t i = 0; i < dim; i++) - ptr[i] |= e2.ptr[i]; - return *this; + for (size_t i = 0; i < dim; i++) + ptr[i] |= e2.ptr[i]; + return *this; } unittest { - debug(bitarray) printf("BitArray.opOrAssign unittest\n"); + debug(bitarray) printf("BitArray.opOrAssign unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - a |= b; - assert(a[0] == 1); - assert(a[1] == 0); - assert(a[2] == 1); - assert(a[3] == 1); - assert(a[4] == 1); + a |= b; + assert(a[0] == 1); + assert(a[1] == 0); + assert(a[2] == 1); + assert(a[3] == 1); + assert(a[4] == 1); } /*************************************** @@ -738,33 +738,33 @@ struct BitArray BitArray opXorAssign(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - for (size_t i = 0; i < dim; i++) - ptr[i] ^= e2.ptr[i]; - return *this; + for (size_t i = 0; i < dim; i++) + ptr[i] ^= e2.ptr[i]; + return *this; } unittest { - debug(bitarray) printf("BitArray.opXorAssign unittest\n"); + debug(bitarray) printf("BitArray.opXorAssign unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - a ^= b; - assert(a[0] == 0); - assert(a[1] == 0); - assert(a[2] == 0); - assert(a[3] == 1); - assert(a[4] == 1); + a ^= b; + assert(a[0] == 0); + assert(a[1] == 0); + assert(a[2] == 0); + assert(a[3] == 1); + assert(a[4] == 1); } /*************************************** @@ -775,33 +775,33 @@ struct BitArray BitArray opSubAssign(BitArray e2) in { - assert(len == e2.length); + assert(len == e2.length); } body { - auto dim = this.dim(); + auto dim = this.dim(); - for (size_t i = 0; i < dim; i++) - ptr[i] &= ~e2.ptr[i]; - return *this; + for (size_t i = 0; i < dim; i++) + ptr[i] &= ~e2.ptr[i]; + return *this; } unittest { - debug(bitarray) printf("BitArray.opSubAssign unittest\n"); + debug(bitarray) printf("BitArray.opSubAssign unittest\n"); - static bool[] ba = [1,0,1,0,1]; - static bool[] bb = [1,0,1,1,0]; + static bool[] ba = [1,0,1,0,1]; + static bool[] bb = [1,0,1,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); + BitArray a; a.init(ba); + BitArray b; b.init(bb); - a -= b; - assert(a[0] == 0); - assert(a[1] == 0); - assert(a[2] == 0); - assert(a[3] == 0); - assert(a[4] == 1); + a -= b; + assert(a[0] == 0); + assert(a[1] == 0); + assert(a[2] == 0); + assert(a[3] == 0); + assert(a[4] == 1); } /*************************************** @@ -810,29 +810,29 @@ struct BitArray BitArray opCatAssign(bool b) { - length = len + 1; - (*this)[len - 1] = b; - return *this; + length = len + 1; + (*this)[len - 1] = b; + return *this; } unittest { - debug(bitarray) printf("BitArray.opCatAssign unittest\n"); + debug(bitarray) printf("BitArray.opCatAssign unittest\n"); - static bool[] ba = [1,0,1,0,1]; + static bool[] ba = [1,0,1,0,1]; - BitArray a; a.init(ba); - BitArray b; + BitArray a; a.init(ba); + BitArray b; - b = (a ~= true); - assert(a[0] == 1); - assert(a[1] == 0); - assert(a[2] == 1); - assert(a[3] == 0); - assert(a[4] == 1); - assert(a[5] == 1); + b = (a ~= true); + assert(a[0] == 1); + assert(a[1] == 0); + assert(a[2] == 1); + assert(a[3] == 0); + assert(a[4] == 1); + assert(a[5] == 1); - assert(b == a); + assert(b == a); } /*************************************** @@ -841,33 +841,33 @@ struct BitArray BitArray opCatAssign(BitArray b) { - auto istart = len; - length = len + b.length; - for (auto i = istart; i < len; i++) - (*this)[i] = b[i - istart]; - return *this; + auto istart = len; + length = len + b.length; + for (auto i = istart; i < len; i++) + (*this)[i] = b[i - istart]; + return *this; } unittest { - debug(bitarray) printf("BitArray.opCatAssign unittest\n"); + debug(bitarray) printf("BitArray.opCatAssign unittest\n"); - static bool[] ba = [1,0]; - static bool[] bb = [0,1,0]; + static bool[] ba = [1,0]; + static bool[] bb = [0,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); - BitArray c; + BitArray a; a.init(ba); + BitArray b; b.init(bb); + BitArray c; - c = (a ~= b); - assert(a.length == 5); - assert(a[0] == 1); - assert(a[1] == 0); - assert(a[2] == 0); - assert(a[3] == 1); - assert(a[4] == 0); + c = (a ~= b); + assert(a.length == 5); + assert(a[0] == 1); + assert(a[1] == 0); + assert(a[2] == 0); + assert(a[3] == 1); + assert(a[4] == 0); - assert(c == a); + assert(c == a); } /*************************************** @@ -875,65 +875,65 @@ struct BitArray */ BitArray opCat(bool b) { - BitArray r; + BitArray r; - r = this.dup; - r.length = len + 1; - r[len] = b; - return r; + r = this.dup; + r.length = len + 1; + r[len] = b; + return r; } /** ditto */ BitArray opCat_r(bool b) { - BitArray r; + BitArray r; - r.length = len + 1; - r[0] = b; - for (size_t i = 0; i < len; i++) - r[1 + i] = (*this)[i]; - return r; + r.length = len + 1; + r[0] = b; + for (size_t i = 0; i < len; i++) + r[1 + i] = (*this)[i]; + return r; } /** ditto */ BitArray opCat(BitArray b) { - BitArray r; + BitArray r; - r = this.dup(); - r ~= b; - return r; + r = this.dup(); + r ~= b; + return r; } unittest { - debug(bitarray) printf("BitArray.opCat unittest\n"); + debug(bitarray) printf("BitArray.opCat unittest\n"); - static bool[] ba = [1,0]; - static bool[] bb = [0,1,0]; + static bool[] ba = [1,0]; + static bool[] bb = [0,1,0]; - BitArray a; a.init(ba); - BitArray b; b.init(bb); - BitArray c; + BitArray a; a.init(ba); + BitArray b; b.init(bb); + BitArray c; - c = (a ~ b); - assert(c.length == 5); - assert(c[0] == 1); - assert(c[1] == 0); - assert(c[2] == 0); - assert(c[3] == 1); - assert(c[4] == 0); + c = (a ~ b); + assert(c.length == 5); + assert(c[0] == 1); + assert(c[1] == 0); + assert(c[2] == 0); + assert(c[3] == 1); + assert(c[4] == 0); - c = (a ~ true); - assert(c.length == 3); - assert(c[0] == 1); - assert(c[1] == 0); - assert(c[2] == 1); + c = (a ~ true); + assert(c.length == 3); + assert(c[0] == 1); + assert(c[1] == 0); + assert(c[2] == 1); - c = (false ~ a); - assert(c.length == 3); - assert(c[0] == 0); - assert(c[1] == 1); - assert(c[2] == 0); + c = (false ~ a); + assert(c.length == 3); + assert(c[0] == 0); + assert(c[1] == 1); + assert(c[2] == 0); } } diff --git a/std/boxer.d b/std/boxer.d index b02dba338..2a836170e 100644 --- a/std/boxer.d +++ b/std/boxer.d @@ -2,7 +2,7 @@ * This module is a set of types and functions for converting any object (value * or heap) into a generic box type, allowing the user to pass that object * around without knowing what's in the box, and then allowing him to recover - * the value afterwards. + * the value afterwards. * * Example: --- @@ -18,15 +18,15 @@ real r = unbox!(real)(b); * UnboxException. As demonstrated, it uses implicit casts to behave in the exact * same way that static types behave. So for example, you can unbox from int to * real, but you cannot unbox from real to int: that would require an explicit - * cast. + * cast. * * This therefore means that attempting to unbox an int as a string will throw * an error instead of formatting it. In general, you can call the toString method * on the box and receive a good result, depending upon whether std.string.format - * accepts it. + * accepts it. * * Boxes can be compared to one another and they can be used as keys for - * associative arrays. + * associative arrays. * * There are also functions for converting to and from arrays of boxes. * @@ -50,16 +50,16 @@ a = boxArray(arg_types, arg_data); * with the array. * * Authors: - * Burton Radons + * Burton Radons * License: - * Public Domain + * Public Domain * Bugs: - * $(UL - * $(LI $(BUGZILLA 309)) - * $(LI $(BUGZILLA 1968)) - * ) + * $(UL + * $(LI $(BUGZILLA 309)) + * $(LI $(BUGZILLA 1968)) + * ) * Macros: - * WIKI=Phobos/StdBoxer + * WIKI=Phobos/StdBoxer */ module std.boxer; @@ -72,7 +72,7 @@ private import std.utf; * and recovering them later. This comes into play in a wide spectrum of * utilities, such as with a scripting language, or as additional user data * for an object. - * + * * Box an object by calling the box function: * * Box x = box(4); @@ -93,7 +93,7 @@ private import std.utf; * throw an error and not format it. In general, you can call the toString * method on the box and receive a good result, depending upon whether * std.string.format accepts it. - * + * * Boxes can be compared to one another and they can be used as keys for * associative arrays. Boxes of different types can be compared to one * another, using the same casting rules as the main type system. @@ -115,7 +115,7 @@ private import std.utf; * bool unboxable!(T) (Box value); * bool Box.unboxable(TypeInfo T); */ - + /** Return the next type in an array typeinfo, or null if there is none. */ private bool isArrayTypeInfo(TypeInfo type) { @@ -127,7 +127,7 @@ private bool isArrayTypeInfo(TypeInfo type) private enum TypeClass { Bool, /**< bool */ - Bit = Bool, // for backwards compatibility + Bit = Bool, // for backwards compatibility Integer, /**< byte, ubyte, short, ushort, int, uint, long, ulong */ Float, /**< float, double, real */ Complex, /**< cfloat, cdouble, creal */ @@ -149,13 +149,13 @@ private enum TypeClass struct Box { private TypeInfo p_type; /**< The type of the contained object. */ - + private union { void* p_longData; /**< An array of the contained object. */ void[8] p_shortData; /**< Data used when the object is small. */ } - + private static TypeClass findTypeClass(TypeInfo type) { if (cast(TypeInfo_Class) type) @@ -194,36 +194,36 @@ struct Box } } } - + /** Return whether this value could be unboxed as the given type without throwing. */ bool unboxable(TypeInfo test) { if (type is test) return true; - + TypeInfo_Class ca = cast(TypeInfo_Class) type, cb = cast(TypeInfo_Class) test; - + if (ca !is null && cb !is null) { ClassInfo ia = (*cast(Object *) data).classinfo, ib = cb.info; - + for ( ; ia !is null; ia = ia.base) if (ia is ib) return true; return false; } - + TypeClass ta = findTypeClass(type), tb = findTypeClass(test); - + if (type is typeid(void*) && *cast(void**) data is null) return (tb == TypeClass.Class || tb == TypeClass.Pointer || tb == TypeClass.Array); - + if (test is typeid(void*)) return (tb == TypeClass.Class || tb == TypeClass.Pointer || tb == TypeClass.Array); - + if (ta == TypeClass.Pointer && tb == TypeClass.Pointer) return (cast(TypeInfo_Pointer)type).next is (cast(TypeInfo_Pointer)test).next; - + if ((ta == tb && ta != TypeClass.Other) || (ta == TypeClass.Bool && tb == TypeClass.Integer) || (ta <= TypeClass.Integer && tb == TypeClass.Float) @@ -231,7 +231,7 @@ struct Box return true; return false; } - + /** * Property for the type contained by the box. * This is initially null and cannot be assigned directly. @@ -241,7 +241,7 @@ struct Box { return p_type; } - + /** * Property for the data pointer to the value of the box. * This is initially null and cannot be assigned directly. @@ -250,41 +250,41 @@ struct Box void[] data() { size_t size = type.tsize(); - + return size <= p_shortData.length ? p_shortData[0..size] : p_longData[0..size]; } /** * Attempt to convert the boxed value into a string using std.string.format; * this will throw if that function cannot handle it. If the box is - * uninitialized then this returns "". + * uninitialized then this returns "". */ char[] toString() { if (type is null) return ""; - + TypeInfo[2] arguments; char[] string; void[] args = new void[(char[]).sizeof + data.length]; char[] format = "%s"; - + arguments[0] = typeid(char[]); arguments[1] = type; - + void putc(dchar ch) { std.utf.encode(string, ch); } - + args[0..(char[]).sizeof] = (cast(void*) &format)[0..(char[]).sizeof]; args[(char[]).sizeof..length] = data; std.format.doFormat(&putc, arguments, args.ptr); delete args; - + return string; } - + private bool opEqualsInternal(Box other, bool inverted) { if (type != other.type) @@ -295,13 +295,13 @@ struct Box return false; return other.opEqualsInternal(*this, true); } - + TypeClass ta = findTypeClass(type), tb = findTypeClass(other.type); - + if (ta <= TypeClass.Integer && tb <= TypeClass.Integer) { char[] na = type.toString, nb = other.type.toString; - + if (na == "ulong" || nb == "ulong") return unbox!(ulong)(*this) == unbox!(ulong)(other); return unbox!(long)(*this) == unbox!(long)(other); @@ -312,22 +312,22 @@ struct Box return unbox!(creal)(*this) == unbox!(creal)(other); else if (tb == TypeClass.Imaginary) return unbox!(ireal)(*this) == unbox!(ireal)(other); - + assert (0); } - + return cast(bool)type.equals(data.ptr, other.data.ptr); } /** * Compare this box's value with another box. This implicitly casts if the - * types are different, identical to the regular type system. + * types are different, identical to the regular type system. */ bool opEquals(Box other) { return opEqualsInternal(other, false); } - + private float opCmpInternal(Box other, bool inverted) { if (type != other.type) @@ -338,9 +338,9 @@ struct Box return 0; return other.opCmpInternal(*this, true); } - + TypeClass ta = findTypeClass(type), tb = findTypeClass(other.type); - + if (ta <= TypeClass.Integer && tb == TypeClass.Integer) { if (type == typeid(ulong) || other.type == typeid(ulong)) @@ -348,7 +348,7 @@ struct Box ulong va = unbox!(ulong)(*this), vb = unbox!(ulong)(other); return va > vb ? 1 : va < vb ? -1 : 0; } - + long va = unbox!(long)(*this), vb = unbox!(long)(other); return va > vb ? 1 : va < vb ? -1 : 0; } @@ -367,10 +367,10 @@ struct Box ireal va = unbox!(ireal)(*this), vb = unbox!(ireal)(other); return va > vb ? 1 : va < vb ? -1 : va == vb ? 0 : float.nan; } - + assert (0); } - + return type.compare(data.ptr, other.data.ptr); } @@ -394,8 +394,8 @@ struct Box /** * Box the single argument passed to the function. If more or fewer than one - * argument is passed, this will assert. - */ + * argument is passed, this will assert. + */ Box box(...) in { @@ -410,7 +410,7 @@ body * Box the explicitly-defined object. type must not be null; data must not be * null if the type's size is greater than zero. * The data is copied. - */ + */ Box box(TypeInfo type, void* data) in { @@ -420,13 +420,13 @@ body { Box result; size_t size = type.tsize(); - + result.p_type = type; if (size <= result.p_shortData.length) result.p_shortData[0..size] = data[0..size]; else result.p_longData = data[0..size].dup.ptr; - + return result; } @@ -438,23 +438,23 @@ private size_t argumentLength(size_t baseLength) /** * Convert a list of arguments into a list of boxes. - */ + */ Box[] boxArray(TypeInfo[] types, void* data) { Box[] array = new Box[types.length]; - + foreach(size_t index, TypeInfo type; types) { array[index] = box(type, data); data += argumentLength(type.tsize()); } - + return array; } /** * Box each argument passed to the function, returning an array of boxes. - */ + */ Box[] boxArray(...) { return boxArray(_arguments, _argptr); @@ -462,16 +462,16 @@ Box[] boxArray(...) /** * Convert an array of boxes into an array of arguments. - */ + */ void boxArrayToArguments(Box[] arguments, out TypeInfo[] types, out void* data) { size_t dataLength; void* pointer; - + /* Determine the number of bytes of data to allocate by summing the arguments. */ foreach (Box item; arguments) dataLength += argumentLength(item.data.length); - + types = new TypeInfo[arguments.length]; pointer = data = (new void[dataLength]).ptr; @@ -481,16 +481,16 @@ void boxArrayToArguments(Box[] arguments, out TypeInfo[] types, out void* data) types[index] = item.type; pointer[0..item.data.length] = item.data; pointer += argumentLength(item.data.length); - } + } } /** * This class is thrown if unbox is unable to cast the value into the desired * result. - */ + */ class UnboxException : Exception { - Box object; /// This is the box that the user attempted to unbox. + Box object; /// This is the box that the user attempted to unbox. TypeInfo outputType; /// This is the type that the user attempted to unbox the value as. @@ -512,7 +512,7 @@ private template unboxCastReal(T) T unboxCastReal(Box value) { assert (value.type !is null); - + if (value.type is typeid(float)) return cast(T) *cast(float*) value.data; if (value.type is typeid(double)) @@ -529,7 +529,7 @@ private template unboxCastInteger(T) T unboxCastInteger(Box value) { assert (value.type !is null); - + if (value.type is typeid(int)) return cast(T) *cast(int*) value.data; if (value.type is typeid(uint)) @@ -558,7 +558,7 @@ private template unboxCastComplex(T) T unboxCastComplex(Box value) { assert (value.type !is null); - + if (value.type is typeid(cfloat)) return cast(T) *cast(cfloat*) value.data; if (value.type is typeid(cdouble)) @@ -581,7 +581,7 @@ private template unboxCastImaginary(T) T unboxCastImaginary(Box value) { assert (value.type !is null); - + if (value.type is typeid(ifloat)) return cast(T) *cast(ifloat*) value.data; if (value.type is typeid(idouble)) @@ -597,7 +597,7 @@ private template unboxCastImaginary(T) * takes a box object and returns the specified type. * * To use it, instantiate the template with the desired result type, and then - * call the function with the box to convert. + * call the function with the box to convert. * This will implicitly cast base types as necessary and in a way consistent * with static types - for example, it will cast a boxed byte into int, but it * won't cast a boxed float into short. @@ -613,13 +613,13 @@ private template unboxCastImaginary(T) * Box y = box(4); * int x = unbox!(int) (y); * --- - */ + */ template unbox(T) { T unbox(Box value) { assert (value.type !is null); - + if (typeid(T) is value.type) return *cast(T*) value.data; throw new UnboxException(value, typeid(T)); @@ -649,19 +649,19 @@ template unbox(T : Object) T unbox(Box value) { assert (value.type !is null); - + if (typeid(T) == value.type || cast(TypeInfo_Class) value.type) { Object object = *cast(Object*)value.data; T result = cast(T)object; - + if (object is null) return null; if (result is null) throw new UnboxException(value, typeid(T)); return result; } - + if (typeid(void*) is value.type && *cast(void**) value.data is null) return null; throw new UnboxException(value, typeid(T)); @@ -673,7 +673,7 @@ template unbox(T : T[]) T[] unbox(Box value) { assert (value.type !is null); - + if (typeid(T[]) is value.type) return *cast(T[]*) value.data; if (typeid(void*) is value.type && *cast(void**) value.data is null) @@ -687,14 +687,14 @@ template unbox(T : T*) T* unbox(Box value) { assert (value.type !is null); - + if (typeid(T*) is value.type) return *cast(T**) value.data; if (typeid(void*) is value.type && *cast(void**) value.data is null) return null; if (typeid(T[]) is value.type) return (*cast(T[]*) value.data).ptr; - + throw new UnboxException(value, typeid(T*)); } } @@ -704,14 +704,14 @@ template unbox(T : void*) T unbox(Box value) { assert (value.type !is null); - + if (cast(TypeInfo_Pointer) value.type) return *cast(void**) value.data; if (isArrayTypeInfo(value.type)) return (*cast(void[]*) value.data).ptr; if (cast(TypeInfo_Class) value.type) return cast(T)(*cast(Object*) value.data); - + throw new UnboxException(value, typeid(T)); } } @@ -719,7 +719,7 @@ template unbox(T : void*) /** * Return whether the value can be unboxed as the given type; if this returns * false, attempting to do so will throw UnboxException. - */ + */ template unboxable(T) { bool unboxable(Box value) @@ -735,7 +735,7 @@ private template unboxTest(T) { T result; bool unboxable = value.unboxable(typeid(T)); - + try result = unbox!(T) (value); catch (UnboxException error) { @@ -744,7 +744,7 @@ private template unboxTest(T) assert (!unboxable); throw error; } - + if (!unboxable) throw new Error ("Unboxed " ~ value.type.toString ~ " as " ~ typeid(T).toString ~ "; however, unboxable says it should fail."); return result; @@ -757,9 +757,9 @@ unittest class B : A { } struct SA { } struct SB { } - + Box a, b; - + /* Call the function, catch UnboxException, return that it threw correctly. */ bool fails(void delegate()func) { @@ -768,107 +768,107 @@ unittest return true; return false; } - + /* Check that equals and comparison work properly. */ a = box(0); b = box(32); assert (a != b); assert (a == a); assert (a < b); - + /* Check that toString works properly. */ assert (b.toString == "32"); - + /* Assert that unboxable works. */ assert (unboxable!(char[])(box("foobar"))); - + /* Assert that we can cast from int to byte. */ assert (unboxTest!(byte)(b) == 32); - + /* Assert that we can cast from int to real. */ assert (unboxTest!(real)(b) == 32.0L); - + /* Check that real works properly. */ assert (unboxTest!(real)(box(32.45L)) == 32.45L); - + /* Assert that we cannot implicitly cast from real to int. */ assert(fails(delegate void() { unboxTest!(int)(box(1.3)); })); - + /* Check that the unspecialized unbox template works. */ assert(unboxTest!(char[])(box("foobar")) == "foobar"); - + /* Assert that complex works correctly. */ assert(unboxTest!(cdouble)(box(1 + 2i)) == 1 + 2i); - + /* Assert that imaginary works correctly. */ assert(unboxTest!(ireal)(box(45i)) == 45i); - + /* Create an array of boxes from arguments. */ Box[] array = boxArray(16, "foobar", new Object); - + assert(array.length == 3); assert(unboxTest!(int)(array[0]) == 16); assert(unboxTest!(char[])(array[1]) == "foobar"); assert(unboxTest!(Object)(array[2]) !is null); - + /* Convert the box array back into arguments. */ TypeInfo[] array_types; void* array_data; - + boxArrayToArguments(array, array_types, array_data); assert (array_types.length == 3); - + /* Confirm the symmetry. */ assert (boxArray(array_types, array_data) == array); - + /* Assert that we can cast from int to creal. */ assert (unboxTest!(creal)(box(45)) == 45+0i); - + /* Assert that we can cast from idouble to creal. */ assert (unboxTest!(creal)(box(45i)) == 0+45i); - + /* Assert that equality testing casts properly. */ assert (box(1) == box(cast(byte)1)); assert (box(cast(real)4) == box(4)); assert (box(5) == box(5+0i)); assert (box(0+4i) == box(4i)); assert (box(8i) == box(0+8i)); - + /* Assert that comparisons cast properly. */ assert (box(450) < box(451)); assert (box(4) > box(3.0)); assert (box(0+3i) < box(0+4i)); - + /* Assert that casting from bool to int works. */ assert (1 == unboxTest!(int)(box(true))); assert (box(1) == box(true)); - + /* Assert that unboxing to an object works properly. */ assert (unboxTest!(B)(box(cast(A)new B)) !is null); - - /* Assert that illegal object casting fails properly. */ + + /* Assert that illegal object casting fails properly. */ assert (fails(delegate void() { unboxTest!(B)(box(new A)); })); - + /* Assert that we can unbox a null. */ assert (unboxTest!(A)(box(cast(A)null)) is null); assert (unboxTest!(A)(box(null)) is null); - + /* Unboxing null in various contexts. */ assert (unboxTest!(char[])(box(null)) is null); assert (unboxTest!(int*)(box(null)) is null); - + /* Assert that unboxing between pointer types fails. */ int [1] p; assert (fails(delegate void() { unboxTest!(char*)(box(p.ptr)); })); - + /* Assert that unboxing various types as void* does work. */ assert (unboxTest!(void*)(box(p.ptr))); // int* assert (unboxTest!(void*)(box(p))); // int[] assert (unboxTest!(void*)(box(new A))); // Object - + /* Assert that we can't unbox an integer as bool. */ assert (!unboxable!(bool) (box(4))); - + /* Assert that we can't unbox a struct as another struct. */ SA sa; assert (!unboxable!(SB)(box(sa))); diff --git a/std/c/stdarg.d b/std/c/stdarg.d index f2fdb51ad..20859d523 100644 --- a/std/c/stdarg.d +++ b/std/c/stdarg.d @@ -4,7 +4,7 @@ * Authors: Hauke Duden and Walter Bright, Digital Mars, www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCStdarg + * WIKI=Phobos/StdCStdarg */ /* This is for use with extern(C) variable argument lists. */ @@ -17,7 +17,7 @@ template va_start(T) { void va_start(out va_list ap, inout T parmn) { - ap = cast(va_list)(cast(void*)&parmn + ((T.sizeof + int.sizeof - 1) & ~(int.sizeof - 1))); + ap = cast(va_list)(cast(void*)&parmn + ((T.sizeof + int.sizeof - 1) & ~(int.sizeof - 1))); } } @@ -25,9 +25,9 @@ template va_arg(T) { T va_arg(inout va_list ap) { - T arg = *cast(T*)ap; - ap = cast(va_list)(cast(void*)ap + ((T.sizeof + int.sizeof - 1) & ~(int.sizeof - 1))); - return arg; + T arg = *cast(T*)ap; + ap = cast(va_list)(cast(void*)ap + ((T.sizeof + int.sizeof - 1) & ~(int.sizeof - 1))); + return arg; } } diff --git a/std/c/windows/com.d b/std/c/windows/com.d index 52b4ee2a7..8c6d70e78 100644 --- a/std/c/windows/com.d +++ b/std/c/windows/com.d @@ -10,49 +10,49 @@ alias OLECHAR *LPCOLESTR; enum { - rmm = 23, // OLE 2 version number info - rup = 639, + rmm = 23, // OLE 2 version number info + rup = 639, } enum : int { - S_OK = 0, - S_FALSE = 0x00000001, - NOERROR = 0, - E_NOTIMPL = cast(int)0x80004001, - E_NOINTERFACE = cast(int)0x80004002, - E_POINTER = cast(int)0x80004003, - E_ABORT = cast(int)0x80004004, - E_FAIL = cast(int)0x80004005, - E_HANDLE = cast(int)0x80070006, - CLASS_E_NOAGGREGATION = cast(int)0x80040110, - E_OUTOFMEMORY = cast(int)0x8007000E, - E_INVALIDARG = cast(int)0x80070057, - E_UNEXPECTED = cast(int)0x8000FFFF, + S_OK = 0, + S_FALSE = 0x00000001, + NOERROR = 0, + E_NOTIMPL = cast(int)0x80004001, + E_NOINTERFACE = cast(int)0x80004002, + E_POINTER = cast(int)0x80004003, + E_ABORT = cast(int)0x80004004, + E_FAIL = cast(int)0x80004005, + E_HANDLE = cast(int)0x80070006, + CLASS_E_NOAGGREGATION = cast(int)0x80040110, + E_OUTOFMEMORY = cast(int)0x8007000E, + E_INVALIDARG = cast(int)0x80070057, + E_UNEXPECTED = cast(int)0x8000FFFF, } struct GUID { // size is 16 align(1): - DWORD Data1; - WORD Data2; - WORD Data3; - BYTE Data4[8]; + DWORD Data1; + WORD Data2; + WORD Data3; + BYTE Data4[8]; } enum { - CLSCTX_INPROC_SERVER = 0x1, - CLSCTX_INPROC_HANDLER = 0x2, - CLSCTX_LOCAL_SERVER = 0x4, - CLSCTX_INPROC_SERVER16 = 0x8, - CLSCTX_REMOTE_SERVER = 0x10, - CLSCTX_INPROC_HANDLER16 = 0x20, - CLSCTX_INPROC_SERVERX86 = 0x40, - CLSCTX_INPROC_HANDLERX86 = 0x80, + CLSCTX_INPROC_SERVER = 0x1, + CLSCTX_INPROC_HANDLER = 0x2, + CLSCTX_LOCAL_SERVER = 0x4, + CLSCTX_INPROC_SERVER16 = 0x8, + CLSCTX_REMOTE_SERVER = 0x10, + CLSCTX_INPROC_HANDLER16 = 0x20, + CLSCTX_INPROC_SERVERX86 = 0x40, + CLSCTX_INPROC_HANDLERX86 = 0x80, - CLSCTX_INPROC = (CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER), - CLSCTX_ALL = (CLSCTX_INPROC_SERVER| CLSCTX_INPROC_HANDLER| CLSCTX_LOCAL_SERVER), - CLSCTX_SERVER = (CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER), + CLSCTX_INPROC = (CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER), + CLSCTX_ALL = (CLSCTX_INPROC_SERVER| CLSCTX_INPROC_HANDLER| CLSCTX_LOCAL_SERVER), + CLSCTX_SERVER = (CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER), } alias GUID IID; @@ -206,41 +206,41 @@ class ComObject : IUnknown extern (System): HRESULT QueryInterface(IID* riid, void** ppv) { - if (*riid == IID_IUnknown) - { - *ppv = cast(void*)cast(IUnknown)this; - AddRef(); - return S_OK; - } - else - { *ppv = null; - return E_NOINTERFACE; - } + if (*riid == IID_IUnknown) + { + *ppv = cast(void*)cast(IUnknown)this; + AddRef(); + return S_OK; + } + else + { *ppv = null; + return E_NOINTERFACE; + } } ULONG AddRef() { - return InterlockedIncrement(&count); + return InterlockedIncrement(&count); } ULONG Release() { - LONG lRef = InterlockedDecrement(&count); - if (lRef == 0) - { - // free object + LONG lRef = InterlockedDecrement(&count); + if (lRef == 0) + { + // free object - // If we delete this object, then the postinvariant called upon - // return from Release() will fail. - // Just let the GC reap it. - //delete this; + // If we delete this object, then the postinvariant called upon + // return from Release() will fail. + // Just let the GC reap it. + //delete this; - return 0; - } - return cast(ULONG)lRef; + return 0; + } + return cast(ULONG)lRef; } - LONG count = 0; // object reference count + LONG count = 0; // object reference count } } diff --git a/std/c/windows/windows.d b/std/c/windows/windows.d index a3fbab671..5ba406adf 100644 --- a/std/c/windows/windows.d +++ b/std/c/windows/windows.d @@ -9,7 +9,7 @@ version (Windows) } else { - static assert(0); // Windows only + static assert(0); // Windows only } extern (Windows) @@ -165,24 +165,24 @@ enum : uint enum { - ERROR_SUCCESS = 0, - ERROR_INVALID_FUNCTION = 1, - ERROR_FILE_NOT_FOUND = 2, - ERROR_PATH_NOT_FOUND = 3, - ERROR_TOO_MANY_OPEN_FILES = 4, - ERROR_ACCESS_DENIED = 5, - ERROR_INVALID_HANDLE = 6, - ERROR_NO_MORE_FILES = 18, - ERROR_MORE_DATA = 234, - ERROR_NO_MORE_ITEMS = 259, + ERROR_SUCCESS = 0, + ERROR_INVALID_FUNCTION = 1, + ERROR_FILE_NOT_FOUND = 2, + ERROR_PATH_NOT_FOUND = 3, + ERROR_TOO_MANY_OPEN_FILES = 4, + ERROR_ACCESS_DENIED = 5, + ERROR_INVALID_HANDLE = 6, + ERROR_NO_MORE_FILES = 18, + ERROR_MORE_DATA = 234, + ERROR_NO_MORE_ITEMS = 259, } enum { - DLL_PROCESS_ATTACH = 1, - DLL_THREAD_ATTACH = 2, - DLL_THREAD_DETACH = 3, - DLL_PROCESS_DETACH = 0, + DLL_PROCESS_ATTACH = 1, + DLL_THREAD_ATTACH = 2, + DLL_THREAD_DETACH = 3, + DLL_PROCESS_DETACH = 0, } enum @@ -219,41 +219,41 @@ enum { FILE_SHARE_READ = 0x00000001, FILE_SHARE_WRITE = 0x00000002, - FILE_SHARE_DELETE = 0x00000004, - FILE_ATTRIBUTE_READONLY = 0x00000001, - FILE_ATTRIBUTE_HIDDEN = 0x00000002, - FILE_ATTRIBUTE_SYSTEM = 0x00000004, - FILE_ATTRIBUTE_DIRECTORY = 0x00000010, - FILE_ATTRIBUTE_ARCHIVE = 0x00000020, - FILE_ATTRIBUTE_NORMAL = 0x00000080, - FILE_ATTRIBUTE_TEMPORARY = 0x00000100, - FILE_ATTRIBUTE_COMPRESSED = 0x00000800, - FILE_ATTRIBUTE_OFFLINE = 0x00001000, - FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001, - FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002, - FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004, - FILE_NOTIFY_CHANGE_SIZE = 0x00000008, - FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010, - FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020, - FILE_NOTIFY_CHANGE_CREATION = 0x00000040, - FILE_NOTIFY_CHANGE_SECURITY = 0x00000100, - FILE_ACTION_ADDED = 0x00000001, - FILE_ACTION_REMOVED = 0x00000002, - FILE_ACTION_MODIFIED = 0x00000003, - FILE_ACTION_RENAMED_OLD_NAME = 0x00000004, - FILE_ACTION_RENAMED_NEW_NAME = 0x00000005, - FILE_CASE_SENSITIVE_SEARCH = 0x00000001, - FILE_CASE_PRESERVED_NAMES = 0x00000002, - FILE_UNICODE_ON_DISK = 0x00000004, - FILE_PERSISTENT_ACLS = 0x00000008, - FILE_FILE_COMPRESSION = 0x00000010, - FILE_VOLUME_IS_COMPRESSED = 0x00008000, + FILE_SHARE_DELETE = 0x00000004, + FILE_ATTRIBUTE_READONLY = 0x00000001, + FILE_ATTRIBUTE_HIDDEN = 0x00000002, + FILE_ATTRIBUTE_SYSTEM = 0x00000004, + FILE_ATTRIBUTE_DIRECTORY = 0x00000010, + FILE_ATTRIBUTE_ARCHIVE = 0x00000020, + FILE_ATTRIBUTE_NORMAL = 0x00000080, + FILE_ATTRIBUTE_TEMPORARY = 0x00000100, + FILE_ATTRIBUTE_COMPRESSED = 0x00000800, + FILE_ATTRIBUTE_OFFLINE = 0x00001000, + FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001, + FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002, + FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004, + FILE_NOTIFY_CHANGE_SIZE = 0x00000008, + FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010, + FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020, + FILE_NOTIFY_CHANGE_CREATION = 0x00000040, + FILE_NOTIFY_CHANGE_SECURITY = 0x00000100, + FILE_ACTION_ADDED = 0x00000001, + FILE_ACTION_REMOVED = 0x00000002, + FILE_ACTION_MODIFIED = 0x00000003, + FILE_ACTION_RENAMED_OLD_NAME = 0x00000004, + FILE_ACTION_RENAMED_NEW_NAME = 0x00000005, + FILE_CASE_SENSITIVE_SEARCH = 0x00000001, + FILE_CASE_PRESERVED_NAMES = 0x00000002, + FILE_UNICODE_ON_DISK = 0x00000004, + FILE_PERSISTENT_ACLS = 0x00000008, + FILE_FILE_COMPRESSION = 0x00000010, + FILE_VOLUME_IS_COMPRESSED = 0x00008000, } enum { MAILSLOT_NO_MESSAGE = cast(DWORD)-1, - MAILSLOT_WAIT_FOREVER = cast(DWORD)-1, + MAILSLOT_WAIT_FOREVER = cast(DWORD)-1, } enum : uint @@ -335,9 +335,9 @@ struct WIN32_FIND_DATAW { enum { - STD_INPUT_HANDLE = cast(DWORD)-10, - STD_OUTPUT_HANDLE = cast(DWORD)-11, - STD_ERROR_HANDLE = cast(DWORD)-12, + STD_INPUT_HANDLE = cast(DWORD)-10, + STD_OUTPUT_HANDLE = cast(DWORD)-11, + STD_ERROR_HANDLE = cast(DWORD)-12, } export @@ -356,11 +356,11 @@ BOOL RemoveDirectoryW(LPCWSTR lpPathName); BOOL CloseHandle(HANDLE hObject); HANDLE CreateFileA(char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); + SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); + SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); BOOL DeleteFileA(char *lpFileName); BOOL DeleteFileW(LPCWSTR lpFileName); @@ -380,11 +380,11 @@ BOOL CopyFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIf BOOL MoveFileA(char *from, char *to); BOOL MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName); BOOL ReadFile(HANDLE hFile, void *lpBuffer, DWORD nNumberOfBytesToRead, - DWORD *lpNumberOfBytesRead, OVERLAPPED *lpOverlapped); + DWORD *lpNumberOfBytesRead, OVERLAPPED *lpOverlapped); DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, - LONG *lpDistanceToMoveHigh, DWORD dwMoveMethod); + LONG *lpDistanceToMoveHigh, DWORD dwMoveMethod); BOOL WriteFile(HANDLE hFile, void *lpBuffer, DWORD nNumberOfBytesToWrite, - DWORD *lpNumberOfBytesWritten, OVERLAPPED *lpOverlapped); + DWORD *lpNumberOfBytesWritten, OVERLAPPED *lpOverlapped); DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize); } @@ -425,17 +425,17 @@ BOOL DisableThreadLibraryCalls(HMODULE hLibModule); enum { - KEY_QUERY_VALUE = 0x0001, - KEY_SET_VALUE = 0x0002, - KEY_CREATE_SUB_KEY = 0x0004, - KEY_ENUMERATE_SUB_KEYS = 0x0008, - KEY_NOTIFY = 0x0010, - KEY_CREATE_LINK = 0x0020, + KEY_QUERY_VALUE = 0x0001, + KEY_SET_VALUE = 0x0002, + KEY_CREATE_SUB_KEY = 0x0004, + KEY_ENUMERATE_SUB_KEYS = 0x0008, + KEY_NOTIFY = 0x0010, + KEY_CREATE_LINK = 0x0020, - KEY_READ = cast(int)((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & ~SYNCHRONIZE), - KEY_WRITE = cast(int)((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & ~SYNCHRONIZE), - KEY_EXECUTE = cast(int)(KEY_READ & ~SYNCHRONIZE), - KEY_ALL_ACCESS = cast(int)((STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | KEY_CREATE_LINK) & ~SYNCHRONIZE), + KEY_READ = cast(int)((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & ~SYNCHRONIZE), + KEY_WRITE = cast(int)((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & ~SYNCHRONIZE), + KEY_EXECUTE = cast(int)(KEY_READ & ~SYNCHRONIZE), + KEY_ALL_ACCESS = cast(int)((STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | KEY_CREATE_LINK) & ~SYNCHRONIZE), } // @@ -444,8 +444,8 @@ enum enum : int { - REG_CREATED_NEW_KEY = 0x00000001, // New Registry Key created - REG_OPENED_EXISTING_KEY = 0x00000002, // Existing Key opened + REG_CREATED_NEW_KEY = 0x00000001, // New Registry Key created + REG_OPENED_EXISTING_KEY = 0x00000002, // Existing Key opened } @@ -455,21 +455,21 @@ enum : int // enum { - REG_NONE = 0, // No value type - REG_SZ = 1, // Unicode nul terminated string - REG_EXPAND_SZ = 2, // Unicode nul terminated string + REG_NONE = 0, // No value type + REG_SZ = 1, // Unicode nul terminated string + REG_EXPAND_SZ = 2, // Unicode nul terminated string // (with environment variable references) - REG_BINARY = 3, // Free form binary - REG_DWORD = 4, // 32-bit number - REG_DWORD_LITTLE_ENDIAN = 4, // 32-bit number (same as REG_DWORD) - REG_DWORD_BIG_ENDIAN = 5, // 32-bit number - REG_LINK = 6, // Symbolic Link (unicode) - REG_MULTI_SZ = 7, // Multiple Unicode strings - REG_RESOURCE_LIST = 8, // Resource list in the resource map - REG_FULL_RESOURCE_DESCRIPTOR = 9, // Resource list in the hardware description - REG_RESOURCE_REQUIREMENTS_LIST = 10, - REG_QWORD = 11, - REG_QWORD_LITTLE_ENDIAN = 11, + REG_BINARY = 3, // Free form binary + REG_DWORD = 4, // 32-bit number + REG_DWORD_LITTLE_ENDIAN = 4, // 32-bit number (same as REG_DWORD) + REG_DWORD_BIG_ENDIAN = 5, // 32-bit number + REG_LINK = 6, // Symbolic Link (unicode) + REG_MULTI_SZ = 7, // Multiple Unicode strings + REG_RESOURCE_LIST = 8, // Resource list in the resource map + REG_FULL_RESOURCE_DESCRIPTOR = 9, // Resource list in the hardware description + REG_RESOURCE_REQUIREMENTS_LIST = 10, + REG_QWORD = 11, + REG_QWORD_LITTLE_ENDIAN = 11, } /* @@ -477,57 +477,57 @@ enum */ enum { - MB_OK = 0x00000000, - MB_OKCANCEL = 0x00000001, - MB_ABORTRETRYIGNORE = 0x00000002, - MB_YESNOCANCEL = 0x00000003, - MB_YESNO = 0x00000004, - MB_RETRYCANCEL = 0x00000005, + MB_OK = 0x00000000, + MB_OKCANCEL = 0x00000001, + MB_ABORTRETRYIGNORE = 0x00000002, + MB_YESNOCANCEL = 0x00000003, + MB_YESNO = 0x00000004, + MB_RETRYCANCEL = 0x00000005, - MB_ICONHAND = 0x00000010, - MB_ICONQUESTION = 0x00000020, - MB_ICONEXCLAMATION = 0x00000030, - MB_ICONASTERISK = 0x00000040, + MB_ICONHAND = 0x00000010, + MB_ICONQUESTION = 0x00000020, + MB_ICONEXCLAMATION = 0x00000030, + MB_ICONASTERISK = 0x00000040, - MB_USERICON = 0x00000080, - MB_ICONWARNING = MB_ICONEXCLAMATION, - MB_ICONERROR = MB_ICONHAND, + MB_USERICON = 0x00000080, + MB_ICONWARNING = MB_ICONEXCLAMATION, + MB_ICONERROR = MB_ICONHAND, - MB_ICONINFORMATION = MB_ICONASTERISK, - MB_ICONSTOP = MB_ICONHAND, + MB_ICONINFORMATION = MB_ICONASTERISK, + MB_ICONSTOP = MB_ICONHAND, - MB_DEFBUTTON1 = 0x00000000, - MB_DEFBUTTON2 = 0x00000100, - MB_DEFBUTTON3 = 0x00000200, + MB_DEFBUTTON1 = 0x00000000, + MB_DEFBUTTON2 = 0x00000100, + MB_DEFBUTTON3 = 0x00000200, - MB_DEFBUTTON4 = 0x00000300, + MB_DEFBUTTON4 = 0x00000300, - MB_APPLMODAL = 0x00000000, - MB_SYSTEMMODAL = 0x00001000, - MB_TASKMODAL = 0x00002000, + MB_APPLMODAL = 0x00000000, + MB_SYSTEMMODAL = 0x00001000, + MB_TASKMODAL = 0x00002000, - MB_HELP = 0x00004000, // Help Button + MB_HELP = 0x00004000, // Help Button - MB_NOFOCUS = 0x00008000, - MB_SETFOREGROUND = 0x00010000, - MB_DEFAULT_DESKTOP_ONLY = 0x00020000, + MB_NOFOCUS = 0x00008000, + MB_SETFOREGROUND = 0x00010000, + MB_DEFAULT_DESKTOP_ONLY = 0x00020000, - MB_TOPMOST = 0x00040000, - MB_RIGHT = 0x00080000, - MB_RTLREADING = 0x00100000, + MB_TOPMOST = 0x00040000, + MB_RIGHT = 0x00080000, + MB_RTLREADING = 0x00100000, - MB_TYPEMASK = 0x0000000F, - MB_ICONMASK = 0x000000F0, - MB_DEFMASK = 0x00000F00, - MB_MODEMASK = 0x00003000, - MB_MISCMASK = 0x0000C000, + MB_TYPEMASK = 0x0000000F, + MB_ICONMASK = 0x000000F0, + MB_DEFMASK = 0x00000F00, + MB_MODEMASK = 0x00003000, + MB_MISCMASK = 0x0000C000, } @@ -546,24 +546,24 @@ const HKEY HKEY_DYN_DATA = cast(HKEY)(0x80000006); enum { - REG_OPTION_RESERVED = (0x00000000), // Parameter is reserved + REG_OPTION_RESERVED = (0x00000000), // Parameter is reserved - REG_OPTION_NON_VOLATILE = (0x00000000), // Key is preserved + REG_OPTION_NON_VOLATILE = (0x00000000), // Key is preserved // when system is rebooted - REG_OPTION_VOLATILE = (0x00000001), // Key is not preserved + REG_OPTION_VOLATILE = (0x00000001), // Key is not preserved // when system is rebooted - REG_OPTION_CREATE_LINK = (0x00000002), // Created key is a + REG_OPTION_CREATE_LINK = (0x00000002), // Created key is a // symbolic link - REG_OPTION_BACKUP_RESTORE = (0x00000004), // open for backup or restore + REG_OPTION_BACKUP_RESTORE = (0x00000004), // open for backup or restore // special access rules // privilege required - REG_OPTION_OPEN_LINK = (0x00000008), // Open symbolic link + REG_OPTION_OPEN_LINK = (0x00000008), // Open symbolic link - REG_LEGAL_OPTION = (REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK), + REG_LEGAL_OPTION = (REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE | REG_OPTION_OPEN_LINK), } export LONG RegDeleteKeyA(HKEY hKey, LPCSTR lpSubKey); @@ -606,46 +606,46 @@ alias MEMORY_BASIC_INFORMATION* PMEMORY_BASIC_INFORMATION; enum { - SECTION_QUERY = 0x0001, - SECTION_MAP_WRITE = 0x0002, - SECTION_MAP_READ = 0x0004, - SECTION_MAP_EXECUTE = 0x0008, - SECTION_EXTEND_SIZE = 0x0010, + SECTION_QUERY = 0x0001, + SECTION_MAP_WRITE = 0x0002, + SECTION_MAP_READ = 0x0004, + SECTION_MAP_EXECUTE = 0x0008, + SECTION_EXTEND_SIZE = 0x0010, - SECTION_ALL_ACCESS = cast(int)(STANDARD_RIGHTS_REQUIRED|SECTION_QUERY| SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE), - PAGE_NOACCESS = 0x01, - PAGE_READONLY = 0x02, - PAGE_READWRITE = 0x04, - PAGE_WRITECOPY = 0x08, - PAGE_EXECUTE = 0x10, - PAGE_EXECUTE_READ = 0x20, - PAGE_EXECUTE_READWRITE = 0x40, - PAGE_EXECUTE_WRITECOPY = 0x80, - PAGE_GUARD = 0x100, - PAGE_NOCACHE = 0x200, - MEM_COMMIT = 0x1000, - MEM_RESERVE = 0x2000, - MEM_DECOMMIT = 0x4000, - MEM_RELEASE = 0x8000, - MEM_FREE = 0x10000, - MEM_PRIVATE = 0x20000, - MEM_MAPPED = 0x40000, - MEM_RESET = 0x80000, - MEM_TOP_DOWN = 0x100000, - SEC_FILE = 0x800000, - SEC_IMAGE = 0x1000000, - SEC_RESERVE = 0x4000000, - SEC_COMMIT = 0x8000000, - SEC_NOCACHE = 0x10000000, - MEM_IMAGE = SEC_IMAGE, + SECTION_ALL_ACCESS = cast(int)(STANDARD_RIGHTS_REQUIRED|SECTION_QUERY| SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE), + PAGE_NOACCESS = 0x01, + PAGE_READONLY = 0x02, + PAGE_READWRITE = 0x04, + PAGE_WRITECOPY = 0x08, + PAGE_EXECUTE = 0x10, + PAGE_EXECUTE_READ = 0x20, + PAGE_EXECUTE_READWRITE = 0x40, + PAGE_EXECUTE_WRITECOPY = 0x80, + PAGE_GUARD = 0x100, + PAGE_NOCACHE = 0x200, + MEM_COMMIT = 0x1000, + MEM_RESERVE = 0x2000, + MEM_DECOMMIT = 0x4000, + MEM_RELEASE = 0x8000, + MEM_FREE = 0x10000, + MEM_PRIVATE = 0x20000, + MEM_MAPPED = 0x40000, + MEM_RESET = 0x80000, + MEM_TOP_DOWN = 0x100000, + SEC_FILE = 0x800000, + SEC_IMAGE = 0x1000000, + SEC_RESERVE = 0x4000000, + SEC_COMMIT = 0x8000000, + SEC_NOCACHE = 0x10000000, + MEM_IMAGE = SEC_IMAGE, } enum { - FILE_MAP_COPY = SECTION_QUERY, - FILE_MAP_WRITE = SECTION_MAP_WRITE, - FILE_MAP_READ = SECTION_MAP_READ, - FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS, + FILE_MAP_COPY = SECTION_QUERY, + FILE_MAP_WRITE = SECTION_MAP_WRITE, + FILE_MAP_READ = SECTION_MAP_READ, + FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS, } @@ -663,36 +663,36 @@ enum enum { - FILE_READ_DATA = ( 0x0001 ), // file & pipe - FILE_LIST_DIRECTORY = ( 0x0001 ), // directory + FILE_READ_DATA = ( 0x0001 ), // file & pipe + FILE_LIST_DIRECTORY = ( 0x0001 ), // directory - FILE_WRITE_DATA = ( 0x0002 ), // file & pipe - FILE_ADD_FILE = ( 0x0002 ), // directory + FILE_WRITE_DATA = ( 0x0002 ), // file & pipe + FILE_ADD_FILE = ( 0x0002 ), // directory - FILE_APPEND_DATA = ( 0x0004 ), // file - FILE_ADD_SUBDIRECTORY = ( 0x0004 ), // directory - FILE_CREATE_PIPE_INSTANCE = ( 0x0004 ), // named pipe + FILE_APPEND_DATA = ( 0x0004 ), // file + FILE_ADD_SUBDIRECTORY = ( 0x0004 ), // directory + FILE_CREATE_PIPE_INSTANCE = ( 0x0004 ), // named pipe - FILE_READ_EA = ( 0x0008 ), // file & directory + FILE_READ_EA = ( 0x0008 ), // file & directory - FILE_WRITE_EA = ( 0x0010 ), // file & directory + FILE_WRITE_EA = ( 0x0010 ), // file & directory - FILE_EXECUTE = ( 0x0020 ), // file - FILE_TRAVERSE = ( 0x0020 ), // directory + FILE_EXECUTE = ( 0x0020 ), // file + FILE_TRAVERSE = ( 0x0020 ), // directory - FILE_DELETE_CHILD = ( 0x0040 ), // directory + FILE_DELETE_CHILD = ( 0x0040 ), // directory - FILE_READ_ATTRIBUTES = ( 0x0080 ), // all + FILE_READ_ATTRIBUTES = ( 0x0080 ), // all - FILE_WRITE_ATTRIBUTES = ( 0x0100 ), // all + FILE_WRITE_ATTRIBUTES = ( 0x0100 ), // all - FILE_ALL_ACCESS = cast(int)(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF), + FILE_ALL_ACCESS = cast(int)(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF), - FILE_GENERIC_READ = cast(int)(STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE), + FILE_GENERIC_READ = cast(int)(STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE), - FILE_GENERIC_WRITE = cast(int)(STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE), + FILE_GENERIC_WRITE = cast(int)(STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE), - FILE_GENERIC_EXECUTE = cast(int)(STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE), + FILE_GENERIC_EXECUTE = cast(int)(STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE), } export @@ -750,9 +750,9 @@ struct TIME_ZONE_INFORMATION { enum { - TIME_ZONE_ID_UNKNOWN = 0, - TIME_ZONE_ID_STANDARD = 1, - TIME_ZONE_ID_DAYLIGHT = 2, + TIME_ZONE_ID_UNKNOWN = 0, + TIME_ZONE_ID_STANDARD = 1, + TIME_ZONE_ID_DAYLIGHT = 2, } export void GetSystemTime(SYSTEMTIME* lpSystemTime); @@ -778,13 +778,13 @@ export DWORD FormatMessageA(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, enum { - FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100, - FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, - FORMAT_MESSAGE_FROM_STRING = 0x00000400, - FORMAT_MESSAGE_FROM_HMODULE = 0x00000800, - FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, - FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000, - FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF, + FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100, + FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, + FORMAT_MESSAGE_FROM_STRING = 0x00000400, + FORMAT_MESSAGE_FROM_HMODULE = 0x00000800, + FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, + FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000, + FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF, }; @@ -807,51 +807,51 @@ enum enum { - LANG_NEUTRAL = 0x00, + LANG_NEUTRAL = 0x00, - LANG_AFRIKAANS = 0x36, - LANG_ALBANIAN = 0x1c, - LANG_ARABIC = 0x01, - LANG_BASQUE = 0x2d, - LANG_BELARUSIAN = 0x23, - LANG_BULGARIAN = 0x02, - LANG_CATALAN = 0x03, - LANG_CHINESE = 0x04, - LANG_CROATIAN = 0x1a, - LANG_CZECH = 0x05, - LANG_DANISH = 0x06, - LANG_DUTCH = 0x13, - LANG_ENGLISH = 0x09, - LANG_ESTONIAN = 0x25, - LANG_FAEROESE = 0x38, - LANG_FARSI = 0x29, - LANG_FINNISH = 0x0b, - LANG_FRENCH = 0x0c, - LANG_GERMAN = 0x07, - LANG_GREEK = 0x08, - LANG_HEBREW = 0x0d, - LANG_HUNGARIAN = 0x0e, - LANG_ICELANDIC = 0x0f, - LANG_INDONESIAN = 0x21, - LANG_ITALIAN = 0x10, - LANG_JAPANESE = 0x11, - LANG_KOREAN = 0x12, - LANG_LATVIAN = 0x26, - LANG_LITHUANIAN = 0x27, - LANG_NORWEGIAN = 0x14, - LANG_POLISH = 0x15, - LANG_PORTUGUESE = 0x16, - LANG_ROMANIAN = 0x18, - LANG_RUSSIAN = 0x19, - LANG_SERBIAN = 0x1a, - LANG_SLOVAK = 0x1b, - LANG_SLOVENIAN = 0x24, - LANG_SPANISH = 0x0a, - LANG_SWEDISH = 0x1d, - LANG_THAI = 0x1e, - LANG_TURKISH = 0x1f, - LANG_UKRAINIAN = 0x22, - LANG_VIETNAMESE = 0x2a, + LANG_AFRIKAANS = 0x36, + LANG_ALBANIAN = 0x1c, + LANG_ARABIC = 0x01, + LANG_BASQUE = 0x2d, + LANG_BELARUSIAN = 0x23, + LANG_BULGARIAN = 0x02, + LANG_CATALAN = 0x03, + LANG_CHINESE = 0x04, + LANG_CROATIAN = 0x1a, + LANG_CZECH = 0x05, + LANG_DANISH = 0x06, + LANG_DUTCH = 0x13, + LANG_ENGLISH = 0x09, + LANG_ESTONIAN = 0x25, + LANG_FAEROESE = 0x38, + LANG_FARSI = 0x29, + LANG_FINNISH = 0x0b, + LANG_FRENCH = 0x0c, + LANG_GERMAN = 0x07, + LANG_GREEK = 0x08, + LANG_HEBREW = 0x0d, + LANG_HUNGARIAN = 0x0e, + LANG_ICELANDIC = 0x0f, + LANG_INDONESIAN = 0x21, + LANG_ITALIAN = 0x10, + LANG_JAPANESE = 0x11, + LANG_KOREAN = 0x12, + LANG_LATVIAN = 0x26, + LANG_LITHUANIAN = 0x27, + LANG_NORWEGIAN = 0x14, + LANG_POLISH = 0x15, + LANG_PORTUGUESE = 0x16, + LANG_ROMANIAN = 0x18, + LANG_RUSSIAN = 0x19, + LANG_SERBIAN = 0x1a, + LANG_SLOVAK = 0x1b, + LANG_SLOVENIAN = 0x24, + LANG_SPANISH = 0x0a, + LANG_SWEDISH = 0x1d, + LANG_THAI = 0x1e, + LANG_TURKISH = 0x1f, + LANG_UKRAINIAN = 0x22, + LANG_VIETNAMESE = 0x2a, } // // Sublanguage IDs. @@ -862,85 +862,85 @@ enum // enum { - SUBLANG_NEUTRAL = 0x00, // language neutral - SUBLANG_DEFAULT = 0x01, // user default - SUBLANG_SYS_DEFAULT = 0x02, // system default + SUBLANG_NEUTRAL = 0x00, // language neutral + SUBLANG_DEFAULT = 0x01, // user default + SUBLANG_SYS_DEFAULT = 0x02, // system default - SUBLANG_ARABIC_SAUDI_ARABIA = 0x01, // Arabic (Saudi Arabia) - SUBLANG_ARABIC_IRAQ = 0x02, // Arabic (Iraq) - SUBLANG_ARABIC_EGYPT = 0x03, // Arabic (Egypt) - SUBLANG_ARABIC_LIBYA = 0x04, // Arabic (Libya) - SUBLANG_ARABIC_ALGERIA = 0x05, // Arabic (Algeria) - SUBLANG_ARABIC_MOROCCO = 0x06, // Arabic (Morocco) - SUBLANG_ARABIC_TUNISIA = 0x07, // Arabic (Tunisia) - SUBLANG_ARABIC_OMAN = 0x08, // Arabic (Oman) - SUBLANG_ARABIC_YEMEN = 0x09, // Arabic (Yemen) - SUBLANG_ARABIC_SYRIA = 0x0a, // Arabic (Syria) - SUBLANG_ARABIC_JORDAN = 0x0b, // Arabic (Jordan) - SUBLANG_ARABIC_LEBANON = 0x0c, // Arabic (Lebanon) - SUBLANG_ARABIC_KUWAIT = 0x0d, // Arabic (Kuwait) - SUBLANG_ARABIC_UAE = 0x0e, // Arabic (U.A.E) - SUBLANG_ARABIC_BAHRAIN = 0x0f, // Arabic (Bahrain) - SUBLANG_ARABIC_QATAR = 0x10, // Arabic (Qatar) - SUBLANG_CHINESE_TRADITIONAL = 0x01, // Chinese (Taiwan) - SUBLANG_CHINESE_SIMPLIFIED = 0x02, // Chinese (PR China) - SUBLANG_CHINESE_HONGKONG = 0x03, // Chinese (Hong Kong) - SUBLANG_CHINESE_SINGAPORE = 0x04, // Chinese (Singapore) - SUBLANG_DUTCH = 0x01, // Dutch - SUBLANG_DUTCH_BELGIAN = 0x02, // Dutch (Belgian) - SUBLANG_ENGLISH_US = 0x01, // English (USA) - SUBLANG_ENGLISH_UK = 0x02, // English (UK) - SUBLANG_ENGLISH_AUS = 0x03, // English (Australian) - SUBLANG_ENGLISH_CAN = 0x04, // English (Canadian) - SUBLANG_ENGLISH_NZ = 0x05, // English (New Zealand) - SUBLANG_ENGLISH_EIRE = 0x06, // English (Irish) - SUBLANG_ENGLISH_SOUTH_AFRICA = 0x07, // English (South Africa) - SUBLANG_ENGLISH_JAMAICA = 0x08, // English (Jamaica) - SUBLANG_ENGLISH_CARIBBEAN = 0x09, // English (Caribbean) - SUBLANG_ENGLISH_BELIZE = 0x0a, // English (Belize) - SUBLANG_ENGLISH_TRINIDAD = 0x0b, // English (Trinidad) - SUBLANG_FRENCH = 0x01, // French - SUBLANG_FRENCH_BELGIAN = 0x02, // French (Belgian) - SUBLANG_FRENCH_CANADIAN = 0x03, // French (Canadian) - SUBLANG_FRENCH_SWISS = 0x04, // French (Swiss) - SUBLANG_FRENCH_LUXEMBOURG = 0x05, // French (Luxembourg) - SUBLANG_GERMAN = 0x01, // German - SUBLANG_GERMAN_SWISS = 0x02, // German (Swiss) - SUBLANG_GERMAN_AUSTRIAN = 0x03, // German (Austrian) - SUBLANG_GERMAN_LUXEMBOURG = 0x04, // German (Luxembourg) - SUBLANG_GERMAN_LIECHTENSTEIN = 0x05, // German (Liechtenstein) - SUBLANG_ITALIAN = 0x01, // Italian - SUBLANG_ITALIAN_SWISS = 0x02, // Italian (Swiss) - SUBLANG_KOREAN = 0x01, // Korean (Extended Wansung) - SUBLANG_KOREAN_JOHAB = 0x02, // Korean (Johab) - SUBLANG_NORWEGIAN_BOKMAL = 0x01, // Norwegian (Bokmal) - SUBLANG_NORWEGIAN_NYNORSK = 0x02, // Norwegian (Nynorsk) - SUBLANG_PORTUGUESE = 0x02, // Portuguese - SUBLANG_PORTUGUESE_BRAZILIAN = 0x01, // Portuguese (Brazilian) - SUBLANG_SERBIAN_LATIN = 0x02, // Serbian (Latin) - SUBLANG_SERBIAN_CYRILLIC = 0x03, // Serbian (Cyrillic) - SUBLANG_SPANISH = 0x01, // Spanish (Castilian) - SUBLANG_SPANISH_MEXICAN = 0x02, // Spanish (Mexican) - SUBLANG_SPANISH_MODERN = 0x03, // Spanish (Modern) - SUBLANG_SPANISH_GUATEMALA = 0x04, // Spanish (Guatemala) - SUBLANG_SPANISH_COSTA_RICA = 0x05, // Spanish (Costa Rica) - SUBLANG_SPANISH_PANAMA = 0x06, // Spanish (Panama) - SUBLANG_SPANISH_DOMINICAN_REPUBLIC = 0x07, // Spanish (Dominican Republic) - SUBLANG_SPANISH_VENEZUELA = 0x08, // Spanish (Venezuela) - SUBLANG_SPANISH_COLOMBIA = 0x09, // Spanish (Colombia) - SUBLANG_SPANISH_PERU = 0x0a, // Spanish (Peru) - SUBLANG_SPANISH_ARGENTINA = 0x0b, // Spanish (Argentina) - SUBLANG_SPANISH_ECUADOR = 0x0c, // Spanish (Ecuador) - SUBLANG_SPANISH_CHILE = 0x0d, // Spanish (Chile) - SUBLANG_SPANISH_URUGUAY = 0x0e, // Spanish (Uruguay) - SUBLANG_SPANISH_PARAGUAY = 0x0f, // Spanish (Paraguay) - SUBLANG_SPANISH_BOLIVIA = 0x10, // Spanish (Bolivia) - SUBLANG_SPANISH_EL_SALVADOR = 0x11, // Spanish (El Salvador) - SUBLANG_SPANISH_HONDURAS = 0x12, // Spanish (Honduras) - SUBLANG_SPANISH_NICARAGUA = 0x13, // Spanish (Nicaragua) - SUBLANG_SPANISH_PUERTO_RICO = 0x14, // Spanish (Puerto Rico) - SUBLANG_SWEDISH = 0x01, // Swedish - SUBLANG_SWEDISH_FINLAND = 0x02, // Swedish (Finland) + SUBLANG_ARABIC_SAUDI_ARABIA = 0x01, // Arabic (Saudi Arabia) + SUBLANG_ARABIC_IRAQ = 0x02, // Arabic (Iraq) + SUBLANG_ARABIC_EGYPT = 0x03, // Arabic (Egypt) + SUBLANG_ARABIC_LIBYA = 0x04, // Arabic (Libya) + SUBLANG_ARABIC_ALGERIA = 0x05, // Arabic (Algeria) + SUBLANG_ARABIC_MOROCCO = 0x06, // Arabic (Morocco) + SUBLANG_ARABIC_TUNISIA = 0x07, // Arabic (Tunisia) + SUBLANG_ARABIC_OMAN = 0x08, // Arabic (Oman) + SUBLANG_ARABIC_YEMEN = 0x09, // Arabic (Yemen) + SUBLANG_ARABIC_SYRIA = 0x0a, // Arabic (Syria) + SUBLANG_ARABIC_JORDAN = 0x0b, // Arabic (Jordan) + SUBLANG_ARABIC_LEBANON = 0x0c, // Arabic (Lebanon) + SUBLANG_ARABIC_KUWAIT = 0x0d, // Arabic (Kuwait) + SUBLANG_ARABIC_UAE = 0x0e, // Arabic (U.A.E) + SUBLANG_ARABIC_BAHRAIN = 0x0f, // Arabic (Bahrain) + SUBLANG_ARABIC_QATAR = 0x10, // Arabic (Qatar) + SUBLANG_CHINESE_TRADITIONAL = 0x01, // Chinese (Taiwan) + SUBLANG_CHINESE_SIMPLIFIED = 0x02, // Chinese (PR China) + SUBLANG_CHINESE_HONGKONG = 0x03, // Chinese (Hong Kong) + SUBLANG_CHINESE_SINGAPORE = 0x04, // Chinese (Singapore) + SUBLANG_DUTCH = 0x01, // Dutch + SUBLANG_DUTCH_BELGIAN = 0x02, // Dutch (Belgian) + SUBLANG_ENGLISH_US = 0x01, // English (USA) + SUBLANG_ENGLISH_UK = 0x02, // English (UK) + SUBLANG_ENGLISH_AUS = 0x03, // English (Australian) + SUBLANG_ENGLISH_CAN = 0x04, // English (Canadian) + SUBLANG_ENGLISH_NZ = 0x05, // English (New Zealand) + SUBLANG_ENGLISH_EIRE = 0x06, // English (Irish) + SUBLANG_ENGLISH_SOUTH_AFRICA = 0x07, // English (South Africa) + SUBLANG_ENGLISH_JAMAICA = 0x08, // English (Jamaica) + SUBLANG_ENGLISH_CARIBBEAN = 0x09, // English (Caribbean) + SUBLANG_ENGLISH_BELIZE = 0x0a, // English (Belize) + SUBLANG_ENGLISH_TRINIDAD = 0x0b, // English (Trinidad) + SUBLANG_FRENCH = 0x01, // French + SUBLANG_FRENCH_BELGIAN = 0x02, // French (Belgian) + SUBLANG_FRENCH_CANADIAN = 0x03, // French (Canadian) + SUBLANG_FRENCH_SWISS = 0x04, // French (Swiss) + SUBLANG_FRENCH_LUXEMBOURG = 0x05, // French (Luxembourg) + SUBLANG_GERMAN = 0x01, // German + SUBLANG_GERMAN_SWISS = 0x02, // German (Swiss) + SUBLANG_GERMAN_AUSTRIAN = 0x03, // German (Austrian) + SUBLANG_GERMAN_LUXEMBOURG = 0x04, // German (Luxembourg) + SUBLANG_GERMAN_LIECHTENSTEIN = 0x05, // German (Liechtenstein) + SUBLANG_ITALIAN = 0x01, // Italian + SUBLANG_ITALIAN_SWISS = 0x02, // Italian (Swiss) + SUBLANG_KOREAN = 0x01, // Korean (Extended Wansung) + SUBLANG_KOREAN_JOHAB = 0x02, // Korean (Johab) + SUBLANG_NORWEGIAN_BOKMAL = 0x01, // Norwegian (Bokmal) + SUBLANG_NORWEGIAN_NYNORSK = 0x02, // Norwegian (Nynorsk) + SUBLANG_PORTUGUESE = 0x02, // Portuguese + SUBLANG_PORTUGUESE_BRAZILIAN = 0x01, // Portuguese (Brazilian) + SUBLANG_SERBIAN_LATIN = 0x02, // Serbian (Latin) + SUBLANG_SERBIAN_CYRILLIC = 0x03, // Serbian (Cyrillic) + SUBLANG_SPANISH = 0x01, // Spanish (Castilian) + SUBLANG_SPANISH_MEXICAN = 0x02, // Spanish (Mexican) + SUBLANG_SPANISH_MODERN = 0x03, // Spanish (Modern) + SUBLANG_SPANISH_GUATEMALA = 0x04, // Spanish (Guatemala) + SUBLANG_SPANISH_COSTA_RICA = 0x05, // Spanish (Costa Rica) + SUBLANG_SPANISH_PANAMA = 0x06, // Spanish (Panama) + SUBLANG_SPANISH_DOMINICAN_REPUBLIC = 0x07, // Spanish (Dominican Republic) + SUBLANG_SPANISH_VENEZUELA = 0x08, // Spanish (Venezuela) + SUBLANG_SPANISH_COLOMBIA = 0x09, // Spanish (Colombia) + SUBLANG_SPANISH_PERU = 0x0a, // Spanish (Peru) + SUBLANG_SPANISH_ARGENTINA = 0x0b, // Spanish (Argentina) + SUBLANG_SPANISH_ECUADOR = 0x0c, // Spanish (Ecuador) + SUBLANG_SPANISH_CHILE = 0x0d, // Spanish (Chile) + SUBLANG_SPANISH_URUGUAY = 0x0e, // Spanish (Uruguay) + SUBLANG_SPANISH_PARAGUAY = 0x0f, // Spanish (Paraguay) + SUBLANG_SPANISH_BOLIVIA = 0x10, // Spanish (Bolivia) + SUBLANG_SPANISH_EL_SALVADOR = 0x11, // Spanish (El Salvador) + SUBLANG_SPANISH_HONDURAS = 0x12, // Spanish (Honduras) + SUBLANG_SPANISH_NICARAGUA = 0x13, // Spanish (Nicaragua) + SUBLANG_SPANISH_PUERTO_RICO = 0x14, // Spanish (Puerto Rico) + SUBLANG_SWEDISH = 0x01, // Swedish + SUBLANG_SWEDISH_FINLAND = 0x02, // Swedish (Finland) } // // Sorting IDs. @@ -948,20 +948,20 @@ enum enum { - SORT_DEFAULT = 0x0, // sorting default + SORT_DEFAULT = 0x0, // sorting default - SORT_JAPANESE_XJIS = 0x0, // Japanese XJIS order - SORT_JAPANESE_UNICODE = 0x1, // Japanese Unicode order + SORT_JAPANESE_XJIS = 0x0, // Japanese XJIS order + SORT_JAPANESE_UNICODE = 0x1, // Japanese Unicode order - SORT_CHINESE_BIG5 = 0x0, // Chinese BIG5 order - SORT_CHINESE_PRCP = 0x0, // PRC Chinese Phonetic order - SORT_CHINESE_UNICODE = 0x1, // Chinese Unicode order - SORT_CHINESE_PRC = 0x2, // PRC Chinese Stroke Count order + SORT_CHINESE_BIG5 = 0x0, // Chinese BIG5 order + SORT_CHINESE_PRCP = 0x0, // PRC Chinese Phonetic order + SORT_CHINESE_UNICODE = 0x1, // Chinese Unicode order + SORT_CHINESE_PRC = 0x2, // PRC Chinese Stroke Count order - SORT_KOREAN_KSC = 0x0, // Korean KSC order - SORT_KOREAN_UNICODE = 0x1, // Korean Unicode order + SORT_KOREAN_KSC = 0x0, // Korean KSC order + SORT_KOREAN_UNICODE = 0x1, // Korean Unicode order - SORT_GERMAN_PHONE_BOOK = 0x1, // German Phone Book order + SORT_GERMAN_PHONE_BOOK = 0x1, // German Phone Book order } // end_r_winnt @@ -1004,20 +1004,20 @@ struct FLOATING_SAVE_AREA { enum { - SIZE_OF_80387_REGISTERS = 80, + SIZE_OF_80387_REGISTERS = 80, // // The following flags control the contents of the CONTEXT structure. // - CONTEXT_i386 = 0x00010000, // this assumes that i386 and - CONTEXT_i486 = 0x00010000, // i486 have identical context records + CONTEXT_i386 = 0x00010000, // this assumes that i386 and + CONTEXT_i486 = 0x00010000, // i486 have identical context records - CONTEXT_CONTROL = (CONTEXT_i386 | 0x00000001), // SS:SP, CS:IP, FLAGS, BP - CONTEXT_INTEGER = (CONTEXT_i386 | 0x00000002), // AX, BX, CX, DX, SI, DI - CONTEXT_SEGMENTS = (CONTEXT_i386 | 0x00000004), // DS, ES, FS, GS - CONTEXT_FLOATING_POINT = (CONTEXT_i386 | 0x00000008), // 387 state - CONTEXT_DEBUG_REGISTERS = (CONTEXT_i386 | 0x00000010), // DB 0-3,6,7 + CONTEXT_CONTROL = (CONTEXT_i386 | 0x00000001), // SS:SP, CS:IP, FLAGS, BP + CONTEXT_INTEGER = (CONTEXT_i386 | 0x00000002), // AX, BX, CX, DX, SI, DI + CONTEXT_SEGMENTS = (CONTEXT_i386 | 0x00000004), // DS, ES, FS, GS + CONTEXT_FLOATING_POINT = (CONTEXT_i386 | 0x00000008), // 387 state + CONTEXT_DEBUG_REGISTERS = (CONTEXT_i386 | 0x00000010), // DB 0-3,6,7 - CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS), + CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS), } struct CONTEXT @@ -1100,20 +1100,20 @@ struct CONTEXT enum { - THREAD_BASE_PRIORITY_LOWRT = 15, // value that gets a thread to LowRealtime-1 - THREAD_BASE_PRIORITY_MAX = 2, // maximum thread base priority boost - THREAD_BASE_PRIORITY_MIN = -2, // minimum thread base priority boost - THREAD_BASE_PRIORITY_IDLE = -15, // value that gets a thread to idle + THREAD_BASE_PRIORITY_LOWRT = 15, // value that gets a thread to LowRealtime-1 + THREAD_BASE_PRIORITY_MAX = 2, // maximum thread base priority boost + THREAD_BASE_PRIORITY_MIN = -2, // minimum thread base priority boost + THREAD_BASE_PRIORITY_IDLE = -15, // value that gets a thread to idle - THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN, - THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST+1), - THREAD_PRIORITY_NORMAL = 0, - THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX, - THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST-1), - THREAD_PRIORITY_ERROR_RETURN = int.max, + THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN, + THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST+1), + THREAD_PRIORITY_NORMAL = 0, + THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX, + THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST-1), + THREAD_PRIORITY_ERROR_RETURN = int.max, - THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT, - THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE, + THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT, + THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE, } export HANDLE GetCurrentThread(); @@ -1121,7 +1121,7 @@ export BOOL GetProcessTimes(HANDLE hProcess, LPFILETIME lpCreationTime, LPFILETI export HANDLE GetCurrentProcess(); export DWORD GetCurrentProcessId(); export BOOL DuplicateHandle (HANDLE sourceProcess, HANDLE sourceThread, - HANDLE targetProcessHandle, HANDLE *targetHandle, DWORD access, + HANDLE targetProcessHandle, HANDLE *targetHandle, DWORD access, BOOL inheritHandle, DWORD options); export DWORD GetCurrentThreadId(); export BOOL SetThreadPriority(HANDLE hThread, int nPriority); @@ -1142,102 +1142,102 @@ export BOOL QueryPerformanceFrequency(long* lpFrequency); enum { - WM_NOTIFY = 0x004E, - WM_INPUTLANGCHANGEREQUEST = 0x0050, - WM_INPUTLANGCHANGE = 0x0051, - WM_TCARD = 0x0052, - WM_HELP = 0x0053, - WM_USERCHANGED = 0x0054, - WM_NOTIFYFORMAT = 0x0055, + WM_NOTIFY = 0x004E, + WM_INPUTLANGCHANGEREQUEST = 0x0050, + WM_INPUTLANGCHANGE = 0x0051, + WM_TCARD = 0x0052, + WM_HELP = 0x0053, + WM_USERCHANGED = 0x0054, + WM_NOTIFYFORMAT = 0x0055, - NFR_ANSI = 1, - NFR_UNICODE = 2, - NF_QUERY = 3, - NF_REQUERY = 4, + NFR_ANSI = 1, + NFR_UNICODE = 2, + NF_QUERY = 3, + NF_REQUERY = 4, - WM_CONTEXTMENU = 0x007B, - WM_STYLECHANGING = 0x007C, - WM_STYLECHANGED = 0x007D, - WM_DISPLAYCHANGE = 0x007E, - WM_GETICON = 0x007F, - WM_SETICON = 0x0080, + WM_CONTEXTMENU = 0x007B, + WM_STYLECHANGING = 0x007C, + WM_STYLECHANGED = 0x007D, + WM_DISPLAYCHANGE = 0x007E, + WM_GETICON = 0x007F, + WM_SETICON = 0x0080, - WM_NCCREATE = 0x0081, - WM_NCDESTROY = 0x0082, - WM_NCCALCSIZE = 0x0083, - WM_NCHITTEST = 0x0084, - WM_NCPAINT = 0x0085, - WM_NCACTIVATE = 0x0086, - WM_GETDLGCODE = 0x0087, + WM_NCCREATE = 0x0081, + WM_NCDESTROY = 0x0082, + WM_NCCALCSIZE = 0x0083, + WM_NCHITTEST = 0x0084, + WM_NCPAINT = 0x0085, + WM_NCACTIVATE = 0x0086, + WM_GETDLGCODE = 0x0087, - WM_NCMOUSEMOVE = 0x00A0, - WM_NCLBUTTONDOWN = 0x00A1, - WM_NCLBUTTONUP = 0x00A2, - WM_NCLBUTTONDBLCLK = 0x00A3, - WM_NCRBUTTONDOWN = 0x00A4, - WM_NCRBUTTONUP = 0x00A5, - WM_NCRBUTTONDBLCLK = 0x00A6, - WM_NCMBUTTONDOWN = 0x00A7, - WM_NCMBUTTONUP = 0x00A8, - WM_NCMBUTTONDBLCLK = 0x00A9, + WM_NCMOUSEMOVE = 0x00A0, + WM_NCLBUTTONDOWN = 0x00A1, + WM_NCLBUTTONUP = 0x00A2, + WM_NCLBUTTONDBLCLK = 0x00A3, + WM_NCRBUTTONDOWN = 0x00A4, + WM_NCRBUTTONUP = 0x00A5, + WM_NCRBUTTONDBLCLK = 0x00A6, + WM_NCMBUTTONDOWN = 0x00A7, + WM_NCMBUTTONUP = 0x00A8, + WM_NCMBUTTONDBLCLK = 0x00A9, - WM_KEYFIRST = 0x0100, - WM_KEYDOWN = 0x0100, - WM_KEYUP = 0x0101, - WM_CHAR = 0x0102, - WM_DEADCHAR = 0x0103, - WM_SYSKEYDOWN = 0x0104, - WM_SYSKEYUP = 0x0105, - WM_SYSCHAR = 0x0106, - WM_SYSDEADCHAR = 0x0107, - WM_KEYLAST = 0x0108, + WM_KEYFIRST = 0x0100, + WM_KEYDOWN = 0x0100, + WM_KEYUP = 0x0101, + WM_CHAR = 0x0102, + WM_DEADCHAR = 0x0103, + WM_SYSKEYDOWN = 0x0104, + WM_SYSKEYUP = 0x0105, + WM_SYSCHAR = 0x0106, + WM_SYSDEADCHAR = 0x0107, + WM_KEYLAST = 0x0108, - WM_IME_STARTCOMPOSITION = 0x010D, - WM_IME_ENDCOMPOSITION = 0x010E, - WM_IME_COMPOSITION = 0x010F, - WM_IME_KEYLAST = 0x010F, + WM_IME_STARTCOMPOSITION = 0x010D, + WM_IME_ENDCOMPOSITION = 0x010E, + WM_IME_COMPOSITION = 0x010F, + WM_IME_KEYLAST = 0x010F, - WM_INITDIALOG = 0x0110, - WM_COMMAND = 0x0111, - WM_SYSCOMMAND = 0x0112, - WM_TIMER = 0x0113, - WM_HSCROLL = 0x0114, - WM_VSCROLL = 0x0115, - WM_INITMENU = 0x0116, - WM_INITMENUPOPUP = 0x0117, - WM_MENUSELECT = 0x011F, - WM_MENUCHAR = 0x0120, - WM_ENTERIDLE = 0x0121, + WM_INITDIALOG = 0x0110, + WM_COMMAND = 0x0111, + WM_SYSCOMMAND = 0x0112, + WM_TIMER = 0x0113, + WM_HSCROLL = 0x0114, + WM_VSCROLL = 0x0115, + WM_INITMENU = 0x0116, + WM_INITMENUPOPUP = 0x0117, + WM_MENUSELECT = 0x011F, + WM_MENUCHAR = 0x0120, + WM_ENTERIDLE = 0x0121, - WM_CTLCOLORMSGBOX = 0x0132, - WM_CTLCOLOREDIT = 0x0133, - WM_CTLCOLORLISTBOX = 0x0134, - WM_CTLCOLORBTN = 0x0135, - WM_CTLCOLORDLG = 0x0136, - WM_CTLCOLORSCROLLBAR = 0x0137, - WM_CTLCOLORSTATIC = 0x0138, + WM_CTLCOLORMSGBOX = 0x0132, + WM_CTLCOLOREDIT = 0x0133, + WM_CTLCOLORLISTBOX = 0x0134, + WM_CTLCOLORBTN = 0x0135, + WM_CTLCOLORDLG = 0x0136, + WM_CTLCOLORSCROLLBAR = 0x0137, + WM_CTLCOLORSTATIC = 0x0138, - WM_MOUSEFIRST = 0x0200, - WM_MOUSEMOVE = 0x0200, - WM_LBUTTONDOWN = 0x0201, - WM_LBUTTONUP = 0x0202, - WM_LBUTTONDBLCLK = 0x0203, - WM_RBUTTONDOWN = 0x0204, - WM_RBUTTONUP = 0x0205, - WM_RBUTTONDBLCLK = 0x0206, - WM_MBUTTONDOWN = 0x0207, - WM_MBUTTONUP = 0x0208, - WM_MBUTTONDBLCLK = 0x0209, + WM_MOUSEFIRST = 0x0200, + WM_MOUSEMOVE = 0x0200, + WM_LBUTTONDOWN = 0x0201, + WM_LBUTTONUP = 0x0202, + WM_LBUTTONDBLCLK = 0x0203, + WM_RBUTTONDOWN = 0x0204, + WM_RBUTTONUP = 0x0205, + WM_RBUTTONDBLCLK = 0x0206, + WM_MBUTTONDOWN = 0x0207, + WM_MBUTTONUP = 0x0208, + WM_MBUTTONDBLCLK = 0x0209, - WM_MOUSELAST = 0x0209, + WM_MOUSELAST = 0x0209, @@ -1246,14 +1246,14 @@ enum - WM_PARENTNOTIFY = 0x0210, - MENULOOP_WINDOW = 0, - MENULOOP_POPUP = 1, - WM_ENTERMENULOOP = 0x0211, - WM_EXITMENULOOP = 0x0212, + WM_PARENTNOTIFY = 0x0210, + MENULOOP_WINDOW = 0, + MENULOOP_POPUP = 1, + WM_ENTERMENULOOP = 0x0211, + WM_EXITMENULOOP = 0x0212, - WM_NEXTMENU = 0x0213, + WM_NEXTMENU = 0x0213, } enum @@ -1261,16 +1261,16 @@ enum /* * Dialog Box Command IDs */ - IDOK = 1, - IDCANCEL = 2, - IDABORT = 3, - IDRETRY = 4, - IDIGNORE = 5, - IDYES = 6, - IDNO = 7, + IDOK = 1, + IDCANCEL = 2, + IDABORT = 3, + IDRETRY = 4, + IDIGNORE = 5, + IDYES = 6, + IDNO = 7, - IDCLOSE = 8, - IDHELP = 9, + IDCLOSE = 8, + IDHELP = 9, // end_r_winuser @@ -1288,21 +1288,21 @@ enum /* * Edit Control Styles */ - ES_LEFT = 0x0000, - ES_CENTER = 0x0001, - ES_RIGHT = 0x0002, - ES_MULTILINE = 0x0004, - ES_UPPERCASE = 0x0008, - ES_LOWERCASE = 0x0010, - ES_PASSWORD = 0x0020, - ES_AUTOVSCROLL = 0x0040, - ES_AUTOHSCROLL = 0x0080, - ES_NOHIDESEL = 0x0100, - ES_OEMCONVERT = 0x0400, - ES_READONLY = 0x0800, - ES_WANTRETURN = 0x1000, + ES_LEFT = 0x0000, + ES_CENTER = 0x0001, + ES_RIGHT = 0x0002, + ES_MULTILINE = 0x0004, + ES_UPPERCASE = 0x0008, + ES_LOWERCASE = 0x0010, + ES_PASSWORD = 0x0020, + ES_AUTOVSCROLL = 0x0040, + ES_AUTOHSCROLL = 0x0080, + ES_NOHIDESEL = 0x0100, + ES_OEMCONVERT = 0x0400, + ES_READONLY = 0x0800, + ES_WANTRETURN = 0x1000, - ES_NUMBER = 0x2000, + ES_NUMBER = 0x2000, // end_r_winuser @@ -1312,20 +1312,20 @@ enum /* * Edit Control Notification Codes */ - EN_SETFOCUS = 0x0100, - EN_KILLFOCUS = 0x0200, - EN_CHANGE = 0x0300, - EN_UPDATE = 0x0400, - EN_ERRSPACE = 0x0500, - EN_MAXTEXT = 0x0501, - EN_HSCROLL = 0x0601, - EN_VSCROLL = 0x0602, + EN_SETFOCUS = 0x0100, + EN_KILLFOCUS = 0x0200, + EN_CHANGE = 0x0300, + EN_UPDATE = 0x0400, + EN_ERRSPACE = 0x0500, + EN_MAXTEXT = 0x0501, + EN_HSCROLL = 0x0601, + EN_VSCROLL = 0x0602, /* Edit control EM_SETMARGIN parameters */ - EC_LEFTMARGIN = 0x0001, - EC_RIGHTMARGIN = 0x0002, - EC_USEFONTINFO = 0xffff, + EC_LEFTMARGIN = 0x0001, + EC_RIGHTMARGIN = 0x0002, + EC_USEFONTINFO = 0xffff, @@ -1335,44 +1335,44 @@ enum /* * Edit Control Messages */ - EM_GETSEL = 0x00B0, - EM_SETSEL = 0x00B1, - EM_GETRECT = 0x00B2, - EM_SETRECT = 0x00B3, - EM_SETRECTNP = 0x00B4, - EM_SCROLL = 0x00B5, - EM_LINESCROLL = 0x00B6, - EM_SCROLLCARET = 0x00B7, - EM_GETMODIFY = 0x00B8, - EM_SETMODIFY = 0x00B9, - EM_GETLINECOUNT = 0x00BA, - EM_LINEINDEX = 0x00BB, - EM_SETHANDLE = 0x00BC, - EM_GETHANDLE = 0x00BD, - EM_GETTHUMB = 0x00BE, - EM_LINELENGTH = 0x00C1, - EM_REPLACESEL = 0x00C2, - EM_GETLINE = 0x00C4, - EM_LIMITTEXT = 0x00C5, - EM_CANUNDO = 0x00C6, - EM_UNDO = 0x00C7, - EM_FMTLINES = 0x00C8, - EM_LINEFROMCHAR = 0x00C9, - EM_SETTABSTOPS = 0x00CB, - EM_SETPASSWORDCHAR = 0x00CC, - EM_EMPTYUNDOBUFFER = 0x00CD, - EM_GETFIRSTVISIBLELINE = 0x00CE, - EM_SETREADONLY = 0x00CF, - EM_SETWORDBREAKPROC = 0x00D0, - EM_GETWORDBREAKPROC = 0x00D1, - EM_GETPASSWORDCHAR = 0x00D2, + EM_GETSEL = 0x00B0, + EM_SETSEL = 0x00B1, + EM_GETRECT = 0x00B2, + EM_SETRECT = 0x00B3, + EM_SETRECTNP = 0x00B4, + EM_SCROLL = 0x00B5, + EM_LINESCROLL = 0x00B6, + EM_SCROLLCARET = 0x00B7, + EM_GETMODIFY = 0x00B8, + EM_SETMODIFY = 0x00B9, + EM_GETLINECOUNT = 0x00BA, + EM_LINEINDEX = 0x00BB, + EM_SETHANDLE = 0x00BC, + EM_GETHANDLE = 0x00BD, + EM_GETTHUMB = 0x00BE, + EM_LINELENGTH = 0x00C1, + EM_REPLACESEL = 0x00C2, + EM_GETLINE = 0x00C4, + EM_LIMITTEXT = 0x00C5, + EM_CANUNDO = 0x00C6, + EM_UNDO = 0x00C7, + EM_FMTLINES = 0x00C8, + EM_LINEFROMCHAR = 0x00C9, + EM_SETTABSTOPS = 0x00CB, + EM_SETPASSWORDCHAR = 0x00CC, + EM_EMPTYUNDOBUFFER = 0x00CD, + EM_GETFIRSTVISIBLELINE = 0x00CE, + EM_SETREADONLY = 0x00CF, + EM_SETWORDBREAKPROC = 0x00D0, + EM_GETWORDBREAKPROC = 0x00D1, + EM_GETPASSWORDCHAR = 0x00D2, - EM_SETMARGINS = 0x00D3, - EM_GETMARGINS = 0x00D4, - EM_SETLIMITTEXT = EM_LIMITTEXT, /* ;win40 Name change */ - EM_GETLIMITTEXT = 0x00D5, - EM_POSFROMCHAR = 0x00D6, - EM_CHARFROMPOS = 0x00D7, + EM_SETMARGINS = 0x00D3, + EM_GETMARGINS = 0x00D4, + EM_SETLIMITTEXT = EM_LIMITTEXT, /* ;win40 Name change */ + EM_GETLIMITTEXT = 0x00D5, + EM_POSFROMCHAR = 0x00D6, + EM_CHARFROMPOS = 0x00D7, @@ -1382,117 +1382,117 @@ enum /* * EDITWORDBREAKPROC code values */ - WB_LEFT = 0, - WB_RIGHT = 1, - WB_ISDELIMITER = 2, + WB_LEFT = 0, + WB_RIGHT = 1, + WB_ISDELIMITER = 2, // begin_r_winuser /* * Button Control Styles */ - BS_PUSHBUTTON = 0x00000000, - BS_DEFPUSHBUTTON = 0x00000001, - BS_CHECKBOX = 0x00000002, - BS_AUTOCHECKBOX = 0x00000003, - BS_RADIOBUTTON = 0x00000004, - BS_3STATE = 0x00000005, - BS_AUTO3STATE = 0x00000006, - BS_GROUPBOX = 0x00000007, - BS_USERBUTTON = 0x00000008, - BS_AUTORADIOBUTTON = 0x00000009, - BS_OWNERDRAW = 0x0000000B, - BS_LEFTTEXT = 0x00000020, + BS_PUSHBUTTON = 0x00000000, + BS_DEFPUSHBUTTON = 0x00000001, + BS_CHECKBOX = 0x00000002, + BS_AUTOCHECKBOX = 0x00000003, + BS_RADIOBUTTON = 0x00000004, + BS_3STATE = 0x00000005, + BS_AUTO3STATE = 0x00000006, + BS_GROUPBOX = 0x00000007, + BS_USERBUTTON = 0x00000008, + BS_AUTORADIOBUTTON = 0x00000009, + BS_OWNERDRAW = 0x0000000B, + BS_LEFTTEXT = 0x00000020, - BS_TEXT = 0x00000000, - BS_ICON = 0x00000040, - BS_BITMAP = 0x00000080, - BS_LEFT = 0x00000100, - BS_RIGHT = 0x00000200, - BS_CENTER = 0x00000300, - BS_TOP = 0x00000400, - BS_BOTTOM = 0x00000800, - BS_VCENTER = 0x00000C00, - BS_PUSHLIKE = 0x00001000, - BS_MULTILINE = 0x00002000, - BS_NOTIFY = 0x00004000, - BS_FLAT = 0x00008000, - BS_RIGHTBUTTON = BS_LEFTTEXT, + BS_TEXT = 0x00000000, + BS_ICON = 0x00000040, + BS_BITMAP = 0x00000080, + BS_LEFT = 0x00000100, + BS_RIGHT = 0x00000200, + BS_CENTER = 0x00000300, + BS_TOP = 0x00000400, + BS_BOTTOM = 0x00000800, + BS_VCENTER = 0x00000C00, + BS_PUSHLIKE = 0x00001000, + BS_MULTILINE = 0x00002000, + BS_NOTIFY = 0x00004000, + BS_FLAT = 0x00008000, + BS_RIGHTBUTTON = BS_LEFTTEXT, /* * User Button Notification Codes */ - BN_CLICKED = 0, - BN_PAINT = 1, - BN_HILITE = 2, - BN_UNHILITE = 3, - BN_DISABLE = 4, - BN_DOUBLECLICKED = 5, + BN_CLICKED = 0, + BN_PAINT = 1, + BN_HILITE = 2, + BN_UNHILITE = 3, + BN_DISABLE = 4, + BN_DOUBLECLICKED = 5, - BN_PUSHED = BN_HILITE, - BN_UNPUSHED = BN_UNHILITE, - BN_DBLCLK = BN_DOUBLECLICKED, - BN_SETFOCUS = 6, - BN_KILLFOCUS = 7, + BN_PUSHED = BN_HILITE, + BN_UNPUSHED = BN_UNHILITE, + BN_DBLCLK = BN_DOUBLECLICKED, + BN_SETFOCUS = 6, + BN_KILLFOCUS = 7, /* * Button Control Messages */ - BM_GETCHECK = 0x00F0, - BM_SETCHECK = 0x00F1, - BM_GETSTATE = 0x00F2, - BM_SETSTATE = 0x00F3, - BM_SETSTYLE = 0x00F4, + BM_GETCHECK = 0x00F0, + BM_SETCHECK = 0x00F1, + BM_GETSTATE = 0x00F2, + BM_SETSTATE = 0x00F3, + BM_SETSTYLE = 0x00F4, - BM_CLICK = 0x00F5, - BM_GETIMAGE = 0x00F6, - BM_SETIMAGE = 0x00F7, + BM_CLICK = 0x00F5, + BM_GETIMAGE = 0x00F6, + BM_SETIMAGE = 0x00F7, - BST_UNCHECKED = 0x0000, - BST_CHECKED = 0x0001, - BST_INDETERMINATE = 0x0002, - BST_PUSHED = 0x0004, - BST_FOCUS = 0x0008, + BST_UNCHECKED = 0x0000, + BST_CHECKED = 0x0001, + BST_INDETERMINATE = 0x0002, + BST_PUSHED = 0x0004, + BST_FOCUS = 0x0008, /* * Static Control Constants */ - SS_LEFT = 0x00000000, - SS_CENTER = 0x00000001, - SS_RIGHT = 0x00000002, - SS_ICON = 0x00000003, - SS_BLACKRECT = 0x00000004, - SS_GRAYRECT = 0x00000005, - SS_WHITERECT = 0x00000006, - SS_BLACKFRAME = 0x00000007, - SS_GRAYFRAME = 0x00000008, - SS_WHITEFRAME = 0x00000009, - SS_USERITEM = 0x0000000A, - SS_SIMPLE = 0x0000000B, - SS_LEFTNOWORDWRAP = 0x0000000C, + SS_LEFT = 0x00000000, + SS_CENTER = 0x00000001, + SS_RIGHT = 0x00000002, + SS_ICON = 0x00000003, + SS_BLACKRECT = 0x00000004, + SS_GRAYRECT = 0x00000005, + SS_WHITERECT = 0x00000006, + SS_BLACKFRAME = 0x00000007, + SS_GRAYFRAME = 0x00000008, + SS_WHITEFRAME = 0x00000009, + SS_USERITEM = 0x0000000A, + SS_SIMPLE = 0x0000000B, + SS_LEFTNOWORDWRAP = 0x0000000C, - SS_OWNERDRAW = 0x0000000D, - SS_BITMAP = 0x0000000E, - SS_ENHMETAFILE = 0x0000000F, - SS_ETCHEDHORZ = 0x00000010, - SS_ETCHEDVERT = 0x00000011, - SS_ETCHEDFRAME = 0x00000012, - SS_TYPEMASK = 0x0000001F, + SS_OWNERDRAW = 0x0000000D, + SS_BITMAP = 0x0000000E, + SS_ENHMETAFILE = 0x0000000F, + SS_ETCHEDHORZ = 0x00000010, + SS_ETCHEDVERT = 0x00000011, + SS_ETCHEDFRAME = 0x00000012, + SS_TYPEMASK = 0x0000001F, - SS_NOPREFIX = 0x00000080, /* Don't do "&" character translation */ + SS_NOPREFIX = 0x00000080, /* Don't do "&" character translation */ - SS_NOTIFY = 0x00000100, - SS_CENTERIMAGE = 0x00000200, - SS_RIGHTJUST = 0x00000400, - SS_REALSIZEIMAGE = 0x00000800, - SS_SUNKEN = 0x00001000, - SS_ENDELLIPSIS = 0x00004000, - SS_PATHELLIPSIS = 0x00008000, - SS_WORDELLIPSIS = 0x0000C000, - SS_ELLIPSISMASK = 0x0000C000, + SS_NOTIFY = 0x00000100, + SS_CENTERIMAGE = 0x00000200, + SS_RIGHTJUST = 0x00000400, + SS_REALSIZEIMAGE = 0x00000800, + SS_SUNKEN = 0x00001000, + SS_ENDELLIPSIS = 0x00004000, + SS_PATHELLIPSIS = 0x00008000, + SS_WORDELLIPSIS = 0x0000C000, + SS_ELLIPSISMASK = 0x0000C000, // end_r_winuser @@ -1501,17 +1501,17 @@ enum /* * Static Control Mesages */ - STM_SETICON = 0x0170, - STM_GETICON = 0x0171, + STM_SETICON = 0x0170, + STM_GETICON = 0x0171, - STM_SETIMAGE = 0x0172, - STM_GETIMAGE = 0x0173, - STN_CLICKED = 0, - STN_DBLCLK = 1, - STN_ENABLE = 2, - STN_DISABLE = 3, + STM_SETIMAGE = 0x0172, + STM_GETIMAGE = 0x0173, + STN_CLICKED = 0, + STN_DBLCLK = 1, + STN_ENABLE = 2, + STN_DISABLE = 3, - STM_MSGMAX = 0x0174, + STM_MSGMAX = 0x0174, } @@ -1521,53 +1521,53 @@ enum * Window Messages */ - WM_NULL = 0x0000, - WM_CREATE = 0x0001, - WM_DESTROY = 0x0002, - WM_MOVE = 0x0003, - WM_SIZE = 0x0005, + WM_NULL = 0x0000, + WM_CREATE = 0x0001, + WM_DESTROY = 0x0002, + WM_MOVE = 0x0003, + WM_SIZE = 0x0005, - WM_ACTIVATE = 0x0006, + WM_ACTIVATE = 0x0006, /* * WM_ACTIVATE state values */ - WA_INACTIVE = 0, - WA_ACTIVE = 1, - WA_CLICKACTIVE = 2, + WA_INACTIVE = 0, + WA_ACTIVE = 1, + WA_CLICKACTIVE = 2, - WM_SETFOCUS = 0x0007, - WM_KILLFOCUS = 0x0008, - WM_ENABLE = 0x000A, - WM_SETREDRAW = 0x000B, - WM_SETTEXT = 0x000C, - WM_GETTEXT = 0x000D, - WM_GETTEXTLENGTH = 0x000E, - WM_PAINT = 0x000F, - WM_CLOSE = 0x0010, - WM_QUERYENDSESSION = 0x0011, - WM_QUIT = 0x0012, - WM_QUERYOPEN = 0x0013, - WM_ERASEBKGND = 0x0014, - WM_SYSCOLORCHANGE = 0x0015, - WM_ENDSESSION = 0x0016, - WM_SHOWWINDOW = 0x0018, - WM_WININICHANGE = 0x001A, + WM_SETFOCUS = 0x0007, + WM_KILLFOCUS = 0x0008, + WM_ENABLE = 0x000A, + WM_SETREDRAW = 0x000B, + WM_SETTEXT = 0x000C, + WM_GETTEXT = 0x000D, + WM_GETTEXTLENGTH = 0x000E, + WM_PAINT = 0x000F, + WM_CLOSE = 0x0010, + WM_QUERYENDSESSION = 0x0011, + WM_QUIT = 0x0012, + WM_QUERYOPEN = 0x0013, + WM_ERASEBKGND = 0x0014, + WM_SYSCOLORCHANGE = 0x0015, + WM_ENDSESSION = 0x0016, + WM_SHOWWINDOW = 0x0018, + WM_WININICHANGE = 0x001A, - WM_SETTINGCHANGE = WM_WININICHANGE, + WM_SETTINGCHANGE = WM_WININICHANGE, - WM_DEVMODECHANGE = 0x001B, - WM_ACTIVATEAPP = 0x001C, - WM_FONTCHANGE = 0x001D, - WM_TIMECHANGE = 0x001E, - WM_CANCELMODE = 0x001F, - WM_SETCURSOR = 0x0020, - WM_MOUSEACTIVATE = 0x0021, - WM_CHILDACTIVATE = 0x0022, - WM_QUEUESYNC = 0x0023, + WM_DEVMODECHANGE = 0x001B, + WM_ACTIVATEAPP = 0x001C, + WM_FONTCHANGE = 0x001D, + WM_TIMECHANGE = 0x001E, + WM_CANCELMODE = 0x001F, + WM_SETCURSOR = 0x0020, + WM_MOUSEACTIVATE = 0x0021, + WM_CHILDACTIVATE = 0x0022, + WM_QUEUESYNC = 0x0023, - WM_GETMINMAXINFO = 0x0024, + WM_GETMINMAXINFO = 0x0024, } struct RECT @@ -1593,18 +1593,18 @@ alias PAINTSTRUCT* PPAINTSTRUCT, NPPAINTSTRUCT, LPPAINTSTRUCT; enum { - DCX_WINDOW = 0x00000001, - DCX_CACHE = 0x00000002, - DCX_NORESETATTRS = 0x00000004, - DCX_CLIPCHILDREN = 0x00000008, - DCX_CLIPSIBLINGS = 0x00000010, - DCX_PARENTCLIP = 0x00000020, - DCX_EXCLUDERGN = 0x00000040, - DCX_INTERSECTRGN = 0x00000080, - DCX_EXCLUDEUPDATE = 0x00000100, - DCX_INTERSECTUPDATE = 0x00000200, - DCX_LOCKWINDOWUPDATE = 0x00000400, - DCX_VALIDATE = 0x00200000, + DCX_WINDOW = 0x00000001, + DCX_CACHE = 0x00000002, + DCX_NORESETATTRS = 0x00000004, + DCX_CLIPCHILDREN = 0x00000008, + DCX_CLIPSIBLINGS = 0x00000010, + DCX_PARENTCLIP = 0x00000020, + DCX_EXCLUDERGN = 0x00000040, + DCX_INTERSECTRGN = 0x00000080, + DCX_EXCLUDEUPDATE = 0x00000100, + DCX_INTERSECTUPDATE = 0x00000200, + DCX_LOCKWINDOWUPDATE = 0x00000400, + DCX_VALIDATE = 0x00200000, } export @@ -1636,18 +1636,18 @@ export // flags for RedrawWindow() enum { - RDW_INVALIDATE = 0x0001, - RDW_INTERNALPAINT = 0x0002, - RDW_ERASE = 0x0004, - RDW_VALIDATE = 0x0008, - RDW_NOINTERNALPAINT = 0x0010, - RDW_NOERASE = 0x0020, - RDW_NOCHILDREN = 0x0040, - RDW_ALLCHILDREN = 0x0080, - RDW_UPDATENOW = 0x0100, - RDW_ERASENOW = 0x0200, - RDW_FRAME = 0x0400, - RDW_NOFRAME = 0x0800, + RDW_INVALIDATE = 0x0001, + RDW_INTERNALPAINT = 0x0002, + RDW_ERASE = 0x0004, + RDW_VALIDATE = 0x0008, + RDW_NOINTERNALPAINT = 0x0010, + RDW_NOERASE = 0x0020, + RDW_NOCHILDREN = 0x0040, + RDW_ALLCHILDREN = 0x0080, + RDW_UPDATENOW = 0x0100, + RDW_ERASENOW = 0x0200, + RDW_FRAME = 0x0400, + RDW_NOFRAME = 0x0800, } export @@ -1666,122 +1666,122 @@ export enum { - OUT_DEFAULT_PRECIS = 0, - OUT_STRING_PRECIS = 1, - OUT_CHARACTER_PRECIS = 2, - OUT_STROKE_PRECIS = 3, - OUT_TT_PRECIS = 4, - OUT_DEVICE_PRECIS = 5, - OUT_RASTER_PRECIS = 6, - OUT_TT_ONLY_PRECIS = 7, - OUT_OUTLINE_PRECIS = 8, - OUT_SCREEN_OUTLINE_PRECIS = 9, + OUT_DEFAULT_PRECIS = 0, + OUT_STRING_PRECIS = 1, + OUT_CHARACTER_PRECIS = 2, + OUT_STROKE_PRECIS = 3, + OUT_TT_PRECIS = 4, + OUT_DEVICE_PRECIS = 5, + OUT_RASTER_PRECIS = 6, + OUT_TT_ONLY_PRECIS = 7, + OUT_OUTLINE_PRECIS = 8, + OUT_SCREEN_OUTLINE_PRECIS = 9, - CLIP_DEFAULT_PRECIS = 0, - CLIP_CHARACTER_PRECIS = 1, - CLIP_STROKE_PRECIS = 2, - CLIP_MASK = 0xf, - CLIP_LH_ANGLES = (1<<4), - CLIP_TT_ALWAYS = (2<<4), - CLIP_EMBEDDED = (8<<4), + CLIP_DEFAULT_PRECIS = 0, + CLIP_CHARACTER_PRECIS = 1, + CLIP_STROKE_PRECIS = 2, + CLIP_MASK = 0xf, + CLIP_LH_ANGLES = (1<<4), + CLIP_TT_ALWAYS = (2<<4), + CLIP_EMBEDDED = (8<<4), - DEFAULT_QUALITY = 0, - DRAFT_QUALITY = 1, - PROOF_QUALITY = 2, + DEFAULT_QUALITY = 0, + DRAFT_QUALITY = 1, + PROOF_QUALITY = 2, - NONANTIALIASED_QUALITY = 3, - ANTIALIASED_QUALITY = 4, + NONANTIALIASED_QUALITY = 3, + ANTIALIASED_QUALITY = 4, - DEFAULT_PITCH = 0, - FIXED_PITCH = 1, - VARIABLE_PITCH = 2, + DEFAULT_PITCH = 0, + FIXED_PITCH = 1, + VARIABLE_PITCH = 2, - MONO_FONT = 8, + MONO_FONT = 8, - ANSI_CHARSET = 0, - DEFAULT_CHARSET = 1, - SYMBOL_CHARSET = 2, - SHIFTJIS_CHARSET = 128, - HANGEUL_CHARSET = 129, - GB2312_CHARSET = 134, - CHINESEBIG5_CHARSET = 136, - OEM_CHARSET = 255, + ANSI_CHARSET = 0, + DEFAULT_CHARSET = 1, + SYMBOL_CHARSET = 2, + SHIFTJIS_CHARSET = 128, + HANGEUL_CHARSET = 129, + GB2312_CHARSET = 134, + CHINESEBIG5_CHARSET = 136, + OEM_CHARSET = 255, - JOHAB_CHARSET = 130, - HEBREW_CHARSET = 177, - ARABIC_CHARSET = 178, - GREEK_CHARSET = 161, - TURKISH_CHARSET = 162, - VIETNAMESE_CHARSET = 163, - THAI_CHARSET = 222, - EASTEUROPE_CHARSET = 238, - RUSSIAN_CHARSET = 204, + JOHAB_CHARSET = 130, + HEBREW_CHARSET = 177, + ARABIC_CHARSET = 178, + GREEK_CHARSET = 161, + TURKISH_CHARSET = 162, + VIETNAMESE_CHARSET = 163, + THAI_CHARSET = 222, + EASTEUROPE_CHARSET = 238, + RUSSIAN_CHARSET = 204, - MAC_CHARSET = 77, - BALTIC_CHARSET = 186, + MAC_CHARSET = 77, + BALTIC_CHARSET = 186, - FS_LATIN1 = 0x00000001L, - FS_LATIN2 = 0x00000002L, - FS_CYRILLIC = 0x00000004L, - FS_GREEK = 0x00000008L, - FS_TURKISH = 0x00000010L, - FS_HEBREW = 0x00000020L, - FS_ARABIC = 0x00000040L, - FS_BALTIC = 0x00000080L, - FS_VIETNAMESE = 0x00000100L, - FS_THAI = 0x00010000L, - FS_JISJAPAN = 0x00020000L, - FS_CHINESESIMP = 0x00040000L, - FS_WANSUNG = 0x00080000L, - FS_CHINESETRAD = 0x00100000L, - FS_JOHAB = 0x00200000L, - FS_SYMBOL = cast(int)0x80000000L, + FS_LATIN1 = 0x00000001L, + FS_LATIN2 = 0x00000002L, + FS_CYRILLIC = 0x00000004L, + FS_GREEK = 0x00000008L, + FS_TURKISH = 0x00000010L, + FS_HEBREW = 0x00000020L, + FS_ARABIC = 0x00000040L, + FS_BALTIC = 0x00000080L, + FS_VIETNAMESE = 0x00000100L, + FS_THAI = 0x00010000L, + FS_JISJAPAN = 0x00020000L, + FS_CHINESESIMP = 0x00040000L, + FS_WANSUNG = 0x00080000L, + FS_CHINESETRAD = 0x00100000L, + FS_JOHAB = 0x00200000L, + FS_SYMBOL = cast(int)0x80000000L, /* Font Families */ - FF_DONTCARE = (0<<4), /* Don't care or don't know. */ - FF_ROMAN = (1<<4), /* Variable stroke width, serifed. */ + FF_DONTCARE = (0<<4), /* Don't care or don't know. */ + FF_ROMAN = (1<<4), /* Variable stroke width, serifed. */ /* Times Roman, Century Schoolbook, etc. */ - FF_SWISS = (2<<4), /* Variable stroke width, sans-serifed. */ + FF_SWISS = (2<<4), /* Variable stroke width, sans-serifed. */ /* Helvetica, Swiss, etc. */ - FF_MODERN = (3<<4), /* Constant stroke width, serifed or sans-serifed. */ + FF_MODERN = (3<<4), /* Constant stroke width, serifed or sans-serifed. */ /* Pica, Elite, Courier, etc. */ - FF_SCRIPT = (4<<4), /* Cursive, etc. */ - FF_DECORATIVE = (5<<4), /* Old English, etc. */ + FF_SCRIPT = (4<<4), /* Cursive, etc. */ + FF_DECORATIVE = (5<<4), /* Old English, etc. */ /* Font Weights */ - FW_DONTCARE = 0, - FW_THIN = 100, - FW_EXTRALIGHT = 200, - FW_LIGHT = 300, - FW_NORMAL = 400, - FW_MEDIUM = 500, - FW_SEMIBOLD = 600, - FW_BOLD = 700, - FW_EXTRABOLD = 800, - FW_HEAVY = 900, + FW_DONTCARE = 0, + FW_THIN = 100, + FW_EXTRALIGHT = 200, + FW_LIGHT = 300, + FW_NORMAL = 400, + FW_MEDIUM = 500, + FW_SEMIBOLD = 600, + FW_BOLD = 700, + FW_EXTRABOLD = 800, + FW_HEAVY = 900, - FW_ULTRALIGHT = FW_EXTRALIGHT, - FW_REGULAR = FW_NORMAL, - FW_DEMIBOLD = FW_SEMIBOLD, - FW_ULTRABOLD = FW_EXTRABOLD, - FW_BLACK = FW_HEAVY, + FW_ULTRALIGHT = FW_EXTRALIGHT, + FW_REGULAR = FW_NORMAL, + FW_DEMIBOLD = FW_SEMIBOLD, + FW_ULTRABOLD = FW_EXTRABOLD, + FW_BLACK = FW_HEAVY, - PANOSE_COUNT = 10, - PAN_FAMILYTYPE_INDEX = 0, - PAN_SERIFSTYLE_INDEX = 1, - PAN_WEIGHT_INDEX = 2, - PAN_PROPORTION_INDEX = 3, - PAN_CONTRAST_INDEX = 4, - PAN_STROKEVARIATION_INDEX = 5, - PAN_ARMSTYLE_INDEX = 6, - PAN_LETTERFORM_INDEX = 7, - PAN_MIDLINE_INDEX = 8, - PAN_XHEIGHT_INDEX = 9, + PANOSE_COUNT = 10, + PAN_FAMILYTYPE_INDEX = 0, + PAN_SERIFSTYLE_INDEX = 1, + PAN_WEIGHT_INDEX = 2, + PAN_PROPORTION_INDEX = 3, + PAN_CONTRAST_INDEX = 4, + PAN_STROKEVARIATION_INDEX = 5, + PAN_ARMSTYLE_INDEX = 6, + PAN_LETTERFORM_INDEX = 7, + PAN_MIDLINE_INDEX = 8, + PAN_XHEIGHT_INDEX = 9, - PAN_CULTURE_LATIN = 0, + PAN_CULTURE_LATIN = 0, } struct RGBQUAD { @@ -1905,19 +1905,19 @@ export /* Text Alignment Options */ enum { - TA_NOUPDATECP = 0, - TA_UPDATECP = 1, + TA_NOUPDATECP = 0, + TA_UPDATECP = 1, - TA_LEFT = 0, - TA_RIGHT = 2, - TA_CENTER = 6, + TA_LEFT = 0, + TA_RIGHT = 2, + TA_CENTER = 6, - TA_TOP = 0, - TA_BOTTOM = 8, - TA_BASELINE = 24, + TA_TOP = 0, + TA_BOTTOM = 8, + TA_BASELINE = 24, - TA_RTLREADING = 256, - TA_MASK = (TA_BASELINE+TA_CENTER+TA_UPDATECP+TA_RTLREADING), + TA_RTLREADING = 256, + TA_MASK = (TA_BASELINE+TA_CENTER+TA_UPDATECP+TA_RTLREADING), } struct POINT @@ -1980,39 +1980,39 @@ alias WNDCLASSA WNDCLASS; */ enum : uint { - WS_OVERLAPPED = 0x00000000, - WS_POPUP = 0x80000000, - WS_CHILD = 0x40000000, - WS_MINIMIZE = 0x20000000, - WS_VISIBLE = 0x10000000, - WS_DISABLED = 0x08000000, - WS_CLIPSIBLINGS = 0x04000000, - WS_CLIPCHILDREN = 0x02000000, - WS_MAXIMIZE = 0x01000000, - WS_CAPTION = 0x00C00000, /* WS_BORDER | WS_DLGFRAME */ - WS_BORDER = 0x00800000, - WS_DLGFRAME = 0x00400000, - WS_VSCROLL = 0x00200000, - WS_HSCROLL = 0x00100000, - WS_SYSMENU = 0x00080000, - WS_THICKFRAME = 0x00040000, - WS_GROUP = 0x00020000, - WS_TABSTOP = 0x00010000, + WS_OVERLAPPED = 0x00000000, + WS_POPUP = 0x80000000, + WS_CHILD = 0x40000000, + WS_MINIMIZE = 0x20000000, + WS_VISIBLE = 0x10000000, + WS_DISABLED = 0x08000000, + WS_CLIPSIBLINGS = 0x04000000, + WS_CLIPCHILDREN = 0x02000000, + WS_MAXIMIZE = 0x01000000, + WS_CAPTION = 0x00C00000, /* WS_BORDER | WS_DLGFRAME */ + WS_BORDER = 0x00800000, + WS_DLGFRAME = 0x00400000, + WS_VSCROLL = 0x00200000, + WS_HSCROLL = 0x00100000, + WS_SYSMENU = 0x00080000, + WS_THICKFRAME = 0x00040000, + WS_GROUP = 0x00020000, + WS_TABSTOP = 0x00010000, - WS_MINIMIZEBOX = 0x00020000, - WS_MAXIMIZEBOX = 0x00010000, + WS_MINIMIZEBOX = 0x00020000, + WS_MAXIMIZEBOX = 0x00010000, - WS_TILED = WS_OVERLAPPED, - WS_ICONIC = WS_MINIMIZE, - WS_SIZEBOX = WS_THICKFRAME, + WS_TILED = WS_OVERLAPPED, + WS_ICONIC = WS_MINIMIZE, + WS_SIZEBOX = WS_THICKFRAME, /* * Common Window Styles */ - WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), - WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, - WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), - WS_CHILDWINDOW = (WS_CHILD), + WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), + WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, + WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), + WS_CHILDWINDOW = (WS_CHILD), } /* @@ -2020,22 +2020,22 @@ enum : uint */ enum { - CS_VREDRAW = 0x0001, - CS_HREDRAW = 0x0002, - CS_KEYCVTWINDOW = 0x0004, - CS_DBLCLKS = 0x0008, - CS_OWNDC = 0x0020, - CS_CLASSDC = 0x0040, - CS_PARENTDC = 0x0080, - CS_NOKEYCVT = 0x0100, - CS_NOCLOSE = 0x0200, - CS_SAVEBITS = 0x0800, - CS_BYTEALIGNCLIENT = 0x1000, - CS_BYTEALIGNWINDOW = 0x2000, - CS_GLOBALCLASS = 0x4000, + CS_VREDRAW = 0x0001, + CS_HREDRAW = 0x0002, + CS_KEYCVTWINDOW = 0x0004, + CS_DBLCLKS = 0x0008, + CS_OWNDC = 0x0020, + CS_CLASSDC = 0x0040, + CS_PARENTDC = 0x0080, + CS_NOKEYCVT = 0x0100, + CS_NOCLOSE = 0x0200, + CS_SAVEBITS = 0x0800, + CS_BYTEALIGNCLIENT = 0x1000, + CS_BYTEALIGNWINDOW = 0x2000, + CS_GLOBALCLASS = 0x4000, - CS_IME = 0x00010000, + CS_IME = 0x00010000, } export @@ -2056,54 +2056,54 @@ const LPSTR IDC_CROSS = cast(LPSTR)(32515); */ enum { - CTLCOLOR_MSGBOX = 0, - CTLCOLOR_EDIT = 1, - CTLCOLOR_LISTBOX = 2, - CTLCOLOR_BTN = 3, - CTLCOLOR_DLG = 4, - CTLCOLOR_SCROLLBAR = 5, - CTLCOLOR_STATIC = 6, - CTLCOLOR_MAX = 7, + CTLCOLOR_MSGBOX = 0, + CTLCOLOR_EDIT = 1, + CTLCOLOR_LISTBOX = 2, + CTLCOLOR_BTN = 3, + CTLCOLOR_DLG = 4, + CTLCOLOR_SCROLLBAR = 5, + CTLCOLOR_STATIC = 6, + CTLCOLOR_MAX = 7, - COLOR_SCROLLBAR = 0, - COLOR_BACKGROUND = 1, - COLOR_ACTIVECAPTION = 2, - COLOR_INACTIVECAPTION = 3, - COLOR_MENU = 4, - COLOR_WINDOW = 5, - COLOR_WINDOWFRAME = 6, - COLOR_MENUTEXT = 7, - COLOR_WINDOWTEXT = 8, - COLOR_CAPTIONTEXT = 9, - COLOR_ACTIVEBORDER = 10, - COLOR_INACTIVEBORDER = 11, - COLOR_APPWORKSPACE = 12, - COLOR_HIGHLIGHT = 13, - COLOR_HIGHLIGHTTEXT = 14, - COLOR_BTNFACE = 15, - COLOR_BTNSHADOW = 16, - COLOR_GRAYTEXT = 17, - COLOR_BTNTEXT = 18, - COLOR_INACTIVECAPTIONTEXT = 19, - COLOR_BTNHIGHLIGHT = 20, + COLOR_SCROLLBAR = 0, + COLOR_BACKGROUND = 1, + COLOR_ACTIVECAPTION = 2, + COLOR_INACTIVECAPTION = 3, + COLOR_MENU = 4, + COLOR_WINDOW = 5, + COLOR_WINDOWFRAME = 6, + COLOR_MENUTEXT = 7, + COLOR_WINDOWTEXT = 8, + COLOR_CAPTIONTEXT = 9, + COLOR_ACTIVEBORDER = 10, + COLOR_INACTIVEBORDER = 11, + COLOR_APPWORKSPACE = 12, + COLOR_HIGHLIGHT = 13, + COLOR_HIGHLIGHTTEXT = 14, + COLOR_BTNFACE = 15, + COLOR_BTNSHADOW = 16, + COLOR_GRAYTEXT = 17, + COLOR_BTNTEXT = 18, + COLOR_INACTIVECAPTIONTEXT = 19, + COLOR_BTNHIGHLIGHT = 20, - COLOR_3DDKSHADOW = 21, - COLOR_3DLIGHT = 22, - COLOR_INFOTEXT = 23, - COLOR_INFOBK = 24, + COLOR_3DDKSHADOW = 21, + COLOR_3DLIGHT = 22, + COLOR_INFOTEXT = 23, + COLOR_INFOBK = 24, - COLOR_DESKTOP = COLOR_BACKGROUND, - COLOR_3DFACE = COLOR_BTNFACE, - COLOR_3DSHADOW = COLOR_BTNSHADOW, - COLOR_3DHIGHLIGHT = COLOR_BTNHIGHLIGHT, - COLOR_3DHILIGHT = COLOR_BTNHIGHLIGHT, - COLOR_BTNHILIGHT = COLOR_BTNHIGHLIGHT, + COLOR_DESKTOP = COLOR_BACKGROUND, + COLOR_3DFACE = COLOR_BTNFACE, + COLOR_3DSHADOW = COLOR_BTNSHADOW, + COLOR_3DHIGHLIGHT = COLOR_BTNHIGHLIGHT, + COLOR_3DHILIGHT = COLOR_BTNHIGHLIGHT, + COLOR_BTNHILIGHT = COLOR_BTNHIGHLIGHT, } enum : int { - CW_USEDEFAULT = cast(int)0x80000000 + CW_USEDEFAULT = cast(int)0x80000000 } /* @@ -2196,45 +2196,45 @@ export BOOL ShowWindow(HWND hWnd, int nCmdShow); /* Stock Logical Objects */ enum -{ WHITE_BRUSH = 0, - LTGRAY_BRUSH = 1, - GRAY_BRUSH = 2, - DKGRAY_BRUSH = 3, - BLACK_BRUSH = 4, - NULL_BRUSH = 5, - HOLLOW_BRUSH = NULL_BRUSH, - WHITE_PEN = 6, - BLACK_PEN = 7, - NULL_PEN = 8, - OEM_FIXED_FONT = 10, - ANSI_FIXED_FONT = 11, - ANSI_VAR_FONT = 12, - SYSTEM_FONT = 13, - DEVICE_DEFAULT_FONT = 14, - DEFAULT_PALETTE = 15, - SYSTEM_FIXED_FONT = 16, - DEFAULT_GUI_FONT = 17, - STOCK_LAST = 17, +{ WHITE_BRUSH = 0, + LTGRAY_BRUSH = 1, + GRAY_BRUSH = 2, + DKGRAY_BRUSH = 3, + BLACK_BRUSH = 4, + NULL_BRUSH = 5, + HOLLOW_BRUSH = NULL_BRUSH, + WHITE_PEN = 6, + BLACK_PEN = 7, + NULL_PEN = 8, + OEM_FIXED_FONT = 10, + ANSI_FIXED_FONT = 11, + ANSI_VAR_FONT = 12, + SYSTEM_FONT = 13, + DEVICE_DEFAULT_FONT = 14, + DEFAULT_PALETTE = 15, + SYSTEM_FIXED_FONT = 16, + DEFAULT_GUI_FONT = 17, + STOCK_LAST = 17, } /* * ShowWindow() Commands */ enum -{ SW_HIDE = 0, - SW_SHOWNORMAL = 1, - SW_NORMAL = 1, - SW_SHOWMINIMIZED = 2, - SW_SHOWMAXIMIZED = 3, - SW_MAXIMIZE = 3, - SW_SHOWNOACTIVATE = 4, - SW_SHOW = 5, - SW_MINIMIZE = 6, - SW_SHOWMINNOACTIVE = 7, - SW_SHOWNA = 8, - SW_RESTORE = 9, - SW_SHOWDEFAULT = 10, - SW_MAX = 10, +{ SW_HIDE = 0, + SW_SHOWNORMAL = 1, + SW_NORMAL = 1, + SW_SHOWMINIMIZED = 2, + SW_SHOWMAXIMIZED = 3, + SW_MAXIMIZE = 3, + SW_SHOWNOACTIVATE = 4, + SW_SHOW = 5, + SW_MINIMIZE = 6, + SW_SHOWMINNOACTIVE = 7, + SW_SHOWNA = 8, + SW_RESTORE = 9, + SW_SHOWDEFAULT = 10, + SW_MAX = 10, } struct TEXTMETRICA @@ -2267,31 +2267,31 @@ export BOOL GetTextMetricsA(HDC, TEXTMETRICA*); * Scroll Bar Constants */ enum -{ SB_HORZ = 0, - SB_VERT = 1, - SB_CTL = 2, - SB_BOTH = 3, +{ SB_HORZ = 0, + SB_VERT = 1, + SB_CTL = 2, + SB_BOTH = 3, } /* * Scroll Bar Commands */ enum -{ SB_LINEUP = 0, - SB_LINELEFT = 0, - SB_LINEDOWN = 1, - SB_LINERIGHT = 1, - SB_PAGEUP = 2, - SB_PAGELEFT = 2, - SB_PAGEDOWN = 3, - SB_PAGERIGHT = 3, - SB_THUMBPOSITION = 4, - SB_THUMBTRACK = 5, - SB_TOP = 6, - SB_LEFT = 6, - SB_BOTTOM = 7, - SB_RIGHT = 7, - SB_ENDSCROLL = 8, +{ SB_LINEUP = 0, + SB_LINELEFT = 0, + SB_LINEDOWN = 1, + SB_LINERIGHT = 1, + SB_PAGEUP = 2, + SB_PAGELEFT = 2, + SB_PAGEDOWN = 3, + SB_PAGERIGHT = 3, + SB_THUMBPOSITION = 4, + SB_THUMBTRACK = 5, + SB_TOP = 6, + SB_LEFT = 6, + SB_BOTTOM = 7, + SB_RIGHT = 7, + SB_ENDSCROLL = 8, } export int SetScrollPos(HWND hWnd, int nBar, int nPos, BOOL bRedraw); @@ -2314,119 +2314,119 @@ export int ScrollWindowEx(HWND hWnd, int dx, int dy, RECT* prcScroll, RECT* prcC * Virtual Keys, Standard Set */ enum -{ VK_LBUTTON = 0x01, - VK_RBUTTON = 0x02, - VK_CANCEL = 0x03, - VK_MBUTTON = 0x04, /* NOT contiguous with L & RBUTTON */ +{ VK_LBUTTON = 0x01, + VK_RBUTTON = 0x02, + VK_CANCEL = 0x03, + VK_MBUTTON = 0x04, /* NOT contiguous with L & RBUTTON */ - VK_BACK = 0x08, - VK_TAB = 0x09, + VK_BACK = 0x08, + VK_TAB = 0x09, - VK_CLEAR = 0x0C, - VK_RETURN = 0x0D, + VK_CLEAR = 0x0C, + VK_RETURN = 0x0D, - VK_SHIFT = 0x10, - VK_CONTROL = 0x11, - VK_MENU = 0x12, - VK_PAUSE = 0x13, - VK_CAPITAL = 0x14, + VK_SHIFT = 0x10, + VK_CONTROL = 0x11, + VK_MENU = 0x12, + VK_PAUSE = 0x13, + VK_CAPITAL = 0x14, - VK_ESCAPE = 0x1B, + VK_ESCAPE = 0x1B, - VK_SPACE = 0x20, - VK_PRIOR = 0x21, - VK_NEXT = 0x22, - VK_END = 0x23, - VK_HOME = 0x24, - VK_LEFT = 0x25, - VK_UP = 0x26, - VK_RIGHT = 0x27, - VK_DOWN = 0x28, - VK_SELECT = 0x29, - VK_PRINT = 0x2A, - VK_EXECUTE = 0x2B, - VK_SNAPSHOT = 0x2C, - VK_INSERT = 0x2D, - VK_DELETE = 0x2E, - VK_HELP = 0x2F, + VK_SPACE = 0x20, + VK_PRIOR = 0x21, + VK_NEXT = 0x22, + VK_END = 0x23, + VK_HOME = 0x24, + VK_LEFT = 0x25, + VK_UP = 0x26, + VK_RIGHT = 0x27, + VK_DOWN = 0x28, + VK_SELECT = 0x29, + VK_PRINT = 0x2A, + VK_EXECUTE = 0x2B, + VK_SNAPSHOT = 0x2C, + VK_INSERT = 0x2D, + VK_DELETE = 0x2E, + VK_HELP = 0x2F, /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */ /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */ - VK_LWIN = 0x5B, - VK_RWIN = 0x5C, - VK_APPS = 0x5D, + VK_LWIN = 0x5B, + VK_RWIN = 0x5C, + VK_APPS = 0x5D, - VK_NUMPAD0 = 0x60, - VK_NUMPAD1 = 0x61, - VK_NUMPAD2 = 0x62, - VK_NUMPAD3 = 0x63, - VK_NUMPAD4 = 0x64, - VK_NUMPAD5 = 0x65, - VK_NUMPAD6 = 0x66, - VK_NUMPAD7 = 0x67, - VK_NUMPAD8 = 0x68, - VK_NUMPAD9 = 0x69, - VK_MULTIPLY = 0x6A, - VK_ADD = 0x6B, - VK_SEPARATOR = 0x6C, - VK_SUBTRACT = 0x6D, - VK_DECIMAL = 0x6E, - VK_DIVIDE = 0x6F, - VK_F1 = 0x70, - VK_F2 = 0x71, - VK_F3 = 0x72, - VK_F4 = 0x73, - VK_F5 = 0x74, - VK_F6 = 0x75, - VK_F7 = 0x76, - VK_F8 = 0x77, - VK_F9 = 0x78, - VK_F10 = 0x79, - VK_F11 = 0x7A, - VK_F12 = 0x7B, - VK_F13 = 0x7C, - VK_F14 = 0x7D, - VK_F15 = 0x7E, - VK_F16 = 0x7F, - VK_F17 = 0x80, - VK_F18 = 0x81, - VK_F19 = 0x82, - VK_F20 = 0x83, - VK_F21 = 0x84, - VK_F22 = 0x85, - VK_F23 = 0x86, - VK_F24 = 0x87, + VK_NUMPAD0 = 0x60, + VK_NUMPAD1 = 0x61, + VK_NUMPAD2 = 0x62, + VK_NUMPAD3 = 0x63, + VK_NUMPAD4 = 0x64, + VK_NUMPAD5 = 0x65, + VK_NUMPAD6 = 0x66, + VK_NUMPAD7 = 0x67, + VK_NUMPAD8 = 0x68, + VK_NUMPAD9 = 0x69, + VK_MULTIPLY = 0x6A, + VK_ADD = 0x6B, + VK_SEPARATOR = 0x6C, + VK_SUBTRACT = 0x6D, + VK_DECIMAL = 0x6E, + VK_DIVIDE = 0x6F, + VK_F1 = 0x70, + VK_F2 = 0x71, + VK_F3 = 0x72, + VK_F4 = 0x73, + VK_F5 = 0x74, + VK_F6 = 0x75, + VK_F7 = 0x76, + VK_F8 = 0x77, + VK_F9 = 0x78, + VK_F10 = 0x79, + VK_F11 = 0x7A, + VK_F12 = 0x7B, + VK_F13 = 0x7C, + VK_F14 = 0x7D, + VK_F15 = 0x7E, + VK_F16 = 0x7F, + VK_F17 = 0x80, + VK_F18 = 0x81, + VK_F19 = 0x82, + VK_F20 = 0x83, + VK_F21 = 0x84, + VK_F22 = 0x85, + VK_F23 = 0x86, + VK_F24 = 0x87, - VK_NUMLOCK = 0x90, - VK_SCROLL = 0x91, + VK_NUMLOCK = 0x90, + VK_SCROLL = 0x91, /* * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. * Used only as parameters to GetAsyncKeyState() and GetKeyState(). * No other API or message will distinguish left and right keys in this way. */ - VK_LSHIFT = 0xA0, - VK_RSHIFT = 0xA1, - VK_LCONTROL = 0xA2, - VK_RCONTROL = 0xA3, - VK_LMENU = 0xA4, - VK_RMENU = 0xA5, + VK_LSHIFT = 0xA0, + VK_RSHIFT = 0xA1, + VK_LCONTROL = 0xA2, + VK_RCONTROL = 0xA3, + VK_LMENU = 0xA4, + VK_RMENU = 0xA5, - VK_PROCESSKEY = 0xE5, + VK_PROCESSKEY = 0xE5, - VK_ATTN = 0xF6, - VK_CRSEL = 0xF7, - VK_EXSEL = 0xF8, - VK_EREOF = 0xF9, - VK_PLAY = 0xFA, - VK_ZOOM = 0xFB, - VK_NONAME = 0xFC, - VK_PA1 = 0xFD, - VK_OEM_CLEAR = 0xFE, + VK_ATTN = 0xF6, + VK_CRSEL = 0xF7, + VK_EXSEL = 0xF8, + VK_EREOF = 0xF9, + VK_PLAY = 0xFA, + VK_ZOOM = 0xFB, + VK_NONAME = 0xFC, + VK_PA1 = 0xFD, + VK_OEM_CLEAR = 0xFE, } export LRESULT SendMessageA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); @@ -2492,9 +2492,9 @@ short GetFileTitleW(LPCWSTR, LPWSTR, WORD); enum { - PM_NOREMOVE = 0x0000, - PM_REMOVE = 0x0001, - PM_NOYIELD = 0x0002, + PM_NOREMOVE = 0x0000, + PM_REMOVE = 0x0001, + PM_NOYIELD = 0x0002, } /* Bitmap Header Definition */ @@ -2572,7 +2572,7 @@ export HWND ChildWindowFromPoint(HWND hWndParent, POINT Point); export BOOL TrackPopupMenu(HMENU hMenu, UINT uFlags, int x, int y, - int nReserved, HWND hWnd, RECT *prcRect); + int nReserved, HWND hWnd, RECT *prcRect); align (2) struct DLGTEMPLATE { DWORD style; @@ -2597,50 +2597,50 @@ alias LPCDLGTEMPLATEA LPCDLGTEMPLATE; export int DialogBoxParamA(HINSTANCE hInstance, LPCSTR lpTemplateName, - HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam); + HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam); export int DialogBoxIndirectParamA(HINSTANCE hInstance, - LPCDLGTEMPLATEA hDialogTemplate, HWND hWndParent, DLGPROC lpDialogFunc, - LPARAM dwInitParam); + LPCDLGTEMPLATEA hDialogTemplate, HWND hWndParent, DLGPROC lpDialogFunc, + LPARAM dwInitParam); enum : DWORD { - SRCCOPY = cast(DWORD)0x00CC0020, /* dest = source */ - SRCPAINT = cast(DWORD)0x00EE0086, /* dest = source OR dest */ - SRCAND = cast(DWORD)0x008800C6, /* dest = source AND dest */ - SRCINVERT = cast(DWORD)0x00660046, /* dest = source XOR dest */ - SRCERASE = cast(DWORD)0x00440328, /* dest = source AND (NOT dest) */ - NOTSRCCOPY = cast(DWORD)0x00330008, /* dest = (NOT source) */ - NOTSRCERASE = cast(DWORD)0x001100A6, /* dest = (NOT src) AND (NOT dest) */ - MERGECOPY = cast(DWORD)0x00C000CA, /* dest = (source AND pattern) */ - MERGEPAINT = cast(DWORD)0x00BB0226, /* dest = (NOT source) OR dest */ - PATCOPY = cast(DWORD)0x00F00021, /* dest = pattern */ - PATPAINT = cast(DWORD)0x00FB0A09, /* dest = DPSnoo */ - PATINVERT = cast(DWORD)0x005A0049, /* dest = pattern XOR dest */ - DSTINVERT = cast(DWORD)0x00550009, /* dest = (NOT dest) */ - BLACKNESS = cast(DWORD)0x00000042, /* dest = BLACK */ - WHITENESS = cast(DWORD)0x00FF0062, /* dest = WHITE */ + SRCCOPY = cast(DWORD)0x00CC0020, /* dest = source */ + SRCPAINT = cast(DWORD)0x00EE0086, /* dest = source OR dest */ + SRCAND = cast(DWORD)0x008800C6, /* dest = source AND dest */ + SRCINVERT = cast(DWORD)0x00660046, /* dest = source XOR dest */ + SRCERASE = cast(DWORD)0x00440328, /* dest = source AND (NOT dest) */ + NOTSRCCOPY = cast(DWORD)0x00330008, /* dest = (NOT source) */ + NOTSRCERASE = cast(DWORD)0x001100A6, /* dest = (NOT src) AND (NOT dest) */ + MERGECOPY = cast(DWORD)0x00C000CA, /* dest = (source AND pattern) */ + MERGEPAINT = cast(DWORD)0x00BB0226, /* dest = (NOT source) OR dest */ + PATCOPY = cast(DWORD)0x00F00021, /* dest = pattern */ + PATPAINT = cast(DWORD)0x00FB0A09, /* dest = DPSnoo */ + PATINVERT = cast(DWORD)0x005A0049, /* dest = pattern XOR dest */ + DSTINVERT = cast(DWORD)0x00550009, /* dest = (NOT dest) */ + BLACKNESS = cast(DWORD)0x00000042, /* dest = BLACK */ + WHITENESS = cast(DWORD)0x00FF0062, /* dest = WHITE */ } enum { - SND_SYNC = 0x0000, /* play synchronously (default) */ - SND_ASYNC = 0x0001, /* play asynchronously */ - SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */ - SND_MEMORY = 0x0004, /* pszSound points to a memory file */ - SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */ - SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */ + SND_SYNC = 0x0000, /* play synchronously (default) */ + SND_ASYNC = 0x0001, /* play asynchronously */ + SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */ + SND_MEMORY = 0x0004, /* pszSound points to a memory file */ + SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */ + SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */ - SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */ - SND_ALIAS = 0x00010000, /* name is a registry alias */ - SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */ - SND_FILENAME = 0x00020000, /* name is file name */ - SND_RESOURCE = 0x00040004, /* name is resource name or atom */ + SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */ + SND_ALIAS = 0x00010000, /* name is a registry alias */ + SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */ + SND_FILENAME = 0x00020000, /* name is file name */ + SND_RESOURCE = 0x00040004, /* name is resource name or atom */ - SND_PURGE = 0x0040, /* purge non-static events for task */ - SND_APPLICATION = 0x0080, /* look for application specific association */ + SND_PURGE = 0x0040, /* purge non-static events for task */ + SND_APPLICATION = 0x0080, /* look for application specific association */ - SND_ALIAS_START = 0, /* alias base */ + SND_ALIAS_START = 0, /* alias base */ } export BOOL PlaySoundA(LPCSTR pszSound, HMODULE hmod, DWORD fdwSound); @@ -2663,30 +2663,30 @@ alias LOGPEN* PLOGPEN, NPLOGPEN, LPLOGPEN; enum { - PS_SOLID = 0, - PS_DASH = 1, /* ------- */ - PS_DOT = 2, /* ....... */ - PS_DASHDOT = 3, /* _._._._ */ - PS_DASHDOTDOT = 4, /* _.._.._ */ - PS_NULL = 5, - PS_INSIDEFRAME = 6, - PS_USERSTYLE = 7, - PS_ALTERNATE = 8, - PS_STYLE_MASK = 0x0000000F, + PS_SOLID = 0, + PS_DASH = 1, /* ------- */ + PS_DOT = 2, /* ....... */ + PS_DASHDOT = 3, /* _._._._ */ + PS_DASHDOTDOT = 4, /* _.._.._ */ + PS_NULL = 5, + PS_INSIDEFRAME = 6, + PS_USERSTYLE = 7, + PS_ALTERNATE = 8, + PS_STYLE_MASK = 0x0000000F, - PS_ENDCAP_ROUND = 0x00000000, - PS_ENDCAP_SQUARE = 0x00000100, - PS_ENDCAP_FLAT = 0x00000200, - PS_ENDCAP_MASK = 0x00000F00, + PS_ENDCAP_ROUND = 0x00000000, + PS_ENDCAP_SQUARE = 0x00000100, + PS_ENDCAP_FLAT = 0x00000200, + PS_ENDCAP_MASK = 0x00000F00, - PS_JOIN_ROUND = 0x00000000, - PS_JOIN_BEVEL = 0x00001000, - PS_JOIN_MITER = 0x00002000, - PS_JOIN_MASK = 0x0000F000, + PS_JOIN_ROUND = 0x00000000, + PS_JOIN_BEVEL = 0x00001000, + PS_JOIN_MITER = 0x00002000, + PS_JOIN_MASK = 0x0000F000, - PS_COSMETIC = 0x00000000, - PS_GEOMETRIC = 0x00010000, - PS_TYPE_MASK = 0x000F0000, + PS_COSMETIC = 0x00000000, + PS_GEOMETRIC = 0x00010000, + PS_TYPE_MASK = 0x000F0000, } export HPALETTE CreatePalette(LOGPALETTE *); @@ -2703,7 +2703,7 @@ export BOOL CreateScalableFontResourceW(DWORD, LPCWSTR, LPCWSTR, LPCWSTR); COLORREF RGB(int r, int g, int b) { return cast(COLORREF) - ((cast(BYTE)r|(cast(WORD)(cast(BYTE)g)<<8))|((cast(DWORD)cast(BYTE)b)<<16)); + ((cast(BYTE)r|(cast(WORD)(cast(BYTE)g)<<8))|((cast(DWORD)cast(BYTE)b)<<16)); } export BOOL LineTo(HDC, int, int); @@ -2737,8 +2737,8 @@ export int wsprintfW(LPWSTR, LPCWSTR, ...); enum : uint { - INFINITE = uint.max, - WAIT_OBJECT_0 = 0, + INFINITE = uint.max, + WAIT_OBJECT_0 = 0, } export HANDLE CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCTSTR lpName); @@ -2778,15 +2778,15 @@ alias KEY_EVENT_RECORD *PKEY_EVENT_RECORD; enum { - RIGHT_ALT_PRESSED = 0x0001, // the right alt key is pressed. - LEFT_ALT_PRESSED = 0x0002, // the left alt key is pressed. - RIGHT_CTRL_PRESSED = 0x0004, // the right ctrl key is pressed. - LEFT_CTRL_PRESSED = 0x0008, // the left ctrl key is pressed. - SHIFT_PRESSED = 0x0010, // the shift key is pressed. - NUMLOCK_ON = 0x0020, // the numlock light is on. - SCROLLLOCK_ON = 0x0040, // the scrolllock light is on. - CAPSLOCK_ON = 0x0080, // the capslock light is on. - ENHANCED_KEY = 0x0100, // the key is enhanced. + RIGHT_ALT_PRESSED = 0x0001, // the right alt key is pressed. + LEFT_ALT_PRESSED = 0x0002, // the left alt key is pressed. + RIGHT_CTRL_PRESSED = 0x0004, // the right ctrl key is pressed. + LEFT_CTRL_PRESSED = 0x0008, // the left ctrl key is pressed. + SHIFT_PRESSED = 0x0010, // the shift key is pressed. + NUMLOCK_ON = 0x0020, // the numlock light is on. + SCROLLLOCK_ON = 0x0040, // the scrolllock light is on. + CAPSLOCK_ON = 0x0080, // the capslock light is on. + ENHANCED_KEY = 0x0100, // the key is enhanced. } struct MOUSE_EVENT_RECORD { @@ -2802,11 +2802,11 @@ alias MOUSE_EVENT_RECORD *PMOUSE_EVENT_RECORD; // enum { - FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001, - RIGHTMOST_BUTTON_PRESSED = 0x0002, - FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004, - FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008, - FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010, + FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001, + RIGHTMOST_BUTTON_PRESSED = 0x0002, + FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004, + FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008, + FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010, } // @@ -2815,8 +2815,8 @@ enum enum { - MOUSE_MOVED = 0x0001, - DOUBLE_CLICK = 0x0002, + MOUSE_MOVED = 0x0001, + DOUBLE_CLICK = 0x0002, } struct WINDOW_BUFFER_SIZE_RECORD { @@ -2852,11 +2852,11 @@ alias INPUT_RECORD *PINPUT_RECORD; enum { - KEY_EVENT = 0x0001, // Event contains key event record - MOUSE_EVENT = 0x0002, // Event contains mouse event record - WINDOW_BUFFER_SIZE_EVENT = 0x0004, // Event contains window change event record - MENU_EVENT = 0x0008, // Event contains menu event record - FOCUS_EVENT = 0x0010, // event contains focus change + KEY_EVENT = 0x0001, // Event contains key event record + MOUSE_EVENT = 0x0002, // Event contains mouse event record + WINDOW_BUFFER_SIZE_EVENT = 0x0004, // Event contains window change event record + MENU_EVENT = 0x0008, // Event contains menu event record + FOCUS_EVENT = 0x0010, // event contains focus change } struct CHAR_INFO { @@ -2874,14 +2874,14 @@ alias CHAR_INFO *PCHAR_INFO; enum { - FOREGROUND_BLUE = 0x0001, // text color contains blue. - FOREGROUND_GREEN = 0x0002, // text color contains green. - FOREGROUND_RED = 0x0004, // text color contains red. - FOREGROUND_INTENSITY = 0x0008, // text color is intensified. - BACKGROUND_BLUE = 0x0010, // background color contains blue. - BACKGROUND_GREEN = 0x0020, // background color contains green. - BACKGROUND_RED = 0x0040, // background color contains red. - BACKGROUND_INTENSITY = 0x0080, // background color is intensified. + FOREGROUND_BLUE = 0x0001, // text color contains blue. + FOREGROUND_GREEN = 0x0002, // text color contains green. + FOREGROUND_RED = 0x0004, // text color contains red. + FOREGROUND_INTENSITY = 0x0008, // text color is intensified. + BACKGROUND_BLUE = 0x0010, // background color contains blue. + BACKGROUND_GREEN = 0x0020, // background color contains green. + BACKGROUND_RED = 0x0040, // background color contains red. + BACKGROUND_INTENSITY = 0x0080, // background color is intensified. } struct CONSOLE_SCREEN_BUFFER_INFO { @@ -2901,17 +2901,17 @@ alias CONSOLE_CURSOR_INFO *PCONSOLE_CURSOR_INFO; enum { - ENABLE_PROCESSED_INPUT = 0x0001, - ENABLE_LINE_INPUT = 0x0002, - ENABLE_ECHO_INPUT = 0x0004, - ENABLE_WINDOW_INPUT = 0x0008, - ENABLE_MOUSE_INPUT = 0x0010, + ENABLE_PROCESSED_INPUT = 0x0001, + ENABLE_LINE_INPUT = 0x0002, + ENABLE_ECHO_INPUT = 0x0004, + ENABLE_WINDOW_INPUT = 0x0008, + ENABLE_MOUSE_INPUT = 0x0010, } enum { - ENABLE_PROCESSED_OUTPUT = 0x0001, - ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002, + ENABLE_PROCESSED_OUTPUT = 0x0001, + ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002, } BOOL PeekConsoleInputA(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead); @@ -2970,91 +2970,91 @@ BOOL SetConsoleOutputCP(UINT wCodePageID); enum : int { - CONSOLE_TEXTMODE_BUFFER = 1, + CONSOLE_TEXTMODE_BUFFER = 1, } enum { - SM_CXSCREEN = 0, - SM_CYSCREEN = 1, - SM_CXVSCROLL = 2, - SM_CYHSCROLL = 3, - SM_CYCAPTION = 4, - SM_CXBORDER = 5, - SM_CYBORDER = 6, - SM_CXDLGFRAME = 7, - SM_CYDLGFRAME = 8, - SM_CYVTHUMB = 9, - SM_CXHTHUMB = 10, - SM_CXICON = 11, - SM_CYICON = 12, - SM_CXCURSOR = 13, - SM_CYCURSOR = 14, - SM_CYMENU = 15, - SM_CXFULLSCREEN = 16, - SM_CYFULLSCREEN = 17, - SM_CYKANJIWINDOW = 18, - SM_MOUSEPRESENT = 19, - SM_CYVSCROLL = 20, - SM_CXHSCROLL = 21, - SM_DEBUG = 22, - SM_SWAPBUTTON = 23, - SM_RESERVED1 = 24, - SM_RESERVED2 = 25, - SM_RESERVED3 = 26, - SM_RESERVED4 = 27, - SM_CXMIN = 28, - SM_CYMIN = 29, - SM_CXSIZE = 30, - SM_CYSIZE = 31, - SM_CXFRAME = 32, - SM_CYFRAME = 33, - SM_CXMINTRACK = 34, - SM_CYMINTRACK = 35, - SM_CXDOUBLECLK = 36, - SM_CYDOUBLECLK = 37, - SM_CXICONSPACING = 38, - SM_CYICONSPACING = 39, - SM_MENUDROPALIGNMENT = 40, - SM_PENWINDOWS = 41, - SM_DBCSENABLED = 42, - SM_CMOUSEBUTTONS = 43, + SM_CXSCREEN = 0, + SM_CYSCREEN = 1, + SM_CXVSCROLL = 2, + SM_CYHSCROLL = 3, + SM_CYCAPTION = 4, + SM_CXBORDER = 5, + SM_CYBORDER = 6, + SM_CXDLGFRAME = 7, + SM_CYDLGFRAME = 8, + SM_CYVTHUMB = 9, + SM_CXHTHUMB = 10, + SM_CXICON = 11, + SM_CYICON = 12, + SM_CXCURSOR = 13, + SM_CYCURSOR = 14, + SM_CYMENU = 15, + SM_CXFULLSCREEN = 16, + SM_CYFULLSCREEN = 17, + SM_CYKANJIWINDOW = 18, + SM_MOUSEPRESENT = 19, + SM_CYVSCROLL = 20, + SM_CXHSCROLL = 21, + SM_DEBUG = 22, + SM_SWAPBUTTON = 23, + SM_RESERVED1 = 24, + SM_RESERVED2 = 25, + SM_RESERVED3 = 26, + SM_RESERVED4 = 27, + SM_CXMIN = 28, + SM_CYMIN = 29, + SM_CXSIZE = 30, + SM_CYSIZE = 31, + SM_CXFRAME = 32, + SM_CYFRAME = 33, + SM_CXMINTRACK = 34, + SM_CYMINTRACK = 35, + SM_CXDOUBLECLK = 36, + SM_CYDOUBLECLK = 37, + SM_CXICONSPACING = 38, + SM_CYICONSPACING = 39, + SM_MENUDROPALIGNMENT = 40, + SM_PENWINDOWS = 41, + SM_DBCSENABLED = 42, + SM_CMOUSEBUTTONS = 43, - SM_CXFIXEDFRAME = SM_CXDLGFRAME, - SM_CYFIXEDFRAME = SM_CYDLGFRAME, - SM_CXSIZEFRAME = SM_CXFRAME, - SM_CYSIZEFRAME = SM_CYFRAME, + SM_CXFIXEDFRAME = SM_CXDLGFRAME, + SM_CYFIXEDFRAME = SM_CYDLGFRAME, + SM_CXSIZEFRAME = SM_CXFRAME, + SM_CYSIZEFRAME = SM_CYFRAME, - SM_SECURE = 44, - SM_CXEDGE = 45, - SM_CYEDGE = 46, - SM_CXMINSPACING = 47, - SM_CYMINSPACING = 48, - SM_CXSMICON = 49, - SM_CYSMICON = 50, - SM_CYSMCAPTION = 51, - SM_CXSMSIZE = 52, - SM_CYSMSIZE = 53, - SM_CXMENUSIZE = 54, - SM_CYMENUSIZE = 55, - SM_ARRANGE = 56, - SM_CXMINIMIZED = 57, - SM_CYMINIMIZED = 58, - SM_CXMAXTRACK = 59, - SM_CYMAXTRACK = 60, - SM_CXMAXIMIZED = 61, - SM_CYMAXIMIZED = 62, - SM_NETWORK = 63, - SM_CLEANBOOT = 67, - SM_CXDRAG = 68, - SM_CYDRAG = 69, - SM_SHOWSOUNDS = 70, - SM_CXMENUCHECK = 71, - SM_CYMENUCHECK = 72, - SM_SLOWMACHINE = 73, - SM_MIDEASTENABLED = 74, - SM_CMETRICS = 75, + SM_SECURE = 44, + SM_CXEDGE = 45, + SM_CYEDGE = 46, + SM_CXMINSPACING = 47, + SM_CYMINSPACING = 48, + SM_CXSMICON = 49, + SM_CYSMICON = 50, + SM_CYSMCAPTION = 51, + SM_CXSMSIZE = 52, + SM_CYSMSIZE = 53, + SM_CXMENUSIZE = 54, + SM_CYMENUSIZE = 55, + SM_ARRANGE = 56, + SM_CXMINIMIZED = 57, + SM_CYMINIMIZED = 58, + SM_CXMAXTRACK = 59, + SM_CYMAXTRACK = 60, + SM_CXMAXIMIZED = 61, + SM_CYMAXIMIZED = 62, + SM_NETWORK = 63, + SM_CLEANBOOT = 67, + SM_CXDRAG = 68, + SM_CYDRAG = 69, + SM_SHOWSOUNDS = 70, + SM_CXMENUCHECK = 71, + SM_CYMENUCHECK = 72, + SM_SLOWMACHINE = 73, + SM_MIDEASTENABLED = 74, + SM_CMETRICS = 75, } int GetSystemMetrics(int nIndex); diff --git a/std/c/windows/winsock.d b/std/c/windows/winsock.d index 178d9b9b1..7d051c5fa 100644 --- a/std/c/windows/winsock.d +++ b/std/c/windows/winsock.d @@ -1,6 +1,6 @@ /* - Written by Christopher E. Miller - Placed into public domain. + Written by Christopher E. Miller + Placed into public domain. */ @@ -23,13 +23,13 @@ const int WSASYS_STATUS_LEN = 128; struct WSADATA { - WORD wVersion; - WORD wHighVersion; - char szDescription[WSADESCRIPTION_LEN + 1]; - char szSystemStatus[WSASYS_STATUS_LEN + 1]; - USHORT iMaxSockets; - USHORT iMaxUdpDg; - char* lpVendorInfo; + WORD wVersion; + WORD wHighVersion; + char szDescription[WSADESCRIPTION_LEN + 1]; + char szSystemStatus[WSASYS_STATUS_LEN + 1]; + USHORT iMaxSockets; + USHORT iMaxUdpDg; + char* lpVendorInfo; } alias WSADATA* LPWSADATA; @@ -73,9 +73,9 @@ int getnameinfo(sockaddr* sa, socklen_t salen, char* host, DWORD hostlen, char* enum: int { - WSAEWOULDBLOCK = 10035, - WSAEINTR = 10004, - WSAHOST_NOT_FOUND = 11001, + WSAEWOULDBLOCK = 10035, + WSAEINTR = 10004, + WSAHOST_NOT_FOUND = 11001, } int WSAGetLastError(); @@ -83,113 +83,113 @@ int WSAGetLastError(); enum: int { - AF_UNSPEC = 0, - - AF_UNIX = 1, - AF_INET = 2, - AF_IMPLINK = 3, - AF_PUP = 4, - AF_CHAOS = 5, - AF_NS = 6, - AF_IPX = AF_NS, - AF_ISO = 7, - AF_OSI = AF_ISO, - AF_ECMA = 8, - AF_DATAKIT = 9, - AF_CCITT = 10, - AF_SNA = 11, - AF_DECnet = 12, - AF_DLI = 13, - AF_LAT = 14, - AF_HYLINK = 15, - AF_APPLETALK = 16, - AF_NETBIOS = 17, - AF_VOICEVIEW = 18, - AF_FIREFOX = 19, - AF_UNKNOWN1 = 20, - AF_BAN = 21, - AF_ATM = 22, - AF_INET6 = 23, - AF_CLUSTER = 24, - AF_12844 = 25, - AF_IRDA = 26, - AF_NETDES = 28, - - AF_MAX = 29, - - - PF_UNSPEC = AF_UNSPEC, - - PF_UNIX = AF_UNIX, - PF_INET = AF_INET, - PF_IMPLINK = AF_IMPLINK, - PF_PUP = AF_PUP, - PF_CHAOS = AF_CHAOS, - PF_NS = AF_NS, - PF_IPX = AF_IPX, - PF_ISO = AF_ISO, - PF_OSI = AF_OSI, - PF_ECMA = AF_ECMA, - PF_DATAKIT = AF_DATAKIT, - PF_CCITT = AF_CCITT, - PF_SNA = AF_SNA, - PF_DECnet = AF_DECnet, - PF_DLI = AF_DLI, - PF_LAT = AF_LAT, - PF_HYLINK = AF_HYLINK, - PF_APPLETALK = AF_APPLETALK, - PF_VOICEVIEW = AF_VOICEVIEW, - PF_FIREFOX = AF_FIREFOX, - PF_UNKNOWN1 = AF_UNKNOWN1, - PF_BAN = AF_BAN, - PF_INET6 = AF_INET6, - - PF_MAX = AF_MAX, + AF_UNSPEC = 0, + + AF_UNIX = 1, + AF_INET = 2, + AF_IMPLINK = 3, + AF_PUP = 4, + AF_CHAOS = 5, + AF_NS = 6, + AF_IPX = AF_NS, + AF_ISO = 7, + AF_OSI = AF_ISO, + AF_ECMA = 8, + AF_DATAKIT = 9, + AF_CCITT = 10, + AF_SNA = 11, + AF_DECnet = 12, + AF_DLI = 13, + AF_LAT = 14, + AF_HYLINK = 15, + AF_APPLETALK = 16, + AF_NETBIOS = 17, + AF_VOICEVIEW = 18, + AF_FIREFOX = 19, + AF_UNKNOWN1 = 20, + AF_BAN = 21, + AF_ATM = 22, + AF_INET6 = 23, + AF_CLUSTER = 24, + AF_12844 = 25, + AF_IRDA = 26, + AF_NETDES = 28, + + AF_MAX = 29, + + + PF_UNSPEC = AF_UNSPEC, + + PF_UNIX = AF_UNIX, + PF_INET = AF_INET, + PF_IMPLINK = AF_IMPLINK, + PF_PUP = AF_PUP, + PF_CHAOS = AF_CHAOS, + PF_NS = AF_NS, + PF_IPX = AF_IPX, + PF_ISO = AF_ISO, + PF_OSI = AF_OSI, + PF_ECMA = AF_ECMA, + PF_DATAKIT = AF_DATAKIT, + PF_CCITT = AF_CCITT, + PF_SNA = AF_SNA, + PF_DECnet = AF_DECnet, + PF_DLI = AF_DLI, + PF_LAT = AF_LAT, + PF_HYLINK = AF_HYLINK, + PF_APPLETALK = AF_APPLETALK, + PF_VOICEVIEW = AF_VOICEVIEW, + PF_FIREFOX = AF_FIREFOX, + PF_UNKNOWN1 = AF_UNKNOWN1, + PF_BAN = AF_BAN, + PF_INET6 = AF_INET6, + + PF_MAX = AF_MAX, } enum: int { - SOL_SOCKET = 0xFFFF, + SOL_SOCKET = 0xFFFF, } enum: int { - SO_DEBUG = 0x0001, - SO_ACCEPTCONN = 0x0002, - SO_REUSEADDR = 0x0004, - SO_KEEPALIVE = 0x0008, - SO_DONTROUTE = 0x0010, - SO_BROADCAST = 0x0020, - SO_USELOOPBACK = 0x0040, - SO_LINGER = 0x0080, - SO_DONTLINGER = ~SO_LINGER, - SO_OOBINLINE = 0x0100, - SO_SNDBUF = 0x1001, - SO_RCVBUF = 0x1002, - SO_SNDLOWAT = 0x1003, - SO_RCVLOWAT = 0x1004, - SO_SNDTIMEO = 0x1005, - SO_RCVTIMEO = 0x1006, - SO_ERROR = 0x1007, - SO_TYPE = 0x1008, - SO_EXCLUSIVEADDRUSE = ~SO_REUSEADDR, - - TCP_NODELAY = 1, - - IP_MULTICAST_LOOP = 0x4, - IP_ADD_MEMBERSHIP = 0x5, - IP_DROP_MEMBERSHIP = 0x6, - - IPV6_UNICAST_HOPS = 4, - IPV6_MULTICAST_IF = 9, - IPV6_MULTICAST_HOPS = 10, - IPV6_MULTICAST_LOOP = 11, - IPV6_ADD_MEMBERSHIP = 12, - IPV6_DROP_MEMBERSHIP = 13, - IPV6_JOIN_GROUP = IPV6_ADD_MEMBERSHIP, - IPV6_LEAVE_GROUP = IPV6_DROP_MEMBERSHIP, + SO_DEBUG = 0x0001, + SO_ACCEPTCONN = 0x0002, + SO_REUSEADDR = 0x0004, + SO_KEEPALIVE = 0x0008, + SO_DONTROUTE = 0x0010, + SO_BROADCAST = 0x0020, + SO_USELOOPBACK = 0x0040, + SO_LINGER = 0x0080, + SO_DONTLINGER = ~SO_LINGER, + SO_OOBINLINE = 0x0100, + SO_SNDBUF = 0x1001, + SO_RCVBUF = 0x1002, + SO_SNDLOWAT = 0x1003, + SO_RCVLOWAT = 0x1004, + SO_SNDTIMEO = 0x1005, + SO_RCVTIMEO = 0x1006, + SO_ERROR = 0x1007, + SO_TYPE = 0x1008, + SO_EXCLUSIVEADDRUSE = ~SO_REUSEADDR, + + TCP_NODELAY = 1, + + IP_MULTICAST_LOOP = 0x4, + IP_ADD_MEMBERSHIP = 0x5, + IP_DROP_MEMBERSHIP = 0x6, + + IPV6_UNICAST_HOPS = 4, + IPV6_MULTICAST_IF = 9, + IPV6_MULTICAST_HOPS = 10, + IPV6_MULTICAST_LOOP = 11, + IPV6_ADD_MEMBERSHIP = 12, + IPV6_DROP_MEMBERSHIP = 13, + IPV6_JOIN_GROUP = IPV6_ADD_MEMBERSHIP, + IPV6_LEAVE_GROUP = IPV6_DROP_MEMBERSHIP, } @@ -198,280 +198,280 @@ const uint FD_SETSIZE = 64; struct fd_set { - UINT fd_count; - SOCKET[FD_SETSIZE] fd_array; + UINT fd_count; + SOCKET[FD_SETSIZE] fd_array; } // Removes. void FD_CLR(SOCKET fd, fd_set* set) { - uint c = set.fd_count; - SOCKET* start = set.fd_array.ptr; - SOCKET* stop = start + c; - - for(; start != stop; start++) - { - if(*start == fd) - goto found; - } - return; //not found - - found: - for(++start; start != stop; start++) - { - *(start - 1) = *start; - } - - set.fd_count = c - 1; + uint c = set.fd_count; + SOCKET* start = set.fd_array.ptr; + SOCKET* stop = start + c; + + for(; start != stop; start++) + { + if(*start == fd) + goto found; + } + return; //not found + + found: + for(++start; start != stop; start++) + { + *(start - 1) = *start; + } + + set.fd_count = c - 1; } // Tests. int FD_ISSET(SOCKET fd, fd_set* set) { - SOCKET* start = set.fd_array.ptr; - SOCKET* stop = start + set.fd_count; - - for(; start != stop; start++) - { - if(*start == fd) - return true; - } - return false; + SOCKET* start = set.fd_array.ptr; + SOCKET* stop = start + set.fd_count; + + for(; start != stop; start++) + { + if(*start == fd) + return true; + } + return false; } // Adds. void FD_SET(SOCKET fd, fd_set* set) { - uint c = set.fd_count; - set.fd_array.ptr[c] = fd; - set.fd_count = c + 1; + uint c = set.fd_count; + set.fd_array.ptr[c] = fd; + set.fd_count = c + 1; } // Resets to zero. void FD_ZERO(fd_set* set) { - set.fd_count = 0; + set.fd_count = 0; } struct linger { - USHORT l_onoff; - USHORT l_linger; + USHORT l_onoff; + USHORT l_linger; } struct protoent { - char* p_name; - char** p_aliases; - SHORT p_proto; + char* p_name; + char** p_aliases; + SHORT p_proto; } struct servent { - char* s_name; - char** s_aliases; - SHORT s_port; - char* s_proto; + char* s_name; + char** s_aliases; + SHORT s_port; + char* s_proto; } /+ union in6_addr { - private union _u_t - { - BYTE[16] Byte; - WORD[8] Word; - } - _u_t u; + private union _u_t + { + BYTE[16] Byte; + WORD[8] Word; + } + _u_t u; } struct in_addr6 { - BYTE[16] s6_addr; + BYTE[16] s6_addr; } +/ version(BigEndian) { - uint16_t htons(uint16_t x) - { - return x; - } - - - uint32_t htonl(uint32_t x) - { - return x; - } + uint16_t htons(uint16_t x) + { + return x; + } + + + uint32_t htonl(uint32_t x) + { + return x; + } } else version(LittleEndian) { - private import std.intrinsic; - - - uint16_t htons(uint16_t x) - { - return cast(uint16_t)((x >> 8) | (x << 8)); - } + private import std.intrinsic; - uint32_t htonl(uint32_t x) - { - return bswap(x); - } + uint16_t htons(uint16_t x) + { + return cast(uint16_t)((x >> 8) | (x << 8)); + } + + + uint32_t htonl(uint32_t x) + { + return bswap(x); + } } else { - static assert(0); + static assert(0); } uint16_t ntohs(uint16_t x) { - return htons(x); + return htons(x); } uint32_t ntohl(uint32_t x) { - return htonl(x); + return htonl(x); } enum: int { - SOCK_STREAM = 1, - SOCK_DGRAM = 2, - SOCK_RAW = 3, - SOCK_RDM = 4, - SOCK_SEQPACKET = 5, + SOCK_STREAM = 1, + SOCK_DGRAM = 2, + SOCK_RAW = 3, + SOCK_RDM = 4, + SOCK_SEQPACKET = 5, } enum: int { - IPPROTO_IP = 0, - IPPROTO_ICMP = 1, - IPPROTO_IGMP = 2, - IPPROTO_GGP = 3, - IPPROTO_TCP = 6, - IPPROTO_PUP = 12, - IPPROTO_UDP = 17, - IPPROTO_IDP = 22, - IPPROTO_IPV6 = 41, - IPPROTO_ND = 77, - IPPROTO_RAW = 255, - - IPPROTO_MAX = 256, + IPPROTO_IP = 0, + IPPROTO_ICMP = 1, + IPPROTO_IGMP = 2, + IPPROTO_GGP = 3, + IPPROTO_TCP = 6, + IPPROTO_PUP = 12, + IPPROTO_UDP = 17, + IPPROTO_IDP = 22, + IPPROTO_IPV6 = 41, + IPPROTO_ND = 77, + IPPROTO_RAW = 255, + + IPPROTO_MAX = 256, } enum: int { - MSG_OOB = 0x1, - MSG_PEEK = 0x2, - MSG_DONTROUTE = 0x4, + MSG_OOB = 0x1, + MSG_PEEK = 0x2, + MSG_DONTROUTE = 0x4, MSG_NOSIGNAL = 0x0, /// not supported on win32, would be 0x4000 if it was } enum: int { - SD_RECEIVE = 0, - SD_SEND = 1, - SD_BOTH = 2, + SD_RECEIVE = 0, + SD_SEND = 1, + SD_BOTH = 2, } enum: uint { - INADDR_ANY = 0, - INADDR_LOOPBACK = 0x7F000001, - INADDR_BROADCAST = 0xFFFFFFFF, - INADDR_NONE = 0xFFFFFFFF, - ADDR_ANY = INADDR_ANY, + INADDR_ANY = 0, + INADDR_LOOPBACK = 0x7F000001, + INADDR_BROADCAST = 0xFFFFFFFF, + INADDR_NONE = 0xFFFFFFFF, + ADDR_ANY = INADDR_ANY, } enum: int { - AI_PASSIVE = 0x1, - AI_CANONNAME = 0x2, - AI_NUMERICHOST = 0x4, + AI_PASSIVE = 0x1, + AI_CANONNAME = 0x2, + AI_NUMERICHOST = 0x4, } struct timeval { - int32_t tv_sec; - int32_t tv_usec; + int32_t tv_sec; + int32_t tv_usec; } union in_addr { - private union _S_un_t - { - private struct _S_un_b_t - { - uint8_t s_b1, s_b2, s_b3, s_b4; - } - _S_un_b_t S_un_b; - - private struct _S_un_w_t - { - uint16_t s_w1, s_w2; - } - _S_un_w_t S_un_w; - - uint32_t S_addr; - } - _S_un_t S_un; - - uint32_t s_addr; - - struct - { - uint8_t s_net, s_host; - - union - { - uint16_t s_imp; - - struct - { - uint8_t s_lh, s_impno; - } - } - } + private union _S_un_t + { + private struct _S_un_b_t + { + uint8_t s_b1, s_b2, s_b3, s_b4; + } + _S_un_b_t S_un_b; + + private struct _S_un_w_t + { + uint16_t s_w1, s_w2; + } + _S_un_w_t S_un_w; + + uint32_t S_addr; + } + _S_un_t S_un; + + uint32_t s_addr; + + struct + { + uint8_t s_net, s_host; + + union + { + uint16_t s_imp; + + struct + { + uint8_t s_lh, s_impno; + } + } + } } union in6_addr { - private union _in6_u_t - { - uint8_t[16] u6_addr8; - uint16_t[8] u6_addr16; - uint32_t[4] u6_addr32; - } - _in6_u_t in6_u; - - uint8_t[16] s6_addr8; - uint16_t[8] s6_addr16; - uint32_t[4] s6_addr32; - - alias s6_addr8 s6_addr; + private union _in6_u_t + { + uint8_t[16] u6_addr8; + uint16_t[8] u6_addr16; + uint32_t[4] u6_addr32; + } + _in6_u_t in6_u; + + uint8_t[16] s6_addr8; + uint16_t[8] s6_addr16; + uint32_t[4] s6_addr32; + + alias s6_addr8 s6_addr; } @@ -479,62 +479,62 @@ const in6_addr IN6ADDR_ANY = { s6_addr8: [0] }; const in6_addr IN6ADDR_LOOPBACK = { s6_addr8: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }; //alias IN6ADDR_ANY IN6ADDR_ANY_INIT; //alias IN6ADDR_LOOPBACK IN6ADDR_LOOPBACK_INIT; - + const uint INET_ADDRSTRLEN = 16; const uint INET6_ADDRSTRLEN = 46; struct sockaddr { - int16_t sa_family; - ubyte[14] sa_data; + int16_t sa_family; + ubyte[14] sa_data; } struct sockaddr_in { - int16_t sin_family = AF_INET; - uint16_t sin_port; - in_addr sin_addr; - ubyte[8] sin_zero; + int16_t sin_family = AF_INET; + uint16_t sin_port; + in_addr sin_addr; + ubyte[8] sin_zero; } struct sockaddr_in6 { - int16_t sin6_family = AF_INET6; - uint16_t sin6_port; - uint32_t sin6_flowinfo; - in6_addr sin6_addr; - uint32_t sin6_scope_id; + int16_t sin6_family = AF_INET6; + uint16_t sin6_port; + uint32_t sin6_flowinfo; + in6_addr sin6_addr; + uint32_t sin6_scope_id; } struct addrinfo { - int32_t ai_flags; - int32_t ai_family; - int32_t ai_socktype; - int32_t ai_protocol; - size_t ai_addrlen; - char* ai_canonname; - sockaddr* ai_addr; - addrinfo* ai_next; + int32_t ai_flags; + int32_t ai_family; + int32_t ai_socktype; + int32_t ai_protocol; + size_t ai_addrlen; + char* ai_canonname; + sockaddr* ai_addr; + addrinfo* ai_next; } struct hostent { - char* h_name; - char** h_aliases; - int16_t h_addrtype; - int16_t h_length; - char** h_addr_list; - - - char* h_addr() - { - return h_addr_list[0]; - } + char* h_name; + char** h_aliases; + int16_t h_addrtype; + int16_t h_length; + char** h_addr_list; + + + char* h_addr() + { + return h_addr_list[0]; + } } diff --git a/std/compiler.d b/std/compiler.d index b1dfd727f..2855fe3f2 100644 --- a/std/compiler.d +++ b/std/compiler.d @@ -1,7 +1,7 @@ /** * Macros: - * WIKI = Phobos/StdCompiler + * WIKI = Phobos/StdCompiler */ /** @@ -21,7 +21,7 @@ const /// Master list of D compiler vendors. enum Vendor { - DigitalMars = 1, /// Digital Mars + DigitalMars = 1, /// Digital Mars } /// Which vendor produced this compiler. @@ -33,7 +33,7 @@ const * version_major.version_minor */ uint version_major = __VERSION__ / 1000; - uint version_minor = __VERSION__ % 1000; /// ditto + uint version_minor = __VERSION__ % 1000; /// ditto /** diff --git a/std/conv.d b/std/conv.d index 890690021..acb0ea5ee 100644 --- a/std/conv.d +++ b/std/conv.d @@ -46,7 +46,7 @@ $(I UnsignedInteger): $(I DecimalDigit) $(I UnsignedInteger) * * Macros: - * WIKI=Phobos/StdConv + * WIKI=Phobos/StdConv */ module std.conv; @@ -57,7 +57,7 @@ private import std.math; // for fabs(), isnan() private import std.stdio; // for writefln() and printf() -//debug=conv; // uncomment to turn on debugging printf's +//debug=conv; // uncomment to turn on debugging printf's /* ************* Exceptions *************** */ @@ -68,7 +68,7 @@ class ConvError : Error { this(char[] s) { - super("conversion " ~ s); + super("conversion " ~ s); } } @@ -84,7 +84,7 @@ class ConvOverflowError : Error { this(char[] s) { - super("Error: overflow " ~ s); + super("Error: overflow " ~ s); } } @@ -102,45 +102,45 @@ int toInt(char[] s) int length = s.length; if (!length) - goto Lerr; + goto Lerr; int sign = 0; int v = 0; for (int i = 0; i < length; i++) { - char c = s[i]; - if (c >= '0' && c <= '9') - { - if (v < int.max/10 || (v == int.max/10 && c + sign <= '7')) - v = v * 10 + (c - '0'); - else - goto Loverflow; - } - else if (c == '-' && i == 0) - { - sign = -1; - if (length == 1) - goto Lerr; - } - else if (c == '+' && i == 0) - { - if (length == 1) - goto Lerr; - } - else - goto Lerr; + char c = s[i]; + if (c >= '0' && c <= '9') + { + if (v < int.max/10 || (v == int.max/10 && c + sign <= '7')) + v = v * 10 + (c - '0'); + else + goto Loverflow; + } + else if (c == '-' && i == 0) + { + sign = -1; + if (length == 1) + goto Lerr; + } + else if (c == '+' && i == 0) + { + if (length == 1) + goto Lerr; + } + else + goto Lerr; } if (sign == -1) { - if (cast(uint)v > 0x80000000) - goto Loverflow; - v = -v; + if (cast(uint)v > 0x80000000) + goto Loverflow; + v = -v; } else { - if (cast(uint)v > 0x7FFFFFFF) - goto Loverflow; + if (cast(uint)v > 0x7FFFFFFF) + goto Loverflow; } return v; @@ -184,36 +184,36 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "xx", - "123h", - "2147483648", - "-2147483649", - "5656566565", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "xx", + "123h", + "2147483648", + "-2147483649", + "5656566565", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toInt(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toInt(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -227,22 +227,22 @@ uint toUint(char[] s) int length = s.length; if (!length) - goto Lerr; + goto Lerr; uint v = 0; for (int i = 0; i < length; i++) { - char c = s[i]; - if (c >= '0' && c <= '9') - { - if (v < uint.max/10 || (v == uint.max/10 && c <= '5')) - v = v * 10 + (c - '0'); - else - goto Loverflow; - } - else - goto Lerr; + char c = s[i]; + if (c >= '0' && c <= '9') + { + if (v < uint.max/10 || (v == uint.max/10 && c <= '5')) + v = v * 10 + (c - '0'); + else + goto Loverflow; + } + else + goto Lerr; } return v; @@ -280,36 +280,36 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "+5", - "-78", - "xx", - "123h", - "4294967296", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "+5", + "-78", + "xx", + "123h", + "4294967296", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toUint(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toUint(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -322,45 +322,45 @@ long toLong(char[] s) int length = s.length; if (!length) - goto Lerr; + goto Lerr; int sign = 0; long v = 0; for (int i = 0; i < length; i++) { - char c = s[i]; - if (c >= '0' && c <= '9') - { - if (v < long.max/10 || (v == long.max/10 && c + sign <= '7')) - v = v * 10 + (c - '0'); - else - goto Loverflow; - } - else if (c == '-' && i == 0) - { - sign = -1; - if (length == 1) - goto Lerr; - } - else if (c == '+' && i == 0) - { - if (length == 1) - goto Lerr; - } - else - goto Lerr; + char c = s[i]; + if (c >= '0' && c <= '9') + { + if (v < long.max/10 || (v == long.max/10 && c + sign <= '7')) + v = v * 10 + (c - '0'); + else + goto Loverflow; + } + else if (c == '-' && i == 0) + { + sign = -1; + if (length == 1) + goto Lerr; + } + else if (c == '+' && i == 0) + { + if (length == 1) + goto Lerr; + } + else + goto Lerr; } if (sign == -1) { - if (cast(ulong)v > 0x8000000000000000) - goto Loverflow; - v = -v; + if (cast(ulong)v > 0x8000000000000000) + goto Loverflow; + v = -v; } else { - if (cast(ulong)v > 0x7FFFFFFFFFFFFFFF) - goto Loverflow; + if (cast(ulong)v > 0x7FFFFFFFFFFFFFFF) + goto Loverflow; } return v; @@ -410,35 +410,35 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "xx", - "123h", - "9223372036854775808", - "-9223372036854775809", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "xx", + "123h", + "9223372036854775808", + "-9223372036854775809", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toLong(errors[j]); - printf("l = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toLong(errors[j]); + printf("l = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -452,22 +452,22 @@ ulong toUlong(char[] s) int length = s.length; if (!length) - goto Lerr; + goto Lerr; ulong v = 0; for (int i = 0; i < length; i++) { - char c = s[i]; - if (c >= '0' && c <= '9') - { - if (v < ulong.max/10 || (v == ulong.max/10 && c <= '5')) - v = v * 10 + (c - '0'); - else - goto Loverflow; - } - else - goto Lerr; + char c = s[i]; + if (c >= '0' && c <= '9') + { + if (v < ulong.max/10 || (v == ulong.max/10 && c <= '5')) + v = v * 10 + (c - '0'); + else + goto Loverflow; + } + else + goto Lerr; } return v; @@ -512,36 +512,36 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "+5", - "-78", - "xx", - "123h", - "18446744073709551616", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "+5", + "-78", + "xx", + "123h", + "18446744073709551616", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toUlong(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toUlong(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -555,7 +555,7 @@ short toShort(char[] s) int v = toInt(s); if (v != cast(short)v) - goto Loverflow; + goto Loverflow; return cast(short)v; @@ -596,35 +596,35 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "xx", - "123h", - "32768", - "-32769", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "xx", + "123h", + "32768", + "-32769", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toShort(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toShort(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -638,7 +638,7 @@ ushort toUshort(char[] s) uint v = toUint(s); if (v != cast(ushort)v) - goto Loverflow; + goto Loverflow; return cast(ushort)v; @@ -673,36 +673,36 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "+5", - "-78", - "xx", - "123h", - "65536", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "+5", + "-78", + "xx", + "123h", + "65536", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toUshort(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toUshort(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -716,7 +716,7 @@ byte toByte(char[] s) int v = toInt(s); if (v != cast(byte)v) - goto Loverflow; + goto Loverflow; return cast(byte)v; @@ -757,35 +757,35 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "xx", - "123h", - "128", - "-129", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "xx", + "123h", + "128", + "-129", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toByte(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toByte(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -799,7 +799,7 @@ ubyte toUbyte(char[] s) uint v = toUint(s); if (v != cast(ubyte)v) - goto Loverflow; + goto Loverflow; return cast(ubyte)v; @@ -834,36 +834,36 @@ unittest static char[][] errors = [ - "", - "-", - "+", - "-+", - " ", - " 0", - "0 ", - "- 0", - "1-", - "+5", - "-78", - "xx", - "123h", - "256", + "", + "-", + "+", + "-+", + " ", + " 0", + "0 ", + "- 0", + "1-", + "+5", + "-78", + "xx", + "123h", + "256", ]; for (int j = 0; j < errors.length; j++) { - i = 47; - try - { - i = toUbyte(errors[j]); - printf("i = %d\n", i); - } - catch (Error e) - { - debug(conv) e.print(); - i = 3; - } - assert(i == 3); + i = 47; + try + { + i = toUbyte(errors[j]); + printf("i = %d\n", i); + } + catch (Error e) + { + debug(conv) e.print(); + i = 3; + } + assert(i == 3); } } @@ -881,29 +881,29 @@ float toFloat(in char[] s) //writefln("toFloat('%s')", s); sz = toStringz(s); if (std.ctype.isspace(*sz)) - goto Lerr; + goto Lerr; // BUG: should set __locale_decpoint to "." for DMC setErrno(0); f = strtof(sz, &endptr); if (getErrno() == ERANGE) - goto Lerr; + goto Lerr; if (endptr && (endptr == sz || *endptr != 0)) - goto Lerr; + goto Lerr; return f; - + Lerr: conv_error(s ~ " not representable as a float"); assert(0); } - + unittest { debug( conv ) writefln( "conv.toFloat.unittest" ); float f; - + f = toFloat( "123" ); assert( f == 123f ); f = toFloat( "+123" ); @@ -919,7 +919,7 @@ unittest assert( f == 123.f ); f = toFloat( ".456" ); assert( f == .456f ); - + // min and max f = toFloat("1.17549e-38"); assert(feq(cast(real)f, cast(real)1.17549e-38)); @@ -934,11 +934,11 @@ unittest bool ok = false; try { - toFloat("\x00"); + toFloat("\x00"); } catch (ConvError e) { - ok = true; + ok = true; } assert(ok); } @@ -956,19 +956,19 @@ double toDouble(in char[] s) //writefln("toDouble('%s')", s); sz = toStringz(s); if (std.ctype.isspace(*sz)) - goto Lerr; + goto Lerr; // BUG: should set __locale_decpoint to "." for DMC setErrno(0); f = strtod(sz, &endptr); if (getErrno() == ERANGE) - goto Lerr; + goto Lerr; if (endptr && (endptr == sz || *endptr != 0)) - goto Lerr; + goto Lerr; return f; - + Lerr: conv_error(s ~ " not representable as a double"); assert(0); @@ -1012,11 +1012,11 @@ unittest bool ok = false; try { - toDouble("\x00"); + toDouble("\x00"); } catch (ConvError e) { - ok = true; + ok = true; } assert(ok); } @@ -1033,19 +1033,19 @@ real toReal(in char[] s) //writefln("toReal('%s')", s); sz = toStringz(s); if (std.ctype.isspace(*sz)) - goto Lerr; + goto Lerr; // BUG: should set __locale_decpoint to "." for DMC setErrno(0); f = strtold(sz, &endptr); if (getErrno() == ERANGE) - goto Lerr; + goto Lerr; if (endptr && (endptr == sz || *endptr != 0)) - goto Lerr; + goto Lerr; return f; - + Lerr: conv_error(s ~ " not representable as a real"); assert(0); @@ -1094,11 +1094,11 @@ unittest bool ok = false; try { - toReal("\x00"); + toReal("\x00"); } catch (ConvError e) { - ok = true; + ok = true; } assert(ok); } @@ -1124,7 +1124,7 @@ unittest { debug(conv) writefln("conv.toIfloat.unittest"); ifloat ift; - + ift = toIfloat(toString(123.45)); assert(toString(ift) == toString(123.45i)); @@ -1139,7 +1139,7 @@ unittest ift = toIfloat(toString(ifloat.max)); assert(toString(ift) == toString(ifloat.max)); assert(feq(cast(ireal)ift, cast(ireal)ifloat.max)); - + // nan ift = toIfloat("nani"); assert(cast(real)ift == cast(real)ifloat.nan); @@ -1174,12 +1174,12 @@ unittest assert(toString( id ) == toString(idouble.min)); assert(feq(cast(ireal)id.re, cast(ireal)idouble.min.re)); assert(feq(cast(ireal)id.im, cast(ireal)idouble.min.im)); - + id = toIdouble(toString(idouble.max)); assert(toString(id) == toString(idouble.max)); assert(feq(cast(ireal)id.re, cast(ireal)idouble.max.re)); assert(feq(cast(ireal)id.im, cast(ireal)idouble.max.im)); - + // nan id = toIdouble("nani"); assert(cast(real)id == cast(real)idouble.nan); @@ -1203,7 +1203,7 @@ unittest ireal ir; ir = toIreal(toString("123.45")); - assert(feq(cast(real)ir.re, cast(real)123.45i)); + assert(feq(cast(real)ir.re, cast(real)123.45i)); ir = toIreal(toString("123.45e+82i")); assert(toString(ir) == toString(123.45e+82i)); @@ -1244,26 +1244,26 @@ cfloat toCfloat(in char[] s) if (!s.length) goto Lerr; - + b = getComplexStrings(s, s1, s2); if (!b) goto Lerr; - + // atof(s1); endptr = &s1[s1.length - 1]; - r1 = strtold(s1, &endptr); + r1 = strtold(s1, &endptr); // atof(s2); endptr = &s2[s2.length - 1]; - r2 = strtold(s2, &endptr); + r2 = strtold(s2, &endptr); cf = cast(cfloat)(r1 + (r2 * 1.0i)); - //writefln( "toCfloat() r1=%g, r2=%g, cf=%g, max=%g", + //writefln( "toCfloat() r1=%g, r2=%g, cf=%g, max=%g", // r1, r2, cf, cfloat.max); - // Currently disabled due to a posted bug where a - // complex float greater-than compare to .max compares + // Currently disabled due to a posted bug where a + // complex float greater-than compare to .max compares // incorrectly. //if (cf > cfloat.max) // goto Loverflow; @@ -1272,10 +1272,10 @@ cfloat toCfloat(in char[] s) Loverflow: conv_overflow(s); - + Lerr: conv_error(s); - return cast(cfloat)0.0e-0+0i; + return cast(cfloat)0.0e-0+0i; } unittest @@ -1293,10 +1293,10 @@ unittest cf = toCfloat(toString(cfloat.max)); assert(toString(cf) == toString(cfloat.max)); - + // nan ( nan+nani ) cf = toCfloat("nani"); - //writefln("toCfloat() cf=%g, cf=\"%s\", nan=%s", + //writefln("toCfloat() cf=%g, cf=\"%s\", nan=%s", // cf, toString(cf), toString(cfloat.nan)); assert(toString(cf) == toString(cfloat.nan)); @@ -1323,7 +1323,7 @@ cdouble toCdouble(in char[] s) if (!s.length) goto Lerr; - + b = getComplexStrings(s, s1, s2); if (!b) @@ -1331,14 +1331,14 @@ cdouble toCdouble(in char[] s) // atof(s1); endptr = &s1[s1.length - 1]; - r1 = strtold(s1, &endptr); + r1 = strtold(s1, &endptr); // atof(s2); endptr = &s2[s2.length - 1]; r2 = strtold(s2, &endptr); //atof(s2); cd = cast(cdouble)(r1 + (r2 * 1.0i)); - + //Disabled, waiting on a bug fix. //if (cd > cdouble.max) //same problem the toCfloat() having // goto Loverflow; @@ -1347,10 +1347,10 @@ cdouble toCdouble(in char[] s) Loverflow: conv_overflow(s); - + Lerr: conv_error(s); - return cast(cdouble)0.0e-0+0i; + return cast(cdouble)0.0e-0+0i; } unittest @@ -1403,30 +1403,30 @@ creal toCreal(in char[] s) if (!b) goto Lerr; - + // atof(s1); endptr = &s1[s1.length - 1]; - r1 = strtold(s1, &endptr); + r1 = strtold(s1, &endptr); // atof(s2); endptr = &s2[s2.length - 1]; r2 = strtold(s2, &endptr); //atof(s2); - //writefln("toCreal() r1=%g, r2=%g, s1=\"%s\", s2=\"%s\", nan=%g", + //writefln("toCreal() r1=%g, r2=%g, s1=\"%s\", s2=\"%s\", nan=%g", // r1, r2, s1, s2, creal.nan); - + if (s1 =="nan" && s2 == "nani") cr = creal.nan; else if (r2 != 0.0) cr = cast(creal)(r1 + (r2 * 1.0i)); else - cr = cast(creal)(r1 + 0.0i); - + cr = cast(creal)(r1 + 0.0i); + return cr; Lerr: conv_error(s); - return cast(creal)0.0e-0+0i; + return cast(creal)0.0e-0+0i; } unittest @@ -1442,13 +1442,13 @@ unittest assert(toString(cr) == toString(0.0e-0+0i)); assert(cr == 0.0e-0+0i); assert(feq(cr, 0.0e-0+0i)); - + cr = toCreal("123"); assert(cr == 123); cr = toCreal("+5"); assert(cr == 5); - + cr = toCreal("-78"); assert(cr == -78); @@ -1456,7 +1456,7 @@ unittest cr = toCreal(toString(creal.min)); assert(toString(cr) == toString(creal.min)); assert(feq(cr, creal.min)); - + cr = toCreal(toString(creal.max)); assert(toString(cr) == toString(creal.max)); assert(feq(cr, creal.max)); @@ -1484,7 +1484,7 @@ private bool getComplexStrings(in char[] s, out char[] s1, out char[] s2) { int len = s.length; - if (!len) + if (!len) goto Lerr; // When "nan" or "nani" just return them. @@ -1494,7 +1494,7 @@ private bool getComplexStrings(in char[] s, out char[] s1, out char[] s2) s2 = "nani"; return 1; } - + // Split the original string out into two strings. for (int i = 1; i < len; i++) if ((s[i - 1] != 'e' && s[i - 1] != 'E') && s[i] == '+') @@ -1502,23 +1502,23 @@ private bool getComplexStrings(in char[] s, out char[] s1, out char[] s2) s1 = s[0..i]; if (i + 1 < len - 1) s2 = s[i + 1..len - 1]; - else + else s2 = "0e+0i"; - - break; - } - // Handle the case when there's only a single value + break; + } + + // Handle the case when there's only a single value // to work with, and set the other string to zero. if (!s1.length) { s1 = s; s2 = "0e+0i"; } - - //writefln( "getComplexStrings() s=\"%s\", s1=\"%s\", s2=\"%s\", len=%d", + + //writefln( "getComplexStrings() s=\"%s\", s1=\"%s\", s2=\"%s\", len=%d", // s, s1, s2, len ); - + return 1; Lerr: @@ -1536,13 +1536,13 @@ private bool feq(in real rx, in real ry, in real precision) { if (rx == ry) return 1; - + if (isnan(rx)) return cast(bool)isnan(ry); if (isnan(ry)) return 0; - + return cast(bool)(fabs(rx - ry) <= precision); } @@ -1558,16 +1558,16 @@ private bool feq(in real r1, in real r2) { if (r1 == r2) return 1; - + if (isnan(r1)) return cast(bool)isnan(r2); if (isnan(r2)) return 0; - + return cast(bool)(feq(r1, r2, 0.000001L)); -} - +} + /* *************************************** * compare ireals with given precision */ @@ -1578,15 +1578,15 @@ private bool feq(in ireal r1, in ireal r2) if (rx == ry) return 1; - - if (isnan(rx)) + + if (isnan(rx)) return cast(bool)isnan(ry); if (isnan(ry)) return 0; - + return feq(rx, ry, 0.000001L); -} +} /* *************************************** * compare creals with given precision @@ -1599,7 +1599,7 @@ private bool feq(in creal r1, in creal r2) if ((cast(real)r1.re == cast(real)r2.re) && (cast(real)r1.im == cast(real)r2.im)) return 1; - + if (isnan(r1a)) return cast(bool)isnan(r2b); diff --git a/std/cover.d b/std/cover.d index 2c855ee48..f3a769996 100644 --- a/std/cover.d +++ b/std/cover.d @@ -24,12 +24,12 @@ /** * Code coverage analyzer. * Bugs: - * $(UL - * $(LI the execution counters are 32 bits in size, and can overflow) - * $(LI inline asm statements are not counted) - * ) + * $(UL + * $(LI the execution counters are 32 bits in size, and can overflow) + * $(LI inline asm statements are not counted) + * ) * Macros: - * WIKI = Phobos/StdCover + * WIKI = Phobos/StdCover */ module std.cover; @@ -42,9 +42,9 @@ private { struct Cover { - string filename; - BitArray valid; - uint[] data; + string filename; + BitArray valid; + uint[] data; } Cover[] gdata; @@ -74,9 +74,9 @@ void setDestDir(string pathname) /*********************************** * Set merge mode. * Params: - * flag = true means new data is summed with existing data in the - * listing file; false means a new listing file is always - * created. + * flag = true means new data is summed with existing data in the + * listing file; false means a new listing file is always + * created. */ void setMerge(bool flag) @@ -103,81 +103,81 @@ static ~this() foreach (Cover c; gdata) { - //printf("filename = '%.*s'\n", c.filename); + //printf("filename = '%.*s'\n", c.filename); - // Generate source file name - string srcfilename = std.path.join(srcpath, c.filename); + // Generate source file name + string srcfilename = std.path.join(srcpath, c.filename); - string buf = cast(string)std.file.read(srcfilename); - string[] lines = std.string.splitlines(buf); + string buf = cast(string)std.file.read(srcfilename); + string[] lines = std.string.splitlines(buf); - // Generate listing file name - string lstfilename = std.path.addExt(std.path.getBaseName(c.filename), "lst"); + // Generate listing file name + string lstfilename = std.path.addExt(std.path.getBaseName(c.filename), "lst"); - if (merge && exists(lstfilename) && isfile(lstfilename)) - { - string lst = cast(string)std.file.read(lstfilename); - string[] lstlines = std.string.splitlines(lst); + if (merge && exists(lstfilename) && isfile(lstfilename)) + { + string lst = cast(string)std.file.read(lstfilename); + string[] lstlines = std.string.splitlines(lst); - for (size_t i = 0; i < lstlines.length; i++) - { - if (i >= c.data.length) - break; - int count = 0; - foreach (char c2; lstlines[i]) - { - switch (c2) - { case ' ': - continue; - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - count = count * 10 + c2 - '0'; - continue; - default: - break; - } - break; - } - //printf("[%d] %d\n", i, count); - c.data[i] += count; - } - } + for (size_t i = 0; i < lstlines.length; i++) + { + if (i >= c.data.length) + break; + int count = 0; + foreach (char c2; lstlines[i]) + { + switch (c2) + { case ' ': + continue; + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + count = count * 10 + c2 - '0'; + continue; + default: + break; + } + break; + } + //printf("[%d] %d\n", i, count); + c.data[i] += count; + } + } - FILE *flst = std.c.stdio.fopen(lstfilename.ptr, "wb"); - if (!flst) - throw new std.file.FileException(lstfilename, "cannot open for write"); + FILE *flst = std.c.stdio.fopen(lstfilename.ptr, "wb"); + if (!flst) + throw new std.file.FileException(lstfilename, "cannot open for write"); - uint nno; - uint nyes; + uint nno; + uint nyes; - for (int i = 0; i < c.data.length; i++) - { - //printf("[%2d] = %u\n", i, c.data[i]); - if (i < lines.length) - { - uint n = c.data[i]; - string line = lines[i]; - line = std.string.expandtabs(line); - if (n == 0) - { - if (c.valid[i]) - { nno++; - fwritefln(flst, "0000000|%s", line); - } - else - fwritefln(flst, " |%s", line); - } - else - { nyes++; - fwritefln(flst, "%7s|%s", n, line); - } - } - } + for (int i = 0; i < c.data.length; i++) + { + //printf("[%2d] = %u\n", i, c.data[i]); + if (i < lines.length) + { + uint n = c.data[i]; + string line = lines[i]; + line = std.string.expandtabs(line); + if (n == 0) + { + if (c.valid[i]) + { nno++; + fwritefln(flst, "0000000|%s", line); + } + else + fwritefln(flst, " |%s", line); + } + else + { nyes++; + fwritefln(flst, "%7s|%s", n, line); + } + } + } - if (nyes + nno) // no divide by 0 bugs - fwritefln(flst, "%s is %s%% covered", c.filename, (nyes * 100) / (nyes + nno)); + if (nyes + nno) // no divide by 0 bugs + fwritefln(flst, "%s is %s%% covered", c.filename, (nyes * 100) / (nyes + nno)); - std.c.stdio.fclose(flst); + std.c.stdio.fclose(flst); } } diff --git a/std/cpuid.d b/std/cpuid.d index 38a32620e..274b02aa8 100644 --- a/std/cpuid.d +++ b/std/cpuid.d @@ -4,13 +4,13 @@ * Implemented according to: - AP-485 Intel(C) Processor Identification and the CPUID Instruction - $(LINK http://www.intel.com/design/xeon/applnots/241618.htm) + $(LINK http://www.intel.com/design/xeon/applnots/241618.htm) - Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 2A: Instruction Set Reference, A-M - $(LINK http://developer.intel.com/design/pentium4/manuals/index_new.htm) + $(LINK http://developer.intel.com/design/pentium4/manuals/index_new.htm) - AMD CPUID Specification Publication # 25481 - $(LINK http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25481.pdf) + $(LINK http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25481.pdf) Example: --- @@ -23,15 +23,15 @@ void main() } --- -AUTHORS: Tomas Lindquist Olsen <tomas@famolsen.dk> - (slightly altered by Walter Bright) -COPYRIGHT: Public Domain +AUTHORS: Tomas Lindquist Olsen <tomas@famolsen.dk> + (slightly altered by Walter Bright) +COPYRIGHT: Public Domain - * BUGS: Only works on x86 CPUs + * BUGS: Only works on x86 CPUs * * Macros: - * WIKI = Phobos/StdCpuid - * COPYRIGHT = Public Domain + * WIKI = Phobos/StdCpuid + * COPYRIGHT = Public Domain */ module std.cpuid; @@ -43,166 +43,166 @@ version(D_InlineAsm_X86) /// Returns everything as a printable string char[] toString() { - char[] feats; - if (mmx) feats ~= "MMX "; - if (fxsr) feats ~= "FXSR "; - if (sse) feats ~= "SSE "; - if (sse2) feats ~= "SSE2 "; - if (sse3) feats ~= "SSE3 "; - if (ssse3) feats ~= "SSSE3 "; - if (amd3dnow) feats ~= "3DNow! "; - if (amd3dnowExt) feats ~= "3DNow!+ "; - if (amdMmx) feats ~= "MMX+ "; - if (ia64) feats ~= "IA-64 "; - if (amd64) feats ~= "AMD64 "; - if (hyperThreading) feats ~= "HTT"; + char[] feats; + if (mmx) feats ~= "MMX "; + if (fxsr) feats ~= "FXSR "; + if (sse) feats ~= "SSE "; + if (sse2) feats ~= "SSE2 "; + if (sse3) feats ~= "SSE3 "; + if (ssse3) feats ~= "SSSE3 "; + if (amd3dnow) feats ~= "3DNow! "; + if (amd3dnowExt) feats ~= "3DNow!+ "; + if (amdMmx) feats ~= "MMX+ "; + if (ia64) feats ~= "IA-64 "; + if (amd64) feats ~= "AMD64 "; + if (hyperThreading) feats ~= "HTT"; - return format( - "Vendor string: %s\n", vendor, - "Processor string: %s\n", processor, - "Signature: Family=%d Model=%d Stepping=%d\n", family, model, stepping, - "Features: %s\n", feats, - "Multithreading: %d threads / %d cores\n", threadsPerCPU, coresPerCPU); + return format( + "Vendor string: %s\n", vendor, + "Processor string: %s\n", processor, + "Signature: Family=%d Model=%d Stepping=%d\n", family, model, stepping, + "Features: %s\n", feats, + "Multithreading: %d threads / %d cores\n", threadsPerCPU, coresPerCPU); } /// Returns vendor string - char[] vendor() {return vendorStr;} + char[] vendor() {return vendorStr;} /// Returns processor string - char[] processor() {return processorStr;} + char[] processor() {return processorStr;} /// Is MMX supported? - bool mmx() {return (flags&MMX_BIT)!=0;} + bool mmx() {return (flags&MMX_BIT)!=0;} /// Is FXSR supported? - bool fxsr() {return (flags&FXSR_BIT)!=0;} + bool fxsr() {return (flags&FXSR_BIT)!=0;} /// Is SSE supported? - bool sse() {return (flags&SSE_BIT)!=0;} + bool sse() {return (flags&SSE_BIT)!=0;} /// Is SSE2 supported? - bool sse2() {return (flags&SSE2_BIT)!=0;} + bool sse2() {return (flags&SSE2_BIT)!=0;} /// Is SSE3 supported? - bool sse3() {return (misc&SSE3_BIT)!=0;} + bool sse3() {return (misc&SSE3_BIT)!=0;} /// Is SSSE3 supported? - bool ssse3() {return (misc&SSSE3_BIT)!=0;} + bool ssse3() {return (misc&SSSE3_BIT)!=0;} /// Is AMD 3DNOW supported? - bool amd3dnow() {return (exflags&AMD_3DNOW_BIT)!=0;} + bool amd3dnow() {return (exflags&AMD_3DNOW_BIT)!=0;} /// Is AMD 3DNOW Ext supported? - bool amd3dnowExt() {return (exflags&AMD_3DNOW_EXT_BIT)!=0;} + bool amd3dnowExt() {return (exflags&AMD_3DNOW_EXT_BIT)!=0;} /// Is AMD MMX supported? - bool amdMmx() {return (exflags&AMD_MMX_BIT)!=0;} + bool amdMmx() {return (exflags&AMD_MMX_BIT)!=0;} /// Is this an Intel Architecture IA64? - bool ia64() {return (flags&IA64_BIT)!=0;} + bool ia64() {return (flags&IA64_BIT)!=0;} /// Is this an AMD 64? - bool amd64() {return (exflags&AMD64_BIT)!=0;} + bool amd64() {return (exflags&AMD64_BIT)!=0;} /// Is hyperthreading supported? - bool hyperThreading() {return (flags&HTT_BIT)!=0;} + bool hyperThreading() {return (flags&HTT_BIT)!=0;} /// Returns number of threads per CPU - uint threadsPerCPU() {return maxThreads;} + uint threadsPerCPU() {return maxThreads;} /// Returns number of cores in CPU - uint coresPerCPU() {return maxCores;} + uint coresPerCPU() {return maxCores;} /// Is this an Intel processor? - bool intel() {return manufac==INTEL;} + bool intel() {return manufac==INTEL;} /// Is this an AMD processor? - bool amd() {return manufac==AMD;} + bool amd() {return manufac==AMD;} /// Returns stepping - uint stepping() {return _stepping;} + uint stepping() {return _stepping;} /// Returns model - uint model() {return _model;} + uint model() {return _model;} /// Returns family - uint family() {return _family;} - //uint processorType() {return (signature>>>12)&0x3;} + uint family() {return _family;} + //uint processorType() {return (signature>>>12)&0x3;} static this() { - getVendorString(); - getProcessorString(); - getFeatureFlags(); + getVendorString(); + getProcessorString(); + getFeatureFlags(); - // stepping / family / model - _stepping = signature&0xF; - uint fbase = (signature>>>8)&0xF; - uint fex = (signature>>>20)&0xFF; - uint mbase = (signature>>>4)&0xF; - uint mex = (signature>>>16)&0xF; + // stepping / family / model + _stepping = signature&0xF; + uint fbase = (signature>>>8)&0xF; + uint fex = (signature>>>20)&0xFF; + uint mbase = (signature>>>4)&0xF; + uint mex = (signature>>>16)&0xF; - // vendor specific - void function() threadFn; - switch(vendorStr) - { - case "GenuineIntel": - manufac = INTEL; - threadFn = &getThreadingIntel; - if (fbase == 0xF) - _family = fbase+fex; - else - _family = fbase; - if (_family == 0x6 || _family == 0xF) - _model = mbase+(mex<<4); - else - _model = mbase; - break; + // vendor specific + void function() threadFn; + switch(vendorStr) + { + case "GenuineIntel": + manufac = INTEL; + threadFn = &getThreadingIntel; + if (fbase == 0xF) + _family = fbase+fex; + else + _family = fbase; + if (_family == 0x6 || _family == 0xF) + _model = mbase+(mex<<4); + else + _model = mbase; + break; - case "AuthenticAMD": - manufac = AMD; - threadFn = &getThreadingAMD; - if (fbase < 0xF) - { - _family = fbase; - _model = mbase; - } - else - { - _family = fbase+fex; - _model = mbase+(mex<<4); - } - break; + case "AuthenticAMD": + manufac = AMD; + threadFn = &getThreadingAMD; + if (fbase < 0xF) + { + _family = fbase; + _model = mbase; + } + else + { + _family = fbase+fex; + _model = mbase+(mex<<4); + } + break; - default: - manufac = OTHER; - } + default: + manufac = OTHER; + } - // threading details - if (hyperThreading && threadFn !is null) - { - threadFn(); - } + // threading details + if (hyperThreading && threadFn !is null) + { + threadFn(); + } } private: // feature flags enum : uint { - MMX_BIT = 1<<23, - FXSR_BIT = 1<<24, - SSE_BIT = 1<<25, - SSE2_BIT = 1<<26, - HTT_BIT = 1<<28, - IA64_BIT = 1<<30 + MMX_BIT = 1<<23, + FXSR_BIT = 1<<24, + SSE_BIT = 1<<25, + SSE2_BIT = 1<<26, + HTT_BIT = 1<<28, + IA64_BIT = 1<<30 } // feature flags misc enum : uint { - SSE3_BIT = 1, - SSSE3_BIT = 1<<9 + SSE3_BIT = 1, + SSSE3_BIT = 1<<9 } // extended feature flags enum : uint { - AMD_MMX_BIT = 1<<22, - AMD64_BIT = 1<<29, - AMD_3DNOW_EXT_BIT = 1<<30, - AMD_3DNOW_BIT = 1<<31 + AMD_MMX_BIT = 1<<22, + AMD64_BIT = 1<<29, + AMD_3DNOW_EXT_BIT = 1<<30, + AMD_3DNOW_BIT = 1<<31 } // manufacturer enum { - OTHER, - INTEL, - AMD + OTHER, + INTEL, + AMD } uint flags, misc, exflags, apic, signature; @@ -220,180 +220,180 @@ private: */ private void getVendorString() { - char* dst = vendorStr.ptr; - // puts the vendor string into dst - asm - { - mov EAX, 0 ; - cpuid ; - mov EAX, dst ; - mov [EAX], EBX ; - mov [EAX+4], EDX ; - mov [EAX+8], ECX ; - } + char* dst = vendorStr.ptr; + // puts the vendor string into dst + asm + { + mov EAX, 0 ; + cpuid ; + mov EAX, dst ; + mov [EAX], EBX ; + mov [EAX+4], EDX ; + mov [EAX+8], ECX ; + } } private void getProcessorString() { - char[48] buffer; - char* dst = buffer.ptr; - // puts the processor string into dst - asm - { - mov EAX, 0x8000_0000 ; - cpuid ; - cmp EAX, 0x8000_0004 ; - jb PSLabel ; // no support - push EDI ; - mov EDI, dst ; - mov EAX, 0x8000_0002 ; - cpuid ; - mov [EDI], EAX ; - mov [EDI+4], EBX ; - mov [EDI+8], ECX ; - mov [EDI+12], EDX ; - mov EAX, 0x8000_0003 ; - cpuid ; - mov [EDI+16], EAX ; - mov [EDI+20], EBX ; - mov [EDI+24], ECX ; - mov [EDI+28], EDX ; - mov EAX, 0x8000_0004 ; - cpuid ; - mov [EDI+32], EAX ; - mov [EDI+36], EBX ; - mov [EDI+40], ECX ; - mov [EDI+44], EDX ; - pop EDI ; - PSLabel: ; - } + char[48] buffer; + char* dst = buffer.ptr; + // puts the processor string into dst + asm + { + mov EAX, 0x8000_0000 ; + cpuid ; + cmp EAX, 0x8000_0004 ; + jb PSLabel ; // no support + push EDI ; + mov EDI, dst ; + mov EAX, 0x8000_0002 ; + cpuid ; + mov [EDI], EAX ; + mov [EDI+4], EBX ; + mov [EDI+8], ECX ; + mov [EDI+12], EDX ; + mov EAX, 0x8000_0003 ; + cpuid ; + mov [EDI+16], EAX ; + mov [EDI+20], EBX ; + mov [EDI+24], ECX ; + mov [EDI+28], EDX ; + mov EAX, 0x8000_0004 ; + cpuid ; + mov [EDI+32], EAX ; + mov [EDI+36], EBX ; + mov [EDI+40], ECX ; + mov [EDI+44], EDX ; + pop EDI ; + PSLabel: ; + } - if (buffer[0] == char.init) // no support - return; + if (buffer[0] == char.init) // no support + return; - // seems many intel processors prepend whitespace - processorStr = std.string.strip(std.string.toString(dst)).dup; + // seems many intel processors prepend whitespace + processorStr = std.string.strip(std.string.toString(dst)).dup; } private void getFeatureFlags() { - uint f,m,e,a,s; - asm - { - mov EAX, 0 ; - cpuid ; - cmp EAX, 1 ; - jb FeatLabel ; // no support - mov EAX, 1 ; - cpuid ; - mov f, EDX ; - mov m, ECX ; - mov a, EBX ; - mov s, EAX ; + uint f,m,e,a,s; + asm + { + mov EAX, 0 ; + cpuid ; + cmp EAX, 1 ; + jb FeatLabel ; // no support + mov EAX, 1 ; + cpuid ; + mov f, EDX ; + mov m, ECX ; + mov a, EBX ; + mov s, EAX ; - FeatLabel: ; - mov EAX, 0x8000_0000 ; - cpuid ; - cmp EAX, 0x8000_0001 ; - jb FeatLabel2 ; // no support - mov EAX, 0x8000_0001 ; - cpuid ; - mov e, EDX ; + FeatLabel: ; + mov EAX, 0x8000_0000 ; + cpuid ; + cmp EAX, 0x8000_0001 ; + jb FeatLabel2 ; // no support + mov EAX, 0x8000_0001 ; + cpuid ; + mov e, EDX ; - FeatLabel2: - ; - } - flags = f; - misc = m; - exflags = e; - apic = a; - signature = s; + FeatLabel2: + ; + } + flags = f; + misc = m; + exflags = e; + apic = a; + signature = s; } private void getThreadingIntel() { - uint n; - ubyte b = 0; - asm - { - mov EAX, 0 ; - cpuid ; - cmp EAX, 4 ; - jb IntelSingle ; - mov EAX, 4 ; - mov ECX, 0 ; - cpuid ; - mov n, EAX ; - mov b, 1 ; - IntelSingle: ; - } - if (b != 0) - { - maxCores = ((n>>>26)&0x3F)+1; - maxThreads = (apic>>>16)&0xFF; - } - else - { - maxCores = maxThreads = 1; - } + uint n; + ubyte b = 0; + asm + { + mov EAX, 0 ; + cpuid ; + cmp EAX, 4 ; + jb IntelSingle ; + mov EAX, 4 ; + mov ECX, 0 ; + cpuid ; + mov n, EAX ; + mov b, 1 ; + IntelSingle: ; + } + if (b != 0) + { + maxCores = ((n>>>26)&0x3F)+1; + maxThreads = (apic>>>16)&0xFF; + } + else + { + maxCores = maxThreads = 1; + } } private void getThreadingAMD() { - ubyte n; - ubyte b = 0; - asm - { - mov EAX, 0x8000_0000 ; - cpuid ; - cmp EAX, 0x8000_0008 ; - jb AMDSingle ; - mov EAX, 0x8000_0008 ; - cpuid ; - mov n, CL ; - mov b, 1 ; - AMDSingle: ; - } - if (b != 0) - { - maxCores = n+1; - maxThreads = (apic>>>16)&0xFF; - } - else - { - maxCores = maxThreads = 1; - } + ubyte n; + ubyte b = 0; + asm + { + mov EAX, 0x8000_0000 ; + cpuid ; + cmp EAX, 0x8000_0008 ; + jb AMDSingle ; + mov EAX, 0x8000_0008 ; + cpuid ; + mov n, CL ; + mov b, 1 ; + AMDSingle: ; + } + if (b != 0) + { + maxCores = n+1; + maxThreads = (apic>>>16)&0xFF; + } + else + { + maxCores = maxThreads = 1; + } } } else { char[] toString() { return "unknown CPU\n"; } - char[] vendor() {return "unknown vendor"; } - char[] processor() {return "unknown processor"; } + char[] vendor() {return "unknown vendor"; } + char[] processor() {return "unknown processor"; } - bool mmx() {return false; } - bool fxsr() {return false; } - bool sse() {return false; } - bool sse2() {return false; } - bool sse3() {return false; } - bool ssse3() {return false; } + bool mmx() {return false; } + bool fxsr() {return false; } + bool sse() {return false; } + bool sse2() {return false; } + bool sse3() {return false; } + bool ssse3() {return false; } - bool amd3dnow() {return false; } - bool amd3dnowExt() {return false; } - bool amdMmx() {return false; } + bool amd3dnow() {return false; } + bool amd3dnowExt() {return false; } + bool amdMmx() {return false; } - bool ia64() {return false; } - bool amd64() {return false; } + bool ia64() {return false; } + bool amd64() {return false; } - bool hyperThreading() {return false; } - uint threadsPerCPU() {return 0; } - uint coresPerCPU() {return 0; } + bool hyperThreading() {return false; } + uint threadsPerCPU() {return 0; } + uint coresPerCPU() {return 0; } - bool intel() {return false; } - bool amd() {return false; } + bool intel() {return false; } + bool amd() {return false; } - uint stepping() {return 0; } - uint model() {return 0; } - uint family() {return 0; } + uint stepping() {return 0; } + uint model() {return 0; } + uint family() {return 0; } } diff --git a/std/cstream.d b/std/cstream.d index 2118d470f..4662711e9 100644 --- a/std/cstream.d +++ b/std/cstream.d @@ -6,7 +6,7 @@ * Authors: Ben Hinkle * License: Public Domain * Macros: - * WIKI=Phobos/StdCstream + * WIKI=Phobos/StdCstream */ module std.cstream; @@ -50,7 +50,7 @@ class CFile : Stream { * Ditto */ void file(FILE* cfile) { - this.cfile = cfile; + this.cfile = cfile; isopen = true; } @@ -63,31 +63,31 @@ class CFile : Stream { /** * Ditto */ - override void close() { + override void close() { if (isopen) - fclose(cfile); - isopen = readable = writeable = seekable = false; + fclose(cfile); + isopen = readable = writeable = seekable = false; } /** * Ditto */ - override bool eof() { - return cast(bool)(readEOF || feof(cfile)); + override bool eof() { + return cast(bool)(readEOF || feof(cfile)); } /** * Ditto */ - override char getc() { - return cast(char)fgetc(cfile); + override char getc() { + return cast(char)fgetc(cfile); } /** * Ditto */ - override char ungetc(char c) { - return cast(char)std.c.stdio.ungetc(c,cfile); + override char ungetc(char c) { + return cast(char)std.c.stdio.ungetc(c,cfile); } /** diff --git a/std/ctype.d b/std/ctype.d index 6335e950f..2c3ec9007 100644 --- a/std/ctype.d +++ b/std/ctype.d @@ -8,10 +8,10 @@ * Simple ASCII character classification functions. * For Unicode classification, see $(LINK2 std_uni.html, std.uni). * References: - * $(LINK2 http://www.digitalmars.com/d/ascii-table.html, ASCII Table), - * $(LINK2 http://en.wikipedia.org/wiki/Ascii, Wikipedia) + * $(LINK2 http://www.digitalmars.com/d/ascii-table.html, ASCII Table), + * $(LINK2 http://en.wikipedia.org/wiki/Ascii, Wikipedia) * Macros: - * WIKI=Phobos/StdCtype + * WIKI=Phobos/StdCtype */ module std.ctype; @@ -85,11 +85,11 @@ int isascii(dchar c) { return c <= 0x7F; } dchar tolower(dchar c) out (result) { - assert(!isupper(result)); + assert(!isupper(result)); } body { - return isupper(c) ? c + (cast(dchar)'a' - 'A') : c; + return isupper(c) ? c + (cast(dchar)'a' - 'A') : c; } @@ -100,47 +100,47 @@ dchar tolower(dchar c) dchar toupper(dchar c) out (result) { - assert(!islower(result)); + assert(!islower(result)); } body { - return islower(c) ? c - (cast(dchar)'a' - 'A') : c; + return islower(c) ? c - (cast(dchar)'a' - 'A') : c; } private: enum { - _SPC = 8, - _CTL = 0x20, - _BLK = 0x40, - _HEX = 0x80, - _UC = 1, - _LC = 2, - _PNC = 0x10, - _DIG = 4, - _ALP = _UC|_LC, + _SPC = 8, + _CTL = 0x20, + _BLK = 0x40, + _HEX = 0x80, + _UC = 1, + _LC = 2, + _PNC = 0x10, + _DIG = 4, + _ALP = _UC|_LC, } ubyte _ctype[128] = [ - _CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL, - _CTL,_CTL|_SPC,_CTL|_SPC,_CTL|_SPC,_CTL|_SPC,_CTL|_SPC,_CTL,_CTL, - _CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL, - _CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL, - _SPC|_BLK,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC, - _PNC,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC, - _DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX, - _DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX, - _PNC,_PNC,_PNC,_PNC,_PNC,_PNC, - _PNC,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC, - _UC,_UC,_UC,_UC,_UC,_UC,_UC,_UC, - _UC,_UC,_UC,_UC,_UC,_UC,_UC,_UC, - _UC,_UC,_UC,_PNC,_PNC,_PNC,_PNC,_PNC, - _PNC,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC, - _LC,_LC,_LC,_LC,_LC,_LC,_LC,_LC, - _LC,_LC,_LC,_LC,_LC,_LC,_LC,_LC, - _LC,_LC,_LC,_PNC,_PNC,_PNC,_PNC,_CTL + _CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL, + _CTL,_CTL|_SPC,_CTL|_SPC,_CTL|_SPC,_CTL|_SPC,_CTL|_SPC,_CTL,_CTL, + _CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL, + _CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL,_CTL, + _SPC|_BLK,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC, + _PNC,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC,_PNC, + _DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX, + _DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX,_DIG|_HEX, + _PNC,_PNC,_PNC,_PNC,_PNC,_PNC, + _PNC,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC|_HEX,_UC, + _UC,_UC,_UC,_UC,_UC,_UC,_UC,_UC, + _UC,_UC,_UC,_UC,_UC,_UC,_UC,_UC, + _UC,_UC,_UC,_PNC,_PNC,_PNC,_PNC,_PNC, + _PNC,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC|_HEX,_LC, + _LC,_LC,_LC,_LC,_LC,_LC,_LC,_LC, + _LC,_LC,_LC,_LC,_LC,_LC,_LC,_LC, + _LC,_LC,_LC,_PNC,_PNC,_PNC,_PNC,_CTL ]; diff --git a/std/dateparse.d b/std/dateparse.d index 1706ff5d2..18c8bc7bb 100644 --- a/std/dateparse.d +++ b/std/dateparse.d @@ -37,7 +37,7 @@ class DateParseError : Error { this(char[] s) { - super("Invalid date string: " ~ s); + super("Invalid date string: " ~ s); } } @@ -45,90 +45,90 @@ struct DateParse { void parse(char[] s, out Date date) { - *this = DateParse.init; + *this = DateParse.init; - //version (Win32) - buffer = (cast(char *)alloca(s.length))[0 .. s.length]; - //else - //buffer = new char[s.length]; + //version (Win32) + buffer = (cast(char *)alloca(s.length))[0 .. s.length]; + //else + //buffer = new char[s.length]; - debug(dateparse) printf("DateParse.parse('%.*s')\n", s); - if (!parseString(s)) - { - goto Lerror; - } + debug(dateparse) printf("DateParse.parse('%.*s')\n", s); + if (!parseString(s)) + { + goto Lerror; + } /+ - if (year == year.init) - year = 0; - else + if (year == year.init) + year = 0; + else +/ - debug(dateparse) - printf("year = %d, month = %d, day = %d\n%02d:%02d:%02d.%03d\nweekday = %d, tzcorrection = %d\n", - year, month, day, - hours, minutes, seconds, ms, - weekday, tzcorrection); - if ( - year == year.init || - (month < 1 || month > 12) || - (day < 1 || day > 31) || - (hours < 0 || hours > 23) || - (minutes < 0 || minutes > 59) || - (seconds < 0 || seconds > 59) || - (tzcorrection != int.min && - ((tzcorrection < -2300 || tzcorrection > 2300) || - (tzcorrection % 10))) - ) - { - Lerror: - throw new DateParseError(s); - } + debug(dateparse) + printf("year = %d, month = %d, day = %d\n%02d:%02d:%02d.%03d\nweekday = %d, tzcorrection = %d\n", + year, month, day, + hours, minutes, seconds, ms, + weekday, tzcorrection); + if ( + year == year.init || + (month < 1 || month > 12) || + (day < 1 || day > 31) || + (hours < 0 || hours > 23) || + (minutes < 0 || minutes > 59) || + (seconds < 0 || seconds > 59) || + (tzcorrection != int.min && + ((tzcorrection < -2300 || tzcorrection > 2300) || + (tzcorrection % 10))) + ) + { + Lerror: + throw new DateParseError(s); + } - if (ampm) - { if (hours > 12) - goto Lerror; - if (hours < 12) - { - if (ampm == 2) // if P.M. - hours += 12; - } - else if (ampm == 1) // if 12am - { - hours = 0; // which is midnight - } - } + if (ampm) + { if (hours > 12) + goto Lerror; + if (hours < 12) + { + if (ampm == 2) // if P.M. + hours += 12; + } + else if (ampm == 1) // if 12am + { + hours = 0; // which is midnight + } + } -// if (tzcorrection != tzcorrection.init) -// tzcorrection /= 100; +// if (tzcorrection != tzcorrection.init) +// tzcorrection /= 100; - if (year >= 0 && year <= 99) - year += 1900; + if (year >= 0 && year <= 99) + year += 1900; - date.year = year; - date.month = month; - date.day = day; - date.hour = hours; - date.minute = minutes; - date.second = seconds; - date.ms = ms; - date.weekday = weekday; - date.tzcorrection = tzcorrection; + date.year = year; + date.month = month; + date.day = day; + date.hour = hours; + date.minute = minutes; + date.second = seconds; + date.ms = ms; + date.weekday = weekday; + date.tzcorrection = tzcorrection; } private: - int year = int.min; // our "nan" Date value - int month; // 1..12 - int day; // 1..31 - int hours; // 0..23 - int minutes; // 0..59 - int seconds; // 0..59 - int ms; // 0..999 - int weekday; // 1..7 - int ampm; // 0: not specified - // 1: AM - // 2: PM - int tzcorrection = int.min; // -1200..1200 correction in hours + int year = int.min; // our "nan" Date value + int month; // 1..12 + int day; // 1..31 + int hours; // 0..23 + int minutes; // 0..59 + int seconds; // 0..59 + int ms; // 0..999 + int weekday; // 1..7 + int ampm; // 0: not specified + // 1: AM + // 2: PM + int tzcorrection = int.min; // -1200..1200 correction in hours char[] s; int si; @@ -137,540 +137,540 @@ private: enum DP : byte { - err, - weekday, - month, - number, - end, - colon, - minus, - slash, - ampm, - plus, - tz, - dst, - dsttz, + err, + weekday, + month, + number, + end, + colon, + minus, + slash, + ampm, + plus, + tz, + dst, + dsttz, } DP nextToken() { int nest; - uint c; - int bi; - DP result = DP.err; + uint c; + int bi; + DP result = DP.err; - //printf("DateParse::nextToken()\n"); - for (;;) - { - assert(si <= s.length); - if (si == s.length) - { result = DP.end; - goto Lret; - } - //printf("\ts[%d] = '%c'\n", si, s[si]); - switch (s[si]) - { - case ':': result = DP.colon; goto ret_inc; - case '+': result = DP.plus; goto ret_inc; - case '-': result = DP.minus; goto ret_inc; - case '/': result = DP.slash; goto ret_inc; - case '.': - version(DATE_DOT_DELIM) - { - result = DP.slash; - goto ret_inc; - } - else - { - si++; - break; - } + //printf("DateParse::nextToken()\n"); + for (;;) + { + assert(si <= s.length); + if (si == s.length) + { result = DP.end; + goto Lret; + } + //printf("\ts[%d] = '%c'\n", si, s[si]); + switch (s[si]) + { + case ':': result = DP.colon; goto ret_inc; + case '+': result = DP.plus; goto ret_inc; + case '-': result = DP.minus; goto ret_inc; + case '/': result = DP.slash; goto ret_inc; + case '.': + version(DATE_DOT_DELIM) + { + result = DP.slash; + goto ret_inc; + } + else + { + si++; + break; + } - ret_inc: - si++; - goto Lret; + ret_inc: + si++; + goto Lret; - case ' ': - case '\n': - case '\r': - case '\t': - case ',': - si++; - break; + case ' ': + case '\n': + case '\r': + case '\t': + case ',': + si++; + break; - case '(': // comment - nest = 1; - for (;;) - { - si++; - if (si == s.length) - goto Lret; // error - switch (s[si]) - { - case '(': - nest++; - break; + case '(': // comment + nest = 1; + for (;;) + { + si++; + if (si == s.length) + goto Lret; // error + switch (s[si]) + { + case '(': + nest++; + break; - case ')': - if (--nest == 0) - goto Lendofcomment; - break; + case ')': + if (--nest == 0) + goto Lendofcomment; + break; - default: - break; - } - } - Lendofcomment: - si++; - break; + default: + break; + } + } + Lendofcomment: + si++; + break; - default: - number = 0; - for (;;) - { - if (si == s.length) - // c cannot be undefined here - break; - c = s[si]; - if (!(c >= '0' && c <= '9')) - break; - result = DP.number; - number = number * 10 + (c - '0'); - si++; - } - if (result == DP.number) - goto Lret; + default: + number = 0; + for (;;) + { + if (si == s.length) + // c cannot be undefined here + break; + c = s[si]; + if (!(c >= '0' && c <= '9')) + break; + result = DP.number; + number = number * 10 + (c - '0'); + si++; + } + if (result == DP.number) + goto Lret; - bi = 0; - bufloop: - while (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') - { - if (c < 'a') // if upper case - c += cast(uint)'a' - cast(uint)'A'; // to lower case - buffer[bi] = cast(char)c; - bi++; - do - { - si++; - if (si == s.length) - break bufloop; - c = s[si]; - } while (c == '.'); // ignore embedded '.'s - } - result = classify(buffer[0 .. bi]); - goto Lret; - } - } + bi = 0; + bufloop: + while (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') + { + if (c < 'a') // if upper case + c += cast(uint)'a' - cast(uint)'A'; // to lower case + buffer[bi] = cast(char)c; + bi++; + do + { + si++; + if (si == s.length) + break bufloop; + c = s[si]; + } while (c == '.'); // ignore embedded '.'s + } + result = classify(buffer[0 .. bi]); + goto Lret; + } + } Lret: - //printf("-DateParse::nextToken()\n"); - return result; + //printf("-DateParse::nextToken()\n"); + return result; } DP classify(char[] buf) { - struct DateID - { - char[] name; - DP tok; - short value; - } + struct DateID + { + char[] name; + DP tok; + short value; + } - static DateID dateidtab[] = - [ - { "january", DP.month, 1}, - { "february", DP.month, 2}, - { "march", DP.month, 3}, - { "april", DP.month, 4}, - { "may", DP.month, 5}, - { "june", DP.month, 6}, - { "july", DP.month, 7}, - { "august", DP.month, 8}, - { "september", DP.month, 9}, - { "october", DP.month, 10}, - { "november", DP.month, 11}, - { "december", DP.month, 12}, - { "jan", DP.month, 1}, - { "feb", DP.month, 2}, - { "mar", DP.month, 3}, - { "apr", DP.month, 4}, - { "jun", DP.month, 6}, - { "jul", DP.month, 7}, - { "aug", DP.month, 8}, - { "sep", DP.month, 9}, - { "sept", DP.month, 9}, - { "oct", DP.month, 10}, - { "nov", DP.month, 11}, - { "dec", DP.month, 12}, + static DateID dateidtab[] = + [ + { "january", DP.month, 1}, + { "february", DP.month, 2}, + { "march", DP.month, 3}, + { "april", DP.month, 4}, + { "may", DP.month, 5}, + { "june", DP.month, 6}, + { "july", DP.month, 7}, + { "august", DP.month, 8}, + { "september", DP.month, 9}, + { "october", DP.month, 10}, + { "november", DP.month, 11}, + { "december", DP.month, 12}, + { "jan", DP.month, 1}, + { "feb", DP.month, 2}, + { "mar", DP.month, 3}, + { "apr", DP.month, 4}, + { "jun", DP.month, 6}, + { "jul", DP.month, 7}, + { "aug", DP.month, 8}, + { "sep", DP.month, 9}, + { "sept", DP.month, 9}, + { "oct", DP.month, 10}, + { "nov", DP.month, 11}, + { "dec", DP.month, 12}, - { "sunday", DP.weekday, 1}, - { "monday", DP.weekday, 2}, - { "tuesday", DP.weekday, 3}, - { "tues", DP.weekday, 3}, - { "wednesday", DP.weekday, 4}, - { "wednes", DP.weekday, 4}, - { "thursday", DP.weekday, 5}, - { "thur", DP.weekday, 5}, - { "thurs", DP.weekday, 5}, - { "friday", DP.weekday, 6}, - { "saturday", DP.weekday, 7}, + { "sunday", DP.weekday, 1}, + { "monday", DP.weekday, 2}, + { "tuesday", DP.weekday, 3}, + { "tues", DP.weekday, 3}, + { "wednesday", DP.weekday, 4}, + { "wednes", DP.weekday, 4}, + { "thursday", DP.weekday, 5}, + { "thur", DP.weekday, 5}, + { "thurs", DP.weekday, 5}, + { "friday", DP.weekday, 6}, + { "saturday", DP.weekday, 7}, - { "sun", DP.weekday, 1}, - { "mon", DP.weekday, 2}, - { "tue", DP.weekday, 3}, - { "wed", DP.weekday, 4}, - { "thu", DP.weekday, 5}, - { "fri", DP.weekday, 6}, - { "sat", DP.weekday, 7}, + { "sun", DP.weekday, 1}, + { "mon", DP.weekday, 2}, + { "tue", DP.weekday, 3}, + { "wed", DP.weekday, 4}, + { "thu", DP.weekday, 5}, + { "fri", DP.weekday, 6}, + { "sat", DP.weekday, 7}, - { "am", DP.ampm, 1}, - { "pm", DP.ampm, 2}, + { "am", DP.ampm, 1}, + { "pm", DP.ampm, 2}, - { "gmt", DP.tz, +000}, - { "ut", DP.tz, +000}, - { "utc", DP.tz, +000}, - { "wet", DP.tz, +000}, - { "z", DP.tz, +000}, - { "wat", DP.tz, +100}, - { "a", DP.tz, +100}, - { "at", DP.tz, +200}, - { "b", DP.tz, +200}, - { "c", DP.tz, +300}, - { "ast", DP.tz, +400}, - { "d", DP.tz, +400}, - { "est", DP.tz, +500}, - { "e", DP.tz, +500}, - { "cst", DP.tz, +600}, - { "f", DP.tz, +600}, - { "mst", DP.tz, +700}, - { "g", DP.tz, +700}, - { "pst", DP.tz, +800}, - { "h", DP.tz, +800}, - { "yst", DP.tz, +900}, - { "i", DP.tz, +900}, - { "ahst", DP.tz, +1000}, - { "cat", DP.tz, +1000}, - { "hst", DP.tz, +1000}, - { "k", DP.tz, +1000}, - { "nt", DP.tz, +1100}, - { "l", DP.tz, +1100}, - { "idlw", DP.tz, +1200}, - { "m", DP.tz, +1200}, + { "gmt", DP.tz, +000}, + { "ut", DP.tz, +000}, + { "utc", DP.tz, +000}, + { "wet", DP.tz, +000}, + { "z", DP.tz, +000}, + { "wat", DP.tz, +100}, + { "a", DP.tz, +100}, + { "at", DP.tz, +200}, + { "b", DP.tz, +200}, + { "c", DP.tz, +300}, + { "ast", DP.tz, +400}, + { "d", DP.tz, +400}, + { "est", DP.tz, +500}, + { "e", DP.tz, +500}, + { "cst", DP.tz, +600}, + { "f", DP.tz, +600}, + { "mst", DP.tz, +700}, + { "g", DP.tz, +700}, + { "pst", DP.tz, +800}, + { "h", DP.tz, +800}, + { "yst", DP.tz, +900}, + { "i", DP.tz, +900}, + { "ahst", DP.tz, +1000}, + { "cat", DP.tz, +1000}, + { "hst", DP.tz, +1000}, + { "k", DP.tz, +1000}, + { "nt", DP.tz, +1100}, + { "l", DP.tz, +1100}, + { "idlw", DP.tz, +1200}, + { "m", DP.tz, +1200}, - { "cet", DP.tz, -100}, - { "fwt", DP.tz, -100}, - { "met", DP.tz, -100}, - { "mewt", DP.tz, -100}, - { "swt", DP.tz, -100}, - { "n", DP.tz, -100}, - { "eet", DP.tz, -200}, - { "o", DP.tz, -200}, - { "bt", DP.tz, -300}, - { "p", DP.tz, -300}, - { "zp4", DP.tz, -400}, - { "q", DP.tz, -400}, - { "zp5", DP.tz, -500}, - { "r", DP.tz, -500}, - { "zp6", DP.tz, -600}, - { "s", DP.tz, -600}, - { "wast", DP.tz, -700}, - { "t", DP.tz, -700}, - { "cct", DP.tz, -800}, - { "u", DP.tz, -800}, - { "jst", DP.tz, -900}, - { "v", DP.tz, -900}, - { "east", DP.tz, -1000}, - { "gst", DP.tz, -1000}, - { "w", DP.tz, -1000}, - { "x", DP.tz, -1100}, - { "idle", DP.tz, -1200}, - { "nzst", DP.tz, -1200}, - { "nzt", DP.tz, -1200}, - { "y", DP.tz, -1200}, + { "cet", DP.tz, -100}, + { "fwt", DP.tz, -100}, + { "met", DP.tz, -100}, + { "mewt", DP.tz, -100}, + { "swt", DP.tz, -100}, + { "n", DP.tz, -100}, + { "eet", DP.tz, -200}, + { "o", DP.tz, -200}, + { "bt", DP.tz, -300}, + { "p", DP.tz, -300}, + { "zp4", DP.tz, -400}, + { "q", DP.tz, -400}, + { "zp5", DP.tz, -500}, + { "r", DP.tz, -500}, + { "zp6", DP.tz, -600}, + { "s", DP.tz, -600}, + { "wast", DP.tz, -700}, + { "t", DP.tz, -700}, + { "cct", DP.tz, -800}, + { "u", DP.tz, -800}, + { "jst", DP.tz, -900}, + { "v", DP.tz, -900}, + { "east", DP.tz, -1000}, + { "gst", DP.tz, -1000}, + { "w", DP.tz, -1000}, + { "x", DP.tz, -1100}, + { "idle", DP.tz, -1200}, + { "nzst", DP.tz, -1200}, + { "nzt", DP.tz, -1200}, + { "y", DP.tz, -1200}, - { "bst", DP.dsttz, 000}, - { "adt", DP.dsttz, +400}, - { "edt", DP.dsttz, +500}, - { "cdt", DP.dsttz, +600}, - { "mdt", DP.dsttz, +700}, - { "pdt", DP.dsttz, +800}, - { "ydt", DP.dsttz, +900}, - { "hdt", DP.dsttz, +1000}, - { "mest", DP.dsttz, -100}, - { "mesz", DP.dsttz, -100}, - { "sst", DP.dsttz, -100}, - { "fst", DP.dsttz, -100}, - { "wadt", DP.dsttz, -700}, - { "eadt", DP.dsttz, -1000}, - { "nzdt", DP.dsttz, -1200}, + { "bst", DP.dsttz, 000}, + { "adt", DP.dsttz, +400}, + { "edt", DP.dsttz, +500}, + { "cdt", DP.dsttz, +600}, + { "mdt", DP.dsttz, +700}, + { "pdt", DP.dsttz, +800}, + { "ydt", DP.dsttz, +900}, + { "hdt", DP.dsttz, +1000}, + { "mest", DP.dsttz, -100}, + { "mesz", DP.dsttz, -100}, + { "sst", DP.dsttz, -100}, + { "fst", DP.dsttz, -100}, + { "wadt", DP.dsttz, -700}, + { "eadt", DP.dsttz, -1000}, + { "nzdt", DP.dsttz, -1200}, - { "dst", DP.dst, 0}, - ]; + { "dst", DP.dst, 0}, + ]; - //message(DTEXT("DateParse::classify('%s')\n"), buf); + //message(DTEXT("DateParse::classify('%s')\n"), buf); - // Do a linear search. Yes, it would be faster with a binary - // one. - for (uint i = 0; i < dateidtab.length; i++) - { - if (std.string.cmp(dateidtab[i].name, buf) == 0) - { - number = dateidtab[i].value; - return dateidtab[i].tok; - } - } - return DP.err; + // Do a linear search. Yes, it would be faster with a binary + // one. + for (uint i = 0; i < dateidtab.length; i++) + { + if (std.string.cmp(dateidtab[i].name, buf) == 0) + { + number = dateidtab[i].value; + return dateidtab[i].tok; + } + } + return DP.err; } int parseString(char[] s) { - int n1; - int dp; - int sisave; - int result; + int n1; + int dp; + int sisave; + int result; - //message(DTEXT("DateParse::parseString('%ls')\n"), s); - this.s = s; - si = 0; - dp = nextToken(); - for (;;) - { - //message(DTEXT("\tdp = %d\n"), dp); - switch (dp) - { - case DP.end: - result = 1; - Lret: - return result; + //message(DTEXT("DateParse::parseString('%ls')\n"), s); + this.s = s; + si = 0; + dp = nextToken(); + for (;;) + { + //message(DTEXT("\tdp = %d\n"), dp); + switch (dp) + { + case DP.end: + result = 1; + Lret: + return result; - case DP.err: - case_error: - //message(DTEXT("\terror\n")); - default: - result = 0; - goto Lret; + case DP.err: + case_error: + //message(DTEXT("\terror\n")); + default: + result = 0; + goto Lret; - case DP.minus: - break; // ignore spurious '-' + case DP.minus: + break; // ignore spurious '-' - case DP.weekday: - weekday = number; - break; + case DP.weekday: + weekday = number; + break; - case DP.month: // month day, [year] - month = number; - dp = nextToken(); - if (dp == DP.number) - { - day = number; - sisave = si; - dp = nextToken(); - if (dp == DP.number) - { - n1 = number; - dp = nextToken(); - if (dp == DP.colon) - { // back up, not a year - si = sisave; - } - else - { year = n1; - continue; - } - break; - } - } - continue; + case DP.month: // month day, [year] + month = number; + dp = nextToken(); + if (dp == DP.number) + { + day = number; + sisave = si; + dp = nextToken(); + if (dp == DP.number) + { + n1 = number; + dp = nextToken(); + if (dp == DP.colon) + { // back up, not a year + si = sisave; + } + else + { year = n1; + continue; + } + break; + } + } + continue; - case DP.number: - n1 = number; - dp = nextToken(); - switch (dp) - { - case DP.end: - year = n1; - break; + case DP.number: + n1 = number; + dp = nextToken(); + switch (dp) + { + case DP.end: + year = n1; + break; - case DP.minus: - case DP.slash: // n1/ ? ? ? - dp = parseCalendarDate(n1); - if (dp == DP.err) - goto case_error; - break; + case DP.minus: + case DP.slash: // n1/ ? ? ? + dp = parseCalendarDate(n1); + if (dp == DP.err) + goto case_error; + break; - case DP.colon: // hh:mm [:ss] [am | pm] - dp = parseTimeOfDay(n1); - if (dp == DP.err) - goto case_error; - break; + case DP.colon: // hh:mm [:ss] [am | pm] + dp = parseTimeOfDay(n1); + if (dp == DP.err) + goto case_error; + break; - case DP.ampm: - hours = n1; - minutes = 0; - seconds = 0; - ampm = number; - break; + case DP.ampm: + hours = n1; + minutes = 0; + seconds = 0; + ampm = number; + break; - case DP.month: - day = n1; - month = number; - dp = nextToken(); - if (dp == DP.number) - { // day month year - year = number; - dp = nextToken(); - } - break; + case DP.month: + day = n1; + month = number; + dp = nextToken(); + if (dp == DP.number) + { // day month year + year = number; + dp = nextToken(); + } + break; - default: - year = n1; - break; - } - continue; - } - dp = nextToken(); - } - assert(0); + default: + year = n1; + break; + } + continue; + } + dp = nextToken(); + } + assert(0); } int parseCalendarDate(int n1) { - int n2; - int n3; - int dp; + int n2; + int n3; + int dp; - debug(dateparse) printf("DateParse.parseCalendarDate(%d)\n", n1); - dp = nextToken(); - if (dp == DP.month) // day/month - { - day = n1; - month = number; - dp = nextToken(); - if (dp == DP.number) - { // day/month year - year = number; - dp = nextToken(); - } - else if (dp == DP.minus || dp == DP.slash) - { // day/month/year - dp = nextToken(); - if (dp != DP.number) - goto case_error; - year = number; - dp = nextToken(); - } - return dp; - } - if (dp != DP.number) - goto case_error; - n2 = number; - //message(DTEXT("\tn2 = %d\n"), n2); - dp = nextToken(); - if (dp == DP.minus || dp == DP.slash) - { - dp = nextToken(); - if (dp != DP.number) - goto case_error; - n3 = number; - //message(DTEXT("\tn3 = %d\n"), n3); - dp = nextToken(); + debug(dateparse) printf("DateParse.parseCalendarDate(%d)\n", n1); + dp = nextToken(); + if (dp == DP.month) // day/month + { + day = n1; + month = number; + dp = nextToken(); + if (dp == DP.number) + { // day/month year + year = number; + dp = nextToken(); + } + else if (dp == DP.minus || dp == DP.slash) + { // day/month/year + dp = nextToken(); + if (dp != DP.number) + goto case_error; + year = number; + dp = nextToken(); + } + return dp; + } + if (dp != DP.number) + goto case_error; + n2 = number; + //message(DTEXT("\tn2 = %d\n"), n2); + dp = nextToken(); + if (dp == DP.minus || dp == DP.slash) + { + dp = nextToken(); + if (dp != DP.number) + goto case_error; + n3 = number; + //message(DTEXT("\tn3 = %d\n"), n3); + dp = nextToken(); - // case1: year/month/day - // case2: month/day/year - int case1, case2; + // case1: year/month/day + // case2: month/day/year + int case1, case2; - case1 = (n1 > 12 || - (n2 >= 1 && n2 <= 12) && - (n3 >= 1 && n3 <= 31)); - case2 = ((n1 >= 1 && n1 <= 12) && - (n2 >= 1 && n2 <= 31) || - n3 > 31); - if (case1 == case2) - goto case_error; - if (case1) - { - year = n1; - month = n2; - day = n3; - } - else - { - month = n1; - day = n2; - year = n3; - } - } - else - { // must be month/day - month = n1; - day = n2; - } - return dp; + case1 = (n1 > 12 || + (n2 >= 1 && n2 <= 12) && + (n3 >= 1 && n3 <= 31)); + case2 = ((n1 >= 1 && n1 <= 12) && + (n2 >= 1 && n2 <= 31) || + n3 > 31); + if (case1 == case2) + goto case_error; + if (case1) + { + year = n1; + month = n2; + day = n3; + } + else + { + month = n1; + day = n2; + year = n3; + } + } + else + { // must be month/day + month = n1; + day = n2; + } + return dp; case_error: - return DP.err; + return DP.err; } int parseTimeOfDay(int n1) { - int dp; - int sign; + int dp; + int sign; - // 12am is midnight - // 12pm is noon + // 12am is midnight + // 12pm is noon - //message(DTEXT("DateParse::parseTimeOfDay(%d)\n"), n1); - hours = n1; - dp = nextToken(); - if (dp != DP.number) - goto case_error; - minutes = number; - dp = nextToken(); - if (dp == DP.colon) - { - dp = nextToken(); - if (dp != DP.number) - goto case_error; - seconds = number; - dp = nextToken(); - } - else - seconds = 0; + //message(DTEXT("DateParse::parseTimeOfDay(%d)\n"), n1); + hours = n1; + dp = nextToken(); + if (dp != DP.number) + goto case_error; + minutes = number; + dp = nextToken(); + if (dp == DP.colon) + { + dp = nextToken(); + if (dp != DP.number) + goto case_error; + seconds = number; + dp = nextToken(); + } + else + seconds = 0; - if (dp == DP.ampm) - { - ampm = number; - dp = nextToken(); - } - else if (dp == DP.plus || dp == DP.minus) - { - Loffset: - sign = (dp == DP.minus) ? -1 : 1; - dp = nextToken(); - if (dp != DP.number) - goto case_error; - tzcorrection = -sign * number; - dp = nextToken(); - } - else if (dp == DP.tz) - { - tzcorrection = number; - dp = nextToken(); - if (number == 0 && (dp == DP.plus || dp == DP.minus)) - goto Loffset; - if (dp == DP.dst) - { tzcorrection += 100; - dp = nextToken(); - } - } - else if (dp == DP.dsttz) - { - tzcorrection = number; - dp = nextToken(); - } + if (dp == DP.ampm) + { + ampm = number; + dp = nextToken(); + } + else if (dp == DP.plus || dp == DP.minus) + { + Loffset: + sign = (dp == DP.minus) ? -1 : 1; + dp = nextToken(); + if (dp != DP.number) + goto case_error; + tzcorrection = -sign * number; + dp = nextToken(); + } + else if (dp == DP.tz) + { + tzcorrection = number; + dp = nextToken(); + if (number == 0 && (dp == DP.plus || dp == DP.minus)) + goto Loffset; + if (dp == DP.dst) + { tzcorrection += 100; + dp = nextToken(); + } + } + else if (dp == DP.dsttz) + { + tzcorrection = number; + dp = nextToken(); + } - return dp; + return dp; case_error: - return DP.err; + return DP.err; } } @@ -780,8 +780,8 @@ unittest assert(d.tzcorrection == -530); debug(dateparse) printf("year = %d, month = %d, day = %d\n%02d:%02d:%02d.%03d\nweekday = %d, tzcorrection = %d\n", - d.year, d.month, d.day, - d.hour, d.minute, d.second, d.ms, - d.weekday, d.tzcorrection); + d.year, d.month, d.day, + d.hour, d.minute, d.second, d.ms, + d.weekday, d.tzcorrection); } diff --git a/std/demangle.d b/std/demangle.d index 24fa2f958..5f760be13 100644 --- a/std/demangle.d +++ b/std/demangle.d @@ -7,18 +7,18 @@ /**** * Demangle D mangled names. * Macros: - * WIKI = Phobos/StdDemangle + * WIKI = Phobos/StdDemangle */ /* Authors: - * Walter Bright, Digital Mars, www.digitalmars.com - * Thomas Kuehne - * Frits van Bommel + * Walter Bright, Digital Mars, www.digitalmars.com + * Thomas Kuehne + * Frits van Bommel */ module std.demangle; -//debug=demangle; // uncomment to turn on debugging printf's +//debug=demangle; // uncomment to turn on debugging printf's private import std.ctype; private import std.string; @@ -30,7 +30,7 @@ private class MangleException : Exception { this() { - super("MangleException"); + super("MangleException"); } } @@ -39,8 +39,8 @@ private class MangleException : Exception * * If it is not a D mangled name, it returns its argument name. * Example: - * This program reads standard in and writes it to standard out, - * pretty-printing any found D mangled names. + * This program reads standard in and writes it to standard out, + * pretty-printing any found D mangled names. ------------------- import std.stdio; import std.ctype; @@ -53,28 +53,28 @@ int main() while ((c = fgetc(stdin)) != EOF) { - if (inword) - { - if (c == '_' || isalnum(c)) - buffer ~= cast(char) c; - else - { - inword = false; - writef(demangle(buffer), cast(char) c); - } - } - else - { if (c == '_' || isalpha(c)) - { inword = true; - buffer.length = 0; - buffer ~= cast(char) c; - } - else - writef(cast(char) c); - } + if (inword) + { + if (c == '_' || isalnum(c)) + buffer ~= cast(char) c; + else + { + inword = false; + writef(demangle(buffer), cast(char) c); + } + } + else + { if (c == '_' || isalpha(c)) + { inword = true; + buffer.length = 0; + buffer ~= cast(char) c; + } + else + writef(cast(char) c); + } } if (inword) - writef(demangle(buffer)); + writef(demangle(buffer)); return 0; } ------------------- @@ -87,390 +87,390 @@ string demangle(string name) static void error() { - //writefln("error()"); - throw new MangleException(); + //writefln("error()"); + throw new MangleException(); } static ubyte ascii2hex(char c) { - if (!isxdigit(c)) - error(); - return cast(ubyte) - ( (c >= 'a') ? c - 'a' + 10 : - (c >= 'A') ? c - 'A' + 10 : - c - '0' - ); + if (!isxdigit(c)) + error(); + return cast(ubyte) + ( (c >= 'a') ? c - 'a' + 10 : + (c >= 'A') ? c - 'A' + 10 : + c - '0' + ); } size_t parseNumber() { - //writefln("parseNumber() %d", ni); - size_t result; + //writefln("parseNumber() %d", ni); + size_t result; - while (ni < name.length && isdigit(name[ni])) - { int i = name[ni] - '0'; - if (result > (size_t.max - i) / 10) - error(); - result = result * 10 + i; - ni++; - } - return result; + while (ni < name.length && isdigit(name[ni])) + { int i = name[ni] - '0'; + if (result > (size_t.max - i) / 10) + error(); + result = result * 10 + i; + ni++; + } + return result; } string parseSymbolName() { - //writefln("parseSymbolName() %d", ni); - size_t i = parseNumber(); - if (ni + i > name.length) - error(); - string result; - if (i >= 5 && - name[ni] == '_' && - name[ni + 1] == '_' && - name[ni + 2] == 'T') - { - size_t nisave = ni; - bool err; - ni += 3; - try - { - result = fparseTemplateInstanceName(); - if (ni != nisave + i) - err = true; - } - catch (MangleException me) - { - err = true; - } - ni = nisave; - if (err) - goto L1; - goto L2; - } + //writefln("parseSymbolName() %d", ni); + size_t i = parseNumber(); + if (ni + i > name.length) + error(); + string result; + if (i >= 5 && + name[ni] == '_' && + name[ni + 1] == '_' && + name[ni + 2] == 'T') + { + size_t nisave = ni; + bool err; + ni += 3; + try + { + result = fparseTemplateInstanceName(); + if (ni != nisave + i) + err = true; + } + catch (MangleException me) + { + err = true; + } + ni = nisave; + if (err) + goto L1; + goto L2; + } L1: - result = name[ni .. ni + i]; + result = name[ni .. ni + i]; L2: - ni += i; - return result; + ni += i; + return result; } string parseQualifiedName() { - //writefln("parseQualifiedName() %d", ni); - string result; + //writefln("parseQualifiedName() %d", ni); + string result; - while (ni < name.length && isdigit(name[ni])) - { - if (result.length) - result ~= "."; - result ~= parseSymbolName(); - } - return result; + while (ni < name.length && isdigit(name[ni])) + { + if (result.length) + result ~= "."; + result ~= parseSymbolName(); + } + return result; } string parseType(string identifier = null) { - //writefln("parseType() %d", ni); - int isdelegate = 0; - bool hasthisptr = false; /// For function/delegate types: expects a 'this' pointer as last argument + //writefln("parseType() %d", ni); + int isdelegate = 0; + bool hasthisptr = false; /// For function/delegate types: expects a 'this' pointer as last argument Lagain: - if (ni >= name.length) - error(); - string p; - switch (name[ni++]) - { - case 'v': p = "void"; goto L1; - case 'b': p = "bool"; goto L1; - case 'g': p = "byte"; goto L1; - case 'h': p = "ubyte"; goto L1; - case 's': p = "short"; goto L1; - case 't': p = "ushort"; goto L1; - case 'i': p = "int"; goto L1; - case 'k': p = "uint"; goto L1; - case 'l': p = "long"; goto L1; - case 'm': p = "ulong"; goto L1; - case 'f': p = "float"; goto L1; - case 'd': p = "double"; goto L1; - case 'e': p = "real"; goto L1; - case 'o': p = "ifloat"; goto L1; - case 'p': p = "idouble"; goto L1; - case 'j': p = "ireal"; goto L1; - case 'q': p = "cfloat"; goto L1; - case 'r': p = "cdouble"; goto L1; - case 'c': p = "creal"; goto L1; - case 'a': p = "char"; goto L1; - case 'u': p = "wchar"; goto L1; - case 'w': p = "dchar"; goto L1; + if (ni >= name.length) + error(); + string p; + switch (name[ni++]) + { + case 'v': p = "void"; goto L1; + case 'b': p = "bool"; goto L1; + case 'g': p = "byte"; goto L1; + case 'h': p = "ubyte"; goto L1; + case 's': p = "short"; goto L1; + case 't': p = "ushort"; goto L1; + case 'i': p = "int"; goto L1; + case 'k': p = "uint"; goto L1; + case 'l': p = "long"; goto L1; + case 'm': p = "ulong"; goto L1; + case 'f': p = "float"; goto L1; + case 'd': p = "double"; goto L1; + case 'e': p = "real"; goto L1; + case 'o': p = "ifloat"; goto L1; + case 'p': p = "idouble"; goto L1; + case 'j': p = "ireal"; goto L1; + case 'q': p = "cfloat"; goto L1; + case 'r': p = "cdouble"; goto L1; + case 'c': p = "creal"; goto L1; + case 'a': p = "char"; goto L1; + case 'u': p = "wchar"; goto L1; + case 'w': p = "dchar"; goto L1; - case 'A': // dynamic array - p = parseType() ~ "[]"; - goto L1; + case 'A': // dynamic array + p = parseType() ~ "[]"; + goto L1; - case 'P': // pointer - p = parseType() ~ "*"; - goto L1; + case 'P': // pointer + p = parseType() ~ "*"; + goto L1; - case 'G': // static array - { size_t ns = ni; - parseNumber(); - size_t ne = ni; - p = parseType() ~ "[" ~ name[ns .. ne] ~ "]"; - goto L1; - } + case 'G': // static array + { size_t ns = ni; + parseNumber(); + size_t ne = ni; + p = parseType() ~ "[" ~ name[ns .. ne] ~ "]"; + goto L1; + } - case 'H': // associative array - p = parseType(); - p = parseType() ~ "[" ~ p ~ "]"; - goto L1; + case 'H': // associative array + p = parseType(); + p = parseType() ~ "[" ~ p ~ "]"; + goto L1; - case 'D': // delegate - isdelegate = 1; - goto Lagain; + case 'D': // delegate + isdelegate = 1; + goto Lagain; - case 'M': - hasthisptr = true; - goto Lagain; + case 'M': + hasthisptr = true; + goto Lagain; - case 'F': // D function - case 'U': // C function - case 'W': // Windows function - case 'V': // Pascal function - case 'R': // C++ function - { char mc = name[ni - 1]; - string args; + case 'F': // D function + case 'U': // C function + case 'W': // Windows function + case 'V': // Pascal function + case 'R': // C++ function + { char mc = name[ni - 1]; + string args; - while (1) - { - if (ni >= name.length) - error(); - char c = name[ni]; - if (c == 'Z') - break; - if (c == 'X') - { - if (!args.length) error(); - args ~= " ..."; - break; - } - if (args.length) - args ~= ", "; - switch (c) - { - case 'J': - args ~= "out "; - ni++; - goto default; + while (1) + { + if (ni >= name.length) + error(); + char c = name[ni]; + if (c == 'Z') + break; + if (c == 'X') + { + if (!args.length) error(); + args ~= " ..."; + break; + } + if (args.length) + args ~= ", "; + switch (c) + { + case 'J': + args ~= "out "; + ni++; + goto default; - case 'K': - args ~= "inout "; - ni++; - goto default; + case 'K': + args ~= "inout "; + ni++; + goto default; - case 'L': - args ~= "lazy "; - ni++; - goto default; + case 'L': + args ~= "lazy "; + ni++; + goto default; - default: - args ~= parseType(); - continue; + default: + args ~= parseType(); + continue; - case 'Y': - args ~= "..."; - break; - } - break; - } - ni++; - if (!isdelegate && identifier.length) - { - switch (mc) - { - case 'F': p = null; break; // D function - case 'U': p = "extern (C) "; break; // C function - case 'W': p = "extern (Windows) "; break; // Windows function - case 'V': p = "extern (Pascal) "; break; // Pascal function - default: assert(0); - } - p ~= parseType() ~ " " ~ identifier ~ "(" ~ args ~ ")"; - return p; - } - p = parseType() ~ - (isdelegate ? " delegate(" : " function(") ~ - args ~ - ")"; - isdelegate = 0; - goto L1; - } + case 'Y': + args ~= "..."; + break; + } + break; + } + ni++; + if (!isdelegate && identifier.length) + { + switch (mc) + { + case 'F': p = null; break; // D function + case 'U': p = "extern (C) "; break; // C function + case 'W': p = "extern (Windows) "; break; // Windows function + case 'V': p = "extern (Pascal) "; break; // Pascal function + default: assert(0); + } + p ~= parseType() ~ " " ~ identifier ~ "(" ~ args ~ ")"; + return p; + } + p = parseType() ~ + (isdelegate ? " delegate(" : " function(") ~ + args ~ + ")"; + isdelegate = 0; + goto L1; + } - case 'C': p = "class "; goto L2; - case 'S': p = "struct "; goto L2; - case 'E': p = "enum "; goto L2; - case 'T': p = "typedef "; goto L2; + case 'C': p = "class "; goto L2; + case 'S': p = "struct "; goto L2; + case 'E': p = "enum "; goto L2; + case 'T': p = "typedef "; goto L2; - L2: p ~= parseQualifiedName(); - goto L1; + L2: p ~= parseQualifiedName(); + goto L1; - L1: - if (isdelegate) - error(); // 'D' must be followed by function - if (identifier.length) - p ~= " " ~ identifier; - return p; + L1: + if (isdelegate) + error(); // 'D' must be followed by function + if (identifier.length) + p ~= " " ~ identifier; + return p; - default: - size_t i = ni - 1; - ni = name.length; - p = name[i .. length]; - goto L1; - } + default: + size_t i = ni - 1; + ni = name.length; + p = name[i .. length]; + goto L1; + } } string parseTemplateInstanceName() { - auto result = parseSymbolName() ~ "!("; - int nargs; + auto result = parseSymbolName() ~ "!("; + int nargs; - while (1) - { size_t i; + while (1) + { size_t i; - if (ni >= name.length) - error(); - if (nargs && name[ni] != 'Z') - result ~= ", "; - nargs++; - switch (name[ni++]) - { - case 'T': - result ~= parseType(); - continue; + if (ni >= name.length) + error(); + if (nargs && name[ni] != 'Z') + result ~= ", "; + nargs++; + switch (name[ni++]) + { + case 'T': + result ~= parseType(); + continue; - case 'V': + case 'V': - void getReal() - { real r; - ubyte *p = cast(ubyte *)&r; + void getReal() + { real r; + ubyte *p = cast(ubyte *)&r; - if (ni + 10 * 2 > name.length) - error(); - for (i = 0; i < 10; i++) - { ubyte b; + if (ni + 10 * 2 > name.length) + error(); + for (i = 0; i < 10; i++) + { ubyte b; - b = cast(ubyte) - ( - (ascii2hex(name[ni + i * 2]) << 4) + - ascii2hex(name[ni + i * 2 + 1]) - ); - p[i] = b; - } - result ~= format(r); - ni += 10 * 2; - } + b = cast(ubyte) + ( + (ascii2hex(name[ni + i * 2]) << 4) + + ascii2hex(name[ni + i * 2 + 1]) + ); + p[i] = b; + } + result ~= format(r); + ni += 10 * 2; + } - result ~= parseType() ~ " "; - if (ni >= name.length) - error(); - switch (name[ni++]) - { - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - i = ni - 1; - while (ni < name.length && isdigit(name[ni])) - ni++; - result ~= name[i .. ni]; - break; + result ~= parseType() ~ " "; + if (ni >= name.length) + error(); + switch (name[ni++]) + { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + i = ni - 1; + while (ni < name.length && isdigit(name[ni])) + ni++; + result ~= name[i .. ni]; + break; - case 'N': - i = ni; - while (ni < name.length && isdigit(name[ni])) - ni++; - if (i == ni) - error(); - result ~= "-" ~ name[i .. ni]; - break; + case 'N': + i = ni; + while (ni < name.length && isdigit(name[ni])) + ni++; + if (i == ni) + error(); + result ~= "-" ~ name[i .. ni]; + break; - case 'n': - result ~= "null"; - break; + case 'n': + result ~= "null"; + break; - case 'e': - getReal(); - break; + case 'e': + getReal(); + break; - case 'c': - getReal(); - result ~= '+'; - getReal(); - result ~= 'i'; - break; + case 'c': + getReal(); + result ~= '+'; + getReal(); + result ~= 'i'; + break; - case 'a': - case 'w': - case 'd': - { char m = name[ni - 1]; - if (m == 'a') - m = 'c'; - size_t n = parseNumber(); - if (ni >= name.length || name[ni++] != '_' || - ni + n * 2 > name.length) - error(); - result ~= '"'; - for (i = 0; i < n; i++) - { char c; + case 'a': + case 'w': + case 'd': + { char m = name[ni - 1]; + if (m == 'a') + m = 'c'; + size_t n = parseNumber(); + if (ni >= name.length || name[ni++] != '_' || + ni + n * 2 > name.length) + error(); + result ~= '"'; + for (i = 0; i < n; i++) + { char c; - c = cast(char)((ascii2hex(name[ni + i * 2]) << 4) + - ascii2hex(name[ni + i * 2 + 1])); - result ~= c; - } - ni += n * 2; - result ~= '"'; - result ~= m; - break; - } + c = cast(char)((ascii2hex(name[ni + i * 2]) << 4) + + ascii2hex(name[ni + i * 2 + 1])); + result ~= c; + } + ni += n * 2; + result ~= '"'; + result ~= m; + break; + } - default: - error(); - break; - } - continue; + default: + error(); + break; + } + continue; - case 'S': - result ~= parseSymbolName(); - continue; + case 'S': + result ~= parseSymbolName(); + continue; - case 'Z': - break; + case 'Z': + break; - default: - error(); - } - break; - } - result ~= ")"; - return result; + default: + error(); + } + break; + } + result ~= ")"; + return result; } if (name.length < 3 || - name[0] != '_' || - name[1] != 'D' || - !isdigit(name[2])) + name[0] != '_' || + name[1] != 'D' || + !isdigit(name[2])) { - goto Lnot; + goto Lnot; } fparseTemplateInstanceName = &parseTemplateInstanceName; try { - auto result = parseQualifiedName(); - result = parseType(result); - while(ni < name.length){ - result ~= " . " ~ parseType(parseQualifiedName()); - } + auto result = parseQualifiedName(); + result = parseType(result); + while(ni < name.length){ + result ~= " . " ~ parseType(parseQualifiedName()); + } - if (ni != name.length) - goto Lnot; - return result; + if (ni != name.length) + goto Lnot; + return result; } catch (MangleException e) { @@ -488,24 +488,24 @@ unittest static string[2][] table = [ - [ "printf", "printf" ], - [ "_foo", "_foo" ], - [ "_D88", "_D88" ], - [ "_D4test3fooAa", "char[] test.foo"], - [ "_D8demangle8demangleFAaZAa", "char[] demangle.demangle(char[])" ], - [ "_D6object6Object8opEqualsFC6ObjectZi", "int object.Object.opEquals(class Object)" ], - [ "_D4test2dgDFiYd", "double delegate(int, ...) test.dg" ], - [ "_D4test58__T9factorialVde67666666666666860140VG5aa5_68656c6c6fVPvnZ9factorialf", "float test.factorial!(double 4.2, char[5] \"hello\"c, void* null).factorial" ], - [ "_D4test101__T9factorialVde67666666666666860140Vrc9a999999999999d9014000000000000000c00040VG5aa5_68656c6c6fVPvnZ9factorialf", "float test.factorial!(double 4.2, cdouble 6.8+3i, char[5] \"hello\"c, void* null).factorial" ], - [ "_D4test34__T3barVG3uw3_616263VG3wd3_646566Z1xi", "int test.bar!(wchar[3] \"abc\"w, dchar[3] \"def\"d).x" ], - [ "_D8demangle4testFLC6ObjectLDFLiZiZi", "int demangle.test(lazy class Object, lazy int delegate(lazy int))"], - [ "_D8demangle4testFAiXi", "int demangle.test(int[] ...)"], - [ "_D8demangle4testFLAiXi", "int demangle.test(lazy int[] ...)"] + [ "printf", "printf" ], + [ "_foo", "_foo" ], + [ "_D88", "_D88" ], + [ "_D4test3fooAa", "char[] test.foo"], + [ "_D8demangle8demangleFAaZAa", "char[] demangle.demangle(char[])" ], + [ "_D6object6Object8opEqualsFC6ObjectZi", "int object.Object.opEquals(class Object)" ], + [ "_D4test2dgDFiYd", "double delegate(int, ...) test.dg" ], + [ "_D4test58__T9factorialVde67666666666666860140VG5aa5_68656c6c6fVPvnZ9factorialf", "float test.factorial!(double 4.2, char[5] \"hello\"c, void* null).factorial" ], + [ "_D4test101__T9factorialVde67666666666666860140Vrc9a999999999999d9014000000000000000c00040VG5aa5_68656c6c6fVPvnZ9factorialf", "float test.factorial!(double 4.2, cdouble 6.8+3i, char[5] \"hello\"c, void* null).factorial" ], + [ "_D4test34__T3barVG3uw3_616263VG3wd3_646566Z1xi", "int test.bar!(wchar[3] \"abc\"w, dchar[3] \"def\"d).x" ], + [ "_D8demangle4testFLC6ObjectLDFLiZiZi", "int demangle.test(lazy class Object, lazy int delegate(lazy int))"], + [ "_D8demangle4testFAiXi", "int demangle.test(int[] ...)"], + [ "_D8demangle4testFLAiXi", "int demangle.test(lazy int[] ...)"] ]; foreach (i, name; table) { - string r = demangle(name[0]); + string r = demangle(name[0]); assert(r == name[1], "table entry #" ~ toString(i) ~ ": '" ~ name[0] ~ "' demangles as '" ~ r ~ "' but is expected to be '" ~ name[1] ~ "'"); diff --git a/std/file.d b/std/file.d index 8a62e1d04..3b8287328 100644 --- a/std/file.d +++ b/std/file.d @@ -2,7 +2,7 @@ /** * Macros: - * WIKI = Phobos/StdFile + * WIKI = Phobos/StdFile */ /* @@ -61,22 +61,22 @@ static this() class FileException : Exception { - uint errno; // operating system error code + uint errno; // operating system error code this(string name) { - this(name, "file I/O"); + this(name, "file I/O"); } this(string name, string message) { - super(name ~ ": " ~ message); + super(name ~ ": " ~ message); } this(string name, uint errno) { - this(name, sysErrorString(errno)); - this.errno = errno; + this(name, sysErrorString(errno)); + this.errno = errno; } } @@ -87,7 +87,7 @@ class FileException : Exception /******************************************** * Read file name[], return array of bytes read. * Throws: - * FileException on error. + * FileException on error. */ void[] read(char[] name) @@ -97,36 +97,36 @@ void[] read(char[] name) if (useWfuncs) { - wchar* namez = std.utf.toUTF16z(name); - h = CreateFileW(namez,GENERIC_READ,FILE_SHARE_READ,null,OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); + wchar* namez = std.utf.toUTF16z(name); + h = CreateFileW(namez,GENERIC_READ,FILE_SHARE_READ,null,OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); } else { - char* namez = toMBSz(name); - h = CreateFileA(namez,GENERIC_READ,FILE_SHARE_READ,null,OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); + char* namez = toMBSz(name); + h = CreateFileA(namez,GENERIC_READ,FILE_SHARE_READ,null,OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); } if (h == INVALID_HANDLE_VALUE) - goto err1; + goto err1; auto size = GetFileSize(h, null); if (size == INVALID_FILE_SIZE) - goto err2; + goto err2; auto buf = std.gc.malloc(size); if (buf) - std.gc.hasNoPointers(buf.ptr); + std.gc.hasNoPointers(buf.ptr); if (ReadFile(h,buf.ptr,size,&numread,null) != 1) - goto err2; + goto err2; if (numread != size) - goto err2; + goto err2; if (!CloseHandle(h)) - goto err; + goto err; return buf[0 .. size]; @@ -150,27 +150,27 @@ void write(char[] name, void[] buffer) if (useWfuncs) { - wchar* namez = std.utf.toUTF16z(name); - h = CreateFileW(namez,GENERIC_WRITE,0,null,CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); + wchar* namez = std.utf.toUTF16z(name); + h = CreateFileW(namez,GENERIC_WRITE,0,null,CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); } else { - char* namez = toMBSz(name); - h = CreateFileA(namez,GENERIC_WRITE,0,null,CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); + char* namez = toMBSz(name); + h = CreateFileA(namez,GENERIC_WRITE,0,null,CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); } if (h == INVALID_HANDLE_VALUE) - goto err; + goto err; if (WriteFile(h,buffer.ptr,buffer.length,&numwritten,null) != 1) - goto err2; + goto err2; if (buffer.length != numwritten) - goto err2; + goto err2; if (!CloseHandle(h)) - goto err; + goto err; return; err2: @@ -192,29 +192,29 @@ void append(char[] name, void[] buffer) if (useWfuncs) { - wchar* namez = std.utf.toUTF16z(name); - h = CreateFileW(namez,GENERIC_WRITE,0,null,OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); + wchar* namez = std.utf.toUTF16z(name); + h = CreateFileW(namez,GENERIC_WRITE,0,null,OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); } else { - char* namez = toMBSz(name); - h = CreateFileA(namez,GENERIC_WRITE,0,null,OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); + char* namez = toMBSz(name); + h = CreateFileA(namez,GENERIC_WRITE,0,null,OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,cast(HANDLE)null); } if (h == INVALID_HANDLE_VALUE) - goto err; + goto err; SetFilePointer(h, 0, null, FILE_END); if (WriteFile(h,buffer.ptr,buffer.length,&numwritten,null) != 1) - goto err2; + goto err2; if (buffer.length != numwritten) - goto err2; + goto err2; if (!CloseHandle(h)) - goto err; + goto err; return; err2: @@ -234,11 +234,11 @@ void rename(char[] from, char[] to) BOOL result; if (useWfuncs) - result = MoveFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to)); + result = MoveFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to)); else - result = MoveFileA(toMBSz(from), toMBSz(to)); + result = MoveFileA(toMBSz(from), toMBSz(to)); if (!result) - throw new FileException(to, GetLastError()); + throw new FileException(to, GetLastError()); } @@ -252,11 +252,11 @@ void remove(char[] name) BOOL result; if (useWfuncs) - result = DeleteFileW(std.utf.toUTF16z(name)); + result = DeleteFileW(std.utf.toUTF16z(name)); else - result = DeleteFileA(toMBSz(name)); + result = DeleteFileA(toMBSz(name)); if (!result) - throw new FileException(name, GetLastError()); + throw new FileException(name, GetLastError()); } @@ -273,24 +273,24 @@ ulong getSize(char[] name) if (useWfuncs) { - WIN32_FIND_DATAW filefindbuf; + WIN32_FIND_DATAW filefindbuf; - findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf); - resulth = filefindbuf.nFileSizeHigh; - resultl = filefindbuf.nFileSizeLow; + findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf); + resulth = filefindbuf.nFileSizeHigh; + resultl = filefindbuf.nFileSizeLow; } else { - WIN32_FIND_DATA filefindbuf; + WIN32_FIND_DATA filefindbuf; - findhndl = FindFirstFileA(toMBSz(name), &filefindbuf); - resulth = filefindbuf.nFileSizeHigh; - resultl = filefindbuf.nFileSizeLow; + findhndl = FindFirstFileA(toMBSz(name), &filefindbuf); + resulth = filefindbuf.nFileSizeHigh; + resultl = filefindbuf.nFileSizeLow; } if (findhndl == cast(HANDLE)-1) { - throw new FileException(name, GetLastError()); + throw new FileException(name, GetLastError()); } FindClose(findhndl); return (cast(ulong)resulth << 32) + resultl; @@ -307,26 +307,26 @@ void getTimes(char[] name, out d_time ftc, out d_time fta, out d_time ftm) if (useWfuncs) { - WIN32_FIND_DATAW filefindbuf; + WIN32_FIND_DATAW filefindbuf; - findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf); - ftc = std.date.FILETIME2d_time(&filefindbuf.ftCreationTime); - fta = std.date.FILETIME2d_time(&filefindbuf.ftLastAccessTime); - ftm = std.date.FILETIME2d_time(&filefindbuf.ftLastWriteTime); + findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf); + ftc = std.date.FILETIME2d_time(&filefindbuf.ftCreationTime); + fta = std.date.FILETIME2d_time(&filefindbuf.ftLastAccessTime); + ftm = std.date.FILETIME2d_time(&filefindbuf.ftLastWriteTime); } else { - WIN32_FIND_DATA filefindbuf; + WIN32_FIND_DATA filefindbuf; - findhndl = FindFirstFileA(toMBSz(name), &filefindbuf); - ftc = std.date.FILETIME2d_time(&filefindbuf.ftCreationTime); - fta = std.date.FILETIME2d_time(&filefindbuf.ftLastAccessTime); - ftm = std.date.FILETIME2d_time(&filefindbuf.ftLastWriteTime); + findhndl = FindFirstFileA(toMBSz(name), &filefindbuf); + ftc = std.date.FILETIME2d_time(&filefindbuf.ftCreationTime); + fta = std.date.FILETIME2d_time(&filefindbuf.ftLastAccessTime); + ftm = std.date.FILETIME2d_time(&filefindbuf.ftLastWriteTime); } if (findhndl == cast(HANDLE)-1) { - throw new FileException(name, GetLastError()); + throw new FileException(name, GetLastError()); } FindClose(findhndl); } @@ -342,10 +342,10 @@ int exists(char[] name) uint result; if (useWfuncs) - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/getfileattributes.asp - result = GetFileAttributesW(std.utf.toUTF16z(name)); + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/getfileattributes.asp + result = GetFileAttributesW(std.utf.toUTF16z(name)); else - result = GetFileAttributesA(toMBSz(name)); + result = GetFileAttributesA(toMBSz(name)); return result != 0xFFFFFFFF; } @@ -360,12 +360,12 @@ uint getAttributes(string name) uint result; if (useWfuncs) - result = GetFileAttributesW(std.utf.toUTF16z(name)); + result = GetFileAttributesW(std.utf.toUTF16z(name)); else - result = GetFileAttributesA(toMBSz(name)); + result = GetFileAttributesA(toMBSz(name)); if (result == 0xFFFFFFFF) { - throw new FileException(name, GetLastError()); + throw new FileException(name, GetLastError()); } return result; } @@ -399,13 +399,13 @@ void chdir(char[] pathname) { BOOL result; if (useWfuncs) - result = SetCurrentDirectoryW(std.utf.toUTF16z(pathname)); + result = SetCurrentDirectoryW(std.utf.toUTF16z(pathname)); else - result = SetCurrentDirectoryA(toMBSz(pathname)); + result = SetCurrentDirectoryA(toMBSz(pathname)); if (!result) { - throw new FileException(pathname, GetLastError()); + throw new FileException(pathname, GetLastError()); } } @@ -418,13 +418,13 @@ void mkdir(char[] pathname) { BOOL result; if (useWfuncs) - result = CreateDirectoryW(std.utf.toUTF16z(pathname), null); + result = CreateDirectoryW(std.utf.toUTF16z(pathname), null); else - result = CreateDirectoryA(toMBSz(pathname), null); + result = CreateDirectoryA(toMBSz(pathname), null); if (!result) { - throw new FileException(pathname, GetLastError()); + throw new FileException(pathname, GetLastError()); } } @@ -437,13 +437,13 @@ void rmdir(char[] pathname) { BOOL result; if (useWfuncs) - result = RemoveDirectoryW(std.utf.toUTF16z(pathname)); + result = RemoveDirectoryW(std.utf.toUTF16z(pathname)); else - result = RemoveDirectoryA(toMBSz(pathname)); + result = RemoveDirectoryA(toMBSz(pathname)); if (!result) { - throw new FileException(pathname, GetLastError()); + throw new FileException(pathname, GetLastError()); } } @@ -456,29 +456,29 @@ char[] getcwd() { if (useWfuncs) { - wchar c; + wchar c; - auto len = GetCurrentDirectoryW(0, &c); - if (!len) - goto Lerr; - auto dir = new wchar[len]; - len = GetCurrentDirectoryW(len, dir.ptr); - if (!len) - goto Lerr; - return std.utf.toUTF8(dir[0 .. len]); // leave off terminating 0 + auto len = GetCurrentDirectoryW(0, &c); + if (!len) + goto Lerr; + auto dir = new wchar[len]; + len = GetCurrentDirectoryW(len, dir.ptr); + if (!len) + goto Lerr; + return std.utf.toUTF8(dir[0 .. len]); // leave off terminating 0 } else { - char c; + char c; - auto len = GetCurrentDirectoryA(0, &c); - if (!len) - goto Lerr; - auto dir = new char[len]; - len = GetCurrentDirectoryA(len, dir.ptr); - if (!len) - goto Lerr; - return dir[0 .. len]; // leave off terminating 0 + auto len = GetCurrentDirectoryA(0, &c); + if (!len) + goto Lerr; + auto dir = new char[len]; + len = GetCurrentDirectoryA(len, dir.ptr); + if (!len) + goto Lerr; + return dir[0 .. len]; // leave off terminating 0 } Lerr: @@ -491,47 +491,47 @@ Lerr: struct DirEntry { - string name; /// file or directory name - ulong size = ~0UL; /// size of file in bytes - d_time creationTime = d_time_nan; /// time of file creation - d_time lastAccessTime = d_time_nan; /// time file was last accessed - d_time lastWriteTime = d_time_nan; /// time file was last written to - uint attributes; // Windows file attributes OR'd together + string name; /// file or directory name + ulong size = ~0UL; /// size of file in bytes + d_time creationTime = d_time_nan; /// time of file creation + d_time lastAccessTime = d_time_nan; /// time file was last accessed + d_time lastWriteTime = d_time_nan; /// time file was last written to + uint attributes; // Windows file attributes OR'd together void init(string path, WIN32_FIND_DATA *fd) { - wchar[] wbuf; - size_t clength; - size_t wlength; - size_t n; + wchar[] wbuf; + size_t clength; + size_t wlength; + size_t n; - clength = std.c.string.strlen(fd.cFileName.ptr); + clength = std.c.string.strlen(fd.cFileName.ptr); - // Convert cFileName[] to unicode - wlength = MultiByteToWideChar(0,0,fd.cFileName.ptr,clength,null,0); - if (wlength > wbuf.length) - wbuf.length = wlength; - n = MultiByteToWideChar(0,0,fd.cFileName.ptr,clength,cast(wchar*)wbuf,wlength); - assert(n == wlength); - // toUTF8() returns a new buffer - name = std.path.join(path, std.utf.toUTF8(wbuf[0 .. wlength])); + // Convert cFileName[] to unicode + wlength = MultiByteToWideChar(0,0,fd.cFileName.ptr,clength,null,0); + if (wlength > wbuf.length) + wbuf.length = wlength; + n = MultiByteToWideChar(0,0,fd.cFileName.ptr,clength,cast(wchar*)wbuf,wlength); + assert(n == wlength); + // toUTF8() returns a new buffer + name = std.path.join(path, std.utf.toUTF8(wbuf[0 .. wlength])); - size = (cast(ulong)fd.nFileSizeHigh << 32) | fd.nFileSizeLow; - creationTime = std.date.FILETIME2d_time(&fd.ftCreationTime); - lastAccessTime = std.date.FILETIME2d_time(&fd.ftLastAccessTime); - lastWriteTime = std.date.FILETIME2d_time(&fd.ftLastWriteTime); - attributes = fd.dwFileAttributes; + size = (cast(ulong)fd.nFileSizeHigh << 32) | fd.nFileSizeLow; + creationTime = std.date.FILETIME2d_time(&fd.ftCreationTime); + lastAccessTime = std.date.FILETIME2d_time(&fd.ftLastAccessTime); + lastWriteTime = std.date.FILETIME2d_time(&fd.ftLastWriteTime); + attributes = fd.dwFileAttributes; } void init(string path, WIN32_FIND_DATAW *fd) { - size_t clength = std.string.wcslen(fd.cFileName.ptr); - name = std.path.join(path, std.utf.toUTF8(fd.cFileName[0 .. clength])); - size = (cast(ulong)fd.nFileSizeHigh << 32) | fd.nFileSizeLow; - creationTime = std.date.FILETIME2d_time(&fd.ftCreationTime); - lastAccessTime = std.date.FILETIME2d_time(&fd.ftLastAccessTime); - lastWriteTime = std.date.FILETIME2d_time(&fd.ftLastWriteTime); - attributes = fd.dwFileAttributes; + size_t clength = std.string.wcslen(fd.cFileName.ptr); + name = std.path.join(path, std.utf.toUTF8(fd.cFileName[0 .. clength])); + size = (cast(ulong)fd.nFileSizeHigh << 32) | fd.nFileSizeLow; + creationTime = std.date.FILETIME2d_time(&fd.ftCreationTime); + lastAccessTime = std.date.FILETIME2d_time(&fd.ftLastAccessTime); + lastWriteTime = std.date.FILETIME2d_time(&fd.ftLastWriteTime); + attributes = fd.dwFileAttributes; } /**** @@ -539,7 +539,7 @@ struct DirEntry */ uint isdir() { - return attributes & FILE_ATTRIBUTE_DIRECTORY; + return attributes & FILE_ATTRIBUTE_DIRECTORY; } /**** @@ -547,7 +547,7 @@ struct DirEntry */ uint isfile() { - return !(attributes & FILE_ATTRIBUTE_DIRECTORY); + return !(attributes & FILE_ATTRIBUTE_DIRECTORY); } } @@ -557,8 +557,8 @@ struct DirEntry * The names in the contents do not include the pathname. * Throws: FileException on error * Example: - * This program lists all the files and subdirectories in its - * path argument. + * This program lists all the files and subdirectories in its + * path argument. * ---- * import std.stdio; * import std.file; @@ -568,7 +568,7 @@ struct DirEntry * auto dirs = std.file.listdir(args[1]); * * foreach (d; dirs) - * writefln(d); + * writefln(d); * } * ---- */ @@ -579,8 +579,8 @@ string[] listdir(string pathname) bool listing(string filename) { - result ~= filename; - return true; // continue + result ~= filename; + return true; // continue } listdir(pathname, &listing); @@ -592,14 +592,14 @@ string[] listdir(string pathname) * Return all the files in the directory and its subdirectories * that match pattern or regular expression r. * Params: - * pathname = Directory name - * pattern = String with wildcards, such as $(RED "*.d"). The supported - * wildcard strings are described under fnmatch() in - * $(LINK2 std_path.html, std.path). - * r = Regular expression, for more powerful _pattern matching. + * pathname = Directory name + * pattern = String with wildcards, such as $(RED "*.d"). The supported + * wildcard strings are described under fnmatch() in + * $(LINK2 std_path.html, std.path). + * r = Regular expression, for more powerful _pattern matching. * Example: - * This program lists all the files with a "d" extension in - * the path passed as the first argument. + * This program lists all the files with a "d" extension in + * the path passed as the first argument. * ---- * import std.stdio; * import std.file; @@ -609,7 +609,7 @@ string[] listdir(string pathname) * auto d_source_files = std.file.listdir(args[1], "*.d"); * * foreach (d; d_source_files) - * writefln(d); + * writefln(d); * } * ---- * A regular expression version that searches for all files with "d" or @@ -624,7 +624,7 @@ string[] listdir(string pathname) * auto d_source_files = std.file.listdir(args[1], RegExp(r"\.(d|obj)$")); * * foreach (d; d_source_files) - * writefln(d); + * writefln(d); * } * ---- */ @@ -634,13 +634,13 @@ string[] listdir(string pathname, string pattern) bool callback(DirEntry* de) { - if (de.isdir) - listdir(de.name, &callback); - else - { if (std.path.fnmatch(de.name, pattern)) - result ~= de.name; - } - return true; // continue + if (de.isdir) + listdir(de.name, &callback); + else + { if (std.path.fnmatch(de.name, pattern)) + result ~= de.name; + } + return true; // continue } listdir(pathname, &callback); @@ -654,13 +654,13 @@ string[] listdir(string pathname, RegExp r) bool callback(DirEntry* de) { - if (de.isdir) - listdir(de.name, &callback); - else - { if (r.test(de.name)) - result ~= de.name; - } - return true; // continue + if (de.isdir) + listdir(de.name, &callback); + else + { if (r.test(de.name)) + result ~= de.name; + } + return true; // continue } listdir(pathname, &callback); @@ -671,12 +671,12 @@ string[] listdir(string pathname, RegExp r) * For each file and directory name in pathname[], * pass it to the callback delegate. * Params: - * callback = Delegate that processes each - * filename in turn. Returns true to - * continue, false to stop. + * callback = Delegate that processes each + * filename in turn. Returns true to + * continue, false to stop. * Example: - * This program lists all the files in its - * path argument, including the path. + * This program lists all the files in its + * path argument, including the path. * ---- * import std.stdio; * import std.path; @@ -705,7 +705,7 @@ void listdir(string pathname, bool delegate(string filename) callback) { bool listing(DirEntry* de) { - return callback(std.path.getBaseName(de.name)); + return callback(std.path.getBaseName(de.name)); } listdir(pathname, &listing); @@ -715,12 +715,12 @@ void listdir(string pathname, bool delegate(string filename) callback) * For each file and directory DirEntry in pathname[], * pass it to the callback delegate. * Params: - * callback = Delegate that processes each - * DirEntry in turn. Returns true to - * continue, false to stop. + * callback = Delegate that processes each + * DirEntry in turn. Returns true to + * continue, false to stop. * Example: - * This program lists all the files in its - * path argument and all subdirectories thereof. + * This program lists all the files in its + * path argument and all subdirectories thereof. * ---- * import std.stdio; * import std.file; @@ -750,57 +750,57 @@ void listdir(string pathname, bool delegate(DirEntry* de) callback) c = std.path.join(pathname, "*.*"); if (useWfuncs) { - WIN32_FIND_DATAW fileinfo; + WIN32_FIND_DATAW fileinfo; - h = FindFirstFileW(std.utf.toUTF16z(c), &fileinfo); - if (h != INVALID_HANDLE_VALUE) - { - try - { - do - { - // Skip "." and ".." - if (std.string.wcscmp(fileinfo.cFileName.ptr, ".") == 0 || - std.string.wcscmp(fileinfo.cFileName.ptr, "..") == 0) - continue; + h = FindFirstFileW(std.utf.toUTF16z(c), &fileinfo); + if (h != INVALID_HANDLE_VALUE) + { + try + { + do + { + // Skip "." and ".." + if (std.string.wcscmp(fileinfo.cFileName.ptr, ".") == 0 || + std.string.wcscmp(fileinfo.cFileName.ptr, "..") == 0) + continue; - de.init(pathname, &fileinfo); - if (!callback(&de)) - break; - } while (FindNextFileW(h,&fileinfo) != FALSE); - } - finally - { - FindClose(h); - } - } + de.init(pathname, &fileinfo); + if (!callback(&de)) + break; + } while (FindNextFileW(h,&fileinfo) != FALSE); + } + finally + { + FindClose(h); + } + } } else { - WIN32_FIND_DATA fileinfo; + WIN32_FIND_DATA fileinfo; - h = FindFirstFileA(toMBSz(c), &fileinfo); - if (h != INVALID_HANDLE_VALUE) // should we throw exception if invalid? - { - try - { - do - { - // Skip "." and ".." - if (std.c.string.strcmp(fileinfo.cFileName.ptr, ".") == 0 || - std.c.string.strcmp(fileinfo.cFileName.ptr, "..") == 0) - continue; + h = FindFirstFileA(toMBSz(c), &fileinfo); + if (h != INVALID_HANDLE_VALUE) // should we throw exception if invalid? + { + try + { + do + { + // Skip "." and ".." + if (std.c.string.strcmp(fileinfo.cFileName.ptr, ".") == 0 || + std.c.string.strcmp(fileinfo.cFileName.ptr, "..") == 0) + continue; - de.init(pathname, &fileinfo); - if (!callback(&de)) - break; - } while (FindNextFileA(h,&fileinfo) != FALSE); - } - finally - { - FindClose(h); - } - } + de.init(pathname, &fileinfo); + if (!callback(&de)) + break; + } while (FindNextFileA(h,&fileinfo) != FALSE); + } + finally + { + FindClose(h); + } + } } } @@ -827,9 +827,9 @@ void copy(string from, string to) BOOL result; if (useWfuncs) - result = CopyFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to), false); + result = CopyFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to), false); else - result = CopyFileA(toMBSz(from), toMBSz(to), false); + result = CopyFileA(toMBSz(from), toMBSz(to), false); if (!result) throw new FileException(to, GetLastError()); } @@ -851,31 +851,31 @@ private import std.c.string; class FileException : Exception { - uint errno; // operating system error code + uint errno; // operating system error code this(string name) { - this(name, "file I/O"); + this(name, "file I/O"); } this(string name, string message) { - super(name ~ ": " ~ message); + super(name ~ ": " ~ message); } this(string name, uint errno) { char[1024] buf = void; - auto s = strerror_r(errno, buf.ptr, buf.length); - this(name, std.string.toString(s).dup); - this.errno = errno; + auto s = strerror_r(errno, buf.ptr, buf.length); + this(name, std.string.toString(s).dup); + this.errno = errno; } } /******************************************** * Read a file. * Returns: - * array of bytes read + * array of bytes read */ void[] read(string name) @@ -899,54 +899,54 @@ void[] read(string name) } auto size = statbuf.st_size; if (size > int.max) - goto err2; + goto err2; void[] buf; if (size == 0) - { /* The size could be 0 if the file is a device or a procFS file, - * so we just have to try reading it. - */ - int readsize = 1024; - while (1) - { - buf = std.gc.realloc(buf.ptr, cast(int)size + readsize); + { /* The size could be 0 if the file is a device or a procFS file, + * so we just have to try reading it. + */ + int readsize = 1024; + while (1) + { + buf = std.gc.realloc(buf.ptr, cast(int)size + readsize); - auto toread = readsize; - while (toread) - { - auto numread = std.c.posix.posix.read(fd, buf.ptr + size, toread); - if (numread == -1) - goto err2; - size += numread; - if (numread == 0) - { if (size == 0) // it really was 0 size - delete buf; // don't need the buffer - else - std.gc.hasNoPointers(buf.ptr); - goto Leof; // end of file - } - toread -= numread; - } - } + auto toread = readsize; + while (toread) + { + auto numread = std.c.posix.posix.read(fd, buf.ptr + size, toread); + if (numread == -1) + goto err2; + size += numread; + if (numread == 0) + { if (size == 0) // it really was 0 size + delete buf; // don't need the buffer + else + std.gc.hasNoPointers(buf.ptr); + goto Leof; // end of file + } + toread -= numread; + } + } } else { - buf = std.gc.malloc(cast(int)size); - if (buf.ptr) - std.gc.hasNoPointers(buf.ptr); + buf = std.gc.malloc(cast(int)size); + if (buf.ptr) + std.gc.hasNoPointers(buf.ptr); - auto numread = std.c.posix.posix.read(fd, buf.ptr, cast(int)size); - if (numread != size) - { - //printf("\tread error, errno = %d\n",getErrno()); - goto err2; - } + auto numread = std.c.posix.posix.read(fd, buf.ptr, cast(int)size); + if (numread != size) + { + //printf("\tread error, errno = %d\n",getErrno()); + goto err2; + } } Leof: if (std.c.posix.posix.close(fd) == -1) { - //printf("\tclose error, errno = %d\n",getErrno()); + //printf("\tclose error, errno = %d\n",getErrno()); goto err; } @@ -964,10 +964,10 @@ err1: unittest { version (linux) - { // A file with "zero" length that doesn't have 0 length at all - char[] s = cast(char[])std.file.read("/proc/sys/kernel/osrelease"); - assert(s.length > 0); - //writefln("'%s'", s); + { // A file with "zero" length that doesn't have 0 length at all + char[] s = cast(char[])std.file.read("/proc/sys/kernel/osrelease"); + assert(s.length > 0); + //writefln("'%s'", s); } } @@ -1043,7 +1043,7 @@ void rename(string from, string to) char *toz = toStringz(to); if (std.c.stdio.rename(fromz, toz) == -1) - throw new FileException(to, getErrno()); + throw new FileException(to, getErrno()); } @@ -1054,7 +1054,7 @@ void rename(string from, string to) void remove(string name) { if (std.c.stdio.remove(toStringz(name)) == -1) - throw new FileException(name, getErrno()); + throw new FileException(name, getErrno()); } @@ -1087,7 +1087,7 @@ ulong getSize(string name) if (std.c.posix.posix.close(fd) == -1) { - //printf("\tclose error, errno = %d\n",getErrno()); + //printf("\tclose error, errno = %d\n",getErrno()); goto err; } @@ -1113,7 +1113,7 @@ uint getAttributes(string name) namez = toStringz(name); if (std.c.posix.posix.stat(namez, &statbuf)) { - throw new FileException(name, getErrno()); + throw new FileException(name, getErrno()); } return statbuf.st_mode; @@ -1132,26 +1132,26 @@ void getTimes(string name, out d_time ftc, out d_time fta, out d_time ftm) namez = toStringz(name); if (std.c.posix.posix.stat(namez, &statbuf)) { - throw new FileException(name, getErrno()); + throw new FileException(name, getErrno()); } version (linux) { - ftc = cast(d_time)statbuf.st_ctime * std.date.TicksPerSecond; - fta = cast(d_time)statbuf.st_atime * std.date.TicksPerSecond; - ftm = cast(d_time)statbuf.st_mtime * std.date.TicksPerSecond; + ftc = cast(d_time)statbuf.st_ctime * std.date.TicksPerSecond; + fta = cast(d_time)statbuf.st_atime * std.date.TicksPerSecond; + ftm = cast(d_time)statbuf.st_mtime * std.date.TicksPerSecond; } else version (OSX) - { // BUG: should add in tv_nsec field - ftc = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; - fta = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; - ftm = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; + { // BUG: should add in tv_nsec field + ftc = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; + fta = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; + ftm = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; } else version (FreeBSD) - { // BUG: should add in tv_nsec field - ftc = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; - fta = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; - ftm = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; + { // BUG: should add in tv_nsec field + ftc = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; + fta = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; + ftm = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; } else version (Solaris) { // BUG: should add in *nsec fields @@ -1161,7 +1161,7 @@ void getTimes(string name, out d_time ftc, out d_time fta, out d_time ftm) } else { - static assert(0); + static assert(0); } } @@ -1181,7 +1181,7 @@ int exists(char[] name) namez = toStringz(name); if (std.c.posix.posix.stat(namez, &statbuf)) { - return 0; + return 0; } return 1; +/ @@ -1198,7 +1198,7 @@ unittest int isfile(string name) { - return (getAttributes(name) & S_IFMT) == S_IFREG; // regular file + return (getAttributes(name) & S_IFMT) == S_IFREG; // regular file } /**************************************************** @@ -1218,7 +1218,7 @@ void chdir(string pathname) { if (std.c.posix.posix.chdir(toStringz(pathname))) { - throw new FileException(pathname, getErrno()); + throw new FileException(pathname, getErrno()); } } @@ -1230,7 +1230,7 @@ void mkdir(char[] pathname) { if (std.c.posix.posix.mkdir(toStringz(pathname), 0777)) { - throw new FileException(pathname, getErrno()); + throw new FileException(pathname, getErrno()); } } @@ -1242,7 +1242,7 @@ void rmdir(string pathname) { if (std.c.posix.posix.rmdir(toStringz(pathname))) { - throw new FileException(pathname, getErrno()); + throw new FileException(pathname, getErrno()); } } @@ -1255,7 +1255,7 @@ string getcwd() auto p = std.c.posix.posix.getcwd(null, 0); if (!p) { - throw new FileException("cannot get cwd", getErrno()); + throw new FileException("cannot get cwd", getErrno()); } auto len = std.c.string.strlen(p); @@ -1271,61 +1271,61 @@ string getcwd() struct DirEntry { - string name; /// file or directory name - ulong _size = ~0UL; // size of file in bytes - d_time _creationTime = d_time_nan; // time of file creation + string name; /// file or directory name + ulong _size = ~0UL; // size of file in bytes + d_time _creationTime = d_time_nan; // time of file creation d_time _lastAccessTime = d_time_nan; // time file was last accessed - d_time _lastWriteTime = d_time_nan; // time file was last written to + d_time _lastWriteTime = d_time_nan; // time file was last written to ubyte d_type; - ubyte didstat; // done lazy evaluation of stat() + ubyte didstat; // done lazy evaluation of stat() void init(string path, dirent *fd) - { size_t len = std.c.string.strlen(fd.d_name.ptr); - name = std.path.join(path, fd.d_name[0 .. len]); - d_type = fd.d_type; + { size_t len = std.c.string.strlen(fd.d_name.ptr); + name = std.path.join(path, fd.d_name[0 .. len]); + d_type = fd.d_type; // Some platforms, like Solaris, don't have this member. // TODO: Bug: d_type is never set on Solaris (see bugzilla 2838 for fix.) static if (is(fd.d_type)) d_type = fd.d_type; - didstat = 0; + didstat = 0; } int isdir() { - return d_type & DT_DIR; + return d_type & DT_DIR; } int isfile() { - return d_type & DT_REG; + return d_type & DT_REG; } ulong size() { - if (!didstat) - doStat(); - return _size; + if (!didstat) + doStat(); + return _size; } d_time creationTime() { - if (!didstat) - doStat(); - return _creationTime; + if (!didstat) + doStat(); + return _creationTime; } d_time lastAccessTime() { - if (!didstat) - doStat(); - return _lastAccessTime; + if (!didstat) + doStat(); + return _lastAccessTime; } d_time lastWriteTime() { - if (!didstat) - doStat(); - return _lastWriteTime; + if (!didstat) + doStat(); + return _lastWriteTime; } /* This is to support lazy evaluation, because doing stat's is @@ -1334,47 +1334,47 @@ struct DirEntry void doStat() { - int fd; - struct_stat statbuf; - char* namez; + int fd; + struct_stat statbuf; + char* namez; - namez = toStringz(name); - if (std.c.posix.posix.stat(namez, &statbuf)) - { - //printf("\tstat error, errno = %d\n",getErrno()); - return; - } - _size = cast(ulong)statbuf.st_size; - version (linux) - { - _creationTime = cast(d_time)statbuf.st_ctime * std.date.TicksPerSecond; - _lastAccessTime = cast(d_time)statbuf.st_atime * std.date.TicksPerSecond; - _lastWriteTime = cast(d_time)statbuf.st_mtime * std.date.TicksPerSecond; - } - else version (OSX) - { - _creationTime = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; - _lastAccessTime = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; - _lastWriteTime = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; - } - else version (FreeBSD) - { - _creationTime = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; - _lastAccessTime = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; - _lastWriteTime = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; - } - else version (Solaris) - { - _creationTime = cast(d_time)statbuf.st_ctime * std.date.TicksPerSecond; - _lastAccessTime = cast(d_time)statbuf.st_atime * std.date.TicksPerSecond; - _lastWriteTime = cast(d_time)statbuf.st_mtime * std.date.TicksPerSecond; - } - else - { - static assert(0); - } + namez = toStringz(name); + if (std.c.posix.posix.stat(namez, &statbuf)) + { + //printf("\tstat error, errno = %d\n",getErrno()); + return; + } + _size = cast(ulong)statbuf.st_size; + version (linux) + { + _creationTime = cast(d_time)statbuf.st_ctime * std.date.TicksPerSecond; + _lastAccessTime = cast(d_time)statbuf.st_atime * std.date.TicksPerSecond; + _lastWriteTime = cast(d_time)statbuf.st_mtime * std.date.TicksPerSecond; + } + else version (OSX) + { + _creationTime = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; + _lastAccessTime = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; + _lastWriteTime = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; + } + else version (FreeBSD) + { + _creationTime = cast(d_time)statbuf.st_ctimespec.tv_sec * std.date.TicksPerSecond; + _lastAccessTime = cast(d_time)statbuf.st_atimespec.tv_sec * std.date.TicksPerSecond; + _lastWriteTime = cast(d_time)statbuf.st_mtimespec.tv_sec * std.date.TicksPerSecond; + } + else version (Solaris) + { + _creationTime = cast(d_time)statbuf.st_ctime * std.date.TicksPerSecond; + _lastAccessTime = cast(d_time)statbuf.st_atime * std.date.TicksPerSecond; + _lastWriteTime = cast(d_time)statbuf.st_mtime * std.date.TicksPerSecond; + } + else + { + static assert(0); + } - didstat = 1; + didstat = 1; } } @@ -1388,8 +1388,8 @@ string[] listdir(string pathname) string[] result; bool listing(string filename) { - result ~= filename; - return true; // continue + result ~= filename; + return true; // continue } listdir(pathname, &listing); @@ -1400,15 +1400,15 @@ string[] listdir(string pathname, string pattern) { string[] result; bool callback(DirEntry* de) { - if (de.isdir) - listdir(de.name, &callback); - else - { if (std.path.fnmatch(de.name, pattern)) - result ~= de.name; - } - return true; // continue + if (de.isdir) + listdir(de.name, &callback); + else + { if (std.path.fnmatch(de.name, pattern)) + result ~= de.name; + } + return true; // continue } - + listdir(pathname, &callback); return result; } @@ -1418,13 +1418,13 @@ string[] listdir(string pathname, RegExp r) bool callback(DirEntry* de) { - if (de.isdir) - listdir(de.name, &callback); - else - { if (r.test(de.name)) - result ~= de.name; - } - return true; // continue + if (de.isdir) + listdir(de.name, &callback); + else + { if (r.test(de.name)) + result ~= de.name; + } + return true; // continue } listdir(pathname, &callback); @@ -1435,7 +1435,7 @@ void listdir(string pathname, bool delegate(string filename) callback) { bool listing(DirEntry* de) { - return callback(std.path.getBaseName(de.name)); + return callback(std.path.getBaseName(de.name)); } listdir(pathname, &listing); @@ -1450,24 +1450,24 @@ void listdir(string pathname, bool delegate(DirEntry* de) callback) h = opendir(toStringz(pathname)); if (h) { - try - { - while((fdata = readdir(h)) != null) - { - // Skip "." and ".." - if (!std.c.string.strcmp(fdata.d_name.ptr, ".") || - !std.c.string.strcmp(fdata.d_name.ptr, "..")) - continue; + try + { + while((fdata = readdir(h)) != null) + { + // Skip "." and ".." + if (!std.c.string.strcmp(fdata.d_name.ptr, ".") || + !std.c.string.strcmp(fdata.d_name.ptr, "..")) + continue; - de.init(pathname, fdata); - if (!callback(&de)) - break; - } - } - finally - { - closedir(h); - } + de.init(pathname, fdata); + if (!callback(&de)) + break; + } + } + finally + { + closedir(h); + } } else { @@ -1514,8 +1514,8 @@ void copy(string from, string to) size_t BUFSIZ = 4096 * 16; void* buf = std.c.stdlib.malloc(BUFSIZ); if (!buf) - { BUFSIZ = 4096; - buf = std.c.stdlib.malloc(BUFSIZ); + { BUFSIZ = 4096; + buf = std.c.stdlib.malloc(BUFSIZ); } if (!buf) { @@ -1524,46 +1524,46 @@ void copy(string from, string to) } for (auto size = statbuf.st_size; size; ) - { size_t toread = (size > BUFSIZ) ? BUFSIZ : cast(size_t)size; + { size_t toread = (size > BUFSIZ) ? BUFSIZ : cast(size_t)size; - auto n = std.c.posix.posix.read(fd, buf, toread); - if (n != toread) - { - //printf("\tread error, errno = %d\n",getErrno()); - goto err5; - } - n = std.c.posix.posix.write(fdw, buf, toread); - if (n != toread) - { - //printf("\twrite error, errno = %d\n",getErrno()); - goto err5; - } - size -= toread; + auto n = std.c.posix.posix.read(fd, buf, toread); + if (n != toread) + { + //printf("\tread error, errno = %d\n",getErrno()); + goto err5; + } + n = std.c.posix.posix.write(fdw, buf, toread); + if (n != toread) + { + //printf("\twrite error, errno = %d\n",getErrno()); + goto err5; + } + size -= toread; } std.c.stdlib.free(buf); if (std.c.posix.posix.close(fdw) == -1) { - //printf("\tclose error, errno = %d\n",getErrno()); + //printf("\tclose error, errno = %d\n",getErrno()); goto err2; } utimbuf utim = void; version (linux) { - utim.actime = cast(__time_t)statbuf.st_atime; - utim.modtime = cast(__time_t)statbuf.st_mtime; + utim.actime = cast(__time_t)statbuf.st_atime; + utim.modtime = cast(__time_t)statbuf.st_mtime; } else version (OSX) { - utim.actime = cast(__time_t)statbuf.st_atimespec.tv_sec; - utim.modtime = cast(__time_t)statbuf.st_mtimespec.tv_sec; + utim.actime = cast(__time_t)statbuf.st_atimespec.tv_sec; + utim.modtime = cast(__time_t)statbuf.st_mtimespec.tv_sec; } else version (FreeBSD) { - utim.actime = cast(__time_t)statbuf.st_atimespec.tv_sec; - utim.modtime = cast(__time_t)statbuf.st_mtimespec.tv_sec; + utim.actime = cast(__time_t)statbuf.st_atimespec.tv_sec; + utim.modtime = cast(__time_t)statbuf.st_mtimespec.tv_sec; } else version (Solaris) { @@ -1572,17 +1572,17 @@ void copy(string from, string to) } else { - static assert(0); + static assert(0); } if (utime(toz, &utim) == -1) { - //printf("\tutime error, errno = %d\n",getErrno()); - goto err3; + //printf("\tutime error, errno = %d\n",getErrno()); + goto err3; } if (std.c.posix.posix.close(fd) == -1) { - //printf("\tclose error, errno = %d\n",getErrno()); + //printf("\tclose error, errno = %d\n",getErrno()); goto err1; } @@ -1630,21 +1630,21 @@ unittest remove("unittest_write.tmp"); if (exists("unittest_write.tmp")) - assert(0); + assert(0); remove("unittest_write2.tmp"); if (exists("unittest_write2.tmp")) - assert(0); + assert(0); } unittest { listdir (".", delegate bool (DirEntry * de) { - auto s = std.string.format("%s : c %s, w %s, a %s", de.name, - toUTCString (de.creationTime), - toUTCString (de.lastWriteTime), - toUTCString (de.lastAccessTime)); - return true; + auto s = std.string.format("%s : c %s, w %s, a %s", de.name, + toUTCString (de.creationTime), + toUTCString (de.lastWriteTime), + toUTCString (de.lastAccessTime)); + return true; } ); } diff --git a/std/format.d b/std/format.d index 2d167cdb4..524e2f475 100644 --- a/std/format.d +++ b/std/format.d @@ -6,7 +6,7 @@ * I/O formatting. It's comparable to C99's vsprintf(). * * Macros: - * WIKI = Phobos/StdFormat + * WIKI = Phobos/StdFormat */ /* @@ -33,9 +33,9 @@ module std.format; -//debug=format; // uncomment to turn on debugging printf's +//debug=format; // uncomment to turn on debugging printf's -import std.stdarg; // caller will need va_list +import std.stdarg; // caller will need va_list private import std.utf; private import std.c.stdlib; @@ -46,7 +46,7 @@ version (Windows) { version (DigitalMars) { - version = DigitalMarsC; + version = DigitalMarsC; } } @@ -55,8 +55,8 @@ version (DigitalMarsC) // This is DMC's internal floating point formatting function extern (C) { - extern char* function(int c, int flags, int precision, real* pdval, - char* buf, int* psl, int width) __pfloatfmt; + extern char* function(int c, int flags, int precision, real* pdval, + char* buf, int* psl, int width) __pfloatfmt; } } else @@ -74,12 +74,12 @@ class FormatError : Error this() { - super("std.format"); + super("std.format"); } this(string msg) { - super("std.format " ~ msg); + super("std.format " ~ msg); } } @@ -131,7 +131,7 @@ enum Mangle : char // This is required since for arrays of ints we only have the mangled // char to work from. If arrays always subclassed TypeInfo_Array this // routine could go away. -private TypeInfo primitiveTypeInfo(Mangle m) +private TypeInfo primitiveTypeInfo(Mangle m) { TypeInfo ti; @@ -205,22 +205,22 @@ private TypeInfo primitiveTypeInfo(Mangle m) * processing of arguments resumes until they are all consumed. * * Params: - * putc = Output is sent do this delegate, character by character. - * arguments = Array of TypeInfo's, one for each argument to be formatted. - * argptr = Points to variadic argument list. + * putc = Output is sent do this delegate, character by character. + * arguments = Array of TypeInfo's, one for each argument to be formatted. + * argptr = Points to variadic argument list. * * Throws: - * Mismatched arguments and formats result in a FormatError being thrown. + * Mismatched arguments and formats result in a FormatError being thrown. * * Format_String: - * $(I Format strings) - * consist of characters interspersed with - * $(I format specifications). Characters are simply copied - * to the output (such as putc) after any necessary conversion - * to the corresponding UTF-8 sequence. + * $(I Format strings) + * consist of characters interspersed with + * $(I format specifications). Characters are simply copied + * to the output (such as putc) after any necessary conversion + * to the corresponding UTF-8 sequence. * - * A $(I format specification) starts with a '%' character, - * and has the following grammar: + * A $(I format specification) starts with a '%' character, + * and has the following grammar:
 $(I FormatSpecification):
@@ -281,38 +281,38 @@ $(I FormatChar):
     
$(I Flags)
-
$(B '-') -
- Left justify the result in the field. - It overrides any $(B 0) flag. +
$(B '-') +
+ Left justify the result in the field. + It overrides any $(B 0) flag. -
$(B '+') -
Prefix positive numbers in a signed conversion with a $(B +). - It overrides any $(I space) flag. +
$(B '+') +
Prefix positive numbers in a signed conversion with a $(B +). + It overrides any $(I space) flag. -
$(B '#') -
Use alternative formatting: -
-
For $(B 'o'): -
Add to precision as necessary so that the first digit - of the octal formatting is a '0', even if both the argument - and the $(I Precision) are zero. -
For $(B 'x') ($(B 'X')): -
If non-zero, prefix result with $(B 0x) ($(B 0X)). -
For floating point formatting: -
Always insert the decimal point. -
For $(B 'g') ($(B 'G')): -
Do not elide trailing zeros. -
+
$(B '#') +
Use alternative formatting: +
+
For $(B 'o'): +
Add to precision as necessary so that the first digit + of the octal formatting is a '0', even if both the argument + and the $(I Precision) are zero. +
For $(B 'x') ($(B 'X')): +
If non-zero, prefix result with $(B 0x) ($(B 0X)). +
For floating point formatting: +
Always insert the decimal point. +
For $(B 'g') ($(B 'G')): +
Do not elide trailing zeros. +
-
$(B '0') -
For integer and floating point formatting when not nan or - infinity, use leading zeros - to pad rather than spaces. - Ignore if there's a $(I Precision). +
$(B '0') +
For integer and floating point formatting when not nan or + infinity, use leading zeros + to pad rather than spaces. + Ignore if there's a $(I Precision). -
$(B ' ') -
Prefix positive numbers in a signed conversion with a space. +
$(B ' ') +
Prefix positive numbers in a signed conversion with a space.
$(I Width) @@ -332,86 +332,86 @@ $(I FormatChar):
$(I FormatChar)
-
$(B 's') -
The corresponding argument is formatted in a manner consistent - with its type: -
-
$(B bool) -
The result is 'true' or 'false'. -
integral types -
The $(B %d) format is used. -
floating point types -
The $(B %g) format is used. -
string types -
The result is the string converted to UTF-8. - A $(I Precision) specifies the maximum number of characters - to use in the result. -
classes derived from $(B Object) -
The result is the string returned from the class instance's - $(B .toString()) method. - A $(I Precision) specifies the maximum number of characters - to use in the result. -
non-string static and dynamic arrays -
The result is [s0, s1, ...] - where sk is the kth element - formatted with the default format. -
+
$(B 's') +
The corresponding argument is formatted in a manner consistent + with its type: +
+
$(B bool) +
The result is 'true' or 'false'. +
integral types +
The $(B %d) format is used. +
floating point types +
The $(B %g) format is used. +
string types +
The result is the string converted to UTF-8. + A $(I Precision) specifies the maximum number of characters + to use in the result. +
classes derived from $(B Object) +
The result is the string returned from the class instance's + $(B .toString()) method. + A $(I Precision) specifies the maximum number of characters + to use in the result. +
non-string static and dynamic arrays +
The result is [s0, s1, ...] + where sk is the kth element + formatted with the default format. +
-
$(B 'b','d','o','x','X') -
The corresponding argument must be an integral type - and is formatted as an integer. If the argument is a signed type - and the $(I FormatChar) is $(B d) it is converted to - a signed string of characters, otherwise it is treated as - unsigned. An argument of type $(B bool) is formatted as '1' - or '0'. The base used is binary for $(B b), octal for $(B o), - decimal - for $(B d), and hexadecimal for $(B x) or $(B X). - $(B x) formats using lower case letters, $(B X) uppercase. - If there are fewer resulting digits than the $(I Precision), - leading zeros are used as necessary. - If the $(I Precision) is 0 and the number is 0, no digits - result. +
$(B 'b','d','o','x','X') +
The corresponding argument must be an integral type + and is formatted as an integer. If the argument is a signed type + and the $(I FormatChar) is $(B d) it is converted to + a signed string of characters, otherwise it is treated as + unsigned. An argument of type $(B bool) is formatted as '1' + or '0'. The base used is binary for $(B b), octal for $(B o), + decimal + for $(B d), and hexadecimal for $(B x) or $(B X). + $(B x) formats using lower case letters, $(B X) uppercase. + If there are fewer resulting digits than the $(I Precision), + leading zeros are used as necessary. + If the $(I Precision) is 0 and the number is 0, no digits + result. -
$(B 'e','E') -
A floating point number is formatted as one digit before - the decimal point, $(I Precision) digits after, the $(I FormatChar), - ±, followed by at least a two digit exponent: $(I d.dddddd)e$(I ±dd). - If there is no $(I Precision), six - digits are generated after the decimal point. - If the $(I Precision) is 0, no decimal point is generated. +
$(B 'e','E') +
A floating point number is formatted as one digit before + the decimal point, $(I Precision) digits after, the $(I FormatChar), + ±, followed by at least a two digit exponent: $(I d.dddddd)e$(I ±dd). + If there is no $(I Precision), six + digits are generated after the decimal point. + If the $(I Precision) is 0, no decimal point is generated. -
$(B 'f','F') -
A floating point number is formatted in decimal notation. - The $(I Precision) specifies the number of digits generated - after the decimal point. It defaults to six. At least one digit - is generated before the decimal point. If the $(I Precision) - is zero, no decimal point is generated. +
$(B 'f','F') +
A floating point number is formatted in decimal notation. + The $(I Precision) specifies the number of digits generated + after the decimal point. It defaults to six. At least one digit + is generated before the decimal point. If the $(I Precision) + is zero, no decimal point is generated. -
$(B 'g','G') -
A floating point number is formatted in either $(B e) or - $(B f) format for $(B g); $(B E) or $(B F) format for - $(B G). - The $(B f) format is used if the exponent for an $(B e) format - is greater than -5 and less than the $(I Precision). - The $(I Precision) specifies the number of significant - digits, and defaults to six. - Trailing zeros are elided after the decimal point, if the fractional - part is zero then no decimal point is generated. +
$(B 'g','G') +
A floating point number is formatted in either $(B e) or + $(B f) format for $(B g); $(B E) or $(B F) format for + $(B G). + The $(B f) format is used if the exponent for an $(B e) format + is greater than -5 and less than the $(I Precision). + The $(I Precision) specifies the number of significant + digits, and defaults to six. + Trailing zeros are elided after the decimal point, if the fractional + part is zero then no decimal point is generated. -
$(B 'a','A') -
A floating point number is formatted in hexadecimal - exponential notation 0x$(I h.hhhhhh)p$(I ±d). - There is one hexadecimal digit before the decimal point, and as - many after as specified by the $(I Precision). - If the $(I Precision) is zero, no decimal point is generated. - If there is no $(I Precision), as many hexadecimal digits as - necessary to exactly represent the mantissa are generated. - The exponent is written in as few digits as possible, - but at least one, is in decimal, and represents a power of 2 as in - $(I h.hhhhhh)*2$(I ±d). - The exponent for zero is zero. - The hexadecimal digits, x and p are in upper case if the - $(I FormatChar) is upper case. +
$(B 'a','A') +
A floating point number is formatted in hexadecimal + exponential notation 0x$(I h.hhhhhh)p$(I ±d). + There is one hexadecimal digit before the decimal point, and as + many after as specified by the $(I Precision). + If the $(I Precision) is zero, no decimal point is generated. + If there is no $(I Precision), as many hexadecimal digits as + necessary to exactly represent the mantissa are generated. + The exponent is written in as few digits as possible, + but at least one, is in decimal, and represents a power of 2 as in + $(I h.hhhhhh)*2$(I ±d). + The exponent for zero is zero. + The hexadecimal digits, x and p are in upper case if the + $(I FormatChar) is upper case.
Floating point NaN's are formatted as $(B nan) if the @@ -431,7 +431,7 @@ void formattedPrint(...) { void putc(char c) { - fputc(c, stdout); + fputc(c, stdout); } std.format.doFormat(&putc, _arguments, _argptr); @@ -455,810 +455,810 @@ void doFormat(void delegate(dchar) putc, TypeInfo[] arguments, va_list argptr) enum : uint { - FLdash = 1, - FLplus = 2, - FLspace = 4, - FLhash = 8, - FLlngdbl = 0x20, - FL0pad = 0x40, - FLprecision = 0x80, + FLdash = 1, + FLplus = 2, + FLspace = 4, + FLhash = 8, + FLlngdbl = 0x20, + FL0pad = 0x40, + FLprecision = 0x80, } static TypeInfo skipCI(TypeInfo valti) { while (1) { - if (valti.classinfo.name.length == 18 && - valti.classinfo.name[9..18] == "Invariant") - valti = (cast(TypeInfo_Invariant)valti).next; - else if (valti.classinfo.name.length == 14 && - valti.classinfo.name[9..14] == "Const") - valti = (cast(TypeInfo_Const)valti).next; - else - break; + if (valti.classinfo.name.length == 18 && + valti.classinfo.name[9..18] == "Invariant") + valti = (cast(TypeInfo_Invariant)valti).next; + else if (valti.classinfo.name.length == 14 && + valti.classinfo.name[9..14] == "Const") + valti = (cast(TypeInfo_Const)valti).next; + else + break; } return valti; } void formatArg(char fc) { - bool vbit; - ulong vnumber; - char vchar; - dchar vdchar; - Object vobject; - real vreal; - creal vcreal; - Mangle m2; - int signed = 0; - uint base = 10; - int uc; - char[ulong.sizeof * 8] tmpbuf; // long enough to print long in binary - char* prefix = ""; - string s; + bool vbit; + ulong vnumber; + char vchar; + dchar vdchar; + Object vobject; + real vreal; + creal vcreal; + Mangle m2; + int signed = 0; + uint base = 10; + int uc; + char[ulong.sizeof * 8] tmpbuf; // long enough to print long in binary + char* prefix = ""; + string s; - void putstr(char[] s) - { - //printf("flags = x%x\n", flags); - int prepad = 0; - int postpad = 0; - int padding = field_width - (strlen(prefix) + toUCSindex(s, s.length)); - if (padding > 0) - { - if (flags & FLdash) - postpad = padding; - else - prepad = padding; - } + void putstr(char[] s) + { + //printf("flags = x%x\n", flags); + int prepad = 0; + int postpad = 0; + int padding = field_width - (strlen(prefix) + toUCSindex(s, s.length)); + if (padding > 0) + { + if (flags & FLdash) + postpad = padding; + else + prepad = padding; + } - if (flags & FL0pad) - { - while (*prefix) - putc(*prefix++); - while (prepad--) - putc('0'); - } - else - { - while (prepad--) - putc(' '); - while (*prefix) - putc(*prefix++); - } + if (flags & FL0pad) + { + while (*prefix) + putc(*prefix++); + while (prepad--) + putc('0'); + } + else + { + while (prepad--) + putc(' '); + while (*prefix) + putc(*prefix++); + } - foreach (dchar c; s) - putc(c); + foreach (dchar c; s) + putc(c); - while (postpad--) - putc(' '); - } + while (postpad--) + putc(' '); + } - void putreal(real v) - { - //printf("putreal %Lg\n", vreal); + void putreal(real v) + { + //printf("putreal %Lg\n", vreal); - switch (fc) - { - case 's': - fc = 'g'; - break; + switch (fc) + { + case 's': + fc = 'g'; + break; - case 'f', 'F', 'e', 'E', 'g', 'G', 'a', 'A': - break; + case 'f', 'F', 'e', 'E', 'g', 'G', 'a', 'A': + break; - default: - //printf("fc = '%c'\n", fc); - Lerror: - throw new FormatError("floating"); - } - version (DigitalMarsC) - { - int sl; - char[] fbuf = tmpbuf; - if (!(flags & FLprecision)) - precision = 6; - while (1) - { - sl = fbuf.length; - prefix = (*__pfloatfmt)(fc, flags | FLlngdbl, - precision, &v, cast(char*)fbuf, &sl, field_width); - if (sl != -1) - break; - sl = fbuf.length * 2; - fbuf = (cast(char*)alloca(sl * char.sizeof))[0 .. sl]; - } - putstr(fbuf[0 .. sl]); - } - else - { - int sl; - char[] fbuf = tmpbuf; - char[12] format; - format[0] = '%'; - int i = 1; - if (flags & FLdash) - format[i++] = '-'; - if (flags & FLplus) - format[i++] = '+'; - if (flags & FLspace) - format[i++] = ' '; - if (flags & FLhash) - format[i++] = '#'; - if (flags & FL0pad) - format[i++] = '0'; - format[i + 0] = '*'; - format[i + 1] = '.'; - format[i + 2] = '*'; - format[i + 3] = 'L'; - format[i + 4] = fc; - format[i + 5] = 0; - if (!(flags & FLprecision)) - precision = -1; - while (1) - { int n; + default: + //printf("fc = '%c'\n", fc); + Lerror: + throw new FormatError("floating"); + } + version (DigitalMarsC) + { + int sl; + char[] fbuf = tmpbuf; + if (!(flags & FLprecision)) + precision = 6; + while (1) + { + sl = fbuf.length; + prefix = (*__pfloatfmt)(fc, flags | FLlngdbl, + precision, &v, cast(char*)fbuf, &sl, field_width); + if (sl != -1) + break; + sl = fbuf.length * 2; + fbuf = (cast(char*)alloca(sl * char.sizeof))[0 .. sl]; + } + putstr(fbuf[0 .. sl]); + } + else + { + int sl; + char[] fbuf = tmpbuf; + char[12] format; + format[0] = '%'; + int i = 1; + if (flags & FLdash) + format[i++] = '-'; + if (flags & FLplus) + format[i++] = '+'; + if (flags & FLspace) + format[i++] = ' '; + if (flags & FLhash) + format[i++] = '#'; + if (flags & FL0pad) + format[i++] = '0'; + format[i + 0] = '*'; + format[i + 1] = '.'; + format[i + 2] = '*'; + format[i + 3] = 'L'; + format[i + 4] = fc; + format[i + 5] = 0; + if (!(flags & FLprecision)) + precision = -1; + while (1) + { int n; - sl = fbuf.length; - n = snprintf(fbuf.ptr, sl, format.ptr, field_width, precision, v); - //printf("format = '%s', n = %d\n", cast(char*)format, n); - if (n >= 0 && n < sl) - { sl = n; - break; - } - if (n < 0) - sl = sl * 2; - else - sl = n + 1; - fbuf = (cast(char*)alloca(sl * char.sizeof))[0 .. sl]; - } - putstr(fbuf[0 .. sl]); - } - return; - } + sl = fbuf.length; + n = snprintf(fbuf.ptr, sl, format.ptr, field_width, precision, v); + //printf("format = '%s', n = %d\n", cast(char*)format, n); + if (n >= 0 && n < sl) + { sl = n; + break; + } + if (n < 0) + sl = sl * 2; + else + sl = n + 1; + fbuf = (cast(char*)alloca(sl * char.sizeof))[0 .. sl]; + } + putstr(fbuf[0 .. sl]); + } + return; + } - static Mangle getMan(TypeInfo ti) - { - auto m = cast(Mangle)ti.classinfo.name[9]; - if (ti.classinfo.name.length == 20 && - ti.classinfo.name[9..20] == "StaticArray") - m = cast(Mangle)'G'; - return m; - } + static Mangle getMan(TypeInfo ti) + { + auto m = cast(Mangle)ti.classinfo.name[9]; + if (ti.classinfo.name.length == 20 && + ti.classinfo.name[9..20] == "StaticArray") + m = cast(Mangle)'G'; + return m; + } - void putArray(void* p, size_t len, TypeInfo valti) - { - //printf("\nputArray(len = %u), tsize = %u\n", len, valti.tsize()); - putc('['); - valti = skipCI(valti); - size_t tsize = valti.tsize(); - auto argptrSave = argptr; - auto tiSave = ti; - auto mSave = m; - ti = valti; - //printf("\n%.*s\n", valti.classinfo.name); - m = getMan(valti); - while (len--) - { - //doFormat(putc, (&valti)[0 .. 1], p); - argptr = p; - formatArg('s'); + void putArray(void* p, size_t len, TypeInfo valti) + { + //printf("\nputArray(len = %u), tsize = %u\n", len, valti.tsize()); + putc('['); + valti = skipCI(valti); + size_t tsize = valti.tsize(); + auto argptrSave = argptr; + auto tiSave = ti; + auto mSave = m; + ti = valti; + //printf("\n%.*s\n", valti.classinfo.name); + m = getMan(valti); + while (len--) + { + //doFormat(putc, (&valti)[0 .. 1], p); + argptr = p; + formatArg('s'); - p += tsize; - if (len > 0) putc(','); - } - m = mSave; - ti = tiSave; - argptr = argptrSave; - putc(']'); - } + p += tsize; + if (len > 0) putc(','); + } + m = mSave; + ti = tiSave; + argptr = argptrSave; + putc(']'); + } - void putAArray(ubyte[long] vaa, TypeInfo valti, TypeInfo keyti) - { - putc('['); - bool comma=false; - auto argptrSave = argptr; - auto tiSave = ti; - auto mSave = m; - valti = skipCI(valti); - keyti = skipCI(keyti); - foreach(inout fakevalue; vaa) - { - if (comma) putc(','); - comma = true; - // the key comes before the value - ubyte* key = &fakevalue - long.sizeof; + void putAArray(ubyte[long] vaa, TypeInfo valti, TypeInfo keyti) + { + putc('['); + bool comma=false; + auto argptrSave = argptr; + auto tiSave = ti; + auto mSave = m; + valti = skipCI(valti); + keyti = skipCI(keyti); + foreach(inout fakevalue; vaa) + { + if (comma) putc(','); + comma = true; + // the key comes before the value + ubyte* key = &fakevalue - long.sizeof; - //doFormat(putc, (&keyti)[0..1], key); - argptr = key; - ti = keyti; - m = getMan(keyti); - formatArg('s'); + //doFormat(putc, (&keyti)[0..1], key); + argptr = key; + ti = keyti; + m = getMan(keyti); + formatArg('s'); - putc(':'); - auto keysize = keyti.tsize; - keysize = (keysize + 3) & ~3; - ubyte* value = key + keysize; - //doFormat(putc, (&valti)[0..1], value); - argptr = value; - ti = valti; - m = getMan(valti); - formatArg('s'); - } - m = mSave; - ti = tiSave; - argptr = argptrSave; - putc(']'); - } + putc(':'); + auto keysize = keyti.tsize; + keysize = (keysize + 3) & ~3; + ubyte* value = key + keysize; + //doFormat(putc, (&valti)[0..1], value); + argptr = value; + ti = valti; + m = getMan(valti); + formatArg('s'); + } + m = mSave; + ti = tiSave; + argptr = argptrSave; + putc(']'); + } - //printf("formatArg(fc = '%c', m = '%c')\n", fc, m); - switch (m) - { - case Mangle.Tbool: - vbit = va_arg!(bool)(argptr); - if (fc != 's') - { vnumber = vbit; - goto Lnumber; - } - putstr(vbit ? "true" : "false"); - return; + //printf("formatArg(fc = '%c', m = '%c')\n", fc, m); + switch (m) + { + case Mangle.Tbool: + vbit = va_arg!(bool)(argptr); + if (fc != 's') + { vnumber = vbit; + goto Lnumber; + } + putstr(vbit ? "true" : "false"); + return; - case Mangle.Tchar: - vchar = va_arg!(char)(argptr); - if (fc != 's') - { vnumber = vchar; - goto Lnumber; - } - L2: - putstr((&vchar)[0 .. 1]); - return; + case Mangle.Tchar: + vchar = va_arg!(char)(argptr); + if (fc != 's') + { vnumber = vchar; + goto Lnumber; + } + L2: + putstr((&vchar)[0 .. 1]); + return; - case Mangle.Twchar: - vdchar = va_arg!(wchar)(argptr); - goto L1; + case Mangle.Twchar: + vdchar = va_arg!(wchar)(argptr); + goto L1; - case Mangle.Tdchar: - vdchar = va_arg!(dchar)(argptr); - L1: - if (fc != 's') - { vnumber = vdchar; - goto Lnumber; - } - if (vdchar <= 0x7F) - { vchar = cast(char)vdchar; - goto L2; - } - else - { if (!isValidDchar(vdchar)) - throw new UtfException("invalid dchar in format", 0); - char[4] vbuf; - putstr(toUTF8(vbuf, vdchar)); - } - return; + case Mangle.Tdchar: + vdchar = va_arg!(dchar)(argptr); + L1: + if (fc != 's') + { vnumber = vdchar; + goto Lnumber; + } + if (vdchar <= 0x7F) + { vchar = cast(char)vdchar; + goto L2; + } + else + { if (!isValidDchar(vdchar)) + throw new UtfException("invalid dchar in format", 0); + char[4] vbuf; + putstr(toUTF8(vbuf, vdchar)); + } + return; - case Mangle.Tbyte: - signed = 1; - vnumber = va_arg!(byte)(argptr); - goto Lnumber; + case Mangle.Tbyte: + signed = 1; + vnumber = va_arg!(byte)(argptr); + goto Lnumber; - case Mangle.Tubyte: - vnumber = va_arg!(ubyte)(argptr); - goto Lnumber; + case Mangle.Tubyte: + vnumber = va_arg!(ubyte)(argptr); + goto Lnumber; - case Mangle.Tshort: - signed = 1; - vnumber = va_arg!(short)(argptr); - goto Lnumber; + case Mangle.Tshort: + signed = 1; + vnumber = va_arg!(short)(argptr); + goto Lnumber; - case Mangle.Tushort: - vnumber = va_arg!(ushort)(argptr); - goto Lnumber; + case Mangle.Tushort: + vnumber = va_arg!(ushort)(argptr); + goto Lnumber; - case Mangle.Tint: - signed = 1; - vnumber = va_arg!(int)(argptr); - goto Lnumber; + case Mangle.Tint: + signed = 1; + vnumber = va_arg!(int)(argptr); + goto Lnumber; - case Mangle.Tuint: - Luint: - vnumber = va_arg!(uint)(argptr); - goto Lnumber; + case Mangle.Tuint: + Luint: + vnumber = va_arg!(uint)(argptr); + goto Lnumber; - case Mangle.Tlong: - signed = 1; - vnumber = cast(ulong)va_arg!(long)(argptr); - goto Lnumber; + case Mangle.Tlong: + signed = 1; + vnumber = cast(ulong)va_arg!(long)(argptr); + goto Lnumber; - case Mangle.Tulong: - Lulong: - vnumber = va_arg!(ulong)(argptr); - goto Lnumber; + case Mangle.Tulong: + Lulong: + vnumber = va_arg!(ulong)(argptr); + goto Lnumber; - case Mangle.Tclass: - vobject = va_arg!(Object)(argptr); - if (vobject is null) - s = "null"; - else - s = vobject.toString(); - goto Lputstr; + case Mangle.Tclass: + vobject = va_arg!(Object)(argptr); + if (vobject is null) + s = "null"; + else + s = vobject.toString(); + goto Lputstr; - case Mangle.Tpointer: - vnumber = cast(ulong)va_arg!(void*)(argptr); - if (fc != 'x' && fc != 'X') uc = 1; - flags |= FL0pad; - if (!(flags & FLprecision)) - { flags |= FLprecision; - precision = (void*).sizeof; - } - base = 16; - goto Lnumber; + case Mangle.Tpointer: + vnumber = cast(ulong)va_arg!(void*)(argptr); + if (fc != 'x' && fc != 'X') uc = 1; + flags |= FL0pad; + if (!(flags & FLprecision)) + { flags |= FLprecision; + precision = (void*).sizeof; + } + base = 16; + goto Lnumber; - case Mangle.Tfloat: - case Mangle.Tifloat: - if (fc == 'x' || fc == 'X') - goto Luint; - vreal = va_arg!(float)(argptr); - goto Lreal; + case Mangle.Tfloat: + case Mangle.Tifloat: + if (fc == 'x' || fc == 'X') + goto Luint; + vreal = va_arg!(float)(argptr); + goto Lreal; - case Mangle.Tdouble: - case Mangle.Tidouble: - if (fc == 'x' || fc == 'X') - goto Lulong; - vreal = va_arg!(double)(argptr); - goto Lreal; + case Mangle.Tdouble: + case Mangle.Tidouble: + if (fc == 'x' || fc == 'X') + goto Lulong; + vreal = va_arg!(double)(argptr); + goto Lreal; - case Mangle.Treal: - case Mangle.Tireal: - vreal = va_arg!(real)(argptr); - goto Lreal; + case Mangle.Treal: + case Mangle.Tireal: + vreal = va_arg!(real)(argptr); + goto Lreal; - case Mangle.Tcfloat: - vcreal = va_arg!(cfloat)(argptr); - goto Lcomplex; + case Mangle.Tcfloat: + vcreal = va_arg!(cfloat)(argptr); + goto Lcomplex; - case Mangle.Tcdouble: - vcreal = va_arg!(cdouble)(argptr); - goto Lcomplex; + case Mangle.Tcdouble: + vcreal = va_arg!(cdouble)(argptr); + goto Lcomplex; - case Mangle.Tcreal: - vcreal = va_arg!(creal)(argptr); - goto Lcomplex; + case Mangle.Tcreal: + vcreal = va_arg!(creal)(argptr); + goto Lcomplex; - case Mangle.Tsarray: - putArray(argptr, (cast(TypeInfo_StaticArray)ti).len, (cast(TypeInfo_StaticArray)ti).next); - return; + case Mangle.Tsarray: + putArray(argptr, (cast(TypeInfo_StaticArray)ti).len, (cast(TypeInfo_StaticArray)ti).next); + return; - case Mangle.Tarray: - int mi = 10; - if (ti.classinfo.name.length == 14 && - ti.classinfo.name[9..14] == "Array") - { // array of non-primitive types - TypeInfo tn = (cast(TypeInfo_Array)ti).next; - tn = skipCI(tn); - switch (cast(Mangle)tn.classinfo.name[9]) - { - case Mangle.Tchar: goto LarrayChar; - case Mangle.Twchar: goto LarrayWchar; - case Mangle.Tdchar: goto LarrayDchar; - default: - break; - } - void[] va = va_arg!(void[])(argptr); - putArray(va.ptr, va.length, tn); - return; - } - if (ti.classinfo.name.length == 25 && - ti.classinfo.name[9..25] == "AssociativeArray") - { // associative array - ubyte[long] vaa = va_arg!(ubyte[long])(argptr); - putAArray(vaa, - (cast(TypeInfo_AssociativeArray)ti).next, - (cast(TypeInfo_AssociativeArray)ti).key); - return; - } + case Mangle.Tarray: + int mi = 10; + if (ti.classinfo.name.length == 14 && + ti.classinfo.name[9..14] == "Array") + { // array of non-primitive types + TypeInfo tn = (cast(TypeInfo_Array)ti).next; + tn = skipCI(tn); + switch (cast(Mangle)tn.classinfo.name[9]) + { + case Mangle.Tchar: goto LarrayChar; + case Mangle.Twchar: goto LarrayWchar; + case Mangle.Tdchar: goto LarrayDchar; + default: + break; + } + void[] va = va_arg!(void[])(argptr); + putArray(va.ptr, va.length, tn); + return; + } + if (ti.classinfo.name.length == 25 && + ti.classinfo.name[9..25] == "AssociativeArray") + { // associative array + ubyte[long] vaa = va_arg!(ubyte[long])(argptr); + putAArray(vaa, + (cast(TypeInfo_AssociativeArray)ti).next, + (cast(TypeInfo_AssociativeArray)ti).key); + return; + } - while (1) - { - m2 = cast(Mangle)ti.classinfo.name[mi]; - switch (m2) - { - case Mangle.Tchar: - LarrayChar: - s = va_arg!(string)(argptr); - goto Lputstr; + while (1) + { + m2 = cast(Mangle)ti.classinfo.name[mi]; + switch (m2) + { + case Mangle.Tchar: + LarrayChar: + s = va_arg!(string)(argptr); + goto Lputstr; - case Mangle.Twchar: - LarrayWchar: - wchar[] sw = va_arg!(wstring)(argptr); - s = toUTF8(sw); - goto Lputstr; + case Mangle.Twchar: + LarrayWchar: + wchar[] sw = va_arg!(wstring)(argptr); + s = toUTF8(sw); + goto Lputstr; - case Mangle.Tdchar: - LarrayDchar: - dchar[] sd = va_arg!(dstring)(argptr); - s = toUTF8(sd); - Lputstr: - if (fc != 's') - throw new FormatError("string"); - if (flags & FLprecision && precision < s.length) - s = s[0 .. precision]; - putstr(s); - break; + case Mangle.Tdchar: + LarrayDchar: + dchar[] sd = va_arg!(dstring)(argptr); + s = toUTF8(sd); + Lputstr: + if (fc != 's') + throw new FormatError("string"); + if (flags & FLprecision && precision < s.length) + s = s[0 .. precision]; + putstr(s); + break; - case Mangle.Tconst: - case Mangle.Tinvariant: - mi++; - continue; + case Mangle.Tconst: + case Mangle.Tinvariant: + mi++; + continue; - default: - TypeInfo ti2 = primitiveTypeInfo(m2); - if (!ti2) - goto Lerror; - void[] va = va_arg!(void[])(argptr); - putArray(va.ptr, va.length, ti2); - } - return; - } + default: + TypeInfo ti2 = primitiveTypeInfo(m2); + if (!ti2) + goto Lerror; + void[] va = va_arg!(void[])(argptr); + putArray(va.ptr, va.length, ti2); + } + return; + } - case Mangle.Ttypedef: - ti = (cast(TypeInfo_Typedef)ti).base; - m = cast(Mangle)ti.classinfo.name[9]; - formatArg(fc); - return; + case Mangle.Ttypedef: + ti = (cast(TypeInfo_Typedef)ti).base; + m = cast(Mangle)ti.classinfo.name[9]; + formatArg(fc); + return; - case Mangle.Tenum: - ti = (cast(TypeInfo_Enum)ti).base; - m = cast(Mangle)ti.classinfo.name[9]; - formatArg(fc); - return; + case Mangle.Tenum: + ti = (cast(TypeInfo_Enum)ti).base; + m = cast(Mangle)ti.classinfo.name[9]; + formatArg(fc); + return; - case Mangle.Tstruct: - { TypeInfo_Struct tis = cast(TypeInfo_Struct)ti; - if (tis.xtoString is null) - throw new FormatError("Can't convert " ~ tis.toString() ~ " to string: \"string toString()\" not defined"); - s = tis.xtoString(argptr); - argptr += (tis.tsize() + 3) & ~3; - goto Lputstr; - } + case Mangle.Tstruct: + { TypeInfo_Struct tis = cast(TypeInfo_Struct)ti; + if (tis.xtoString is null) + throw new FormatError("Can't convert " ~ tis.toString() ~ " to string: \"string toString()\" not defined"); + s = tis.xtoString(argptr); + argptr += (tis.tsize() + 3) & ~3; + goto Lputstr; + } - default: - goto Lerror; - } + default: + goto Lerror; + } Lnumber: - switch (fc) - { - case 's': - case 'd': - if (signed) - { if (cast(long)vnumber < 0) - { prefix = "-"; - vnumber = -vnumber; - } - else if (flags & FLplus) - prefix = "+"; - else if (flags & FLspace) - prefix = " "; - } - break; + switch (fc) + { + case 's': + case 'd': + if (signed) + { if (cast(long)vnumber < 0) + { prefix = "-"; + vnumber = -vnumber; + } + else if (flags & FLplus) + prefix = "+"; + else if (flags & FLspace) + prefix = " "; + } + break; - case 'b': - signed = 0; - base = 2; - break; + case 'b': + signed = 0; + base = 2; + break; - case 'o': - signed = 0; - base = 8; - break; + case 'o': + signed = 0; + base = 8; + break; - case 'X': - uc = 1; - if (flags & FLhash && vnumber) - prefix = "0X"; - signed = 0; - base = 16; - break; + case 'X': + uc = 1; + if (flags & FLhash && vnumber) + prefix = "0X"; + signed = 0; + base = 16; + break; - case 'x': - if (flags & FLhash && vnumber) - prefix = "0x"; - signed = 0; - base = 16; - break; + case 'x': + if (flags & FLhash && vnumber) + prefix = "0x"; + signed = 0; + base = 16; + break; - default: - goto Lerror; - } + default: + goto Lerror; + } - if (!signed) - { - switch (m) - { - case Mangle.Tbyte: - vnumber &= 0xFF; - break; + if (!signed) + { + switch (m) + { + case Mangle.Tbyte: + vnumber &= 0xFF; + break; - case Mangle.Tshort: - vnumber &= 0xFFFF; - break; + case Mangle.Tshort: + vnumber &= 0xFFFF; + break; - case Mangle.Tint: - vnumber &= 0xFFFFFFFF; - break; + case Mangle.Tint: + vnumber &= 0xFFFFFFFF; + break; - default: - break; - } - } + default: + break; + } + } - if (flags & FLprecision && fc != 'p') - flags &= ~FL0pad; + if (flags & FLprecision && fc != 'p') + flags &= ~FL0pad; - if (vnumber < base) - { - if (vnumber == 0 && precision == 0 && flags & FLprecision && - !(fc == 'o' && flags & FLhash)) - { - putstr(null); - return; - } - if (precision == 0 || !(flags & FLprecision)) - { vchar = cast(char)('0' + vnumber); - if (vnumber < 10) - vchar = cast(char)('0' + vnumber); - else - vchar = cast(char)((uc ? 'A' - 10 : 'a' - 10) + vnumber); - goto L2; - } - } + if (vnumber < base) + { + if (vnumber == 0 && precision == 0 && flags & FLprecision && + !(fc == 'o' && flags & FLhash)) + { + putstr(null); + return; + } + if (precision == 0 || !(flags & FLprecision)) + { vchar = cast(char)('0' + vnumber); + if (vnumber < 10) + vchar = cast(char)('0' + vnumber); + else + vchar = cast(char)((uc ? 'A' - 10 : 'a' - 10) + vnumber); + goto L2; + } + } - int n = tmpbuf.length; - char c; - int hexoffset = uc ? ('A' - ('9' + 1)) : ('a' - ('9' + 1)); + int n = tmpbuf.length; + char c; + int hexoffset = uc ? ('A' - ('9' + 1)) : ('a' - ('9' + 1)); - while (vnumber) - { - c = cast(char)((vnumber % base) + '0'); - if (c > '9') - c += hexoffset; - vnumber /= base; - tmpbuf[--n] = c; - } - if (tmpbuf.length - n < precision && precision < tmpbuf.length) - { - int m = tmpbuf.length - precision; - tmpbuf[m .. n] = '0'; - n = m; - } - else if (flags & FLhash && fc == 'o') - prefix = "0"; - putstr(tmpbuf[n .. tmpbuf.length]); - return; + while (vnumber) + { + c = cast(char)((vnumber % base) + '0'); + if (c > '9') + c += hexoffset; + vnumber /= base; + tmpbuf[--n] = c; + } + if (tmpbuf.length - n < precision && precision < tmpbuf.length) + { + int m = tmpbuf.length - precision; + tmpbuf[m .. n] = '0'; + n = m; + } + else if (flags & FLhash && fc == 'o') + prefix = "0"; + putstr(tmpbuf[n .. tmpbuf.length]); + return; Lreal: - putreal(vreal); - return; + putreal(vreal); + return; Lcomplex: - putreal(vcreal.re); - putc('+'); - putreal(vcreal.im); - putc('i'); - return; + putreal(vcreal.re); + putc('+'); + putreal(vcreal.im); + putc('i'); + return; Lerror: - throw new FormatError("formatArg"); + throw new FormatError("formatArg"); } for (j = 0; j < arguments.length; ) - { ti = arguments[j++]; - //printf("test1: '%.*s' %d\n", ti.classinfo.name, ti.classinfo.name.length); - //ti.print(); + { ti = arguments[j++]; + //printf("test1: '%.*s' %d\n", ti.classinfo.name, ti.classinfo.name.length); + //ti.print(); - flags = 0; - precision = 0; - field_width = 0; + flags = 0; + precision = 0; + field_width = 0; - ti = skipCI(ti); - int mi = 9; - do - { - if (ti.classinfo.name.length <= mi) - goto Lerror; - m = cast(Mangle)ti.classinfo.name[mi++]; - } while (m == Mangle.Tconst || m == Mangle.Tinvariant); + ti = skipCI(ti); + int mi = 9; + do + { + if (ti.classinfo.name.length <= mi) + goto Lerror; + m = cast(Mangle)ti.classinfo.name[mi++]; + } while (m == Mangle.Tconst || m == Mangle.Tinvariant); - if (m == Mangle.Tarray) - { - if (ti.classinfo.name.length == 14 && - ti.classinfo.name[9..14] == "Array") - { - TypeInfo tn = (cast(TypeInfo_Array)ti).next; - tn = skipCI(tn); - switch (cast(Mangle)tn.classinfo.name[9]) - { - case Mangle.Tchar: - case Mangle.Twchar: - case Mangle.Tdchar: - ti = tn; - mi = 9; - break; - default: - break; - } - } - L1: - Mangle m2 = cast(Mangle)ti.classinfo.name[mi]; - string fmt; // format string - wstring wfmt; - dstring dfmt; + if (m == Mangle.Tarray) + { + if (ti.classinfo.name.length == 14 && + ti.classinfo.name[9..14] == "Array") + { + TypeInfo tn = (cast(TypeInfo_Array)ti).next; + tn = skipCI(tn); + switch (cast(Mangle)tn.classinfo.name[9]) + { + case Mangle.Tchar: + case Mangle.Twchar: + case Mangle.Tdchar: + ti = tn; + mi = 9; + break; + default: + break; + } + } + L1: + Mangle m2 = cast(Mangle)ti.classinfo.name[mi]; + string fmt; // format string + wstring wfmt; + dstring dfmt; - /* For performance reasons, this code takes advantage of the - * fact that most format strings will be ASCII, and that the - * format specifiers are always ASCII. This means we only need - * to deal with UTF in a couple of isolated spots. - */ + /* For performance reasons, this code takes advantage of the + * fact that most format strings will be ASCII, and that the + * format specifiers are always ASCII. This means we only need + * to deal with UTF in a couple of isolated spots. + */ - switch (m2) - { - case Mangle.Tchar: - fmt = va_arg!(string)(argptr); - break; + switch (m2) + { + case Mangle.Tchar: + fmt = va_arg!(string)(argptr); + break; - case Mangle.Twchar: - wfmt = va_arg!(wstring)(argptr); - fmt = toUTF8(wfmt); - break; + case Mangle.Twchar: + wfmt = va_arg!(wstring)(argptr); + fmt = toUTF8(wfmt); + break; - case Mangle.Tdchar: - dfmt = va_arg!(dstring)(argptr); - fmt = toUTF8(dfmt); - break; + case Mangle.Tdchar: + dfmt = va_arg!(dstring)(argptr); + fmt = toUTF8(dfmt); + break; - case Mangle.Tconst: - case Mangle.Tinvariant: - mi++; - goto L1; + case Mangle.Tconst: + case Mangle.Tinvariant: + mi++; + goto L1; - default: - formatArg('s'); - continue; - } + default: + formatArg('s'); + continue; + } - for (size_t i = 0; i < fmt.length; ) - { dchar c = fmt[i++]; + for (size_t i = 0; i < fmt.length; ) + { dchar c = fmt[i++]; - dchar getFmtChar() - { // Valid format specifier characters will never be UTF - if (i == fmt.length) - throw new FormatError("invalid specifier"); - return fmt[i++]; - } + dchar getFmtChar() + { // Valid format specifier characters will never be UTF + if (i == fmt.length) + throw new FormatError("invalid specifier"); + return fmt[i++]; + } - int getFmtInt() - { int n; + int getFmtInt() + { int n; - while (1) - { - n = n * 10 + (c - '0'); - if (n < 0) // overflow - throw new FormatError("int overflow"); - c = getFmtChar(); - if (c < '0' || c > '9') - break; - } - return n; - } + while (1) + { + n = n * 10 + (c - '0'); + if (n < 0) // overflow + throw new FormatError("int overflow"); + c = getFmtChar(); + if (c < '0' || c > '9') + break; + } + return n; + } - int getFmtStar() - { Mangle m; - TypeInfo ti; + int getFmtStar() + { Mangle m; + TypeInfo ti; - if (j == arguments.length) - throw new FormatError("too few arguments"); - ti = arguments[j++]; - m = cast(Mangle)ti.classinfo.name[9]; - if (m != Mangle.Tint) - throw new FormatError("int argument expected"); - return va_arg!(int)(argptr); - } + if (j == arguments.length) + throw new FormatError("too few arguments"); + ti = arguments[j++]; + m = cast(Mangle)ti.classinfo.name[9]; + if (m != Mangle.Tint) + throw new FormatError("int argument expected"); + return va_arg!(int)(argptr); + } - if (c != '%') - { - if (c > 0x7F) // if UTF sequence - { - i--; // back up and decode UTF sequence - c = std.utf.decode(fmt, i); - } - Lputc: - putc(c); - continue; - } + if (c != '%') + { + if (c > 0x7F) // if UTF sequence + { + i--; // back up and decode UTF sequence + c = std.utf.decode(fmt, i); + } + Lputc: + putc(c); + continue; + } - // Get flags {-+ #} - flags = 0; - while (1) - { - c = getFmtChar(); - switch (c) - { - case '-': flags |= FLdash; continue; - case '+': flags |= FLplus; continue; - case ' ': flags |= FLspace; continue; - case '#': flags |= FLhash; continue; - case '0': flags |= FL0pad; continue; + // Get flags {-+ #} + flags = 0; + while (1) + { + c = getFmtChar(); + switch (c) + { + case '-': flags |= FLdash; continue; + case '+': flags |= FLplus; continue; + case ' ': flags |= FLspace; continue; + case '#': flags |= FLhash; continue; + case '0': flags |= FL0pad; continue; - case '%': if (flags == 0) - goto Lputc; - default: break; - } - break; - } + case '%': if (flags == 0) + goto Lputc; + default: break; + } + break; + } - // Get field width - field_width = 0; - if (c == '*') - { - field_width = getFmtStar(); - if (field_width < 0) - { flags |= FLdash; - field_width = -field_width; - } + // Get field width + field_width = 0; + if (c == '*') + { + field_width = getFmtStar(); + if (field_width < 0) + { flags |= FLdash; + field_width = -field_width; + } - c = getFmtChar(); - } - else if (c >= '0' && c <= '9') - field_width = getFmtInt(); + c = getFmtChar(); + } + else if (c >= '0' && c <= '9') + field_width = getFmtInt(); - if (flags & FLplus) - flags &= ~FLspace; - if (flags & FLdash) - flags &= ~FL0pad; + if (flags & FLplus) + flags &= ~FLspace; + if (flags & FLdash) + flags &= ~FL0pad; - // Get precision - precision = 0; - if (c == '.') - { flags |= FLprecision; - //flags &= ~FL0pad; + // Get precision + precision = 0; + if (c == '.') + { flags |= FLprecision; + //flags &= ~FL0pad; - c = getFmtChar(); - if (c == '*') - { - precision = getFmtStar(); - if (precision < 0) - { precision = 0; - flags &= ~FLprecision; - } + c = getFmtChar(); + if (c == '*') + { + precision = getFmtStar(); + if (precision < 0) + { precision = 0; + flags &= ~FLprecision; + } - c = getFmtChar(); - } - else if (c >= '0' && c <= '9') - precision = getFmtInt(); - } + c = getFmtChar(); + } + else if (c >= '0' && c <= '9') + precision = getFmtInt(); + } - if (j == arguments.length) - goto Lerror; - ti = arguments[j++]; - ti = skipCI(ti); - mi = 9; - do - { - m = cast(Mangle)ti.classinfo.name[mi++]; - } while (m == Mangle.Tconst || m == Mangle.Tinvariant); + if (j == arguments.length) + goto Lerror; + ti = arguments[j++]; + ti = skipCI(ti); + mi = 9; + do + { + m = cast(Mangle)ti.classinfo.name[mi++]; + } while (m == Mangle.Tconst || m == Mangle.Tinvariant); - if (c > 0x7F) // if UTF sequence - goto Lerror; // format specifiers can't be UTF - formatArg(cast(char)c); - } - } - else - { - formatArg('s'); - } + if (c > 0x7F) // if UTF sequence + goto Lerror; // format specifiers can't be UTF + formatArg(cast(char)c); + } + } + else + { + formatArg('s'); + } } return; @@ -1274,7 +1274,7 @@ unittest string s; debug(format) printf("std.format.format.unittest\n"); - + s = std.string.format("hello world! %s %s ", true, 57, 1_000_000_000, 'x', " foo"); assert(s == "hello world! true 57 1000000000x foo"); @@ -1284,9 +1284,9 @@ unittest * is for %A. */ version (Posix) - assert(s == "1.67 -0XA.3D70A3D70A3D8P-3 nan"); + assert(s == "1.67 -0XA.3D70A3D70A3D8P-3 nan"); else - assert(s == "1.67 -0X1.47AE147AE147BP+0 nan"); + assert(s == "1.67 -0X1.47AE147AE147BP+0 nan"); s = std.string.format("%x %X", 0x1234AF, 0xAFAFAFAF); assert(s == "1234af AFAFAFAF"); @@ -1532,7 +1532,7 @@ unittest enum TestEnum { - Value1, Value2 + Value1, Value2 } r = std.string.format("%s", TestEnum.Value2); assert(r == "1"); @@ -1546,11 +1546,11 @@ unittest static const dchar[] ds = ['a','b']; for (int j = 0; j < ds.length; ++j) { - r = std.string.format(" %d", ds[j]); - if (j == 0) - assert(r == " 97"); - else - assert(r == " 98"); + r = std.string.format(" %d", ds[j]); + if (j == 0) + assert(r == " 97"); + else + assert(r == " 98"); } r = std.string.format(">%14d<, ", 15, [1,2,3]); diff --git a/std/loader.d b/std/loader.d index e7cc3ddfa..9022066c0 100644 --- a/std/loader.d +++ b/std/loader.d @@ -36,7 +36,7 @@ -/** \file D/std/loader.d This file contains the \c D standard library +/** \file D/std/loader.d This file contains the \c D standard library * executable module loader library, and the ExeModule class. */ @@ -78,14 +78,14 @@ else version(Posix) extern(C) { - alias void* HModule_; + alias void* HModule_; } } else { - const int platform_not_discriminated = 0; + const int platform_not_discriminated = 0; - static assert(platform_not_discriminated); + static assert(platform_not_discriminated); } /** The platform-independent module handle. Note that this has to be @@ -106,7 +106,7 @@ typedef void *HXModule; /** ExeModule library Initialisation * - * \retval <0 Initialisation failed. Processing must gracefully terminate, + * \retval <0 Initialisation failed. Processing must gracefully terminate, * without making any use of the ExeModule library * \retval 0 Initialisation succeeded for the first time. Any necessary resources * were successfully allocated @@ -122,7 +122,7 @@ public void ExeModule_Uninit() ExeModule_Uninit_(); } -/** +/** * * \note The value of the handle returned may not be a valid handle for your operating * system, and you must not attempt to use it with any other operating system @@ -239,20 +239,20 @@ version(Windows) private string ExeModule_Error_() { - return sysErrorString(s_lastError); + return sysErrorString(s_lastError); } private string ExeModule_GetPath_(HXModule hModule) { char szFileName[260]; // Need to use a constant here - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getmodulefilename.asp + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getmodulefilename.asp uint cch = GetModuleFileNameA(cast(HModule_)hModule, szFileName.ptr, szFileName.length); - if (cch == 0) - { + if (cch == 0) + { record_error_(); - } + } return szFileName[0 .. cch].dup; } } @@ -308,8 +308,8 @@ else version(Posix) } body { - ExeModuleInfo* mi_p = moduleName in s_modules; - ExeModuleInfo mi = mi_p is null ? null : *mi_p; + ExeModuleInfo* mi_p = moduleName in s_modules; + ExeModuleInfo mi = mi_p is null ? null : *mi_p; if(null !is mi) { @@ -448,9 +448,9 @@ else version(Posix) } else { - const int platform_not_discriminated = 0; + const int platform_not_discriminated = 0; - static assert(platform_not_discriminated); + static assert(platform_not_discriminated); } /* ///////////////////////////////////////////////////////////////////////////// @@ -470,12 +470,12 @@ public: { version (Posix) { - char[80] buf = void; - super(std.string.toString(strerror_r(errcode, buf.ptr, buf.length)).dup); + char[80] buf = void; + super(std.string.toString(strerror_r(errcode, buf.ptr, buf.length)).dup); } else { - super(std.string.toString(strerror(errcode)).dup); + super(std.string.toString(strerror(errcode)).dup); } } } @@ -500,19 +500,19 @@ public: } else { - version (Windows) - { - string path = Path(); - m_hModule = cast(HXModule)LoadLibraryA(toStringz(path)); - if (m_hModule == null) - throw new ExeModuleException(GetLastError()); - } - else version (Posix) - { - m_hModule = ExeModule_AddRef(hModule); - } - else - static assert(0); + version (Windows) + { + string path = Path(); + m_hModule = cast(HXModule)LoadLibraryA(toStringz(path)); + if (m_hModule == null) + throw new ExeModuleException(GetLastError()); + } + else version (Posix) + { + m_hModule = ExeModule_AddRef(hModule); + } + else + static assert(0); } } @@ -523,22 +523,22 @@ public: } body { - version (Windows) - { - m_hModule = cast(HXModule)LoadLibraryA(toStringz(moduleName)); - if (null is m_hModule) - throw new ExeModuleException(GetLastError()); - } - else version (Posix) - { - m_hModule = ExeModule_Load(moduleName); - if (null is m_hModule) - throw new ExeModuleException(ExeModule_Error()); - } - else - { - static assert(0); // unsupported system - } + version (Windows) + { + m_hModule = cast(HXModule)LoadLibraryA(toStringz(moduleName)); + if (null is m_hModule) + throw new ExeModuleException(GetLastError()); + } + else version (Posix) + { + m_hModule = ExeModule_Load(moduleName); + if (null is m_hModule) + throw new ExeModuleException(ExeModule_Error()); + } + else + { + static assert(0); // unsupported system + } } ~this() { @@ -557,17 +557,17 @@ public: { if(null !is m_hModule) { - version (Windows) - { - if(!FreeLibrary(cast(HModule_)m_hModule)) - throw new ExeModuleException(GetLastError()); - } - else version (Posix) - { - ExeModule_Release(m_hModule); - } - else - static assert(0); + version (Windows) + { + if(!FreeLibrary(cast(HModule_)m_hModule)) + throw new ExeModuleException(GetLastError()); + } + else version (Posix) + { + ExeModule_Release(m_hModule); + } + else + static assert(0); } } /// @} @@ -582,27 +582,27 @@ public: */ void *getSymbol(in string symbolName) { - version (Windows) - { - void *symbol = GetProcAddress(cast(HModule_)m_hModule, toStringz(symbolName)); - if(null is symbol) - { - throw new ExeModuleException(GetLastError()); - } - } - else version (Posix) - { - void *symbol = ExeModule_GetSymbol(m_hModule, symbolName); + version (Windows) + { + void *symbol = GetProcAddress(cast(HModule_)m_hModule, toStringz(symbolName)); + if(null is symbol) + { + throw new ExeModuleException(GetLastError()); + } + } + else version (Posix) + { + void *symbol = ExeModule_GetSymbol(m_hModule, symbolName); - if(null is symbol) - { - throw new ExeModuleException(ExeModule_Error()); - } - } - else - { - static assert(0); - } + if(null is symbol) + { + throw new ExeModuleException(ExeModule_Error()); + } + } + else + { + static assert(0); + } return symbol; } @@ -635,23 +635,23 @@ public: { assert(null != m_hModule); - version (Windows) - { - char szFileName[260]; // Need to use a constant here + version (Windows) + { + char szFileName[260]; // Need to use a constant here - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getmodulefilename.asp - uint cch = GetModuleFileNameA(cast(HModule_)m_hModule, szFileName.ptr, szFileName.length); - if (cch == 0) - throw new ExeModuleException(GetLastError()); + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getmodulefilename.asp + uint cch = GetModuleFileNameA(cast(HModule_)m_hModule, szFileName.ptr, szFileName.length); + if (cch == 0) + throw new ExeModuleException(GetLastError()); - return szFileName[0 .. cch].dup; - } - else version (Posix) - { - return ExeModule_GetPath_(m_hModule); - } - else - static assert(0); + return szFileName[0 .. cch].dup; + } + else version (Posix) + { + return ExeModule_GetPath_(m_hModule); + } + else + static assert(0); } /// @} diff --git a/std/math.d b/std/math.d index aca554312..26d488a6b 100644 --- a/std/math.d +++ b/std/math.d @@ -75,7 +75,7 @@ version(GNU){ // GDC can't actually do inline asm. } else version(D_InlineAsm_X86) { version = Naked_D_InlineAsm_X86; -} else version(LDC) { +} else version(LDC) { import ldc.intrinsics; version(X86) { @@ -84,7 +84,7 @@ version(GNU){ } version(DigitalMars){ - version=INLINE_YL2X; // x87 has opcodes for these + version=INLINE_YL2X; // x87 has opcodes for these } private: @@ -423,7 +423,7 @@ trigerr: return real.nan; Lret: - ; + ; } else { return stdc.math.tanl(x); } @@ -554,7 +554,7 @@ real atan2(real y, real x) { return std.c.math.atan2l(y,x); } */ real cosh(real x) { // cosh = (exp(x)+exp(-x))/2. - // The naive implementation works correctly. + // The naive implementation works correctly. real y = exp(x); return (y + 1.0/y) * 0.5; } @@ -570,13 +570,13 @@ real cosh(real x) { */ real sinh(real x) { - // sinh(x) = (exp(x)-exp(-x))/2; + // sinh(x) = (exp(x)-exp(-x))/2; // Very large arguments could cause an overflow, but // the maximum value of x for which exp(x) + exp(-x)) != exp(x) // is x = 0.5 * (real.mant_dig) * LN2. // = 22.1807 for real80. if (fabs(x) > real.mant_dig * LN2) { return copysign(0.5 * exp(fabs(x)), x); - } + } real y = expm1(x); return 0.5 * y / (y+1) * (y+2); } @@ -594,7 +594,7 @@ real tanh(real x) { // tanh(x) = (exp(x) - exp(-x))/(exp(x)+exp(-x)) if (fabs(x) > real.mant_dig * LN2) { - return copysign(1, x); + return copysign(1, x); } real y = expm1(2*x); return y / (y + 2); @@ -788,8 +788,8 @@ real exp(real x) { // and exp2 are so similar). return exp2(LOG2E*x); } else { - return std.c.math.exp(x); - } + return std.c.math.exp(x); + } } /** @@ -807,24 +807,24 @@ real exp(real x) { * $(TR $(TD $(NAN)) $(TD $(NAN)) ) * ) */ -real expm1(real x) +real expm1(real x) { version(Naked_D_InlineAsm_X86) { enum { PARAMSIZE = (real.sizeof+3)&(0xFFFF_FFFC) } // always a multiple of 4 asm { /* expm1() for x87 80-bit reals, IEEE754-2008 conformant. * Author: Don Clugston. - * + * * expm1(x) = 2^(rndint(y))* 2^(y-rndint(y)) - 1 where y = LN2*x. * = 2rndy * 2ym1 + 2rndy - 1, where 2rndy = 2^(rndint(y)) * and 2ym1 = (2^(y-rndint(y))-1). * If 2rndy < 0.5*real.epsilon, result is -1. * Implementation is otherwise the same as for exp2() */ - naked; + naked; fld real ptr [ESP+4] ; // x mov AX, [ESP+4+8]; // AX = exponent and sign - sub ESP, 12+8; // Create scratch space on the stack + sub ESP, 12+8; // Create scratch space on the stack // [ESP,ESP+2] = scratchint // [ESP+4..+6, +8..+10, +10] = scratchreal // set scratchreal mantissa = 1.0 @@ -834,7 +834,7 @@ real expm1(real x) cmp AX, 0x401D; // avoid InvalidException in fist jae L_extreme; fldl2e; - fmul ; // y = x*log2(e) + fmul ; // y = x*log2(e) fist dword ptr [ESP]; // scratchint = rndint(y) fisub dword ptr [ESP]; // y - rndint(y) // and now set scratchreal exponent @@ -843,26 +843,26 @@ real expm1(real x) jle short L_largenegative; cmp EAX,0x8000; jge short L_largepositive; - mov [ESP+8+8],AX; - f2xm1; // 2^(y-rndint(y)) -1 + mov [ESP+8+8],AX; + f2xm1; // 2^(y-rndint(y)) -1 fld real ptr [ESP+8] ; // 2^rndint(y) fmul ST(1), ST; fld1; fsubp ST(1), ST; - fadd; - add ESP,12+8; + fadd; + add ESP,12+8; ret PARAMSIZE; - + L_extreme: // Extreme exponent. X is very large positive, very // large negative, infinity, or NaN. fxam; fstsw AX; - test AX, 0x0400; // NaN_or_zero, but we already know x!=0 + test AX, 0x0400; // NaN_or_zero, but we already know x!=0 jz L_was_nan; // if x is NaN, returns x test AX, 0x0200; jnz L_largenegative; -L_largepositive: - // Set scratchreal = real.max. +L_largepositive: + // Set scratchreal = real.max. // squaring it will create infinity, and set overflow flag. mov word ptr [ESP+8+8], 0x7FFE; fstp ST(0), ST; @@ -871,7 +871,7 @@ L_largepositive: L_was_nan: add ESP,12+8; ret PARAMSIZE; -L_largenegative: +L_largenegative: fstp ST(0), ST; fld1; fchs; // return -1. Underflow flag is not set. @@ -879,7 +879,7 @@ L_largenegative: ret PARAMSIZE; } } else { - return std.c.math.expm1(x); + return std.c.math.expm1(x); } } @@ -893,30 +893,30 @@ L_largenegative: * $(TR $(TD $(NAN)) $(TD $(NAN)) ) * ) */ -real exp2(real x) +real exp2(real x) { version(Naked_D_InlineAsm_X86) { enum { PARAMSIZE = (real.sizeof+3)&(0xFFFF_FFFC) } // always a multiple of 4 asm { /* exp2() for x87 80-bit reals, IEEE754-2008 conformant. * Author: Don Clugston. - * + * * exp2(x) = 2^(rndint(x))* 2^(y-rndint(x)) * The trick for high performance is to avoid the fscale(28cycles on core2), * frndint(19 cycles), leaving f2xm1(19 cycles) as the only slow instruction. - * + * * We can do frndint by using fist. BUT we can't use it for huge numbers, * because it will set the Invalid Operation flag is overflow or NaN occurs. * Fortunately, whenever this happens the result would be zero or infinity. - * + * * We can perform fscale by directly poking into the exponent. BUT this doesn't * work for the (very rare) cases where the result is subnormal. So we fall back * to the slow method in that case. */ - naked; + naked; fld real ptr [ESP+4] ; // x mov AX, [ESP+4+8]; // AX = exponent and sign - sub ESP, 12+8; // Create scratch space on the stack + sub ESP, 12+8; // Create scratch space on the stack // [ESP,ESP+2] = scratchint // [ESP+4..+6, +8..+10, +10] = scratchreal // set scratchreal mantissa = 1.0 @@ -933,43 +933,43 @@ real exp2(real x) jle short L_subnormal; cmp EAX,0x8000; jge short L_overflow; - mov [ESP+8+8],AX; + mov [ESP+8+8],AX; L_normal: f2xm1; fld1; fadd; // 2^(x-rndint(x)) fld real ptr [ESP+8] ; // 2^rndint(x) - add ESP,12+8; + add ESP,12+8; fmulp ST(1), ST; ret PARAMSIZE; L_subnormal: // Result will be subnormal. - // In this rare case, the simple poking method doesn't work. + // In this rare case, the simple poking method doesn't work. // The speed doesn't matter, so use the slow fscale method. fild dword ptr [ESP]; // scratchint fld1; fscale; fstp real ptr [ESP+8]; // scratchreal = 2^scratchint - fstp ST(0),ST; // drop scratchint + fstp ST(0),ST; // drop scratchint jmp L_normal; - + L_extreme: // Extreme exponent. X is very large positive, very // large negative, infinity, or NaN. fxam; fstsw AX; - test AX, 0x0400; // NaN_or_zero, but we already know x!=0 + test AX, 0x0400; // NaN_or_zero, but we already know x!=0 jz L_was_nan; // if x is NaN, returns x // set scratchreal = real.min // squaring it will return 0, setting underflow flag mov word ptr [ESP+8+8], 1; test AX, 0x0200; jnz L_waslargenegative; -L_overflow: +L_overflow: // Set scratchreal = real.max. // squaring it will create infinity, and set overflow flag. mov word ptr [ESP+8+8], 0x7FFE; -L_waslargenegative: +L_waslargenegative: fstp ST(0), ST; fld real ptr [ESP+8]; // load scratchreal fmul ST(0), ST; // square it, to create havoc! @@ -979,7 +979,7 @@ L_was_nan: } } else { return std.c.math.exp2(x); - } + } } /** @@ -1019,7 +1019,7 @@ unittest * Calculate and return $(I x) and $(I exp) such that * value =$(I x)*2$(SUP exp) and * .5 $(LT)= |$(I x)| $(LT) 1.0 - * + * * $(I x) has same sign as value. * * $(TABLE_SV @@ -1069,7 +1069,7 @@ real frexp(real value, out int exp) vu[F.EXPPOS_SHORT] = cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE); } - } else static if (real.mant_dig == 113) { // quadruple + } else static if (real.mant_dig == 113) { // quadruple if (ex) { // If exponent is non-zero if (ex == F.EXPMASK) { // infinity or NaN if (vl[MANTISSA_LSB] | @@ -1087,7 +1087,7 @@ real frexp(real value, out int exp) vu[F.EXPPOS_SHORT] = cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE); } - } else if ((vl[MANTISSA_LSB] + } else if ((vl[MANTISSA_LSB] |(vl[MANTISSA_MSB] & 0x0000_FFFF_FFFF_FFFF)) == 0) { // value is +-0.0 exp = 0; @@ -1096,7 +1096,7 @@ real frexp(real value, out int exp) value *= F.POW2MANTDIG; ex = vu[F.EXPPOS_SHORT] & F.EXPMASK; exp = ex - F.EXPBIAS - 113; - vu[F.EXPPOS_SHORT] = + vu[F.EXPPOS_SHORT] = cast(ushort)((0x8000 & vu[F.EXPPOS_SHORT]) | 0x3FFE); } } else static if (real.mant_dig==53) { // real is double @@ -1229,9 +1229,9 @@ real ldexp(real n, int exp); /* intrinsic */ real log(real x) { version (INLINE_YL2X) - return yl2x(x, LN2); + return yl2x(x, LN2); else - return std.c.math.logl(x); + return std.c.math.logl(x); } unittest @@ -1253,9 +1253,9 @@ unittest real log10(real x) { version (INLINE_YL2X) - return yl2x(x, LOG2); + return yl2x(x, LOG2); else - return std.c.math.log10l(x); + return std.c.math.log10l(x); } unittest @@ -1295,9 +1295,9 @@ real log1p(real x) { return std.c.math.log1pl(x); } real log2(real x) { version (INLINE_YL2X) - return yl2x(x, 1); + return yl2x(x, 1); else - return std.c.math.log2l(x); + return std.c.math.log2l(x); } @@ -2825,10 +2825,10 @@ body ; } } - else - { - static assert(0); - } + else + { + static assert(0); + } } else { @@ -2857,15 +2857,15 @@ unittest * translate to a single x87 instruction. */ -real yl2x(real x, real y); // y * log2(x) -real yl2xp1(real x, real y); // y * log2(x + 1) +real yl2x(real x, real y); // y * log2(x) +real yl2xp1(real x, real y); // y * log2(x + 1) unittest { version (INLINE_YL2X) { - assert(yl2x(1024, 1) == 10); - assert(yl2xp1(1023, 1) == 10); + assert(yl2x(1024, 1) == 10); + assert(yl2xp1(1023, 1) == 10); } } diff --git a/std/math2.d b/std/math2.d index 759033f15..d32b06248 100644 --- a/std/math2.d +++ b/std/math2.d @@ -13,7 +13,7 @@ * the suitability of this software for any purpose. It is provided * "as is" without express or implied warranty. */ - + module std.math2; private import std.math, std.string, std.c.stdlib, std.c.stdio; @@ -25,32 +25,32 @@ private import std.math, std.string, std.c.stdlib, std.c.stdio; bool feq(real a, real b) { - return feq(a, b, 0.000001); -} - + return feq(a, b, 0.000001); +} + bool feq(real a, real b, real eps) { - return abs(a - b) <= eps; + return abs(a - b) <= eps; } /********************************* * Modulus */ - + int abs(int n) { - return n > 0 ? n : -n; + return n > 0 ? n : -n; } - + long abs(long n) { - return n > 0 ? n : -n; + return n > 0 ? n : -n; } real abs(real n) { - // just let the compiler handle it - return std.math.fabs(n); + // just let the compiler handle it + return std.math.fabs(n); } /********************************* @@ -59,22 +59,22 @@ real abs(real n) int sqr(int n) { - return n * n; + return n * n; } - + long sqr(long n) { - return n * n; -} - + return n * n; +} + real sqr(real n) { - return n * n; + return n * n; } unittest { - assert(sqr(sqr(3)) == 81); + assert(sqr(sqr(3)) == 81); } private ushort fp_cw_chop = 7999; @@ -82,39 +82,39 @@ private ushort fp_cw_chop = 7999; /********************************* * Integer part */ - + real trunc(real n) { - ushort cw; - asm - { - fstcw cw; - fldcw fp_cw_chop; - fld n; - frndint; - fldcw cw; - } + ushort cw; + asm + { + fstcw cw; + fldcw fp_cw_chop; + fld n; + frndint; + fldcw cw; + } } unittest { - assert(feq(trunc(+123.456), +123.0L)); - assert(feq(trunc(-123.456), -123.0L)); + assert(feq(trunc(+123.456), +123.0L)); + assert(feq(trunc(-123.456), -123.0L)); } /********************************* * Fractional part */ - + real frac(real n) { - return n - trunc(n); + return n - trunc(n); } unittest { - assert(feq(frac(+123.456), +0.456L)); - assert(feq(frac(-123.456), -0.456L)); + assert(feq(frac(+123.456), +0.456L)); + assert(feq(frac(-123.456), -0.456L)); } /********************************* @@ -123,136 +123,136 @@ unittest int sign(int n) { - return (n > 0 ? +1 : (n < 0 ? -1 : 0)); + return (n > 0 ? +1 : (n < 0 ? -1 : 0)); } unittest { - assert(sign(0) == 0); - assert(sign(+666) == +1); - assert(sign(-666) == -1); + assert(sign(0) == 0); + assert(sign(+666) == +1); + assert(sign(-666) == -1); } - + int sign(long n) { - return (n > 0 ? +1 : (n < 0 ? -1 : 0)); + return (n > 0 ? +1 : (n < 0 ? -1 : 0)); } unittest { - assert(sign(0) == 0); - assert(sign(+666L) == +1); - assert(sign(-666L) == -1); + assert(sign(0) == 0); + assert(sign(+666L) == +1); + assert(sign(-666L) == -1); } - + int sign(real n) { - return (n > 0 ? +1 : (n < 0 ? -1 : 0)); + return (n > 0 ? +1 : (n < 0 ? -1 : 0)); } unittest { - assert(sign(0.0L) == 0); - assert(sign(+123.456L) == +1); - assert(sign(-123.456L) == -1); + assert(sign(0.0L) == 0); + assert(sign(+123.456L) == +1); + assert(sign(-123.456L) == -1); } /********************************************************** * Cycles <-> radians <-> grads <-> degrees conversions */ - + real cycle2deg(real c) { - return c * 360; + return c * 360; } real cycle2rad(real c) { - return c * PI * 2; + return c * PI * 2; } real cycle2grad(real c) { - return c * 400; + return c * 400; } real deg2cycle(real d) { - return d / 360; + return d / 360; } real deg2rad(real d) { - return d / 180 * PI; + return d / 180 * PI; } real deg2grad(real d) { - return d / 90 * 100; + return d / 90 * 100; } real rad2deg(real r) { - return r / PI * 180; + return r / PI * 180; } real rad2cycle(real r) { - return r / (PI * 2); + return r / (PI * 2); } real rad2grad(real r) { - return r / PI * 200; + return r / PI * 200; } real grad2deg(real g) { - return g / 100 * 90; + return g / 100 * 90; } real grad2cycle(real g) { - return g / 400; + return g / 400; } real grad2rad(real g) { - return g / 200 * PI; + return g / 200 * PI; } unittest { - assert(feq(cycle2deg(0.5), 180)); - assert(feq(cycle2rad(0.5), PI)); - assert(feq(cycle2grad(0.5), 200)); - assert(feq(deg2cycle(180), 0.5)); - assert(feq(deg2rad(180), PI)); - assert(feq(deg2grad(180), 200)); - assert(feq(rad2deg(PI), 180)); - assert(feq(rad2cycle(PI), 0.5)); - assert(feq(rad2grad(PI), 200)); - assert(feq(grad2deg(200), 180)); - assert(feq(grad2cycle(200), 0.5)); - assert(feq(grad2rad(200), PI)); + assert(feq(cycle2deg(0.5), 180)); + assert(feq(cycle2rad(0.5), PI)); + assert(feq(cycle2grad(0.5), 200)); + assert(feq(deg2cycle(180), 0.5)); + assert(feq(deg2rad(180), PI)); + assert(feq(deg2grad(180), 200)); + assert(feq(rad2deg(PI), 180)); + assert(feq(rad2cycle(PI), 0.5)); + assert(feq(rad2grad(PI), 200)); + assert(feq(grad2deg(200), 180)); + assert(feq(grad2cycle(200), 0.5)); + assert(feq(grad2rad(200), PI)); } /************************************ * Arithmetic average of values */ - + real avg(real[] n) { - real result = 0; - for (uint i = 0; i < n.length; i++) - result += n[i]; - return result / n.length; + real result = 0; + for (uint i = 0; i < n.length; i++) + result += n[i]; + return result / n.length; } unittest { - static real[4] n = [ 1, 2, 4, 5 ]; - assert(feq(avg(n), 3)); + static real[4] n = [ 1, 2, 4, 5 ]; + assert(feq(avg(n), 3)); } /************************************* @@ -261,44 +261,44 @@ unittest int sum(int[] n) { - long result = 0; - for (size_t i = 0; i < n.length; i++) - result += n[i]; - return cast(int)result; + long result = 0; + for (size_t i = 0; i < n.length; i++) + result += n[i]; + return cast(int)result; } unittest { - static int[3] n = [ 1, 2, 3 ]; - assert(sum(n) == 6); + static int[3] n = [ 1, 2, 3 ]; + assert(sum(n) == 6); } - + long sum(long[] n) { - long result = 0; - for (uint i = 0; i < n.length; i++) - result += n[i]; - return result; + long result = 0; + for (uint i = 0; i < n.length; i++) + result += n[i]; + return result; } unittest { - static long[3] n = [ 1, 2, 3 ]; - assert(sum(n) == 6); + static long[3] n = [ 1, 2, 3 ]; + assert(sum(n) == 6); } - + real sum(real[] n) { - real result = 0; - for (uint i = 0; i < n.length; i++) - result += n[i]; - return result; + real result = 0; + for (uint i = 0; i < n.length; i++) + result += n[i]; + return result; } unittest { - static real[3] n = [ 1, 2, 3 ]; - assert(feq(sum(n), 6)); + static real[3] n = [ 1, 2, 3 ]; + assert(feq(sum(n), 6)); } /************************************* @@ -307,79 +307,79 @@ unittest int min(int[] n) { - int result = int.max; - for (uint i = 0; i < n.length; i++) - if (n[i] < result) - result = n[i]; - return result; + int result = int.max; + for (uint i = 0; i < n.length; i++) + if (n[i] < result) + result = n[i]; + return result; } unittest { - static int[3] n = [ 2, -1, 0 ]; - assert(min(n) == -1); + static int[3] n = [ 2, -1, 0 ]; + assert(min(n) == -1); } - + long min(long[] n) { - long result = long.max; - for (uint i = 0; i < n.length; i++) - if (n[i] < result) - result = n[i]; - return result; + long result = long.max; + for (uint i = 0; i < n.length; i++) + if (n[i] < result) + result = n[i]; + return result; } unittest { - static long[3] n = [ 2, -1, 0 ]; - assert(min(n) == -1); + static long[3] n = [ 2, -1, 0 ]; + assert(min(n) == -1); } real min(real[] n) { - real result = real.max; - for (uint i = 0; i < n.length; i++) - { - if (n[i] < result) - result = n[i]; - } - return result; + real result = real.max; + for (uint i = 0; i < n.length; i++) + { + if (n[i] < result) + result = n[i]; + } + return result; } unittest { - static real[3] n = [ 2.0, -1.0, 0.0 ]; - assert(feq(min(n), -1)); + static real[3] n = [ 2.0, -1.0, 0.0 ]; + assert(feq(min(n), -1)); } int min(int a, int b) { - return a < b ? a : b; + return a < b ? a : b; } unittest { - assert(min(1, 2) == 1); + assert(min(1, 2) == 1); } long min(long a, long b) { - return a < b ? a : b; + return a < b ? a : b; } unittest { - assert(min(1L, 2L) == 1); + assert(min(1L, 2L) == 1); } real min(real a, real b) { - return a < b ? a : b; + return a < b ? a : b; } unittest { - assert(feq(min(1.0L, 2.0L), 1.0L)); + assert(feq(min(1.0L, 2.0L), 1.0L)); } /************************************* @@ -388,77 +388,77 @@ unittest int max(int[] n) { - int result = int.min; - for (uint i = 0; i < n.length; i++) - if (n[i] > result) - result = n[i]; - return result; + int result = int.min; + for (uint i = 0; i < n.length; i++) + if (n[i] > result) + result = n[i]; + return result; } unittest { - static int[3] n = [ 0, 2, -1 ]; - assert(max(n) == 2); + static int[3] n = [ 0, 2, -1 ]; + assert(max(n) == 2); } - + long max(long[] n) { - long result = long.min; - for (uint i = 0; i < n.length; i++) - if (n[i] > result) - result = n[i]; - return result; + long result = long.min; + for (uint i = 0; i < n.length; i++) + if (n[i] > result) + result = n[i]; + return result; } unittest { - static long[3] n = [ 0, 2, -1 ]; - assert(max(n) == 2); + static long[3] n = [ 0, 2, -1 ]; + assert(max(n) == 2); } real max(real[] n) { - real result = real.min; - for (uint i = 0; i < n.length; i++) - if (n[i] > result) - result = n[i]; - return result; + real result = real.min; + for (uint i = 0; i < n.length; i++) + if (n[i] > result) + result = n[i]; + return result; } unittest { - static real[3] n = [ 0.0, 2.0, -1.0 ]; - assert(feq(max(n), 2)); + static real[3] n = [ 0.0, 2.0, -1.0 ]; + assert(feq(max(n), 2)); } int max(int a, int b) { - return a > b ? a : b; + return a > b ? a : b; } unittest { - assert(max(1, 2) == 2); + assert(max(1, 2) == 2); } long max(long a, long b) { - return a > b ? a : b; + return a > b ? a : b; } unittest { - assert(max(1L, 2L) == 2); + assert(max(1L, 2L) == 2); } real max(real a, real b) { - return a > b ? a : b; + return a > b ? a : b; } unittest { - assert(feq(max(1.0L, 2.0L), 2.0L)); + assert(feq(max(1.0L, 2.0L), 2.0L)); } /************************************* @@ -467,12 +467,12 @@ unittest real acot(real x) { - return tan(1.0 / x); + return tan(1.0 / x); } unittest { - assert(feq(acot(cot(0.000001)), 0.000001)); + assert(feq(acot(cot(0.000001)), 0.000001)); } /************************************* @@ -481,7 +481,7 @@ unittest real asec(real x) { - return std.math.cos(1.0 / x); + return std.math.cos(1.0 / x); } @@ -491,7 +491,7 @@ real asec(real x) real acosec(real x) { - return std.math.sin(1.0 / x); + return std.math.sin(1.0 / x); } /************************************* @@ -501,18 +501,18 @@ real acosec(real x) /+ real tan(real x) { - asm - { - fld x; - fptan; - fstp ST(0); - fwait; - } + asm + { + fld x; + fptan; + fstp ST(0); + fwait; + } } unittest { - assert(feq(tan(PI / 3), std.math.sqrt(3))); + assert(feq(tan(PI / 3), std.math.sqrt(3))); } +/ @@ -522,18 +522,18 @@ unittest real cot(real x) { - asm - { - fld x; - fptan; - fdivrp; - fwait; - } + asm + { + fld x; + fptan; + fdivrp; + fwait; + } } unittest { - assert(feq(cot(PI / 6), std.math.sqrt(3.0L))); + assert(feq(cot(PI / 6), std.math.sqrt(3.0L))); } /************************************* @@ -542,14 +542,14 @@ unittest real sec(real x) { - asm - { - fld x; - fcos; - fld1; - fdivrp; - fwait; - } + asm + { + fld x; + fcos; + fld1; + fdivrp; + fwait; + } } @@ -559,14 +559,14 @@ real sec(real x) real cosec(real x) { - asm - { - fld x; - fsin; - fld1; - fdivrp; - fwait; - } + asm + { + fld x; + fsin; + fld1; + fdivrp; + fwait; + } } /********************************************* @@ -576,35 +576,35 @@ real cosec(real x) /+ real frexp(real x, out int exponent) { - asm - { - fld x; - mov EDX, exponent; - mov dword ptr [EDX], 0; - ftst; - fstsw AX; - fwait; - sahf; - jz done; - fxtract; - fxch; - fistp dword ptr [EDX]; - fld1; - fchs; - fxch; - fscale; - inc dword ptr [EDX]; - fstp ST(1); + asm + { + fld x; + mov EDX, exponent; + mov dword ptr [EDX], 0; + ftst; + fstsw AX; + fwait; + sahf; + jz done; + fxtract; + fxch; + fistp dword ptr [EDX]; + fld1; + fchs; + fxch; + fscale; + inc dword ptr [EDX]; + fstp ST(1); done: - fwait; - } + fwait; + } } unittest { - int exponent; - real mantissa = frexp(123.456, exponent); - assert(feq(mantissa * pow(2.0L, cast(real)exponent), 123.456)); + int exponent; + real mantissa = frexp(123.456, exponent); + assert(feq(mantissa * pow(2.0L, cast(real)exponent), 123.456)); } +/ @@ -614,12 +614,12 @@ unittest real coth(real x) { - return 1 / tanh(x); + return 1 / tanh(x); } unittest { - assert(feq(coth(1), cosh(1) / sinh(1))); + assert(feq(coth(1), cosh(1) / sinh(1))); } /************************************* @@ -628,7 +628,7 @@ unittest real sech(real x) { - return 1 / cosh(x); + return 1 / cosh(x); } /************************************* @@ -637,7 +637,7 @@ real sech(real x) real cosech(real x) { - return 1 / sinh(x); + return 1 / sinh(x); } /************************************* @@ -647,18 +647,18 @@ real cosech(real x) /+ real acosh(real x) { - if (x <= 1) - return 0; - else if (x > 1.0e10) - return log(2) + log(x); - else - return log(x + std.math.sqrt((x - 1) * (x + 1))); + if (x <= 1) + return 0; + else if (x > 1.0e10) + return log(2) + log(x); + else + return log(x + std.math.sqrt((x - 1) * (x + 1))); } unittest { - assert(acosh(0.5) == 0); - assert(feq(acosh(cosh(3)), 3)); + assert(acosh(0.5) == 0); + assert(feq(acosh(cosh(3)), 3)); } +/ @@ -669,25 +669,25 @@ unittest /+ real asinh(real x) { - if (!x) - return 0; - else if (x > 1.0e10) - return log(2) + log(1.0e10); - else if (x < -1.0e10) - return -log(2) - log(1.0e10); - else - { - real z = x * x; - return x > 0 ? - log1p(x + z / (1.0 + std.math.sqrt(1.0 + z))) : - -log1p(-x + z / (1.0 + std.math.sqrt(1.0 + z))); - } + if (!x) + return 0; + else if (x > 1.0e10) + return log(2) + log(1.0e10); + else if (x < -1.0e10) + return -log(2) - log(1.0e10); + else + { + real z = x * x; + return x > 0 ? + log1p(x + z / (1.0 + std.math.sqrt(1.0 + z))) : + -log1p(-x + z / (1.0 + std.math.sqrt(1.0 + z))); + } } unittest { - assert(asinh(0) == 0); - assert(feq(asinh(sinh(3)), 3)); + assert(asinh(0) == 0); + assert(feq(asinh(sinh(3)), 3)); } +/ @@ -697,25 +697,25 @@ unittest /+ real atanh(real x) { - if (!x) - return 0; - else - { - if (x >= 1) - return real.max; - else if (x <= -1) - return -real.max; - else - return x > 0 ? - 0.5 * log1p((2.0 * x) / (1.0 - x)) : - -0.5 * log1p((-2.0 * x) / (1.0 + x)); - } + if (!x) + return 0; + else + { + if (x >= 1) + return real.max; + else if (x <= -1) + return -real.max; + else + return x > 0 ? + 0.5 * log1p((2.0 * x) / (1.0 - x)) : + -0.5 * log1p((-2.0 * x) / (1.0 + x)); + } } unittest { - assert(atanh(0) == 0); - assert(feq(atanh(tanh(0.5)), 0.5)); + assert(atanh(0) == 0); + assert(feq(atanh(tanh(0.5)), 0.5)); } +/ @@ -725,12 +725,12 @@ unittest real acoth(real x) { - return 1 / acot(x); + return 1 / acot(x); } unittest { - assert(feq(acoth(coth(0.01)), 100)); + assert(feq(acoth(coth(0.01)), 100)); } /************************************* @@ -739,7 +739,7 @@ unittest real asech(real x) { - return 1 / asec(x); + return 1 / asec(x); } /************************************* @@ -748,7 +748,7 @@ real asech(real x) real acosech(real x) { - return 1 / acosec(x); + return 1 / acosec(x); } /************************************* @@ -757,158 +757,158 @@ real acosech(real x) real atof(char[] s) { - if (!s.length) - return real.nan; - real result = 0; - uint i = 0; - while (s[i] == '\t' || s[i] == ' ') - if (++i >= s.length) - return real.nan; - bool neg = false; - if (s[i] == '-') - { - neg = true; - i++; - } - else if (s[i] == '+') - i++; - if (i >= s.length) - return real.nan; - bool hex; - if (s[s.length - 1] == 'h') - { - hex = true; - s.length = s.length - 1; - } - else if (i + 1 < s.length && s[i] == '0' && s[i+1] == 'x') - { - hex = true; - i += 2; - if (i >= s.length) - return real.nan; - } - else - hex = false; - while (s[i] != '.') - { - if (hex) - { - if ((s[i] == 'p' || s[i] == 'P')) - break; - result *= 0x10; - } - else - { - if ((s[i] == 'e' || s[i] == 'E')) - break; - result *= 10; - } - if (s[i] >= '0' && s[i] <= '9') - result += s[i] - '0'; - else if (hex) - { - if (s[i] >= 'a' && s[i] <= 'f') - result += s[i] - 'a' + 10; - else if (s[i] >= 'A' && s[i] <= 'F') - result += s[i] - 'A' + 10; - else - return real.nan; - } - else - return real.nan; - if (++i >= s.length) - goto done; - } - if (s[i] == '.') - { - if (++i >= s.length) - goto done; - ulong k = 1; - while (true) - { - if (hex) - { - if ((s[i] == 'p' || s[i] == 'P')) - break; - result *= 0x10; - } - else - { - if ((s[i] == 'e' || s[i] == 'E')) - break; - result *= 10; - } - k *= (hex ? 0x10 : 10); - if (s[i] >= '0' && s[i] <= '9') - result += s[i] - '0'; - else if (hex) - { - if (s[i] >= 'a' && s[i] <= 'f') - result += s[i] - 'a' + 10; - else if (s[i] >= 'A' && s[i] <= 'F') - result += s[i] - 'A' + 10; - else - return real.nan; - } - else - return real.nan; - if (++i >= s.length) - { - result /= k; - goto done; - } - } - result /= k; - } - if (++i >= s.length) - return real.nan; - bool eneg = false; - if (s[i] == '-') - { - eneg = true; - i++; - } - else if (s[i] == '+') - i++; - if (i >= s.length) - return real.nan; - int e = 0; - while (i < s.length) - { - e *= 10; - if (s[i] >= '0' && s[i] <= '9') - e += s[i] - '0'; - else - return real.nan; - i++; - } - if (eneg) - e = -e; - result *= pow(hex ? 2.0L : 10.0L, cast(real)e); -done: - return neg ? -result : result; + if (!s.length) + return real.nan; + real result = 0; + uint i = 0; + while (s[i] == '\t' || s[i] == ' ') + if (++i >= s.length) + return real.nan; + bool neg = false; + if (s[i] == '-') + { + neg = true; + i++; + } + else if (s[i] == '+') + i++; + if (i >= s.length) + return real.nan; + bool hex; + if (s[s.length - 1] == 'h') + { + hex = true; + s.length = s.length - 1; + } + else if (i + 1 < s.length && s[i] == '0' && s[i+1] == 'x') + { + hex = true; + i += 2; + if (i >= s.length) + return real.nan; + } + else + hex = false; + while (s[i] != '.') + { + if (hex) + { + if ((s[i] == 'p' || s[i] == 'P')) + break; + result *= 0x10; + } + else + { + if ((s[i] == 'e' || s[i] == 'E')) + break; + result *= 10; + } + if (s[i] >= '0' && s[i] <= '9') + result += s[i] - '0'; + else if (hex) + { + if (s[i] >= 'a' && s[i] <= 'f') + result += s[i] - 'a' + 10; + else if (s[i] >= 'A' && s[i] <= 'F') + result += s[i] - 'A' + 10; + else + return real.nan; + } + else + return real.nan; + if (++i >= s.length) + goto done; + } + if (s[i] == '.') + { + if (++i >= s.length) + goto done; + ulong k = 1; + while (true) + { + if (hex) + { + if ((s[i] == 'p' || s[i] == 'P')) + break; + result *= 0x10; + } + else + { + if ((s[i] == 'e' || s[i] == 'E')) + break; + result *= 10; + } + k *= (hex ? 0x10 : 10); + if (s[i] >= '0' && s[i] <= '9') + result += s[i] - '0'; + else if (hex) + { + if (s[i] >= 'a' && s[i] <= 'f') + result += s[i] - 'a' + 10; + else if (s[i] >= 'A' && s[i] <= 'F') + result += s[i] - 'A' + 10; + else + return real.nan; + } + else + return real.nan; + if (++i >= s.length) + { + result /= k; + goto done; + } + } + result /= k; + } + if (++i >= s.length) + return real.nan; + bool eneg = false; + if (s[i] == '-') + { + eneg = true; + i++; + } + else if (s[i] == '+') + i++; + if (i >= s.length) + return real.nan; + int e = 0; + while (i < s.length) + { + e *= 10; + if (s[i] >= '0' && s[i] <= '9') + e += s[i] - '0'; + else + return real.nan; + i++; + } + if (eneg) + e = -e; + result *= pow(hex ? 2.0L : 10.0L, cast(real)e); +done: + return neg ? -result : result; } unittest { - assert(feq(atof("123"), 123)); - assert(feq(atof("+123"), +123)); - assert(feq(atof("-123"), -123)); - assert(feq(atof("123e2"), 12300)); - assert(feq(atof("123e+2"), 12300)); - assert(feq(atof("123e-2"), 1.23)); - assert(feq(atof("123."), 123)); - assert(feq(atof("123.E-2"), 1.23)); - assert(feq(atof(".456"), .456)); - assert(feq(atof("123.456"), 123.456)); - assert(feq(atof("1.23456E+2"), 123.456)); - //assert(feq(atof("1A2h"), 1A2h)); - //assert(feq(atof("1a2h"), 1a2h)); - assert(feq(atof("0x1A2"), 0x1A2)); - assert(feq(atof("0x1a2p2"), 0x1a2p2)); - assert(feq(atof("0x1a2p+2"), 0x1a2p+2)); - assert(feq(atof("0x1a2p-2"), 0x1a2p-2)); - assert(feq(atof("0x1A2.3B4"), 0x1A2.3B4p0)); - assert(feq(atof("0x1a2.3b4P2"), 0x1a2.3b4P2)); + assert(feq(atof("123"), 123)); + assert(feq(atof("+123"), +123)); + assert(feq(atof("-123"), -123)); + assert(feq(atof("123e2"), 12300)); + assert(feq(atof("123e+2"), 12300)); + assert(feq(atof("123e-2"), 1.23)); + assert(feq(atof("123."), 123)); + assert(feq(atof("123.E-2"), 1.23)); + assert(feq(atof(".456"), .456)); + assert(feq(atof("123.456"), 123.456)); + assert(feq(atof("1.23456E+2"), 123.456)); + //assert(feq(atof("1A2h"), 1A2h)); + //assert(feq(atof("1a2h"), 1a2h)); + assert(feq(atof("0x1A2"), 0x1A2)); + assert(feq(atof("0x1a2p2"), 0x1a2p2)); + assert(feq(atof("0x1a2p+2"), 0x1a2p+2)); + assert(feq(atof("0x1a2p-2"), 0x1a2p-2)); + assert(feq(atof("0x1A2.3B4"), 0x1A2.3B4p0)); + assert(feq(atof("0x1a2.3b4P2"), 0x1a2.3b4P2)); } diff --git a/std/md5.d b/std/md5.d index 6a99774aa..24285cd20 100644 --- a/std/md5.d +++ b/std/md5.d @@ -3,10 +3,10 @@ */ /** - * Computes MD5 digests of arbitrary data. MD5 digests are 16 byte quantities that are like a checksum or crc, but are more robust. + * Computes MD5 digests of arbitrary data. MD5 digests are 16 byte quantities that are like a checksum or crc, but are more robust. * * There are two ways to do this. The first does it all in one function call to - * sum(). The second is for when the data is buffered. + * sum(). The second is for when the data is buffered. * * Bugs: * MD5 digests have been demonstrated to not be unique. @@ -16,10 +16,10 @@ * $(I RSA Data Security, Inc. MD5 Message-Digest Algorithm). * * References: - * $(LINK2 http://en.wikipedia.org/wiki/Md5, Wikipedia on MD5) + * $(LINK2 http://en.wikipedia.org/wiki/Md5, Wikipedia on MD5) * * Macros: - * WIKI = Phobos/StdMd5 + * WIKI = Phobos/StdMd5 */ /++++++++++++++++++++++++++++++++ @@ -39,7 +39,7 @@ private import std.c.string; int main(char[][] args) { foreach (char[] arg; args) - MDFile(arg); + MDFile(arg); return 0; } @@ -53,16 +53,16 @@ void MDFile(char[] filename) ubyte digest[16]; if ((file = fopen(std.string.toStringz(filename), "rb")) == null) - writefln("%s can't be opened", filename); + writefln("%s can't be opened", filename); else { - context.start(); - while ((len = fread(buffer, 1, buffer.sizeof, file)) != 0) - context.update(buffer[0 .. len]); - context.finish(digest); - fclose(file); + context.start(); + while ((len = fread(buffer, 1, buffer.sizeof, file)) != 0) + context.update(buffer[0 .. len]); + context.finish(digest); + fclose(file); - writefln("MD5 (%s) = %s", filename, digestToString(digest)); + writefln("MD5 (%s) = %s", filename, digestToString(digest)); } } -------------------- @@ -91,7 +91,7 @@ documentation and/or software. module std.md5; -//debug=md5; // uncomment to turn on debugging printf's +//debug=md5; // uncomment to turn on debugging printf's import std.string; @@ -114,7 +114,7 @@ void sum(ubyte[16] digest, void[] data) void printDigest(ubyte digest[16]) { foreach (ubyte u; digest) - printf("%02x", u); + printf("%02x", u); } /**************************************** @@ -128,9 +128,9 @@ char[] digestToString(ubyte[16] digest) foreach (ubyte u; digest) { - result[i] = std.string.hexdigits[u >> 4]; - result[i + 1] = std.string.hexdigits[u & 15]; - i += 2; + result[i] = std.string.hexdigits[u >> 4]; + result[i + 1] = std.string.hexdigits[u & 15]; + i += 2; } return result; } @@ -146,8 +146,8 @@ struct MD5_CTX /* magic initialization constants */ [0x67452301,0xefcdab89,0x98badcfe,0x10325476]; - ulong count; /* number of bits, modulo 2^64 */ - ubyte buffer[64]; /* input buffer */ + ulong count; /* number of bits, modulo 2^64 */ + ubyte buffer[64]; /* input buffer */ static ubyte[64] PADDING = [ @@ -160,30 +160,30 @@ struct MD5_CTX */ private static { - uint F(uint x, uint y, uint z) { return (x & y) | (~x & z); } - uint G(uint x, uint y, uint z) { return (x & z) | (y & ~z); } - uint H(uint x, uint y, uint z) { return x ^ y ^ z; } - uint I(uint x, uint y, uint z) { return y ^ (x | ~z); } + uint F(uint x, uint y, uint z) { return (x & y) | (~x & z); } + uint G(uint x, uint y, uint z) { return (x & z) | (y & ~z); } + uint H(uint x, uint y, uint z) { return x ^ y ^ z; } + uint I(uint x, uint y, uint z) { return y ^ (x | ~z); } } /* ROTATE_LEFT rotates x left n bits. */ static uint ROTATE_LEFT(uint x, uint n) { - version (X86) - { - asm - { naked ; - mov ECX,EAX ; - mov EAX,4[ESP] ; - rol EAX,CL ; - ret 4 ; - } - } - else - { - return (x << n) | (x >> (32-n)); - } + version (X86) + { + asm + { naked ; + mov ECX,EAX ; + mov EAX,4[ESP] ; + rol EAX,CL ; + ret 4 ; + } + } + else + { + return (x << n) | (x >> (32-n)); + } } /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. @@ -191,30 +191,30 @@ struct MD5_CTX */ static void FF(inout uint a, uint b, uint c, uint d, uint x, uint s, uint ac) { - a += F (b, c, d) + x + cast(uint)(ac); - a = ROTATE_LEFT (a, s); - a += b; + a += F (b, c, d) + x + cast(uint)(ac); + a = ROTATE_LEFT (a, s); + a += b; } static void GG(inout uint a, uint b, uint c, uint d, uint x, uint s, uint ac) { - a += G (b, c, d) + x + cast(uint)(ac); - a = ROTATE_LEFT (a, s); - a += b; + a += G (b, c, d) + x + cast(uint)(ac); + a = ROTATE_LEFT (a, s); + a += b; } static void HH(inout uint a, uint b, uint c, uint d, uint x, uint s, uint ac) { - a += H (b, c, d) + x + cast(uint)(ac); - a = ROTATE_LEFT (a, s); - a += b; + a += H (b, c, d) + x + cast(uint)(ac); + a = ROTATE_LEFT (a, s); + a += b; } static void II(inout uint a, uint b, uint c, uint d, uint x, uint s, uint ac) { - a += I (b, c, d) + x + cast(uint)(ac); - a = ROTATE_LEFT (a, s); - a += b; + a += I (b, c, d) + x + cast(uint)(ac); + a = ROTATE_LEFT (a, s); + a += b; } /** @@ -222,7 +222,7 @@ struct MD5_CTX */ void start() { - *this = MD5_CTX.init; + *this = MD5_CTX.init; } /** MD5 block update operation. Continues an MD5 message-digest @@ -245,20 +245,20 @@ struct MD5_CTX /* Transform as many times as possible. */ if (inputLen >= partLen) { - std.c.string.memcpy(&buffer[index], input.ptr, partLen); - transform (buffer.ptr); + std.c.string.memcpy(&buffer[index], input.ptr, partLen); + transform (buffer.ptr); - for (i = partLen; i + 63 < inputLen; i += 64) - transform ((cast(ubyte[])input)[i .. i + 64].ptr); + for (i = partLen; i + 63 < inputLen; i += 64) + transform ((cast(ubyte[])input)[i .. i + 64].ptr); - index = 0; + index = 0; } else - i = 0; + i = 0; /* Buffer remaining input */ if (inputLen - i) - std.c.string.memcpy(&buffer[index], &input[i], inputLen-i); + std.c.string.memcpy(&buffer[index], &input[i], inputLen-i); } /** MD5 finalization. Ends an MD5 message-digest operation, writing the @@ -296,30 +296,30 @@ struct MD5_CTX /* Constants for MD5Transform routine. */ enum { - S11 = 7, - S12 = 12, - S13 = 17, - S14 = 22, - S21 = 5, - S22 = 9, - S23 = 14, - S24 = 20, - S31 = 4, - S32 = 11, - S33 = 16, - S34 = 23, - S41 = 6, - S42 = 10, - S43 = 15, - S44 = 21, + S11 = 7, + S12 = 12, + S13 = 17, + S14 = 22, + S21 = 5, + S22 = 9, + S23 = 14, + S24 = 20, + S31 = 4, + S32 = 11, + S33 = 16, + S34 = 23, + S41 = 6, + S42 = 10, + S43 = 15, + S44 = 21, } private void transform (ubyte* /*[64]*/ block) { uint a = state[0], - b = state[1], - c = state[2], - d = state[3]; + b = state[1], + c = state[2], + d = state[3]; uint[16] x; Decode (x.ptr, block, 64); @@ -410,16 +410,16 @@ struct MD5_CTX */ private static void Encode (ubyte *output, uint *input, uint len) { - uint i, j; + uint i, j; - for (i = 0, j = 0; j < len; i++, j += 4) - { - uint u = input[i]; - output[j] = cast(ubyte)(u); - output[j+1] = cast(ubyte)(u >> 8); - output[j+2] = cast(ubyte)(u >> 16); - output[j+3] = cast(ubyte)(u >> 24); - } + for (i = 0, j = 0; j < len; i++, j += 4) + { + uint u = input[i]; + output[j] = cast(ubyte)(u); + output[j+1] = cast(ubyte)(u >> 8); + output[j+2] = cast(ubyte)(u >> 16); + output[j+3] = cast(ubyte)(u >> 24); + } } /* Decodes input (ubyte) into output (uint). Assumes len is @@ -427,20 +427,20 @@ struct MD5_CTX */ private static void Decode (uint *output, ubyte *input, uint len) { - uint i, j; + uint i, j; - for (i = 0, j = 0; j < len; i++, j += 4) - { - version (LittleEndian) - { - output[i] = *cast(uint*)&input[j]; - } - else - { - output[i] = (cast(uint)input[j]) | ((cast(uint)input[j+1]) << 8) | - ((cast(uint)input[j+2]) << 16) | ((cast(uint)input[j+3]) << 24); - } - } + for (i = 0, j = 0; j < len; i++, j += 4) + { + version (LittleEndian) + { + output[i] = *cast(uint*)&input[j]; + } + else + { + output[i] = (cast(uint)input[j]) | ((cast(uint)input[j+1]) << 8) | + ((cast(uint)input[j+2]) << 16) | ((cast(uint)input[j+3]) << 24); + } + } } } @@ -469,8 +469,8 @@ unittest assert(digest == cast(ubyte[])x"d174ab98d277d9f5a5611c2c9f419d9f"); sum (digest, - "1234567890123456789012345678901234567890" - "1234567890123456789012345678901234567890"); + "1234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890"); assert(digest == cast(ubyte[])x"57edf4a22be3c955ac49da2e2107b67a"); assert(digestToString(cast(ubyte[16])x"c3fcd3d76192e4007dfb496cca67e13b") diff --git a/std/mmfile.d b/std/mmfile.d index c456287a3..228e01b23 100644 --- a/std/mmfile.d +++ b/std/mmfile.d @@ -26,7 +26,7 @@ /** * Read and write memory mapped files. * Macros: - * WIKI=Phobos/StdMmfile + * WIKI=Phobos/StdMmfile */ module std.mmfile; @@ -41,23 +41,23 @@ private import std.string; version (Win32) { - private import std.c.windows.windows; - private import std.utf; - - private uint dwVersion; - - static this() - { // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/getversion.asp - dwVersion = GetVersion(); - } + private import std.c.windows.windows; + private import std.utf; + + private uint dwVersion; + + static this() + { // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/getversion.asp + dwVersion = GetVersion(); + } } else version (Posix) { - private import std.c.posix.posix; + private import std.c.posix.posix; } else { - static assert(0); + static assert(0); } /** @@ -69,538 +69,538 @@ class MmFile * The mode the memory mapped file is opened with. */ enum Mode - { Read, /// read existing file - ReadWriteNew, /// delete existing file, write new file - ReadWrite, /// read/write existing file, create if not existing - ReadCopyOnWrite, /// read/write existing file, copy on write + { Read, /// read existing file + ReadWriteNew, /// delete existing file, write new file + ReadWrite, /// read/write existing file, create if not existing + ReadCopyOnWrite, /// read/write existing file, copy on write } - + /** * Open memory mapped file filename for reading. * File is closed when the object instance is deleted. * Throws: - * std.file.FileException + * std.file.FileException */ this(string filename) { - this(filename, Mode.Read, 0, null); + this(filename, Mode.Read, 0, null); } - + /** * Open memory mapped file filename in mode. * File is closed when the object instance is deleted. * Params: - * filename = name of the file. - * If null, an anonymous file mapping is created. - * mode = access mode defined above. - * size = the size of the file. If 0, it is taken to be the - * size of the existing file. - * address = the preferred address to map the file to, - * although the system is not required to honor it. - * If null, the system selects the most convenient address. - * window = preferred block size of the amount of data to map at one time - * with 0 meaning map the entire file. The window size must be a - * multiple of the memory allocation page size. + * filename = name of the file. + * If null, an anonymous file mapping is created. + * mode = access mode defined above. + * size = the size of the file. If 0, it is taken to be the + * size of the existing file. + * address = the preferred address to map the file to, + * although the system is not required to honor it. + * If null, the system selects the most convenient address. + * window = preferred block size of the amount of data to map at one time + * with 0 meaning map the entire file. The window size must be a + * multiple of the memory allocation page size. * Throws: - * std.file.FileException + * std.file.FileException */ this(string filename, Mode mode, ulong size, void* address, - size_t window = 0) + size_t window = 0) { - this.filename = filename; - this.mMode = mode; - this.window = window; - this.address = address; - - version (Win32) - { - void* p; - uint dwDesiredAccess2; - uint dwShareMode; - uint dwCreationDisposition; - uint flProtect; - - if (dwVersion & 0x80000000 && (dwVersion & 0xFF) == 3) - { - throw new FileException(filename, - "Win32s does not implement mm files"); - } - - switch (mode) - { - case Mode.Read: - dwDesiredAccess2 = GENERIC_READ; - dwShareMode = FILE_SHARE_READ; - dwCreationDisposition = OPEN_EXISTING; - flProtect = PAGE_READONLY; - dwDesiredAccess = FILE_MAP_READ; - break; + this.filename = filename; + this.mMode = mode; + this.window = window; + this.address = address; - case Mode.ReadWriteNew: - assert(size != 0); - dwDesiredAccess2 = GENERIC_READ | GENERIC_WRITE; - dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; - dwCreationDisposition = CREATE_ALWAYS; - flProtect = PAGE_READWRITE; - dwDesiredAccess = FILE_MAP_WRITE; - break; + version (Win32) + { + void* p; + uint dwDesiredAccess2; + uint dwShareMode; + uint dwCreationDisposition; + uint flProtect; - case Mode.ReadWrite: - dwDesiredAccess2 = GENERIC_READ | GENERIC_WRITE; - dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; - dwCreationDisposition = OPEN_ALWAYS; - flProtect = PAGE_READWRITE; - dwDesiredAccess = FILE_MAP_WRITE; - break; + if (dwVersion & 0x80000000 && (dwVersion & 0xFF) == 3) + { + throw new FileException(filename, + "Win32s does not implement mm files"); + } - case Mode.ReadCopyOnWrite: - if (dwVersion & 0x80000000) - { - throw new FileException(filename, - "Win9x does not implement copy on write"); - } - dwDesiredAccess2 = GENERIC_READ | GENERIC_WRITE; - dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; - dwCreationDisposition = OPEN_EXISTING; - flProtect = PAGE_WRITECOPY; - dwDesiredAccess = FILE_MAP_COPY; - break; + switch (mode) + { + case Mode.Read: + dwDesiredAccess2 = GENERIC_READ; + dwShareMode = FILE_SHARE_READ; + dwCreationDisposition = OPEN_EXISTING; + flProtect = PAGE_READONLY; + dwDesiredAccess = FILE_MAP_READ; + break; - default: - assert(0); - } - - if (filename) - { - if (useWfuncs) - { - auto namez = std.utf.toUTF16z(filename); - hFile = CreateFileW(namez, - dwDesiredAccess2, - dwShareMode, - null, - dwCreationDisposition, - FILE_ATTRIBUTE_NORMAL, - cast(HANDLE)null); - } - else - { - auto namez = std.file.toMBSz(filename); - hFile = CreateFileA(namez, - dwDesiredAccess2, - dwShareMode, - null, - dwCreationDisposition, - FILE_ATTRIBUTE_NORMAL, - cast(HANDLE)null); - } - if (hFile == INVALID_HANDLE_VALUE) - goto err1; - } - else - hFile = null; - - int hi = cast(int)(size>>32); - hFileMap = CreateFileMappingA(hFile, null, flProtect, hi, cast(uint)size, null); - if (hFileMap == null) // mapping failed - goto err1; - - if (size == 0) - { - uint sizehi; - uint sizelow = GetFileSize(hFile,&sizehi); - size = (cast(ulong)sizehi << 32) + sizelow; - } - this.size = size; - - size_t initial_map = (window && 2*window statbuf.st_size) - { - // Need to make the file size bytes big - std.c.posix.posix.lseek(fd, cast(int)(size - 1), SEEK_SET); - char c = 0; - std.c.posix.posix.write(fd, &c, 1); - } - else if (prot & PROT_READ && size == 0) - size = cast(ulong)statbuf.st_size; - } - else - { - fd = -1; -version (linux) flags |= MAP_ANONYMOUS; -else version (OSX) flags |= MAP_ANON; -else version (FreeBSD) flags |= MAP_ANON; -else version (Solaris) flags |= MAP_ANON; -else static assert(0); - } - this.size = size; - size_t initial_map = (window && 2*window>32); + hFileMap = CreateFileMappingA(hFile, null, flProtect, hi, cast(uint)size, null); + if (hFileMap == null) // mapping failed + goto err1; - i = msync(cast(void*)data, data.length, MS_SYNC); // sys/mman.h - if (i != 0) - errNo(); - } - else - { - static assert(0); - } - } + if (size == 0) + { + uint sizehi; + uint sizelow = GetFileSize(hFile,&sizehi); + size = (cast(ulong)sizehi << 32) + sizelow; + } + this.size = size; - /** - * Gives size in bytes of the memory mapped file. - */ - ulong length() - { - debug (MMFILE) printf("MmFile.length()\n"); - return size; - } + size_t initial_map = (window && 2*window statbuf.st_size) + { + // Need to make the file size bytes big + std.c.posix.posix.lseek(fd, cast(int)(size - 1), SEEK_SET); + char c = 0; + std.c.posix.posix.write(fd, &c, 1); + } + else if (prot & PROT_READ && size == 0) + size = cast(ulong)statbuf.st_size; + } + else + { + fd = -1; +version (linux) flags |= MAP_ANONYMOUS; +else version (OSX) flags |= MAP_ANON; +else version (FreeBSD) flags |= MAP_ANON; +else version (Solaris) flags |= MAP_ANON; +else static assert(0); + } + this.size = size; + size_t initial_map = (window && 2*window= start && i < start+data.length; - } + // return true if the given position is currently mapped + private int mapped(ulong i) + { + debug (MMFILE) printf("MmFile.mapped(%lld, %lld, %d)\n", i,start, + data.length); + return i >= start && i < start+data.length; + } - // unmap the current range - private void unmap() - { - debug (MMFILE) printf("MmFile.unmap()\n"); - version(Windows) { - /* Note that under Windows 95, UnmapViewOfFile() seems to return - * random values, not TRUE or FALSE. - */ - if (data && UnmapViewOfFile(data.ptr) == FALSE && - (dwVersion & 0x80000000) == 0) - errNo(); - } else { - if (data && munmap(cast(void*)data, data.length) != 0) - errNo(); - } - data = null; - } + // unmap the current range + private void unmap() + { + debug (MMFILE) printf("MmFile.unmap()\n"); + version(Windows) { + /* Note that under Windows 95, UnmapViewOfFile() seems to return + * random values, not TRUE or FALSE. + */ + if (data && UnmapViewOfFile(data.ptr) == FALSE && + (dwVersion & 0x80000000) == 0) + errNo(); + } else { + if (data && munmap(cast(void*)data, data.length) != 0) + errNo(); + } + data = null; + } - // map range - private void map(ulong start, size_t len) - { - debug (MMFILE) printf("MmFile.map(%lld, %d)\n", start, len); - void* p; - if (start+len > size) - len = cast(size_t)(size-start); - version(Windows) { - uint hi = cast(uint)(start>>32); - p = MapViewOfFileEx(hFileMap, dwDesiredAccess, hi, cast(uint)start, len, address); - if (!p) errNo(); - } else { - p = mmap(address, len, prot, flags, fd, cast(int)start); - if (p == MAP_FAILED) errNo(); - } - data = p[0 .. len]; - this.start = start; - } + // map range + private void map(ulong start, size_t len) + { + debug (MMFILE) printf("MmFile.map(%lld, %d)\n", start, len); + void* p; + if (start+len > size) + len = cast(size_t)(size-start); + version(Windows) { + uint hi = cast(uint)(start>>32); + p = MapViewOfFileEx(hFileMap, dwDesiredAccess, hi, cast(uint)start, len, address); + if (!p) errNo(); + } else { + p = mmap(address, len, prot, flags, fd, cast(int)start); + if (p == MAP_FAILED) errNo(); + } + data = p[0 .. len]; + this.start = start; + } - // ensure a given position is mapped - private void ensureMapped(ulong i) - { - debug (MMFILE) printf("MmFile.ensureMapped(%lld)\n", i); - if (!mapped(i)) { - unmap(); - if (window == 0) { - map(0,cast(size_t)size); - } else { - ulong block = i/window; - if (block == 0) - map(0,2*window); - else - map(window*(block-1),3*window); - } - } - } + // ensure a given position is mapped + private void ensureMapped(ulong i) + { + debug (MMFILE) printf("MmFile.ensureMapped(%lld)\n", i); + if (!mapped(i)) { + unmap(); + if (window == 0) { + map(0,cast(size_t)size); + } else { + ulong block = i/window; + if (block == 0) + map(0,2*window); + else + map(window*(block-1),3*window); + } + } + } - // ensure a given range is mapped - private void ensureMapped(ulong i, ulong j) - { - debug (MMFILE) printf("MmFile.ensureMapped(%lld, %lld)\n", i, j); - if (!mapped(i) || !mapped(j-1)) { - unmap(); - if (window == 0) { - map(0,cast(size_t)size); - } else { - ulong iblock = i/window; - ulong jblock = (j-1)/window; - if (iblock == 0) { - map(0,cast(size_t)(window*(jblock+2))); - } else { - map(window*(iblock-1),cast(size_t)(window*(jblock-iblock+3))); - } - } - } - } + // ensure a given range is mapped + private void ensureMapped(ulong i, ulong j) + { + debug (MMFILE) printf("MmFile.ensureMapped(%lld, %lld)\n", i, j); + if (!mapped(i) || !mapped(j-1)) { + unmap(); + if (window == 0) { + map(0,cast(size_t)size); + } else { + ulong iblock = i/window; + ulong jblock = (j-1)/window; + if (iblock == 0) { + map(0,cast(size_t)(window*(jblock+2))); + } else { + map(window*(iblock-1),cast(size_t)(window*(jblock-iblock+3))); + } + } + } + } - private: - string filename; - void[] data; - ulong start; - size_t window; - ulong size; - Mode mMode; - void* address; + private: + string filename; + void[] data; + ulong start; + size_t window; + ulong size; + Mode mMode; + void* address; - version (Win32) - { - HANDLE hFile = INVALID_HANDLE_VALUE; - HANDLE hFileMap = null; - uint dwDesiredAccess; - } - else version (Posix) - { - int fd; - int prot; - int flags; - int fmode; - } - else - { - static assert(0); - } + version (Win32) + { + HANDLE hFile = INVALID_HANDLE_VALUE; + HANDLE hFileMap = null; + uint dwDesiredAccess; + } + else version (Posix) + { + int fd; + int prot; + int flags; + int fmode; + } + else + { + static assert(0); + } - // Report error, where errno gives the error number - void errNo() - { - version (Win32) - { - throw new FileException(filename, GetLastError()); - } - else version (Posix) - { - throw new FileException(filename, getErrno()); - } - else - { - static assert(0); - } - } + // Report error, where errno gives the error number + void errNo() + { + version (Win32) + { + throw new FileException(filename, GetLastError()); + } + else version (Posix) + { + throw new FileException(filename, getErrno()); + } + else + { + static assert(0); + } + } } unittest { - const size_t K = 1024; - size_t win = 64*K; // assume the page size is 64K - version(Win32) { - /+ these aren't defined in std.c.windows.windows so let's use the default + const size_t K = 1024; + size_t win = 64*K; // assume the page size is 64K + version(Win32) { + /+ these aren't defined in std.c.windows.windows so let's use the default SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); win = sysinfo.dwAllocationGranularity; - +/ - } else version (Posix) { - // getpagesize() is not defined in the unix D headers so use the guess - } - MmFile mf = new MmFile("testing.txt",MmFile.Mode.ReadWriteNew,100*K,null,win); - ubyte[] str = cast(ubyte[])"1234567890"; - ubyte[] data = cast(ubyte[])mf[0 .. 10]; - data[] = str[]; - assert( mf[0 .. 10] == str ); - data = cast(ubyte[])mf[50 .. 60]; - data[] = str[]; - assert( mf[50 .. 60] == str ); - ubyte[] data2 = cast(ubyte[])mf[20*K .. 60*K]; - assert( data2.length == 40*K ); - assert( data2[length-1] == 0 ); - mf[100*K-1] = cast(ubyte)'b'; - data2 = cast(ubyte[])mf[21*K .. 100*K]; - assert( data2.length == 79*K ); - assert( data2[length-1] == 'b' ); - delete mf; - std.file.remove("testing.txt"); + +/ + } else version (Posix) { + // getpagesize() is not defined in the unix D headers so use the guess + } + MmFile mf = new MmFile("testing.txt",MmFile.Mode.ReadWriteNew,100*K,null,win); + ubyte[] str = cast(ubyte[])"1234567890"; + ubyte[] data = cast(ubyte[])mf[0 .. 10]; + data[] = str[]; + assert( mf[0 .. 10] == str ); + data = cast(ubyte[])mf[50 .. 60]; + data[] = str[]; + assert( mf[50 .. 60] == str ); + ubyte[] data2 = cast(ubyte[])mf[20*K .. 60*K]; + assert( data2.length == 40*K ); + assert( data2[length-1] == 0 ); + mf[100*K-1] = cast(ubyte)'b'; + data2 = cast(ubyte[])mf[21*K .. 100*K]; + assert( data2.length == 79*K ); + assert( data2[length-1] == 'b' ); + delete mf; + std.file.remove("testing.txt"); - // Create anonymous mapping - auto test = new MmFile(null, MmFile.Mode.ReadWriteNew, 1024*1024, null); + // Create anonymous mapping + auto test = new MmFile(null, MmFile.Mode.ReadWriteNew, 1024*1024, null); } diff --git a/std/moduleinit.d b/std/moduleinit.d index 49a082e91..d29221c86 100644 --- a/std/moduleinit.d +++ b/std/moduleinit.d @@ -14,11 +14,11 @@ private } enum -{ MIctorstart = 1, // we've started constructing it - MIctordone = 2, // finished construction - MIstandalone = 4, // module ctor does not depend on other module - // ctors being done first - MIhasictor = 8, // has ictor member +{ MIctorstart = 1, // we've started constructing it + MIctordone = 2, // finished construction + MIstandalone = 4, // module ctor does not depend on other module + // ctors being done first + MIhasictor = 8, // has ictor member } /*********************** @@ -30,22 +30,22 @@ class ModuleInfo ModuleInfo importedModules[]; ClassInfo localClasses[]; - uint flags; // initialization state + uint flags; // initialization state - void (*ctor)(); // module static constructor (order dependent) - void (*dtor)(); // module static destructor - void (*unitTest)(); // module unit tests + void (*ctor)(); // module static constructor (order dependent) + void (*dtor)(); // module static destructor + void (*unitTest)(); // module unit tests - void* xgetMembers; // module getMembers() function + void* xgetMembers; // module getMembers() function - void (*ictor)(); // module static constructor (order independent) + void (*ictor)(); // module static constructor (order independent) /****************** * Return collection of all modules in the program. */ static ModuleInfo[] modules() { - return _moduleinfo_array; + return _moduleinfo_array; } } @@ -53,7 +53,7 @@ class ModuleCtorError : Exception { this(ModuleInfo m) { - super(cast(string) ("circular initialization dependency with module " + super(cast(string) ("circular initialization dependency with module " ~ m.name)); } } @@ -70,11 +70,11 @@ version (linux) // into the .ctor list by the compiler. struct ModuleReference { - ModuleReference* next; - ModuleInfo mod; + ModuleReference* next; + ModuleInfo mod; } - extern (C) ModuleReference *_Dmodule_ref; // start of linked list + extern (C) ModuleReference *_Dmodule_ref; // start of linked list } version (FreeBSD) @@ -83,11 +83,11 @@ version (FreeBSD) // into the .ctor list by the compiler. struct ModuleReference { - ModuleReference* next; - ModuleInfo mod; + ModuleReference* next; + ModuleInfo mod; } - extern (C) ModuleReference *_Dmodule_ref; // start of linked list + extern (C) ModuleReference *_Dmodule_ref; // start of linked list } version (Solaris) @@ -107,8 +107,8 @@ version (OSX) { extern (C) { - extern void* _minfo_beg; - extern void* _minfo_end; + extern void* _minfo_beg; + extern void* _minfo_end; } } @@ -128,32 +128,32 @@ extern (C) void _moduleCtor() version (linux) { - int len = 0; - ModuleReference *mr; + int len = 0; + ModuleReference *mr; - for (mr = _Dmodule_ref; mr; mr = mr.next) - len++; - _moduleinfo_array = new ModuleInfo[len]; - len = 0; - for (mr = _Dmodule_ref; mr; mr = mr.next) - { _moduleinfo_array[len] = mr.mod; - len++; - } + for (mr = _Dmodule_ref; mr; mr = mr.next) + len++; + _moduleinfo_array = new ModuleInfo[len]; + len = 0; + for (mr = _Dmodule_ref; mr; mr = mr.next) + { _moduleinfo_array[len] = mr.mod; + len++; + } } version (FreeBSD) { - int len = 0; - ModuleReference *mr; + int len = 0; + ModuleReference *mr; - for (mr = _Dmodule_ref; mr; mr = mr.next) - len++; - _moduleinfo_array = new ModuleInfo[len]; - len = 0; - for (mr = _Dmodule_ref; mr; mr = mr.next) - { _moduleinfo_array[len] = mr.mod; - len++; - } + for (mr = _Dmodule_ref; mr; mr = mr.next) + len++; + _moduleinfo_array = new ModuleInfo[len]; + len = 0; + for (mr = _Dmodule_ref; mr; mr = mr.next) + { _moduleinfo_array[len] = mr.mod; + len++; + } } version (Solaris) @@ -172,27 +172,27 @@ extern (C) void _moduleCtor() } version (OSX) - { /* The ModuleInfo references are stored in the special segment - * __minfodata, which is bracketed by the segments __minfo_beg - * and __minfo_end. The variables _minfo_beg and _minfo_end - * are of zero size and are in the two bracketing segments, - * respectively. - */ - size_t length = cast(ModuleInfo*)&_minfo_end - cast(ModuleInfo*)&_minfo_beg; - _moduleinfo_array = (cast(ModuleInfo*)&_minfo_beg)[0 .. length]; - debug printf("moduleinfo: ptr = %p, length = %d\n", _moduleinfo_array.ptr, _moduleinfo_array.length); + { /* The ModuleInfo references are stored in the special segment + * __minfodata, which is bracketed by the segments __minfo_beg + * and __minfo_end. The variables _minfo_beg and _minfo_end + * are of zero size and are in the two bracketing segments, + * respectively. + */ + size_t length = cast(ModuleInfo*)&_minfo_end - cast(ModuleInfo*)&_minfo_beg; + _moduleinfo_array = (cast(ModuleInfo*)&_minfo_beg)[0 .. length]; + debug printf("moduleinfo: ptr = %p, length = %d\n", _moduleinfo_array.ptr, _moduleinfo_array.length); - debug foreach (m; _moduleinfo_array) - { - //printf("\t%p\n", m); - printf("\t%.*s\n", m.name); - } + debug foreach (m; _moduleinfo_array) + { + //printf("\t%p\n", m); + printf("\t%.*s\n", m.name); + } } version (Win32) { - // Ensure module destructors also get called on program termination - //_fatexit(&_STD_moduleDtor); + // Ensure module destructors also get called on program termination + //_fatexit(&_STD_moduleDtor); } _moduleinfo_dtors = new ModuleInfo[_moduleinfo_array.length]; @@ -202,14 +202,14 @@ extern (C) void _moduleCtor() version (none) { - foreach (m; _moduleinfo_array) - { - writefln("module %s, %d", m.name, m.localClasses.length); - foreach (c; m.localClasses) - { - writefln("\tclass %s", c.name); - } - } + foreach (m; _moduleinfo_array) + { + writefln("module %s, %d", m.name, m.localClasses.length); + foreach (c; m.localClasses) + { + writefln("\tclass %s", c.name); + } + } } } @@ -218,41 +218,41 @@ void _moduleCtor2(ModuleInfo[] mi, int skip) debug printf("_moduleCtor2(): %d modules\n", mi.length); for (uint i = 0; i < mi.length; i++) { - ModuleInfo m = mi[i]; + ModuleInfo m = mi[i]; - debug printf("\tmodule[%d] = '%p'\n", i, m); - if (!m) - continue; - debug printf("\tmodule[%d] = '%.*s'\n", i, m.name); - if (m.flags & MIctordone) - continue; - debug printf("\tmodule[%d] = '%.*s', m = x%x, m.flags = x%x\n", i, m.name, m, m.flags); + debug printf("\tmodule[%d] = '%p'\n", i, m); + if (!m) + continue; + debug printf("\tmodule[%d] = '%.*s'\n", i, m.name); + if (m.flags & MIctordone) + continue; + debug printf("\tmodule[%d] = '%.*s', m = x%x, m.flags = x%x\n", i, m.name, m, m.flags); - if (m.ctor || m.dtor) - { - if (m.flags & MIctorstart) - { if (skip || m.flags & MIstandalone) - continue; - throw new ModuleCtorError(m); - } + if (m.ctor || m.dtor) + { + if (m.flags & MIctorstart) + { if (skip || m.flags & MIstandalone) + continue; + throw new ModuleCtorError(m); + } - m.flags |= MIctorstart; - _moduleCtor2(m.importedModules, 0); - if (m.ctor) - (*m.ctor)(); - m.flags &= ~MIctorstart; - m.flags |= MIctordone; + m.flags |= MIctorstart; + _moduleCtor2(m.importedModules, 0); + if (m.ctor) + (*m.ctor)(); + m.flags &= ~MIctorstart; + m.flags |= MIctordone; - // Now that construction is done, register the destructor - //printf("\tadding module dtor x%x\n", m); - assert(_moduleinfo_dtors_i < _moduleinfo_dtors.length); - _moduleinfo_dtors[_moduleinfo_dtors_i++] = m; - } - else - { - m.flags |= MIctordone; - _moduleCtor2(m.importedModules, 1); - } + // Now that construction is done, register the destructor + //printf("\tadding module dtor x%x\n", m); + assert(_moduleinfo_dtors_i < _moduleinfo_dtors.length); + _moduleinfo_dtors[_moduleinfo_dtors_i++] = m; + } + else + { + m.flags |= MIctordone; + _moduleCtor2(m.importedModules, 1); + } } } @@ -269,13 +269,13 @@ extern (C) void _moduleDtor() debug printf("_moduleDtor(): %d modules\n", _moduleinfo_dtors_i); for (uint i = _moduleinfo_dtors_i; i-- != 0;) { - ModuleInfo m = _moduleinfo_dtors[i]; + ModuleInfo m = _moduleinfo_dtors[i]; - debug printf("\tmodule[%d] = '%.*s', x%x\n", i, m.name, m); - if (m.dtor) - { - (*m.dtor)(); - } + debug printf("\tmodule[%d] = '%.*s', x%x\n", i, m.name, m); + if (m.dtor) + { + (*m.dtor)(); + } } debug printf("_moduleDtor() done\n"); } @@ -289,16 +289,16 @@ extern (C) void _moduleUnitTests() debug printf("_moduleUnitTests()\n"); for (uint i = 0; i < _moduleinfo_array.length; i++) { - ModuleInfo m = _moduleinfo_array[i]; + ModuleInfo m = _moduleinfo_array[i]; - if (!m) - continue; + if (!m) + continue; - debug printf("\tmodule[%d] = '%.*s'\n", i, m.name); - if (m.unitTest) - { - (*m.unitTest)(); - } + debug printf("\tmodule[%d] = '%.*s'\n", i, m.name); + if (m.unitTest) + { + (*m.unitTest)(); + } } } @@ -311,10 +311,10 @@ extern (C) void _moduleIndependentCtors() debug printf("_moduleIndependentCtors()\n"); foreach (m; _moduleinfo_array) { - if (m && m.flags & MIhasictor && m.ictor) - { - (*m.ictor)(); - } + if (m && m.flags & MIhasictor && m.ictor) + { + (*m.ictor)(); + } } } diff --git a/std/openrj.d b/std/openrj.d index 975690086..5fc1a6f75 100644 --- a/std/openrj.d +++ b/std/openrj.d @@ -38,12 +38,12 @@ * Open-RJ mapping for the D standard library. * * Authors: - * Matthew Wilson + * Matthew Wilson * References: - * $(LINK2 http://www.$(OPENRJ).org/, Open-RJ) + * $(LINK2 http://www.$(OPENRJ).org/, Open-RJ) * Macros: - * WIKI=Phobos/StdOpenrj - * OPENRJ=openrj + * WIKI=Phobos/StdOpenrj + * OPENRJ=openrj */ /* ///////////////////////////////////////////////////////////////////////////// @@ -151,7 +151,7 @@ public enum ORJ_FLAG */ public char[] toString(ORJ_FLAG f) { - const EnumString strings[] = + const EnumString strings[] = [ { ORJ_FLAG.ORDER_FIELDS, "Arranges the fields in alphabetical order" } , { ORJ_FLAG.ELIDE_BLANK_RECORDS, "Causes blank records to be ignored" } @@ -179,7 +179,7 @@ public enum ORJRC */ public char[] toString(ORJRC f) { - const EnumString strings[] = + const EnumString strings[] = [ { ORJRC.SUCCESS, "Operation was successful" } , { ORJRC.CANNOT_OPEN_JAR_FILE, "The given file does not exist, or cannot be accessed" } @@ -188,8 +188,8 @@ public char[] toString(ORJRC f) , { ORJRC.BAD_FILE_READ, "A read operation failed" } , { ORJRC.PARSE_ERROR, "Parsing of the database file failed due to a syntax error" } , { ORJRC.INVALID_INDEX, "An invalid index was specified" } - , { ORJRC.UNEXPECTED, "An unexpected condition was encountered" } - , { ORJRC.INVALID_CONTENT, "The database file contained invalid content" } + , { ORJRC.UNEXPECTED, "An unexpected condition was encountered" } + , { ORJRC.INVALID_CONTENT, "The database file contained invalid content" } ]; return enum_to_string!(ORJRC)(strings, f); @@ -210,7 +210,7 @@ public enum ORJ_PARSE_ERROR */ public char[] toString(ORJ_PARSE_ERROR f) { - const EnumString strings[] = + const EnumString strings[] = [ { ORJ_PARSE_ERROR.SUCCESS, "Parsing was successful" } , { ORJ_PARSE_ERROR.RECORD_SEPARATOR_IN_CONTINUATION, "A record separator was encountered during a content line continuation" } @@ -782,7 +782,7 @@ private: bContinuing = false; } -/+ // This is currently commented out as it seems unlikely to be sensible to +/+ // This is currently commented out as it seems unlikely to be sensible to // order the Fields globally. The reasoning is that if the Fields are used // globally then it's more likely that their ordering in the database source // is meaningful. If someone really needs an all-Fields array ordered, they diff --git a/std/outbuffer.d b/std/outbuffer.d index 9cdf2e26f..248658e8e 100644 --- a/std/outbuffer.d +++ b/std/outbuffer.d @@ -2,13 +2,13 @@ /** * Boilerplate: - * $(std_boilerplate.html) + * $(std_boilerplate.html) * Macros: - * WIKI = Phobos/StdOutbuffer + * WIKI = Phobos/StdOutbuffer * Copyright: - * Copyright (c) 2001-2005 by Digital Mars - * All Rights Reserved - * www.digitalmars.com + * Copyright (c) 2001-2005 by Digital Mars + * All Rights Reserved + * www.digitalmars.com */ @@ -41,14 +41,14 @@ class OutBuffer invariant { - //printf("this = %p, offset = %x, data.length = %u\n", this, offset, data.length); - assert(offset <= data.length); - assert(data.length <= std.gc.capacity(data.ptr)); + //printf("this = %p, offset = %x, data.length = %u\n", this, offset, data.length); + assert(offset <= data.length); + assert(data.length <= std.gc.capacity(data.ptr)); } this() { - //printf("in OutBuffer constructor\n"); + //printf("in OutBuffer constructor\n"); } /********************************* @@ -67,110 +67,110 @@ class OutBuffer void reserve(uint nbytes) - in - { - assert(offset + nbytes >= offset); - } - out - { - assert(offset + nbytes <= data.length); - assert(data.length <= std.gc.capacity(data.ptr)); - } - body - { - if (data.length < offset + nbytes) - { - //std.c.stdio.printf("OutBuffer.reserve: ptr = %p, length = %d, offset = %d, nbytes = %d, capacity = %d\n", data.ptr, data.length, offset, nbytes, std.gc.capacity(data.ptr)); - data.length = (offset + nbytes) * 2; - //std.c.stdio.printf("OutBuffer.reserve: ptr = %p, length = %d, capacity = %d\n", data.ptr, data.length, std.gc.capacity(data.ptr)); - std.gc.hasPointers(data.ptr); - } - } + in + { + assert(offset + nbytes >= offset); + } + out + { + assert(offset + nbytes <= data.length); + assert(data.length <= std.gc.capacity(data.ptr)); + } + body + { + if (data.length < offset + nbytes) + { + //std.c.stdio.printf("OutBuffer.reserve: ptr = %p, length = %d, offset = %d, nbytes = %d, capacity = %d\n", data.ptr, data.length, offset, nbytes, std.gc.capacity(data.ptr)); + data.length = (offset + nbytes) * 2; + //std.c.stdio.printf("OutBuffer.reserve: ptr = %p, length = %d, capacity = %d\n", data.ptr, data.length, std.gc.capacity(data.ptr)); + std.gc.hasPointers(data.ptr); + } + } /************************************* * Append data to the internal buffer. */ void write(ubyte[] bytes) - { - reserve(bytes.length); - data[offset .. offset + bytes.length] = bytes; - offset += bytes.length; - } + { + reserve(bytes.length); + data[offset .. offset + bytes.length] = bytes; + offset += bytes.length; + } - void write(ubyte b) /// ditto - { - reserve(ubyte.sizeof); - this.data[offset] = b; - offset += ubyte.sizeof; - } + void write(ubyte b) /// ditto + { + reserve(ubyte.sizeof); + this.data[offset] = b; + offset += ubyte.sizeof; + } - void write(byte b) { write(cast(ubyte)b); } /// ditto - void write(char c) { write(cast(ubyte)c); } /// ditto + void write(byte b) { write(cast(ubyte)b); } /// ditto + void write(char c) { write(cast(ubyte)c); } /// ditto - void write(ushort w) /// ditto + void write(ushort w) /// ditto { - reserve(ushort.sizeof); - *cast(ushort *)&data[offset] = w; - offset += ushort.sizeof; + reserve(ushort.sizeof); + *cast(ushort *)&data[offset] = w; + offset += ushort.sizeof; } - void write(short s) { write(cast(ushort)s); } /// ditto + void write(short s) { write(cast(ushort)s); } /// ditto - void write(wchar c) /// ditto + void write(wchar c) /// ditto { - reserve(wchar.sizeof); - *cast(wchar *)&data[offset] = c; - offset += wchar.sizeof; + reserve(wchar.sizeof); + *cast(wchar *)&data[offset] = c; + offset += wchar.sizeof; } - void write(uint w) /// ditto + void write(uint w) /// ditto { - reserve(uint.sizeof); - *cast(uint *)&data[offset] = w; - offset += uint.sizeof; + reserve(uint.sizeof); + *cast(uint *)&data[offset] = w; + offset += uint.sizeof; } - void write(int i) { write(cast(uint)i); } /// ditto + void write(int i) { write(cast(uint)i); } /// ditto - void write(ulong l) /// ditto + void write(ulong l) /// ditto { - reserve(ulong.sizeof); - *cast(ulong *)&data[offset] = l; - offset += ulong.sizeof; + reserve(ulong.sizeof); + *cast(ulong *)&data[offset] = l; + offset += ulong.sizeof; } - void write(long l) { write(cast(ulong)l); } /// ditto + void write(long l) { write(cast(ulong)l); } /// ditto - void write(float f) /// ditto + void write(float f) /// ditto { - reserve(float.sizeof); - *cast(float *)&data[offset] = f; - offset += float.sizeof; + reserve(float.sizeof); + *cast(float *)&data[offset] = f; + offset += float.sizeof; } - void write(double f) /// ditto + void write(double f) /// ditto { - reserve(double.sizeof); - *cast(double *)&data[offset] = f; - offset += double.sizeof; + reserve(double.sizeof); + *cast(double *)&data[offset] = f; + offset += double.sizeof; } - void write(real f) /// ditto + void write(real f) /// ditto { - reserve(real.sizeof); - *cast(real *)&data[offset] = f; - offset += real.sizeof; + reserve(real.sizeof); + *cast(real *)&data[offset] = f; + offset += real.sizeof; } - void write(string s) /// ditto + void write(string s) /// ditto { - write(cast(ubyte[])s); + write(cast(ubyte[])s); } - void write(OutBuffer buf) /// ditto + void write(OutBuffer buf) /// ditto { - write(buf.toBytes()); + write(buf.toBytes()); } /**************************************** @@ -179,9 +179,9 @@ class OutBuffer void fill0(uint nbytes) { - reserve(nbytes); - data[offset .. offset + nbytes] = 0; - offset += nbytes; + reserve(nbytes); + data[offset .. offset + nbytes] = 0; + offset += nbytes; } /********************************** @@ -191,18 +191,18 @@ class OutBuffer void alignSize(uint alignsize) in { - assert(alignsize && (alignsize & (alignsize - 1)) == 0); + assert(alignsize && (alignsize & (alignsize - 1)) == 0); } out { - assert((offset & (alignsize - 1)) == 0); + assert((offset & (alignsize - 1)) == 0); } body { uint nbytes; - nbytes = offset & (alignsize - 1); - if (nbytes) - fill0(alignsize - nbytes); + nbytes = offset & (alignsize - 1); + if (nbytes) + fill0(alignsize - nbytes); } /**************************************** @@ -211,8 +211,8 @@ class OutBuffer void align2() { - if (offset & 1) - write(cast(byte)0); + if (offset & 1) + write(cast(byte)0); } /**************************************** @@ -221,10 +221,10 @@ class OutBuffer void align4() { - if (offset & 3) - { uint nbytes = (4 - offset) & 3; - fill0(nbytes); - } + if (offset & 3) + { uint nbytes = (4 - offset) & 3; + fill0(nbytes); + } } /************************************** @@ -233,8 +233,8 @@ class OutBuffer char[] toString() { - //printf("OutBuffer.toString()\n"); - return cast(char[])data[0 .. offset]; + //printf("OutBuffer.toString()\n"); + return cast(char[])data[0 .. offset]; } /***************************************** @@ -243,49 +243,49 @@ class OutBuffer void vprintf(string format, va_list args) { - char[128] buffer; - char* p; - uint psize; - int count; + char[128] buffer; + char* p; + uint psize; + int count; - auto f = toStringz(format); - p = buffer.ptr; - psize = buffer.length; - for (;;) - { - version(Win32) - { - count = _vsnprintf(p,psize,f,args); - if (count != -1) - break; - psize *= 2; - p = cast(char *) alloca(psize); // buffer too small, try again with larger size - } - version(Posix) - { - count = vsnprintf(p,psize,f,args); - if (count == -1) - psize *= 2; - else if (count >= psize) - psize = count + 1; - else - break; - /+ - if (p != buffer) - c.stdlib.free(p); - p = (char *) c.stdlib.malloc(psize); // buffer too small, try again with larger size - +/ - p = cast(char *) alloca(psize); // buffer too small, try again with larger size - } - } - write(p[0 .. count]); - /+ - version (Posix) - { - if (p != buffer) - c.stdlib.free(p); - } - +/ + auto f = toStringz(format); + p = buffer.ptr; + psize = buffer.length; + for (;;) + { + version(Win32) + { + count = _vsnprintf(p,psize,f,args); + if (count != -1) + break; + psize *= 2; + p = cast(char *) alloca(psize); // buffer too small, try again with larger size + } + version(Posix) + { + count = vsnprintf(p,psize,f,args); + if (count == -1) + psize *= 2; + else if (count >= psize) + psize = count + 1; + else + break; + /+ + if (p != buffer) + c.stdlib.free(p); + p = (char *) c.stdlib.malloc(psize); // buffer too small, try again with larger size + +/ + p = cast(char *) alloca(psize); // buffer too small, try again with larger size + } + } + write(p[0 .. count]); + /+ + version (Posix) + { + if (p != buffer) + c.stdlib.free(p); + } + +/ } /***************************************** @@ -294,10 +294,10 @@ class OutBuffer void printf(string format, ...) { - va_list ap; - ap = cast(va_list)&format; - ap += format.sizeof; - vprintf(format, ap); + va_list ap; + ap = cast(va_list)&format; + ap += format.sizeof; + vprintf(format, ap); } /***************************************** @@ -306,22 +306,22 @@ class OutBuffer */ void spread(uint index, uint nbytes) - in - { - assert(index <= offset); - } - body - { - reserve(nbytes); + in + { + assert(index <= offset); + } + body + { + reserve(nbytes); - // This is an overlapping copy - should use memmove() - for (uint i = offset; i > index; ) - { - --i; - data[i + nbytes] = data[i]; - } - offset += nbytes; - } + // This is an overlapping copy - should use memmove() + for (uint i = offset; i > index; ) + { + --i; + data[i + nbytes] = data[i]; + } + offset += nbytes; + } } unittest diff --git a/std/outofmemory.d b/std/outofmemory.d index b93564d83..71d3ea41f 100644 --- a/std/outofmemory.d +++ b/std/outofmemory.d @@ -1,9 +1,9 @@ /** * Macros: - * WIKI=Phobos/StdOutOfMemory + * WIKI=Phobos/StdOutOfMemory * Copyright: - * Placed into public domain. - * www.digitalmars.com + * Placed into public domain. + * www.digitalmars.com */ @@ -22,20 +22,20 @@ class OutOfMemoryException : Exception */ this() { - super(s); + super(s); } char[] toString() { - return s; + return s; } } extern (C) void _d_OutOfMemory() { throw cast(OutOfMemoryException) - cast(void *) - OutOfMemoryException.classinfo.init; + cast(void *) + OutOfMemoryException.classinfo.init; } static this() diff --git a/std/path.d b/std/path.d index cb88a2c52..9f8dd94c4 100644 --- a/std/path.d +++ b/std/path.d @@ -2,10 +2,10 @@ /** * Macros: - * WIKI = Phobos/StdPath + * WIKI = Phobos/StdPath * Copyright: - * Placed into public domain. - * http://www.digitalmars.com + * Placed into public domain. + * http://www.digitalmars.com * * Grzegorz Adam Hankiewicz added some documentation. * @@ -19,7 +19,7 @@ module std.path; -//debug=path; // uncomment to turn on debugging printf's +//debug=path; // uncomment to turn on debugging printf's //private import std.stdio; private import std.string; @@ -46,7 +46,7 @@ version(Windows) /** String used to separate lines, \r\n under Windows and \n * under Linux. */ const char[2] linesep = "\r\n"; /// String used to separate lines. - const char[1] curdir = "."; /// String representing the current directory. + const char[1] curdir = "."; /// String representing the current directory. const char[2] pardir = ".."; /// String representing the parent directory. } version(Posix) @@ -63,18 +63,18 @@ version(Posix) /** String used to separate lines, \r\n under Windows and \n * under Linux. */ const char[1] linesep = "\n"; - const char[1] curdir = "."; /// String representing the current directory. + const char[1] curdir = "."; /// String representing the current directory. const char[2] pardir = ".."; /// String representing the parent directory. } /***************************** * Compare file names. * Returns: - * - *
< 0 filename1 < filename2 - *
= 0 filename1 == filename2 - *
> 0 filename1 > filename2 - *
+ * + *
< 0 filename1 < filename2 + *
= 0 filename1 == filename2 + *
> 0 filename1 > filename2 + *
*/ version (Windows) alias std.string.icmp fcmp; @@ -116,19 +116,19 @@ string getExt(string fullname) auto i = fullname.length; while (i > 0) { - if (fullname[i - 1] == '.') - return fullname[i .. fullname.length]; - i--; - version(Win32) - { - if (fullname[i] == ':' || fullname[i] == '\\') - break; - } - version(Posix) - { - if (fullname[i] == '/') - break; - } + if (fullname[i - 1] == '.') + return fullname[i .. fullname.length]; + i--; + version(Win32) + { + if (fullname[i] == ':' || fullname[i] == '\\') + break; + } + version(Posix) + { + if (fullname[i] == '/') + break; + } } return null; } @@ -139,30 +139,30 @@ unittest string result; version (Win32) - result = getExt("d:\\path\\foo.bat"); + result = getExt("d:\\path\\foo.bat"); version (Posix) - result = getExt("/path/foo.bat"); + result = getExt("/path/foo.bat"); auto i = cmp(result, "bat"); assert(i == 0); version (Win32) - result = getExt("d:\\path\\foo."); + result = getExt("d:\\path\\foo."); version (Posix) - result = getExt("d/path/foo."); + result = getExt("d/path/foo."); i = cmp(result, ""); assert(i == 0); version (Win32) - result = getExt("d:\\path\\foo"); + result = getExt("d:\\path\\foo"); version (Posix) - result = getExt("d/path/foo"); + result = getExt("d/path/foo"); i = cmp(result, ""); assert(i == 0); version (Win32) - result = getExt("d:\\path.bar\\foo"); + result = getExt("d:\\path.bar\\foo"); version (Posix) - result = getExt("/path.bar/foo"); + result = getExt("/path.bar/foo"); i = cmp(result, ""); assert(i == 0); @@ -207,19 +207,19 @@ string getName(string fullname) auto i = fullname.length; while (i > 0) { - if (fullname[i - 1] == '.') - return fullname[0 .. i - 1]; - i--; - version(Win32) - { - if (fullname[i] == ':' || fullname[i] == '\\') - break; - } - version(Posix) - { - if (fullname[i] == '/') - break; - } + if (fullname[i - 1] == '.') + return fullname[0 .. i - 1]; + i--; + version(Win32) + { + if (fullname[i] == ':' || fullname[i] == '\\') + break; + } + version(Posix) + { + if (fullname[i] == '/') + break; + } } return null; } @@ -235,9 +235,9 @@ unittest result = getName("d:\\path.two\\bar"); version (Win32) - i = cmp(result, null); + i = cmp(result, null); version (Posix) - i = cmp(result, "d:\\path"); + i = cmp(result, "d:\\path"); assert(i == 0); } @@ -270,25 +270,25 @@ unittest string getBaseName(string fullname) out (result) { - assert(result.length <= fullname.length); + assert(result.length <= fullname.length); } body { - auto i = fullname.length; - for (; i > 0; i--) - { - version(Win32) - { - if (fullname[i - 1] == ':' || fullname[i - 1] == '\\') - break; - } - version(Posix) - { - if (fullname[i - 1] == '/') - break; - } - } - return fullname[i .. fullname.length]; + auto i = fullname.length; + for (; i > 0; i--) + { + version(Win32) + { + if (fullname[i - 1] == ':' || fullname[i - 1] == '\\') + break; + } + version(Posix) + { + if (fullname[i - 1] == '/') + break; + } + } + return fullname[i .. fullname.length]; } unittest @@ -298,17 +298,17 @@ unittest string result; version (Windows) - result = getBaseName("d:\\path\\foo.bat"); + result = getBaseName("d:\\path\\foo.bat"); version (Posix) - result = getBaseName("/path/foo.bat"); + result = getBaseName("/path/foo.bat"); //printf("result = '%.*s'\n", result); i = cmp(result, "foo.bat"); assert(i == 0); version (Windows) - result = getBaseName("a\\b"); + result = getBaseName("a\\b"); version (Posix) - result = getBaseName("a/b"); + result = getBaseName("a/b"); i = cmp(result, "b"); assert(i == 0); } @@ -348,32 +348,32 @@ unittest string getDirName(string fullname) out (result) { - assert(result.length <= fullname.length); + assert(result.length <= fullname.length); } body { - uint i; + uint i; - for (i = fullname.length; i > 0; i--) - { - version(Win32) - { - if (fullname[i - 1] == ':') - break; - if (fullname[i - 1] == '\\' || fullname[i - 1] == '/') - { i--; - break; - } - } - version(Posix) - { - if (fullname[i - 1] == '/') - { i--; - break; - } - } - } - return fullname[0 .. i]; + for (i = fullname.length; i > 0; i--) + { + version(Win32) + { + if (fullname[i - 1] == ':') + break; + if (fullname[i - 1] == '\\' || fullname[i - 1] == '/') + { i--; + break; + } + } + version(Posix) + { + if (fullname[i - 1] == '/') + { i--; + break; + } + } + } + return fullname[0 .. i]; } unittest @@ -404,23 +404,23 @@ unittest string getDrive(string fullname) out (result) { - assert(result.length <= fullname.length); + assert(result.length <= fullname.length); } body { - version(Win32) - { - for (uint i = 0; i < fullname.length; i++) - { - if (fullname[i] == ':') - return fullname[0 .. i + 1]; - } - return null; - } - version(Posix) - { - return null; - } + version(Win32) + { + for (uint i = 0; i < fullname.length; i++) + { + if (fullname[i] == ':') + return fullname[0 .. i + 1]; + } + return null; + } + version(Posix) + { + return null; + } } /**************************** @@ -451,11 +451,11 @@ string defaultExt(string filename, string ext) existing = getExt(filename); if (existing.length == 0) { - // Check for filename ending in '.' - if (filename.length && filename[filename.length - 1] == '.') - filename ~= ext; - else - filename = filename ~ "." ~ ext; + // Check for filename ending in '.' + if (filename.length && filename[filename.length - 1] == '.') + filename ~= ext; + else + filename = filename ~ "." ~ ext; } return filename; } @@ -491,15 +491,15 @@ string addExt(string filename, string ext) existing = getExt(filename); if (existing.length == 0) { - // Check for filename ending in '.' - if (filename.length && filename[filename.length - 1] == '.') - filename ~= ext; - else - filename = filename ~ "." ~ ext; + // Check for filename ending in '.' + if (filename.length && filename[filename.length - 1] == '.') + filename ~= ext; + else + filename = filename ~ "." ~ ext; } else { - filename = filename[0 .. filename.length - existing.length] ~ ext; + filename = filename[0 .. filename.length - existing.length] ~ ext; } return filename; } @@ -536,10 +536,10 @@ int isabs(string path) version (Windows) { - return d.length && d.length < path.length && path[d.length] == sep[0]; + return d.length && d.length < path.length && path[d.length] == sep[0]; } else - return d.length < path.length && path[d.length] == sep[0]; + return d.length < path.length && path[d.length] == sep[0]; } unittest @@ -548,14 +548,14 @@ unittest version (Windows) { - assert(isabs(r"relative\path") == 0); - assert(isabs(r"\relative\path") == 0); - assert(isabs(r"d:\absolute") == 1); + assert(isabs(r"relative\path") == 0); + assert(isabs(r"\relative\path") == 0); + assert(isabs(r"d:\absolute") == 1); } version (Posix) { - assert(isabs("/home/user") == 1); - assert(isabs("foo") == 0); + assert(isabs("/home/user") == 1); + assert(isabs("foo") == 0); } } @@ -588,59 +588,59 @@ unittest string join(string p1, string p2) { if (!p2.length) - return p1; + return p1; if (!p1.length) - return p2; + return p2; string p; string d1; version(Win32) { - if (getDrive(p2)) - { - p = p2; - } - else - { - d1 = getDrive(p1); - if (p1.length == d1.length) - { - p = p1 ~ p2; - } - else if (p2[0] == '\\') - { - if (d1.length == 0) - p = p2; - else if (p1[p1.length - 1] == '\\') - p = p1 ~ p2[1 .. p2.length]; - else - p = p1 ~ p2; - } - else if (p1[p1.length - 1] == '\\') - { - p = p1 ~ p2; - } - else - { - p = p1 ~ sep ~ p2; - } - } + if (getDrive(p2)) + { + p = p2; + } + else + { + d1 = getDrive(p1); + if (p1.length == d1.length) + { + p = p1 ~ p2; + } + else if (p2[0] == '\\') + { + if (d1.length == 0) + p = p2; + else if (p1[p1.length - 1] == '\\') + p = p1 ~ p2[1 .. p2.length]; + else + p = p1 ~ p2; + } + else if (p1[p1.length - 1] == '\\') + { + p = p1 ~ p2; + } + else + { + p = p1 ~ sep ~ p2; + } + } } version(Posix) { - if (p2[0] == sep[0]) - { - p = p2; - } - else if (p1[p1.length - 1] == sep[0]) - { - p = p1 ~ p2; - } - else - { - p = p1 ~ sep ~ p2; - } + if (p2[0] == sep[0]) + { + p = p2; + } + else if (p1[p1.length - 1] == sep[0]) + { + p = p1 ~ p2; + } + else + { + p = p1 ~ sep ~ p2; + } } return p; } @@ -654,74 +654,74 @@ unittest p = join("foo", "bar"); version (Win32) - i = cmp(p, "foo\\bar"); + i = cmp(p, "foo\\bar"); version (Posix) - i = cmp(p, "foo/bar"); + i = cmp(p, "foo/bar"); assert(i == 0); version (Win32) - { p = join("foo\\", "bar"); - i = cmp(p, "foo\\bar"); + { p = join("foo\\", "bar"); + i = cmp(p, "foo\\bar"); } version (Posix) - { p = join("foo/", "bar"); - i = cmp(p, "foo/bar"); + { p = join("foo/", "bar"); + i = cmp(p, "foo/bar"); } assert(i == 0); version (Win32) - { p = join("foo", "\\bar"); - i = cmp(p, "\\bar"); + { p = join("foo", "\\bar"); + i = cmp(p, "\\bar"); } version (Posix) - { p = join("foo", "/bar"); - i = cmp(p, "/bar"); + { p = join("foo", "/bar"); + i = cmp(p, "/bar"); } assert(i == 0); version (Win32) - { p = join("foo\\", "\\bar"); - i = cmp(p, "\\bar"); + { p = join("foo\\", "\\bar"); + i = cmp(p, "\\bar"); } version (Posix) - { p = join("foo/", "/bar"); - i = cmp(p, "/bar"); + { p = join("foo/", "/bar"); + i = cmp(p, "/bar"); } assert(i == 0); version(Win32) { - p = join("d:", "bar"); - i = cmp(p, "d:bar"); - assert(i == 0); + p = join("d:", "bar"); + i = cmp(p, "d:bar"); + assert(i == 0); - p = join("d:\\", "bar"); - i = cmp(p, "d:\\bar"); - assert(i == 0); + p = join("d:\\", "bar"); + i = cmp(p, "d:\\bar"); + assert(i == 0); - p = join("d:\\", "\\bar"); - i = cmp(p, "d:\\bar"); - assert(i == 0); + p = join("d:\\", "\\bar"); + i = cmp(p, "d:\\bar"); + assert(i == 0); - p = join("d:\\foo", "bar"); - i = cmp(p, "d:\\foo\\bar"); - assert(i == 0); + p = join("d:\\foo", "bar"); + i = cmp(p, "d:\\foo\\bar"); + assert(i == 0); - p = join("d:", "\\bar"); - i = cmp(p, "d:\\bar"); - assert(i == 0); + p = join("d:", "\\bar"); + i = cmp(p, "d:\\bar"); + assert(i == 0); - p = join("foo", "d:"); - i = cmp(p, "d:"); - assert(i == 0); + p = join("foo", "d:"); + i = cmp(p, "d:"); + assert(i == 0); - p = join("foo", "d:\\"); - i = cmp(p, "d:\\"); - assert(i == 0); + p = join("foo", "d:\\"); + i = cmp(p, "d:\\"); + assert(i == 0); - p = join("foo", "d:\\bar"); - i = cmp(p, "d:\\bar"); - assert(i == 0); + p = join("foo", "d:\\bar"); + i = cmp(p, "d:\\bar"); + assert(i == 0); } } @@ -755,19 +755,19 @@ int fncharmatch(dchar c1, dchar c2) { version (Win32) { - if (c1 != c2) - { - if ('A' <= c1 && c1 <= 'Z') - c1 += cast(char)'a' - 'A'; - if ('A' <= c2 && c2 <= 'Z') - c2 += cast(char)'a' - 'A'; - return c1 == c2; - } - return true; + if (c1 != c2) + { + if ('A' <= c1 && c1 <= 'Z') + c1 += cast(char)'a' - 'A'; + if ('A' <= c2 && c2 <= 'Z') + c2 += cast(char)'a' - 'A'; + return c1 == c2; + } + return true; } version (Posix) { - return c1 == c2; + return c1 == c2; } } @@ -821,104 +821,104 @@ int fncharmatch(dchar c1, dchar c2) int fnmatch(string filename, string pattern) in { - // Verify that pattern[] is valid - int i; - int inbracket = false; + // Verify that pattern[] is valid + int i; + int inbracket = false; - for (i = 0; i < pattern.length; i++) - { - switch (pattern[i]) - { - case '[': - assert(!inbracket); - inbracket = true; - break; + for (i = 0; i < pattern.length; i++) + { + switch (pattern[i]) + { + case '[': + assert(!inbracket); + inbracket = true; + break; - case ']': - assert(inbracket); - inbracket = false; - break; + case ']': + assert(inbracket); + inbracket = false; + break; - default: - break; - } - } + default: + break; + } + } } body { - int pi; - int ni; - char pc; - char nc; - int j; - int not; - int anymatch; + int pi; + int ni; + char pc; + char nc; + int j; + int not; + int anymatch; - ni = 0; - for (pi = 0; pi < pattern.length; pi++) - { - pc = pattern[pi]; - switch (pc) - { - case '*': - if (pi + 1 == pattern.length) - goto match; - for (j = ni; j < filename.length; j++) - { - if (fnmatch(filename[j .. filename.length], pattern[pi + 1 .. pattern.length])) - goto match; - } - goto nomatch; + ni = 0; + for (pi = 0; pi < pattern.length; pi++) + { + pc = pattern[pi]; + switch (pc) + { + case '*': + if (pi + 1 == pattern.length) + goto match; + for (j = ni; j < filename.length; j++) + { + if (fnmatch(filename[j .. filename.length], pattern[pi + 1 .. pattern.length])) + goto match; + } + goto nomatch; - case '?': - if (ni == filename.length) - goto nomatch; - ni++; - break; + case '?': + if (ni == filename.length) + goto nomatch; + ni++; + break; - case '[': - if (ni == filename.length) - goto nomatch; - nc = filename[ni]; - ni++; - not = 0; - pi++; - if (pattern[pi] == '!') - { not = 1; - pi++; - } - anymatch = 0; - while (1) - { - pc = pattern[pi]; - if (pc == ']') - break; - if (!anymatch && fncharmatch(nc, pc)) - anymatch = 1; - pi++; - } - if (!(anymatch ^ not)) - goto nomatch; - break; + case '[': + if (ni == filename.length) + goto nomatch; + nc = filename[ni]; + ni++; + not = 0; + pi++; + if (pattern[pi] == '!') + { not = 1; + pi++; + } + anymatch = 0; + while (1) + { + pc = pattern[pi]; + if (pc == ']') + break; + if (!anymatch && fncharmatch(nc, pc)) + anymatch = 1; + pi++; + } + if (!(anymatch ^ not)) + goto nomatch; + break; - default: - if (ni == filename.length) - goto nomatch; - nc = filename[ni]; - if (!fncharmatch(pc, nc)) - goto nomatch; - ni++; - break; - } - } - if (ni < filename.length) - goto nomatch; + default: + if (ni == filename.length) + goto nomatch; + nc = filename[ni]; + if (!fncharmatch(pc, nc)) + goto nomatch; + ni++; + break; + } + } + if (ni < filename.length) + goto nomatch; match: - return true; + return true; nomatch: - return false; + return false; } unittest @@ -926,9 +926,9 @@ unittest debug(path) printf("path.fnmatch.unittest\n"); version (Win32) - assert(fnmatch("foo", "Foo")); + assert(fnmatch("foo", "Foo")); version (Posix) - assert(!fnmatch("foo", "Foo")); + assert(!fnmatch("foo", "Foo")); assert(fnmatch("foo", "*")); assert(fnmatch("foo.bar", "*")); assert(fnmatch("foo.bar", "*.*")); @@ -1011,25 +1011,25 @@ string expandTilde(string inputPath) { version(Posix) { - static assert(sep.length == 1); + static assert(sep.length == 1); // Return early if there is no tilde in path. if (inputPath.length < 1 || inputPath[0] != '~') - return inputPath; + return inputPath; - if (inputPath.length == 1 || inputPath[1] == sep[0]) - return expandFromEnvironment(inputPath); + if (inputPath.length == 1 || inputPath[1] == sep[0]) + return expandFromEnvironment(inputPath); else - return expandFromDatabase(inputPath); + return expandFromDatabase(inputPath); } else version(Windows) { - // Put here real windows implementation. - return inputPath; + // Put here real windows implementation. + return inputPath; } else { - static assert(0); // Guard. Implement on other platforms. + static assert(0); // Guard. Implement on other platforms. } } @@ -1040,36 +1040,36 @@ unittest version (Posix) { - // Retrieve the current home variable. - char* c_home = getenv("HOME"); + // Retrieve the current home variable. + char* c_home = getenv("HOME"); - // Testing when there is no environment variable. - unsetenv("HOME"); - assert(expandTilde("~/") == "~/"); - assert(expandTilde("~") == "~"); + // Testing when there is no environment variable. + unsetenv("HOME"); + assert(expandTilde("~/") == "~/"); + assert(expandTilde("~") == "~"); - // Testing when an environment variable is set. - int ret = setenv("HOME", "dmd/test\0", 1); - assert(ret == 0); - assert(expandTilde("~/") == "dmd/test/"); - assert(expandTilde("~") == "dmd/test"); + // Testing when an environment variable is set. + int ret = setenv("HOME", "dmd/test\0", 1); + assert(ret == 0); + assert(expandTilde("~/") == "dmd/test/"); + assert(expandTilde("~") == "dmd/test"); - // The same, but with a variable ending in a slash. - ret = setenv("HOME", "dmd/test/\0", 1); - assert(ret == 0); - assert(expandTilde("~/") == "dmd/test/"); - assert(expandTilde("~") == "dmd/test"); + // The same, but with a variable ending in a slash. + ret = setenv("HOME", "dmd/test/\0", 1); + assert(ret == 0); + assert(expandTilde("~/") == "dmd/test/"); + assert(expandTilde("~") == "dmd/test"); - // Recover original HOME variable before continuing. - if (c_home) - setenv("HOME", c_home, 1); - else - unsetenv("HOME"); + // Recover original HOME variable before continuing. + if (c_home) + setenv("HOME", c_home, 1); + else + unsetenv("HOME"); - // Test user expansion for root. Are there unices without /root? - assert(expandTilde("~root") == "/root"); - assert(expandTilde("~root/") == "/root/"); - assert(expandTilde("~Idontexist/hey") == "~Idontexist/hey"); + // Test user expansion for root. Are there unices without /root? + assert(expandTilde("~root") == "/root"); + assert(expandTilde("~root/") == "/root/"); + assert(expandTilde("~Idontexist/hey") == "~Idontexist/hey"); } } @@ -1083,7 +1083,7 @@ private string expandFromEnvironment(string path) { assert(path.length >= 1); assert(path[0] == '~'); - + // Get HOME and use that to replace the tilde. char* home = getenv("HOME"); if (home == null) @@ -1111,14 +1111,14 @@ private string combineCPathWithDPath(char* c_path, string path, int char_pos) // Remove trailing path separator, if any if (end && c_path[end - 1] == sep[0]) - end--; + end--; // Create our own copy, as lifetime of c_path is undocumented string cp = c_path[0 .. end].dup; // Do we append something from path? if (char_pos < path.length) - cp ~= path[char_pos .. length]; + cp ~= path[char_pos .. length]; return cp; } @@ -1139,14 +1139,14 @@ private string expandFromDatabase(string path) if (last_char == -1) { username = path[1 .. length] ~ '\0'; - last_char = username.length + 1; + last_char = username.length + 1; } else { username = path[1 .. last_char] ~ '\0'; } assert(last_char > 1); - + // Reserve C memory for the getpwnam_r() function. passwd result; int extra_memory_size = 5 * 1024; @@ -1154,29 +1154,29 @@ private string expandFromDatabase(string path) while (1) { - extra_memory = std.c.stdlib.malloc(extra_memory_size); - if (extra_memory == null) - goto Lerror; + extra_memory = std.c.stdlib.malloc(extra_memory_size); + if (extra_memory == null) + goto Lerror; - // Obtain info from database. - passwd *verify; - std.c.stdlib.setErrno(0); - if (getpwnam_r(username.ptr, &result, extra_memory, extra_memory_size, - &verify) == 0) - { - // Failure if verify doesn't point at result. - if (verify != &result) - // username is not found, so return path[] - goto Lnotfound; - break; - } + // Obtain info from database. + passwd *verify; + std.c.stdlib.setErrno(0); + if (getpwnam_r(username.ptr, &result, extra_memory, extra_memory_size, + &verify) == 0) + { + // Failure if verify doesn't point at result. + if (verify != &result) + // username is not found, so return path[] + goto Lnotfound; + break; + } - if (std.c.stdlib.getErrno() != ERANGE) - goto Lerror; + if (std.c.stdlib.getErrno() != ERANGE) + goto Lerror; - // extra_memory isn't large enough - std.c.stdlib.free(extra_memory); - extra_memory_size *= 2; + // extra_memory isn't large enough + std.c.stdlib.free(extra_memory); + extra_memory_size *= 2; } path = combineCPathWithDPath(result.pw_dir, path, last_char); @@ -1188,7 +1188,7 @@ Lnotfound: Lerror: // Errors are going to be caused by running out of memory if (extra_memory) - std.c.stdlib.free(extra_memory); + std.c.stdlib.free(extra_memory); _d_OutOfMemory(); return null; } diff --git a/std/perf.d b/std/perf.d index 021a52f0e..0a81978de 100644 --- a/std/perf.d +++ b/std/perf.d @@ -37,51 +37,51 @@ auto class PerformanceCounterScope(T) /// \name Construction /// @{ public: - /// Constructs an instance of the PerformanceCounterScope using a reference - /// to the parameterising performance counter class, whose measurement is - /// to be scoped. The measurement interval is commenced with a call to - /// start() on the managed counter instance. - this(T counter) - in - { - assert(null !is counter); - } - body - { - m_counter = counter; + /// Constructs an instance of the PerformanceCounterScope using a reference + /// to the parameterising performance counter class, whose measurement is + /// to be scoped. The measurement interval is commenced with a call to + /// start() on the managed counter instance. + this(T counter) + in + { + assert(null !is counter); + } + body + { + m_counter = counter; - m_counter.start(); - } - /// The measurement interval is completed with a call to stop() on the - /// managed counter instance. - ~this() - { - m_counter.stop(); - } + m_counter.start(); + } + /// The measurement interval is completed with a call to stop() on the + /// managed counter instance. + ~this() + { + m_counter.stop(); + } - /// Calls stop() on the managed counter instance, so that intermediate - /// timings can be taken. - void stop() - { - m_counter.stop(); - } + /// Calls stop() on the managed counter instance, so that intermediate + /// timings can be taken. + void stop() + { + m_counter.stop(); + } - /// Returns a reference to the managed counter instance. - T counter() - { - return m_counter; - } + /// Returns a reference to the managed counter instance. + T counter() + { + return m_counter; + } /// @} /// \name Members /// @{ private: - T m_counter; + T m_counter; /// @} // Not to be implemented private: - this(PerformanceCounterScope rhs); + this(PerformanceCounterScope rhs); } version(Posix) @@ -89,24 +89,24 @@ version(Posix) extern (C) { - private struct timeval - { - int tv_sec; /*!< The number of seconds, since Jan. 1, 1970, in the time value. */ - int tv_usec; /*!< The number of microseconds in the time value. */ - }; - private struct timezone - { - int tz_minuteswest; /*!< minutes west of Greenwich. */ - int tz_dsttime; /*!< type of dst corrections to apply. */ - }; - private void gettimeofday(timeval *tv, timezone *tz); + private struct timeval + { + int tv_sec; /*!< The number of seconds, since Jan. 1, 1970, in the time value. */ + int tv_usec; /*!< The number of microseconds in the time value. */ + }; + private struct timezone + { + int tz_minuteswest; /*!< minutes west of Greenwich. */ + int tz_dsttime; /*!< type of dst corrections to apply. */ + }; + private void gettimeofday(timeval *tv, timezone *tz); } /* ////////////////////////////////////////////////////////////////////////// */ /// \brief A performance counter that uses the most accurate measurement APIs available on the host machine /// - /// This class attempts to use the high performance hardware counter as its measurement resource, but failing + /// This class attempts to use the high performance hardware counter as its measurement resource, but failing /// that it defaults to less accurate resources in order to guarantee that meaningful measurements are always /// available to application code /// @@ -116,123 +116,123 @@ version(Posix) /// \name Types /// @{ private: - alias timeval epoch_type; + alias timeval epoch_type; public: - /// \brief The interval type - /// - /// The type of the interval measurement, a 64-bit signed integer - alias long interval_type; + /// \brief The interval type + /// + /// The type of the interval measurement, a 64-bit signed integer + alias long interval_type; - /// \brief The scope type - /// - /// The type with which instances of the counter class can be subject to the RAII mechanism in order - /// to scope particular measurement intervals - alias PerformanceCounterScope!(PerformanceCounter) scope_type; + /// \brief The scope type + /// + /// The type with which instances of the counter class can be subject to the RAII mechanism in order + /// to scope particular measurement intervals + alias PerformanceCounterScope!(PerformanceCounter) scope_type; /// @} /// \name Operations /// @{ public: - /// \brief Starts measurement - /// - /// Begins the measurement period - void start() - { - timezone tz; + /// \brief Starts measurement + /// + /// Begins the measurement period + void start() + { + timezone tz; - gettimeofday(&m_start, &tz); - } + gettimeofday(&m_start, &tz); + } - /// \brief Ends measurement - /// - /// Ends the measurement period - void stop() - { - timezone tz; + /// \brief Ends measurement + /// + /// Ends the measurement period + void stop() + { + timezone tz; - gettimeofday(&m_end, &tz); - } + gettimeofday(&m_end, &tz); + } /// @} /// \name Attributes /// @{ public: - /// \brief The elapsed count in the measurement period - /// - /// This represents the extent, in machine-specific increments, of the measurement period - interval_type periodCount() - { - return microseconds; - } + /// \brief The elapsed count in the measurement period + /// + /// This represents the extent, in machine-specific increments, of the measurement period + interval_type periodCount() + { + return microseconds; + } - /// \brief The number of whole seconds in the measurement period - /// - /// This represents the extent, in whole seconds, of the measurement period - interval_type seconds() - { - interval_type start = cast(interval_type)m_start.tv_sec + cast(interval_type)m_start.tv_usec / (1000 * 1000); - interval_type end = cast(interval_type)m_end.tv_sec + cast(interval_type)m_end.tv_usec / (1000 * 1000); + /// \brief The number of whole seconds in the measurement period + /// + /// This represents the extent, in whole seconds, of the measurement period + interval_type seconds() + { + interval_type start = cast(interval_type)m_start.tv_sec + cast(interval_type)m_start.tv_usec / (1000 * 1000); + interval_type end = cast(interval_type)m_end.tv_sec + cast(interval_type)m_end.tv_usec / (1000 * 1000); - return end - start; - } + return end - start; + } - /// \brief The number of whole milliseconds in the measurement period - /// - /// This represents the extent, in whole milliseconds, of the measurement period - interval_type milliseconds() - { - interval_type start = cast(interval_type)m_start.tv_sec * 1000 + cast(interval_type)m_start.tv_usec / 1000; - interval_type end = cast(interval_type)m_end.tv_sec * 1000 + cast(interval_type)m_end.tv_usec / 1000; + /// \brief The number of whole milliseconds in the measurement period + /// + /// This represents the extent, in whole milliseconds, of the measurement period + interval_type milliseconds() + { + interval_type start = cast(interval_type)m_start.tv_sec * 1000 + cast(interval_type)m_start.tv_usec / 1000; + interval_type end = cast(interval_type)m_end.tv_sec * 1000 + cast(interval_type)m_end.tv_usec / 1000; - return end - start; - } + return end - start; + } - /// \brief The number of whole microseconds in the measurement period - /// - /// This represents the extent, in whole microseconds, of the measurement period - interval_type microseconds() - { - interval_type start = cast(interval_type)m_start.tv_sec * 1000 * 1000 + cast(interval_type)m_start.tv_usec; - interval_type end = cast(interval_type)m_end.tv_sec * 1000 * 1000 + cast(interval_type)m_end.tv_usec; + /// \brief The number of whole microseconds in the measurement period + /// + /// This represents the extent, in whole microseconds, of the measurement period + interval_type microseconds() + { + interval_type start = cast(interval_type)m_start.tv_sec * 1000 * 1000 + cast(interval_type)m_start.tv_usec; + interval_type end = cast(interval_type)m_end.tv_sec * 1000 * 1000 + cast(interval_type)m_end.tv_usec; - return end - start; - } + return end - start; + } /// @} /// \name Members /// @{ private: - epoch_type m_start; // start of measurement period - epoch_type m_end; // End of measurement period + epoch_type m_start; // start of measurement period + epoch_type m_end; // End of measurement period /// @} } unittest { - alias PerformanceCounter counter_type; + alias PerformanceCounter counter_type; - counter_type counter = new counter_type(); + counter_type counter = new counter_type(); - counter.start(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us1 = counter.microseconds(); - counter_type.interval_type ms1 = counter.milliseconds(); - counter_type.interval_type s1 = counter.seconds(); + counter_type.interval_type us1 = counter.microseconds(); + counter_type.interval_type ms1 = counter.milliseconds(); + counter_type.interval_type s1 = counter.seconds(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us2 = counter.microseconds(); - counter_type.interval_type ms2 = counter.milliseconds(); - counter_type.interval_type s2 = counter.seconds(); + counter_type.interval_type us2 = counter.microseconds(); + counter_type.interval_type ms2 = counter.milliseconds(); + counter_type.interval_type s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ @@ -262,147 +262,147 @@ else version(Windows) /// \name Types /// @{ private: - alias long epoch_type; + alias long epoch_type; public: - /// \brief The interval type - /// - /// The type of the interval measurement, a 64-bit signed integer - alias long interval_type; + /// \brief The interval type + /// + /// The type of the interval measurement, a 64-bit signed integer + alias long interval_type; - /// \brief The scope type - /// - /// The type with which instances of the counter class can be subject to the RAII mechanism in order - /// to scope particular measurement intervals - alias PerformanceCounterScope!(HighPerformanceCounter) scope_type; + /// \brief The scope type + /// + /// The type with which instances of the counter class can be subject to the RAII mechanism in order + /// to scope particular measurement intervals + alias PerformanceCounterScope!(HighPerformanceCounter) scope_type; /// @} /// \name Construction /// @{ private: - static this() - { - if(!QueryPerformanceFrequency(&sm_freq)) - { - sm_freq = 0x7fffffffffffffffL; - } - } + static this() + { + if(!QueryPerformanceFrequency(&sm_freq)) + { + sm_freq = 0x7fffffffffffffffL; + } + } /// @} /// \name Operations /// @{ public: - /// \brief Starts measurement - /// - /// Begins the measurement period - void start() - { - QueryPerformanceCounter(&m_start); - } + /// \brief Starts measurement + /// + /// Begins the measurement period + void start() + { + QueryPerformanceCounter(&m_start); + } - /// \brief Ends measurement - /// - /// Ends the measurement period - void stop() - { - QueryPerformanceCounter(&m_end); - } + /// \brief Ends measurement + /// + /// Ends the measurement period + void stop() + { + QueryPerformanceCounter(&m_end); + } /// @} /// \name Attributes /// @{ public: - /// \brief The elapsed count in the measurement period - /// - /// This represents the extent, in machine-specific increments, of the measurement period - interval_type periodCount() - { - return m_end - m_start; - } + /// \brief The elapsed count in the measurement period + /// + /// This represents the extent, in machine-specific increments, of the measurement period + interval_type periodCount() + { + return m_end - m_start; + } - /// \brief The number of whole seconds in the measurement period - /// - /// This represents the extent, in whole seconds, of the measurement period - interval_type seconds() - { - return periodCount() / sm_freq; - } + /// \brief The number of whole seconds in the measurement period + /// + /// This represents the extent, in whole seconds, of the measurement period + interval_type seconds() + { + return periodCount() / sm_freq; + } - /// \brief The number of whole milliseconds in the measurement period - /// - /// This represents the extent, in whole milliseconds, of the measurement period - interval_type milliseconds() - { - interval_type result; - interval_type count = periodCount(); + /// \brief The number of whole milliseconds in the measurement period + /// + /// This represents the extent, in whole milliseconds, of the measurement period + interval_type milliseconds() + { + interval_type result; + interval_type count = periodCount(); - if(count < 0x20C49BA5E353F7L) - { - result = (count * 1000) / sm_freq; - } - else - { - result = (count / sm_freq) * 1000; - } + if(count < 0x20C49BA5E353F7L) + { + result = (count * 1000) / sm_freq; + } + else + { + result = (count / sm_freq) * 1000; + } - return result; - } + return result; + } - /// \brief The number of whole microseconds in the measurement period - /// - /// This represents the extent, in whole microseconds, of the measurement period - interval_type microseconds() - { - interval_type result; - interval_type count = periodCount(); + /// \brief The number of whole microseconds in the measurement period + /// + /// This represents the extent, in whole microseconds, of the measurement period + interval_type microseconds() + { + interval_type result; + interval_type count = periodCount(); - if(count < 0x8637BD05AF6L) - { - result = (count * 1000000) / sm_freq; - } - else - { - result = (count / sm_freq) * 1000000; - } + if(count < 0x8637BD05AF6L) + { + result = (count * 1000000) / sm_freq; + } + else + { + result = (count / sm_freq) * 1000000; + } - return result; - } + return result; + } /// @} /// \name Members /// @{ private: - epoch_type m_start; // start of measurement period - epoch_type m_end; // End of measurement period - static interval_type sm_freq; // Frequency + epoch_type m_start; // start of measurement period + epoch_type m_end; // End of measurement period + static interval_type sm_freq; // Frequency /// @} } unittest { - alias HighPerformanceCounter counter_type; + alias HighPerformanceCounter counter_type; - counter_type counter = new counter_type(); + counter_type counter = new counter_type(); - counter.start(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us1 = counter.microseconds(); - counter_type.interval_type ms1 = counter.milliseconds(); - counter_type.interval_type s1 = counter.seconds(); + counter_type.interval_type us1 = counter.microseconds(); + counter_type.interval_type ms1 = counter.milliseconds(); + counter_type.interval_type s1 = counter.seconds(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us2 = counter.microseconds(); - counter_type.interval_type ms2 = counter.milliseconds(); - counter_type.interval_type s2 = counter.seconds(); + counter_type.interval_type us2 = counter.microseconds(); + counter_type.interval_type ms2 = counter.milliseconds(); + counter_type.interval_type s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ @@ -418,18 +418,18 @@ else version(Windows) /// \name Types /// @{ private: - alias long epoch_type; + alias long epoch_type; public: - /// \brief The interval type - /// - /// The type of the interval measurement, a 64-bit signed integer - alias long interval_type; + /// \brief The interval type + /// + /// The type of the interval measurement, a 64-bit signed integer + alias long interval_type; - /// \brief The scope type - /// - /// The type with which instances of the counter class can be subject to the RAII mechanism in order - /// to scope particular measurement intervals - alias PerformanceCounterScope!(TickCounter) scope_type; + /// \brief The scope type + /// + /// The type with which instances of the counter class can be subject to the RAII mechanism in order + /// to scope particular measurement intervals + alias PerformanceCounterScope!(TickCounter) scope_type; /// @} /// \name Construction @@ -440,100 +440,100 @@ else version(Windows) /// \name Operations /// @{ public: - /// \brief Starts measurement - /// - /// Begins the measurement period - void start() - { - m_start = GetTickCount(); - } + /// \brief Starts measurement + /// + /// Begins the measurement period + void start() + { + m_start = GetTickCount(); + } - /// \brief Ends measurement - /// - /// Ends the measurement period - void stop() - { - m_end = GetTickCount(); - } + /// \brief Ends measurement + /// + /// Ends the measurement period + void stop() + { + m_end = GetTickCount(); + } /// @} /// \name Attributes /// @{ public: - /// \brief The elapsed count in the measurement period - /// - /// This represents the extent, in machine-specific increments, of the measurement period - interval_type periodCount() - { - return m_end - m_start; - } + /// \brief The elapsed count in the measurement period + /// + /// This represents the extent, in machine-specific increments, of the measurement period + interval_type periodCount() + { + return m_end - m_start; + } - /// \brief The number of whole seconds in the measurement period - /// - /// This represents the extent, in whole seconds, of the measurement period - interval_type seconds() - { - return periodCount() / 1000; - } + /// \brief The number of whole seconds in the measurement period + /// + /// This represents the extent, in whole seconds, of the measurement period + interval_type seconds() + { + return periodCount() / 1000; + } - /// \brief The number of whole milliseconds in the measurement period - /// - /// This represents the extent, in whole milliseconds, of the measurement period - interval_type milliseconds() - { - return periodCount(); - } + /// \brief The number of whole milliseconds in the measurement period + /// + /// This represents the extent, in whole milliseconds, of the measurement period + interval_type milliseconds() + { + return periodCount(); + } - /// \brief The number of whole microseconds in the measurement period - /// - /// This represents the extent, in whole microseconds, of the measurement period - interval_type microseconds() - { - return periodCount() * 1000; - } + /// \brief The number of whole microseconds in the measurement period + /// + /// This represents the extent, in whole microseconds, of the measurement period + interval_type microseconds() + { + return periodCount() * 1000; + } /// @} /// \name Members /// @{ private: - uint m_start; // start of measurement period - uint m_end; // End of measurement period + uint m_start; // start of measurement period + uint m_end; // End of measurement period /// @} } unittest { - alias TickCounter counter_type; + alias TickCounter counter_type; - counter_type counter = new counter_type(); + counter_type counter = new counter_type(); - counter.start(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us1 = counter.microseconds(); - counter_type.interval_type ms1 = counter.milliseconds(); - counter_type.interval_type s1 = counter.seconds(); + counter_type.interval_type us1 = counter.microseconds(); + counter_type.interval_type ms1 = counter.milliseconds(); + counter_type.interval_type s1 = counter.seconds(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us2 = counter.microseconds(); - counter_type.interval_type ms2 = counter.milliseconds(); - counter_type.interval_type s2 = counter.seconds(); + counter_type.interval_type us2 = counter.microseconds(); + counter_type.interval_type ms2 = counter.milliseconds(); + counter_type.interval_type s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ /// \brief A performance counter that provides thread-specific performance timings /// - /// This class uses the operating system's performance monitoring facilities to provide timing + /// This class uses the operating system's performance monitoring facilities to provide timing /// information pertaining to the calling thread only, irrespective of the activities of other /// threads on the system. This class does not provide meaningful timing information on operating /// systems that do not provide thread-specific monitoring. @@ -544,209 +544,209 @@ else version(Windows) /// \name Types /// @{ private: - alias long epoch_type; + alias long epoch_type; public: - /// \brief The interval type - /// - /// The type of the interval measurement, a 64-bit signed integer - alias long interval_type; + /// \brief The interval type + /// + /// The type of the interval measurement, a 64-bit signed integer + alias long interval_type; - /// \brief The scope type - /// - /// The type with which instances of the counter class can be subject to the RAII mechanism in order - /// to scope particular measurement intervals - alias PerformanceCounterScope!(ThreadTimesCounter) scope_type; + /// \brief The scope type + /// + /// The type with which instances of the counter class can be subject to the RAII mechanism in order + /// to scope particular measurement intervals + alias PerformanceCounterScope!(ThreadTimesCounter) scope_type; /// @} /// \name Construction /// @{ public: - /// \brief Constructor - /// - /// Creates an instance of the class, and caches the thread token so that measurements will - /// be taken with respect to the thread in which the class was created. - this() - { - m_thread = GetCurrentThread(); - } + /// \brief Constructor + /// + /// Creates an instance of the class, and caches the thread token so that measurements will + /// be taken with respect to the thread in which the class was created. + this() + { + m_thread = GetCurrentThread(); + } /// @} /// \name Operations /// @{ public: - /// \brief Starts measurement - /// - /// Begins the measurement period - void start() - { - FILETIME creationTime; - FILETIME exitTime; + /// \brief Starts measurement + /// + /// Begins the measurement period + void start() + { + FILETIME creationTime; + FILETIME exitTime; - GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); - } + GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); + } - /// \brief Ends measurement - /// - /// Ends the measurement period - void stop() - { - FILETIME creationTime; - FILETIME exitTime; + /// \brief Ends measurement + /// + /// Ends the measurement period + void stop() + { + FILETIME creationTime; + FILETIME exitTime; - GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); - } + GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); + } /// @} /// \name Attributes /// @{ public: - /// \name Kernel - /// @{ + /// \name Kernel + /// @{ - /// \brief The elapsed count in the measurement period for kernel mode activity - /// - /// This represents the extent, in machine-specific increments, of the measurement period for kernel mode activity - interval_type kernelPeriodCount() - { - return m_kernelEnd - m_kernelStart; - } - /// \brief The number of whole seconds in the measurement period for kernel mode activity - /// - /// This represents the extent, in whole seconds, of the measurement period for kernel mode activity - interval_type kernelSeconds() - { - return kernelPeriodCount() / 10000000; - } - /// \brief The number of whole milliseconds in the measurement period for kernel mode activity - /// - /// This represents the extent, in whole milliseconds, of the measurement period for kernel mode activity - interval_type kernelMilliseconds() - { - return kernelPeriodCount() / 10000; - } - /// \brief The number of whole microseconds in the measurement period for kernel mode activity - /// - /// This represents the extent, in whole microseconds, of the measurement period for kernel mode activity - interval_type kernelMicroseconds() - { - return kernelPeriodCount() / 10; - } - /// @} + /// \brief The elapsed count in the measurement period for kernel mode activity + /// + /// This represents the extent, in machine-specific increments, of the measurement period for kernel mode activity + interval_type kernelPeriodCount() + { + return m_kernelEnd - m_kernelStart; + } + /// \brief The number of whole seconds in the measurement period for kernel mode activity + /// + /// This represents the extent, in whole seconds, of the measurement period for kernel mode activity + interval_type kernelSeconds() + { + return kernelPeriodCount() / 10000000; + } + /// \brief The number of whole milliseconds in the measurement period for kernel mode activity + /// + /// This represents the extent, in whole milliseconds, of the measurement period for kernel mode activity + interval_type kernelMilliseconds() + { + return kernelPeriodCount() / 10000; + } + /// \brief The number of whole microseconds in the measurement period for kernel mode activity + /// + /// This represents the extent, in whole microseconds, of the measurement period for kernel mode activity + interval_type kernelMicroseconds() + { + return kernelPeriodCount() / 10; + } + /// @} - /// \name User - /// @{ + /// \name User + /// @{ - /// \brief The elapsed count in the measurement period for user mode activity - /// - /// This represents the extent, in machine-specific increments, of the measurement period for user mode activity - interval_type userPeriodCount() - { - return m_userEnd - m_userStart; - } - /// \brief The number of whole seconds in the measurement period for user mode activity - /// - /// This represents the extent, in whole seconds, of the measurement period for user mode activity - interval_type userSeconds() - { - return userPeriodCount() / 10000000; - } - /// \brief The number of whole milliseconds in the measurement period for user mode activity - /// - /// This represents the extent, in whole milliseconds, of the measurement period for user mode activity - interval_type userMilliseconds() - { - return userPeriodCount() / 10000; - } - /// \brief The number of whole microseconds in the measurement period for user mode activity - /// - /// This represents the extent, in whole microseconds, of the measurement period for user mode activity - interval_type userMicroseconds() - { - return userPeriodCount() / 10; - } - /// @} + /// \brief The elapsed count in the measurement period for user mode activity + /// + /// This represents the extent, in machine-specific increments, of the measurement period for user mode activity + interval_type userPeriodCount() + { + return m_userEnd - m_userStart; + } + /// \brief The number of whole seconds in the measurement period for user mode activity + /// + /// This represents the extent, in whole seconds, of the measurement period for user mode activity + interval_type userSeconds() + { + return userPeriodCount() / 10000000; + } + /// \brief The number of whole milliseconds in the measurement period for user mode activity + /// + /// This represents the extent, in whole milliseconds, of the measurement period for user mode activity + interval_type userMilliseconds() + { + return userPeriodCount() / 10000; + } + /// \brief The number of whole microseconds in the measurement period for user mode activity + /// + /// This represents the extent, in whole microseconds, of the measurement period for user mode activity + interval_type userMicroseconds() + { + return userPeriodCount() / 10; + } + /// @} - /// \name Total - /// @{ + /// \name Total + /// @{ - /// \brief The elapsed count in the measurement period - /// - /// This represents the extent, in machine-specific increments, of the measurement period - interval_type periodCount() - { - return kernelPeriodCount() + userPeriodCount(); - } + /// \brief The elapsed count in the measurement period + /// + /// This represents the extent, in machine-specific increments, of the measurement period + interval_type periodCount() + { + return kernelPeriodCount() + userPeriodCount(); + } - /// \brief The number of whole seconds in the measurement period - /// - /// This represents the extent, in whole seconds, of the measurement period - interval_type seconds() - { - return periodCount() / 10000000; - } + /// \brief The number of whole seconds in the measurement period + /// + /// This represents the extent, in whole seconds, of the measurement period + interval_type seconds() + { + return periodCount() / 10000000; + } - /// \brief The number of whole milliseconds in the measurement period - /// - /// This represents the extent, in whole milliseconds, of the measurement period - interval_type milliseconds() - { - return periodCount() / 10000; - } + /// \brief The number of whole milliseconds in the measurement period + /// + /// This represents the extent, in whole milliseconds, of the measurement period + interval_type milliseconds() + { + return periodCount() / 10000; + } - /// \brief The number of whole microseconds in the measurement period - /// - /// This represents the extent, in whole microseconds, of the measurement period - interval_type microseconds() - { - return periodCount() / 10; - } - /// @} + /// \brief The number of whole microseconds in the measurement period + /// + /// This represents the extent, in whole microseconds, of the measurement period + interval_type microseconds() + { + return periodCount() / 10; + } + /// @} /// @} /// \name Members /// @{ private: - epoch_type m_kernelStart; - epoch_type m_kernelEnd; - epoch_type m_userStart; - epoch_type m_userEnd; - HANDLE m_thread; + epoch_type m_kernelStart; + epoch_type m_kernelEnd; + epoch_type m_userStart; + epoch_type m_userEnd; + HANDLE m_thread; /// @} } unittest { - alias ThreadTimesCounter counter_type; + alias ThreadTimesCounter counter_type; - counter_type counter = new counter_type(); + counter_type counter = new counter_type(); - counter.start(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us1 = counter.microseconds(); - counter_type.interval_type ms1 = counter.milliseconds(); - counter_type.interval_type s1 = counter.seconds(); + counter_type.interval_type us1 = counter.microseconds(); + counter_type.interval_type ms1 = counter.milliseconds(); + counter_type.interval_type s1 = counter.seconds(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us2 = counter.microseconds(); - counter_type.interval_type ms2 = counter.milliseconds(); - counter_type.interval_type s2 = counter.seconds(); + counter_type.interval_type us2 = counter.microseconds(); + counter_type.interval_type ms2 = counter.milliseconds(); + counter_type.interval_type s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ /// \brief A performance counter that provides process-specific performance timings /// - /// This class uses the operating system's performance monitoring facilities to provide timing + /// This class uses the operating system's performance monitoring facilities to provide timing /// information pertaining to the calling process only, irrespective of the activities of other /// processes on the system. This class does not provide meaningful timing information on operating /// systems that do not provide process-specific monitoring. @@ -757,209 +757,209 @@ else version(Windows) /// \name Types /// @{ private: - alias long epoch_type; + alias long epoch_type; public: - /// \brief The interval type - /// - /// The type of the interval measurement, a 64-bit signed integer - alias long interval_type; + /// \brief The interval type + /// + /// The type of the interval measurement, a 64-bit signed integer + alias long interval_type; - /// \brief The scope type - /// - /// The type with which instances of the counter class can be subject to the RAII mechanism in order - /// to scope particular measurement intervals - alias PerformanceCounterScope!(ProcessTimesCounter) scope_type; + /// \brief The scope type + /// + /// The type with which instances of the counter class can be subject to the RAII mechanism in order + /// to scope particular measurement intervals + alias PerformanceCounterScope!(ProcessTimesCounter) scope_type; /// @} /// \name Construction /// @{ private: - /// \brief Class constructor - /// - /// Detects availability of the high performance hardware counter, and if - /// not available adjusts - static this() - { - sm_process = GetCurrentProcess(); - } + /// \brief Class constructor + /// + /// Detects availability of the high performance hardware counter, and if + /// not available adjusts + static this() + { + sm_process = GetCurrentProcess(); + } /// @} /// \name Operations /// @{ public: - /// \brief Starts measurement - /// - /// Begins the measurement period - void start() - { - FILETIME creationTime; - FILETIME exitTime; + /// \brief Starts measurement + /// + /// Begins the measurement period + void start() + { + FILETIME creationTime; + FILETIME exitTime; - GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); - } + GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); + } - /// \brief Ends measurement - /// - /// Ends the measurement period - void stop() - { - FILETIME creationTime; - FILETIME exitTime; + /// \brief Ends measurement + /// + /// Ends the measurement period + void stop() + { + FILETIME creationTime; + FILETIME exitTime; - GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); - } + GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); + } /// @} /// \name Attributes /// @{ public: - /// \name Kernel - /// @{ + /// \name Kernel + /// @{ - /// \brief The elapsed count in the measurement period for kernel mode activity - /// - /// This represents the extent, in machine-specific increments, of the measurement period for kernel mode activity - interval_type kernelPeriodCount() - { - return m_kernelEnd - m_kernelStart; - } - /// \brief The number of whole seconds in the measurement period for kernel mode activity - /// - /// This represents the extent, in whole seconds, of the measurement period for kernel mode activity - interval_type kernelSeconds() - { - return kernelPeriodCount() / 10000000; - } - /// \brief The number of whole milliseconds in the measurement period for kernel mode activity - /// - /// This represents the extent, in whole milliseconds, of the measurement period for kernel mode activity - interval_type kernelMilliseconds() - { - return kernelPeriodCount() / 10000; - } - /// \brief The number of whole microseconds in the measurement period for kernel mode activity - /// - /// This represents the extent, in whole microseconds, of the measurement period for kernel mode activity - interval_type kernelMicroseconds() - { - return kernelPeriodCount() / 10; - } - /// @} + /// \brief The elapsed count in the measurement period for kernel mode activity + /// + /// This represents the extent, in machine-specific increments, of the measurement period for kernel mode activity + interval_type kernelPeriodCount() + { + return m_kernelEnd - m_kernelStart; + } + /// \brief The number of whole seconds in the measurement period for kernel mode activity + /// + /// This represents the extent, in whole seconds, of the measurement period for kernel mode activity + interval_type kernelSeconds() + { + return kernelPeriodCount() / 10000000; + } + /// \brief The number of whole milliseconds in the measurement period for kernel mode activity + /// + /// This represents the extent, in whole milliseconds, of the measurement period for kernel mode activity + interval_type kernelMilliseconds() + { + return kernelPeriodCount() / 10000; + } + /// \brief The number of whole microseconds in the measurement period for kernel mode activity + /// + /// This represents the extent, in whole microseconds, of the measurement period for kernel mode activity + interval_type kernelMicroseconds() + { + return kernelPeriodCount() / 10; + } + /// @} - /// \name User - /// @{ + /// \name User + /// @{ - /// \brief The elapsed count in the measurement period for user mode activity - /// - /// This represents the extent, in machine-specific increments, of the measurement period for user mode activity - interval_type userPeriodCount() - { - return m_userEnd - m_userStart; - } - /// \brief The number of whole seconds in the measurement period for user mode activity - /// - /// This represents the extent, in whole seconds, of the measurement period for user mode activity - interval_type userSeconds() - { - return userPeriodCount() / 10000000; - } - /// \brief The number of whole milliseconds in the measurement period for user mode activity - /// - /// This represents the extent, in whole milliseconds, of the measurement period for user mode activity - interval_type userMilliseconds() - { - return userPeriodCount() / 10000; - } - /// \brief The number of whole microseconds in the measurement period for user mode activity - /// - /// This represents the extent, in whole microseconds, of the measurement period for user mode activity - interval_type userMicroseconds() - { - return userPeriodCount() / 10; - } - /// @} + /// \brief The elapsed count in the measurement period for user mode activity + /// + /// This represents the extent, in machine-specific increments, of the measurement period for user mode activity + interval_type userPeriodCount() + { + return m_userEnd - m_userStart; + } + /// \brief The number of whole seconds in the measurement period for user mode activity + /// + /// This represents the extent, in whole seconds, of the measurement period for user mode activity + interval_type userSeconds() + { + return userPeriodCount() / 10000000; + } + /// \brief The number of whole milliseconds in the measurement period for user mode activity + /// + /// This represents the extent, in whole milliseconds, of the measurement period for user mode activity + interval_type userMilliseconds() + { + return userPeriodCount() / 10000; + } + /// \brief The number of whole microseconds in the measurement period for user mode activity + /// + /// This represents the extent, in whole microseconds, of the measurement period for user mode activity + interval_type userMicroseconds() + { + return userPeriodCount() / 10; + } + /// @} - /// \name Total - /// @{ + /// \name Total + /// @{ - /// \brief The elapsed count in the measurement period - /// - /// This represents the extent, in machine-specific increments, of the measurement period - interval_type periodCount() - { - return kernelPeriodCount() + userPeriodCount(); - } + /// \brief The elapsed count in the measurement period + /// + /// This represents the extent, in machine-specific increments, of the measurement period + interval_type periodCount() + { + return kernelPeriodCount() + userPeriodCount(); + } - /// \brief The number of whole seconds in the measurement period - /// - /// This represents the extent, in whole seconds, of the measurement period - interval_type seconds() - { - return periodCount() / 10000000; - } + /// \brief The number of whole seconds in the measurement period + /// + /// This represents the extent, in whole seconds, of the measurement period + interval_type seconds() + { + return periodCount() / 10000000; + } - /// \brief The number of whole milliseconds in the measurement period - /// - /// This represents the extent, in whole milliseconds, of the measurement period - interval_type milliseconds() - { - return periodCount() / 10000; - } + /// \brief The number of whole milliseconds in the measurement period + /// + /// This represents the extent, in whole milliseconds, of the measurement period + interval_type milliseconds() + { + return periodCount() / 10000; + } - /// \brief The number of whole microseconds in the measurement period - /// - /// This represents the extent, in whole microseconds, of the measurement period - interval_type microseconds() - { - return periodCount() / 10; - } - /// @} + /// \brief The number of whole microseconds in the measurement period + /// + /// This represents the extent, in whole microseconds, of the measurement period + interval_type microseconds() + { + return periodCount() / 10; + } + /// @} /// @} /// \name Members /// @{ private: - epoch_type m_kernelStart; - epoch_type m_kernelEnd; - epoch_type m_userStart; - epoch_type m_userEnd; - static HANDLE sm_process; + epoch_type m_kernelStart; + epoch_type m_kernelEnd; + epoch_type m_userStart; + epoch_type m_userEnd; + static HANDLE sm_process; /// @} } unittest { - alias ProcessTimesCounter counter_type; + alias ProcessTimesCounter counter_type; - counter_type counter = new counter_type(); + counter_type counter = new counter_type(); - counter.start(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us1 = counter.microseconds(); - counter_type.interval_type ms1 = counter.milliseconds(); - counter_type.interval_type s1 = counter.seconds(); + counter_type.interval_type us1 = counter.microseconds(); + counter_type.interval_type ms1 = counter.milliseconds(); + counter_type.interval_type s1 = counter.seconds(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us2 = counter.microseconds(); - counter_type.interval_type ms2 = counter.milliseconds(); - counter_type.interval_type s2 = counter.seconds(); + counter_type.interval_type us2 = counter.microseconds(); + counter_type.interval_type ms2 = counter.milliseconds(); + counter_type.interval_type s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ /// \brief A performance counter that uses the most accurate measurement APIs available on the host machine /// - /// This class attempts to use the high performance hardware counter as its measurement resource, but failing + /// This class attempts to use the high performance hardware counter as its measurement resource, but failing /// that it defaults to less accurate resources in order to guarantee that meaningful measurements are always /// available to application code /// @@ -969,173 +969,173 @@ else version(Windows) /// \name Types /// @{ private: - alias long epoch_type; + alias long epoch_type; public: - /// \brief The interval type - /// - /// The type of the interval measurement, a 64-bit signed integer - alias long interval_type; + /// \brief The interval type + /// + /// The type of the interval measurement, a 64-bit signed integer + alias long interval_type; - /// \brief The scope type - /// - /// The type with which instances of the counter class can be subject to the RAII mechanism in order - /// to scope particular measurement intervals - alias PerformanceCounterScope!(PerformanceCounter) scope_type; + /// \brief The scope type + /// + /// The type with which instances of the counter class can be subject to the RAII mechanism in order + /// to scope particular measurement intervals + alias PerformanceCounterScope!(PerformanceCounter) scope_type; /// @} /// \name Constructors /// @{ private: - /// \brief Class constructor - /// - /// Detects availability of the high performance hardware counter, and if - /// not available adjusts - static this() - { - if(QueryPerformanceFrequency(&sm_freq)) - { - sm_fn = &_qpc; - } - else - { - sm_freq = 1000; - sm_fn = &_qtc; - } - } + /// \brief Class constructor + /// + /// Detects availability of the high performance hardware counter, and if + /// not available adjusts + static this() + { + if(QueryPerformanceFrequency(&sm_freq)) + { + sm_fn = &_qpc; + } + else + { + sm_freq = 1000; + sm_fn = &_qtc; + } + } /// @} /// \name Operations /// @{ public: - /// \brief Starts measurement - /// - /// Begins the measurement period - void start() - { - sm_fn(m_start); - } + /// \brief Starts measurement + /// + /// Begins the measurement period + void start() + { + sm_fn(m_start); + } - /// \brief Ends measurement - /// - /// Ends the measurement period - void stop() - { - sm_fn(m_end); - } + /// \brief Ends measurement + /// + /// Ends the measurement period + void stop() + { + sm_fn(m_end); + } /// @} /// \name Attributes /// @{ public: - /// \brief The elapsed count in the measurement period - /// - /// This represents the extent, in machine-specific increments, of the measurement period - interval_type periodCount() - { - return m_end - m_start; - } + /// \brief The elapsed count in the measurement period + /// + /// This represents the extent, in machine-specific increments, of the measurement period + interval_type periodCount() + { + return m_end - m_start; + } - /// \brief The number of whole seconds in the measurement period - /// - /// This represents the extent, in whole seconds, of the measurement period - interval_type seconds() - { - return periodCount() / sm_freq; - } + /// \brief The number of whole seconds in the measurement period + /// + /// This represents the extent, in whole seconds, of the measurement period + interval_type seconds() + { + return periodCount() / sm_freq; + } - /// \brief The number of whole milliseconds in the measurement period - /// - /// This represents the extent, in whole milliseconds, of the measurement period - interval_type milliseconds() - { - interval_type result; - interval_type count = periodCount(); + /// \brief The number of whole milliseconds in the measurement period + /// + /// This represents the extent, in whole milliseconds, of the measurement period + interval_type milliseconds() + { + interval_type result; + interval_type count = periodCount(); - if(count < 0x20C49BA5E353F7L) - { - result = (count * 1000) / sm_freq; - } - else - { - result = (count / sm_freq) * 1000; - } + if(count < 0x20C49BA5E353F7L) + { + result = (count * 1000) / sm_freq; + } + else + { + result = (count / sm_freq) * 1000; + } - return result; - } + return result; + } - /// \brief The number of whole microseconds in the measurement period - /// - /// This represents the extent, in whole microseconds, of the measurement period - interval_type microseconds() - { - interval_type result; - interval_type count = periodCount(); + /// \brief The number of whole microseconds in the measurement period + /// + /// This represents the extent, in whole microseconds, of the measurement period + interval_type microseconds() + { + interval_type result; + interval_type count = periodCount(); - if(count < 0x8637BD05AF6L) - { - result = (count * 1000000) / sm_freq; - } - else - { - result = (count / sm_freq) * 1000000; - } + if(count < 0x8637BD05AF6L) + { + result = (count * 1000000) / sm_freq; + } + else + { + result = (count / sm_freq) * 1000000; + } - return result; - } + return result; + } /// @} /// \name Implementation /// @{ private: - alias void function(out epoch_type interval) measure_func; + alias void function(out epoch_type interval) measure_func; - static void _qpc(out epoch_type interval) - { - QueryPerformanceCounter(&interval); - } + static void _qpc(out epoch_type interval) + { + QueryPerformanceCounter(&interval); + } - static void _qtc(out epoch_type interval) - { - interval = GetTickCount(); - } + static void _qtc(out epoch_type interval) + { + interval = GetTickCount(); + } /// @} /// \name Members /// @{ private: - epoch_type m_start; // start of measurement period - epoch_type m_end; // End of measurement period - static interval_type sm_freq; // Frequency - static measure_func sm_fn; // Measurement function + epoch_type m_start; // start of measurement period + epoch_type m_end; // End of measurement period + static interval_type sm_freq; // Frequency + static measure_func sm_fn; // Measurement function /// @} } unittest { - alias PerformanceCounter counter_type; + alias PerformanceCounter counter_type; - counter_type counter = new counter_type(); + counter_type counter = new counter_type(); - counter.start(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us1 = counter.microseconds(); - counter_type.interval_type ms1 = counter.milliseconds(); - counter_type.interval_type s1 = counter.seconds(); + counter_type.interval_type us1 = counter.microseconds(); + counter_type.interval_type ms1 = counter.milliseconds(); + counter_type.interval_type s1 = counter.seconds(); - volatile for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + volatile for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_type us2 = counter.microseconds(); - counter_type.interval_type ms2 = counter.milliseconds(); - counter_type.interval_type s2 = counter.seconds(); + counter_type.interval_type us2 = counter.microseconds(); + counter_type.interval_type ms2 = counter.milliseconds(); + counter_type.interval_type s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ diff --git a/std/random.d b/std/random.d index 46e5e36df..83fe80de8 100644 --- a/std/random.d +++ b/std/random.d @@ -2,7 +2,7 @@ /** * Macros: - * WIKI = Phobos/StdRandom + * WIKI = Phobos/StdRandom */ // random.d @@ -27,8 +27,8 @@ version (Posix) // BUG: not multithreaded -private uint seed; // starting seed -private uint index; // ith random number +private uint seed; // starting seed +private uint index; // ith random number /** * The random number generator is seeded at program startup with a random value. @@ -78,7 +78,7 @@ uint rand() loword = seed; hiword = index++; - for (i = 0; i < 4; i++) // loop limit can be 2..20, we choose 4 + for (i = 0; i < 4; i++) // loop limit can be 2..20, we choose 4 { hihold = hiword; // save hiword for later temp = hihold ^ xormix1[i]; // mix up bits of hiword @@ -98,23 +98,23 @@ static this() version(Win32) { - QueryPerformanceCounter(&s); + QueryPerformanceCounter(&s); } version(Posix) { - // time.h - // sys/time.h + // time.h + // sys/time.h - timeval tv; + timeval tv; - if (gettimeofday(&tv, null)) - { // Some error happened - try time() instead - s = time(null); - } - else - { - s = cast(ulong)((cast(long)tv.tv_sec << 32) + tv.tv_usec); - } + if (gettimeofday(&tv, null)) + { // Some error happened - try time() instead + s = time(null); + } + else + { + s = cast(ulong)((cast(long)tv.tv_sec << 32) + tv.tv_usec); + } } rand_seed(cast(uint) s, cast(uint)(s >> 32)); } @@ -124,16 +124,16 @@ unittest { static uint results[10] = [ - 0x8c0188cb, - 0xb161200c, - 0xfc904ac5, - 0x2702e049, - 0x9705a923, - 0x1c139d89, - 0x346b6d1f, - 0xf8c33e32, - 0xdb9fef76, - 0xa97fcb3f + 0x8c0188cb, + 0xb161200c, + 0xfc904ac5, + 0x2702e049, + 0x9705a923, + 0x1c139d89, + 0x346b6d1f, + 0xf8c33e32, + 0xdb9fef76, + 0xa97fcb3f ]; int i; uint seedsave = seed; @@ -141,9 +141,9 @@ unittest rand_seed(1234, 5678); for (i = 0; i < 10; i++) - { uint r = rand(); - //printf("0x%x,\n", rand()); - assert(r == results[i]); + { uint r = rand(); + //printf("0x%x,\n", rand()); + assert(r == results[i]); } seed = seedsave; diff --git a/std/regexp.d b/std/regexp.d index b6fcb84a5..ad004c1cf 100644 --- a/std/regexp.d +++ b/std/regexp.d @@ -36,102 +36,102 @@ * In the following guide, $(I pattern)[] refers to a * $(LINK2 http://www.digitalmars.com/ctg/regular.html, regular expression). * The $(I attributes)[] refers to - a string controlling the interpretation - of the regular expression. - It consists of a sequence of one or more - of the following characters: + a string controlling the interpretation + of the regular expression. + It consists of a sequence of one or more + of the following characters: - - - $(TR $(TH Attribute) $(TH Action)) - - $(TD $(B g)) - $(TD global; repeat over the whole input string) - - - $(TD $(B i)) - $(TD case insensitive) - - - $(TD $(B m)) - $(TD treat as multiple lines separated by newlines) - -
Attribute Characters
+ + + $(TR $(TH Attribute) $(TH Action)) + + $(TD $(B g)) + $(TD global; repeat over the whole input string) + + + $(TD $(B i)) + $(TD case insensitive) + + + $(TD $(B m)) + $(TD treat as multiple lines separated by newlines) + +
Attribute Characters
* * The $(I format)[] string has the formatting characters: * - * - - $(TR $(TH Format) $(TH Replaced With)) - $(TR - $(TD $(B $$)) $(TD $) - ) - $(TR - $(TD $(B $&)) $(TD The matched substring.) - ) - $(TR - $(TD $(B $`)) $(TD The portion of string that precedes the matched substring.) - ) - $(TR - $(TD $(B $')) $(TD The portion of string that follows the matched substring.) - ) - $(TR - $(TD $(B $(DOLLAR))$(I n)) $(TD The $(I n)th capture, where $(I n) - is a single digit 1-9 - and $$(I n) is not followed by a decimal digit.) - ) - $(TR - $(TD $(B $(DOLLAR))$(I nn)) $(TD The $(I nn)th capture, where $(I nn) - is a two-digit decimal - number 01-99. - If $(I nn)th capture is undefined or more than the number - of parenthesized subexpressions, use the empty - string instead.) - ) -
Formatting Characters
+ * + + $(TR $(TH Format) $(TH Replaced With)) + $(TR + $(TD $(B $$)) $(TD $) + ) + $(TR + $(TD $(B $&)) $(TD The matched substring.) + ) + $(TR + $(TD $(B $`)) $(TD The portion of string that precedes the matched substring.) + ) + $(TR + $(TD $(B $')) $(TD The portion of string that follows the matched substring.) + ) + $(TR + $(TD $(B $(DOLLAR))$(I n)) $(TD The $(I n)th capture, where $(I n) + is a single digit 1-9 + and $$(I n) is not followed by a decimal digit.) + ) + $(TR + $(TD $(B $(DOLLAR))$(I nn)) $(TD The $(I nn)th capture, where $(I nn) + is a two-digit decimal + number 01-99. + If $(I nn)th capture is undefined or more than the number + of parenthesized subexpressions, use the empty + string instead.) + ) +
Formatting Characters
- * Any other $ are left as is. + * Any other $ are left as is. * * References: - * $(LINK2 http://en.wikipedia.org/wiki/Regular_expressions, Wikipedia) + * $(LINK2 http://en.wikipedia.org/wiki/Regular_expressions, Wikipedia) * Macros: - * WIKI = StdRegexp - * DOLLAR = $ + * WIKI = StdRegexp + * DOLLAR = $ */ /* - Escape sequences: + Escape sequences: - \nnn starts out a 1, 2 or 3 digit octal sequence, - where n is an octal digit. If nnn is larger than - 0377, then the 3rd digit is not part of the sequence - and is not consumed. - For maximal portability, use exactly 3 digits. + \nnn starts out a 1, 2 or 3 digit octal sequence, + where n is an octal digit. If nnn is larger than + 0377, then the 3rd digit is not part of the sequence + and is not consumed. + For maximal portability, use exactly 3 digits. - \xXX starts out a 1 or 2 digit hex sequence. X - is a hex character. If the first character after the \x - is not a hex character, the value of the sequence is 'x' - and the XX are not consumed. - For maximal portability, use exactly 2 digits. + \xXX starts out a 1 or 2 digit hex sequence. X + is a hex character. If the first character after the \x + is not a hex character, the value of the sequence is 'x' + and the XX are not consumed. + For maximal portability, use exactly 2 digits. - \uUUUU is a unicode sequence. There are exactly - 4 hex characters after the \u, if any are not, then - the value of the sequence is 'u', and the UUUU are not - consumed. + \uUUUU is a unicode sequence. There are exactly + 4 hex characters after the \u, if any are not, then + the value of the sequence is 'u', and the UUUU are not + consumed. - Character classes: + Character classes: - [a-b], where a is greater than b, will produce - an error. + [a-b], where a is greater than b, will produce + an error. - References: + References: - http://www.unicode.org/unicode/reports/tr18/ + http://www.unicode.org/unicode/reports/tr18/ */ module std.regexp; -//debug = regexp; // uncomment to turn on debugging printf's +//debug = regexp; // uncomment to turn on debugging printf's private { @@ -161,38 +161,38 @@ class RegExpException : Exception { this(char[] msg) { - super(msg); + super(msg); } } struct regmatch_t { - int rm_so; // index of start of match - int rm_eo; // index past end of match + int rm_so; // index of start of match + int rm_eo; // index past end of match } -private alias char rchar; // so we can make a wchar version +private alias char rchar; // so we can make a wchar version /****************************************************** * Search string for matches with regular expression * pattern with attributes. * Replace each match with string generated from format. * Params: - * string = String to search. - * pattern = Regular expression pattern. - * format = Replacement string format. - * attributes = Regular expression attributes. + * string = String to search. + * pattern = Regular expression pattern. + * format = Replacement string format. + * attributes = Regular expression attributes. * Returns: - * the resulting string + * the resulting string * Example: - * Replace the letters 'a' with the letters 'ZZ'. + * Replace the letters 'a' with the letters 'ZZ'. * --- * s = "Strap a rocket engine on a chicken." * sub(s, "a", "ZZ") // result: StrZZp a rocket engine on a chicken. * sub(s, "a", "ZZ", "g") // result: StrZZp ZZ rocket engine on ZZ chicken. * --- - * The replacement format can reference the matches using - * the $&, $$, $', $`, $0 .. $99 notation: + * The replacement format can reference the matches using + * the $&, $$, $', $`, $0 .. $99 notation: * --- * sub(s, "[ar]", "[$&]", "g") // result: St[r][a]p [a] [r]ocket engine on [a] chi * --- @@ -220,10 +220,10 @@ unittest * Pass each match to delegate dg. * Replace each match with the return value from dg. * Params: - * string = String to search. - * pattern = Regular expression pattern. - * dg = Delegate - * attributes = Regular expression attributes. + * string = String to search. + * pattern = Regular expression pattern. + * dg = Delegate + * attributes = Regular expression attributes. * Returns: the resulting string. * Example: * Capitalize the letters 'a' and 'r': @@ -250,37 +250,37 @@ char[] sub(char[] string, char[] pattern, char[] delegate(RegExp) dg, char[] att offset = 0; while (r.test(string, lastindex)) { - int so = r.pmatch[0].rm_so; - int eo = r.pmatch[0].rm_eo; + int so = r.pmatch[0].rm_so; + int eo = r.pmatch[0].rm_eo; - rchar[] replacement = dg(r); + rchar[] replacement = dg(r); - // Optimize by using std.string.replace if possible - Dave Fladebo - rchar[] slice = result[offset + so .. offset + eo]; - if (r.attributes & RegExp.REA.global && // global, so replace all - !(r.attributes & RegExp.REA.ignoreCase) && // not ignoring case - !(r.attributes & RegExp.REA.multiline) && // not multiline - pattern == slice) // simple pattern (exact match, no special characters) - { - debug(regexp) - printf("pattern: %.*s, slice: %.*s, replacement: %.*s\n",pattern,result[offset + so .. offset + eo],replacement); - result = std.string.replace(result,slice,replacement); - break; - } + // Optimize by using std.string.replace if possible - Dave Fladebo + rchar[] slice = result[offset + so .. offset + eo]; + if (r.attributes & RegExp.REA.global && // global, so replace all + !(r.attributes & RegExp.REA.ignoreCase) && // not ignoring case + !(r.attributes & RegExp.REA.multiline) && // not multiline + pattern == slice) // simple pattern (exact match, no special characters) + { + debug(regexp) + printf("pattern: %.*s, slice: %.*s, replacement: %.*s\n",pattern,result[offset + so .. offset + eo],replacement); + result = std.string.replace(result,slice,replacement); + break; + } - result = replaceSlice(result, result[offset + so .. offset + eo], replacement); + result = replaceSlice(result, result[offset + so .. offset + eo], replacement); - if (r.attributes & RegExp.REA.global) - { - offset += replacement.length - (eo - so); + if (r.attributes & RegExp.REA.global) + { + offset += replacement.length - (eo - so); - if (lastindex == eo) - lastindex++; // always consume some source - else - lastindex = eo; - } - else - break; + if (lastindex == eo) + lastindex++; // always consume some source + else + lastindex = eo; + } + else + break; } delete r; @@ -300,12 +300,12 @@ unittest assert(r == "hello"); auto s = sub("Strap a rocket engine on a chicken.", - "[ar]", - delegate char[] (RegExp m) - { - return std.string.toupper(m.match(0)); - }, - "g"); + "[ar]", + delegate char[] (RegExp m) + { + return std.string.toupper(m.match(0)); + }, + "g"); assert(s == "StRAp A Rocket engine on A chicken."); } @@ -313,11 +313,11 @@ unittest /************************************************* * Search string[] for first match with pattern[] with attributes[]. * Params: - * string = String to search. - * pattern = Regular expression pattern. - * attributes = Regular expression attributes. + * string = String to search. + * pattern = Regular expression pattern. + * attributes = Regular expression attributes. * Returns: - * index into string[] of match if found, -1 if no match. + * index into string[] of match if found, -1 if no match. * Example: * --- * auto s = "abcabcabab"; @@ -333,7 +333,7 @@ int find(rchar[] string, char[] pattern, char[] attributes = null) auto r = new RegExp(pattern, attributes); if (r.test(string)) { - i = r.pmatch[0].rm_so; + i = r.pmatch[0].rm_so; } delete r; return i; @@ -355,11 +355,11 @@ unittest /************************************************* * Search string[] for last match with pattern[] with attributes[]. * Params: - * string = String to search. - * pattern = Regular expression pattern. - * attributes = Regular expression attributes. + * string = String to search. + * pattern = Regular expression pattern. + * attributes = Regular expression attributes. * Returns: - * index into string[] of match if found, -1 if no match. + * index into string[] of match if found, -1 if no match. * Example: * --- * auto s = "abcabcabab"; @@ -376,11 +376,11 @@ int rfind(rchar[] string, char[] pattern, char[] attributes = null) auto r = new RegExp(pattern, attributes); while (r.test(string, lastindex)) { int eo = r.pmatch[0].rm_eo; - i = r.pmatch[0].rm_so; - if (lastindex == eo) - lastindex++; // always consume some source - else - lastindex = eo; + i = r.pmatch[0].rm_so; + if (lastindex == eo) + lastindex++; // always consume some source + else + lastindex = eo; } delete r; return i; @@ -408,11 +408,11 @@ unittest * Split string[] into an array of strings, using the regular * expression pattern[] with attributes[] as the separator. * Params: - * string = String to search. - * pattern = Regular expression pattern. - * attributes = Regular expression attributes. + * string = String to search. + * pattern = Regular expression pattern. + * attributes = Regular expression attributes. * Returns: - * array of slices into string[] + * array of slices into string[] * Example: * --- * foreach (s; split("abcabcabab", "C.", "i")) @@ -446,22 +446,22 @@ unittest foreach (i, s; split("abcabcabab", "C.", "i")) { - writefln("s[%d] = '%s'", i, s); - if (i == 0) assert(s == "ab"); - else if (i == 1) assert(s == "b"); - else if (i == 2) assert(s == "bab"); - else assert(0); + writefln("s[%d] = '%s'", i, s); + if (i == 0) assert(s == "ab"); + else if (i == 1) assert(s == "b"); + else if (i == 2) assert(s == "bab"); + else assert(0); } } /**************************************************** * Search string[] for first match with pattern[] with attributes[]. * Params: - * string = String to search. - * pattern = Regular expression pattern. - * attributes = Regular expression attributes. + * string = String to search. + * pattern = Regular expression pattern. + * attributes = Regular expression attributes. * Returns: - * corresponding RegExp if found, null if not. + * corresponding RegExp if found, null if not. * Example: * --- * import std.stdio; @@ -487,8 +487,8 @@ RegExp search(char[] string, char[] pattern, char[] attributes = null) { } else - { delete r; - r = null; + { delete r; + r = null; } return r; } @@ -499,17 +499,17 @@ unittest if (auto m = std.regexp.search("abcdef", "c()")) { - auto result = std.string.format("%s[%s]%s", m.pre, m.match(0), m.post); - assert(result == "ab[c]def"); - assert(m.match(1) == null); - assert(m.match(2) == null); + auto result = std.string.format("%s[%s]%s", m.pre, m.match(0), m.post); + assert(result == "ab[c]def"); + assert(m.match(1) == null); + assert(m.match(2) == null); } else - assert(0); + assert(0); if (auto n = std.regexp.search("abcdef", "g")) { - assert(0); + assert(0); } } @@ -529,7 +529,7 @@ class RegExp * with attributes into * an internal form for fast execution. * Params: - * pattern = regular expression + * pattern = regular expression * attributes = _attributes * Throws: RegExpException if there are any compilation errors. * Example: @@ -541,14 +541,14 @@ class RegExp */ public this(rchar[] pattern, rchar[] attributes = null) { - pmatch = (&gmatch)[0 .. 1]; - compile(pattern, attributes); + pmatch = (&gmatch)[0 .. 1]; + compile(pattern, attributes); } /***** * Generate instance of RegExp. * Params: - * pattern = regular expression + * pattern = regular expression * attributes = _attributes * Throws: RegExpException if there are any compilation errors. * Example: @@ -560,31 +560,31 @@ class RegExp */ public static RegExp opCall(rchar[] pattern, rchar[] attributes = null) { - return new RegExp(pattern, attributes); + return new RegExp(pattern, attributes); } unittest { - debug(regexp) printf("regexp.opCall.unittest()\n"); - auto r1 = RegExp("hello", "m"); - char[] msg; - try - { - auto r2 = RegExp("hello", "q"); - assert(0); - } - catch (RegExpException ree) - { - msg = ree.toString(); - //writefln("message: %s", ree); - } - assert(msg == "unrecognized attribute"); + debug(regexp) printf("regexp.opCall.unittest()\n"); + auto r1 = RegExp("hello", "m"); + char[] msg; + try + { + auto r2 = RegExp("hello", "q"); + assert(0); + } + catch (RegExpException ree) + { + msg = ree.toString(); + //writefln("message: %s", ree); + } + assert(msg == "unrecognized attribute"); } /************************************ * Set up for start of foreach loop. * Returns: - * search() returns instance of RegExp set up to _search string[]. + * search() returns instance of RegExp set up to _search string[]. * Example: * --- * import std.stdio; @@ -607,42 +607,42 @@ class RegExp public RegExp search(rchar[] string) { - input = string; - pmatch[0].rm_eo = 0; - return this; + input = string; + pmatch[0].rm_eo = 0; + return this; } /** ditto */ public int opApply(int delegate(inout RegExp) dg) { - int result; - RegExp r = this; + int result; + RegExp r = this; - while (test()) - { - result = dg(r); - if (result) - break; - } + while (test()) + { + result = dg(r); + if (result) + break; + } - return result; + return result; } unittest { - debug(regexp) printf("regexp.search.unittest()\n"); + debug(regexp) printf("regexp.search.unittest()\n"); - int i; - foreach(m; RegExp("ab").search("abcabcabab")) - { - auto s = std.string.format("%s[%s]%s", m.pre, m.match(0), m.post); - if (i == 0) assert(s == "[ab]cabcabab"); - else if (i == 1) assert(s == "abc[ab]cabab"); - else if (i == 2) assert(s == "abcabc[ab]ab"); - else if (i == 3) assert(s == "abcabcab[ab]"); - else assert(0); - i++; - } + int i; + foreach(m; RegExp("ab").search("abcabcabab")) + { + auto s = std.string.format("%s[%s]%s", m.pre, m.match(0), m.post); + if (i == 0) assert(s == "[ab]cabcabab"); + else if (i == 1) assert(s == "abc[ab]cabab"); + else if (i == 2) assert(s == "abcabc[ab]ab"); + else if (i == 3) assert(s == "abcabcab[ab]"); + else assert(0); + i++; + } } /****************** @@ -655,16 +655,16 @@ class RegExp */ public char[] match(size_t n) { - if (n >= pmatch.length) - return null; - else - { size_t rm_so, rm_eo; - rm_so = pmatch[n].rm_so; - rm_eo = pmatch[n].rm_eo; - if (rm_so == rm_eo) - return null; - return input[rm_so .. rm_eo]; - } + if (n >= pmatch.length) + return null; + else + { size_t rm_so, rm_eo; + rm_so = pmatch[n].rm_so; + rm_eo = pmatch[n].rm_eo; + if (rm_so == rm_eo) + return null; + return input[rm_so .. rm_eo]; + } } /******************* @@ -672,7 +672,7 @@ class RegExp */ public char[] pre() { - return input[0 .. pmatch[0].rm_so]; + return input[0 .. pmatch[0].rm_so]; } /******************* @@ -680,19 +680,19 @@ class RegExp */ public char[] post() { - return input[pmatch[0].rm_eo .. $]; + return input[pmatch[0].rm_eo .. $]; } - uint re_nsub; // number of parenthesized subexpression matches - regmatch_t[] pmatch; // array [re_nsub + 1] + uint re_nsub; // number of parenthesized subexpression matches + regmatch_t[] pmatch; // array [re_nsub + 1] - rchar[] input; // the string to search + rchar[] input; // the string to search // per instance: - rchar[] pattern; // source text of the regular expression + rchar[] pattern; // source text of the regular expression - rchar[] flags; // source text of the attributes parameter + rchar[] flags; // source text of the attributes parameter int errors; @@ -700,22 +700,22 @@ class RegExp enum REA { - global = 1, // has the g attribute - ignoreCase = 2, // has the i attribute - multiline = 4, // if treat as multiple lines separated - // by newlines, or as a single line - dotmatchlf = 8, // if . matches \n + global = 1, // has the g attribute + ignoreCase = 2, // has the i attribute + multiline = 4, // if treat as multiple lines separated + // by newlines, or as a single line + dotmatchlf = 8, // if . matches \n } private: - size_t src; // current source index in input[] - size_t src_start; // starting index for match in input[] - size_t p; // position of parser in pattern[] - regmatch_t gmatch; // match for the entire regular expression - // (serves as storage for pmatch[0]) + size_t src; // current source index in input[] + size_t src_start; // starting index for match in input[] + size_t p; // position of parser in pattern[] + regmatch_t gmatch; // match for the entire regular expression + // (serves as storage for pmatch[0]) - ubyte[] program; // pattern[] compiled into regular expression program + ubyte[] program; // pattern[] compiled into regular expression program OutBuffer buf; @@ -727,30 +727,30 @@ private: enum : ubyte { - REend, // end of program - REchar, // single character - REichar, // single character, case insensitive - REdchar, // single UCS character - REidchar, // single wide character, case insensitive - REanychar, // any character - REanystar, // ".*" - REstring, // string of characters - REistring, // string of characters, case insensitive - REtestbit, // any in bitmap, non-consuming - REbit, // any in the bit map - REnotbit, // any not in the bit map - RErange, // any in the string - REnotrange, // any not in the string - REor, // a | b - REplus, // 1 or more - REstar, // 0 or more - REquest, // 0 or 1 - REnm, // n..m - REnmq, // n..m, non-greedy version - REbol, // beginning of line - REeol, // end of line - REparen, // parenthesized subexpression - REgoto, // goto offset + REend, // end of program + REchar, // single character + REichar, // single character, case insensitive + REdchar, // single UCS character + REidchar, // single wide character, case insensitive + REanychar, // any character + REanystar, // ".*" + REstring, // string of characters + REistring, // string of characters, case insensitive + REtestbit, // any in bitmap, non-consuming + REbit, // any in the bit map + REnotbit, // any not in the bit map + RErange, // any in the string + REnotrange, // any not in the string + REor, // a | b + REplus, // 1 or more + REstar, // 0 or more + REquest, // 0 or 1 + REnm, // n..m + REnmq, // n..m, non-greedy version + REbol, // beginning of line + REeol, // end of line + REparen, // parenthesized subexpression + REgoto, // goto offset REwordboundary, REnotwordboundary, @@ -780,20 +780,20 @@ public void compile(rchar[] pattern, rchar[] attributes) foreach (rchar c; attributes) { REA att; - switch (c) - { - case 'g': att = REA.global; break; - case 'i': att = REA.ignoreCase; break; - case 'm': att = REA.multiline; break; - default: - error("unrecognized attribute"); - return; - } - if (this.attributes & att) - { error("redundant attribute"); - return; - } - this.attributes |= att; + switch (c) + { + case 'g': att = REA.global; break; + case 'i': att = REA.ignoreCase; break; + case 'm': att = REA.multiline; break; + default: + error("unrecognized attribute"); + return; + } + if (this.attributes & att) + { error("redundant attribute"); + return; + } + this.attributes |= att; } input = null; @@ -810,7 +810,7 @@ public void compile(rchar[] pattern, rchar[] attributes) p = 0; parseRegexp(); if (p < pattern.length) - { error("unmatched ')'"); + { error("unmatched ')'"); } optimize(); program = buf.data; @@ -819,9 +819,9 @@ public void compile(rchar[] pattern, rchar[] attributes) if (re_nsub > oldre_nsub) { - if (pmatch.ptr is &gmatch) - pmatch = null; - pmatch.length = re_nsub + 1; + if (pmatch.ptr is &gmatch) + pmatch = null; + pmatch.length = re_nsub + 1; } pmatch[0].rm_so = 0; pmatch[0].rm_eo = 0; @@ -831,7 +831,7 @@ public void compile(rchar[] pattern, rchar[] attributes) * Split string[] into an array of strings, using the regular * expression as the separator. * Returns: - * array of slices into string[] + * array of slices into string[] */ public rchar[][] split(rchar[] string) @@ -842,38 +842,38 @@ public rchar[][] split(rchar[] string) if (string.length) { - int p = 0; - int q; - for (q = p; q != string.length;) - { - if (test(string, q)) - { int e; + int p = 0; + int q; + for (q = p; q != string.length;) + { + if (test(string, q)) + { int e; - q = pmatch[0].rm_so; - e = pmatch[0].rm_eo; - if (e != p) - { - result ~= string[p .. q]; - for (int i = 1; i < pmatch.length; i++) - { - int so = pmatch[i].rm_so; - int eo = pmatch[i].rm_eo; - if (so == eo) - { so = 0; // -1 gives array bounds error - eo = 0; - } - result ~= string[so .. eo]; - } - q = p = e; - continue; - } - } - q++; - } - result ~= string[p .. string.length]; + q = pmatch[0].rm_so; + e = pmatch[0].rm_eo; + if (e != p) + { + result ~= string[p .. q]; + for (int i = 1; i < pmatch.length; i++) + { + int so = pmatch[i].rm_so; + int eo = pmatch[i].rm_eo; + if (so == eo) + { so = 0; // -1 gives array bounds error + eo = 0; + } + result ~= string[so .. eo]; + } + q = p = e; + continue; + } + } + q++; + } + result ~= string[p .. string.length]; } else if (!test(string)) - result ~= string; + result ~= string; return result; } @@ -907,7 +907,7 @@ unittest for (i = 0; i < result.length; i++) { - //debug(regexp) printf("result[%d] = '%.*s'\n", i, result[i]); + //debug(regexp) printf("result[%d] = '%.*s'\n", i, result[i]); } j = join(result, ","); @@ -920,7 +920,7 @@ unittest j = join(result, ","); i = std.string.cmp(j, "ab"); assert(i == 0); - + result = r.match("ac"); j = join(result, ","); i = std.string.cmp(j, "ac"); @@ -930,7 +930,7 @@ unittest /************************************************* * Search string[] for match with regular expression. * Returns: - * index of match if successful, -1 if not found + * index of match if successful, -1 if not found */ public int find(rchar[] string) @@ -939,9 +939,9 @@ public int find(rchar[] string) i = test(string); if (i) - i = pmatch[0].rm_so; + i = pmatch[0].rm_so; else - i = -1; // no match + i = -1; // no match return i; } @@ -963,8 +963,8 @@ unittest /************************************************* * Search string[] for match. * Returns: - * If global attribute, return same value as exec(string). - * If not global attribute, return array of all matches. + * If global attribute, return same value as exec(string). + * If not global attribute, return array of all matches. */ public rchar[][] match(rchar[] string) @@ -973,21 +973,21 @@ public rchar[][] match(rchar[] string) if (attributes & REA.global) { - int lastindex = 0; + int lastindex = 0; - while (test(string, lastindex)) - { int eo = pmatch[0].rm_eo; + while (test(string, lastindex)) + { int eo = pmatch[0].rm_eo; - result ~= input[pmatch[0].rm_so .. eo]; - if (lastindex == eo) - lastindex++; // always consume some source - else - lastindex = eo; - } + result ~= input[pmatch[0].rm_so .. eo]; + if (lastindex == eo) + lastindex++; // always consume some source + else + lastindex = eo; + } } else { - result = exec(string); + result = exec(string); } return result; } @@ -1034,41 +1034,41 @@ public rchar[] replace(rchar[] string, rchar[] format) offset = 0; for (;;) { - if (!test(string, lastindex)) - break; + if (!test(string, lastindex)) + break; - int so = pmatch[0].rm_so; - int eo = pmatch[0].rm_eo; + int so = pmatch[0].rm_so; + int eo = pmatch[0].rm_eo; - rchar[] replacement = replace(format); + rchar[] replacement = replace(format); - // Optimize by using std.string.replace if possible - Dave Fladebo - rchar[] slice = result[offset + so .. offset + eo]; - if (attributes & REA.global && // global, so replace all - !(attributes & REA.ignoreCase) && // not ignoring case - !(attributes & REA.multiline) && // not multiline - pattern == slice && // simple pattern (exact match, no special characters) - format == replacement) // simple format, not $ formats - { - debug(regexp) - printf("pattern: %.*s, slice: %.*s, format: %.*s, replacement: %.*s\n",pattern,result[offset + so .. offset + eo],format,replacement); - result = std.string.replace(result,slice,replacement); - break; - } + // Optimize by using std.string.replace if possible - Dave Fladebo + rchar[] slice = result[offset + so .. offset + eo]; + if (attributes & REA.global && // global, so replace all + !(attributes & REA.ignoreCase) && // not ignoring case + !(attributes & REA.multiline) && // not multiline + pattern == slice && // simple pattern (exact match, no special characters) + format == replacement) // simple format, not $ formats + { + debug(regexp) + printf("pattern: %.*s, slice: %.*s, format: %.*s, replacement: %.*s\n",pattern,result[offset + so .. offset + eo],format,replacement); + result = std.string.replace(result,slice,replacement); + break; + } - result = replaceSlice(result, result[offset + so .. offset + eo], replacement); + result = replaceSlice(result, result[offset + so .. offset + eo], replacement); - if (attributes & REA.global) - { - offset += replacement.length - (eo - so); + if (attributes & REA.global) + { + offset += replacement.length - (eo - so); - if (lastindex == eo) - lastindex++; // always consume some source - else - lastindex = eo; - } - else - break; + if (lastindex == eo) + lastindex++; // always consume some source + else + lastindex = eo; + } + else + break; } return result; @@ -1097,7 +1097,7 @@ unittest /************************************************* * Search string[] for match. * Returns: - * array of slices into string[] representing matches + * array of slices into string[] representing matches */ public rchar[][] exec(rchar[] string) @@ -1113,21 +1113,21 @@ public rchar[][] exec(rchar[] string) * Pick up where last exec(string) or exec() left off, * searching string[] for next match. * Returns: - * array of slices into string[] representing matches + * array of slices into string[] representing matches */ public rchar[][] exec() { if (!test()) - return null; + return null; auto result = new rchar[][pmatch.length]; for (int i = 0; i < pmatch.length; i++) { - if (pmatch[i].rm_so == pmatch[i].rm_eo) - result[i] = null; - else - result[i] = input[pmatch[i].rm_so .. pmatch[i].rm_eo]; + if (pmatch[i].rm_so == pmatch[i].rm_eo) + result[i] = null; + else + result[i] = input[pmatch[i].rm_so .. pmatch[i].rm_eo]; } return result; @@ -1193,7 +1193,7 @@ public int test(char[] string, int startindex) pmatch[0].rm_eo = 0; if (startindex < 0 || startindex > input.length) { - return 0; // fail + return 0; // fail } //debug(regexp) printProgram(program); @@ -1201,62 +1201,62 @@ public int test(char[] string, int startindex) firstc = 0; if (program[0] == REchar) { - firstc = program[1]; - if (attributes & REA.ignoreCase && isalpha(firstc)) - firstc = 0; + firstc = program[1]; + if (attributes & REA.ignoreCase && isalpha(firstc)) + firstc = 0; } for (si = startindex; ; si++) { - if (firstc) - { - if (si == input.length) - break; // no match - if (input[si] != firstc) - { - si++; - if (!chr(si, firstc)) // if first character not found - break; // no match - } - } - for (int i = 0; i < re_nsub + 1; i++) - { - pmatch[i].rm_so = -1; - pmatch[i].rm_eo = -1; - } - src_start = src = si; - if (trymatch(0, program.length)) - { - pmatch[0].rm_so = si; - pmatch[0].rm_eo = src; - //debug(regexp) printf("start = %d, end = %d\n", gmatch.rm_so, gmatch.rm_eo); - return 1; - } - // If possible match must start at beginning, we are done - if (program[0] == REbol || program[0] == REanystar) - { - if (attributes & REA.multiline) - { - // Scan for the next \n - if (!chr(si, '\n')) - break; // no match if '\n' not found - } - else - break; - } - if (si == input.length) - break; - //debug(regexp) printf("Starting new try: '%.*s'\n", input[si + 1 .. input.length]); + if (firstc) + { + if (si == input.length) + break; // no match + if (input[si] != firstc) + { + si++; + if (!chr(si, firstc)) // if first character not found + break; // no match + } + } + for (int i = 0; i < re_nsub + 1; i++) + { + pmatch[i].rm_so = -1; + pmatch[i].rm_eo = -1; + } + src_start = src = si; + if (trymatch(0, program.length)) + { + pmatch[0].rm_so = si; + pmatch[0].rm_eo = src; + //debug(regexp) printf("start = %d, end = %d\n", gmatch.rm_so, gmatch.rm_eo); + return 1; + } + // If possible match must start at beginning, we are done + if (program[0] == REbol || program[0] == REanystar) + { + if (attributes & REA.multiline) + { + // Scan for the next \n + if (!chr(si, '\n')) + break; // no match if '\n' not found + } + else + break; + } + if (si == input.length) + break; + //debug(regexp) printf("Starting new try: '%.*s'\n", input[si + 1 .. input.length]); } - return 0; // no match + return 0; // no match } int chr(inout uint si, rchar c) { for (; si < input.length; si++) { - if (input[si] == c) - return 1; + if (input[si] == c) + return 1; } return 0; } @@ -1276,189 +1276,189 @@ void printProgram(ubyte[] prog) printf("printProgram()\n"); for (pc = 0; pc < prog.length; ) { - printf("%3d: ", pc); + printf("%3d: ", pc); - //printf("prog[pc] = %d, REchar = %d, REnmq = %d\n", prog[pc], REchar, REnmq); - switch (prog[pc]) - { - case REchar: - printf("\tREchar '%c'\n", prog[pc + 1]); - pc += 1 + char.sizeof; - break; + //printf("prog[pc] = %d, REchar = %d, REnmq = %d\n", prog[pc], REchar, REnmq); + switch (prog[pc]) + { + case REchar: + printf("\tREchar '%c'\n", prog[pc + 1]); + pc += 1 + char.sizeof; + break; - case REichar: - printf("\tREichar '%c'\n", prog[pc + 1]); - pc += 1 + char.sizeof; - break; + case REichar: + printf("\tREichar '%c'\n", prog[pc + 1]); + pc += 1 + char.sizeof; + break; - case REdchar: - printf("\tREdchar '%c'\n", *cast(dchar *)&prog[pc + 1]); - pc += 1 + dchar.sizeof; - break; + case REdchar: + printf("\tREdchar '%c'\n", *cast(dchar *)&prog[pc + 1]); + pc += 1 + dchar.sizeof; + break; - case REidchar: - printf("\tREidchar '%c'\n", *cast(dchar *)&prog[pc + 1]); - pc += 1 + dchar.sizeof; - break; + case REidchar: + printf("\tREidchar '%c'\n", *cast(dchar *)&prog[pc + 1]); + pc += 1 + dchar.sizeof; + break; - case REanychar: - printf("\tREanychar\n"); - pc++; - break; + case REanychar: + printf("\tREanychar\n"); + pc++; + break; - case REstring: - len = *cast(uint *)&prog[pc + 1]; - printf("\tREstring x%x, '%.*s'\n", len, - (&prog[pc + 1 + uint.sizeof])[0 .. len]); - pc += 1 + uint.sizeof + len * rchar.sizeof; - break; + case REstring: + len = *cast(uint *)&prog[pc + 1]; + printf("\tREstring x%x, '%.*s'\n", len, + (&prog[pc + 1 + uint.sizeof])[0 .. len]); + pc += 1 + uint.sizeof + len * rchar.sizeof; + break; - case REistring: - len = *cast(uint *)&prog[pc + 1]; - printf("\tREistring x%x, '%.*s'\n", len, - (&prog[pc + 1 + uint.sizeof])[0 .. len]); - pc += 1 + uint.sizeof + len * rchar.sizeof; - break; + case REistring: + len = *cast(uint *)&prog[pc + 1]; + printf("\tREistring x%x, '%.*s'\n", len, + (&prog[pc + 1 + uint.sizeof])[0 .. len]); + pc += 1 + uint.sizeof + len * rchar.sizeof; + break; - case REtestbit: - pu = cast(ushort *)&prog[pc + 1]; - printf("\tREtestbit %d, %d\n", pu[0], pu[1]); - len = pu[1]; - pc += 1 + 2 * ushort.sizeof + len; - break; + case REtestbit: + pu = cast(ushort *)&prog[pc + 1]; + printf("\tREtestbit %d, %d\n", pu[0], pu[1]); + len = pu[1]; + pc += 1 + 2 * ushort.sizeof + len; + break; - case REbit: - pu = cast(ushort *)&prog[pc + 1]; - len = pu[1]; - printf("\tREbit cmax=%02x, len=%d:", pu[0], len); - for (n = 0; n < len; n++) - printf(" %02x", prog[pc + 1 + 2 * ushort.sizeof + n]); - printf("\n"); - pc += 1 + 2 * ushort.sizeof + len; - break; + case REbit: + pu = cast(ushort *)&prog[pc + 1]; + len = pu[1]; + printf("\tREbit cmax=%02x, len=%d:", pu[0], len); + for (n = 0; n < len; n++) + printf(" %02x", prog[pc + 1 + 2 * ushort.sizeof + n]); + printf("\n"); + pc += 1 + 2 * ushort.sizeof + len; + break; - case REnotbit: - pu = cast(ushort *)&prog[pc + 1]; - printf("\tREnotbit %d, %d\n", pu[0], pu[1]); - len = pu[1]; - pc += 1 + 2 * ushort.sizeof + len; - break; + case REnotbit: + pu = cast(ushort *)&prog[pc + 1]; + printf("\tREnotbit %d, %d\n", pu[0], pu[1]); + len = pu[1]; + pc += 1 + 2 * ushort.sizeof + len; + break; - case RErange: - len = *cast(uint *)&prog[pc + 1]; - printf("\tRErange %d\n", len); - // BUG: REAignoreCase? - pc += 1 + uint.sizeof + len; - break; + case RErange: + len = *cast(uint *)&prog[pc + 1]; + printf("\tRErange %d\n", len); + // BUG: REAignoreCase? + pc += 1 + uint.sizeof + len; + break; - case REnotrange: - len = *cast(uint *)&prog[pc + 1]; - printf("\tREnotrange %d\n", len); - // BUG: REAignoreCase? - pc += 1 + uint.sizeof + len; - break; + case REnotrange: + len = *cast(uint *)&prog[pc + 1]; + printf("\tREnotrange %d\n", len); + // BUG: REAignoreCase? + pc += 1 + uint.sizeof + len; + break; - case REbol: - printf("\tREbol\n"); - pc++; - break; + case REbol: + printf("\tREbol\n"); + pc++; + break; - case REeol: - printf("\tREeol\n"); - pc++; - break; + case REeol: + printf("\tREeol\n"); + pc++; + break; - case REor: - len = *cast(uint *)&prog[pc + 1]; - printf("\tREor %d, pc=>%d\n", len, pc + 1 + uint.sizeof + len); - pc += 1 + uint.sizeof; - break; + case REor: + len = *cast(uint *)&prog[pc + 1]; + printf("\tREor %d, pc=>%d\n", len, pc + 1 + uint.sizeof + len); + pc += 1 + uint.sizeof; + break; - case REgoto: - len = *cast(uint *)&prog[pc + 1]; - printf("\tREgoto %d, pc=>%d\n", len, pc + 1 + uint.sizeof + len); - pc += 1 + uint.sizeof; - break; + case REgoto: + len = *cast(uint *)&prog[pc + 1]; + printf("\tREgoto %d, pc=>%d\n", len, pc + 1 + uint.sizeof + len); + pc += 1 + uint.sizeof; + break; - case REanystar: - printf("\tREanystar\n"); - pc++; - break; + case REanystar: + printf("\tREanystar\n"); + pc++; + break; - case REnm: - case REnmq: - // len, n, m, () - puint = cast(uint *)&prog[pc + 1]; - len = puint[0]; - n = puint[1]; - m = puint[2]; - printf("\tREnm%.*s len=%d, n=%u, m=%u, pc=>%d\n", - (prog[pc] == REnmq) ? "q" : " ", - len, n, m, pc + 1 + uint.sizeof * 3 + len); - pc += 1 + uint.sizeof * 3; - break; + case REnm: + case REnmq: + // len, n, m, () + puint = cast(uint *)&prog[pc + 1]; + len = puint[0]; + n = puint[1]; + m = puint[2]; + printf("\tREnm%.*s len=%d, n=%u, m=%u, pc=>%d\n", + (prog[pc] == REnmq) ? "q" : " ", + len, n, m, pc + 1 + uint.sizeof * 3 + len); + pc += 1 + uint.sizeof * 3; + break; - case REparen: - // len, n, () - puint = cast(uint *)&prog[pc + 1]; - len = puint[0]; - n = puint[1]; - printf("\tREparen len=%d n=%d, pc=>%d\n", len, n, pc + 1 + uint.sizeof * 2 + len); - pc += 1 + uint.sizeof * 2; - break; + case REparen: + // len, n, () + puint = cast(uint *)&prog[pc + 1]; + len = puint[0]; + n = puint[1]; + printf("\tREparen len=%d n=%d, pc=>%d\n", len, n, pc + 1 + uint.sizeof * 2 + len); + pc += 1 + uint.sizeof * 2; + break; - case REend: - printf("\tREend\n"); - return; + case REend: + printf("\tREend\n"); + return; - case REwordboundary: - printf("\tREwordboundary\n"); - pc++; - break; + case REwordboundary: + printf("\tREwordboundary\n"); + pc++; + break; - case REnotwordboundary: - printf("\tREnotwordboundary\n"); - pc++; - break; + case REnotwordboundary: + printf("\tREnotwordboundary\n"); + pc++; + break; - case REdigit: - printf("\tREdigit\n"); - pc++; - break; + case REdigit: + printf("\tREdigit\n"); + pc++; + break; - case REnotdigit: - printf("\tREnotdigit\n"); - pc++; - break; + case REnotdigit: + printf("\tREnotdigit\n"); + pc++; + break; - case REspace: - printf("\tREspace\n"); - pc++; - break; + case REspace: + printf("\tREspace\n"); + pc++; + break; - case REnotspace: - printf("\tREnotspace\n"); - pc++; - break; + case REnotspace: + printf("\tREnotspace\n"); + pc++; + break; - case REword: - printf("\tREword\n"); - pc++; - break; + case REword: + printf("\tREword\n"); + pc++; + break; - case REnotword: - printf("\tREnotword\n"); - pc++; - break; + case REnotword: + printf("\tREnotword\n"); + pc++; + break; - case REbackref: - printf("\tREbackref %d\n", prog[1]); - pc += 2; - break; + case REbackref: + printf("\tREbackref %d\n", prog[1]); + pc += 2; + break; - default: - assert(0); - } + default: + assert(0); + } } } } @@ -1467,8 +1467,8 @@ void printProgram(ubyte[] prog) /************************************************** * Match input against a section of the program[]. * Returns: - * 1 if successful match - * 0 no match + * 1 if successful match + * 0 no match */ int trymatch(int pc, int pcend) @@ -1486,516 +1486,516 @@ int trymatch(int pc, int pcend) uint* puint; debug(regexp) - printf("RegExp.trymatch(pc = %d, src = '%.*s', pcend = %d)\n", - pc, input[src .. input.length], pcend); + printf("RegExp.trymatch(pc = %d, src = '%.*s', pcend = %d)\n", + pc, input[src .. input.length], pcend); srcsave = src; psave = null; for (;;) { - if (pc == pcend) // if done matching - { debug(regex) printf("\tprogend\n"); - return 1; - } + if (pc == pcend) // if done matching + { debug(regex) printf("\tprogend\n"); + return 1; + } - //printf("\top = %d\n", program[pc]); - switch (program[pc]) - { - case REchar: - if (src == input.length) - goto Lnomatch; - debug(regexp) printf("\tREchar '%c', src = '%c'\n", program[pc + 1], input[src]); - if (program[pc + 1] != input[src]) - goto Lnomatch; - src++; - pc += 1 + char.sizeof; - break; + //printf("\top = %d\n", program[pc]); + switch (program[pc]) + { + case REchar: + if (src == input.length) + goto Lnomatch; + debug(regexp) printf("\tREchar '%c', src = '%c'\n", program[pc + 1], input[src]); + if (program[pc + 1] != input[src]) + goto Lnomatch; + src++; + pc += 1 + char.sizeof; + break; - case REichar: - if (src == input.length) - goto Lnomatch; - debug(regexp) printf("\tREichar '%c', src = '%c'\n", program[pc + 1], input[src]); - c1 = program[pc + 1]; - c2 = input[src]; - if (c1 != c2) - { - if (islower(cast(rchar)c2)) - c2 = std.ctype.toupper(cast(rchar)c2); - else - goto Lnomatch; - if (c1 != c2) - goto Lnomatch; - } - src++; - pc += 1 + char.sizeof; - break; + case REichar: + if (src == input.length) + goto Lnomatch; + debug(regexp) printf("\tREichar '%c', src = '%c'\n", program[pc + 1], input[src]); + c1 = program[pc + 1]; + c2 = input[src]; + if (c1 != c2) + { + if (islower(cast(rchar)c2)) + c2 = std.ctype.toupper(cast(rchar)c2); + else + goto Lnomatch; + if (c1 != c2) + goto Lnomatch; + } + src++; + pc += 1 + char.sizeof; + break; - case REdchar: - debug(regexp) printf("\tREdchar '%c', src = '%c'\n", *(cast(dchar *)&program[pc + 1]), input[src]); - if (src == input.length) - goto Lnomatch; - if (*(cast(dchar *)&program[pc + 1]) != input[src]) - goto Lnomatch; - src++; - pc += 1 + dchar.sizeof; - break; + case REdchar: + debug(regexp) printf("\tREdchar '%c', src = '%c'\n", *(cast(dchar *)&program[pc + 1]), input[src]); + if (src == input.length) + goto Lnomatch; + if (*(cast(dchar *)&program[pc + 1]) != input[src]) + goto Lnomatch; + src++; + pc += 1 + dchar.sizeof; + break; - case REidchar: - debug(regexp) printf("\tREidchar '%c', src = '%c'\n", *(cast(dchar *)&program[pc + 1]), input[src]); - if (src == input.length) - goto Lnomatch; - c1 = *(cast(dchar *)&program[pc + 1]); - c2 = input[src]; - if (c1 != c2) - { - if (islower(cast(rchar)c2)) - c2 = std.ctype.toupper(cast(rchar)c2); - else - goto Lnomatch; - if (c1 != c2) - goto Lnomatch; - } - src++; - pc += 1 + dchar.sizeof; - break; + case REidchar: + debug(regexp) printf("\tREidchar '%c', src = '%c'\n", *(cast(dchar *)&program[pc + 1]), input[src]); + if (src == input.length) + goto Lnomatch; + c1 = *(cast(dchar *)&program[pc + 1]); + c2 = input[src]; + if (c1 != c2) + { + if (islower(cast(rchar)c2)) + c2 = std.ctype.toupper(cast(rchar)c2); + else + goto Lnomatch; + if (c1 != c2) + goto Lnomatch; + } + src++; + pc += 1 + dchar.sizeof; + break; - case REanychar: - debug(regexp) printf("\tREanychar\n"); - if (src == input.length) - goto Lnomatch; - if (!(attributes & REA.dotmatchlf) && input[src] == cast(rchar)'\n') - goto Lnomatch; - src += std.utf.stride(input, src); - //src++; - pc++; - break; + case REanychar: + debug(regexp) printf("\tREanychar\n"); + if (src == input.length) + goto Lnomatch; + if (!(attributes & REA.dotmatchlf) && input[src] == cast(rchar)'\n') + goto Lnomatch; + src += std.utf.stride(input, src); + //src++; + pc++; + break; - case REstring: - len = *cast(uint *)&program[pc + 1]; - debug(regexp) printf("\tREstring x%x, '%.*s'\n", len, - (&program[pc + 1 + uint.sizeof])[0 .. len]); - if (src + len > input.length) - goto Lnomatch; - if (memcmp(&program[pc + 1 + uint.sizeof], &input[src], len * rchar.sizeof)) - goto Lnomatch; - src += len; - pc += 1 + uint.sizeof + len * rchar.sizeof; - break; + case REstring: + len = *cast(uint *)&program[pc + 1]; + debug(regexp) printf("\tREstring x%x, '%.*s'\n", len, + (&program[pc + 1 + uint.sizeof])[0 .. len]); + if (src + len > input.length) + goto Lnomatch; + if (memcmp(&program[pc + 1 + uint.sizeof], &input[src], len * rchar.sizeof)) + goto Lnomatch; + src += len; + pc += 1 + uint.sizeof + len * rchar.sizeof; + break; - case REistring: - len = *cast(uint *)&program[pc + 1]; - debug(regexp) printf("\tREistring x%x, '%.*s'\n", len, - (&program[pc + 1 + uint.sizeof])[0 .. len]); - if (src + len > input.length) - goto Lnomatch; - version (Win32) - { - if (memicmp(cast(char*)&program[pc + 1 + uint.sizeof], &input[src], len * rchar.sizeof)) - goto Lnomatch; - } - else - { - if (icmp((cast(char*)&program[pc + 1 + uint.sizeof])[0..len], - input[src .. src + len])) - goto Lnomatch; - } - src += len; - pc += 1 + uint.sizeof + len * rchar.sizeof; - break; + case REistring: + len = *cast(uint *)&program[pc + 1]; + debug(regexp) printf("\tREistring x%x, '%.*s'\n", len, + (&program[pc + 1 + uint.sizeof])[0 .. len]); + if (src + len > input.length) + goto Lnomatch; + version (Win32) + { + if (memicmp(cast(char*)&program[pc + 1 + uint.sizeof], &input[src], len * rchar.sizeof)) + goto Lnomatch; + } + else + { + if (icmp((cast(char*)&program[pc + 1 + uint.sizeof])[0..len], + input[src .. src + len])) + goto Lnomatch; + } + src += len; + pc += 1 + uint.sizeof + len * rchar.sizeof; + break; - case REtestbit: - pu = (cast(ushort *)&program[pc + 1]); - debug(regexp) printf("\tREtestbit %d, %d, '%c', x%02x\n", - pu[0], pu[1], input[src], input[src]); - if (src == input.length) - goto Lnomatch; - len = pu[1]; - c1 = input[src]; - //printf("[x%02x]=x%02x, x%02x\n", c1 >> 3, ((&program[pc + 1 + 4])[c1 >> 3] ), (1 << (c1 & 7))); - if (c1 <= pu[0] && - !((&(program[pc + 1 + 4]))[c1 >> 3] & (1 << (c1 & 7)))) - goto Lnomatch; - pc += 1 + 2 * ushort.sizeof + len; - break; + case REtestbit: + pu = (cast(ushort *)&program[pc + 1]); + debug(regexp) printf("\tREtestbit %d, %d, '%c', x%02x\n", + pu[0], pu[1], input[src], input[src]); + if (src == input.length) + goto Lnomatch; + len = pu[1]; + c1 = input[src]; + //printf("[x%02x]=x%02x, x%02x\n", c1 >> 3, ((&program[pc + 1 + 4])[c1 >> 3] ), (1 << (c1 & 7))); + if (c1 <= pu[0] && + !((&(program[pc + 1 + 4]))[c1 >> 3] & (1 << (c1 & 7)))) + goto Lnomatch; + pc += 1 + 2 * ushort.sizeof + len; + break; - case REbit: - pu = (cast(ushort *)&program[pc + 1]); - debug(regexp) printf("\tREbit %d, %d, '%c'\n", - pu[0], pu[1], input[src]); - if (src == input.length) - goto Lnomatch; - len = pu[1]; - c1 = input[src]; - if (c1 > pu[0]) - goto Lnomatch; - if (!((&program[pc + 1 + 4])[c1 >> 3] & (1 << (c1 & 7)))) - goto Lnomatch; - src++; - pc += 1 + 2 * ushort.sizeof + len; - break; + case REbit: + pu = (cast(ushort *)&program[pc + 1]); + debug(regexp) printf("\tREbit %d, %d, '%c'\n", + pu[0], pu[1], input[src]); + if (src == input.length) + goto Lnomatch; + len = pu[1]; + c1 = input[src]; + if (c1 > pu[0]) + goto Lnomatch; + if (!((&program[pc + 1 + 4])[c1 >> 3] & (1 << (c1 & 7)))) + goto Lnomatch; + src++; + pc += 1 + 2 * ushort.sizeof + len; + break; - case REnotbit: - pu = (cast(ushort *)&program[pc + 1]); - debug(regexp) printf("\tREnotbit %d, %d, '%c'\n", - pu[0], pu[1], input[src]); - if (src == input.length) - goto Lnomatch; - len = pu[1]; - c1 = input[src]; - if (c1 <= pu[0] && - ((&program[pc + 1 + 4])[c1 >> 3] & (1 << (c1 & 7)))) - goto Lnomatch; - src++; - pc += 1 + 2 * ushort.sizeof + len; - break; + case REnotbit: + pu = (cast(ushort *)&program[pc + 1]); + debug(regexp) printf("\tREnotbit %d, %d, '%c'\n", + pu[0], pu[1], input[src]); + if (src == input.length) + goto Lnomatch; + len = pu[1]; + c1 = input[src]; + if (c1 <= pu[0] && + ((&program[pc + 1 + 4])[c1 >> 3] & (1 << (c1 & 7)))) + goto Lnomatch; + src++; + pc += 1 + 2 * ushort.sizeof + len; + break; - case RErange: - len = *cast(uint *)&program[pc + 1]; - debug(regexp) printf("\tRErange %d\n", len); - if (src == input.length) - goto Lnomatch; - // BUG: REA.ignoreCase? - if (memchr(cast(char*)&program[pc + 1 + uint.sizeof], input[src], len) == null) - goto Lnomatch; - src++; - pc += 1 + uint.sizeof + len; - break; + case RErange: + len = *cast(uint *)&program[pc + 1]; + debug(regexp) printf("\tRErange %d\n", len); + if (src == input.length) + goto Lnomatch; + // BUG: REA.ignoreCase? + if (memchr(cast(char*)&program[pc + 1 + uint.sizeof], input[src], len) == null) + goto Lnomatch; + src++; + pc += 1 + uint.sizeof + len; + break; - case REnotrange: - len = *cast(uint *)&program[pc + 1]; - debug(regexp) printf("\tREnotrange %d\n", len); - if (src == input.length) - goto Lnomatch; - // BUG: REA.ignoreCase? - if (memchr(cast(char*)&program[pc + 1 + uint.sizeof], input[src], len) != null) - goto Lnomatch; - src++; - pc += 1 + uint.sizeof + len; - break; + case REnotrange: + len = *cast(uint *)&program[pc + 1]; + debug(regexp) printf("\tREnotrange %d\n", len); + if (src == input.length) + goto Lnomatch; + // BUG: REA.ignoreCase? + if (memchr(cast(char*)&program[pc + 1 + uint.sizeof], input[src], len) != null) + goto Lnomatch; + src++; + pc += 1 + uint.sizeof + len; + break; - case REbol: - debug(regexp) printf("\tREbol\n"); - if (src == 0) - { - } - else if (attributes & REA.multiline) - { - if (input[src - 1] != '\n') - goto Lnomatch; - } - else - goto Lnomatch; - pc++; - break; + case REbol: + debug(regexp) printf("\tREbol\n"); + if (src == 0) + { + } + else if (attributes & REA.multiline) + { + if (input[src - 1] != '\n') + goto Lnomatch; + } + else + goto Lnomatch; + pc++; + break; - case REeol: - debug(regexp) printf("\tREeol\n"); - if (src == input.length) - { - } - else if (attributes & REA.multiline && input[src] == '\n') - src++; - else - goto Lnomatch; - pc++; - break; + case REeol: + debug(regexp) printf("\tREeol\n"); + if (src == input.length) + { + } + else if (attributes & REA.multiline && input[src] == '\n') + src++; + else + goto Lnomatch; + pc++; + break; - case REor: - len = (cast(uint *)&program[pc + 1])[0]; - debug(regexp) printf("\tREor %d\n", len); - pop = pc + 1 + uint.sizeof; - ss = src; - if (trymatch(pop, pcend)) - { - if (pcend != program.length) - { int s; + case REor: + len = (cast(uint *)&program[pc + 1])[0]; + debug(regexp) printf("\tREor %d\n", len); + pop = pc + 1 + uint.sizeof; + ss = src; + if (trymatch(pop, pcend)) + { + if (pcend != program.length) + { int s; - s = src; - if (trymatch(pcend, program.length)) - { debug(regexp) printf("\tfirst operand matched\n"); - src = s; - return 1; - } - else - { - // If second branch doesn't match to end, take first anyway - src = ss; - if (!trymatch(pop + len, program.length)) - { - debug(regexp) printf("\tfirst operand matched\n"); - src = s; - return 1; - } - } - src = ss; - } - else - { debug(regexp) printf("\tfirst operand matched\n"); - return 1; - } - } - pc = pop + len; // proceed with 2nd branch - break; + s = src; + if (trymatch(pcend, program.length)) + { debug(regexp) printf("\tfirst operand matched\n"); + src = s; + return 1; + } + else + { + // If second branch doesn't match to end, take first anyway + src = ss; + if (!trymatch(pop + len, program.length)) + { + debug(regexp) printf("\tfirst operand matched\n"); + src = s; + return 1; + } + } + src = ss; + } + else + { debug(regexp) printf("\tfirst operand matched\n"); + return 1; + } + } + pc = pop + len; // proceed with 2nd branch + break; - case REgoto: - debug(regexp) printf("\tREgoto\n"); - len = (cast(uint *)&program[pc + 1])[0]; - pc += 1 + uint.sizeof + len; - break; + case REgoto: + debug(regexp) printf("\tREgoto\n"); + len = (cast(uint *)&program[pc + 1])[0]; + pc += 1 + uint.sizeof + len; + break; - case REanystar: - debug(regexp) printf("\tREanystar\n"); - pc++; - for (;;) - { int s1; - int s2; + case REanystar: + debug(regexp) printf("\tREanystar\n"); + pc++; + for (;;) + { int s1; + int s2; - s1 = src; - if (src == input.length) - break; - if (!(attributes & REA.dotmatchlf) && input[src] == '\n') - break; - src++; - s2 = src; + s1 = src; + if (src == input.length) + break; + if (!(attributes & REA.dotmatchlf) && input[src] == '\n') + break; + src++; + s2 = src; - // If no match after consumption, but it - // did match before, then no match - if (!trymatch(pc, program.length)) - { - src = s1; - // BUG: should we save/restore pmatch[]? - if (trymatch(pc, program.length)) - { - src = s1; // no match - break; - } - } - src = s2; - } - break; + // If no match after consumption, but it + // did match before, then no match + if (!trymatch(pc, program.length)) + { + src = s1; + // BUG: should we save/restore pmatch[]? + if (trymatch(pc, program.length)) + { + src = s1; // no match + break; + } + } + src = s2; + } + break; - case REnm: - case REnmq: - // len, n, m, () - puint = cast(uint *)&program[pc + 1]; - len = puint[0]; - n = puint[1]; - m = puint[2]; - debug(regexp) printf("\tREnm%s len=%d, n=%u, m=%u\n", (program[pc] == REnmq) ? cast(char*)"q" : cast(char*)"", len, n, m); - pop = pc + 1 + uint.sizeof * 3; - for (count = 0; count < n; count++) - { - if (!trymatch(pop, pop + len)) - goto Lnomatch; - } - if (!psave && count < m) - { - //version (Win32) - psave = cast(regmatch_t *)alloca((re_nsub + 1) * regmatch_t.sizeof); - //else - //psave = new regmatch_t[re_nsub + 1]; - } - if (program[pc] == REnmq) // if minimal munch - { - for (; count < m; count++) - { int s1; + case REnm: + case REnmq: + // len, n, m, () + puint = cast(uint *)&program[pc + 1]; + len = puint[0]; + n = puint[1]; + m = puint[2]; + debug(regexp) printf("\tREnm%s len=%d, n=%u, m=%u\n", (program[pc] == REnmq) ? cast(char*)"q" : cast(char*)"", len, n, m); + pop = pc + 1 + uint.sizeof * 3; + for (count = 0; count < n; count++) + { + if (!trymatch(pop, pop + len)) + goto Lnomatch; + } + if (!psave && count < m) + { + //version (Win32) + psave = cast(regmatch_t *)alloca((re_nsub + 1) * regmatch_t.sizeof); + //else + //psave = new regmatch_t[re_nsub + 1]; + } + if (program[pc] == REnmq) // if minimal munch + { + for (; count < m; count++) + { int s1; - memcpy(psave, pmatch.ptr, (re_nsub + 1) * regmatch_t.sizeof); - s1 = src; + memcpy(psave, pmatch.ptr, (re_nsub + 1) * regmatch_t.sizeof); + s1 = src; - if (trymatch(pop + len, program.length)) - { - src = s1; - memcpy(pmatch.ptr, psave, (re_nsub + 1) * regmatch_t.sizeof); - break; - } + if (trymatch(pop + len, program.length)) + { + src = s1; + memcpy(pmatch.ptr, psave, (re_nsub + 1) * regmatch_t.sizeof); + break; + } - if (!trymatch(pop, pop + len)) - { debug(regexp) printf("\tdoesn't match subexpression\n"); - break; - } + if (!trymatch(pop, pop + len)) + { debug(regexp) printf("\tdoesn't match subexpression\n"); + break; + } - // If source is not consumed, don't - // infinite loop on the match - if (s1 == src) - { debug(regexp) printf("\tsource is not consumed\n"); - break; - } - } - } - else // maximal munch - { - for (; count < m; count++) - { int s1; - int s2; + // If source is not consumed, don't + // infinite loop on the match + if (s1 == src) + { debug(regexp) printf("\tsource is not consumed\n"); + break; + } + } + } + else // maximal munch + { + for (; count < m; count++) + { int s1; + int s2; - memcpy(psave, pmatch.ptr, (re_nsub + 1) * regmatch_t.sizeof); - s1 = src; - if (!trymatch(pop, pop + len)) - { debug(regexp) printf("\tdoesn't match subexpression\n"); - break; - } - s2 = src; + memcpy(psave, pmatch.ptr, (re_nsub + 1) * regmatch_t.sizeof); + s1 = src; + if (!trymatch(pop, pop + len)) + { debug(regexp) printf("\tdoesn't match subexpression\n"); + break; + } + s2 = src; - // If source is not consumed, don't - // infinite loop on the match - if (s1 == s2) - { debug(regexp) printf("\tsource is not consumed\n"); - break; - } + // If source is not consumed, don't + // infinite loop on the match + if (s1 == s2) + { debug(regexp) printf("\tsource is not consumed\n"); + break; + } - // If no match after consumption, but it - // did match before, then no match - if (!trymatch(pop + len, program.length)) - { - src = s1; - if (trymatch(pop + len, program.length)) - { - src = s1; // no match - memcpy(pmatch.ptr, psave, (re_nsub + 1) * regmatch_t.sizeof); - break; - } - } - src = s2; - } - } - debug(regexp) printf("\tREnm len=%d, n=%u, m=%u, DONE count=%d\n", len, n, m, count); - pc = pop + len; - break; + // If no match after consumption, but it + // did match before, then no match + if (!trymatch(pop + len, program.length)) + { + src = s1; + if (trymatch(pop + len, program.length)) + { + src = s1; // no match + memcpy(pmatch.ptr, psave, (re_nsub + 1) * regmatch_t.sizeof); + break; + } + } + src = s2; + } + } + debug(regexp) printf("\tREnm len=%d, n=%u, m=%u, DONE count=%d\n", len, n, m, count); + pc = pop + len; + break; - case REparen: - // len, () - debug(regexp) printf("\tREparen\n"); - puint = cast(uint *)&program[pc + 1]; - len = puint[0]; - n = puint[1]; - pop = pc + 1 + uint.sizeof * 2; - ss = src; - if (!trymatch(pop, pop + len)) - goto Lnomatch; - pmatch[n + 1].rm_so = ss; - pmatch[n + 1].rm_eo = src; - pc = pop + len; - break; + case REparen: + // len, () + debug(regexp) printf("\tREparen\n"); + puint = cast(uint *)&program[pc + 1]; + len = puint[0]; + n = puint[1]; + pop = pc + 1 + uint.sizeof * 2; + ss = src; + if (!trymatch(pop, pop + len)) + goto Lnomatch; + pmatch[n + 1].rm_so = ss; + pmatch[n + 1].rm_eo = src; + pc = pop + len; + break; - case REend: - debug(regexp) printf("\tREend\n"); - return 1; // successful match + case REend: + debug(regexp) printf("\tREend\n"); + return 1; // successful match - case REwordboundary: - debug(regexp) printf("\tREwordboundary\n"); - if (src > 0 && src < input.length) - { - c1 = input[src - 1]; - c2 = input[src]; - if (!( - (isword(cast(rchar)c1) && !isword(cast(rchar)c2)) || - (!isword(cast(rchar)c1) && isword(cast(rchar)c2)) - ) - ) - goto Lnomatch; - } - pc++; - break; + case REwordboundary: + debug(regexp) printf("\tREwordboundary\n"); + if (src > 0 && src < input.length) + { + c1 = input[src - 1]; + c2 = input[src]; + if (!( + (isword(cast(rchar)c1) && !isword(cast(rchar)c2)) || + (!isword(cast(rchar)c1) && isword(cast(rchar)c2)) + ) + ) + goto Lnomatch; + } + pc++; + break; - case REnotwordboundary: - debug(regexp) printf("\tREnotwordboundary\n"); - if (src == 0 || src == input.length) - goto Lnomatch; - c1 = input[src - 1]; - c2 = input[src]; - if ( - (isword(cast(rchar)c1) && !isword(cast(rchar)c2)) || - (!isword(cast(rchar)c1) && isword(cast(rchar)c2)) - ) - goto Lnomatch; - pc++; - break; + case REnotwordboundary: + debug(regexp) printf("\tREnotwordboundary\n"); + if (src == 0 || src == input.length) + goto Lnomatch; + c1 = input[src - 1]; + c2 = input[src]; + if ( + (isword(cast(rchar)c1) && !isword(cast(rchar)c2)) || + (!isword(cast(rchar)c1) && isword(cast(rchar)c2)) + ) + goto Lnomatch; + pc++; + break; - case REdigit: - debug(regexp) printf("\tREdigit\n"); - if (src == input.length) - goto Lnomatch; - if (!isdigit(input[src])) - goto Lnomatch; - src++; - pc++; - break; + case REdigit: + debug(regexp) printf("\tREdigit\n"); + if (src == input.length) + goto Lnomatch; + if (!isdigit(input[src])) + goto Lnomatch; + src++; + pc++; + break; - case REnotdigit: - debug(regexp) printf("\tREnotdigit\n"); - if (src == input.length) - goto Lnomatch; - if (isdigit(input[src])) - goto Lnomatch; - src++; - pc++; - break; + case REnotdigit: + debug(regexp) printf("\tREnotdigit\n"); + if (src == input.length) + goto Lnomatch; + if (isdigit(input[src])) + goto Lnomatch; + src++; + pc++; + break; - case REspace: - debug(regexp) printf("\tREspace\n"); - if (src == input.length) - goto Lnomatch; - if (!isspace(input[src])) - goto Lnomatch; - src++; - pc++; - break; + case REspace: + debug(regexp) printf("\tREspace\n"); + if (src == input.length) + goto Lnomatch; + if (!isspace(input[src])) + goto Lnomatch; + src++; + pc++; + break; - case REnotspace: - debug(regexp) printf("\tREnotspace\n"); - if (src == input.length) - goto Lnomatch; - if (isspace(input[src])) - goto Lnomatch; - src++; - pc++; - break; + case REnotspace: + debug(regexp) printf("\tREnotspace\n"); + if (src == input.length) + goto Lnomatch; + if (isspace(input[src])) + goto Lnomatch; + src++; + pc++; + break; - case REword: - debug(regexp) printf("\tREword\n"); - if (src == input.length) - goto Lnomatch; - if (!isword(input[src])) - goto Lnomatch; - src++; - pc++; - break; + case REword: + debug(regexp) printf("\tREword\n"); + if (src == input.length) + goto Lnomatch; + if (!isword(input[src])) + goto Lnomatch; + src++; + pc++; + break; - case REnotword: - debug(regexp) printf("\tREnotword\n"); - if (src == input.length) - goto Lnomatch; - if (isword(input[src])) - goto Lnomatch; - src++; - pc++; - break; + case REnotword: + debug(regexp) printf("\tREnotword\n"); + if (src == input.length) + goto Lnomatch; + if (isword(input[src])) + goto Lnomatch; + src++; + pc++; + break; - case REbackref: - { - n = program[pc + 1]; - debug(regexp) printf("\tREbackref %d\n", n); + case REbackref: + { + n = program[pc + 1]; + debug(regexp) printf("\tREbackref %d\n", n); - int so = pmatch[n + 1].rm_so; - int eo = pmatch[n + 1].rm_eo; - len = eo - so; - if (src + len > input.length) - goto Lnomatch; - else if (attributes & REA.ignoreCase) - { - if (icmp(input[src .. src + len], input[so .. eo])) - goto Lnomatch; - } - else if (memcmp(&input[src], &input[so], len * rchar.sizeof)) - goto Lnomatch; - src += len; - pc += 2; - break; - } + int so = pmatch[n + 1].rm_so; + int eo = pmatch[n + 1].rm_eo; + len = eo - so; + if (src + len > input.length) + goto Lnomatch; + else if (attributes & REA.ignoreCase) + { + if (icmp(input[src .. src + len], input[so .. eo])) + goto Lnomatch; + } + else if (memcmp(&input[src], &input[so], len * rchar.sizeof)) + goto Lnomatch; + src += len; + pc += 2; + break; + } - default: - assert(0); - } + default: + assert(0); + } } Lnomatch: @@ -2016,35 +2016,35 @@ int parseRegexp() offset = buf.offset; for (;;) { - assert(p <= pattern.length); - if (p == pattern.length) - { buf.write(REend); - return 1; - } - switch (pattern[p]) - { - case ')': - return 1; + assert(p <= pattern.length); + if (p == pattern.length) + { buf.write(REend); + return 1; + } + switch (pattern[p]) + { + case ')': + return 1; - case '|': - p++; - gotooffset = buf.offset; - buf.write(REgoto); - buf.write(cast(uint)0); - len1 = buf.offset - offset; - buf.spread(offset, 1 + uint.sizeof); - gotooffset += 1 + uint.sizeof; - parseRegexp(); - len2 = buf.offset - (gotooffset + 1 + uint.sizeof); - buf.data[offset] = REor; - (cast(uint *)&buf.data[offset + 1])[0] = len1; - (cast(uint *)&buf.data[gotooffset + 1])[0] = len2; - break; + case '|': + p++; + gotooffset = buf.offset; + buf.write(REgoto); + buf.write(cast(uint)0); + len1 = buf.offset - offset; + buf.spread(offset, 1 + uint.sizeof); + gotooffset += 1 + uint.sizeof; + parseRegexp(); + len2 = buf.offset - (gotooffset + 1 + uint.sizeof); + buf.data[offset] = REor; + (cast(uint *)&buf.data[offset + 1])[0] = len1; + (cast(uint *)&buf.data[gotooffset + 1])[0] = len2; + break; - default: - parsePiece(); - break; - } + default: + parsePiece(); + break; + } } } @@ -2060,94 +2060,94 @@ int parsePiece() offset = buf.offset; parseAtom(); if (p == plength) - return 1; + return 1; switch (pattern[p]) { - case '*': - // Special optimization: replace .* with REanystar - if (buf.offset - offset == 1 && - buf.data[offset] == REanychar && - p + 1 < plength && - pattern[p + 1] != '?') - { - buf.data[offset] = REanystar; - p++; - break; - } + case '*': + // Special optimization: replace .* with REanystar + if (buf.offset - offset == 1 && + buf.data[offset] == REanychar && + p + 1 < plength && + pattern[p + 1] != '?') + { + buf.data[offset] = REanystar; + p++; + break; + } - n = 0; - m = inf; - goto Lnm; + n = 0; + m = inf; + goto Lnm; - case '+': - n = 1; - m = inf; - goto Lnm; + case '+': + n = 1; + m = inf; + goto Lnm; - case '?': - n = 0; - m = 1; - goto Lnm; + case '?': + n = 0; + m = 1; + goto Lnm; - case '{': // {n} {n,} {n,m} - p++; - if (p == plength || !isdigit(pattern[p])) - goto Lerr; - n = 0; - do - { - // BUG: handle overflow - n = n * 10 + pattern[p] - '0'; - p++; - if (p == plength) - goto Lerr; - } while (isdigit(pattern[p])); - if (pattern[p] == '}') // {n} - { m = n; - goto Lnm; - } - if (pattern[p] != ',') - goto Lerr; - p++; - if (p == plength) - goto Lerr; - if (pattern[p] == /*{*/ '}') // {n,} - { m = inf; - goto Lnm; - } - if (!isdigit(pattern[p])) - goto Lerr; - m = 0; // {n,m} - do - { - // BUG: handle overflow - m = m * 10 + pattern[p] - '0'; - p++; - if (p == plength) - goto Lerr; - } while (isdigit(pattern[p])); - if (pattern[p] != /*{*/ '}') - goto Lerr; - goto Lnm; + case '{': // {n} {n,} {n,m} + p++; + if (p == plength || !isdigit(pattern[p])) + goto Lerr; + n = 0; + do + { + // BUG: handle overflow + n = n * 10 + pattern[p] - '0'; + p++; + if (p == plength) + goto Lerr; + } while (isdigit(pattern[p])); + if (pattern[p] == '}') // {n} + { m = n; + goto Lnm; + } + if (pattern[p] != ',') + goto Lerr; + p++; + if (p == plength) + goto Lerr; + if (pattern[p] == /*{*/ '}') // {n,} + { m = inf; + goto Lnm; + } + if (!isdigit(pattern[p])) + goto Lerr; + m = 0; // {n,m} + do + { + // BUG: handle overflow + m = m * 10 + pattern[p] - '0'; + p++; + if (p == plength) + goto Lerr; + } while (isdigit(pattern[p])); + if (pattern[p] != /*{*/ '}') + goto Lerr; + goto Lnm; - Lnm: - p++; - op = REnm; - if (p < plength && pattern[p] == '?') - { op = REnmq; // minimal munch version - p++; - } - len = buf.offset - offset; - buf.spread(offset, 1 + uint.sizeof * 3); - buf.data[offset] = op; - uint* puint = cast(uint *)&buf.data[offset + 1]; - puint[0] = len; - puint[1] = n; - puint[2] = m; - break; + Lnm: + p++; + op = REnm; + if (p < plength && pattern[p] == '?') + { op = REnmq; // minimal munch version + p++; + } + len = buf.offset - offset; + buf.spread(offset, 1 + uint.sizeof * 3); + buf.data[offset] = op; + uint* puint = cast(uint *)&buf.data[offset + 1]; + puint[0] = len; + puint[1] = n; + puint[2] = m; + break; - default: - break; + default: + break; } return 1; @@ -2164,185 +2164,185 @@ int parseAtom() //printf("parseAtom() '%.*s'\n", pattern[p .. pattern.length]); if (p < pattern.length) { - c = pattern[p]; - switch (c) - { - case '*': - case '+': - case '?': - error("*+? not allowed in atom"); - p++; - return 0; + c = pattern[p]; + switch (c) + { + case '*': + case '+': + case '?': + error("*+? not allowed in atom"); + p++; + return 0; - case '(': - p++; - buf.write(REparen); - offset = buf.offset; - buf.write(cast(uint)0); // reserve space for length - buf.write(re_nsub); - re_nsub++; - parseRegexp(); - *cast(uint *)&buf.data[offset] = - buf.offset - (offset + uint.sizeof * 2); - if (p == pattern.length || pattern[p] != ')') - { - error("')' expected"); - return 0; - } - p++; - break; + case '(': + p++; + buf.write(REparen); + offset = buf.offset; + buf.write(cast(uint)0); // reserve space for length + buf.write(re_nsub); + re_nsub++; + parseRegexp(); + *cast(uint *)&buf.data[offset] = + buf.offset - (offset + uint.sizeof * 2); + if (p == pattern.length || pattern[p] != ')') + { + error("')' expected"); + return 0; + } + p++; + break; - case '[': - if (!parseRange()) - return 0; - break; + case '[': + if (!parseRange()) + return 0; + break; - case '.': - p++; - buf.write(REanychar); - break; + case '.': + p++; + buf.write(REanychar); + break; - case '^': - p++; - buf.write(REbol); - break; + case '^': + p++; + buf.write(REbol); + break; - case '$': - p++; - buf.write(REeol); - break; + case '$': + p++; + buf.write(REeol); + break; - case '\\': - p++; - if (p == pattern.length) - { error("no character past '\\'"); - return 0; - } - c = pattern[p]; - switch (c) - { - case 'b': op = REwordboundary; goto Lop; - case 'B': op = REnotwordboundary; goto Lop; - case 'd': op = REdigit; goto Lop; - case 'D': op = REnotdigit; goto Lop; - case 's': op = REspace; goto Lop; - case 'S': op = REnotspace; goto Lop; - case 'w': op = REword; goto Lop; - case 'W': op = REnotword; goto Lop; + case '\\': + p++; + if (p == pattern.length) + { error("no character past '\\'"); + return 0; + } + c = pattern[p]; + switch (c) + { + case 'b': op = REwordboundary; goto Lop; + case 'B': op = REnotwordboundary; goto Lop; + case 'd': op = REdigit; goto Lop; + case 'D': op = REnotdigit; goto Lop; + case 's': op = REspace; goto Lop; + case 'S': op = REnotspace; goto Lop; + case 'w': op = REword; goto Lop; + case 'W': op = REnotword; goto Lop; - Lop: - buf.write(op); - p++; - break; + Lop: + buf.write(op); + p++; + break; - case 'f': - case 'n': - case 'r': - case 't': - case 'v': - case 'c': - case 'x': - case 'u': - case '0': - c = cast(char)escape(); - goto Lbyte; + case 'f': + case 'n': + case 'r': + case 't': + case 'v': + case 'c': + case 'x': + case 'u': + case '0': + c = cast(char)escape(); + goto Lbyte; - case '1': case '2': case '3': - case '4': case '5': case '6': - case '7': case '8': case '9': - c -= '1'; - if (c < re_nsub) - { buf.write(REbackref); - buf.write(cast(ubyte)c); - } - else - { error("no matching back reference"); - return 0; - } - p++; - break; + case '1': case '2': case '3': + case '4': case '5': case '6': + case '7': case '8': case '9': + c -= '1'; + if (c < re_nsub) + { buf.write(REbackref); + buf.write(cast(ubyte)c); + } + else + { error("no matching back reference"); + return 0; + } + p++; + break; - default: - p++; - goto Lbyte; - } - break; + default: + p++; + goto Lbyte; + } + break; - default: - p++; - Lbyte: - op = REchar; - if (attributes & REA.ignoreCase) - { - if (isalpha(c)) - { - op = REichar; - c = cast(char)std.ctype.toupper(c); - } - } - if (op == REchar && c <= 0xFF) - { - // Look ahead and see if we can make this into - // an REstring - int q; - int len; + default: + p++; + Lbyte: + op = REchar; + if (attributes & REA.ignoreCase) + { + if (isalpha(c)) + { + op = REichar; + c = cast(char)std.ctype.toupper(c); + } + } + if (op == REchar && c <= 0xFF) + { + // Look ahead and see if we can make this into + // an REstring + int q; + int len; - for (q = p; q < pattern.length; ++q) - { rchar qc = pattern[q]; + for (q = p; q < pattern.length; ++q) + { rchar qc = pattern[q]; - switch (qc) - { - case '{': - case '*': - case '+': - case '?': - if (q == p) - goto Lchar; - q--; - break; + switch (qc) + { + case '{': + case '*': + case '+': + case '?': + if (q == p) + goto Lchar; + q--; + break; - case '(': case ')': - case '|': - case '[': case ']': - case '.': case '^': - case '$': case '\\': - case '}': - break; + case '(': case ')': + case '|': + case '[': case ']': + case '.': case '^': + case '$': case '\\': + case '}': + break; - default: - continue; - } - break; - } - len = q - p; - if (len > 0) - { - debug(regexp) printf("writing string len %d, c = '%c', pattern[p] = '%c'\n", len+1, c, pattern[p]); - buf.reserve(5 + (1 + len) * rchar.sizeof); - buf.write((attributes & REA.ignoreCase) ? REistring : REstring); - buf.write(len + 1); - buf.write(c); - buf.write(pattern[p .. p + len]); - p = q; - break; - } - } - if (c >= 0x80) - { - // Convert to dchar opcode - op = (op == REchar) ? REdchar : REidchar; - buf.write(op); - buf.write(c); - } - else - { - Lchar: - debug(regexp) printf("It's an REchar '%c'\n", c); - buf.write(op); - buf.write(cast(char)c); - } - break; - } + default: + continue; + } + break; + } + len = q - p; + if (len > 0) + { + debug(regexp) printf("writing string len %d, c = '%c', pattern[p] = '%c'\n", len+1, c, pattern[p]); + buf.reserve(5 + (1 + len) * rchar.sizeof); + buf.write((attributes & REA.ignoreCase) ? REistring : REstring); + buf.write(len + 1); + buf.write(c); + buf.write(pattern[p .. p + len]); + p = q; + break; + } + } + if (c >= 0x80) + { + // Convert to dchar opcode + op = (op == REchar) ? REdchar : REidchar; + buf.write(op); + buf.write(c); + } + else + { + Lchar: + debug(regexp) printf("It's an REchar '%c'\n", c); + buf.write(op); + buf.write(cast(char)c); + } + break; + } } return 1; } @@ -2358,38 +2358,38 @@ class Range this(OutBuffer buf) { - this.buf = buf; - if (buf.data.length) - this.base = &buf.data[buf.offset]; + this.buf = buf; + if (buf.data.length) + this.base = &buf.data[buf.offset]; } void setbitmax(uint u) { uint b; - //printf("setbitmax(x%x), maxc = x%x\n", u, maxc); - if (u > maxc) - { - maxc = u; - b = u / 8; - if (b >= maxb) - { uint u2; + //printf("setbitmax(x%x), maxc = x%x\n", u, maxc); + if (u > maxc) + { + maxc = u; + b = u / 8; + if (b >= maxb) + { uint u2; - u2 = base ? base - &buf.data[0] : 0; - buf.fill0(b - maxb + 1); - base = &buf.data[u2]; - maxb = b + 1; - //bits = (cast(bit*)this.base)[0 .. maxc + 1]; - bits.ptr = cast(uint*)this.base; - } - bits.len = maxc + 1; - } + u2 = base ? base - &buf.data[0] : 0; + buf.fill0(b - maxb + 1); + base = &buf.data[u2]; + maxb = b + 1; + //bits = (cast(bit*)this.base)[0 .. maxc + 1]; + bits.ptr = cast(uint*)this.base; + } + bits.len = maxc + 1; + } } void setbit2(uint u) { - setbitmax(u + 1); - //printf("setbit2 [x%02x] |= x%02x\n", u >> 3, 1 << (u & 7)); - bits[u] = 1; + setbitmax(u + 1); + //printf("setbit2 [x%02x] |= x%02x\n", u >> 3, 1 << (u & 7)); + bits[u] = 1; } }; @@ -2406,31 +2406,31 @@ int parseRange() p++; op = REbit; if (p == pattern.length) - goto Lerr; + goto Lerr; if (pattern[p] == '^') { p++; - op = REnotbit; - if (p == pattern.length) - goto Lerr; + op = REnotbit; + if (p == pattern.length) + goto Lerr; } buf.write(op); offset = buf.offset; - buf.write(cast(uint)0); // reserve space for length + buf.write(cast(uint)0); // reserve space for length buf.reserve(128 / 8); auto r = new Range(buf); if (op == REnotbit) - r.setbit2(0); + r.setbit2(0); switch (pattern[p]) { - case ']': - case '-': - c = pattern[p]; - p++; - r.setbit2(c); - break; + case ']': + case '-': + c = pattern[p]; + p++; + r.setbit2(c); + break; - default: - break; + default: + break; } enum RS { start, rliteral, dash }; @@ -2439,143 +2439,143 @@ int parseRange() rs = RS.start; for (;;) { - if (p == pattern.length) - goto Lerr; - switch (pattern[p]) - { - case ']': - switch (rs) - { case RS.dash: - r.setbit2('-'); - case RS.rliteral: - r.setbit2(c); - break; - case RS.start: - break; - default: - assert(0); - } - p++; - break; + if (p == pattern.length) + goto Lerr; + switch (pattern[p]) + { + case ']': + switch (rs) + { case RS.dash: + r.setbit2('-'); + case RS.rliteral: + r.setbit2(c); + break; + case RS.start: + break; + default: + assert(0); + } + p++; + break; - case '\\': - p++; - r.setbitmax(cmax); - if (p == pattern.length) - goto Lerr; - switch (pattern[p]) - { - case 'd': - for (i = '0'; i <= '9'; i++) - r.bits[i] = 1; - goto Lrs; + case '\\': + p++; + r.setbitmax(cmax); + if (p == pattern.length) + goto Lerr; + switch (pattern[p]) + { + case 'd': + for (i = '0'; i <= '9'; i++) + r.bits[i] = 1; + goto Lrs; - case 'D': - for (i = 1; i < '0'; i++) - r.bits[i] = 1; - for (i = '9' + 1; i <= cmax; i++) - r.bits[i] = 1; - goto Lrs; + case 'D': + for (i = 1; i < '0'; i++) + r.bits[i] = 1; + for (i = '9' + 1; i <= cmax; i++) + r.bits[i] = 1; + goto Lrs; - case 's': - for (i = 0; i <= cmax; i++) - if (isspace(i)) - r.bits[i] = 1; - goto Lrs; + case 's': + for (i = 0; i <= cmax; i++) + if (isspace(i)) + r.bits[i] = 1; + goto Lrs; - case 'S': - for (i = 1; i <= cmax; i++) - if (!isspace(i)) - r.bits[i] = 1; - goto Lrs; + case 'S': + for (i = 1; i <= cmax; i++) + if (!isspace(i)) + r.bits[i] = 1; + goto Lrs; - case 'w': - for (i = 0; i <= cmax; i++) - if (isword(cast(rchar)i)) - r.bits[i] = 1; - goto Lrs; + case 'w': + for (i = 0; i <= cmax; i++) + if (isword(cast(rchar)i)) + r.bits[i] = 1; + goto Lrs; - case 'W': - for (i = 1; i <= cmax; i++) - if (!isword(cast(rchar)i)) - r.bits[i] = 1; - goto Lrs; + case 'W': + for (i = 1; i <= cmax; i++) + if (!isword(cast(rchar)i)) + r.bits[i] = 1; + goto Lrs; - Lrs: - switch (rs) - { case RS.dash: - r.setbit2('-'); - case RS.rliteral: - r.setbit2(c); - break; - default: - break; - } - rs = RS.start; - continue; + Lrs: + switch (rs) + { case RS.dash: + r.setbit2('-'); + case RS.rliteral: + r.setbit2(c); + break; + default: + break; + } + rs = RS.start; + continue; - default: - break; - } - c2 = escape(); - goto Lrange; + default: + break; + } + c2 = escape(); + goto Lrange; - case '-': - p++; - if (rs == RS.start) - goto Lrange; - else if (rs == RS.rliteral) - rs = RS.dash; - else if (rs == RS.dash) - { - r.setbit2(c); - r.setbit2('-'); - rs = RS.start; - } - continue; + case '-': + p++; + if (rs == RS.start) + goto Lrange; + else if (rs == RS.rliteral) + rs = RS.dash; + else if (rs == RS.dash) + { + r.setbit2(c); + r.setbit2('-'); + rs = RS.start; + } + continue; - default: - c2 = pattern[p]; - p++; - Lrange: - switch (rs) - { case RS.rliteral: - r.setbit2(c); - case RS.start: - c = c2; - rs = RS.rliteral; - break; + default: + c2 = pattern[p]; + p++; + Lrange: + switch (rs) + { case RS.rliteral: + r.setbit2(c); + case RS.start: + c = c2; + rs = RS.rliteral; + break; - case RS.dash: - if (c > c2) - { error("inverted range in character class"); - return 0; - } - r.setbitmax(c2); - //printf("c = %x, c2 = %x\n",c,c2); - for (; c <= c2; c++) - r.bits[c] = 1; - rs = RS.start; - break; + case RS.dash: + if (c > c2) + { error("inverted range in character class"); + return 0; + } + r.setbitmax(c2); + //printf("c = %x, c2 = %x\n",c,c2); + for (; c <= c2; c++) + r.bits[c] = 1; + rs = RS.start; + break; - default: - assert(0); - } - continue; - } - break; + default: + assert(0); + } + continue; + } + break; } if (attributes & REA.ignoreCase) { - // BUG: what about dchar? - r.setbitmax(0x7F); - for (c = 'a'; c <= 'z'; c++) - { - if (r.bits[c]) - r.bits[c + 'A' - 'a'] = 1; - else if (r.bits[c + 'A' - 'a']) - r.bits[c] = 1; - } + // BUG: what about dchar? + r.setbitmax(0x7F); + for (c = 'a'; c <= 'z'; c++) + { + if (r.bits[c]) + r.bits[c + 'A' - 'a'] = 1; + else if (r.bits[c + 'A' - 'a']) + r.bits[c] = 1; + } } //printf("maxc = %d, maxb = %d\n",r.maxc,r.maxb); (cast(ushort *)&buf.data[offset])[0] = cast(ushort)r.maxc; @@ -2607,111 +2607,111 @@ body int i; rchar tc; - c = pattern[p]; // none of the cases are multibyte + c = pattern[p]; // none of the cases are multibyte switch (c) { - case 'b': c = '\b'; break; - case 'f': c = '\f'; break; - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'v': c = '\v'; break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'v': c = '\v'; break; - // BUG: Perl does \a and \e too, should we? + // BUG: Perl does \a and \e too, should we? - case 'c': - ++p; - if (p == pattern.length) - goto Lretc; - c = pattern[p]; - // Note: we are deliberately not allowing dchar letters - if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))) - { - Lcerr: - error("letter expected following \\c"); - return 0; - } - c &= 0x1F; - break; + case 'c': + ++p; + if (p == pattern.length) + goto Lretc; + c = pattern[p]; + // Note: we are deliberately not allowing dchar letters + if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))) + { + Lcerr: + error("letter expected following \\c"); + return 0; + } + c &= 0x1F; + break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - c -= '0'; - for (i = 0; i < 2; i++) - { - p++; - if (p == pattern.length) - goto Lretc; - tc = pattern[p]; - if ('0' <= tc && tc <= '7') - { c = c * 8 + (tc - '0'); - // Treat overflow as if last - // digit was not an octal digit - if (c >= 0xFF) - { c >>= 3; - return c; - } - } - else - return c; - } - break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + c -= '0'; + for (i = 0; i < 2; i++) + { + p++; + if (p == pattern.length) + goto Lretc; + tc = pattern[p]; + if ('0' <= tc && tc <= '7') + { c = c * 8 + (tc - '0'); + // Treat overflow as if last + // digit was not an octal digit + if (c >= 0xFF) + { c >>= 3; + return c; + } + } + else + return c; + } + break; - case 'x': - c = 0; - for (i = 0; i < 2; i++) - { - p++; - if (p == pattern.length) - goto Lretc; - tc = pattern[p]; - if ('0' <= tc && tc <= '9') - c = c * 16 + (tc - '0'); - else if ('a' <= tc && tc <= 'f') - c = c * 16 + (tc - 'a' + 10); - else if ('A' <= tc && tc <= 'F') - c = c * 16 + (tc - 'A' + 10); - else if (i == 0) // if no hex digits after \x - { - // Not a valid \xXX sequence - return 'x'; - } - else - return c; - } - break; + case 'x': + c = 0; + for (i = 0; i < 2; i++) + { + p++; + if (p == pattern.length) + goto Lretc; + tc = pattern[p]; + if ('0' <= tc && tc <= '9') + c = c * 16 + (tc - '0'); + else if ('a' <= tc && tc <= 'f') + c = c * 16 + (tc - 'a' + 10); + else if ('A' <= tc && tc <= 'F') + c = c * 16 + (tc - 'A' + 10); + else if (i == 0) // if no hex digits after \x + { + // Not a valid \xXX sequence + return 'x'; + } + else + return c; + } + break; - case 'u': - c = 0; - for (i = 0; i < 4; i++) - { - p++; - if (p == pattern.length) - goto Lretc; - tc = pattern[p]; - if ('0' <= tc && tc <= '9') - c = c * 16 + (tc - '0'); - else if ('a' <= tc && tc <= 'f') - c = c * 16 + (tc - 'a' + 10); - else if ('A' <= tc && tc <= 'F') - c = c * 16 + (tc - 'A' + 10); - else - { - // Not a valid \uXXXX sequence - p -= i; - return 'u'; - } - } - break; + case 'u': + c = 0; + for (i = 0; i < 4; i++) + { + p++; + if (p == pattern.length) + goto Lretc; + tc = pattern[p]; + if ('0' <= tc && tc <= '9') + c = c * 16 + (tc - '0'); + else if ('a' <= tc && tc <= 'f') + c = c * 16 + (tc - 'a' + 10); + else if ('A' <= tc && tc <= 'F') + c = c * 16 + (tc - 'A' + 10); + else + { + // Not a valid \uXXXX sequence + p -= i; + return 'u'; + } + } + break; - default: - break; + default: + break; } p++; Lretc: @@ -2727,65 +2727,65 @@ void optimize() prog = buf.toBytes(); for (size_t i = 0; 1;) { - //printf("\tprog[%d] = %d, %d\n", i, prog[i], REstring); - switch (prog[i]) - { - case REend: - case REanychar: - case REanystar: - case REbackref: - case REeol: - case REchar: - case REichar: - case REdchar: - case REidchar: - case REstring: - case REistring: - case REtestbit: - case REbit: - case REnotbit: - case RErange: - case REnotrange: - case REwordboundary: - case REnotwordboundary: - case REdigit: - case REnotdigit: - case REspace: - case REnotspace: - case REword: - case REnotword: - return; + //printf("\tprog[%d] = %d, %d\n", i, prog[i], REstring); + switch (prog[i]) + { + case REend: + case REanychar: + case REanystar: + case REbackref: + case REeol: + case REchar: + case REichar: + case REdchar: + case REidchar: + case REstring: + case REistring: + case REtestbit: + case REbit: + case REnotbit: + case RErange: + case REnotrange: + case REwordboundary: + case REnotwordboundary: + case REdigit: + case REnotdigit: + case REspace: + case REnotspace: + case REword: + case REnotword: + return; - case REbol: - i++; - continue; + case REbol: + i++; + continue; - case REor: - case REnm: - case REnmq: - case REparen: - case REgoto: - { - auto bitbuf = new OutBuffer; - auto r = new Range(bitbuf); - uint offset; + case REor: + case REnm: + case REnmq: + case REparen: + case REgoto: + { + auto bitbuf = new OutBuffer; + auto r = new Range(bitbuf); + uint offset; - offset = i; - if (starrchars(r, prog[i .. prog.length])) - { - debug(regexp) printf("\tfilter built\n"); - buf.spread(offset, 1 + 4 + r.maxb); - buf.data[offset] = REtestbit; - (cast(ushort *)&buf.data[offset + 1])[0] = cast(ushort)r.maxc; - (cast(ushort *)&buf.data[offset + 1])[1] = cast(ushort)r.maxb; - i = offset + 1 + 4; - buf.data[i .. i + r.maxb] = r.base[0 .. r.maxb]; - } - return; - } - default: - assert(0); - } + offset = i; + if (starrchars(r, prog[i .. prog.length])) + { + debug(regexp) printf("\tfilter built\n"); + buf.spread(offset, 1 + 4 + r.maxb); + buf.data[offset] = REtestbit; + (cast(ushort *)&buf.data[offset + 1])[0] = cast(ushort)r.maxc; + (cast(ushort *)&buf.data[offset + 1])[1] = cast(ushort)r.maxb; + i = offset + 1 + 4; + buf.data[i .. i + r.maxb] = r.base[0 .. r.maxb]; + } + return; + } + default: + assert(0); + } } } @@ -2809,165 +2809,165 @@ int starrchars(Range r, ubyte[] prog) //printf("RegExp.starrchars(prog = %p, progend = %p)\n", prog, progend); for (size_t i = 0; i < prog.length;) { - switch (prog[i]) - { - case REchar: - c = prog[i + 1]; - if (c <= 0x7F) - r.setbit2(c); - return 1; + switch (prog[i]) + { + case REchar: + c = prog[i + 1]; + if (c <= 0x7F) + r.setbit2(c); + return 1; - case REichar: - c = prog[i + 1]; - if (c <= 0x7F) - { r.setbit2(c); - r.setbit2(std.ctype.tolower(cast(rchar)c)); - } - return 1; + case REichar: + c = prog[i + 1]; + if (c <= 0x7F) + { r.setbit2(c); + r.setbit2(std.ctype.tolower(cast(rchar)c)); + } + return 1; - case REdchar: - case REidchar: - return 1; + case REdchar: + case REidchar: + return 1; - case REanychar: - return 0; // no point + case REanychar: + return 0; // no point - case REstring: - len = *cast(uint *)&prog[i + 1]; - assert(len); - c = *cast(rchar *)&prog[i + 1 + uint.sizeof]; - debug(regexp) printf("\tREstring %d, '%c'\n", len, c); - if (c <= 0x7F) - r.setbit2(c); - return 1; + case REstring: + len = *cast(uint *)&prog[i + 1]; + assert(len); + c = *cast(rchar *)&prog[i + 1 + uint.sizeof]; + debug(regexp) printf("\tREstring %d, '%c'\n", len, c); + if (c <= 0x7F) + r.setbit2(c); + return 1; - case REistring: - len = *cast(uint *)&prog[i + 1]; - assert(len); - c = *cast(rchar *)&prog[i + 1 + uint.sizeof]; - debug(regexp) printf("\tREistring %d, '%c'\n", len, c); - if (c <= 0x7F) - { r.setbit2(std.ctype.toupper(cast(rchar)c)); - r.setbit2(std.ctype.tolower(cast(rchar)c)); - } - return 1; + case REistring: + len = *cast(uint *)&prog[i + 1]; + assert(len); + c = *cast(rchar *)&prog[i + 1 + uint.sizeof]; + debug(regexp) printf("\tREistring %d, '%c'\n", len, c); + if (c <= 0x7F) + { r.setbit2(std.ctype.toupper(cast(rchar)c)); + r.setbit2(std.ctype.tolower(cast(rchar)c)); + } + return 1; - case REtestbit: - case REbit: - maxc = (cast(ushort *)&prog[i + 1])[0]; - maxb = (cast(ushort *)&prog[i + 1])[1]; - if (maxc <= 0x7F) - r.setbitmax(maxc); - else - maxb = r.maxb; - for (b = 0; b < maxb; b++) - r.base[b] |= prog[i + 1 + 4 + b]; - return 1; + case REtestbit: + case REbit: + maxc = (cast(ushort *)&prog[i + 1])[0]; + maxb = (cast(ushort *)&prog[i + 1])[1]; + if (maxc <= 0x7F) + r.setbitmax(maxc); + else + maxb = r.maxb; + for (b = 0; b < maxb; b++) + r.base[b] |= prog[i + 1 + 4 + b]; + return 1; - case REnotbit: - maxc = (cast(ushort *)&prog[i + 1])[0]; - maxb = (cast(ushort *)&prog[i + 1])[1]; - if (maxc <= 0x7F) - r.setbitmax(maxc); - else - maxb = r.maxb; - for (b = 0; b < maxb; b++) - r.base[b] |= ~prog[i + 1 + 4 + b]; - return 1; + case REnotbit: + maxc = (cast(ushort *)&prog[i + 1])[0]; + maxb = (cast(ushort *)&prog[i + 1])[1]; + if (maxc <= 0x7F) + r.setbitmax(maxc); + else + maxb = r.maxb; + for (b = 0; b < maxb; b++) + r.base[b] |= ~prog[i + 1 + 4 + b]; + return 1; - case REbol: - case REeol: - return 0; + case REbol: + case REeol: + return 0; - case REor: - len = (cast(uint *)&prog[i + 1])[0]; - return starrchars(r, prog[i + 1 + uint.sizeof .. prog.length]) && - starrchars(r, prog[i + 1 + uint.sizeof + len .. prog.length]); + case REor: + len = (cast(uint *)&prog[i + 1])[0]; + return starrchars(r, prog[i + 1 + uint.sizeof .. prog.length]) && + starrchars(r, prog[i + 1 + uint.sizeof + len .. prog.length]); - case REgoto: - len = (cast(uint *)&prog[i + 1])[0]; - i += 1 + uint.sizeof + len; - break; + case REgoto: + len = (cast(uint *)&prog[i + 1])[0]; + i += 1 + uint.sizeof + len; + break; - case REanystar: - return 0; + case REanystar: + return 0; - case REnm: - case REnmq: - // len, n, m, () - len = (cast(uint *)&prog[i + 1])[0]; - n = (cast(uint *)&prog[i + 1])[1]; - m = (cast(uint *)&prog[i + 1])[2]; - pop = &prog[i + 1 + uint.sizeof * 3]; - if (!starrchars(r, pop[0 .. len])) - return 0; - if (n) - return 1; - i += 1 + uint.sizeof * 3 + len; - break; + case REnm: + case REnmq: + // len, n, m, () + len = (cast(uint *)&prog[i + 1])[0]; + n = (cast(uint *)&prog[i + 1])[1]; + m = (cast(uint *)&prog[i + 1])[2]; + pop = &prog[i + 1 + uint.sizeof * 3]; + if (!starrchars(r, pop[0 .. len])) + return 0; + if (n) + return 1; + i += 1 + uint.sizeof * 3 + len; + break; - case REparen: - // len, () - len = (cast(uint *)&prog[i + 1])[0]; - n = (cast(uint *)&prog[i + 1])[1]; - pop = &prog[0] + i + 1 + uint.sizeof * 2; - return starrchars(r, pop[0 .. len]); + case REparen: + // len, () + len = (cast(uint *)&prog[i + 1])[0]; + n = (cast(uint *)&prog[i + 1])[1]; + pop = &prog[0] + i + 1 + uint.sizeof * 2; + return starrchars(r, pop[0 .. len]); - case REend: - return 0; + case REend: + return 0; - case REwordboundary: - case REnotwordboundary: - return 0; + case REwordboundary: + case REnotwordboundary: + return 0; - case REdigit: - r.setbitmax('9'); - for (c = '0'; c <= '9'; c++) - r.bits[c] = 1; - return 1; + case REdigit: + r.setbitmax('9'); + for (c = '0'; c <= '9'; c++) + r.bits[c] = 1; + return 1; - case REnotdigit: - r.setbitmax(0x7F); - for (c = 0; c <= '0'; c++) - r.bits[c] = 1; - for (c = '9' + 1; c <= r.maxc; c++) - r.bits[c] = 1; - return 1; + case REnotdigit: + r.setbitmax(0x7F); + for (c = 0; c <= '0'; c++) + r.bits[c] = 1; + for (c = '9' + 1; c <= r.maxc; c++) + r.bits[c] = 1; + return 1; - case REspace: - r.setbitmax(0x7F); - for (c = 0; c <= r.maxc; c++) - if (isspace(c)) - r.bits[c] = 1; - return 1; + case REspace: + r.setbitmax(0x7F); + for (c = 0; c <= r.maxc; c++) + if (isspace(c)) + r.bits[c] = 1; + return 1; - case REnotspace: - r.setbitmax(0x7F); - for (c = 0; c <= r.maxc; c++) - if (!isspace(c)) - r.bits[c] = 1; - return 1; + case REnotspace: + r.setbitmax(0x7F); + for (c = 0; c <= r.maxc; c++) + if (!isspace(c)) + r.bits[c] = 1; + return 1; - case REword: - r.setbitmax(0x7F); - for (c = 0; c <= r.maxc; c++) - if (isword(cast(rchar)c)) - r.bits[c] = 1; - return 1; + case REword: + r.setbitmax(0x7F); + for (c = 0; c <= r.maxc; c++) + if (isword(cast(rchar)c)) + r.bits[c] = 1; + return 1; - case REnotword: - r.setbitmax(0x7F); - for (c = 0; c <= r.maxc; c++) - if (!isword(cast(rchar)c)) - r.bits[c] = 1; - return 1; + case REnotword: + r.setbitmax(0x7F); + for (c = 0; c <= r.maxc; c++) + if (!isword(cast(rchar)c)) + r.bits[c] = 1; + return 1; - case REbackref: - return 0; + case REbackref: + return 0; - default: - assert(0); - } + default: + assert(0); + } } return 1; } @@ -3000,104 +3000,104 @@ public static rchar[] replace3(rchar[] format, rchar[] input, regmatch_t[] pmatc result.length = 0; for (size_t f = 0; f < format.length; f++) { - auto c = format[f]; + auto c = format[f]; L1: - if (c != '$') - { - result ~= c; - continue; - } - ++f; - if (f == format.length) - { - result ~= '$'; - break; - } - c = format[f]; - switch (c) - { - case '&': - rm_so = pmatch[0].rm_so; - rm_eo = pmatch[0].rm_eo; - goto Lstring; + if (c != '$') + { + result ~= c; + continue; + } + ++f; + if (f == format.length) + { + result ~= '$'; + break; + } + c = format[f]; + switch (c) + { + case '&': + rm_so = pmatch[0].rm_so; + rm_eo = pmatch[0].rm_eo; + goto Lstring; - case '`': - rm_so = 0; - rm_eo = pmatch[0].rm_so; - goto Lstring; + case '`': + rm_so = 0; + rm_eo = pmatch[0].rm_so; + goto Lstring; - case '\'': - rm_so = pmatch[0].rm_eo; - rm_eo = input.length; - goto Lstring; + case '\'': + rm_so = pmatch[0].rm_eo; + rm_eo = input.length; + goto Lstring; - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - i = c - '0'; - if (f + 1 == format.length) - { - if (i == 0) - { - result ~= '$'; - result ~= c; - continue; - } - } - else - { - c2 = format[f + 1]; - if (c2 >= '0' && c2 <= '9') - { i = (c - '0') * 10 + (c2 - '0'); - f++; - } - if (i == 0) - { - result ~= '$'; - result ~= c; - c = cast(char)c2; - goto L1; - } - } + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + i = c - '0'; + if (f + 1 == format.length) + { + if (i == 0) + { + result ~= '$'; + result ~= c; + continue; + } + } + else + { + c2 = format[f + 1]; + if (c2 >= '0' && c2 <= '9') + { i = (c - '0') * 10 + (c2 - '0'); + f++; + } + if (i == 0) + { + result ~= '$'; + result ~= c; + c = cast(char)c2; + goto L1; + } + } - if (i < pmatch.length) - { rm_so = pmatch[i].rm_so; - rm_eo = pmatch[i].rm_eo; - goto Lstring; - } - break; + if (i < pmatch.length) + { rm_so = pmatch[i].rm_so; + rm_eo = pmatch[i].rm_eo; + goto Lstring; + } + break; - Lstring: - if (rm_so != rm_eo) - result ~= input[rm_so .. rm_eo]; - break; + Lstring: + if (rm_so != rm_eo) + result ~= input[rm_so .. rm_eo]; + break; - default: - result ~= '$'; - result ~= c; - break; - } + default: + result ~= '$'; + result ~= c; + break; + } } return result; } /************************************ * Like replace(char[] format), but uses old style formatting: - - - - - - - -
Format - Description -
& - replace with the match -
\n - replace with the nth parenthesized match, n is 1..9 -
\c - replace with char c. -
+ + + + + + + +
Format + Description +
& + replace with the match +
\n + replace with the nth parenthesized match, n is 1..9 +
\c + replace with char c. +
*/ public rchar[] replaceOld(rchar[] format) @@ -3110,34 +3110,34 @@ public rchar[] replaceOld(rchar[] format) result.length = 0; for (size_t i; i < format.length; i++) { - auto c = format[i]; - switch (c) - { - case '&': + auto c = format[i]; + switch (c) + { + case '&': //printf("match = '%.*s'\n", input[pmatch[0].rm_so .. pmatch[0].rm_eo]); - result ~= input[pmatch[0].rm_so .. pmatch[0].rm_eo]; - break; + result ~= input[pmatch[0].rm_so .. pmatch[0].rm_eo]; + break; - case '\\': - if (i + 1 < format.length) - { - c = format[++i]; - if (c >= '1' && c <= '9') - { uint j; + case '\\': + if (i + 1 < format.length) + { + c = format[++i]; + if (c >= '1' && c <= '9') + { uint j; - j = c - '0'; - if (j <= re_nsub && pmatch[j].rm_so != pmatch[j].rm_eo) - result ~= input[pmatch[j].rm_so .. pmatch[j].rm_eo]; - break; - } - } - result ~= c; - break; + j = c - '0'; + if (j <= re_nsub && pmatch[j].rm_so != pmatch[j].rm_eo) + result ~= input[pmatch[j].rm_so .. pmatch[j].rm_eo]; + break; + } + } + result ~= c; + break; - default: - result ~= c; - break; - } + default: + result ~= c; + break; + } } return result; } diff --git a/std/signals.d b/std/signals.d index 20594452f..bd2d95fb0 100644 --- a/std/signals.d +++ b/std/signals.d @@ -11,45 +11,45 @@ * longer necessary to instrument the slots. * * References: - * $(LINK2 http://scottcollins.net/articles/a-deeper-look-at-_signals-and-slots.html, A Deeper Look at Signals and Slots)$(BR) - * $(LINK2 http://en.wikipedia.org/wiki/Observer_pattern, Observer pattern)$(BR) - * $(LINK2 http://en.wikipedia.org/wiki/Signals_and_slots, Wikipedia)$(BR) - * $(LINK2 http://boost.org/doc/html/$(SIGNALS).html, Boost Signals)$(BR) - * $(LINK2 http://doc.trolltech.com/4.1/signalsandslots.html, Qt)$(BR) + * $(LINK2 http://scottcollins.net/articles/a-deeper-look-at-_signals-and-slots.html, A Deeper Look at Signals and Slots)$(BR) + * $(LINK2 http://en.wikipedia.org/wiki/Observer_pattern, Observer pattern)$(BR) + * $(LINK2 http://en.wikipedia.org/wiki/Signals_and_slots, Wikipedia)$(BR) + * $(LINK2 http://boost.org/doc/html/$(SIGNALS).html, Boost Signals)$(BR) + * $(LINK2 http://doc.trolltech.com/4.1/signalsandslots.html, Qt)$(BR) * - * There has been a great deal of discussion in the D newsgroups - * over this, and several implementations: + * There has been a great deal of discussion in the D newsgroups + * over this, and several implementations: * - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/announce/signal_slots_library_4825.html, signal slots library)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/Signals_and_Slots_in_D_42387.html, Signals and Slots in D)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/Dynamic_binding_--_Qt_s_Signals_and_Slots_vs_Objective-C_42260.html, Dynamic binding -- Qt's Signals and Slots vs Objective-C)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/Dissecting_the_SS_42377.html, Dissecting the SS)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/dwt/about_harmonia_454.html, about harmonia)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/announce/1502.html, Another event handling module)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/41825.html, Suggestion: signal/slot mechanism)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/13251.html, Signals and slots?)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/10714.html, Signals and slots ready for evaluation)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/1393.html, Signals & Slots for Walter)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/28456.html, Signal/Slot mechanism?)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/19470.html, Modern Features?)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/16592.html, Delegates vs interfaces)$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/16583.html, The importance of component programming (properties, signals and slots, etc))$(BR) - * $(LINK2 http://www.digitalmars.com/d/archives/16368.html, signals and slots)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/announce/signal_slots_library_4825.html, signal slots library)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/Signals_and_Slots_in_D_42387.html, Signals and Slots in D)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/Dynamic_binding_--_Qt_s_Signals_and_Slots_vs_Objective-C_42260.html, Dynamic binding -- Qt's Signals and Slots vs Objective-C)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/Dissecting_the_SS_42377.html, Dissecting the SS)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/dwt/about_harmonia_454.html, about harmonia)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/announce/1502.html, Another event handling module)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/41825.html, Suggestion: signal/slot mechanism)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/13251.html, Signals and slots?)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/10714.html, Signals and slots ready for evaluation)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/digitalmars/D/1393.html, Signals & Slots for Walter)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/28456.html, Signal/Slot mechanism?)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/19470.html, Modern Features?)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/16592.html, Delegates vs interfaces)$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/16583.html, The importance of component programming (properties, signals and slots, etc))$(BR) + * $(LINK2 http://www.digitalmars.com/d/archives/16368.html, signals and slots)$(BR) * * Bugs: - * Slots can only be delegates formed from class objects or - * interfaces to class objects. If a delegate to something else - * is passed to connect(), such as a struct member function, - * a nested function or a COM interface, undefined behavior - * will result. + * Slots can only be delegates formed from class objects or + * interfaces to class objects. If a delegate to something else + * is passed to connect(), such as a struct member function, + * a nested function or a COM interface, undefined behavior + * will result. * - * Not safe for multiple threads operating on the same signals - * or slots. + * Not safe for multiple threads operating on the same signals + * or slots. * Macros: - * WIKI = Phobos/StdSignals - * SIGNALS=signals + * WIKI = Phobos/StdSignals + * SIGNALS=signals * Copyright: - * Public Domain + * Public Domain * Author: Walter Bright, Digital Mars, www.digitalmars.com */ @@ -80,7 +80,7 @@ class Observer { // our slot void watch(char[] msg, int i) { - writefln("Observed msg '%s' and value %s", msg, i); + writefln("Observed msg '%s' and value %s", msg, i); } } @@ -90,12 +90,12 @@ class Foo int value(int v) { - if (v != _value) - { _value = v; - // call all the connected slots with the two parameters - emit("setting new value", v); - } - return v; + if (v != _value) + { _value = v; + // call all the connected slots with the two parameters + emit("setting new value", v); + } + return v; } // Mix in all the code we need to make Foo into a signal @@ -110,15 +110,15 @@ void main() Foo a = new Foo; Observer o = new Observer; - a.value = 3; // should not call o.watch() - a.connect(&o.watch); // o.watch is the slot - a.value = 4; // should call o.watch() - a.disconnect(&o.watch); // o.watch is no longer a slot - a.value = 5; // so should not call o.watch() - a.connect(&o.watch); // connect again - a.value = 6; // should call o.watch() - delete o; // destroying o should automatically disconnect it - a.value = 7; // should not call o.watch() + a.value = 3; // should not call o.watch() + a.connect(&o.watch); // o.watch is the slot + a.value = 4; // should call o.watch() + a.disconnect(&o.watch); // o.watch is no longer a slot + a.value = 5; // so should not call o.watch() + a.connect(&o.watch); // connect again + a.value = 6; // should call o.watch() + delete o; // destroying o should automatically disconnect it + a.value = 7; // should not call o.watch() } --- * which should print: @@ -147,9 +147,9 @@ template Signal(T1...) void emit( T1 i ) { foreach (slot; slots[0 .. slots_idx]) - { if (slot) - slot(i); - } + { if (slot) + slot(i); + } } /*** @@ -157,36 +157,36 @@ template Signal(T1...) */ void connect(slot_t slot) { - /* Do this: - * slots ~= slot; - * but use malloc() and friends instead - */ - auto len = slots.length; - if (slots_idx == len) - { - if (slots.length == 0) - { - len = 4; - auto p = std.signals.calloc(slot_t.sizeof, len); - if (!p) - std.signals._d_OutOfMemory(); - slots = (cast(slot_t*)p)[0 .. len]; - } - else - { - len = len * 2 + 4; - auto p = std.signals.realloc(slots.ptr, slot_t.sizeof * len); - if (!p) - std.signals._d_OutOfMemory(); - slots = (cast(slot_t*)p)[0 .. len]; - slots[slots_idx + 1 .. length] = null; - } - } - slots[slots_idx++] = slot; + /* Do this: + * slots ~= slot; + * but use malloc() and friends instead + */ + auto len = slots.length; + if (slots_idx == len) + { + if (slots.length == 0) + { + len = 4; + auto p = std.signals.calloc(slot_t.sizeof, len); + if (!p) + std.signals._d_OutOfMemory(); + slots = (cast(slot_t*)p)[0 .. len]; + } + else + { + len = len * 2 + 4; + auto p = std.signals.realloc(slots.ptr, slot_t.sizeof * len); + if (!p) + std.signals._d_OutOfMemory(); + slots = (cast(slot_t*)p)[0 .. len]; + slots[slots_idx + 1 .. length] = null; + } + } + slots[slots_idx++] = slot; L1: - Object o = _d_toObject(slot.ptr); - o.notifyRegister(&unhook); + Object o = _d_toObject(slot.ptr); + o.notifyRegister(&unhook); } /*** @@ -194,20 +194,20 @@ template Signal(T1...) */ void disconnect( slot_t slot) { - debug (signal) writefln("Signal.disconnect(slot)"); - for (size_t i = 0; i < slots_idx; ) - { - if (slots[i] == slot) - { slots_idx--; - slots[i] = slots[slots_idx]; - slots[slots_idx] = null; // not strictly necessary + debug (signal) writefln("Signal.disconnect(slot)"); + for (size_t i = 0; i < slots_idx; ) + { + if (slots[i] == slot) + { slots_idx--; + slots[i] = slots[slots_idx]; + slots[slots_idx] = null; // not strictly necessary - Object o = _d_toObject(slot.ptr); - o.notifyUnRegister(&unhook); - } - else - i++; - } + Object o = _d_toObject(slot.ptr); + o.notifyUnRegister(&unhook); + } + else + i++; + } } /* ** @@ -217,17 +217,17 @@ template Signal(T1...) */ void unhook(Object o) { - debug (signal) writefln("Signal.unhook(o = %s)", cast(void*)o); - for (size_t i = 0; i < slots_idx; ) - { - if (_d_toObject(slots[i].ptr) is o) - { slots_idx--; - slots[i] = slots[slots_idx]; - slots[slots_idx] = null; // not strictly necessary - } - else - i++; - } + debug (signal) writefln("Signal.unhook(o = %s)", cast(void*)o); + for (size_t i = 0; i < slots_idx; ) + { + if (_d_toObject(slots[i].ptr) is o) + { slots_idx--; + slots[i] = slots[slots_idx]; + slots[slots_idx] = null; // not strictly necessary + } + else + i++; + } } /* ** @@ -235,28 +235,28 @@ template Signal(T1...) */ ~this() { - /* ** - * When this object is destroyed, need to let every slot - * know that this object is destroyed so they are not left - * with dangling references to it. - */ - if (slots) - { - foreach (slot; slots[0 .. slots_idx]) - { - if (slot) - { Object o = _d_toObject(slot.ptr); - o.notifyUnRegister(&unhook); - } - } - std.signals.free(slots.ptr); - slots = null; - } + /* ** + * When this object is destroyed, need to let every slot + * know that this object is destroyed so they are not left + * with dangling references to it. + */ + if (slots) + { + foreach (slot; slots[0 .. slots_idx]) + { + if (slot) + { Object o = _d_toObject(slot.ptr); + o.notifyUnRegister(&unhook); + } + } + std.signals.free(slots.ptr); + slots = null; + } } private: - slot_t[] slots; // the slots to call from emit() - size_t slots_idx; // used length of slots[] + slot_t[] slots; // the slots to call from emit() + size_t slots_idx; // used length of slots[] } // A function whose sole purpose is to get this module linked in @@ -267,29 +267,29 @@ unittest { class Observer { - void watch(char[] msg, int i) - { - writefln("Observed msg '%s' and value %s", msg, i); - } + void watch(char[] msg, int i) + { + writefln("Observed msg '%s' and value %s", msg, i); + } } class Foo { - int value() { return _value; } + int value() { return _value; } - int value(int v) - { - if (v != _value) - { _value = v; - emit("setting new value", v); - } - return v; - } + int value(int v) + { + if (v != _value) + { _value = v; + emit("setting new value", v); + } + return v; + } - mixin Signal!(char[], int); + mixin Signal!(char[], int); private: - int _value; + int _value; } Foo a = new Foo; diff --git a/std/socket.d b/std/socket.d index 2a53916fb..d61fc28e4 100644 --- a/std/socket.d +++ b/std/socket.d @@ -1,29 +1,29 @@ // Written in the D programming language /* - Copyright (C) 2004-2005 Christopher E. Miller + Copyright (C) 2004-2005 Christopher E. Miller - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not - be misrepresented as being the original software. - 3. This notice may not be removed or altered from any source - distribution. + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not + be misrepresented as being the original software. + 3. This notice may not be removed or altered from any source + distribution. - socket.d 1.3 - Jan 2005 + socket.d 1.3 + Jan 2005 - Thanks to Benjamin Herr for his assistance. + Thanks to Benjamin Herr for his assistance. */ /** @@ -31,7 +31,7 @@ * Example: See /dmd/samples/d/listener.d. * Authors: Christopher E. Miller * Macros: - * WIKI=Phobos/StdSocket + * WIKI=Phobos/StdSocket */ module std.socket; @@ -41,89 +41,89 @@ private import std.string, std.stdint, std.c.string, std.c.stdlib; version(Posix) { - version = BsdSockets; + version = BsdSockets; } version(Win32) { - pragma (lib, "wsock32.lib"); + pragma (lib, "wsock32.lib"); - private import std.c.windows.windows, std.c.windows.winsock; - private alias std.c.windows.winsock.timeval _ctimeval; + private import std.c.windows.windows, std.c.windows.winsock; + private alias std.c.windows.winsock.timeval _ctimeval; - typedef SOCKET socket_t = INVALID_SOCKET; - private const int _SOCKET_ERROR = SOCKET_ERROR; + typedef SOCKET socket_t = INVALID_SOCKET; + private const int _SOCKET_ERROR = SOCKET_ERROR; - private int _lasterr() - { - return WSAGetLastError(); - } + private int _lasterr() + { + return WSAGetLastError(); + } } else version(BsdSockets) { - version(Posix) - { - private import std.c.posix.socket; - private import std.c.posix.posix; - private alias std.c.posix.posix.timeval _ctimeval; - } + version(Posix) + { + private import std.c.posix.socket; + private import std.c.posix.posix; + private alias std.c.posix.posix.timeval _ctimeval; + } - typedef int32_t socket_t = -1; - private const int _SOCKET_ERROR = -1; + typedef int32_t socket_t = -1; + private const int _SOCKET_ERROR = -1; - private int _lasterr() - { - return getErrno(); - } + private int _lasterr() + { + return getErrno(); + } } else { - static assert(0); // No socket support yet. + static assert(0); // No socket support yet. } /// Base exception thrown from a Socket. class SocketException: Exception { - int errorCode; /// Platform-specific error code. + int errorCode; /// Platform-specific error code. - this(string msg, int err = 0) - { - errorCode = err; + this(string msg, int err = 0) + { + errorCode = err; - version(Posix) - { - if(errorCode > 0) - { - char[80] buf; - char* cs; - version (linux) - { - cs = strerror_r(errorCode, buf.ptr, buf.length); - } - else version (OSX) - { - auto errs = strerror_r(errorCode, buf.ptr, buf.length); - if (errs == 0) - cs = buf.ptr; - else - { - cs = "Unknown error"; - } - } - else version (FreeBSD) - { - auto errs = strerror_r(errorCode, buf.ptr, buf.length); - if (errs == 0) - cs = buf.ptr; - else - { - cs = "Unknown error"; - } - } + version(Posix) + { + if(errorCode > 0) + { + char[80] buf; + char* cs; + version (linux) + { + cs = strerror_r(errorCode, buf.ptr, buf.length); + } + else version (OSX) + { + auto errs = strerror_r(errorCode, buf.ptr, buf.length); + if (errs == 0) + cs = buf.ptr; + else + { + cs = "Unknown error"; + } + } + else version (FreeBSD) + { + auto errs = strerror_r(errorCode, buf.ptr, buf.length); + if (errs == 0) + cs = buf.ptr; + else + { + cs = "Unknown error"; + } + } else version (Solaris) { auto errs = strerror_r(errorCode, buf.ptr, buf.length); @@ -134,48 +134,48 @@ class SocketException: Exception cs = "Unknown error"; } } - else - { - static assert(0); - } + else + { + static assert(0); + } - auto len = strlen(cs); + auto len = strlen(cs); - if(cs[len - 1] == '\n') - len--; - if(cs[len - 1] == '\r') - len--; - msg = msg ~ ": " ~ cs[0 .. len]; - } - } + if(cs[len - 1] == '\n') + len--; + if(cs[len - 1] == '\r') + len--; + msg = msg ~ ": " ~ cs[0 .. len]; + } + } - super(msg); - } + super(msg); + } } static this() { - version(Win32) - { - WSADATA wd; + version(Win32) + { + WSADATA wd; - // Winsock will still load if an older version is present. - // The version is just a request. - int val; - val = WSAStartup(0x2020, &wd); - if(val) // Request Winsock 2.2 for IPv6. - throw new SocketException("Unable to initialize socket library", val); - } + // Winsock will still load if an older version is present. + // The version is just a request. + int val; + val = WSAStartup(0x2020, &wd); + if(val) // Request Winsock 2.2 for IPv6. + throw new SocketException("Unable to initialize socket library", val); + } } static ~this() { - version(Win32) - { - WSACleanup(); - } + version(Win32) + { + WSACleanup(); + } } /** @@ -183,12 +183,12 @@ static ~this() */ enum AddressFamily: int { - UNSPEC = AF_UNSPEC, /// - UNIX = AF_UNIX, /// local communication - INET = AF_INET, /// internet protocol version 4 - IPX = AF_IPX, /// novell IPX - APPLETALK = AF_APPLETALK, /// appletalk - INET6 = AF_INET6, // internet protocol version 6 + UNSPEC = AF_UNSPEC, /// + UNIX = AF_UNIX, /// local communication + INET = AF_INET, /// internet protocol version 4 + IPX = AF_IPX, /// novell IPX + APPLETALK = AF_APPLETALK, /// appletalk + INET6 = AF_INET6, // internet protocol version 6 } @@ -197,11 +197,11 @@ enum AddressFamily: int */ enum SocketType: int { - STREAM = SOCK_STREAM, /// sequenced, reliable, two-way communication-based byte streams - DGRAM = SOCK_DGRAM, /// connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order - RAW = SOCK_RAW, /// raw protocol access - RDM = SOCK_RDM, /// reliably-delivered message datagrams - SEQPACKET = SOCK_SEQPACKET, /// sequenced, reliable, two-way connection-based datagrams with a fixed maximum length + STREAM = SOCK_STREAM, /// sequenced, reliable, two-way communication-based byte streams + DGRAM = SOCK_DGRAM, /// connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order + RAW = SOCK_RAW, /// raw protocol access + RDM = SOCK_RDM, /// reliably-delivered message datagrams + SEQPACKET = SOCK_SEQPACKET, /// sequenced, reliable, two-way connection-based datagrams with a fixed maximum length } @@ -210,15 +210,15 @@ enum SocketType: int */ enum ProtocolType: int { - IP = IPPROTO_IP, /// internet protocol version 4 - ICMP = IPPROTO_ICMP, /// internet control message protocol - IGMP = IPPROTO_IGMP, /// internet group management protocol - GGP = IPPROTO_GGP, /// gateway to gateway protocol - TCP = IPPROTO_TCP, /// transmission control protocol - PUP = IPPROTO_PUP, /// PARC universal packet protocol - UDP = IPPROTO_UDP, /// user datagram protocol - IDP = IPPROTO_IDP, /// Xerox NS protocol - IPV6 = IPPROTO_IPV6, /// internet protocol version 6 + IP = IPPROTO_IP, /// internet protocol version 4 + ICMP = IPPROTO_ICMP, /// internet control message protocol + IGMP = IPPROTO_IGMP, /// internet group management protocol + GGP = IPPROTO_GGP, /// gateway to gateway protocol + TCP = IPPROTO_TCP, /// transmission control protocol + PUP = IPPROTO_PUP, /// PARC universal packet protocol + UDP = IPPROTO_UDP, /// user datagram protocol + IDP = IPPROTO_IDP, /// Xerox NS protocol + IPV6 = IPPROTO_IPV6, /// internet protocol version 6 } @@ -227,73 +227,73 @@ enum ProtocolType: int */ class Protocol { - ProtocolType type; /// These members are populated when one of the following functions are called without failure: - string name; /// ditto - string[] aliases; /// ditto + ProtocolType type; /// These members are populated when one of the following functions are called without failure: + string name; /// ditto + string[] aliases; /// ditto - void populate(protoent* proto) - { - type = cast(ProtocolType)proto.p_proto; - name = std.string.toString(proto.p_name).dup; + void populate(protoent* proto) + { + type = cast(ProtocolType)proto.p_proto; + name = std.string.toString(proto.p_name).dup; - int i; - for(i = 0;; i++) - { - if(!proto.p_aliases[i]) - break; - } + int i; + for(i = 0;; i++) + { + if(!proto.p_aliases[i]) + break; + } - if(i) - { - aliases = new string[i]; - for(i = 0; i != aliases.length; i++) - { - aliases[i] = - std.string.toString(proto.p_aliases[i]).dup; - } - } - else - { - aliases = null; - } - } + if(i) + { + aliases = new string[i]; + for(i = 0; i != aliases.length; i++) + { + aliases[i] = + std.string.toString(proto.p_aliases[i]).dup; + } + } + else + { + aliases = null; + } + } - /** Returns false on failure */ - bool getProtocolByName(string name) - { - protoent* proto; - proto = getprotobyname(toStringz(name)); - if(!proto) - return false; - populate(proto); - return true; - } + /** Returns false on failure */ + bool getProtocolByName(string name) + { + protoent* proto; + proto = getprotobyname(toStringz(name)); + if(!proto) + return false; + populate(proto); + return true; + } - /** Returns false on failure */ - // Same as getprotobynumber(). - bool getProtocolByType(ProtocolType type) - { - protoent* proto; - proto = getprotobynumber(type); - if(!proto) - return false; - populate(proto); - return true; - } + /** Returns false on failure */ + // Same as getprotobynumber(). + bool getProtocolByType(ProtocolType type) + { + protoent* proto; + proto = getprotobynumber(type); + if(!proto) + return false; + populate(proto); + return true; + } } unittest { - Protocol proto = new Protocol; - assert(proto.getProtocolByType(ProtocolType.TCP)); - printf("About protocol TCP:\n\tName: %.*s\n", proto.name); - foreach(string s; proto.aliases) - { - printf("\tAlias: %.*s\n", s); - } + Protocol proto = new Protocol; + assert(proto.getProtocolByType(ProtocolType.TCP)); + printf("About protocol TCP:\n\tName: %.*s\n", proto.name); + foreach(string s; proto.aliases) + { + printf("\tAlias: %.*s\n", s); + } } @@ -302,111 +302,111 @@ unittest */ class Service { - /** These members are populated when one of the following functions are called without failure: */ - string name; - string[] aliases; /// ditto - ushort port; /// ditto - string protocolName; /// ditto + /** These members are populated when one of the following functions are called without failure: */ + string name; + string[] aliases; /// ditto + ushort port; /// ditto + string protocolName; /// ditto - void populate(servent* serv) - { - name = std.string.toString(serv.s_name).dup; - port = ntohs(cast(ushort)serv.s_port); - protocolName = std.string.toString(serv.s_proto).dup; + void populate(servent* serv) + { + name = std.string.toString(serv.s_name).dup; + port = ntohs(cast(ushort)serv.s_port); + protocolName = std.string.toString(serv.s_proto).dup; - int i; - for(i = 0;; i++) - { - if(!serv.s_aliases[i]) - break; - } + int i; + for(i = 0;; i++) + { + if(!serv.s_aliases[i]) + break; + } - if(i) - { - aliases = new string[i]; - for(i = 0; i != aliases.length; i++) - { + if(i) + { + aliases = new string[i]; + for(i = 0; i != aliases.length; i++) + { aliases[i] = std.string.toString(serv.s_aliases[i]).dup; - } - } - else - { - aliases = null; - } - } + } + } + else + { + aliases = null; + } + } - /** - * If a protocol name is omitted, any protocol will be matched. - * Returns: false on failure. - */ - bool getServiceByName(string name, string protocolName) - { - servent* serv; - serv = getservbyname(toStringz(name), toStringz(protocolName)); - if(!serv) - return false; - populate(serv); - return true; - } + /** + * If a protocol name is omitted, any protocol will be matched. + * Returns: false on failure. + */ + bool getServiceByName(string name, string protocolName) + { + servent* serv; + serv = getservbyname(toStringz(name), toStringz(protocolName)); + if(!serv) + return false; + populate(serv); + return true; + } - // Any protocol name will be matched. - /// ditto - bool getServiceByName(string name) - { - servent* serv; - serv = getservbyname(toStringz(name), null); - if(!serv) - return false; - populate(serv); - return true; - } + // Any protocol name will be matched. + /// ditto + bool getServiceByName(string name) + { + servent* serv; + serv = getservbyname(toStringz(name), null); + if(!serv) + return false; + populate(serv); + return true; + } - /// ditto - bool getServiceByPort(ushort port, string protocolName) - { - servent* serv; - serv = getservbyport(port, toStringz(protocolName)); - if(!serv) - return false; - populate(serv); - return true; - } + /// ditto + bool getServiceByPort(ushort port, string protocolName) + { + servent* serv; + serv = getservbyport(port, toStringz(protocolName)); + if(!serv) + return false; + populate(serv); + return true; + } - // Any protocol name will be matched. - /// ditto - bool getServiceByPort(ushort port) - { - servent* serv; - serv = getservbyport(port, null); - if(!serv) - return false; - populate(serv); - return true; - } + // Any protocol name will be matched. + /// ditto + bool getServiceByPort(ushort port) + { + servent* serv; + serv = getservbyport(port, null); + if(!serv) + return false; + populate(serv); + return true; + } } unittest { - Service serv = new Service; - if(serv.getServiceByName("epmap", "tcp")) - { - printf("About service epmap:\n\tService: %.*s\n\tPort: %d\n\tProtocol: %.*s\n", - serv.name, serv.port, serv.protocolName); - foreach(string s; serv.aliases) - { - printf("\tAlias: %.*s\n", s); - } - } - else - { - printf("No service for epmap.\n"); - } + Service serv = new Service; + if(serv.getServiceByName("epmap", "tcp")) + { + printf("About service epmap:\n\tService: %.*s\n\tPort: %d\n\tProtocol: %.*s\n", + serv.name, serv.port, serv.protocolName); + foreach(string s; serv.aliases) + { + printf("\tAlias: %.*s\n", s); + } + } + else + { + printf("No service for epmap.\n"); + } } @@ -415,14 +415,14 @@ unittest */ class HostException: Exception { - int errorCode; /// Platform-specific error code. + int errorCode; /// Platform-specific error code. - this(string msg, int err = 0) - { - errorCode = err; - super(msg); - } + this(string msg, int err = 0) + { + errorCode = err; + super(msg); + } } /** @@ -430,139 +430,139 @@ class HostException: Exception */ class InternetHost { - /** These members are populated when one of the following functions are called without failure: */ - string name; - string[] aliases; /// ditto - uint32_t[] addrList; /// ditto + /** These members are populated when one of the following functions are called without failure: */ + string name; + string[] aliases; /// ditto + uint32_t[] addrList; /// ditto - void validHostent(hostent* he) - { - if(he.h_addrtype != cast(int)AddressFamily.INET || he.h_length != 4) - throw new HostException("Address family mismatch", _lasterr()); - } + void validHostent(hostent* he) + { + if(he.h_addrtype != cast(int)AddressFamily.INET || he.h_length != 4) + throw new HostException("Address family mismatch", _lasterr()); + } - void populate(hostent* he) - { - int i; - char* p; + void populate(hostent* he) + { + int i; + char* p; - name = std.string.toString(he.h_name).dup; + name = std.string.toString(he.h_name).dup; - for(i = 0;; i++) - { - p = he.h_aliases[i]; - if(!p) - break; - } + for(i = 0;; i++) + { + p = he.h_aliases[i]; + if(!p) + break; + } - if(i) - { - aliases = new string[i]; - for(i = 0; i != aliases.length; i++) - { + if(i) + { + aliases = new string[i]; + for(i = 0; i != aliases.length; i++) + { aliases[i] = std.string.toString(he.h_aliases[i]).dup; - } - } - else - { - aliases = null; - } + } + } + else + { + aliases = null; + } - for(i = 0;; i++) - { - p = he.h_addr_list[i]; - if(!p) - break; - } + for(i = 0;; i++) + { + p = he.h_addr_list[i]; + if(!p) + break; + } - if(i) - { - addrList = new uint32_t[i]; - for(i = 0; i != addrList.length; i++) - { - addrList[i] = ntohl(*(cast(uint32_t*)he.h_addr_list[i])); - } - } - else - { - addrList = null; - } - } + if(i) + { + addrList = new uint32_t[i]; + for(i = 0; i != addrList.length; i++) + { + addrList[i] = ntohl(*(cast(uint32_t*)he.h_addr_list[i])); + } + } + else + { + addrList = null; + } + } - /** - * Resolve host name. Returns false if unable to resolve. - */ - bool getHostByName(string name) - { - hostent* he; + /** + * Resolve host name. Returns false if unable to resolve. + */ + bool getHostByName(string name) + { + hostent* he; synchronized(this.classinfo) he = gethostbyname(toStringz(name)); - if(!he) - return false; - validHostent(he); - populate(he); - return true; - } + if(!he) + return false; + validHostent(he); + populate(he); + return true; + } - /** - * Resolve IPv4 address number. Returns false if unable to resolve. - */ - bool getHostByAddr(uint addr) - { - uint x = htonl(addr); - hostent* he; + /** + * Resolve IPv4 address number. Returns false if unable to resolve. + */ + bool getHostByAddr(uint addr) + { + uint x = htonl(addr); + hostent* he; synchronized(this.classinfo) he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET); - if(!he) - return false; - validHostent(he); - populate(he); - return true; - } + if(!he) + return false; + validHostent(he); + populate(he); + return true; + } - /** - * Same as previous, but addr is an IPv4 address string in the - * dotted-decimal form $(I a.b.c.d). - * Returns false if unable to resolve. - */ - bool getHostByAddr(string addr) - { - uint x = inet_addr(std.string.toStringz(addr)); - hostent* he; + /** + * Same as previous, but addr is an IPv4 address string in the + * dotted-decimal form $(I a.b.c.d). + * Returns false if unable to resolve. + */ + bool getHostByAddr(string addr) + { + uint x = inet_addr(std.string.toStringz(addr)); + hostent* he; synchronized(this.classinfo) he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET); - if(!he) - return false; - validHostent(he); - populate(he); - return true; - } + if(!he) + return false; + validHostent(he); + populate(he); + return true; + } } unittest { - InternetHost ih = new InternetHost; - assert(ih.getHostByName("www.digitalmars.com")); - printf("addrList.length = %d\n", ih.addrList.length); - assert(ih.addrList.length); - InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY); - printf("IP address = %.*s\nname = %.*s\n", ia.toAddrString(), ih.name); - foreach(int i, string s; ih.aliases) - { - printf("aliases[%d] = %.*s\n", i, s); - } + InternetHost ih = new InternetHost; + assert(ih.getHostByName("www.digitalmars.com")); + printf("addrList.length = %d\n", ih.addrList.length); + assert(ih.addrList.length); + InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY); + printf("IP address = %.*s\nname = %.*s\n", ia.toAddrString(), ih.name); + foreach(int i, string s; ih.aliases) + { + printf("aliases[%d] = %.*s\n", i, s); + } - printf("---\n"); + printf("---\n"); - assert(ih.getHostByAddr(ih.addrList[0])); - printf("name = %.*s\n", ih.name); - foreach(int i, string s; ih.aliases) - { - printf("aliases[%d] = %.*s\n", i, s); - } + assert(ih.getHostByAddr(ih.addrList[0])); + printf("name = %.*s\n", ih.name); + foreach(int i, string s; ih.aliases) + { + printf("aliases[%d] = %.*s\n", i, s); + } } @@ -571,10 +571,10 @@ unittest */ class AddressException: Exception { - this(string msg) - { - super(msg); - } + this(string msg) + { + super(msg); + } } @@ -583,10 +583,10 @@ class AddressException: Exception */ abstract class Address { - protected sockaddr* name(); - protected int nameLen(); - AddressFamily addressFamily(); /// Family of this address. - string toString(); /// Human readable string representing this address. + protected sockaddr* name(); + protected int nameLen(); + AddressFamily addressFamily(); /// Family of this address. + string toString(); /// Human readable string representing this address. } /** @@ -594,33 +594,33 @@ abstract class Address */ class UnknownAddress: Address { - protected: - sockaddr sa; + protected: + sockaddr sa; - sockaddr* name() - { - return &sa; - } + sockaddr* name() + { + return &sa; + } - int nameLen() - { - return sa.sizeof; - } + int nameLen() + { + return sa.sizeof; + } - public: - AddressFamily addressFamily() - { - return cast(AddressFamily)sa.sa_family; - } + public: + AddressFamily addressFamily() + { + return cast(AddressFamily)sa.sa_family; + } - string toString() - { - return "Unknown"; - } + string toString() + { + return "Unknown"; + } } @@ -630,155 +630,155 @@ class UnknownAddress: Address */ class InternetAddress: Address { - protected: - sockaddr_in sin; + protected: + sockaddr_in sin; - sockaddr* name() - { - return cast(sockaddr*)&sin; - } + sockaddr* name() + { + return cast(sockaddr*)&sin; + } - int nameLen() - { - return sin.sizeof; - } + int nameLen() + { + return sin.sizeof; + } - this() - { - } + this() + { + } - public: - const uint ADDR_ANY = INADDR_ANY; /// Any IPv4 address number. - const uint ADDR_NONE = INADDR_NONE; /// An invalid IPv4 address number. - const ushort PORT_ANY = 0; /// Any IPv4 port number. + public: + const uint ADDR_ANY = INADDR_ANY; /// Any IPv4 address number. + const uint ADDR_NONE = INADDR_NONE; /// An invalid IPv4 address number. + const ushort PORT_ANY = 0; /// Any IPv4 port number. - /// Overridden to return AddressFamily.INET. - AddressFamily addressFamily() - { - return cast(AddressFamily)AddressFamily.INET; - } + /// Overridden to return AddressFamily.INET. + AddressFamily addressFamily() + { + return cast(AddressFamily)AddressFamily.INET; + } - /// Returns the IPv4 port number. - ushort port() - { - return ntohs(sin.sin_port); - } + /// Returns the IPv4 port number. + ushort port() + { + return ntohs(sin.sin_port); + } - /// Returns the IPv4 address number. - uint addr() - { - return ntohl(sin.sin_addr.s_addr); - } + /// Returns the IPv4 address number. + uint addr() + { + return ntohl(sin.sin_addr.s_addr); + } - /** - * Params: - * addr = an IPv4 address string in the dotted-decimal form a.b.c.d, - * or a host name that will be resolved using an InternetHost - * object. - * port = may be PORT_ANY as stated below. - */ - this(string addr, ushort port) - { - uint uiaddr = parse(addr); - if(ADDR_NONE == uiaddr) - { - InternetHost ih = new InternetHost; - if(!ih.getHostByName(addr)) - //throw new AddressException("Invalid internet address"); + /** + * Params: + * addr = an IPv4 address string in the dotted-decimal form a.b.c.d, + * or a host name that will be resolved using an InternetHost + * object. + * port = may be PORT_ANY as stated below. + */ + this(string addr, ushort port) + { + uint uiaddr = parse(addr); + if(ADDR_NONE == uiaddr) + { + InternetHost ih = new InternetHost; + if(!ih.getHostByName(addr)) + //throw new AddressException("Invalid internet address"); throw new AddressException( "Unable to resolve host '" ~ addr ~ "'"); - uiaddr = ih.addrList[0]; - } - sin.sin_addr.s_addr = htonl(uiaddr); - sin.sin_port = htons(port); - } + uiaddr = ih.addrList[0]; + } + sin.sin_addr.s_addr = htonl(uiaddr); + sin.sin_port = htons(port); + } - /** - * Construct a new Address. addr may be ADDR_ANY (default) and port may - * be PORT_ANY, and the actual numbers may not be known until a connection - * is made. - */ - this(uint addr, ushort port) - { - sin.sin_addr.s_addr = htonl(addr); - sin.sin_port = htons(port); - } + /** + * Construct a new Address. addr may be ADDR_ANY (default) and port may + * be PORT_ANY, and the actual numbers may not be known until a connection + * is made. + */ + this(uint addr, ushort port) + { + sin.sin_addr.s_addr = htonl(addr); + sin.sin_port = htons(port); + } - /// ditto - this(ushort port) - { - sin.sin_addr.s_addr = 0; //any, "0.0.0.0" - sin.sin_port = htons(port); - } + /// ditto + this(ushort port) + { + sin.sin_addr.s_addr = 0; //any, "0.0.0.0" + sin.sin_port = htons(port); + } - /// Human readable string representing the IPv4 address in dotted-decimal form. - string toAddrString() - { - return std.string.toString(inet_ntoa(sin.sin_addr)).dup; - } + /// Human readable string representing the IPv4 address in dotted-decimal form. + string toAddrString() + { + return std.string.toString(inet_ntoa(sin.sin_addr)).dup; + } - /// Human readable string representing the IPv4 port. - string toPortString() - { - return std.string.toString(port()); - } + /// Human readable string representing the IPv4 port. + string toPortString() + { + return std.string.toString(port()); + } - /// Human readable string representing the IPv4 address and port in the form $(I a.b.c.d:e). - string toString() - { + /// Human readable string representing the IPv4 address and port in the form $(I a.b.c.d:e). + string toString() + { return toAddrString() ~ ":" ~ toPortString(); - } + } - /** - * Parse an IPv4 address string in the dotted-decimal form $(I a.b.c.d) - * and return the number. - * If the string is not a legitimate IPv4 address, - * ADDR_NONE is returned. - */ - static uint parse(string addr) - { - return ntohl(inet_addr(std.string.toStringz(addr))); - } + /** + * Parse an IPv4 address string in the dotted-decimal form $(I a.b.c.d) + * and return the number. + * If the string is not a legitimate IPv4 address, + * ADDR_NONE is returned. + */ + static uint parse(string addr) + { + return ntohl(inet_addr(std.string.toStringz(addr))); + } } unittest { - InternetAddress ia = new InternetAddress("63.105.9.61", 80); - assert(ia.toString() == "63.105.9.61:80"); + InternetAddress ia = new InternetAddress("63.105.9.61", 80); + assert(ia.toString() == "63.105.9.61:80"); } /** */ class SocketAcceptException: SocketException { - this(string msg, int err = 0) - { - super(msg, err); - } + this(string msg, int err = 0) + { + super(msg, err); + } } /// How a socket is shutdown: enum SocketShutdown: int { - RECEIVE = SD_RECEIVE, /// socket receives are disallowed - SEND = SD_SEND, /// socket sends are disallowed - BOTH = SD_BOTH, /// both RECEIVE and SEND + RECEIVE = SD_RECEIVE, /// socket receives are disallowed + SEND = SD_SEND, /// socket sends are disallowed + BOTH = SD_BOTH, /// both RECEIVE and SEND } /// Flags may be OR'ed together: enum SocketFlags: int { - NONE = 0, /// no flags specified + NONE = 0, /// no flags specified - OOB = MSG_OOB, /// out-of-band stream data - PEEK = MSG_PEEK, /// peek at incoming data without removing it from the queue, only for receiving - DONTROUTE = MSG_DONTROUTE, /// data should not be subject to routing; this flag may be ignored. Only for sending + OOB = MSG_OOB, /// out-of-band stream data + PEEK = MSG_PEEK, /// peek at incoming data without removing it from the queue, only for receiving + DONTROUTE = MSG_DONTROUTE, /// data should not be subject to routing; this flag may be ignored. Only for sending NOSIGNAL = MSG_NOSIGNAL, /// don't send SIGPIPE signal on socket write error and instead return EPIPE } @@ -786,214 +786,214 @@ enum SocketFlags: int /// Duration timeout value. extern(C) struct timeval { - // D interface - int seconds; /// Number of seconds. - int microseconds; /// Number of additional microseconds. + // D interface + int seconds; /// Number of seconds. + int microseconds; /// Number of additional microseconds. - // C interface - deprecated - { - alias seconds tv_sec; - alias microseconds tv_usec; - } + // C interface + deprecated + { + alias seconds tv_sec; + alias microseconds tv_usec; + } } /// A collection of sockets for use with Socket.select. class SocketSet { - private: - uint maxsockets; /// max desired sockets, the fd_set might be capable of holding more - fd_set set; + private: + uint maxsockets; /// max desired sockets, the fd_set might be capable of holding more + fd_set set; - version(Win32) - { - uint count() - { - return set.fd_count; - } - } - else version(BsdSockets) - { - int maxfd; - uint count; - } + version(Win32) + { + uint count() + { + return set.fd_count; + } + } + else version(BsdSockets) + { + int maxfd; + uint count; + } - public: + public: - /// Set the maximum amount of sockets that may be added. - this(uint max) - { - maxsockets = max; - reset(); - } + /// Set the maximum amount of sockets that may be added. + this(uint max) + { + maxsockets = max; + reset(); + } - /// Uses the default maximum for the system. - this() - { - this(FD_SETSIZE); - } + /// Uses the default maximum for the system. + this() + { + this(FD_SETSIZE); + } - /// Reset the SocketSet so that there are 0 Sockets in the collection. - void reset() - { - FD_ZERO(&set); + /// Reset the SocketSet so that there are 0 Sockets in the collection. + void reset() + { + FD_ZERO(&set); - version(BsdSockets) - { - maxfd = -1; - count = 0; - } - } + version(BsdSockets) + { + maxfd = -1; + count = 0; + } + } - void add(socket_t s) - in - { - // Make sure too many sockets don't get added. - assert(count < maxsockets); - version(BsdSockets) - { - assert(FDELT(s) < (FD_SETSIZE / NFDBITS)); - } - } - body - { - FD_SET(s, &set); + void add(socket_t s) + in + { + // Make sure too many sockets don't get added. + assert(count < maxsockets); + version(BsdSockets) + { + assert(FDELT(s) < (FD_SETSIZE / NFDBITS)); + } + } + body + { + FD_SET(s, &set); - version(BsdSockets) - { - ++count; - if(s > maxfd) - maxfd = s; - } - } + version(BsdSockets) + { + ++count; + if(s > maxfd) + maxfd = s; + } + } - /// Add a Socket to the collection. Adding more than the maximum has dangerous side affects. - void add(Socket s) - { - add(s.sock); - } + /// Add a Socket to the collection. Adding more than the maximum has dangerous side affects. + void add(Socket s) + { + add(s.sock); + } - void remove(socket_t s) - { - FD_CLR(s, &set); - version(BsdSockets) - { - --count; - // note: adjusting maxfd would require scanning the set, not worth it - } - } + void remove(socket_t s) + { + FD_CLR(s, &set); + version(BsdSockets) + { + --count; + // note: adjusting maxfd would require scanning the set, not worth it + } + } - /// Remove this Socket from the collection. - void remove(Socket s) - { - remove(s.sock); - } + /// Remove this Socket from the collection. + void remove(Socket s) + { + remove(s.sock); + } - int isSet(socket_t s) - { - return FD_ISSET(s, &set); - } + int isSet(socket_t s) + { + return FD_ISSET(s, &set); + } - /// Returns nonzero if this Socket is in the collection. - int isSet(Socket s) - { - return isSet(s.sock); - } + /// Returns nonzero if this Socket is in the collection. + int isSet(Socket s) + { + return isSet(s.sock); + } - /// Return maximum amount of sockets that can be added, like FD_SETSIZE. - uint max() - { - return maxsockets; - } + /// Return maximum amount of sockets that can be added, like FD_SETSIZE. + uint max() + { + return maxsockets; + } - fd_set* toFd_set() - { - return &set; - } + fd_set* toFd_set() + { + return &set; + } - int selectn() - { - version(Win32) - { - return count; - } - else version(BsdSockets) - { - return maxfd + 1; - } - } + int selectn() + { + version(Win32) + { + return count; + } + else version(BsdSockets) + { + return maxfd + 1; + } + } } /// The level at which a socket option is defined: enum SocketOptionLevel: int { - SOCKET = SOL_SOCKET, /// socket level - IP = ProtocolType.IP, /// internet protocol version 4 level - ICMP = ProtocolType.ICMP, /// - IGMP = ProtocolType.IGMP, /// - GGP = ProtocolType.GGP, /// - TCP = ProtocolType.TCP, /// transmission control protocol level - PUP = ProtocolType.PUP, /// - UDP = ProtocolType.UDP, /// user datagram protocol level - IDP = ProtocolType.IDP, /// - IPV6 = ProtocolType.IPV6, /// internet protocol version 6 level + SOCKET = SOL_SOCKET, /// socket level + IP = ProtocolType.IP, /// internet protocol version 4 level + ICMP = ProtocolType.ICMP, /// + IGMP = ProtocolType.IGMP, /// + GGP = ProtocolType.GGP, /// + TCP = ProtocolType.TCP, /// transmission control protocol level + PUP = ProtocolType.PUP, /// + UDP = ProtocolType.UDP, /// user datagram protocol level + IDP = ProtocolType.IDP, /// + IPV6 = ProtocolType.IPV6, /// internet protocol version 6 level } /// Linger information for use with SocketOption.LINGER. extern(C) struct linger { - // D interface - version(Win32) - { - uint16_t on; /// Nonzero for on. - uint16_t time; /// Linger time. - } - else version(BsdSockets) - { - int32_t on; - int32_t time; - } + // D interface + version(Win32) + { + uint16_t on; /// Nonzero for on. + uint16_t time; /// Linger time. + } + else version(BsdSockets) + { + int32_t on; + int32_t time; + } - // C interface - deprecated - { - alias on l_onoff; - alias time l_linger; - } + // C interface + deprecated + { + alias on l_onoff; + alias time l_linger; + } } /// Specifies a socket option: enum SocketOption: int { - DEBUG = SO_DEBUG, /// record debugging information - BROADCAST = SO_BROADCAST, /// allow transmission of broadcast messages - REUSEADDR = SO_REUSEADDR, /// allow local reuse of address - LINGER = SO_LINGER, /// linger on close if unsent data is present - OOBINLINE = SO_OOBINLINE, /// receive out-of-band data in band - SNDBUF = SO_SNDBUF, /// send buffer size - RCVBUF = SO_RCVBUF, /// receive buffer size - DONTROUTE = SO_DONTROUTE, /// do not route + DEBUG = SO_DEBUG, /// record debugging information + BROADCAST = SO_BROADCAST, /// allow transmission of broadcast messages + REUSEADDR = SO_REUSEADDR, /// allow local reuse of address + LINGER = SO_LINGER, /// linger on close if unsent data is present + OOBINLINE = SO_OOBINLINE, /// receive out-of-band data in band + SNDBUF = SO_SNDBUF, /// send buffer size + RCVBUF = SO_RCVBUF, /// receive buffer size + DONTROUTE = SO_DONTROUTE, /// do not route - // SocketOptionLevel.TCP: - TCP_NODELAY = .TCP_NODELAY, /// disable the Nagle algorithm for send coalescing + // SocketOptionLevel.TCP: + TCP_NODELAY = .TCP_NODELAY, /// disable the Nagle algorithm for send coalescing - // SocketOptionLevel.IPV6: - IPV6_UNICAST_HOPS = .IPV6_UNICAST_HOPS, /// - IPV6_MULTICAST_IF = .IPV6_MULTICAST_IF, /// - IPV6_MULTICAST_LOOP = .IPV6_MULTICAST_LOOP, /// - IPV6_JOIN_GROUP = .IPV6_JOIN_GROUP, /// - IPV6_LEAVE_GROUP = .IPV6_LEAVE_GROUP, /// + // SocketOptionLevel.IPV6: + IPV6_UNICAST_HOPS = .IPV6_UNICAST_HOPS, /// + IPV6_MULTICAST_IF = .IPV6_MULTICAST_IF, /// + IPV6_MULTICAST_LOOP = .IPV6_MULTICAST_LOOP, /// + IPV6_JOIN_GROUP = .IPV6_JOIN_GROUP, /// + IPV6_LEAVE_GROUP = .IPV6_LEAVE_GROUP, /// } @@ -1003,647 +1003,647 @@ enum SocketOption: int */ class Socket { - private: - socket_t sock; - AddressFamily _family; + private: + socket_t sock; + AddressFamily _family; - version(Win32) - bool _blocking = false; /// Property to get or set whether the socket is blocking or nonblocking. + version(Win32) + bool _blocking = false; /// Property to get or set whether the socket is blocking or nonblocking. - // For use with accepting(). - protected this() - { - } + // For use with accepting(). + protected this() + { + } - public: + public: - /** - * Create a blocking socket. If a single protocol type exists to support - * this socket type within the address family, the ProtocolType may be - * omitted. - */ - this(AddressFamily af, SocketType type, ProtocolType protocol) - { - sock = cast(socket_t)socket(af, type, protocol); - if(sock == socket_t.init) - throw new SocketException("Unable to create socket", _lasterr()); - _family = af; - } + /** + * Create a blocking socket. If a single protocol type exists to support + * this socket type within the address family, the ProtocolType may be + * omitted. + */ + this(AddressFamily af, SocketType type, ProtocolType protocol) + { + sock = cast(socket_t)socket(af, type, protocol); + if(sock == socket_t.init) + throw new SocketException("Unable to create socket", _lasterr()); + _family = af; + } - // A single protocol exists to support this socket type within the - // protocol family, so the ProtocolType is assumed. - /// ditto - this(AddressFamily af, SocketType type) - { - this(af, type, cast(ProtocolType)0); // Pseudo protocol number. - } + // A single protocol exists to support this socket type within the + // protocol family, so the ProtocolType is assumed. + /// ditto + this(AddressFamily af, SocketType type) + { + this(af, type, cast(ProtocolType)0); // Pseudo protocol number. + } - /// ditto - this(AddressFamily af, SocketType type, string protocolName) - { - protoent* proto; - proto = getprotobyname(toStringz(protocolName)); - if(!proto) - throw new SocketException("Unable to find the protocol", _lasterr()); - this(af, type, cast(ProtocolType)proto.p_proto); - } + /// ditto + this(AddressFamily af, SocketType type, string protocolName) + { + protoent* proto; + proto = getprotobyname(toStringz(protocolName)); + if(!proto) + throw new SocketException("Unable to find the protocol", _lasterr()); + this(af, type, cast(ProtocolType)proto.p_proto); + } - ~this() - { - close(); - } + ~this() + { + close(); + } - /// Get underlying socket handle. - socket_t handle() - { - return sock; - } + /// Get underlying socket handle. + socket_t handle() + { + return sock; + } - /** - * Get/set socket's blocking flag. - * - * When a socket is blocking, calls to receive(), accept(), and send() - * will block and wait for data/action. - * A non-blocking socket will immediately return instead of blocking. - */ - bool blocking() - { - version(Win32) - { - return _blocking; - } - else version(BsdSockets) - { - return !(fcntl(handle, F_GETFL, 0) & O_NONBLOCK); - } - } + /** + * Get/set socket's blocking flag. + * + * When a socket is blocking, calls to receive(), accept(), and send() + * will block and wait for data/action. + * A non-blocking socket will immediately return instead of blocking. + */ + bool blocking() + { + version(Win32) + { + return _blocking; + } + else version(BsdSockets) + { + return !(fcntl(handle, F_GETFL, 0) & O_NONBLOCK); + } + } - /// ditto - void blocking(bool byes) - { - version(Win32) - { - uint num = !byes; - if(_SOCKET_ERROR == ioctlsocket(sock, FIONBIO, &num)) - goto err; - _blocking = byes; - } - else version(BsdSockets) - { - int x = fcntl(sock, F_GETFL, 0); - if(-1 == x) - goto err; - if(byes) - x &= ~O_NONBLOCK; - else - x |= O_NONBLOCK; - if(-1 == fcntl(sock, F_SETFL, x)) - goto err; - } - return; // Success. + /// ditto + void blocking(bool byes) + { + version(Win32) + { + uint num = !byes; + if(_SOCKET_ERROR == ioctlsocket(sock, FIONBIO, &num)) + goto err; + _blocking = byes; + } + else version(BsdSockets) + { + int x = fcntl(sock, F_GETFL, 0); + if(-1 == x) + goto err; + if(byes) + x &= ~O_NONBLOCK; + else + x |= O_NONBLOCK; + if(-1 == fcntl(sock, F_SETFL, x)) + goto err; + } + return; // Success. - err: - throw new SocketException("Unable to set socket blocking", _lasterr()); - } + err: + throw new SocketException("Unable to set socket blocking", _lasterr()); + } - /// Get the socket's address family. - AddressFamily addressFamily() // getter - { - return _family; - } + /// Get the socket's address family. + AddressFamily addressFamily() // getter + { + return _family; + } - /// Property that indicates if this is a valid, alive socket. - bool isAlive() // getter - { - int type, typesize = type.sizeof; - return !getsockopt(sock, SOL_SOCKET, SO_TYPE, cast(char*)&type, &typesize); - } + /// Property that indicates if this is a valid, alive socket. + bool isAlive() // getter + { + int type, typesize = type.sizeof; + return !getsockopt(sock, SOL_SOCKET, SO_TYPE, cast(char*)&type, &typesize); + } - /// Associate a local address with this socket. - void bind(Address addr) - { - if(_SOCKET_ERROR == .bind(sock, addr.name(), addr.nameLen())) - throw new SocketException("Unable to bind socket", _lasterr()); - } + /// Associate a local address with this socket. + void bind(Address addr) + { + if(_SOCKET_ERROR == .bind(sock, addr.name(), addr.nameLen())) + throw new SocketException("Unable to bind socket", _lasterr()); + } - /** - * Establish a connection. If the socket is blocking, connect waits for - * the connection to be made. If the socket is nonblocking, connect - * returns immediately and the connection attempt is still in progress. - */ - void connect(Address to) - { - if(_SOCKET_ERROR == .connect(sock, to.name(), to.nameLen())) - { - int err; - err = _lasterr(); + /** + * Establish a connection. If the socket is blocking, connect waits for + * the connection to be made. If the socket is nonblocking, connect + * returns immediately and the connection attempt is still in progress. + */ + void connect(Address to) + { + if(_SOCKET_ERROR == .connect(sock, to.name(), to.nameLen())) + { + int err; + err = _lasterr(); - if(!blocking) - { - version(Win32) - { - if(WSAEWOULDBLOCK == err) - return; - } - else version(Posix) - { - if(EINPROGRESS == err) - return; - } - else - { - static assert(0); - } - } - throw new SocketException("Unable to connect socket", err); - } - } + if(!blocking) + { + version(Win32) + { + if(WSAEWOULDBLOCK == err) + return; + } + else version(Posix) + { + if(EINPROGRESS == err) + return; + } + else + { + static assert(0); + } + } + throw new SocketException("Unable to connect socket", err); + } + } - /** - * Listen for an incoming connection. bind must be called before you can - * listen. The backlog is a request of how many pending incoming - * connections are queued until accept'ed. - */ - void listen(int backlog) - { - if(_SOCKET_ERROR == .listen(sock, backlog)) - throw new SocketException("Unable to listen on socket", _lasterr()); - } + /** + * Listen for an incoming connection. bind must be called before you can + * listen. The backlog is a request of how many pending incoming + * connections are queued until accept'ed. + */ + void listen(int backlog) + { + if(_SOCKET_ERROR == .listen(sock, backlog)) + throw new SocketException("Unable to listen on socket", _lasterr()); + } - /** - * Called by accept when a new Socket must be created for a new - * connection. To use a derived class, override this method and return an - * instance of your class. The returned Socket's handle must not be set; - * Socket has a protected constructor this() to use in this situation. - */ - // Override to use a derived class. - // The returned socket's handle must not be set. - protected Socket accepting() - { - return new Socket; - } + /** + * Called by accept when a new Socket must be created for a new + * connection. To use a derived class, override this method and return an + * instance of your class. The returned Socket's handle must not be set; + * Socket has a protected constructor this() to use in this situation. + */ + // Override to use a derived class. + // The returned socket's handle must not be set. + protected Socket accepting() + { + return new Socket; + } - /** - * Accept an incoming connection. If the socket is blocking, accept - * waits for a connection request. Throws SocketAcceptException if unable - * to accept. See accepting for use with derived classes. - */ - Socket accept() - { - socket_t newsock; - //newsock = cast(socket_t).accept(sock, null, null); // DMD 0.101 error: found '(' when expecting ';' following 'statement - alias .accept topaccept; - newsock = cast(socket_t)topaccept(sock, null, null); - if(socket_t.init == newsock) - throw new SocketAcceptException("Unable to accept socket connection", _lasterr()); + /** + * Accept an incoming connection. If the socket is blocking, accept + * waits for a connection request. Throws SocketAcceptException if unable + * to accept. See accepting for use with derived classes. + */ + Socket accept() + { + socket_t newsock; + //newsock = cast(socket_t).accept(sock, null, null); // DMD 0.101 error: found '(' when expecting ';' following 'statement + alias .accept topaccept; + newsock = cast(socket_t)topaccept(sock, null, null); + if(socket_t.init == newsock) + throw new SocketAcceptException("Unable to accept socket connection", _lasterr()); - Socket newSocket; - try - { - newSocket = accepting(); - assert(newSocket.sock == socket_t.init); + Socket newSocket; + try + { + newSocket = accepting(); + assert(newSocket.sock == socket_t.init); - newSocket.sock = newsock; - version(Win32) - newSocket._blocking = _blocking; //inherits blocking mode - newSocket._family = _family; //same family - } - catch(Object o) - { - _close(newsock); - throw o; - } + newSocket.sock = newsock; + version(Win32) + newSocket._blocking = _blocking; //inherits blocking mode + newSocket._family = _family; //same family + } + catch(Object o) + { + _close(newsock); + throw o; + } - return newSocket; - } + return newSocket; + } - /// Disables sends and/or receives. - void shutdown(SocketShutdown how) - { - .shutdown(sock, cast(int)how); - } + /// Disables sends and/or receives. + void shutdown(SocketShutdown how) + { + .shutdown(sock, cast(int)how); + } - private static void _close(socket_t sock) - { - version(Win32) - { - .closesocket(sock); - } - else version(BsdSockets) - { - .close(sock); - } - } + private static void _close(socket_t sock) + { + version(Win32) + { + .closesocket(sock); + } + else version(BsdSockets) + { + .close(sock); + } + } - /** - * Immediately drop any connections and release socket resources. - * Calling shutdown before close is recommended for connection-oriented - * sockets. The Socket object is no longer usable after close. - */ - //calling shutdown() before this is recommended - //for connection-oriented sockets - void close() - { - _close(sock); - sock = socket_t.init; - } + /** + * Immediately drop any connections and release socket resources. + * Calling shutdown before close is recommended for connection-oriented + * sockets. The Socket object is no longer usable after close. + */ + //calling shutdown() before this is recommended + //for connection-oriented sockets + void close() + { + _close(sock); + sock = socket_t.init; + } - private Address newFamilyObject() - { - Address result; - switch(_family) - { - case cast(AddressFamily)AddressFamily.INET: - result = new InternetAddress; - break; + private Address newFamilyObject() + { + Address result; + switch(_family) + { + case cast(AddressFamily)AddressFamily.INET: + result = new InternetAddress; + break; - default: - result = new UnknownAddress; - } - return result; - } + default: + result = new UnknownAddress; + } + return result; + } - /// Returns the local machine's host name. Idea from mango. - static string hostName() // getter - { - char[256] result; // Host names are limited to 255 chars. - if(_SOCKET_ERROR == .gethostname(result.ptr, result.length)) - throw new SocketException("Unable to obtain host name", _lasterr()); - return std.string.toString(cast(char*)result).dup; - } + /// Returns the local machine's host name. Idea from mango. + static string hostName() // getter + { + char[256] result; // Host names are limited to 255 chars. + if(_SOCKET_ERROR == .gethostname(result.ptr, result.length)) + throw new SocketException("Unable to obtain host name", _lasterr()); + return std.string.toString(cast(char*)result).dup; + } - /// Remote endpoint Address. - Address remoteAddress() - { - Address addr = newFamilyObject(); - int nameLen = addr.nameLen(); - if(_SOCKET_ERROR == .getpeername(sock, addr.name(), &nameLen)) - throw new SocketException("Unable to obtain remote socket address", _lasterr()); - assert(addr.addressFamily() == _family); - return addr; - } + /// Remote endpoint Address. + Address remoteAddress() + { + Address addr = newFamilyObject(); + int nameLen = addr.nameLen(); + if(_SOCKET_ERROR == .getpeername(sock, addr.name(), &nameLen)) + throw new SocketException("Unable to obtain remote socket address", _lasterr()); + assert(addr.addressFamily() == _family); + return addr; + } - /// Local endpoint Address. - Address localAddress() - { - Address addr = newFamilyObject(); - int nameLen = addr.nameLen(); - if(_SOCKET_ERROR == .getsockname(sock, addr.name(), &nameLen)) - throw new SocketException("Unable to obtain local socket address", _lasterr()); - assert(addr.addressFamily() == _family); - return addr; - } + /// Local endpoint Address. + Address localAddress() + { + Address addr = newFamilyObject(); + int nameLen = addr.nameLen(); + if(_SOCKET_ERROR == .getsockname(sock, addr.name(), &nameLen)) + throw new SocketException("Unable to obtain local socket address", _lasterr()); + assert(addr.addressFamily() == _family); + return addr; + } - /// Send or receive error code. - const int ERROR = _SOCKET_ERROR; + /// Send or receive error code. + const int ERROR = _SOCKET_ERROR; - /** - * Send data on the connection. Returns the number of bytes actually - * sent, or ERROR on failure. If the socket is blocking and there is no - * buffer space left, send waits. - */ - //returns number of bytes actually sent, or -1 on error - int send(void[] buf, SocketFlags flags) - { + /** + * Send data on the connection. Returns the number of bytes actually + * sent, or ERROR on failure. If the socket is blocking and there is no + * buffer space left, send waits. + */ + //returns number of bytes actually sent, or -1 on error + int send(void[] buf, SocketFlags flags) + { flags |= SocketFlags.NOSIGNAL; - int sent = .send(sock, buf.ptr, buf.length, cast(int)flags); - return sent; - } + int sent = .send(sock, buf.ptr, buf.length, cast(int)flags); + return sent; + } - /// ditto - int send(void[] buf) - { - return send(buf, SocketFlags.NOSIGNAL); - } + /// ditto + int send(void[] buf) + { + return send(buf, SocketFlags.NOSIGNAL); + } - /** - * Send data to a specific destination Address. If the destination address is not specified, a connection must have been made and that address is used. If the socket is blocking and there is no buffer space left, sendTo waits. - */ - int sendTo(void[] buf, SocketFlags flags, Address to) - { + /** + * Send data to a specific destination Address. If the destination address is not specified, a connection must have been made and that address is used. If the socket is blocking and there is no buffer space left, sendTo waits. + */ + int sendTo(void[] buf, SocketFlags flags, Address to) + { flags |= SocketFlags.NOSIGNAL; - int sent = .sendto(sock, buf.ptr, buf.length, cast(int)flags, to.name(), to.nameLen()); - return sent; - } + int sent = .sendto(sock, buf.ptr, buf.length, cast(int)flags, to.name(), to.nameLen()); + return sent; + } - /// ditto - int sendTo(void[] buf, Address to) - { - return sendTo(buf, SocketFlags.NONE, to); - } + /// ditto + int sendTo(void[] buf, Address to) + { + return sendTo(buf, SocketFlags.NONE, to); + } - //assumes you connect()ed - /// ditto - int sendTo(void[] buf, SocketFlags flags) - { + //assumes you connect()ed + /// ditto + int sendTo(void[] buf, SocketFlags flags) + { flags |= SocketFlags.NOSIGNAL; - int sent = .sendto(sock, buf.ptr, buf.length, cast(int)flags, null, 0); - return sent; - } + int sent = .sendto(sock, buf.ptr, buf.length, cast(int)flags, null, 0); + return sent; + } - //assumes you connect()ed - /// ditto - int sendTo(void[] buf) - { - return sendTo(buf, SocketFlags.NONE); - } + //assumes you connect()ed + /// ditto + int sendTo(void[] buf) + { + return sendTo(buf, SocketFlags.NONE); + } - /** - * Receive data on the connection. Returns the number of bytes actually - * received, 0 if the remote side has closed the connection, or ERROR on - * failure. If the socket is blocking, receive waits until there is data - * to be received. - */ - //returns number of bytes actually received, 0 on connection closure, or -1 on error - int receive(void[] buf, SocketFlags flags) - { - if(!buf.length) //return 0 and don't think the connection closed - return 0; - int read = .recv(sock, buf.ptr, buf.length, cast(int)flags); - // if(!read) //connection closed - return read; - } + /** + * Receive data on the connection. Returns the number of bytes actually + * received, 0 if the remote side has closed the connection, or ERROR on + * failure. If the socket is blocking, receive waits until there is data + * to be received. + */ + //returns number of bytes actually received, 0 on connection closure, or -1 on error + int receive(void[] buf, SocketFlags flags) + { + if(!buf.length) //return 0 and don't think the connection closed + return 0; + int read = .recv(sock, buf.ptr, buf.length, cast(int)flags); + // if(!read) //connection closed + return read; + } - /// ditto - int receive(void[] buf) - { - return receive(buf, SocketFlags.NONE); - } + /// ditto + int receive(void[] buf) + { + return receive(buf, SocketFlags.NONE); + } - /** - * Receive data and get the remote endpoint Address. - * If the socket is blocking, receiveFrom waits until there is data to - * be received. - * Returns: the number of bytes actually received, - * 0 if the remote side has closed the connection, or ERROR on failure. - */ - int receiveFrom(void[] buf, SocketFlags flags, out Address from) - { - if(!buf.length) //return 0 and don't think the connection closed - return 0; - from = newFamilyObject(); - int nameLen = from.nameLen(); - int read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, from.name(), &nameLen); - assert(from.addressFamily() == _family); - // if(!read) //connection closed - return read; - } + /** + * Receive data and get the remote endpoint Address. + * If the socket is blocking, receiveFrom waits until there is data to + * be received. + * Returns: the number of bytes actually received, + * 0 if the remote side has closed the connection, or ERROR on failure. + */ + int receiveFrom(void[] buf, SocketFlags flags, out Address from) + { + if(!buf.length) //return 0 and don't think the connection closed + return 0; + from = newFamilyObject(); + int nameLen = from.nameLen(); + int read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, from.name(), &nameLen); + assert(from.addressFamily() == _family); + // if(!read) //connection closed + return read; + } - /// ditto - int receiveFrom(void[] buf, out Address from) - { - return receiveFrom(buf, SocketFlags.NONE, from); - } + /// ditto + int receiveFrom(void[] buf, out Address from) + { + return receiveFrom(buf, SocketFlags.NONE, from); + } - //assumes you connect()ed - /// ditto - int receiveFrom(void[] buf, SocketFlags flags) - { - if(!buf.length) //return 0 and don't think the connection closed - return 0; - int read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, null, null); - // if(!read) //connection closed - return read; - } + //assumes you connect()ed + /// ditto + int receiveFrom(void[] buf, SocketFlags flags) + { + if(!buf.length) //return 0 and don't think the connection closed + return 0; + int read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, null, null); + // if(!read) //connection closed + return read; + } - //assumes you connect()ed - /// ditto - int receiveFrom(void[] buf) - { - return receiveFrom(buf, SocketFlags.NONE); - } + //assumes you connect()ed + /// ditto + int receiveFrom(void[] buf) + { + return receiveFrom(buf, SocketFlags.NONE); + } - /// Get a socket option. Returns the number of bytes written to result. - //returns the length, in bytes, of the actual result - very different from getsockopt() - int getOption(SocketOptionLevel level, SocketOption option, void[] result) - { - int len = result.length; - if(_SOCKET_ERROR == .getsockopt(sock, cast(int)level, cast(int)option, result.ptr, &len)) - throw new SocketException("Unable to get socket option", _lasterr()); - return len; - } + /// Get a socket option. Returns the number of bytes written to result. + //returns the length, in bytes, of the actual result - very different from getsockopt() + int getOption(SocketOptionLevel level, SocketOption option, void[] result) + { + int len = result.length; + if(_SOCKET_ERROR == .getsockopt(sock, cast(int)level, cast(int)option, result.ptr, &len)) + throw new SocketException("Unable to get socket option", _lasterr()); + return len; + } - /// Common case of getting integer and boolean options. - int getOption(SocketOptionLevel level, SocketOption option, out int32_t result) - { - return getOption(level, option, (&result)[0 .. 1]); - } + /// Common case of getting integer and boolean options. + int getOption(SocketOptionLevel level, SocketOption option, out int32_t result) + { + return getOption(level, option, (&result)[0 .. 1]); + } - /// Get the linger option. - int getOption(SocketOptionLevel level, SocketOption option, out linger result) - { - //return getOption(cast(SocketOptionLevel)SocketOptionLevel.SOCKET, SocketOption.LINGER, (&result)[0 .. 1]); - return getOption(level, option, (&result)[0 .. 1]); - } + /// Get the linger option. + int getOption(SocketOptionLevel level, SocketOption option, out linger result) + { + //return getOption(cast(SocketOptionLevel)SocketOptionLevel.SOCKET, SocketOption.LINGER, (&result)[0 .. 1]); + return getOption(level, option, (&result)[0 .. 1]); + } - // Set a socket option. - void setOption(SocketOptionLevel level, SocketOption option, void[] value) - { - if(_SOCKET_ERROR == .setsockopt(sock, cast(int)level, cast(int)option, value.ptr, value.length)) - throw new SocketException("Unable to set socket option", _lasterr()); - } + // Set a socket option. + void setOption(SocketOptionLevel level, SocketOption option, void[] value) + { + if(_SOCKET_ERROR == .setsockopt(sock, cast(int)level, cast(int)option, value.ptr, value.length)) + throw new SocketException("Unable to set socket option", _lasterr()); + } - /// Common case for setting integer and boolean options. - void setOption(SocketOptionLevel level, SocketOption option, int32_t value) - { - setOption(level, option, (&value)[0 .. 1]); - } + /// Common case for setting integer and boolean options. + void setOption(SocketOptionLevel level, SocketOption option, int32_t value) + { + setOption(level, option, (&value)[0 .. 1]); + } - /// Set the linger option. - void setOption(SocketOptionLevel level, SocketOption option, linger value) - { - //setOption(cast(SocketOptionLevel)SocketOptionLevel.SOCKET, SocketOption.LINGER, (&value)[0 .. 1]); - setOption(level, option, (&value)[0 .. 1]); - } + /// Set the linger option. + void setOption(SocketOptionLevel level, SocketOption option, linger value) + { + //setOption(cast(SocketOptionLevel)SocketOptionLevel.SOCKET, SocketOption.LINGER, (&value)[0 .. 1]); + setOption(level, option, (&value)[0 .. 1]); + } - /** - * Wait for a socket to change status. A wait timeout timeval or int microseconds may be specified; if a timeout is not specified or the timeval is null, the maximum timeout is used. The timeval timeout has an unspecified value when select returns. Returns the number of sockets with status changes, 0 on timeout, or -1 on interruption. If the return value is greater than 0, the SocketSets are updated to only contain the sockets having status changes. For a connecting socket, a write status change means the connection is established and it's able to send. For a listening socket, a read status change means there is an incoming connection request and it's able to accept. - */ - //SocketSet's updated to include only those sockets which an event occured - //returns the number of events, 0 on timeout, or -1 on interruption - //for a connect()ing socket, writeability means connected - //for a listen()ing socket, readability means listening - //Winsock: possibly internally limited to 64 sockets per set - static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, timeval* tv) - in - { - //make sure none of the SocketSet's are the same object - if(checkRead) - { - assert(checkRead !is checkWrite); - assert(checkRead !is checkError); - } - if(checkWrite) - { - assert(checkWrite !is checkError); - } - } - body - { - fd_set* fr, fw, fe; - int n = 0; + /** + * Wait for a socket to change status. A wait timeout timeval or int microseconds may be specified; if a timeout is not specified or the timeval is null, the maximum timeout is used. The timeval timeout has an unspecified value when select returns. Returns the number of sockets with status changes, 0 on timeout, or -1 on interruption. If the return value is greater than 0, the SocketSets are updated to only contain the sockets having status changes. For a connecting socket, a write status change means the connection is established and it's able to send. For a listening socket, a read status change means there is an incoming connection request and it's able to accept. + */ + //SocketSet's updated to include only those sockets which an event occured + //returns the number of events, 0 on timeout, or -1 on interruption + //for a connect()ing socket, writeability means connected + //for a listen()ing socket, readability means listening + //Winsock: possibly internally limited to 64 sockets per set + static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, timeval* tv) + in + { + //make sure none of the SocketSet's are the same object + if(checkRead) + { + assert(checkRead !is checkWrite); + assert(checkRead !is checkError); + } + if(checkWrite) + { + assert(checkWrite !is checkError); + } + } + body + { + fd_set* fr, fw, fe; + int n = 0; - version(Win32) - { - // Windows has a problem with empty fd_set`s that aren't null. - fr = (checkRead && checkRead.count()) ? checkRead.toFd_set() : null; - fw = (checkWrite && checkWrite.count()) ? checkWrite.toFd_set() : null; - fe = (checkError && checkError.count()) ? checkError.toFd_set() : null; - } - else - { - if(checkRead) - { - fr = checkRead.toFd_set(); - n = checkRead.selectn(); - } - else - { - fr = null; - } + version(Win32) + { + // Windows has a problem with empty fd_set`s that aren't null. + fr = (checkRead && checkRead.count()) ? checkRead.toFd_set() : null; + fw = (checkWrite && checkWrite.count()) ? checkWrite.toFd_set() : null; + fe = (checkError && checkError.count()) ? checkError.toFd_set() : null; + } + else + { + if(checkRead) + { + fr = checkRead.toFd_set(); + n = checkRead.selectn(); + } + else + { + fr = null; + } - if(checkWrite) - { - fw = checkWrite.toFd_set(); - int _n; - _n = checkWrite.selectn(); - if(_n > n) - n = _n; - } - else - { - fw = null; - } + if(checkWrite) + { + fw = checkWrite.toFd_set(); + int _n; + _n = checkWrite.selectn(); + if(_n > n) + n = _n; + } + else + { + fw = null; + } - if(checkError) - { - fe = checkError.toFd_set(); - int _n; - _n = checkError.selectn(); - if(_n > n) - n = _n; - } - else - { - fe = null; - } - } + if(checkError) + { + fe = checkError.toFd_set(); + int _n; + _n = checkError.selectn(); + if(_n > n) + n = _n; + } + else + { + fe = null; + } + } - int result = .select(n, fr, fw, fe, cast(_ctimeval*)tv); + int result = .select(n, fr, fw, fe, cast(_ctimeval*)tv); - version(Win32) - { - if(_SOCKET_ERROR == result && WSAGetLastError() == WSAEINTR) - return -1; - } - else version(Posix) - { - if(_SOCKET_ERROR == result && getErrno() == EINTR) - return -1; - } - else - { - static assert(0); - } + version(Win32) + { + if(_SOCKET_ERROR == result && WSAGetLastError() == WSAEINTR) + return -1; + } + else version(Posix) + { + if(_SOCKET_ERROR == result && getErrno() == EINTR) + return -1; + } + else + { + static assert(0); + } - if(_SOCKET_ERROR == result) - throw new SocketException("Socket select error", _lasterr()); + if(_SOCKET_ERROR == result) + throw new SocketException("Socket select error", _lasterr()); - return result; - } + return result; + } - /// ditto - static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, int microseconds) - { - timeval tv; - tv.seconds = microseconds / 1_000_000; - tv.microseconds = microseconds % 1_000_000; - return select(checkRead, checkWrite, checkError, &tv); - } + /// ditto + static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, int microseconds) + { + timeval tv; + tv.seconds = microseconds / 1_000_000; + tv.microseconds = microseconds % 1_000_000; + return select(checkRead, checkWrite, checkError, &tv); + } - /// ditto - //maximum timeout - static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError) - { - return select(checkRead, checkWrite, checkError, null); - } + /// ditto + //maximum timeout + static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError) + { + return select(checkRead, checkWrite, checkError, null); + } - /+ - bool poll(events) - { - int WSAEventSelect(socket_t s, WSAEVENT hEventObject, int lNetworkEvents); // Winsock 2 ? - int poll(pollfd* fds, int nfds, int timeout); // Unix ? - } - +/ + /+ + bool poll(events) + { + int WSAEventSelect(socket_t s, WSAEVENT hEventObject, int lNetworkEvents); // Winsock 2 ? + int poll(pollfd* fds, int nfds, int timeout); // Unix ? + } + +/ } /// TcpSocket is a shortcut class for a TCP Socket. class TcpSocket: Socket { - /// Constructs a blocking TCP Socket. - this(AddressFamily family) - { - super(family, SocketType.STREAM, ProtocolType.TCP); - } + /// Constructs a blocking TCP Socket. + this(AddressFamily family) + { + super(family, SocketType.STREAM, ProtocolType.TCP); + } - /// Constructs a blocking TCP Socket. - this() - { - this(cast(AddressFamily)AddressFamily.INET); - } + /// Constructs a blocking TCP Socket. + this() + { + this(cast(AddressFamily)AddressFamily.INET); + } - //shortcut - /// Constructs a blocking TCP Socket and connects to an InternetAddress. - this(Address connectTo) - { - this(connectTo.addressFamily()); - connect(connectTo); - } + //shortcut + /// Constructs a blocking TCP Socket and connects to an InternetAddress. + this(Address connectTo) + { + this(connectTo.addressFamily()); + connect(connectTo); + } } /// UdpSocket is a shortcut class for a UDP Socket. class UdpSocket: Socket { - /// Constructs a blocking UDP Socket. - this(AddressFamily family) - { - super(family, SocketType.DGRAM, ProtocolType.UDP); - } + /// Constructs a blocking UDP Socket. + this(AddressFamily family) + { + super(family, SocketType.DGRAM, ProtocolType.UDP); + } - /// Constructs a blocking UDP Socket. - this() - { - this(cast(AddressFamily)AddressFamily.INET); - } + /// Constructs a blocking UDP Socket. + this() + { + this(cast(AddressFamily)AddressFamily.INET); + } } diff --git a/std/socketstream.d b/std/socketstream.d index 8c1cfad8c..ce7343c0b 100644 --- a/std/socketstream.d +++ b/std/socketstream.d @@ -1,21 +1,21 @@ /* - Copyright (C) 2004 Christopher E. Miller - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. + Copyright (C) 2004 Christopher E. Miller + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. */ /************** @@ -25,10 +25,10 @@ * For Win32 systems, link with ws2_32.lib. * * Example: - * See /dmd/samples/d/htmlget.d + * See /dmd/samples/d/htmlget.d * Authors: Christopher E. Miller * References: - * $(LINK2 std_stream.html, std.stream) + * $(LINK2 std_stream.html, std.stream) * Macros: WIKI=Phobos/StdSocketstream */ @@ -44,99 +44,99 @@ private import std.socket; class SocketStream: Stream { private: - Socket sock; - + Socket sock; + public: - /** - * Constructs a SocketStream with the specified Socket and FileMode flags. - */ - this(Socket sock, FileMode mode) - { - if(mode & FileMode.In) - readable = true; - if(mode & FileMode.Out) - writeable = true; - - this.sock = sock; - } - - /** - * Uses mode FileMode.In | FileMode.Out. - */ - this(Socket sock) - { - writeable = readable = true; - this.sock = sock; - } - - /** - * Property to get the Socket that is being streamed. - */ - Socket socket() - { - return sock; - } - - /** - * Attempts to read the entire block, waiting if necessary. - */ - override size_t readBlock(void* _buffer, size_t size) - { - ubyte* buffer = cast(ubyte*)_buffer; - assertReadable(); - - if (size == 0) - return size; - - auto len = sock.receive(buffer[0 .. size]); - readEOF = cast(bool)(len == 0); - if (len == sock.ERROR) - len = 0; - return len; - } - - /** - * Attempts to write the entire block, waiting if necessary. - */ - override size_t writeBlock(void* _buffer, size_t size) - { - ubyte* buffer = cast(ubyte*)_buffer; - assertWriteable(); + /** + * Constructs a SocketStream with the specified Socket and FileMode flags. + */ + this(Socket sock, FileMode mode) + { + if(mode & FileMode.In) + readable = true; + if(mode & FileMode.Out) + writeable = true; - if (size == 0) - return size; - - auto len = sock.send(buffer[0 .. size]); - readEOF = cast(bool)(len == 0); - if (len == sock.ERROR) - len = 0; - return len; - } - - /** - * - */ - override ulong seek(long offset, SeekPos whence) - { - throw new SeekException("Cannot seek a socket."); - } - - /** - * Does not return the entire stream because that would - * require the remote connection to be closed. - */ - override char[] toString() - { - return sock.toString(); - } - - /** - * Close the Socket. - */ - override void close() - { - sock.close(); - } + this.sock = sock; + } + + /** + * Uses mode FileMode.In | FileMode.Out. + */ + this(Socket sock) + { + writeable = readable = true; + this.sock = sock; + } + + /** + * Property to get the Socket that is being streamed. + */ + Socket socket() + { + return sock; + } + + /** + * Attempts to read the entire block, waiting if necessary. + */ + override size_t readBlock(void* _buffer, size_t size) + { + ubyte* buffer = cast(ubyte*)_buffer; + assertReadable(); + + if (size == 0) + return size; + + auto len = sock.receive(buffer[0 .. size]); + readEOF = cast(bool)(len == 0); + if (len == sock.ERROR) + len = 0; + return len; + } + + /** + * Attempts to write the entire block, waiting if necessary. + */ + override size_t writeBlock(void* _buffer, size_t size) + { + ubyte* buffer = cast(ubyte*)_buffer; + assertWriteable(); + + if (size == 0) + return size; + + auto len = sock.send(buffer[0 .. size]); + readEOF = cast(bool)(len == 0); + if (len == sock.ERROR) + len = 0; + return len; + } + + /** + * + */ + override ulong seek(long offset, SeekPos whence) + { + throw new SeekException("Cannot seek a socket."); + } + + /** + * Does not return the entire stream because that would + * require the remote connection to be closed. + */ + override char[] toString() + { + return sock.toString(); + } + + /** + * Close the Socket. + */ + override void close() + { + sock.close(); + } } diff --git a/std/stdio.d b/std/stdio.d index fc0330b15..2a9eb69ab 100644 --- a/std/stdio.d +++ b/std/stdio.d @@ -11,7 +11,7 @@ * $(B std.c.stdio) is automatically imported when importing * $(B std.stdio). * Macros: - * WIKI=Phobos/StdStdio + * WIKI=Phobos/StdStdio */ module std.stdio; @@ -31,8 +31,8 @@ version (DigitalMars) { version (Windows) { - // Specific to the way Digital Mars C does stdio - version = DIGITAL_MARS_STDIO; + // Specific to the way Digital Mars C does stdio + version = DIGITAL_MARS_STDIO; } } @@ -62,15 +62,15 @@ version (DIGITAL_MARS_STDIO) { extern (C) { - /* ** - * Digital Mars under-the-hood C I/O functions - */ - int _fputc_nlock(int, FILE*); - int _fputwc_nlock(int, FILE*); - int _fgetc_nlock(FILE*); - int _fgetwc_nlock(FILE*); - int __fp_lock(FILE*); - void __fp_unlock(FILE*); + /* ** + * Digital Mars under-the-hood C I/O functions + */ + int _fputc_nlock(int, FILE*); + int _fputwc_nlock(int, FILE*); + int _fgetc_nlock(FILE*); + int _fgetwc_nlock(FILE*); + int __fp_lock(FILE*); + void __fp_unlock(FILE*); } alias _fputc_nlock FPUTC; alias _fputwc_nlock FPUTWC; @@ -88,14 +88,14 @@ else version (GCC_IO) */ extern (C) { - int fputc_unlocked(int, FILE*); - int fputwc_unlocked(wchar_t, FILE*); - int fgetc_unlocked(FILE*); - int fgetwc_unlocked(FILE*); - void flockfile(FILE*); - void funlockfile(FILE*); - ssize_t getline(char**, size_t*, FILE*); - ssize_t getdelim (char**, size_t*, int, FILE*); + int fputc_unlocked(int, FILE*); + int fputwc_unlocked(wchar_t, FILE*); + int fgetc_unlocked(FILE*); + int fgetwc_unlocked(FILE*); + void flockfile(FILE*); + void funlockfile(FILE*); + ssize_t getline(char**, size_t*, FILE*); + ssize_t getdelim (char**, size_t*, int, FILE*); } alias fputc_unlocked FPUTC; @@ -110,8 +110,8 @@ else version (GENERIC_IO) { extern (C) { - void flockfile(FILE*); - void funlockfile(FILE*); + void flockfile(FILE*); + void funlockfile(FILE*); } alias fputc FPUTC; @@ -133,34 +133,34 @@ else */ class StdioException : Exception { - uint errno; // operating system error code + uint errno; // operating system error code this(string msg) { - super(msg); + super(msg); } this(uint errno) { - version (Posix) - { char[80] buf = void; - auto s = std.c.string.strerror_r(errno, buf.ptr, buf.length); - } - else - { - auto s = std.c.string.strerror(errno); - } - super(std.string.toString(s).dup); + version (Posix) + { char[80] buf = void; + auto s = std.c.string.strerror_r(errno, buf.ptr, buf.length); + } + else + { + auto s = std.c.string.strerror(errno); + } + super(std.string.toString(s).dup); } static void opCall(string msg) { - throw new StdioException(msg); + throw new StdioException(msg); } static void opCall() { - throw new StdioException(getErrno()); + throw new StdioException(getErrno()); } } @@ -175,62 +175,62 @@ void writefx(FILE* fp, TypeInfo[] arguments, void* argptr, int newline=false) FLOCK(fp); scope(exit) FUNLOCK(fp); - if (orientation <= 0) // byte orientation or no orientation + if (orientation <= 0) // byte orientation or no orientation { - void putc(dchar c) - { - if (c <= 0x7F) - { - FPUTC(c, fp); - } - else - { char[4] buf; - auto b = std.utf.toUTF8(buf, c); - for (size_t i = 0; i < b.length; i++) - FPUTC(b[i], fp); - } - } + void putc(dchar c) + { + if (c <= 0x7F) + { + FPUTC(c, fp); + } + else + { char[4] buf; + auto b = std.utf.toUTF8(buf, c); + for (size_t i = 0; i < b.length; i++) + FPUTC(b[i], fp); + } + } - std.format.doFormat(&putc, arguments, argptr); - if (newline) - FPUTC('\n', fp); + std.format.doFormat(&putc, arguments, argptr); + if (newline) + FPUTC('\n', fp); } - else if (orientation > 0) // wide orientation + else if (orientation > 0) // wide orientation { - version (Windows) - { - void putcw(dchar c) - { - assert(isValidDchar(c)); - if (c <= 0xFFFF) - { - FPUTWC(c, fp); - } - else - { wchar[2] buf; + version (Windows) + { + void putcw(dchar c) + { + assert(isValidDchar(c)); + if (c <= 0xFFFF) + { + FPUTWC(c, fp); + } + else + { wchar[2] buf; - buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); - buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); - FPUTWC(buf[0], fp); - FPUTWC(buf[1], fp); - } - } - } - else version (Posix) - { - void putcw(dchar c) - { - FPUTWC(c, fp); - } - } - else - { - static assert(0); - } + buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); + buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); + FPUTWC(buf[0], fp); + FPUTWC(buf[1], fp); + } + } + } + else version (Posix) + { + void putcw(dchar c) + { + FPUTWC(c, fp); + } + } + else + { + static assert(0); + } - std.format.doFormat(&putcw, arguments, argptr); - if (newline) - FPUTWC('\n', fp); + std.format.doFormat(&putcw, arguments, argptr); + if (newline) + FPUTWC('\n', fp); } } @@ -279,14 +279,14 @@ void fwritefln(FILE* fp, ...) /********************************** * Read line from stream fp. * Returns: - * null for end of file, - * char[] for line read from fp, including terminating '\n' + * null for end of file, + * char[] for line read from fp, including terminating '\n' * Params: - * fp = input stream + * fp = input stream * Throws: - * $(B StdioException) on error + * $(B StdioException) on error * Example: - * Reads $(B stdin) and writes it to $(B stdout). + * Reads $(B stdin) and writes it to $(B stdout). --- import std.stdio; @@ -294,7 +294,7 @@ int main() { char[] buf; while ((buf = readln()) != null) - writef("%s", buf); + writef("%s", buf); return 0; } --- @@ -314,16 +314,16 @@ string readln(FILE* fp = stdin) * is reused each call. Note that reusing the buffer means that * the previous contents of it need to be copied if needed. * Params: - * fp = input stream - * buf = buffer used to store the resulting line data. buf - * is resized as necessary. + * fp = input stream + * buf = buffer used to store the resulting line data. buf + * is resized as necessary. * Returns: - * 0 for end of file, otherwise - * number of characters read + * 0 for end of file, otherwise + * number of characters read * Throws: - * $(B StdioException) on error + * $(B StdioException) on error * Example: - * Reads $(B stdin) and writes it to $(B stdout). + * Reads $(B stdin) and writes it to $(B stdout). --- import std.stdio; @@ -331,7 +331,7 @@ int main() { char[] buf; while (readln(stdin, buf)) - writef("%s", buf); + writef("%s", buf); return 0; } --- @@ -340,306 +340,306 @@ size_t readln(FILE* fp, inout char[] buf) { version (DIGITAL_MARS_STDIO) { - FLOCK(fp); - scope(exit) FUNLOCK(fp); + FLOCK(fp); + scope(exit) FUNLOCK(fp); - if (__fhnd_info[fp._file] & FHND_WCHAR) - { /* Stream is in wide characters. - * Read them and convert to chars. - */ - static assert(wchar_t.sizeof == 2); - buf.length = 0; - int c2; - for (int c = void; (c = FGETWC(fp)) != -1; ) - { - if ((c & ~0x7F) == 0) - { buf ~= c; - if (c == '\n') - break; - } - else - { - if (c >= 0xD800 && c <= 0xDBFF) - { - if ((c2 = FGETWC(fp)) != -1 || - c2 < 0xDC00 && c2 > 0xDFFF) - { - StdioException("unpaired UTF-16 surrogate"); - } - c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00); - } - std.utf.encode(buf, c); - } - } - if (ferror(fp)) - StdioException(); - return buf.length; - } + if (__fhnd_info[fp._file] & FHND_WCHAR) + { /* Stream is in wide characters. + * Read them and convert to chars. + */ + static assert(wchar_t.sizeof == 2); + buf.length = 0; + int c2; + for (int c = void; (c = FGETWC(fp)) != -1; ) + { + if ((c & ~0x7F) == 0) + { buf ~= c; + if (c == '\n') + break; + } + else + { + if (c >= 0xD800 && c <= 0xDBFF) + { + if ((c2 = FGETWC(fp)) != -1 || + c2 < 0xDC00 && c2 > 0xDFFF) + { + StdioException("unpaired UTF-16 surrogate"); + } + c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00); + } + std.utf.encode(buf, c); + } + } + if (ferror(fp)) + StdioException(); + return buf.length; + } - auto sz = std.gc.capacity(buf.ptr); - //auto sz = buf.length; - buf = buf.ptr[0 .. sz]; - if (fp._flag & _IONBF) - { - /* Use this for unbuffered I/O, when running - * across buffer boundaries, or for any but the common - * cases. - */ - L1: - char *p; + auto sz = std.gc.capacity(buf.ptr); + //auto sz = buf.length; + buf = buf.ptr[0 .. sz]; + if (fp._flag & _IONBF) + { + /* Use this for unbuffered I/O, when running + * across buffer boundaries, or for any but the common + * cases. + */ + L1: + char *p; - if (sz) - { - p = buf.ptr; - } - else - { - sz = 64; - p = cast(char*) std.gc.malloc(sz); - std.gc.hasNoPointers(p); - buf = p[0 .. sz]; - } - size_t i = 0; - for (int c; (c = FGETC(fp)) != -1; ) - { - if ((p[i] = cast(char)c) != '\n') - { - i++; - if (i < sz) - continue; - buf = p[0 .. i] ~ readln(fp); - return buf.length; - } - else - { - buf = p[0 .. i + 1]; - return i + 1; - } - } - if (ferror(fp)) - StdioException(); - buf = p[0 .. i]; - return i; - } - else - { - int u = fp._cnt; - char* p = fp._ptr; - int i; - if (fp._flag & _IOTRAN) - { /* Translated mode ignores \r and treats ^Z as end-of-file - */ - char c; - while (1) - { - if (i == u) // if end of buffer - goto L1; // give up - c = p[i]; - i++; - if (c != '\r') - { - if (c == '\n') - break; - if (c != 0x1A) - continue; - goto L1; - } - else - { if (i != u && p[i] == '\n') - break; - goto L1; - } - } - if (i > sz) - { - buf = cast(char[])std.gc.malloc(i); - std.gc.hasNoPointers(buf.ptr); - } - if (i - 1) - memcpy(buf.ptr, p, i - 1); - buf[i - 1] = '\n'; - if (c == '\r') - i++; - } - else - { - while (1) - { - if (i == u) // if end of buffer - goto L1; // give up - auto c = p[i]; - i++; - if (c == '\n') - break; - } - if (i > sz) - { - buf = cast(char[])std.gc.malloc(i); - std.gc.hasNoPointers(buf.ptr); - } - memcpy(buf.ptr, p, i); - } - fp._cnt -= i; - fp._ptr += i; - buf = buf[0 .. i]; - return i; - } + if (sz) + { + p = buf.ptr; + } + else + { + sz = 64; + p = cast(char*) std.gc.malloc(sz); + std.gc.hasNoPointers(p); + buf = p[0 .. sz]; + } + size_t i = 0; + for (int c; (c = FGETC(fp)) != -1; ) + { + if ((p[i] = cast(char)c) != '\n') + { + i++; + if (i < sz) + continue; + buf = p[0 .. i] ~ readln(fp); + return buf.length; + } + else + { + buf = p[0 .. i + 1]; + return i + 1; + } + } + if (ferror(fp)) + StdioException(); + buf = p[0 .. i]; + return i; + } + else + { + int u = fp._cnt; + char* p = fp._ptr; + int i; + if (fp._flag & _IOTRAN) + { /* Translated mode ignores \r and treats ^Z as end-of-file + */ + char c; + while (1) + { + if (i == u) // if end of buffer + goto L1; // give up + c = p[i]; + i++; + if (c != '\r') + { + if (c == '\n') + break; + if (c != 0x1A) + continue; + goto L1; + } + else + { if (i != u && p[i] == '\n') + break; + goto L1; + } + } + if (i > sz) + { + buf = cast(char[])std.gc.malloc(i); + std.gc.hasNoPointers(buf.ptr); + } + if (i - 1) + memcpy(buf.ptr, p, i - 1); + buf[i - 1] = '\n'; + if (c == '\r') + i++; + } + else + { + while (1) + { + if (i == u) // if end of buffer + goto L1; // give up + auto c = p[i]; + i++; + if (c == '\n') + break; + } + if (i > sz) + { + buf = cast(char[])std.gc.malloc(i); + std.gc.hasNoPointers(buf.ptr); + } + memcpy(buf.ptr, p, i); + } + fp._cnt -= i; + fp._ptr += i; + buf = buf[0 .. i]; + return i; + } } else version (GCC_IO) { - if (fwide(fp, 0) > 0) - { /* Stream is in wide characters. - * Read them and convert to chars. - */ - FLOCK(fp); - scope(exit) FUNLOCK(fp); - version (Windows) - { - buf.length = 0; - int c2; - for (int c = void; (c = FGETWC(fp)) != -1; ) - { - if ((c & ~0x7F) == 0) - { buf ~= c; - if (c == '\n') - break; - } - else - { - if (c >= 0xD800 && c <= 0xDBFF) - { - if ((c2 = FGETWC(fp)) != -1 || - c2 < 0xDC00 && c2 > 0xDFFF) - { - StdioException("unpaired UTF-16 surrogate"); - } - c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00); - } - std.utf.encode(buf, c); - } - } - if (ferror(fp)) - StdioException(); - return buf.length; - } - else version (Posix) - { - buf.length = 0; - for (int c; (c = FGETWC(fp)) != -1; ) - { - if ((c & ~0x7F) == 0) - buf ~= c; - else - std.utf.encode(buf, cast(dchar)c); - if (c == '\n') - break; - } - if (ferror(fp)) - StdioException(); - return buf.length; - } - else - { - static assert(0); - } - } + if (fwide(fp, 0) > 0) + { /* Stream is in wide characters. + * Read them and convert to chars. + */ + FLOCK(fp); + scope(exit) FUNLOCK(fp); + version (Windows) + { + buf.length = 0; + int c2; + for (int c = void; (c = FGETWC(fp)) != -1; ) + { + if ((c & ~0x7F) == 0) + { buf ~= c; + if (c == '\n') + break; + } + else + { + if (c >= 0xD800 && c <= 0xDBFF) + { + if ((c2 = FGETWC(fp)) != -1 || + c2 < 0xDC00 && c2 > 0xDFFF) + { + StdioException("unpaired UTF-16 surrogate"); + } + c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00); + } + std.utf.encode(buf, c); + } + } + if (ferror(fp)) + StdioException(); + return buf.length; + } + else version (Posix) + { + buf.length = 0; + for (int c; (c = FGETWC(fp)) != -1; ) + { + if ((c & ~0x7F) == 0) + buf ~= c; + else + std.utf.encode(buf, cast(dchar)c); + if (c == '\n') + break; + } + if (ferror(fp)) + StdioException(); + return buf.length; + } + else + { + static assert(0); + } + } - char *lineptr = null; - size_t n = 0; - auto s = getdelim(&lineptr, &n, '\n', fp); - scope(exit) free(lineptr); - if (s < 0) - { - if (ferror(fp)) - StdioException(); - buf.length = 0; // end of file - return 0; - } - buf = buf.ptr[0 .. std.gc.capacity(buf.ptr)]; - if (s <= buf.length) - { - buf.length = s; - buf[] = lineptr[0 .. s]; - } - else - { - buf = lineptr[0 .. s].dup; - } - return s; + char *lineptr = null; + size_t n = 0; + auto s = getdelim(&lineptr, &n, '\n', fp); + scope(exit) free(lineptr); + if (s < 0) + { + if (ferror(fp)) + StdioException(); + buf.length = 0; // end of file + return 0; + } + buf = buf.ptr[0 .. std.gc.capacity(buf.ptr)]; + if (s <= buf.length) + { + buf.length = s; + buf[] = lineptr[0 .. s]; + } + else + { + buf = lineptr[0 .. s].dup; + } + return s; } else version (GENERIC_IO) { - FLOCK(fp); - scope(exit) FUNLOCK(fp); - if (fwide(fp, 0) > 0) - { /* Stream is in wide characters. - * Read them and convert to chars. - */ - version (Windows) - { - buf.length = 0; - int c2; - for (int c; (c = FGETWC(fp)) != -1; ) - { - if ((c & ~0x7F) == 0) - { buf ~= c; - if (c == '\n') - break; - } - else - { - if (c >= 0xD800 && c <= 0xDBFF) - { - if ((c2 = FGETWC(fp)) != -1 || - c2 < 0xDC00 && c2 > 0xDFFF) - { - StdioException("unpaired UTF-16 surrogate"); - } - c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00); - } - std.utf.encode(buf, c); - } - } - if (ferror(fp)) - StdioException(); - return buf.length; - } - else version (Posix) - { - buf.length = 0; - for (int c; (c = FGETWC(fp)) != -1; ) - { - if ((c & ~0x7F) == 0) - buf ~= c; - else - std.utf.encode(buf, cast(dchar)c); - if (c == '\n') - break; - } - if (ferror(fp)) - StdioException(); - return buf.length; - } - else - { - static assert(0); - } - } + FLOCK(fp); + scope(exit) FUNLOCK(fp); + if (fwide(fp, 0) > 0) + { /* Stream is in wide characters. + * Read them and convert to chars. + */ + version (Windows) + { + buf.length = 0; + int c2; + for (int c; (c = FGETWC(fp)) != -1; ) + { + if ((c & ~0x7F) == 0) + { buf ~= c; + if (c == '\n') + break; + } + else + { + if (c >= 0xD800 && c <= 0xDBFF) + { + if ((c2 = FGETWC(fp)) != -1 || + c2 < 0xDC00 && c2 > 0xDFFF) + { + StdioException("unpaired UTF-16 surrogate"); + } + c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00); + } + std.utf.encode(buf, c); + } + } + if (ferror(fp)) + StdioException(); + return buf.length; + } + else version (Posix) + { + buf.length = 0; + for (int c; (c = FGETWC(fp)) != -1; ) + { + if ((c & ~0x7F) == 0) + buf ~= c; + else + std.utf.encode(buf, cast(dchar)c); + if (c == '\n') + break; + } + if (ferror(fp)) + StdioException(); + return buf.length; + } + else + { + static assert(0); + } + } - buf.length = 0; - for (int c; (c = FGETC(fp)) != -1; ) - { - buf ~= c; - if (c == '\n') - break; - } - if (ferror(fp)) - StdioException(); - return buf.length; + buf.length = 0; + for (int c; (c = FGETC(fp)) != -1; ) + { + buf ~= c; + if (c == '\n') + break; + } + if (ferror(fp)) + StdioException(); + return buf.length; } else { - static assert(0); + static assert(0); } } diff --git a/std/stream.d b/std/stream.d index c199f9b25..e0994f29e 100644 --- a/std/stream.d +++ b/std/stream.d @@ -2,7 +2,7 @@ /** * Macros: - * WIKI = Phobos/StdStream + * WIKI = Phobos/StdStream */ /* @@ -95,7 +95,7 @@ interface InputStream { /*** * Read a block of data big enough to fill the given array buffer. * - * Returns: the actual number of bytes read. Unfilled bytes are not modified. + * Returns: the actual number of bytes read. Unfilled bytes are not modified. */ size_t read(ubyte[] buffer); @@ -108,31 +108,31 @@ interface InputStream { * to write. */ void read(out byte x); - void read(out ubyte x); /// ditto - void read(out short x); /// ditto - void read(out ushort x); /// ditto - void read(out int x); /// ditto - void read(out uint x); /// ditto - void read(out long x); /// ditto - void read(out ulong x); /// ditto - void read(out float x); /// ditto - void read(out double x); /// ditto - void read(out real x); /// ditto - void read(out ifloat x); /// ditto - void read(out idouble x); /// ditto - void read(out ireal x); /// ditto - void read(out cfloat x); /// ditto - void read(out cdouble x); /// ditto - void read(out creal x); /// ditto - void read(out char x); /// ditto - void read(out wchar x); /// ditto - void read(out dchar x); /// ditto + void read(out ubyte x); /// ditto + void read(out short x); /// ditto + void read(out ushort x); /// ditto + void read(out int x); /// ditto + void read(out uint x); /// ditto + void read(out long x); /// ditto + void read(out ulong x); /// ditto + void read(out float x); /// ditto + void read(out double x); /// ditto + void read(out real x); /// ditto + void read(out ifloat x); /// ditto + void read(out idouble x); /// ditto + void read(out ireal x); /// ditto + void read(out cfloat x); /// ditto + void read(out cdouble x); /// ditto + void read(out creal x); /// ditto + void read(out char x); /// ditto + void read(out wchar x); /// ditto + void read(out dchar x); /// ditto // reads a string, written earlier by write() - void read(out char[] s); /// ditto + void read(out char[] s); /// ditto // reads a Unicode string, written earlier by write() - void read(out wchar[] s); /// ditto + void read(out wchar[] s); /// ditto /*** * Read a line that is terminated with some combination of carriage return and @@ -140,12 +140,12 @@ interface InputStream { * * The terminators are not included. The wchar version * is identical. The optional buffer parameter is filled (reallocating - * it if necessary) and a slice of the result is returned. + * it if necessary) and a slice of the result is returned. */ char[] readLine(); - char[] readLine(char[] result); /// ditto - wchar[] readLineW(); /// ditto - wchar[] readLineW(wchar[] result); /// ditto + char[] readLine(char[] result); /// ditto + wchar[] readLineW(); /// ditto + wchar[] readLineW(wchar[] result); /// ditto /*** * Overload foreach statements to read the stream line by line and call the @@ -168,7 +168,7 @@ interface InputStream { // iterate through the stream line-by-line int opApply(int delegate(inout char[] line) dg); int opApply(int delegate(inout ulong n, inout char[] line) dg); /// ditto - int opApply(int delegate(inout wchar[] line) dg); /// ditto + int opApply(int delegate(inout wchar[] line) dg); /// ditto int opApply(int delegate(inout ulong n, inout wchar[] line) dg); /// ditto /// Read a string of the given length, @@ -243,7 +243,7 @@ interface InputStream { bool eof(); - bool isOpen(); /// Return true if the stream is currently open. + bool isOpen(); /// Return true if the stream is currently open. } /// Interface for writable streams. @@ -269,25 +269,25 @@ interface OutputStream { * Throw WriteException on error. */ void write(byte x); - void write(ubyte x); /// ditto - void write(short x); /// ditto - void write(ushort x); /// ditto - void write(int x); /// ditto - void write(uint x); /// ditto - void write(long x); /// ditto - void write(ulong x); /// ditto - void write(float x); /// ditto - void write(double x); /// ditto - void write(real x); /// ditto - void write(ifloat x); /// ditto - void write(idouble x); /// ditto - void write(ireal x); /// ditto - void write(cfloat x); /// ditto - void write(cdouble x); /// ditto - void write(creal x); /// ditto - void write(char x); /// ditto - void write(wchar x); /// ditto - void write(dchar x); /// ditto + void write(ubyte x); /// ditto + void write(short x); /// ditto + void write(ushort x); /// ditto + void write(int x); /// ditto + void write(uint x); /// ditto + void write(long x); /// ditto + void write(ulong x); /// ditto + void write(float x); /// ditto + void write(double x); /// ditto + void write(real x); /// ditto + void write(ifloat x); /// ditto + void write(idouble x); /// ditto + void write(ireal x); /// ditto + void write(cfloat x); /// ditto + void write(cdouble x); /// ditto + void write(creal x); /// ditto + void write(char x); /// ditto + void write(wchar x); /// ditto + void write(dchar x); /// ditto /*** * Writes a string, together with its length. @@ -297,7 +297,7 @@ interface OutputStream { * Throw WriteException on error. */ void write(char[] s); - void write(wchar[] s); /// ditto + void write(wchar[] s); /// ditto /*** * Write a line of text, @@ -336,7 +336,7 @@ interface OutputStream { * returning the number of bytes written. */ size_t vprintf(char[] format, va_list args); - size_t printf(char[] format, ...); /// ditto + size_t printf(char[] format, ...); /// ditto /*** * Print a formatted string into the stream using writef-style syntax. @@ -347,7 +347,7 @@ interface OutputStream { OutputStream writefln(...); /// ditto OutputStream writefx(TypeInfo[] arguments, void* argptr, int newline = false); /// ditto - void flush(); /// Flush pending output if appropriate. + void flush(); /// Flush pending output if appropriate. void close(); /// Close the stream, flushing output if appropriate. bool isOpen(); /// Return true if the stream is currently open. } @@ -355,7 +355,7 @@ interface OutputStream { /*** * Stream is the base abstract class from which the other stream classes derive. - * + * * Stream's byte order is the format native to the computer. * * Reading: @@ -383,19 +383,19 @@ class Stream : InputStream, OutputStream { private import std.string, crc32, std.c.stdlib, std.c.stdio; // stream abilities - bool readable = false; /// Indicates whether this stream can be read from. - bool writeable = false; /// Indicates whether this stream can be written to. - bool seekable = false; /// Indicates whether this stream can be seeked within. - protected bool isopen = true; /// Indicates whether this stream is open. + bool readable = false; /// Indicates whether this stream can be read from. + bool writeable = false; /// Indicates whether this stream can be written to. + bool seekable = false; /// Indicates whether this stream can be seeked within. + protected bool isopen = true; /// Indicates whether this stream is open. protected bool readEOF = false; /** Indicates whether this stream is at eof - * after the last read attempt. - */ + * after the last read attempt. + */ protected bool prevCr = false; /** For a non-seekable stream indicates that - * the last readLine or readLineW ended on a - * '\r' character. - */ + * the last readLine or readLineW ended on a + * '\r' character. + */ this() {} @@ -476,25 +476,25 @@ class Stream : InputStream, OutputStream { while (readable) { switch (ch) { case '\r': - if (seekable) { - ch = getc(); - if (ch != '\n') - ungetc(ch); - } else { - prevCr = true; - } + if (seekable) { + ch = getc(); + if (ch != '\n') + ungetc(ch); + } else { + prevCr = true; + } case '\n': case char.init: - result.length = strlen; - return result; + result.length = strlen; + return result; default: - if (strlen < result.length) { - result[strlen] = ch; - } else { - result ~= ch; - } - strlen++; + if (strlen < result.length) { + result[strlen] = ch; + } else { + result ~= ch; + } + strlen++; } ch = getc(); } @@ -518,25 +518,25 @@ class Stream : InputStream, OutputStream { while (readable) { switch (c) { case '\r': - if (seekable) { - c = getcw(); - if (c != '\n') - ungetcw(c); - } else { - prevCr = true; - } + if (seekable) { + c = getcw(); + if (c != '\n') + ungetcw(c); + } else { + prevCr = true; + } case '\n': case wchar.init: - result.length = strlen; - return result; + result.length = strlen; + return result; default: - if (strlen < result.length) { - result[strlen] = c; - } else { - result ~= c; - } - strlen++; + if (strlen < result.length) { + result[strlen] = c; + } else { + result ~= c; + } + strlen++; } c = getcw(); } @@ -624,8 +624,8 @@ class Stream : InputStream, OutputStream { if (prevCr) { prevCr = false; c = getc(); - if (c != '\n') - return c; + if (c != '\n') + return c; } if (unget.length > 1) { c = cast(char)unget[unget.length - 1]; @@ -644,8 +644,8 @@ class Stream : InputStream, OutputStream { if (prevCr) { prevCr = false; c = getcw(); - if (c != '\n') - return c; + if (c != '\n') + return c; } if (unget.length > 1) { c = unget[unget.length - 1]; @@ -688,329 +688,329 @@ class Stream : InputStream, OutputStream { char c = getc(); while ((j < arguments.length || i < fmt.length) && !eof()) { if (fmt.length == 0 || i == fmt.length) { - i = 0; - if (arguments[j] is typeid(char[])) { - fmt = va_arg!(string)(args); - j++; - continue; - } else if (arguments[j] is typeid(int*) || - arguments[j] is typeid(byte*) || - arguments[j] is typeid(short*) || - arguments[j] is typeid(long*)) { - fmt = "%d"; - } else if (arguments[j] is typeid(uint*) || - arguments[j] is typeid(ubyte*) || - arguments[j] is typeid(ushort*) || - arguments[j] is typeid(ulong*)) { - fmt = "%d"; - } else if (arguments[j] is typeid(float*) || - arguments[j] is typeid(double*) || - arguments[j] is typeid(real*)) { - fmt = "%f"; - } else if (arguments[j] is typeid(char[]*) || - arguments[j] is typeid(wchar[]*) || - arguments[j] is typeid(dchar[]*)) { - fmt = "%s"; - } else if (arguments[j] is typeid(char*)) { - fmt = "%c"; - } + i = 0; + if (arguments[j] is typeid(char[])) { + fmt = va_arg!(string)(args); + j++; + continue; + } else if (arguments[j] is typeid(int*) || + arguments[j] is typeid(byte*) || + arguments[j] is typeid(short*) || + arguments[j] is typeid(long*)) { + fmt = "%d"; + } else if (arguments[j] is typeid(uint*) || + arguments[j] is typeid(ubyte*) || + arguments[j] is typeid(ushort*) || + arguments[j] is typeid(ulong*)) { + fmt = "%d"; + } else if (arguments[j] is typeid(float*) || + arguments[j] is typeid(double*) || + arguments[j] is typeid(real*)) { + fmt = "%f"; + } else if (arguments[j] is typeid(char[]*) || + arguments[j] is typeid(wchar[]*) || + arguments[j] is typeid(dchar[]*)) { + fmt = "%s"; + } else if (arguments[j] is typeid(char*)) { + fmt = "%c"; + } } - if (fmt[i] == '%') { // a field - i++; - bool suppress = false; - if (fmt[i] == '*') { // suppress assignment - suppress = true; - i++; - } - // read field width - int width = 0; - while (isdigit(fmt[i])) { - width = width * 10 + (fmt[i] - '0'); - i++; - } - if (width == 0) - width = -1; - // skip any modifier if present - if (fmt[i] == 'h' || fmt[i] == 'l' || fmt[i] == 'L') - i++; - // check the typechar and act accordingly - switch (fmt[i]) { - case 'd': // decimal/hexadecimal/octal integer - case 'D': - case 'u': - case 'U': - case 'o': - case 'O': - case 'x': - case 'X': - case 'i': - case 'I': - { - while (iswhite(c)) { - c = getc(); - count++; - } - bool neg = false; - if (c == '-') { - neg = true; - c = getc(); - count++; - } else if (c == '+') { - c = getc(); - count++; - } - char ifmt = cast(char)(fmt[i] | 0x20); - if (ifmt == 'i') { // undetermined base - if (c == '0') { // octal or hex - c = getc(); - count++; - if (c == 'x' || c == 'X') { // hex - ifmt = 'x'; - c = getc(); - count++; - } else { // octal - ifmt = 'o'; - } - } - else // decimal - ifmt = 'd'; - } - long n = 0; - switch (ifmt) - { - case 'd': // decimal - case 'u': { - while (isdigit(c) && width) { - n = n * 10 + (c - '0'); - width--; - c = getc(); - count++; - } - } break; + if (fmt[i] == '%') { // a field + i++; + bool suppress = false; + if (fmt[i] == '*') { // suppress assignment + suppress = true; + i++; + } + // read field width + int width = 0; + while (isdigit(fmt[i])) { + width = width * 10 + (fmt[i] - '0'); + i++; + } + if (width == 0) + width = -1; + // skip any modifier if present + if (fmt[i] == 'h' || fmt[i] == 'l' || fmt[i] == 'L') + i++; + // check the typechar and act accordingly + switch (fmt[i]) { + case 'd': // decimal/hexadecimal/octal integer + case 'D': + case 'u': + case 'U': + case 'o': + case 'O': + case 'x': + case 'X': + case 'i': + case 'I': + { + while (iswhite(c)) { + c = getc(); + count++; + } + bool neg = false; + if (c == '-') { + neg = true; + c = getc(); + count++; + } else if (c == '+') { + c = getc(); + count++; + } + char ifmt = cast(char)(fmt[i] | 0x20); + if (ifmt == 'i') { // undetermined base + if (c == '0') { // octal or hex + c = getc(); + count++; + if (c == 'x' || c == 'X') { // hex + ifmt = 'x'; + c = getc(); + count++; + } else { // octal + ifmt = 'o'; + } + } + else // decimal + ifmt = 'd'; + } + long n = 0; + switch (ifmt) + { + case 'd': // decimal + case 'u': { + while (isdigit(c) && width) { + n = n * 10 + (c - '0'); + width--; + c = getc(); + count++; + } + } break; - case 'o': { // octal - while (isoctdigit(c) && width) { - n = n * 010 + (c - '0'); - width--; - c = getc(); - count++; - } - } break; + case 'o': { // octal + while (isoctdigit(c) && width) { + n = n * 010 + (c - '0'); + width--; + c = getc(); + count++; + } + } break; - case 'x': { // hexadecimal - while (ishexdigit(c) && width) { - n *= 0x10; - if (isdigit(c)) - n += c - '0'; - else - n += 0xA + (c | 0x20) - 'a'; - width--; - c = getc(); - count++; - } - } break; + case 'x': { // hexadecimal + while (ishexdigit(c) && width) { + n *= 0x10; + if (isdigit(c)) + n += c - '0'; + else + n += 0xA + (c | 0x20) - 'a'; + width--; + c = getc(); + count++; + } + } break; - default: - assert(0); - } - if (neg) - n = -n; - if (arguments[j] is typeid(int*)) { - int* p = va_arg!(int*)(args); - *p = cast(int)n; - } else if (arguments[j] is typeid(short*)) { - short* p = va_arg!(short*)(args); - *p = cast(short)n; - } else if (arguments[j] is typeid(byte*)) { - byte* p = va_arg!(byte*)(args); - *p = cast(byte)n; - } else if (arguments[j] is typeid(long*)) { - long* p = va_arg!(long*)(args); - *p = n; - } else if (arguments[j] is typeid(uint*)) { - uint* p = va_arg!(uint*)(args); - *p = cast(uint)n; - } else if (arguments[j] is typeid(ushort*)) { - ushort* p = va_arg!(ushort*)(args); - *p = cast(ushort)n; - } else if (arguments[j] is typeid(ubyte*)) { - ubyte* p = va_arg!(ubyte*)(args); - *p = cast(ubyte)n; - } else if (arguments[j] is typeid(ulong*)) { - ulong* p = va_arg!(ulong*)(args); - *p = cast(ulong)n; - } - j++; - i++; - } break; + default: + assert(0); + } + if (neg) + n = -n; + if (arguments[j] is typeid(int*)) { + int* p = va_arg!(int*)(args); + *p = cast(int)n; + } else if (arguments[j] is typeid(short*)) { + short* p = va_arg!(short*)(args); + *p = cast(short)n; + } else if (arguments[j] is typeid(byte*)) { + byte* p = va_arg!(byte*)(args); + *p = cast(byte)n; + } else if (arguments[j] is typeid(long*)) { + long* p = va_arg!(long*)(args); + *p = n; + } else if (arguments[j] is typeid(uint*)) { + uint* p = va_arg!(uint*)(args); + *p = cast(uint)n; + } else if (arguments[j] is typeid(ushort*)) { + ushort* p = va_arg!(ushort*)(args); + *p = cast(ushort)n; + } else if (arguments[j] is typeid(ubyte*)) { + ubyte* p = va_arg!(ubyte*)(args); + *p = cast(ubyte)n; + } else if (arguments[j] is typeid(ulong*)) { + ulong* p = va_arg!(ulong*)(args); + *p = cast(ulong)n; + } + j++; + i++; + } break; - case 'f': // float - case 'F': - case 'e': - case 'E': - case 'g': - case 'G': - { - while (iswhite(c)) { - c = getc(); - count++; - } - bool neg = false; - if (c == '-') { - neg = true; - c = getc(); - count++; - } else if (c == '+') { - c = getc(); - count++; - } - real n = 0; - while (isdigit(c) && width) { - n = n * 10 + (c - '0'); - width--; - c = getc(); - count++; - } - if (width && c == '.') { - width--; - c = getc(); - count++; - double frac = 1; - while (isdigit(c) && width) { - n = n * 10 + (c - '0'); - frac *= 10; - width--; - c = getc(); - count++; - } - n /= frac; - } - if (width && (c == 'e' || c == 'E')) { - width--; - c = getc(); - count++; - if (width) { - bool expneg = false; - if (c == '-') { - expneg = true; - width--; - c = getc(); - count++; - } else if (c == '+') { - width--; - c = getc(); - count++; - } - real exp = 0; - while (isdigit(c) && width) { - exp = exp * 10 + (c - '0'); - width--; - c = getc(); - count++; - } - if (expneg) { - while (exp--) - n /= 10; - } else { - while (exp--) - n *= 10; - } - } - } - if (neg) - n = -n; - if (arguments[j] is typeid(float*)) { - float* p = va_arg!(float*)(args); - *p = n; - } else if (arguments[j] is typeid(double*)) { - double* p = va_arg!(double*)(args); - *p = n; - } else if (arguments[j] is typeid(real*)) { - real* p = va_arg!(real*)(args); - *p = n; - } - j++; - i++; - } break; + case 'f': // float + case 'F': + case 'e': + case 'E': + case 'g': + case 'G': + { + while (iswhite(c)) { + c = getc(); + count++; + } + bool neg = false; + if (c == '-') { + neg = true; + c = getc(); + count++; + } else if (c == '+') { + c = getc(); + count++; + } + real n = 0; + while (isdigit(c) && width) { + n = n * 10 + (c - '0'); + width--; + c = getc(); + count++; + } + if (width && c == '.') { + width--; + c = getc(); + count++; + double frac = 1; + while (isdigit(c) && width) { + n = n * 10 + (c - '0'); + frac *= 10; + width--; + c = getc(); + count++; + } + n /= frac; + } + if (width && (c == 'e' || c == 'E')) { + width--; + c = getc(); + count++; + if (width) { + bool expneg = false; + if (c == '-') { + expneg = true; + width--; + c = getc(); + count++; + } else if (c == '+') { + width--; + c = getc(); + count++; + } + real exp = 0; + while (isdigit(c) && width) { + exp = exp * 10 + (c - '0'); + width--; + c = getc(); + count++; + } + if (expneg) { + while (exp--) + n /= 10; + } else { + while (exp--) + n *= 10; + } + } + } + if (neg) + n = -n; + if (arguments[j] is typeid(float*)) { + float* p = va_arg!(float*)(args); + *p = n; + } else if (arguments[j] is typeid(double*)) { + double* p = va_arg!(double*)(args); + *p = n; + } else if (arguments[j] is typeid(real*)) { + real* p = va_arg!(real*)(args); + *p = n; + } + j++; + i++; + } break; - case 's': { // string - while (iswhite(c)) { - c = getc(); - count++; - } - char[] s; - char[]* p; - size_t strlen; - if (arguments[j] is typeid(char[]*)) { - p = va_arg!(char[]*)(args); - s = *p; - } - while (!iswhite(c) && c != char.init) { - if (strlen < s.length) { - s[strlen] = c; - } else { - s ~= c; - } - strlen++; - c = getc(); - count++; - } - s = s[0 .. strlen]; - if (arguments[j] is typeid(char[]*)) { - *p = s; - } else if (arguments[j] is typeid(char*)) { - s ~= 0; - auto q = va_arg!(char*)(args); - q[0 .. s.length] = s[]; - } else if (arguments[j] is typeid(wchar[]*)) { - auto q = va_arg!(wchar[]*)(args); - *q = toUTF16(s); - } else if (arguments[j] is typeid(dchar[]*)) { - auto q = va_arg!(dchar[]*)(args); - *q = toUTF32(s); - } - j++; - i++; - } break; + case 's': { // string + while (iswhite(c)) { + c = getc(); + count++; + } + char[] s; + char[]* p; + size_t strlen; + if (arguments[j] is typeid(char[]*)) { + p = va_arg!(char[]*)(args); + s = *p; + } + while (!iswhite(c) && c != char.init) { + if (strlen < s.length) { + s[strlen] = c; + } else { + s ~= c; + } + strlen++; + c = getc(); + count++; + } + s = s[0 .. strlen]; + if (arguments[j] is typeid(char[]*)) { + *p = s; + } else if (arguments[j] is typeid(char*)) { + s ~= 0; + auto q = va_arg!(char*)(args); + q[0 .. s.length] = s[]; + } else if (arguments[j] is typeid(wchar[]*)) { + auto q = va_arg!(wchar[]*)(args); + *q = toUTF16(s); + } else if (arguments[j] is typeid(dchar[]*)) { + auto q = va_arg!(dchar[]*)(args); + *q = toUTF32(s); + } + j++; + i++; + } break; - case 'c': { // character(s) - char* s = va_arg!(char*)(args); - if (width < 0) - width = 1; - else - while (iswhite(c)) { - c = getc(); - count++; - } - while (width-- && !eof()) { - *(s++) = c; - c = getc(); - count++; - } - j++; - i++; - } break; + case 'c': { // character(s) + char* s = va_arg!(char*)(args); + if (width < 0) + width = 1; + else + while (iswhite(c)) { + c = getc(); + count++; + } + while (width-- && !eof()) { + *(s++) = c; + c = getc(); + count++; + } + j++; + i++; + } break; - case 'n': { // number of chars read so far - int* p = va_arg!(int*)(args); - *p = count; - j++; - i++; - } break; + case 'n': { // number of chars read so far + int* p = va_arg!(int*)(args); + *p = count; + j++; + i++; + } break; - default: // read character as is - goto nws; - } - } else if (iswhite(fmt[i])) { // skip whitespace - while (iswhite(c)) - c = getc(); - i++; - } else { // read character as is + default: // read character as is + goto nws; + } + } else if (iswhite(fmt[i])) { // skip whitespace + while (iswhite(c)) + c = getc(); + i++; + } else { // read character as is nws: - if (fmt[i] != c) - break; - c = getc(); - i++; + if (fmt[i] != c) + break; + c = getc(); + i++; } } ungetc(c); @@ -1129,22 +1129,22 @@ class Stream : InputStream, OutputStream { size_t count; while (true) { version (Win32) { - count = _vsnprintf(p, psize, f, args); - if (count != -1) - break; - psize *= 2; - p = cast(char*) alloca(psize); + count = _vsnprintf(p, psize, f, args); + if (count != -1) + break; + psize *= 2; + p = cast(char*) alloca(psize); } else version (Posix) { - count = vsnprintf(p, psize, f, args); - if (count == -1) - psize *= 2; - else if (count >= psize) - psize = count + 1; - else - break; - p = cast(char*) alloca(psize); + count = vsnprintf(p, psize, f, args); + if (count == -1) + psize *= 2; + else if (count >= psize) + psize = count + 1; + else + break; + p = cast(char*) alloca(psize); } else - throw new Exception("unsupported platform"); + throw new Exception("unsupported platform"); } writeString(p[0 .. count]); return count; @@ -1178,7 +1178,7 @@ class Stream : InputStream, OutputStream { // writes data with optional trailing newline OutputStream writefx(TypeInfo[] arguments, void* argptr, int newline=false) { doFormat(&doFormatCallback,arguments,argptr); - if (newline) + if (newline) writeLine(""); return this; } @@ -1197,8 +1197,8 @@ class Stream : InputStream, OutputStream { } else { ubyte[128] buf; while (!s.eof()) { - size_t m = s.readBlock(buf.ptr, buf.length); - writeExact(buf.ptr, m); + size_t m = s.readBlock(buf.ptr, buf.length); + writeExact(buf.ptr, m); } } } @@ -1232,8 +1232,8 @@ class Stream : InputStream, OutputStream { * Aliases for their normal seek counterparts. */ ulong seekSet(long offset) { return seek (offset, SeekPos.Set); } - ulong seekCur(long offset) { return seek (offset, SeekPos.Current); } /// ditto - ulong seekEnd(long offset) { return seek (offset, SeekPos.End); } /// ditto + ulong seekCur(long offset) { return seek (offset, SeekPos.Current); } /// ditto + ulong seekEnd(long offset) { return seek (offset, SeekPos.End); } /// ditto /*** * Sets file position. Equivalent to calling seek(pos, SeekPos.Set). @@ -1257,12 +1257,12 @@ class Stream : InputStream, OutputStream { } // returns true if end of stream is reached, false otherwise - bool eof() { + bool eof() { // for unseekable streams we only know the end when we read it if (readEOF && !ungetAvailable()) return true; else if (seekable) - return position() == size(); + return position() == size(); else return false; } @@ -1301,18 +1301,18 @@ class Stream : InputStream, OutputStream { blockSize = cast(size_t)size(); result = new char[blockSize]; while (blockSize > 0) { - rdlen = readBlock(&result[pos], blockSize); - pos += rdlen; - blockSize -= rdlen; + rdlen = readBlock(&result[pos], blockSize); + pos += rdlen; + blockSize -= rdlen; } position(orig_pos); } else { blockSize = 4096; result = new char[blockSize]; while ((rdlen = readBlock(&result[pos], blockSize)) > 0) { - pos += rdlen; - blockSize += rdlen; - result.length = result.length + blockSize; + pos += rdlen; + blockSize += rdlen; + result.length = result.length + blockSize; } } return result[0 .. pos]; @@ -1394,7 +1394,7 @@ class FilterStream : Stream { * * Setting the source stream closes this stream before attaching the new * source. Attaching an open stream reopens this stream and resets the stream - * state. + * state. */ void source(Stream s) { close(); @@ -1432,11 +1432,11 @@ class FilterStream : Stream { } // close stream - override void close() { + override void close() { if (isopen) { super.close(); if (nestClose) - s.close(); + s.close(); } } @@ -1562,16 +1562,16 @@ class BufferedStream : FilterStream { if (bufferLen == 0) { // buffer is empty so fill it if possible if ((len < buffer.length) && (readable)) { - // read in data if the buffer is currently empty - bufferLen = s.readBlock(buffer.ptr, buffer.length); - bufferSourcePos = bufferLen; - streamPos += bufferLen; - + // read in data if the buffer is currently empty + bufferLen = s.readBlock(buffer.ptr, buffer.length); + bufferSourcePos = bufferLen; + streamPos += bufferLen; + } else if (len >= buffer.length) { - // buffer can't hold the data so write it directly and exit - writesize = s.writeBlock(buf,len); - streamPos += writesize; - goto ExitWrite; + // buffer can't hold the data so write it directly and exit + writesize = s.writeBlock(buf,len); + streamPos += writesize; + goto ExitWrite; } } @@ -1586,7 +1586,7 @@ class BufferedStream : FilterStream { } writesize = buffer.length - bufferCurPos; - if (writesize > 0) { + if (writesize > 0) { // buffer can take some data buffer[bufferCurPos .. buffer.length] = buf[0 .. writesize]; bufferCurPos = bufferLen = buffer.length; @@ -1610,8 +1610,8 @@ class BufferedStream : FilterStream { assertSeekable(); if ((whence != SeekPos.Current) || - (offset + bufferCurPos < 0) || - (offset + bufferCurPos >= bufferLen)) { + (offset + bufferCurPos < 0) || + (offset + bufferCurPos >= bufferLen)) { flush(); streamPos = s.seek(offset,whence); } else { @@ -1628,49 +1628,49 @@ class BufferedStream : FilterStream { template TreadLine(T) { T[] readLine(T[] inBuffer) { - size_t lineSize = 0; - bool haveCR = false; - T c = '\0'; - size_t idx = 0; - ubyte* pc = cast(ubyte*)&c; + size_t lineSize = 0; + bool haveCR = false; + T c = '\0'; + size_t idx = 0; + ubyte* pc = cast(ubyte*)&c; L0: - for(;;) { - uint start = bufferCurPos; - L1: - foreach(ubyte b; buffer[start .. bufferLen]) { - bufferCurPos++; - pc[idx] = b; - if(idx < T.sizeof - 1) { - idx++; - continue L1; - } else { - idx = 0; - } - if(c == '\n' || haveCR) { - if(haveCR && c != '\n') bufferCurPos--; - break L0; - } else { - if(c == '\r') { - haveCR = true; - } else { - if(lineSize < inBuffer.length) { - inBuffer[lineSize] = c; - } else { - inBuffer ~= c; - } - lineSize++; - } - } - } - flush(); - size_t res = super.readBlock(buffer.ptr, buffer.length); - if(!res) break L0; // EOF - bufferSourcePos = bufferLen = res; - streamPos += res; - } + for(;;) { + uint start = bufferCurPos; + L1: + foreach(ubyte b; buffer[start .. bufferLen]) { + bufferCurPos++; + pc[idx] = b; + if(idx < T.sizeof - 1) { + idx++; + continue L1; + } else { + idx = 0; + } + if(c == '\n' || haveCR) { + if(haveCR && c != '\n') bufferCurPos--; + break L0; + } else { + if(c == '\r') { + haveCR = true; + } else { + if(lineSize < inBuffer.length) { + inBuffer[lineSize] = c; + } else { + inBuffer ~= c; + } + lineSize++; + } + } + } + flush(); + size_t res = super.readBlock(buffer.ptr, buffer.length); + if(!res) break L0; // EOF + bufferSourcePos = bufferLen = res; + streamPos += res; + } - return inBuffer[0 .. lineSize]; + return inBuffer[0 .. lineSize]; } } // template TreadLine(T) @@ -1699,13 +1699,13 @@ class BufferedStream : FilterStream { body { if (writeable && bufferDirty) { if (bufferSourcePos != 0 && seekable) { - // move actual file pointer to front of buffer - streamPos = s.seek(-bufferSourcePos, SeekPos.Current); + // move actual file pointer to front of buffer + streamPos = s.seek(-bufferSourcePos, SeekPos.Current); } // write buffer out bufferSourcePos = s.writeBlock(buffer.ptr, bufferLen); if (bufferSourcePos != bufferLen) { - throw new WriteException("Unable to write to stream"); + throw new WriteException("Unable to write to stream"); } } super.flush(); @@ -1848,11 +1848,11 @@ class File: Stream { writeable = cast(bool)(mode & FileMode.Out); version (Win32) { if (std.file.useWfuncs) { - hFile = CreateFileW(std.utf.toUTF16z(filename), access, share, - null, createMode, 0, null); + hFile = CreateFileW(std.utf.toUTF16z(filename), access, share, + null, createMode, 0, null); } else { - hFile = CreateFileA(std.file.toMBSz(filename), access, share, - null, createMode, 0, null); + hFile = CreateFileA(std.file.toMBSz(filename), access, share, + null, createMode, 0, null); } isopen = hFile != INVALID_HANDLE_VALUE; } @@ -1867,37 +1867,37 @@ class File: Stream { } private void parseMode(int mode, - out int access, - out int share, - out int createMode) { + out int access, + out int share, + out int createMode) { version (Win32) { share |= FILE_SHARE_READ | FILE_SHARE_WRITE; if (mode & FileMode.In) { - access |= GENERIC_READ; - createMode = OPEN_EXISTING; + access |= GENERIC_READ; + createMode = OPEN_EXISTING; } if (mode & FileMode.Out) { - access |= GENERIC_WRITE; - createMode = OPEN_ALWAYS; // will create if not present + access |= GENERIC_WRITE; + createMode = OPEN_ALWAYS; // will create if not present } if ((mode & FileMode.OutNew) == FileMode.OutNew) { - createMode = CREATE_ALWAYS; // resets file + createMode = CREATE_ALWAYS; // resets file } } version (Posix) { share = 0666; if (mode & FileMode.In) { - access = O_RDONLY; + access = O_RDONLY; } if (mode & FileMode.Out) { - createMode = O_CREAT; // will create if not present - access = O_WRONLY; + createMode = O_CREAT; // will create if not present + access = O_WRONLY; } if (access == (O_WRONLY | O_RDONLY)) { - access = O_RDWR; + access = O_RDWR; } if ((mode & FileMode.OutNew) == FileMode.OutNew) { - access |= O_TRUNC; // resets file + access |= O_TRUNC; // resets file } } } @@ -1915,16 +1915,16 @@ class File: Stream { /// Close the current file if it is open; otherwise it does nothing. override void close() { - if (isopen) { + if (isopen) { super.close(); if (hFile) { - version (Win32) { - CloseHandle(hFile); - hFile = null; - } else version (Posix) { - std.c.posix.posix.close(hFile); - hFile = -1; - } + version (Win32) { + CloseHandle(hFile); + hFile = null; + } else version (Posix) { + std.c.posix.posix.close(hFile); + hFile = -1; + } } } } @@ -1949,7 +1949,7 @@ class File: Stream { } else version (Posix) { size = std.c.posix.posix.read(hFile, buffer, size); if (size == -1) - size = 0; + size = 0; } readEOF = (size == 0); return size; @@ -1962,7 +1962,7 @@ class File: Stream { } else version (Posix) { size = std.c.posix.posix.write(hFile, buffer, size); if (size == -1) - size = 0; + size = 0; } return size; } @@ -1973,12 +1973,12 @@ class File: Stream { int hi = cast(int)(offset>>32); uint low = SetFilePointer(hFile, cast(int)offset, &hi, rel); if ((low == INVALID_SET_FILE_POINTER) && (GetLastError() != 0)) - throw new SeekException("unable to move file pointer"); + throw new SeekException("unable to move file pointer"); ulong result = (cast(ulong)hi << 32) + low; } else version (Posix) { ulong result = lseek(hFile, cast(int)offset, rel); if (result == 0xFFFFFFFF) - throw new SeekException("unable to move file pointer"); + throw new SeekException("unable to move file pointer"); } readEOF = false; return result; @@ -2170,23 +2170,23 @@ class BufferedFile: BufferedStream { } -/// UTF byte-order-mark signatures +/// UTF byte-order-mark signatures enum BOM { - UTF8, /// UTF-8 - UTF16LE, /// UTF-16 Little Endian - UTF16BE, /// UTF-16 Big Endian - UTF32LE, /// UTF-32 Little Endian - UTF32BE, /// UTF-32 Big Endian + UTF8, /// UTF-8 + UTF16LE, /// UTF-16 Little Endian + UTF16BE, /// UTF-16 Big Endian + UTF32LE, /// UTF-32 Little Endian + UTF32BE, /// UTF-32 Big Endian } private const int NBOMS = 5; -Endian[NBOMS] BOMEndian = -[ std.system.endian, +Endian[NBOMS] BOMEndian = +[ std.system.endian, Endian.LittleEndian, Endian.BigEndian, Endian.LittleEndian, Endian.BigEndian ]; -ubyte[][NBOMS] ByteOrderMarks = +ubyte[][NBOMS] ByteOrderMarks = [ [0xEF, 0xBB, 0xBF], [0xFF, 0xFE], [0xFE, 0xFF], @@ -2240,16 +2240,16 @@ class EndianStream : FilterStream { int j; ubyte[] bom = ByteOrderMarks[i]; for (j=0; j < bom.length; ++j) { - if (n <= j) { // have to read more - if (eof()) - break; - readExact(&BOM_buffer[n++],1); - } - if (BOM_buffer[j] != bom[j]) - break; + if (n <= j) { // have to read more + if (eof()) + break; + readExact(&BOM_buffer[n++],1); + } + if (BOM_buffer[j] != bom[j]) + break; } if (j == bom.length) // found a match - result = i; + result = i; } int m = 0; if (result != -1) { @@ -2258,15 +2258,15 @@ class EndianStream : FilterStream { } if ((ungetCharSize == 1 && result == -1) || (result == BOM.UTF8)) { while (n-- > m) - ungetc(BOM_buffer[n]); + ungetc(BOM_buffer[n]); } else { // should eventually support unget for dchar as well if (n & 1) // make sure we have an even number of bytes - readExact(&BOM_buffer[n++],1); + readExact(&BOM_buffer[n++],1); while (n > m) { - n -= 2; - wchar cw = *(cast(wchar*)&BOM_buffer[n]); - fixBO(&cw,2); - ungetcw(cw); + n -= 2; + wchar cw = *(cast(wchar*)&BOM_buffer[n]); + fixBO(&cw,2); + ungetcw(cw); } } return result; @@ -2283,29 +2283,29 @@ class EndianStream : FilterStream { switch (size) { case 0: break; case 2: { - ubyte x = *startb; - *startb = *(startb+1); - *(startb+1) = x; - break; + ubyte x = *startb; + *startb = *(startb+1); + *(startb+1) = x; + break; } case 4: { - *start = bswap(*start); - break; + *start = bswap(*start); + break; } default: { - uint* end = cast(uint*)(buffer + size - uint.sizeof); - while (start < end) { - uint x = bswap(*start); - *start = bswap(*end); - *end = x; - ++start; - --end; - } - startb = cast(ubyte*)start; - ubyte* endb = cast(ubyte*)end; - int len = uint.sizeof - (startb - endb); - if (len > 0) - fixBO(startb,len); + uint* end = cast(uint*)(buffer + size - uint.sizeof); + while (start < end) { + uint x = bswap(*start); + *start = bswap(*end); + *end = x; + ++start; + --end; + } + startb = cast(ubyte*)start; + ubyte* endb = cast(ubyte*)end; + int len = uint.sizeof - (startb - endb); + if (len > 0) + fixBO(startb,len); } } } @@ -2348,8 +2348,8 @@ class EndianStream : FilterStream { if (prevCr) { prevCr = false; c = getcw(); - if (c != '\n') - return c; + if (c != '\n') + return c; } if (unget.length > 1) { c = unget[unget.length - 1]; @@ -2553,7 +2553,7 @@ class TArrayStream(Buffer): Stream { case SeekPos.Current: scur = cast(long)(cur + offset); break; case SeekPos.End: scur = cast(long)(len + offset); break; default: - assert(0); + assert(0); } if (scur < 0) @@ -2569,7 +2569,7 @@ class TArrayStream(Buffer): Stream { override size_t available () { return cast(size_t)(len - cur); } /// Get the current memory data in total. - ubyte[] data() { + ubyte[] data() { if (len > size_t.max) throw new StreamException("Stream too big"); void[] res = buf[0 .. cast(size_t)len]; @@ -2619,7 +2619,7 @@ class MemoryStream: TArrayStream!(ubyte[]) { * Load it with specific input data. */ this(ubyte[] buf) { super (buf); } - this(byte[] buf) { this(cast(ubyte[]) buf); } /// ditto + this(byte[] buf) { this(cast(ubyte[]) buf); } /// ditto this(char[] buf) { this(cast(ubyte[]) buf); } /// ditto /// Ensure the stream can hold count bytes. @@ -2663,7 +2663,7 @@ class MemoryStream: TArrayStream!(ubyte[]) { assert (str[0..13] == "100 345 hello", str[0 .. 13]); assert (m.available == 29); assert (m.position == 13); - + MemoryStream m2; m.position = 3; m2 = new MemoryStream (); @@ -2804,7 +2804,7 @@ class SliceStream : FilterStream { override size_t readBlock (void *buffer, size_t size) { assertReadable(); if (bounded && size > high - low - pos) - size = cast(size_t)(high - low - pos); + size = cast(size_t)(high - low - pos); ulong bp = s.position; if (seekable) s.position = low + pos; @@ -2819,7 +2819,7 @@ class SliceStream : FilterStream { override size_t writeBlock (void *buffer, size_t size) { assertWriteable(); if (bounded && size > high - low - pos) - size = cast(size_t)(high - low - pos); + size = cast(size_t)(high - low - pos); ulong bp = s.position; if (seekable) s.position = low + pos; @@ -2837,19 +2837,19 @@ class SliceStream : FilterStream { switch (rel) { case SeekPos.Set: - spos = offset; - break; + spos = offset; + break; case SeekPos.Current: - spos = cast(long)(pos + offset); - break; + spos = cast(long)(pos + offset); + break; case SeekPos.End: - if (bounded) - spos = cast(long)(high - low + offset); - else - spos = cast(long)(s.size - low + offset); - break; + if (bounded) + spos = cast(long)(high - low + offset); + else + spos = cast(long)(s.size - low + offset); + break; default: - assert(0); + assert(0); } if (spos < 0) @@ -2870,9 +2870,9 @@ class SliceStream : FilterStream { ulong bp = s.position; if (bp <= pos+low && pos+low <= bp+res) { if (!bounded || bp+res <= high) - return cast(size_t)(bp + res - pos - low); + return cast(size_t)(bp + res - pos - low); else if (high <= bp+res) - return cast(size_t)(high - pos - low); + return cast(size_t)(high - pos - low); } return 0; } diff --git a/std/string.d b/std/string.d index aa81cf12c..33fc2f884 100644 --- a/std/string.d +++ b/std/string.d @@ -13,13 +13,13 @@ * are done, the returned string is a copy. * * Macros: - * WIKI = Phobos/StdString + * WIKI = Phobos/StdString * Copyright: - * Public Domain + * Public Domain */ /* Author: - * Walter Bright, Digital Mars, www.digitalmars.com + * Walter Bright, Digital Mars, www.digitalmars.com */ // The code is not optimized for speed, that will have to wait @@ -27,7 +27,7 @@ module std.string; -//debug=string; // uncomment to turn on debugging printf's +//debug=string; // uncomment to turn on debugging printf's private import std.stdio; private import std.c.stdio; @@ -52,25 +52,25 @@ extern (C) /// Thrown on errors in string functions. class StringException : Exception { - this(char[] msg) /// Constructor + this(char[] msg) /// Constructor { - super(msg); + super(msg); } } /* ************* Constants *************** */ -const char[16] hexdigits = "0123456789ABCDEF"; /// 0..9A..F -const char[10] digits = "0123456789"; /// 0..9 -const char[8] octdigits = "01234567"; /// 0..7 -const char[26] lowercase = "abcdefghijklmnopqrstuvwxyz"; /// a..z -const char[26] uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// A..Z +const char[16] hexdigits = "0123456789ABCDEF"; /// 0..9A..F +const char[10] digits = "0123456789"; /// 0..9 +const char[8] octdigits = "01234567"; /// 0..7 +const char[26] lowercase = "abcdefghijklmnopqrstuvwxyz"; /// a..z +const char[26] uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// A..Z const char[52] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; /// A..Za..z -const char[6] whitespace = " \t\v\r\n\f"; /// ASCII whitespace + "abcdefghijklmnopqrstuvwxyz"; /// A..Za..z +const char[6] whitespace = " \t\v\r\n\f"; /// ASCII whitespace -const dchar LS = '\u2028'; /// UTF line separator -const dchar PS = '\u2029'; /// UTF paragraph separator +const dchar LS = '\u2028'; /// UTF line separator +const dchar PS = '\u2029'; /// UTF paragraph separator /// Newline sequence for this system version (Windows) @@ -85,8 +85,8 @@ else version (Posix) bool iswhite(dchar c) { return (c <= 0x7F) - ? find(whitespace, c) != -1 - : (c == PS || c == LS); + ? find(whitespace, c) != -1 + : (c == PS || c == LS); } /********************************* @@ -112,11 +112,11 @@ real atof(char[] s) /********************************** * Compare two strings. cmp is case sensitive, icmp is case insensitive. * Returns: - * - * $(TR $(TD < 0) $(TD s1 < s2)) - * $(TR $(TD = 0) $(TD s1 == s2)) - * $(TR $(TD > 0) $(TD s1 > s2)) - *
+ * + * $(TR $(TD < 0) $(TD s1 < s2)) + * $(TR $(TD = 0) $(TD s1 == s2)) + * $(TR $(TD > 0) $(TD s1 > s2)) + *
*/ int cmp(char[] s1, char[] s2) @@ -126,10 +126,10 @@ int cmp(char[] s1, char[] s2) //printf("cmp('%.*s', '%.*s')\n", s1, s2); if (s2.length < len) - len = s2.length; + len = s2.length; result = memcmp(s1.ptr, s2.ptr, len); if (result == 0) - result = cast(int)s1.length - cast(int)s2.length; + result = cast(int)s1.length - cast(int)s2.length; return result; } @@ -143,32 +143,32 @@ int icmp(char[] s1, char[] s2) int result; if (s2.length < len) - len = s2.length; + len = s2.length; version (Win32) { - result = memicmp(s1.ptr, s2.ptr, len); + result = memicmp(s1.ptr, s2.ptr, len); } version (Posix) { - for (size_t i = 0; i < len; i++) - { - if (s1[i] != s2[i]) - { - char c1 = s1[i]; - char c2 = s2[i]; + for (size_t i = 0; i < len; i++) + { + if (s1[i] != s2[i]) + { + char c1 = s1[i]; + char c2 = s2[i]; - if (c1 >= 'A' && c1 <= 'Z') - c1 += cast(int)'a' - cast(int)'A'; - if (c2 >= 'A' && c2 <= 'Z') - c2 += cast(int)'a' - cast(int)'A'; - result = cast(int)c1 - cast(int)c2; - if (result) - break; - } - } + if (c1 >= 'A' && c1 <= 'Z') + c1 += cast(int)'a' - cast(int)'A'; + if (c2 >= 'A' && c2 <= 'Z') + c2 += cast(int)'a' - cast(int)'A'; + result = cast(int)c1 - cast(int)c2; + if (result) + break; + } + } } if (result == 0) - result = cast(int)s1.length - cast(int)s2.length; + result = cast(int)s1.length - cast(int)s2.length; return result; } @@ -211,45 +211,45 @@ deprecated char* toCharz(char[] s) char* toStringz(char[] s) in { - assert(memchr(s.ptr, 0, s.length) == null); + assert(memchr(s.ptr, 0, s.length) == null); } out (result) { - if (result) - { - auto slen = s.length; - while (slen > 0 && s[slen-1] == '\0') --slen; - assert(strlen(result) == slen); - assert(memcmp(result, s.ptr, slen) == 0); - } + if (result) + { + auto slen = s.length; + while (slen > 0 && s[slen-1] == '\0') --slen; + assert(strlen(result) == slen); + assert(memcmp(result, s.ptr, slen) == 0); + } } body { - char[] copy; + char[] copy; - if (s.length == 0) - return ""; + if (s.length == 0) + return ""; - /+ Unfortunately, this isn't reliable. - We could make this work if string literals are put - in read-only memory and we test if s[] is pointing into - that. + /+ Unfortunately, this isn't reliable. + We could make this work if string literals are put + in read-only memory and we test if s[] is pointing into + that. - /* Peek past end of s[], if it's 0, no conversion necessary. - * Note that the compiler will put a 0 past the end of static - * strings, and the storage allocator will put a 0 past the end - * of newly allocated char[]'s. - */ - char* p = &s[0] + s.length; - if (*p == 0) - return s; - +/ + /* Peek past end of s[], if it's 0, no conversion necessary. + * Note that the compiler will put a 0 past the end of static + * strings, and the storage allocator will put a 0 past the end + * of newly allocated char[]'s. + */ + char* p = &s[0] + s.length; + if (*p == 0) + return s; + +/ - // Need to make a copy - copy = new char[s.length + 1]; - copy[0..s.length] = s; - copy[s.length] = 0; - return copy.ptr; + // Need to make a copy + copy = new char[s.length + 1]; + copy[0..s.length] = s; + copy[s.length] = 0; + return copy.ptr; } unittest @@ -281,25 +281,25 @@ unittest * * find, rfind are case sensitive; ifind, irfind are case insensitive. * Returns: - * Index in s where c is found, -1 if not found. + * Index in s where c is found, -1 if not found. */ int find(char[] s, dchar c) { if (c <= 0x7F) - { // Plain old ASCII - auto p = cast(char*)memchr(s.ptr, c, s.length); - if (p) - return p - cast(char *)s; - else - return -1; + { // Plain old ASCII + auto p = cast(char*)memchr(s.ptr, c, s.length); + if (p) + return p - cast(char *)s; + else + return -1; } // c is a universal character foreach (int i, dchar c2; s) { - if (c == c2) - return i; + if (c == c2) + return i; } return -1; } @@ -330,26 +330,26 @@ int ifind(char[] s, dchar c) char* p; if (c <= 0x7F) - { // Plain old ASCII - char c1 = cast(char) std.ctype.tolower(c); + { // Plain old ASCII + char c1 = cast(char) std.ctype.tolower(c); - foreach (int i, char c2; s) - { - c2 = cast(char)std.ctype.tolower(c2); - if (c1 == c2) - return i; - } + foreach (int i, char c2; s) + { + c2 = cast(char)std.ctype.tolower(c2); + if (c1 == c2) + return i; + } } else - { // c is a universal character - dchar c1 = std.uni.toUniLower(c); + { // c is a universal character + dchar c1 = std.uni.toUniLower(c); - foreach (int i, dchar c2; s) - { - c2 = std.uni.toUniLower(c2); - if (c1 == c2) - return i; - } + foreach (int i, dchar c2; s) + { + c2 = std.uni.toUniLower(c2); + if (c1 == c2) + return i; + } } return -1; } @@ -390,13 +390,13 @@ int rfind(char[] s, dchar c) size_t i; if (c <= 0x7F) - { // Plain old ASCII - for (i = s.length; i-- != 0;) - { - if (s[i] == c) - break; - } - return i; + { // Plain old ASCII + for (i = s.length; i-- != 0;) + { + if (s[i] == c) + break; + } + return i; } // c is a universal character @@ -431,35 +431,35 @@ int irfind(char[] s, dchar c) size_t i; if (c <= 0x7F) - { // Plain old ASCII - char c1 = cast(char) std.ctype.tolower(c); + { // Plain old ASCII + char c1 = cast(char) std.ctype.tolower(c); - for (i = s.length; i-- != 0;) - { char c2 = s[i]; + for (i = s.length; i-- != 0;) + { char c2 = s[i]; - c2 = cast(char) std.ctype.tolower(c2); - if (c1 == c2) - break; - } + c2 = cast(char) std.ctype.tolower(c2); + if (c1 == c2) + break; + } } else - { // c is a universal character - dchar c1 = std.uni.toUniLower(c); + { // c is a universal character + dchar c1 = std.uni.toUniLower(c); - for (i = s.length; i-- != 0;) - { char cx = s[i]; + for (i = s.length; i-- != 0;) + { char cx = s[i]; - if (cx <= 0x7F) - continue; // skip, since c is not ASCII - if ((cx & 0xC0) == 0x80) - continue; // skip non-starting UTF-8 chars + if (cx <= 0x7F) + continue; // skip, since c is not ASCII + if ((cx & 0xC0) == 0x80) + continue; // skip non-starting UTF-8 chars - size_t j = i; - dchar c2 = std.utf.decode(s, j); - c2 = std.uni.toUniLower(c2); - if (c1 == c2) - break; - } + size_t j = i; + dchar c2 = std.utf.decode(s, j); + c2 = std.uni.toUniLower(c2); + if (c1 == c2) + break; + } } return i; } @@ -497,57 +497,57 @@ unittest * * find, rfind are case sensitive; ifind, irfind are case insensitive. * Returns: - * Index in s where c is found, -1 if not found. + * Index in s where c is found, -1 if not found. */ int find(char[] s, char[] sub) out (result) { - if (result == -1) - { - } - else - { - assert(0 <= result && result < s.length - sub.length + 1); - assert(memcmp(&s[result], sub.ptr, sub.length) == 0); - } + if (result == -1) + { + } + else + { + assert(0 <= result && result < s.length - sub.length + 1); + assert(memcmp(&s[result], sub.ptr, sub.length) == 0); + } } body { - auto sublength = sub.length; + auto sublength = sub.length; - if (sublength == 0) - return 0; + if (sublength == 0) + return 0; - if (s.length >= sublength) - { - auto c = sub[0]; - if (sublength == 1) - { - auto p = cast(char*)memchr(s.ptr, c, s.length); - if (p) - return p - &s[0]; - } - else - { - size_t imax = s.length - sublength + 1; + if (s.length >= sublength) + { + auto c = sub[0]; + if (sublength == 1) + { + auto p = cast(char*)memchr(s.ptr, c, s.length); + if (p) + return p - &s[0]; + } + else + { + size_t imax = s.length - sublength + 1; - // Remainder of sub[] - char *q = &sub[1]; - sublength--; + // Remainder of sub[] + char *q = &sub[1]; + sublength--; - for (size_t i = 0; i < imax; i++) - { - char *p = cast(char*)memchr(&s[i], c, imax - i); - if (!p) - break; - i = p - &s[0]; - if (memcmp(p + 1, q, sublength) == 0) - return i; - } - } - } - return -1; + for (size_t i = 0; i < imax; i++) + { + char *p = cast(char*)memchr(&s[i], c, imax - i); + if (!p) + break; + i = p - &s[0]; + if (memcmp(p + 1, q, sublength) == 0) + return i; + } + } + } + return -1; } @@ -578,61 +578,61 @@ unittest int ifind(char[] s, char[] sub) out (result) { - if (result == -1) - { - } - else - { - assert(0 <= result && result < s.length - sub.length + 1); - assert(icmp(s[result .. result + sub.length], sub) == 0); - } + if (result == -1) + { + } + else + { + assert(0 <= result && result < s.length - sub.length + 1); + assert(icmp(s[result .. result + sub.length], sub) == 0); + } } body { - auto sublength = sub.length; - int i; + auto sublength = sub.length; + int i; - if (sublength == 0) - return 0; + if (sublength == 0) + return 0; - if (s.length < sublength) - return -1; + if (s.length < sublength) + return -1; - auto c = sub[0]; - if (sublength == 1) - { - i = ifind(s, c); - } - else if (c <= 0x7F) - { - size_t imax = s.length - sublength + 1; + auto c = sub[0]; + if (sublength == 1) + { + i = ifind(s, c); + } + else if (c <= 0x7F) + { + size_t imax = s.length - sublength + 1; - // Remainder of sub[] - char[] subn = sub[1 .. sublength]; + // Remainder of sub[] + char[] subn = sub[1 .. sublength]; - for (i = 0; i < imax; i++) - { - auto j = ifind(s[i .. imax], c); - if (j == -1) - return -1; - i += j; - if (icmp(s[i + 1 .. i + sublength], subn) == 0) - return i; - } - i = -1; - } - else - { - size_t imax = s.length - sublength; + for (i = 0; i < imax; i++) + { + auto j = ifind(s[i .. imax], c); + if (j == -1) + return -1; + i += j; + if (icmp(s[i + 1 .. i + sublength], subn) == 0) + return i; + } + i = -1; + } + else + { + size_t imax = s.length - sublength; - for (i = 0; i <= imax; i++) - { - if (icmp(s[i .. i + sublength], sub) == 0) - return i; - } - i = -1; - } - return i; + for (i = 0; i <= imax; i++) + { + if (icmp(s[i .. i + sublength], sub) == 0) + return i; + } + i = -1; + } + return i; } @@ -676,7 +676,7 @@ unittest // Thanks to Carlos Santander B. and zwang i = ifind("sus mejores cortesanos. Se embarcaron en el puerto de Dubai y", - "page-break-before"); + "page-break-before"); assert(i == -1); } @@ -687,33 +687,33 @@ unittest int rfind(char[] s, char[] sub) out (result) { - if (result == -1) - { - } - else - { - assert(0 <= result && result < s.length - sub.length + 1); - assert(memcmp(&s[0] + result, sub.ptr, sub.length) == 0); - } + if (result == -1) + { + } + else + { + assert(0 <= result && result < s.length - sub.length + 1); + assert(memcmp(&s[0] + result, sub.ptr, sub.length) == 0); + } } body { - char c; + char c; - if (sub.length == 0) - return s.length; - c = sub[0]; - if (sub.length == 1) - return rfind(s, c); - for (int i = s.length - sub.length; i >= 0; i--) - { - if (s[i] == c) - { - if (memcmp(&s[i + 1], &sub[1], sub.length - 1) == 0) - return i; - } - } - return -1; + if (sub.length == 0) + return s.length; + c = sub[0]; + if (sub.length == 1) + return rfind(s, c); + for (int i = s.length - sub.length; i >= 0; i--) + { + if (s[i] == c) + { + if (memcmp(&s[i + 1], &sub[1], sub.length - 1) == 0) + return i; + } + } + return -1; } unittest @@ -741,45 +741,45 @@ unittest int irfind(char[] s, char[] sub) out (result) { - if (result == -1) - { - } - else - { - assert(0 <= result && result < s.length - sub.length + 1); - assert(icmp(s[result .. result + sub.length], sub) == 0); - } + if (result == -1) + { + } + else + { + assert(0 <= result && result < s.length - sub.length + 1); + assert(icmp(s[result .. result + sub.length], sub) == 0); + } } body { - dchar c; + dchar c; - if (sub.length == 0) - return s.length; - c = sub[0]; - if (sub.length == 1) - return irfind(s, c); - if (c <= 0x7F) - { - c = std.ctype.tolower(c); - for (int i = s.length - sub.length; i >= 0; i--) - { - if (std.ctype.tolower(s[i]) == c) - { - if (icmp(s[i + 1 .. i + sub.length], sub[1 .. sub.length]) == 0) - return i; - } - } - } - else - { - for (int i = s.length - sub.length; i >= 0; i--) - { - if (icmp(s[i .. i + sub.length], sub) == 0) - return i; - } - } - return -1; + if (sub.length == 0) + return s.length; + c = sub[0]; + if (sub.length == 1) + return irfind(s, c); + if (c <= 0x7F) + { + c = std.ctype.tolower(c); + for (int i = s.length - sub.length; i >= 0; i--) + { + if (std.ctype.tolower(s[i]) == c) + { + if (icmp(s[i + 1 .. i + sub.length], sub[1 .. sub.length]) == 0) + return i; + } + } + } + else + { + for (int i = s.length - sub.length; i >= 0; i--) + { + if (icmp(s[i .. i + sub.length], sub) == 0) + return i; + } + } + return -1; } unittest @@ -800,14 +800,14 @@ unittest char[] sPlts = "Mars: the fourth Rock (Planet) from the Sun."; char[] sMars = "Who\'s \'My Favorite Maritian?\'"; - + i = irfind("abcdefcdef", "c"); assert(i == 6); i = irfind("abcdefcdef", "cd"); assert(i == 6); i = irfind( "abcdefcdef", "def" ); assert(i == 7); - + i = irfind(sMars, "RiTE maR"); assert(i == 14); i = irfind(sPlts, "FOuRTh"); @@ -830,40 +830,40 @@ string tolower(string s) for (size_t i = 0; i < s.length; i++) { - auto c = s[i]; - if ('A' <= c && c <= 'Z') - { - if (!changed) - { - r = s.dup; - changed = 1; - } - r[i] = cast(char) (c + (cast(char)'a' - 'A')); - } - else if (c > 0x7F) - { - foreach (size_t j, dchar dc; s[i .. length]) - { - if (std.uni.isUniUpper(dc)) - { - dc = std.uni.toUniLower(dc); - if (!changed) - { - r = s[0 .. i + j].dup; - changed = 2; - } - } - if (changed) - { - if (changed == 1) - { r = r[0 .. i + j]; - changed = 2; - } - std.utf.encode(r, dc); - } - } - break; - } + auto c = s[i]; + if ('A' <= c && c <= 'Z') + { + if (!changed) + { + r = s.dup; + changed = 1; + } + r[i] = cast(char) (c + (cast(char)'a' - 'A')); + } + else if (c > 0x7F) + { + foreach (size_t j, dchar dc; s[i .. length]) + { + if (std.uni.isUniUpper(dc)) + { + dc = std.uni.toUniLower(dc); + if (!changed) + { + r = s[0 .. i + j].dup; + changed = 2; + } + } + if (changed) + { + if (changed == 1) + { r = r[0 .. i + j]; + changed = 2; + } + std.utf.encode(r, dc); + } + } + break; + } } return changed ? r : s; } @@ -906,40 +906,40 @@ string toupper(string s) for (size_t i = 0; i < s.length; i++) { - auto c = s[i]; - if ('a' <= c && c <= 'z') - { - if (!changed) - { - r = s.dup; - changed = 1; - } - r[i] = cast(char) (c - (cast(char)'a' - 'A')); - } - else if (c > 0x7F) - { - foreach (size_t j, dchar dc; s[i .. length]) - { - if (std.uni.isUniLower(dc)) - { - dc = std.uni.toUniUpper(dc); - if (!changed) - { - r = s[0 .. i + j].dup; - changed = 2; - } - } - if (changed) - { - if (changed == 1) - { r = r[0 .. i + j]; - changed = 2; - } - std.utf.encode(r, dc); - } - } - break; - } + auto c = s[i]; + if ('a' <= c && c <= 'z') + { + if (!changed) + { + r = s.dup; + changed = 1; + } + r[i] = cast(char) (c - (cast(char)'a' - 'A')); + } + else if (c > 0x7F) + { + foreach (size_t j, dchar dc; s[i .. length]) + { + if (std.uni.isUniLower(dc)) + { + dc = std.uni.toUniUpper(dc); + if (!changed) + { + r = s[0 .. i + j].dup; + changed = 2; + } + } + if (changed) + { + if (changed == 1) + { r = r[0 .. i + j]; + changed = 2; + } + std.utf.encode(r, dc); + } + } + break; + } } return changed ? r : s; } @@ -981,30 +981,30 @@ char[] capitalize(char[] s) changed = 0; foreach (size_t i, dchar c; s) - { dchar c2; + { dchar c2; - if (i == 0) - { - c2 = std.uni.toUniUpper(c); - if (c != c2) - { - changed = 1; - r = null; - } - } - else - { - c2 = std.uni.toUniLower(c); - if (c != c2) - { - if (!changed) - { changed = 1; - r = s[0 .. i].dup; - } - } - } - if (changed) - std.utf.encode(r, c2); + if (i == 0) + { + c2 = std.uni.toUniUpper(c); + if (c != c2) + { + changed = 1; + r = null; + } + } + else + { + c2 = std.uni.toUniLower(c); + if (c != c2) + { + if (!changed) + { changed = 1; + r = s[0 .. i].dup; + } + } + } + if (changed) + std.utf.encode(r, c2); } return r; } @@ -1047,35 +1047,35 @@ char[] capwords(char[] s) for (i = 0; i < s.length; i++) { - switch (s[i]) - { - case ' ': - case '\t': - case '\f': - case '\r': - case '\n': - case '\v': - if (inword) - { - r ~= capitalize(s[istart .. i]); - inword = false; - } - break; + switch (s[i]) + { + case ' ': + case '\t': + case '\f': + case '\r': + case '\n': + case '\v': + if (inword) + { + r ~= capitalize(s[istart .. i]); + inword = false; + } + break; - default: - if (!inword) - { - if (r.length) - r ~= ' '; - istart = i; - inword = true; - } - break; - } + default: + if (!inword) + { + if (r.length) + r ~= ' '; + istart = i; + inword = true; + } + break; + } } if (inword) { - r ~= capitalize(s[istart .. i]); + r ~= capitalize(s[istart .. i]); } return r; @@ -1101,19 +1101,19 @@ unittest char[] repeat(char[] s, size_t n) { if (n == 0) - return null; + return null; if (n == 1) - return s; + return s; char[] r = new char[n * s.length]; if (s.length == 1) - r[] = s[0]; + r[] = s[0]; else - { auto len = s.length; + { auto len = s.length; - for (size_t i = 0; i < n * len; i += len) - { - r[i .. i + len] = s[]; - } + for (size_t i = 0; i < n * len; i += len) + { + r[i .. i + len] = s[]; + } } return r; } @@ -1149,32 +1149,32 @@ char[] join(char[][] words, char[] sep) if (words.length) { - size_t len = 0; - size_t i; + size_t len = 0; + size_t i; - for (i = 0; i < words.length; i++) - len += words[i].length; + for (i = 0; i < words.length; i++) + len += words[i].length; - auto seplen = sep.length; - len += (words.length - 1) * seplen; + auto seplen = sep.length; + len += (words.length - 1) * seplen; - result = new char[len]; + result = new char[len]; - size_t j; - i = 0; - while (true) - { - uint wlen = words[i].length; + size_t j; + i = 0; + while (true) + { + uint wlen = words[i].length; - result[j .. j + wlen] = words[i]; - j += wlen; - i++; - if (i >= words.length) - break; - result[j .. j + seplen] = sep; - j += seplen; - } - assert(j == len); + result[j .. j + wlen] = words[i]; + j += wlen; + i++; + if (i >= words.length) + break; + result[j .. j + seplen] = sep; + j += seplen; + } + assert(j == len); } return result; } @@ -1213,31 +1213,31 @@ char[][] split(char[] s) for (i = 0; i < s.length; i++) { - switch (s[i]) - { - case ' ': - case '\t': - case '\f': - case '\r': - case '\n': - case '\v': - if (inword) - { - words ~= s[istart .. i]; - inword = false; - } - break; + switch (s[i]) + { + case ' ': + case '\t': + case '\f': + case '\r': + case '\n': + case '\v': + if (inword) + { + words ~= s[istart .. i]; + inword = false; + } + break; - default: - if (!inword) - { istart = i; - inword = true; - } - break; - } + default: + if (!inword) + { istart = i; + inword = true; + } + break; + } } if (inword) - words ~= s[istart .. i]; + words ~= s[istart .. i]; return words; } @@ -1268,101 +1268,101 @@ unittest char[][] split(char[] s, char[] delim) in { - assert(delim.length > 0); + assert(delim.length > 0); } body { - size_t i; - size_t j; - char[][] words; + size_t i; + size_t j; + char[][] words; - i = 0; - if (s.length) - { - if (delim.length == 1) - { char c = delim[0]; - size_t nwords = 0; - char* p = &s[0]; - char* pend = p + s.length; + i = 0; + if (s.length) + { + if (delim.length == 1) + { char c = delim[0]; + size_t nwords = 0; + char* p = &s[0]; + char* pend = p + s.length; - while (true) - { - nwords++; - p = cast(char*)memchr(p, c, pend - p); - if (!p) - break; - p++; - if (p == pend) - { nwords++; - break; - } - } - words.length = nwords; + while (true) + { + nwords++; + p = cast(char*)memchr(p, c, pend - p); + if (!p) + break; + p++; + if (p == pend) + { nwords++; + break; + } + } + words.length = nwords; - int wordi = 0; - i = 0; - while (true) - { - p = cast(char*)memchr(&s[i], c, s.length - i); - if (!p) - { - words[wordi] = s[i .. s.length]; - break; - } - j = p - &s[0]; - words[wordi] = s[i .. j]; - wordi++; - i = j + 1; - if (i == s.length) - { - words[wordi] = ""; - break; - } - } - assert(wordi + 1 == nwords); - } - else - { size_t nwords = 0; + int wordi = 0; + i = 0; + while (true) + { + p = cast(char*)memchr(&s[i], c, s.length - i); + if (!p) + { + words[wordi] = s[i .. s.length]; + break; + } + j = p - &s[0]; + words[wordi] = s[i .. j]; + wordi++; + i = j + 1; + if (i == s.length) + { + words[wordi] = ""; + break; + } + } + assert(wordi + 1 == nwords); + } + else + { size_t nwords = 0; - while (true) - { - nwords++; - j = find(s[i .. s.length], delim); - if (j == -1) - break; - i += j + delim.length; - if (i == s.length) - { nwords++; - break; - } - assert(i < s.length); - } - words.length = nwords; + while (true) + { + nwords++; + j = find(s[i .. s.length], delim); + if (j == -1) + break; + i += j + delim.length; + if (i == s.length) + { nwords++; + break; + } + assert(i < s.length); + } + words.length = nwords; - int wordi = 0; - i = 0; - while (true) - { - j = find(s[i .. s.length], delim); - if (j == -1) - { - words[wordi] = s[i .. s.length]; - break; - } - words[wordi] = s[i .. i + j]; - wordi++; - i += j + delim.length; - if (i == s.length) - { - words[wordi] = ""; - break; - } - assert(i < s.length); - } - assert(wordi + 1 == nwords); - } - } - return words; + int wordi = 0; + i = 0; + while (true) + { + j = find(s[i .. s.length], delim); + if (j == -1) + { + words[wordi] = s[i .. s.length]; + break; + } + words[wordi] = s[i .. i + j]; + wordi++; + i += j + delim.length; + if (i == s.length) + { + words[wordi] = ""; + break; + } + assert(i < s.length); + } + assert(wordi + 1 == nwords); + } + } + return words; } unittest @@ -1386,13 +1386,13 @@ unittest i = cmp(words[4], ""); assert(i == 0); - s = s[0 .. s.length - 1]; // lop off trailing ',' + s = s[0 .. s.length - 1]; // lop off trailing ',' words = split(s, ","); assert(words.length == 4); i = cmp(words[3], "jerry"); assert(i == 0); - s = s[1 .. s.length]; // lop off leading ',' + s = s[1 .. s.length]; // lop off leading ',' words = split(s, ","); assert(words.length == 3); i = cmp(words[0], "peter"); @@ -1414,13 +1414,13 @@ unittest i = cmp(words[4], ""); assert(i == 0); - s2 = s2[0 .. s2.length - 2]; // lop off trailing ',,' + s2 = s2[0 .. s2.length - 2]; // lop off trailing ',,' words = split(s2, ",,"); assert(words.length == 4); i = cmp(words[3], "jerry"); assert(i == 0); - s2 = s2[2 .. s2.length]; // lop off leading ',,' + s2 = s2[2 .. s2.length]; // lop off leading ',,' words = split(s2, ",,"); assert(words.length == 3); i = cmp(words[0], "peter"); @@ -1443,45 +1443,45 @@ char[][] splitlines(char[] s) nlines = 0; for (i = 0; i < s.length; i++) - { char c; + { char c; - c = s[i]; - if (c == '\r' || c == '\n') - { - nlines++; - istart = i + 1; - if (c == '\r' && i + 1 < s.length && s[i + 1] == '\n') - { - i++; - istart++; - } - } + c = s[i]; + if (c == '\r' || c == '\n') + { + nlines++; + istart = i + 1; + if (c == '\r' && i + 1 < s.length && s[i + 1] == '\n') + { + i++; + istart++; + } + } } if (istart != i) - nlines++; + nlines++; lines = new char[][nlines]; nlines = 0; istart = 0; for (i = 0; i < s.length; i++) - { char c; + { char c; - c = s[i]; - if (c == '\r' || c == '\n') - { - lines[nlines] = s[istart .. i]; - nlines++; - istart = i + 1; - if (c == '\r' && i + 1 < s.length && s[i + 1] == '\n') - { - i++; - istart++; - } - } + c = s[i]; + if (c == '\r' || c == '\n') + { + lines[nlines] = s[istart .. i]; + nlines++; + istart = i + 1; + if (c == '\r' && i + 1 < s.length && s[i + 1] == '\n') + { + i++; + istart++; + } + } } if (istart != i) - { lines[nlines] = s[istart .. i]; - nlines++; + { lines[nlines] = s[istart .. i]; + nlines++; } assert(nlines == lines.length); @@ -1509,7 +1509,7 @@ unittest i = cmp(lines[4], "jerry"); assert(i == 0); - s = s[0 .. s.length - 1]; // lop off trailing \n + s = s[0 .. s.length - 1]; // lop off trailing \n lines = splitlines(s); //printf("lines.length = %d\n", lines.length); assert(lines.length == 5); @@ -1528,8 +1528,8 @@ char[] stripl(char[] s) for (i = 0; i < s.length; i++) { - if (!std.ctype.isspace(s[i])) - break; + if (!std.ctype.isspace(s[i])) + break; } return s[i .. s.length]; } @@ -1540,8 +1540,8 @@ char[] stripr(char[] s) /// ditto for (i = s.length; i > 0; i--) { - if (!std.ctype.isspace(s[i - 1])) - break; + if (!std.ctype.isspace(s[i - 1])) + break; } return s[0 .. i]; } @@ -1572,24 +1572,24 @@ char[] chomp(char[] s, char[] delimiter = null) if (delimiter is null) { auto len = s.length; - if (len) - { auto c = s[len - 1]; + if (len) + { auto c = s[len - 1]; - if (c == '\r') // if ends in CR - len--; - else if (c == '\n') // if ends in LF - { - len--; - if (len && s[len - 1] == '\r') - len--; // remove CR-LF - } - } - return s[0 .. len]; + if (c == '\r') // if ends in CR + len--; + else if (c == '\n') // if ends in LF + { + len--; + if (len && s[len - 1] == '\r') + len--; // remove CR-LF + } + } + return s[0 .. len]; } else if (s.length >= delimiter.length) { - if (s[length - delimiter.length .. length] == delimiter) - return s[0 .. length - delimiter.length]; + if (s[length - delimiter.length .. length] == delimiter) + return s[0 .. length - delimiter.length]; } return s; } @@ -1641,18 +1641,18 @@ char[] chop(char[] s) if (len) { - if (len >= 2 && s[len - 1] == '\n' && s[len - 2] == '\r') - return s[0 .. len - 2]; + if (len >= 2 && s[len - 1] == '\n' && s[len - 2] == '\r') + return s[0 .. len - 2]; - // If we're in a tail of a UTF-8 sequence, back up - while ((s[len - 1] & 0xC0) == 0x80) - { - len--; - if (len == 0) - throw new std.utf.UtfException("invalid UTF sequence", 0); - } + // If we're in a tail of a UTF-8 sequence, back up + while ((s[len - 1] & 0xC0) == 0x80) + { + len--; + if (len == 0) + throw new std.utf.UtfException("invalid UTF sequence", 0); + } - return s[0 .. len - 1]; + return s[0 .. len - 1]; } return s; } @@ -1682,7 +1682,7 @@ unittest char[] ljustify(char[] s, int width) { if (s.length >= width) - return s; + return s; char[] r = new char[width]; r[0..s.length] = s; r[s.length .. width] = cast(char)' '; @@ -1693,7 +1693,7 @@ char[] ljustify(char[] s, int width) char[] rjustify(char[] s, int width) { if (s.length >= width) - return s; + return s; char[] r = new char[width]; r[0 .. width - s.length] = cast(char)' '; r[width - s.length .. width] = s; @@ -1704,7 +1704,7 @@ char[] rjustify(char[] s, int width) char[] center(char[] s, int width) { if (s.length >= width) - return s; + return s; char[] r = new char[width]; int left = (width - s.length) / 2; r[0 .. left] = cast(char)' '; @@ -1746,7 +1746,7 @@ unittest char[] zfill(char[] s, int width) { if (s.length >= width) - return s; + return s; char[] r = new char[width]; r[0 .. width - s.length] = cast(char)'0'; r[width - s.length .. width] = s; @@ -1765,19 +1765,19 @@ char[] replace(char[] s, char[] from, char[] to) //printf("replace('%.*s','%.*s','%.*s')\n", s, from, to); if (from.length == 0) - return s; + return s; istart = 0; while (istart < s.length) { - i = find(s[istart .. s.length], from); - if (i == -1) - { - p ~= s[istart .. s.length]; - break; - } - p ~= s[istart .. istart + i]; - p ~= to; - istart += i + from.length; + i = find(s[istart .. s.length], from); + if (i == -1) + { + p ~= s[istart .. s.length]; + break; + } + p ~= s[istart .. istart + i]; + p ~= to; + istart += i + from.length; } return p; } @@ -1853,10 +1853,10 @@ in body { if (sub.length == 0) - return s; + return s; if (s.length == 0) - return sub; + return sub; int newlength = s.length + sub.length; char[] result = new char[newlength]; @@ -1907,10 +1907,10 @@ size_t count(char[] s, char[] sub) for (i = 0; i < s.length; i += j + sub.length) { - j = find(s[i .. s.length], sub); - if (j == -1) - break; - count++; + j = find(s[i .. s.length], sub); + if (j == -1) + break; + count++; } return count; } @@ -1942,46 +1942,46 @@ char[] expandtabs(char[] string, int tabsize = 8) foreach (size_t i, dchar c; string) { - switch (c) - { - case '\t': - nspaces = tabsize - (column % tabsize); - if (!changes) - { - changes = true; - result = null; - result.length = string.length + nspaces - 1; - result.length = i + nspaces; - result[0 .. i] = string[0 .. i]; - result[i .. i + nspaces] = ' '; - } - else - { int j = result.length; - result.length = j + nspaces; - result[j .. j + nspaces] = ' '; - } - column += nspaces; - break; + switch (c) + { + case '\t': + nspaces = tabsize - (column % tabsize); + if (!changes) + { + changes = true; + result = null; + result.length = string.length + nspaces - 1; + result.length = i + nspaces; + result[0 .. i] = string[0 .. i]; + result[i .. i + nspaces] = ' '; + } + else + { int j = result.length; + result.length = j + nspaces; + result[j .. j + nspaces] = ' '; + } + column += nspaces; + break; - case '\r': - case '\n': - case PS: - case LS: - column = 0; - goto L1; + case '\r': + case '\n': + case PS: + case LS: + column = 0; + goto L1; - default: - column++; - L1: - if (changes) - { - if (c <= 0x7F) - result ~= cast(char)c; - else - std.utf.encode(result, c); - } - break; - } + default: + column++; + L1: + if (changes) + { + if (c <= 0x7F) + result ~= cast(char)c; + else + std.utf.encode(result, c); + } + break; + } } return result; @@ -2018,8 +2018,8 @@ unittest * Replace spaces in string with the optimal number of tabs. * Trailing spaces or tabs in a line are removed. * Params: - * string = String to convert. - * tabsize = Tab columns are tabsize spaces apart. tabsize defaults to 8. + * string = String to convert. + * tabsize = Tab columns are tabsize spaces apart. tabsize defaults to 8. */ char[] entab(char[] string, int tabsize = 8) @@ -2029,88 +2029,88 @@ char[] entab(char[] string, int tabsize = 8) int nspaces = 0; int nwhite = 0; - int column = 0; // column number + int column = 0; // column number foreach (size_t i, dchar c; string) - { + { - void change() - { - changes = true; - result = null; - result.length = string.length; - result.length = i; - result[0 .. i] = string[0 .. i]; - } + void change() + { + changes = true; + result = null; + result.length = string.length; + result.length = i; + result[0 .. i] = string[0 .. i]; + } - switch (c) - { - case '\t': - nwhite++; - if (nspaces) - { - if (!changes) - change(); + switch (c) + { + case '\t': + nwhite++; + if (nspaces) + { + if (!changes) + change(); - int j = result.length - nspaces; - int ntabs = (((column - nspaces) % tabsize) + nspaces) / tabsize; - result.length = j + ntabs; - result[j .. j + ntabs] = '\t'; - nwhite += ntabs - nspaces; - nspaces = 0; - } - column = (column + tabsize) / tabsize * tabsize; - break; + int j = result.length - nspaces; + int ntabs = (((column - nspaces) % tabsize) + nspaces) / tabsize; + result.length = j + ntabs; + result[j .. j + ntabs] = '\t'; + nwhite += ntabs - nspaces; + nspaces = 0; + } + column = (column + tabsize) / tabsize * tabsize; + break; - case '\r': - case '\n': - case PS: - case LS: - // Truncate any trailing spaces or tabs - if (nwhite) - { - if (!changes) - change(); - result = result[0 .. result.length - nwhite]; - } - break; + case '\r': + case '\n': + case PS: + case LS: + // Truncate any trailing spaces or tabs + if (nwhite) + { + if (!changes) + change(); + result = result[0 .. result.length - nwhite]; + } + break; - default: - if (nspaces >= 2 && (column % tabsize) == 0) - { - if (!changes) - change(); + default: + if (nspaces >= 2 && (column % tabsize) == 0) + { + if (!changes) + change(); - int j = result.length - nspaces; - int ntabs = (nspaces + tabsize - 1) / tabsize; - result.length = j + ntabs; - result[j .. j + ntabs] = '\t'; - nwhite += ntabs - nspaces; - nspaces = 0; - } - if (c == ' ') - { nwhite++; - nspaces++; - } - else - { nwhite = 0; - nspaces = 0; - } - column++; - break; - } - if (changes) - { - if (c <= 0x7F) - result ~= cast(char)c; - else - std.utf.encode(result, c); - } + int j = result.length - nspaces; + int ntabs = (nspaces + tabsize - 1) / tabsize; + result.length = j + ntabs; + result[j .. j + ntabs] = '\t'; + nwhite += ntabs - nspaces; + nspaces = 0; + } + if (c == ' ') + { nwhite++; + nspaces++; + } + else + { nwhite = 0; + nspaces = 0; + } + column++; + break; + } + if (changes) + { + if (c <= 0x7F) + result ~= cast(char)c; + else + std.utf.encode(result, c); + } } // Truncate any trailing spaces or tabs if (nwhite) - result = result[0 .. result.length - nwhite]; + result = result[0 .. result.length - nwhite]; return result; } @@ -2168,29 +2168,29 @@ unittest char[] maketrans(char[] from, char[] to) in { - assert(from.length == to.length); - assert(from.length <= 128); - foreach (char c; from) - { - assert(c <= 0x7F); - } - foreach (char c; to) - { - assert(c <= 0x7F); - } + assert(from.length == to.length); + assert(from.length <= 128); + foreach (char c; from) + { + assert(c <= 0x7F); + } + foreach (char c; to) + { + assert(c <= 0x7F); + } } body { - char[] t = new char[256]; - int i; + char[] t = new char[256]; + int i; - for (i = 0; i < t.length; i++) - t[i] = cast(char)i; + for (i = 0; i < t.length; i++) + t[i] = cast(char)i; - for (i = 0; i < from.length; i++) - t[from[i]] = to[i]; + for (i = 0; i < from.length; i++) + t[from[i]] = to[i]; - return t; + return t; } /****************************************** @@ -2202,40 +2202,40 @@ char[] maketrans(char[] from, char[] to) char[] translate(char[] s, char[] transtab, char[] delchars) in { - assert(transtab.length == 256); + assert(transtab.length == 256); } body { - char[] r; - int count; - bool[256] deltab; + char[] r; + int count; + bool[256] deltab; - deltab[] = false; - foreach (char c; delchars) - { - deltab[c] = true; - } + deltab[] = false; + foreach (char c; delchars) + { + deltab[c] = true; + } - count = 0; - foreach (char c; s) - { - if (!deltab[c]) - count++; - //printf("s[%d] = '%c', count = %d\n", i, s[i], count); - } + count = 0; + foreach (char c; s) + { + if (!deltab[c]) + count++; + //printf("s[%d] = '%c', count = %d\n", i, s[i], count); + } - r = new char[count]; - count = 0; - foreach (char c; s) - { - if (!deltab[c]) - { - r[count] = transtab[c]; - count++; - } - } + r = new char[count]; + count = 0; + foreach (char c; s) + { + if (!deltab[c]) + { + r[count] = transtab[c]; + count++; + } + } - return r; + return r; } unittest @@ -2282,7 +2282,7 @@ unittest char[] s2; foreach (char c; s) { - s2 ~= std.string.toString(c); + s2 ~= std.string.toString(c); } //printf("%.*s", s2); assert(s2 == "foo"); @@ -2299,19 +2299,19 @@ char[] toString(uint u) ndigits = 0; if (u < 10) - // Avoid storage allocation for simple stuff - result = digits[u .. u + 1]; + // Avoid storage allocation for simple stuff + result = digits[u .. u + 1]; else { - while (u) - { - uint c = (u % 10) + '0'; - u /= 10; - ndigits++; - buffer[buffer.length - ndigits] = cast(char)c; - } - result = new char[ndigits]; - result[] = buffer[buffer.length - ndigits .. buffer.length]; + while (u) + { + uint c = (u % 10) + '0'; + u /= 10; + ndigits++; + buffer[buffer.length - ndigits] = cast(char)c; + } + result = new char[ndigits]; + result[] = buffer[buffer.length - ndigits .. buffer.length]; } return result; } @@ -2343,14 +2343,14 @@ char[] toString(ulong u) char[] result; if (u < 0x1_0000_0000) - return toString(cast(uint)u); + return toString(cast(uint)u); ndigits = 0; while (u) { - char c = cast(char)((u % 10) + '0'); - u /= 10; - ndigits++; - buffer[buffer.length - ndigits] = c; + char c = cast(char)((u % 10) + '0'); + u /= 10; + ndigits++; + buffer[buffer.length - ndigits] = c; } result = new char[ndigits]; result[] = buffer[buffer.length - ndigits .. buffer.length]; @@ -2386,16 +2386,16 @@ char[] toString(int i) char[] result; if (i >= 0) - return toString(cast(uint)i); + return toString(cast(uint)i); uint u = -i; int ndigits = 1; while (u) { - char c = cast(char)((u % 10) + '0'); - u /= 10; - buffer[buffer.length - ndigits] = c; - ndigits++; + char c = cast(char)((u % 10) + '0'); + u /= 10; + buffer[buffer.length - ndigits] = c; + ndigits++; } buffer[buffer.length - ndigits] = '-'; result = new char[ndigits]; @@ -2441,18 +2441,18 @@ char[] toString(long i) char[] result; if (i >= 0) - return toString(cast(ulong)i); + return toString(cast(ulong)i); if (cast(int)i == i) - return toString(cast(int)i); + return toString(cast(int)i); ulong u = cast(ulong)(-i); int ndigits = 1; while (u) { - char c = cast(char)((u % 10) + '0'); - u /= 10; - buffer[buffer.length - ndigits] = c; - ndigits++; + char c = cast(char)((u % 10) + '0'); + u /= 10; + buffer[buffer.length - ndigits] = c; + ndigits++; } buffer[buffer.length - ndigits] = '-'; result = new char[ndigits]; @@ -2571,7 +2571,7 @@ in body { if (radix == 10) - return toString(value); // handle signed cases only for radix 10 + return toString(value); // handle signed cases only for radix 10 return toString(cast(ulong)value, radix); } @@ -2587,15 +2587,15 @@ body uint i = buffer.length; if (value < radix && value < hexdigits.length) - return hexdigits[cast(size_t)value .. cast(size_t)value + 1]; + return hexdigits[cast(size_t)value .. cast(size_t)value + 1]; do - { ubyte c; + { ubyte c; - c = cast(ubyte)(value % radix); - value = value / radix; - i--; - buffer[i] = cast(char)((c < 10) ? c + '0' : c + 'A' - 10); + c = cast(ubyte)(value % radix); + value = value / radix; + i--; + buffer[i] = cast(char)((c < 10) ? c + '0' : c + 'A' - 10); } while (value); return buffer[i .. length].dup; } @@ -2660,7 +2660,7 @@ char[] format(...) void putc(dchar c) { - std.utf.encode(s, c); + std.utf.encode(s, c); } std.format.doFormat(&putc, _arguments, _argptr); @@ -2678,23 +2678,23 @@ char[] sformat(char[] s, ...) void putc(dchar c) { - if (c <= 0x7F) - { - if (i >= s.length) - throw new ArrayBoundsError("std.string.sformat", 0); - s[i] = cast(char)c; - ++i; - } - else - { char[4] buf; - char[] b; + if (c <= 0x7F) + { + if (i >= s.length) + throw new ArrayBoundsError("std.string.sformat", 0); + s[i] = cast(char)c; + ++i; + } + else + { char[4] buf; + char[] b; - b = std.utf.toUTF8(buf, c); - if (i + b.length > s.length) - throw new ArrayBoundsError("std.string.sformat", 0); - s[i..i+b.length] = b[]; - i += b.length; - } + b = std.utf.toUTF8(buf, c); + if (i + b.length > s.length) + throw new ArrayBoundsError("std.string.sformat", 0); + s[i..i+b.length] = b[]; + i += b.length; + } } std.format.doFormat(&putc, _arguments, _argptr); @@ -2747,19 +2747,19 @@ unittest * See if character c is in the pattern. * Patterns: * - * A pattern is an array of characters much like a character - * class in regular expressions. A sequence of characters - * can be given, such as "abcde". The '-' can represent a range - * of characters, as "a-e" represents the same pattern as "abcde". - * "a-fA-F0-9" represents all the hex characters. - * If the first character of a pattern is '^', then the pattern - * is negated, i.e. "^0-9" means any character except a digit. - * The functions inPattern, countchars, removeschars, - * and squeeze - * use patterns. + * A pattern is an array of characters much like a character + * class in regular expressions. A sequence of characters + * can be given, such as "abcde". The '-' can represent a range + * of characters, as "a-e" represents the same pattern as "abcde". + * "a-fA-F0-9" represents all the hex characters. + * If the first character of a pattern is '^', then the pattern + * is negated, i.e. "^0-9" means any character except a digit. + * The functions inPattern, countchars, removeschars, + * and squeeze + * use patterns. * * Note: In the future, the pattern syntax may be improved - * to be more like regular expression character classes. + * to be more like regular expression character classes. */ bool inPattern(dchar c, char[] pattern) @@ -2770,25 +2770,25 @@ bool inPattern(dchar c, char[] pattern) foreach (size_t i, dchar p; pattern) { - if (p == '^' && i == 0) - { result = true; - if (i + 1 == pattern.length) - return (c == p); // or should this be an error? - } - else if (range) - { - range = 0; - if (lastc <= c && c <= p || c == p) - return !result; - } - else if (p == '-' && i > result && i + 1 < pattern.length) - { - range = 1; - continue; - } - else if (c == p) - return !result; - lastc = p; + if (p == '^' && i == 0) + { result = true; + if (i + 1 == pattern.length) + return (c == p); // or should this be an error? + } + else if (range) + { + range = 0; + if (lastc <= c && c <= p || c == p) + return !result; + } + else if (p == '-' && i > result && i + 1 < pattern.length) + { + range = 1; + continue; + } + else if (c == p) + return !result; + lastc = p; } return result; } @@ -2850,11 +2850,11 @@ int inPattern(dchar c, char[][] patterns) foreach (char[] pattern; patterns) { - if (!inPattern(c, pattern)) - { result = 0; - break; - } - result = 1; + if (!inPattern(c, pattern)) + { result = 0; + break; + } + result = 1; } return result; } @@ -2870,7 +2870,7 @@ size_t countchars(char[] s, char[] pattern) foreach (dchar c; s) { - count += inPattern(c, pattern); + count += inPattern(c, pattern); } return count; } @@ -2901,22 +2901,22 @@ char[] removechars(char[] s, char[] pattern) foreach (size_t i, dchar c; s) { - if (!inPattern(c, pattern)) - { - if (changed) - { - if (r is s) - r = s[0 .. j].dup; - std.utf.encode(r, c); - } - } - else if (!changed) - { changed = 1; - j = i; - } + if (!inPattern(c, pattern)) + { + if (changed) + { + if (r is s) + r = s[0 .. j].dup; + std.utf.encode(r, c); + } + } + else if (!changed) + { changed = 1; + j = i; + } } if (changed && r is s) - r = s[0 .. j].dup; + r = s[0 .. j].dup; return r; } @@ -2952,36 +2952,36 @@ char[] squeeze(char[] s, char[] pattern = null) foreach (size_t i, dchar c; s) { - if (run && lastc == c) - { - changed = true; - } - else if (pattern is null || inPattern(c, pattern)) - { - run = 1; - if (changed) - { if (r is s) - r = s[0 .. lasti].dup; - std.utf.encode(r, c); - } - else - lasti = i + std.utf.stride(s, i); - lastc = c; - } - else - { - run = 0; - if (changed) - { if (r is s) - r = s[0 .. lasti].dup; - std.utf.encode(r, c); - } - } + if (run && lastc == c) + { + changed = true; + } + else if (pattern is null || inPattern(c, pattern)) + { + run = 1; + if (changed) + { if (r is s) + r = s[0 .. lasti].dup; + std.utf.encode(r, c); + } + else + lasti = i + std.utf.stride(s, i); + lastc = c; + } + else + { + run = 0; + if (changed) + { if (r is s) + r = s[0 .. lasti].dup; + std.utf.encode(r, c); + } + } } if (changed) { - if (r is s) - r = s[0 .. lasti]; + if (r is s) + r = s[0 .. lasti]; } return r; } @@ -3000,7 +3000,7 @@ unittest assert(r is s); s = "xyzz"; r = squeeze(s); - assert(r.ptr == s.ptr); // should just be a slice + assert(r.ptr == s.ptr); // should just be a slice r = squeeze("hello goodbyee", "oe"); assert(r == "hello godbye"); } @@ -3017,41 +3017,41 @@ char[] succ(char[] s) { if (s.length && isalnum(s[length - 1])) { - char[] r = s.dup; - size_t i = r.length - 1; + char[] r = s.dup; + size_t i = r.length - 1; - while (1) - { dchar c = s[i]; - dchar carry; + while (1) + { dchar c = s[i]; + dchar carry; - switch (c) - { - case '9': - c = '0'; - carry = '1'; - goto Lcarry; - case 'z': - case 'Z': - c -= 'Z' - 'A'; - carry = c; - Lcarry: - r[i] = cast(char)c; - if (i == 0) - { - char[] t = new char[r.length + 1]; - t[0] = cast(char)carry; - t[1 .. length] = r[]; - return t; - } - i--; - break; + switch (c) + { + case '9': + c = '0'; + carry = '1'; + goto Lcarry; + case 'z': + case 'Z': + c -= 'Z' - 'A'; + carry = c; + Lcarry: + r[i] = cast(char)c; + if (i == 0) + { + char[] t = new char[r.length + 1]; + t[0] = cast(char)carry; + t[1 .. length] = r[]; + return t; + } + i--; + break; - default: - if (std.ctype.isalnum(c)) - r[i]++; - return r; - } - } + default: + if (std.ctype.isalnum(c)) + r[i]++; + return r; + } + } } return s; } @@ -3082,29 +3082,29 @@ unittest * with corresponding characters in to[] and returns the resulting * string. * Params: - * modifiers = a string of modifier characters + * modifiers = a string of modifier characters * Modifiers: - -
Modifier Description -
c Complement the list of characters in from[] -
d Removes matching characters with no corresponding replacement in to[] -
s Removes adjacent duplicates in the replaced characters -
+ +
Modifier Description +
c Complement the list of characters in from[] +
d Removes matching characters with no corresponding replacement in to[] +
s Removes adjacent duplicates in the replaced characters +
- If modifier d is present, then the number of characters - in to[] may be only 0 or 1. + If modifier d is present, then the number of characters + in to[] may be only 0 or 1. - If modifier d is not present and to[] is null, - then to[] is taken _to be the same as from[]. + If modifier d is not present and to[] is null, + then to[] is taken _to be the same as from[]. - If modifier d is not present and to[] is shorter - than from[], then to[] is extended by replicating the - last character in to[]. + If modifier d is not present and to[] is shorter + than from[], then to[] is extended by replicating the + last character in to[]. - Both from[] and to[] may contain ranges using the - - character, for example a-d is synonymous with abcd. - Neither accept a leading ^ as meaning the complement of - the string (use the c modifier for that). + Both from[] and to[] may contain ranges using the - + character, for example a-d is synonymous with abcd. + Neither accept a leading ^ as meaning the complement of + the string (use the c modifier for that). */ char[] tr(char[] str, char[] from, char[] to, char[] modifiers = null) @@ -3115,17 +3115,17 @@ char[] tr(char[] str, char[] from, char[] to, char[] modifiers = null) foreach (char c; modifiers) { - switch (c) - { - case 'c': mod_c = 1; break; // complement - case 'd': mod_d = 1; break; // delete unreplaced chars - case 's': mod_s = 1; break; // squeeze duplicated replaced chars - default: assert(0); - } + switch (c) + { + case 'c': mod_c = 1; break; // complement + case 'd': mod_d = 1; break; // delete unreplaced chars + case 's': mod_s = 1; break; // squeeze duplicated replaced chars + default: assert(0); + } } if (to is null && !mod_d) - to = from; + to = from; char[] result = new char[str.length]; result.length = 0; @@ -3133,87 +3133,87 @@ char[] tr(char[] str, char[] from, char[] to, char[] modifiers = null) dchar lastc; foreach (dchar c; str) - { dchar lastf; - dchar lastt; - dchar newc; - int n = 0; + { dchar lastf; + dchar lastt; + dchar newc; + int n = 0; - for (size_t i = 0; i < from.length; ) - { - dchar f = std.utf.decode(from, i); - //writefln("\tf = '%s', c = '%s', lastf = '%x', '%x', i = %d, %d", f, c, lastf, dchar.init, i, from.length); - if (f == '-' && lastf != dchar.init && i < from.length) - { - dchar nextf = std.utf.decode(from, i); - //writefln("\tlastf = '%s', c = '%s', nextf = '%s'", lastf, c, nextf); - if (lastf <= c && c <= nextf) - { - n += c - lastf - 1; - if (mod_c) - goto Lnotfound; - goto Lfound; - } - n += nextf - lastf; - lastf = lastf.init; - continue; - } + for (size_t i = 0; i < from.length; ) + { + dchar f = std.utf.decode(from, i); + //writefln("\tf = '%s', c = '%s', lastf = '%x', '%x', i = %d, %d", f, c, lastf, dchar.init, i, from.length); + if (f == '-' && lastf != dchar.init && i < from.length) + { + dchar nextf = std.utf.decode(from, i); + //writefln("\tlastf = '%s', c = '%s', nextf = '%s'", lastf, c, nextf); + if (lastf <= c && c <= nextf) + { + n += c - lastf - 1; + if (mod_c) + goto Lnotfound; + goto Lfound; + } + n += nextf - lastf; + lastf = lastf.init; + continue; + } - if (c == f) - { if (mod_c) - goto Lnotfound; - goto Lfound; - } - lastf = f; - n++; - } - if (!mod_c) - goto Lnotfound; - n = 0; // consider it 'found' at position 0 + if (c == f) + { if (mod_c) + goto Lnotfound; + goto Lfound; + } + lastf = f; + n++; + } + if (!mod_c) + goto Lnotfound; + n = 0; // consider it 'found' at position 0 Lfound: - // Find the nth character in to[] - //writefln("\tc = '%s', n = %d", c, n); - dchar nextt; - for (size_t i = 0; i < to.length; ) - { dchar t = std.utf.decode(to, i); - if (t == '-' && lastt != dchar.init && i < to.length) - { - nextt = std.utf.decode(to, i); - //writefln("\tlastt = '%s', c = '%s', nextt = '%s', n = %d", lastt, c, nextt, n); - n -= nextt - lastt; - if (n < 0) - { - newc = nextt + n + 1; - goto Lnewc; - } - lastt = dchar.init; - continue; - } - if (n == 0) - { newc = t; - goto Lnewc; - } - lastt = t; - nextt = t; - n--; - } - if (mod_d) - continue; - newc = nextt; + // Find the nth character in to[] + //writefln("\tc = '%s', n = %d", c, n); + dchar nextt; + for (size_t i = 0; i < to.length; ) + { dchar t = std.utf.decode(to, i); + if (t == '-' && lastt != dchar.init && i < to.length) + { + nextt = std.utf.decode(to, i); + //writefln("\tlastt = '%s', c = '%s', nextt = '%s', n = %d", lastt, c, nextt, n); + n -= nextt - lastt; + if (n < 0) + { + newc = nextt + n + 1; + goto Lnewc; + } + lastt = dchar.init; + continue; + } + if (n == 0) + { newc = t; + goto Lnewc; + } + lastt = t; + nextt = t; + n--; + } + if (mod_d) + continue; + newc = nextt; Lnewc: - if (mod_s && m && newc == lastc) - continue; - std.utf.encode(result, newc); - m = 1; - lastc = newc; - continue; + if (mod_s && m && newc == lastc) + continue; + std.utf.encode(result, newc); + m = 1; + lastc = newc; + continue; Lnotfound: - std.utf.encode(result, c); - lastc = c; - m = 0; + std.utf.encode(result, c); + lastc = c; + m = 0; } return result; } @@ -3265,7 +3265,7 @@ unittest * Author : David L. 'SpottedTiger' Davis * Date Created : 31.May.05 Compiled and Tested with dmd v0.125 * Date Modified : 01.Jun.05 Modified the function to handle the - * : imaginary and complex float-point + * : imaginary and complex float-point * : datatypes. * : * Licence : Public Domain / Contributed to Digital Mars @@ -3286,7 +3286,7 @@ unittest * or [nan|nani|inf|-inf] * * examples: +123., -123.01, 123.3e-10f, 123.3e-10fi, 123.3e-10L - * + * * (for cfloat, cdouble, and creal) * ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][+] * [digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] @@ -3294,15 +3294,15 @@ unittest * * examples: nan, -123e-1+456.9e-10Li, +123e+10+456i, 123+456 * - * [in] bool bAllowSep - * False by default, but when set to true it will accept the - * separator characters "," and "_" within the string, but these - * characters should be stripped from the string before using any - * of the conversion functions like toInt(), toFloat(), and etc + * [in] bool bAllowSep + * False by default, but when set to true it will accept the + * separator characters "," and "_" within the string, but these + * characters should be stripped from the string before using any + * of the conversion functions like toInt(), toFloat(), and etc * else an error will occur. * - * Also please note, that no spaces are allowed within the string - * anywhere whether it's a leading, trailing, or embedded space(s), + * Also please note, that no spaces are allowed within the string + * anywhere whether it's a leading, trailing, or embedded space(s), * thus they too must be stripped from the string before using this * function, or any of the conversion functions. */ @@ -3313,7 +3313,7 @@ final bool isNumeric(in char[] s, in bool bAllowSep = false) bool bDecimalPoint = false; bool bExponent = false; bool bComplex = false; - char[] sx = std.string.tolower(s); + char[] sx = std.string.tolower(s); int j = 0; char c; @@ -3321,32 +3321,32 @@ final bool isNumeric(in char[] s, in bool bAllowSep = false) // Empty string, return false if (iLen == 0) return false; - + // Check for NaN (Not a Number) if (sx == "nan" || sx == "nani" || sx == "nan+nani") return true; - + // Check for Infinity if (sx == "inf" || sx == "-inf") return true; - - // A sign is allowed only in the 1st character + + // A sign is allowed only in the 1st character if (sx[0] == '-' || sx[0] == '+') j++; - + for (int i = j; i < iLen; i++) { c = sx[i]; - - // Digits are good, continue checking + + // Digits are good, continue checking // with the next character... ;) - if (c >= '0' && c <= '9') + if (c >= '0' && c <= '9') continue; - // Check for the complex type, and if found - // reset the flags for checking the 2nd number. + // Check for the complex type, and if found + // reset the flags for checking the 2nd number. else if (c == '+') - if (i > 0) + if (i > 0) { bDecimalPoint = false; bExponent = false; @@ -3355,97 +3355,97 @@ final bool isNumeric(in char[] s, in bool bAllowSep = false) } else return false; - - // Allow only one exponent per number - else if (c == 'e') + + // Allow only one exponent per number + else if (c == 'e') { // A 2nd exponent found, return not a number if (bExponent) return false; - + if (i + 1 < iLen) { - // Look forward for the sign, and if + // Look forward for the sign, and if // missing then this is not a number. if (sx[i + 1] != '-' && sx[i + 1] != '+') return false; else { bExponent = true; - i++; - } - } + i++; + } + } else // Ending in "E", return not a number - return false; - } + return false; + } // Allow only one decimal point per number to be used else if (c == '.' ) { // A 2nd decimal point found, return not a number if (bDecimalPoint) return false; - + bDecimalPoint = true; continue; - } + } // Check for ending literal characters: "f,u,l,i,ul,fi,li", // and wheater they're being used with the correct datatype. else if (i == iLen - 2) { // Integer Whole Number - if (sx[i..iLen] == "ul" && + if (sx[i..iLen] == "ul" && (!bDecimalPoint && !bExponent && !bComplex)) return true; // Floating-Point Number else if ((sx[i..iLen] == "fi" || sx[i..iLen] == "li") && (bDecimalPoint || bExponent || bComplex)) return true; - else if (sx[i..iLen] == "ul" && + else if (sx[i..iLen] == "ul" && (bDecimalPoint || bExponent || bComplex)) - return false; + return false; // Could be a Integer or a Float, thus - // all these suffixes are valid for both - else if (sx[i..iLen] == "ul" || - sx[i..iLen] == "fi" || + // all these suffixes are valid for both + else if (sx[i..iLen] == "ul" || + sx[i..iLen] == "fi" || sx[i..iLen] == "li") return true; - else + else return false; } else if (i == iLen - 1) { // Integer Whole Number - if ((c == 'u' || c == 'l') && + if ((c == 'u' || c == 'l') && (!bDecimalPoint && !bExponent && !bComplex)) return true; - // Check to see if the last character in the string + // Check to see if the last character in the string // is the required 'i' character else if (bComplex) if (c == 'i') return true; - else - return false; + else + return false; // Floating-Point Number else if ((c == 'l' || c == 'f' || c == 'i') && (bDecimalPoint || bExponent)) return true; - // Could be a Integer or a Float, thus - // all these suffixes are valid for both + // Could be a Integer or a Float, thus + // all these suffixes are valid for both else if (c == 'l' || c == 'f' || c == 'i') return true; else return false; } else - // Check if separators are allow + // Check if separators are allow // to be in the numeric string if (bAllowSep == true && (c == '_' || c == ',')) continue; - else - return false; - } - + else + return false; + } + return true; } @@ -3455,7 +3455,7 @@ bool isNumeric(...) return isNumeric(_arguments, _argptr); } -/// Check only the first parameter, all others will be ignored. +/// Check only the first parameter, all others will be ignored. bool isNumeric(TypeInfo[] _arguments, va_list _argptr) { char[] s = ""; @@ -3474,29 +3474,29 @@ bool isNumeric(TypeInfo[] _arguments, va_list _argptr) return isNumeric(std.utf.toUTF8(va_arg!(dchar[])(_argptr))); else if (_arguments[0] == typeid(real)) return true; - else if (_arguments[0] == typeid(double)) - return true; - else if (_arguments[0] == typeid(float)) - return true; - else if (_arguments[0] == typeid(ulong)) - return true; - else if (_arguments[0] == typeid(long)) - return true; - else if (_arguments[0] == typeid(uint)) - return true; - else if (_arguments[0] == typeid(int)) - return true; - else if (_arguments[0] == typeid(ushort)) - return true; - else if (_arguments[0] == typeid(short)) - return true; - else if (_arguments[0] == typeid(ubyte)) + else if (_arguments[0] == typeid(double)) + return true; + else if (_arguments[0] == typeid(float)) + return true; + else if (_arguments[0] == typeid(ulong)) + return true; + else if (_arguments[0] == typeid(long)) + return true; + else if (_arguments[0] == typeid(uint)) + return true; + else if (_arguments[0] == typeid(int)) + return true; + else if (_arguments[0] == typeid(ushort)) + return true; + else if (_arguments[0] == typeid(short)) + return true; + else if (_arguments[0] == typeid(ubyte)) { s.length = 1; s[0]= va_arg!(ubyte)(_argptr); return isNumeric(cast(char[])s); } - else if (_arguments[0] == typeid(byte)) + else if (_arguments[0] == typeid(byte)) { s.length = 1; s[0] = va_arg!(char)(_argptr); @@ -3504,16 +3504,16 @@ bool isNumeric(TypeInfo[] _arguments, va_list _argptr) } else if (_arguments[0] == typeid(ireal)) return true; - else if (_arguments[0] == typeid(idouble)) - return true; - else if (_arguments[0] == typeid(ifloat)) - return true; + else if (_arguments[0] == typeid(idouble)) + return true; + else if (_arguments[0] == typeid(ifloat)) + return true; else if (_arguments[0] == typeid(creal)) return true; - else if (_arguments[0] == typeid(cdouble)) - return true; - else if (_arguments[0] == typeid(cfloat)) - return true; + else if (_arguments[0] == typeid(cdouble)) + return true; + else if (_arguments[0] == typeid(cfloat)) + return true; else if (_arguments[0] == typeid(char)) { s.length = 1; @@ -3527,17 +3527,17 @@ bool isNumeric(TypeInfo[] _arguments, va_list _argptr) return isNumeric(std.utf.toUTF8(ws)); } else if (_arguments[0] == typeid(dchar)) - { + { ds.length = 1; ds[0] = va_arg!(dchar)(_argptr); return isNumeric(std.utf.toUTF8(ds)); } - //else if (_arguments[0] == typeid(cent)) - // return true; - //else if (_arguments[0] == typeid(ucent)) - // return true; - else - return false; + //else if (_arguments[0] == typeid(cent)) + // return true; + //else if (_arguments[0] == typeid(ucent)) + // return true; + else + return false; } unittest @@ -3557,12 +3557,12 @@ unittest assert(isNumeric(" 12.356") == false ); assert(isNumeric("123 5.6") == false ); assert(isNumeric("1233E-1+1.0e-1i") == true ); - + assert(isNumeric("123.00E-5+1234.45E-12Li") == true); assert(isNumeric("123.00e-5+1234.45E-12iL") == false); assert(isNumeric("123.00e-5+1234.45e-12uL") == false); assert(isNumeric("123.00E-5+1234.45e-12lu") == false); - + assert(isNumeric("123fi") == true); assert(isNumeric("123li") == true); assert(isNumeric("--123L") == false); @@ -3604,22 +3604,22 @@ unittest * of names. * * Params: - * string = String to convert to Soundex representation. - * buffer = Optional 4 char array to put the resulting Soundex - * characters into. If null, the return value - * buffer will be allocated on the heap. + * string = String to convert to Soundex representation. + * buffer = Optional 4 char array to put the resulting Soundex + * characters into. If null, the return value + * buffer will be allocated on the heap. * Returns: - * The four character array with the Soundex result in it. - * Returns null if there is no Soundex representation for the string. + * The four character array with the Soundex result in it. + * Returns null if there is no Soundex representation for the string. * * See_Also: - * $(LINK2 http://en.wikipedia.org/wiki/Soundex, Wikipedia), - * $(LINK2 http://www.archives.gov/publications/general-info-leaflets/55.html, The Soundex Indexing System) + * $(LINK2 http://en.wikipedia.org/wiki/Soundex, Wikipedia), + * $(LINK2 http://www.archives.gov/publications/general-info-leaflets/55.html, The Soundex Indexing System) * * Bugs: - * Only works well with English names. - * There are other arguably better Soundex algorithms, - * but this one is the standard one. + * Only works well with English names. + * There are other arguably better Soundex algorithms, + * but this one is the standard one. */ char[] soundex(char[] string, char[] buffer = null) @@ -3631,10 +3631,10 @@ out (result) { if (result) { - assert(result.length == 4); - assert(result[0] >= 'A' && result[0] <= 'Z'); - foreach (char c; result[1 .. 4]) - assert(c >= '0' && c <= '6'); + assert(result.length == 4); + assert(result[0] >= 'A' && result[0] <= 'Z'); + foreach (char c; result[1 .. 4]) + assert(c >= '0' && c <= '6'); } } body @@ -3647,45 +3647,45 @@ body char lastc; foreach (char c; string) { - if (c >= 'a' && c <= 'z') - c -= 'a' - 'A'; - else if (c >= 'A' && c <= 'Z') - { - ; - } - else - { lastc = lastc.init; - continue; - } - if (b == 0) - { - if (!buffer) - buffer = new char[4]; - buffer[0] = c; - b++; - lastc = dex[c - 'A']; - } - else - { - if (c == 'H' || c == 'W') - continue; - if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') - lastc = lastc.init; - c = dex[c - 'A']; - if (c != '0' && c != lastc) - { - buffer[b] = c; - b++; - lastc = c; - } - } - if (b == 4) - goto Lret; + if (c >= 'a' && c <= 'z') + c -= 'a' - 'A'; + else if (c >= 'A' && c <= 'Z') + { + ; + } + else + { lastc = lastc.init; + continue; + } + if (b == 0) + { + if (!buffer) + buffer = new char[4]; + buffer[0] = c; + b++; + lastc = dex[c - 'A']; + } + else + { + if (c == 'H' || c == 'W') + continue; + if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') + lastc = lastc.init; + c = dex[c - 'A']; + if (c != '0' && c != lastc) + { + buffer[b] = c; + b++; + lastc = c; + } + } + if (b == 4) + goto Lret; } if (b == 0) - buffer = null; + buffer = null; else - buffer[b .. 4] = '0'; + buffer[b .. 4] = '0'; Lret: return buffer; } @@ -3746,13 +3746,13 @@ unittest * --- * import std.stdio; * import std.string; - * + * * void main() * { * static char[][] list = [ "food", "foxy" ]; - * + * * auto abbrevs = std.string.abbrev(list); - * + * * foreach (key, value; abbrevs) * { * writefln("%s => %s", key, value); @@ -3783,25 +3783,25 @@ char[][char[]] abbrev(char[][] values) char[] lv; for (size_t i = 0; i < values_length; i = nexti) - { char[] value = values[i]; + { char[] value = values[i]; - // Skip dups - for (nexti = i + 1; nexti < values_length; nexti++) - { nv = values[nexti]; - if (value != values[nexti]) - break; - } + // Skip dups + for (nexti = i + 1; nexti < values_length; nexti++) + { nv = values[nexti]; + if (value != values[nexti]) + break; + } - for (size_t j = 0; j < value.length; j += std.utf.stride(value, j)) - { char[] v = value[0 .. j]; + for (size_t j = 0; j < value.length; j += std.utf.stride(value, j)) + { char[] v = value[0 .. j]; - if ((nexti == values_length || j > nv.length || v != nv[0 .. j]) && - (lasti == values_length || j > lv.length || v != lv[0 .. j])) - result[v] = value; - } - result[value] = value; - lasti = i; - lv = value; + if ((nexti == values_length || j > nv.length || v != nv[0 .. j]) && + (lasti == values_length || j > lv.length || v != lv[0 .. j])) + result[v] = value; + } + result[value] = value; + lasti = i; + lv = value; } return result; @@ -3846,23 +3846,23 @@ size_t column(char[] string, int tabsize = 8) foreach (dchar c; string) { - switch (c) - { - case '\t': - column = (column + tabsize) / tabsize * tabsize; - break; + switch (c) + { + case '\t': + column = (column + tabsize) / tabsize * tabsize; + break; - case '\r': - case '\n': - case PS: - case LS: - column = 0; - break; + case '\r': + case '\n': + case PS: + case LS: + column = 0; + break; - default: - column++; - break; - } + default: + column++; + break; + } } return column; } @@ -3887,17 +3887,17 @@ unittest * on each line. * The last line is terminated with a \n. * Params: - * s = text string to be wrapped - * columns = maximum number of _columns in the paragraph - * firstindent = string used to _indent first line of the paragraph - * indent = string to use to _indent following lines of the paragraph - * tabsize = column spacing of tabs + * s = text string to be wrapped + * columns = maximum number of _columns in the paragraph + * firstindent = string used to _indent first line of the paragraph + * indent = string to use to _indent following lines of the paragraph + * tabsize = column spacing of tabs * Returns: - * The resulting paragraph. + * The resulting paragraph. */ char[] wrap(char[] s, int columns = 80, char[] firstindent = null, - char[] indent = null, int tabsize = 8) + char[] indent = null, int tabsize = 8) { char[] result; int col; @@ -3912,50 +3912,50 @@ char[] wrap(char[] s, int columns = 80, char[] firstindent = null, col = column(result, tabsize); foreach (size_t i, dchar c; s) { - if (iswhite(c)) - { - if (inword) - { - if (first) - { - ; - } - else if (col + 1 + (i - wordstart) > columns) - { - result ~= '\n'; - result ~= indent; - col = column(indent, tabsize); - } - else - { result ~= ' '; - col += 1; - } - result ~= s[wordstart .. i]; - col += i - wordstart; - inword = false; - first = false; - } - } - else - { - if (!inword) - { - wordstart = i; - inword = true; - } - } + if (iswhite(c)) + { + if (inword) + { + if (first) + { + ; + } + else if (col + 1 + (i - wordstart) > columns) + { + result ~= '\n'; + result ~= indent; + col = column(indent, tabsize); + } + else + { result ~= ' '; + col += 1; + } + result ~= s[wordstart .. i]; + col += i - wordstart; + inword = false; + first = false; + } + } + else + { + if (!inword) + { + wordstart = i; + inword = true; + } + } } if (inword) { - if (col + 1 + (s.length - wordstart) >= columns) - { - result ~= '\n'; - result ~= indent; - } - else if (result.length != firstindent.length) - result ~= ' '; - result ~= s[wordstart .. s.length]; + if (col + 1 + (s.length - wordstart) >= columns) + { + result ~= '\n'; + result ~= indent; + } + else if (result.length != firstindent.length) + result ~= ' '; + result ~= s[wordstart .. s.length]; } result ~= '\n'; @@ -3981,30 +3981,30 @@ unittest /*************************** * Does string s[] start with an email address? * Returns: - * null it does not - * char[] it does, and this is the slice of s[] that is that email address + * null it does not + * char[] it does, and this is the slice of s[] that is that email address * References: - * RFC2822 + * RFC2822 */ char[] isEmail(char[] s) { size_t i; if (!isalpha(s[0])) - goto Lno; + goto Lno; for (i = 1; 1; i++) { - if (i == s.length) - goto Lno; - auto c = s[i]; - if (isalnum(c)) - continue; - if (c == '-' || c == '_' || c == '.') - continue; - if (c != '@') - goto Lno; - i++; - break; + if (i == s.length) + goto Lno; + auto c = s[i]; + if (isalnum(c)) + continue; + if (c == '-' || c == '_' || c == '.') + continue; + if (c != '@') + goto Lno; + i++; + break; } //writefln("test1 '%s'", s[0 .. i]); @@ -4013,20 +4013,20 @@ char[] isEmail(char[] s) size_t lastdot; for (; i < s.length; i++) { - auto c = s[i]; - if (isalnum(c)) - continue; - if (c == '-' || c == '_') - continue; - if (c == '.') - { - lastdot = i; - continue; - } - break; + auto c = s[i]; + if (isalnum(c)) + continue; + if (c == '-' || c == '_') + continue; + if (c == '.') + { + lastdot = i; + continue; + } + break; } if (!lastdot || (i - lastdot != 3 && i - lastdot != 4)) - goto Lno; + goto Lno; return s[0 .. i]; @@ -4038,54 +4038,54 @@ Lno: /*************************** * Does string s[] start with a URL? * Returns: - * null it does not - * char[] it does, and this is the slice of s[] that is that URL + * null it does not + * char[] it does, and this is the slice of s[] that is that URL */ char[] isURL(char[] s) { /* Must start with one of: - * http:// - * https:// - * www. + * http:// + * https:// + * www. */ size_t i; if (s.length <= 4) - goto Lno; + goto Lno; //writefln("isURL(%s)", s); if (s.length > 7 && std.string.icmp(s[0 .. 7], "http://") == 0) - i = 7; + i = 7; else if (s.length > 8 && std.string.icmp(s[0 .. 8], "https://") == 0) - i = 8; + i = 8; // if (icmp(s[0 .. 4], "www.") == 0) -// i = 4; +// i = 4; else - goto Lno; + goto Lno; size_t lastdot; for (; i < s.length; i++) { - auto c = s[i]; - if (isalnum(c)) - continue; - if (c == '-' || c == '_' || c == '?' || - c == '=' || c == '%' || c == '&' || - c == '/' || c == '+' || c == '#' || - c == '~') - continue; - if (c == '.') - { - lastdot = i; - continue; - } - break; + auto c = s[i]; + if (isalnum(c)) + continue; + if (c == '-' || c == '_' || c == '?' || + c == '=' || c == '%' || c == '&' || + c == '/' || c == '+' || c == '#' || + c == '~') + continue; + if (c == '.') + { + lastdot = i; + continue; + } + break; } //if (!lastdot || (i - lastdot != 3 && i - lastdot != 4)) if (!lastdot) - goto Lno; + goto Lno; return s[0 .. i]; diff --git a/std/switcherr.d b/std/switcherr.d index 811b88744..f27e8d879 100644 --- a/std/switcherr.d +++ b/std/switcherr.d @@ -12,12 +12,12 @@ class SwitchError : Error this(char[] filename, uint linnum) { - this.linnum = linnum; - this.filename = filename; + this.linnum = linnum; + this.filename = filename; - char[] buffer = new char[17 + filename.length + linnum.sizeof * 3 + 1]; - int len = sprintf(buffer.ptr, "Switch Default %.*s(%u)", filename, linnum); - super(buffer[0..len]); + char[] buffer = new char[17 + filename.length + linnum.sizeof * 3 + 1]; + int len = sprintf(buffer.ptr, "Switch Default %.*s(%u)", filename, linnum); + super(buffer[0..len]); } @@ -30,7 +30,7 @@ class SwitchError : Error void print() { - printf("Switch Default %s(%u)\n", cast(char *)filename, linnum); + printf("Switch Default %s(%u)\n", cast(char *)filename, linnum); } } diff --git a/std/system.d b/std/system.d index 6d1d178ac..f82491cb6 100644 --- a/std/system.d +++ b/std/system.d @@ -5,7 +5,7 @@ * Authors: Walter Bright, http://www.digitalmars.com * License: Public Domain * Macros: - * WIKI = Phobos/StdSystem + * WIKI = Phobos/StdSystem */ @@ -17,65 +17,65 @@ const // Operating system family enum Family { - Win32 = 1, // Microsoft 32 bit Windows systems - linux, // all linux systems - OSX, - FreeBSD, - Solaris, + Win32 = 1, // Microsoft 32 bit Windows systems + linux, // all linux systems + OSX, + FreeBSD, + Solaris, } version (Win32) { - Family family = Family.Win32; + Family family = Family.Win32; } else version (linux) { - Family family = Family.linux; + Family family = Family.linux; } else version (OSX) { - Family family = Family.OSX; + Family family = Family.OSX; } else version (FreeBSD) { - Family family = Family.FreeBSD; + Family family = Family.FreeBSD; } else version (Solaris) { - Family family = Family.Solaris; + Family family = Family.Solaris; } else { - static assert(0); + static assert(0); } // More specific operating system name enum OS { - Windows95 = 1, - Windows98, - WindowsME, - WindowsNT, - Windows2000, - WindowsXP, + Windows95 = 1, + Windows98, + WindowsME, + WindowsNT, + Windows2000, + WindowsXP, - RedHatLinux, - OSX, - FreeBSD, - Solaris, + RedHatLinux, + OSX, + FreeBSD, + Solaris, } /// Byte order endianness enum Endian { - BigEndian, /// big endian byte order - LittleEndian /// little endian byte order + BigEndian, /// big endian byte order + LittleEndian /// little endian byte order } version(LittleEndian) { - /// Native system endianness + /// Native system endianness Endian endian = Endian.LittleEndian; } else diff --git a/std/thread.d b/std/thread.d index 930b8cb0a..450403e25 100644 --- a/std/thread.d +++ b/std/thread.d @@ -31,7 +31,7 @@ * It is important to use the $(B Thread) class to create and manage * threads as the garbage collector needs to know about all the threads. * Macros: - * WIKI=Phobos/StdThread + * WIKI=Phobos/StdThread */ module std.thread; @@ -51,8 +51,8 @@ extern (Windows) alias uint (*stdfp)(void *); extern (C) thread_hdl _beginthreadex(void* security, uint stack_size, - stdfp start_addr, void* arglist, uint initflag, - thread_id* thrdaddr); + stdfp start_addr, void* arglist, uint initflag, + thread_id* thrdaddr); private const uint WAIT_TIMEOUT = 258; @@ -71,7 +71,7 @@ class ThreadError : Error { this(string s) { - super("Thread error: " ~ s); + super("Thread error: " ~ s); } } @@ -81,13 +81,13 @@ class ThreadError : Error class Thread { /** - * Constructor used by classes derived from Thread that override main(). + * Constructor used by classes derived from Thread that override main(). * The optional stacksize parameter default value of 0 will cause threads * to be created with the default size for the executable - Dave Fladebo */ this(size_t stacksize = 0) { - this.stacksize = stacksize; + this.stacksize = stacksize; } /** @@ -95,9 +95,9 @@ class Thread */ this(int (*fp)(void *), void *arg, size_t stacksize = 0) { - this.fp = fp; - this.arg = arg; - this.stacksize = stacksize; + this.fp = fp; + this.arg = arg; + this.stacksize = stacksize; } /** @@ -105,8 +105,8 @@ class Thread */ this(int delegate() dg, size_t stacksize = 0) { - this.dg = dg; - this.stacksize = stacksize; + this.dg = dg; + this.stacksize = stacksize; } /** @@ -134,22 +134,22 @@ class Thread */ void start() { - synchronized (Thread.classinfo) - { - if (state != TS.INITIAL) - error("already started"); + synchronized (Thread.classinfo) + { + if (state != TS.INITIAL) + error("already started"); add_thread(); - state = TS.RUNNING; - hdl = _beginthreadex(null, cast(uint)stacksize, &threadstart, cast(void*)this, 0, &id); - if (hdl == cast(thread_hdl)0) - { - del_thread(); - state = TS.FINISHED; - error("failed to start"); - } - } + state = TS.RUNNING; + hdl = _beginthreadex(null, cast(uint)stacksize, &threadstart, cast(void*)this, 0, &id); + if (hdl == cast(thread_hdl)0) + { + del_thread(); + state = TS.FINISHED; + error("failed to start"); + } + } } /** @@ -160,11 +160,11 @@ class Thread */ int run() { - if (fp) - return fp(arg); - else if (dg) - return dg(); - assert(0); + if (fp) + return fp(arg); + else if (dg) + return dg(); + assert(0); } /***************************** @@ -175,16 +175,16 @@ class Thread */ void wait() { - if (isSelf) - error("wait on self"); - if (state != TS.FINISHED) - { DWORD dw; + if (isSelf) + error("wait on self"); + if (state != TS.FINISHED) + { DWORD dw; - dw = WaitForSingleObject(hdl, 0xFFFFFFFF); + dw = WaitForSingleObject(hdl, 0xFFFFFFFF); state = TS.FINISHED; CloseHandle(hdl); hdl = null; - } + } } /****************************** @@ -196,19 +196,19 @@ class Thread */ void wait(uint milliseconds) { - if (isSelf) - error("wait on self"); - if (state != TS.FINISHED) - { DWORD dw; + if (isSelf) + error("wait on self"); + if (state != TS.FINISHED) + { DWORD dw; - dw = WaitForSingleObject(hdl, milliseconds); - if (dw != WAIT_TIMEOUT) - { - state = TS.FINISHED; - CloseHandle(hdl); - hdl = null; - } - } + dw = WaitForSingleObject(hdl, milliseconds); + if (dw != WAIT_TIMEOUT) + { + state = TS.FINISHED; + CloseHandle(hdl); + hdl = null; + } + } } /** @@ -216,9 +216,9 @@ class Thread */ enum TS { - INITIAL, /// The thread hasn't been started yet. - RUNNING, /// The thread is running or paused. - TERMINATED, /// The thread has ended. + INITIAL, /// The thread hasn't been started yet. + RUNNING, /// The thread is running or paused. + TERMINATED, /// The thread has ended. FINISHED /// The thread has been cleaned up } @@ -227,7 +227,7 @@ class Thread */ TS getState() { - return state; + return state; } /** @@ -235,11 +235,11 @@ class Thread */ enum PRIORITY { - INCREASE, /// Increase thread priority - DECREASE, /// Decrease thread priority - IDLE, /// Assign thread low priority - CRITICAL, /// Assign thread high priority - NORMAL, + INCREASE, /// Increase thread priority + DECREASE, /// Decrease thread priority + IDLE, /// Assign thread low priority + CRITICAL, /// Assign thread high priority + NORMAL, } /** @@ -248,31 +248,31 @@ class Thread */ void setPriority(PRIORITY p) { - int nPriority; + int nPriority; - switch (p) - { - case PRIORITY.INCREASE: - nPriority = THREAD_PRIORITY_ABOVE_NORMAL; - break; - case PRIORITY.DECREASE: - nPriority = THREAD_PRIORITY_BELOW_NORMAL; - break; - case PRIORITY.IDLE: - nPriority = THREAD_PRIORITY_IDLE; - break; - case PRIORITY.CRITICAL: - nPriority = THREAD_PRIORITY_TIME_CRITICAL; - break; - case PRIORITY.NORMAL: - nPriority = THREAD_PRIORITY_NORMAL; - break; - default: - assert(0); - } + switch (p) + { + case PRIORITY.INCREASE: + nPriority = THREAD_PRIORITY_ABOVE_NORMAL; + break; + case PRIORITY.DECREASE: + nPriority = THREAD_PRIORITY_BELOW_NORMAL; + break; + case PRIORITY.IDLE: + nPriority = THREAD_PRIORITY_IDLE; + break; + case PRIORITY.CRITICAL: + nPriority = THREAD_PRIORITY_TIME_CRITICAL; + break; + case PRIORITY.NORMAL: + nPriority = THREAD_PRIORITY_NORMAL; + break; + default: + assert(0); + } - if (SetThreadPriority(hdl, nPriority) == THREAD_PRIORITY_ERROR_RETURN) - error("set priority"); + if (SetThreadPriority(hdl, nPriority) == THREAD_PRIORITY_ERROR_RETURN) + error("set priority"); } /** @@ -280,8 +280,8 @@ class Thread */ bool isSelf() { - //printf("id = %d, self = %d\n", id, pthread_self()); - return (id == GetCurrentThreadId()); + //printf("id = %d, self = %d\n", id, pthread_self()); + return (id == GetCurrentThreadId()); } /** @@ -297,7 +297,7 @@ class Thread return t; } } - return null; + return null; } /** * Returns a reference to the Thread for the thread that called the @@ -305,18 +305,18 @@ class Thread */ static Thread _getThis() { - //printf("getThis(), allThreadsDim = %d\n", allThreadsDim); + //printf("getThis(), allThreadsDim = %d\n", allThreadsDim); thread_id id = GetCurrentThreadId(); - return _getThreadById(id); + return _getThreadById(id); } static Thread getThis() { - Thread t = _getThis(); - if(t) - return t; - printf("didn't find it\n"); - assert(0); + Thread t = _getThis(); + if(t) + return t; + printf("didn't find it\n"); + assert(0); } /** @@ -324,7 +324,7 @@ class Thread */ static Thread[] getAll() { - synchronized (Thread.classinfo) return allThreads[0 .. allThreadsDim]; + synchronized (Thread.classinfo) return allThreads[0 .. allThreadsDim]; } /** @@ -332,8 +332,8 @@ class Thread */ void pause() { - if (state != TS.RUNNING || SuspendThread(hdl) == 0xFFFFFFFF) - error("cannot pause"); + if (state != TS.RUNNING || SuspendThread(hdl) == 0xFFFFFFFF) + error("cannot pause"); } /** @@ -341,8 +341,8 @@ class Thread */ void resume() { - if (state != TS.RUNNING || ResumeThread(hdl) == 0xFFFFFFFF) - error("cannot resume"); + if (state != TS.RUNNING || ResumeThread(hdl) == 0xFFFFFFFF) + error("cannot resume"); } /** @@ -354,14 +354,14 @@ class Thread { if (nthreads > 1) { - thread_id thisid = GetCurrentThreadId(); + thread_id thisid = GetCurrentThreadId(); - for (int i = 0; i < allThreadsDim; i++) - { - Thread t = allThreads[i]; - if (t && t.id != thisid && t.state == TS.RUNNING) - t.pause(); - } + for (int i = 0; i < allThreadsDim; i++) + { + Thread t = allThreads[i]; + if (t && t.id != thisid && t.state == TS.RUNNING) + t.pause(); + } } } } @@ -392,7 +392,7 @@ class Thread */ static void yield() { - Sleep(0); + Sleep(0); } /** @@ -403,10 +403,10 @@ class Thread private: static uint allThreadsDim; - static Thread[0x400] allThreads; // length matches value in C runtime + static Thread[0x400] allThreads; // length matches value in C runtime TS state; - int idx = -1; // index into allThreads[] + int idx = -1; // index into allThreads[] thread_id id; size_t stacksize = 0; @@ -417,7 +417,7 @@ class Thread void error(string msg) { - throw new ThreadError(msg); + throw new ThreadError(msg); } @@ -427,28 +427,28 @@ class Thread extern (Windows) static uint threadstart(void *p) { - Thread t = cast(Thread)p; - int result; + Thread t = cast(Thread)p; + int result; - debug (thread) printf("Starting thread %d\n", t.idx); - t.stackBottom = os_query_stackBottom(); - try - { - result = t.run(); - } - catch (Object o) - { - fprintf(stderr, "Error: %.*s\n", o.toString()); - result = 1; - } + debug (thread) printf("Starting thread %d\n", t.idx); + t.stackBottom = os_query_stackBottom(); + try + { + result = t.run(); + } + catch (Object o) + { + fprintf(stderr, "Error: %.*s\n", o.toString()); + result = 1; + } - debug (thread) printf("Ending thread %d\n", t.idx); + debug (thread) printf("Ending thread %d\n", t.idx); synchronized (Thread.classinfo) { - t.del_thread(); - t.state = TS.TERMINATED; + t.del_thread(); + t.state = TS.TERMINATED; } - return result; + return result; } /************************************** @@ -458,24 +458,24 @@ class Thread void add_thread() { - // there might be threads that already exist when attaching all existing threads, - // but still call DllMain with DLL_THREAD_ATTACH - if(_getThreadById(id)) - return; - - for (int i = 0; 1; i++) - { - if (i == allThreads.length) - error("too many threads"); - if (!allThreads[i]) - { allThreads[i] = this; - idx = i; - if (i >= allThreadsDim) - allThreadsDim = i + 1; - break; - } - } - nthreads++; + // there might be threads that already exist when attaching all existing threads, + // but still call DllMain with DLL_THREAD_ATTACH + if(_getThreadById(id)) + return; + + for (int i = 0; 1; i++) + { + if (i == allThreads.length) + error("too many threads"); + if (!allThreads[i]) + { allThreads[i] = this; + idx = i; + if (i >= allThreadsDim) + allThreadsDim = i + 1; + break; + } + } + nthreads++; } /************************************** @@ -492,7 +492,7 @@ class Thread idx = -1; while(allThreadsDim > 0 && !allThreads[allThreadsDim - 1]) - allThreadsDim--; + allThreadsDim--; } /************************************** @@ -501,8 +501,8 @@ class Thread public static void thread_init() { - assert(!allThreads[0]); - thread_attach(); + assert(!allThreads[0]); + thread_attach(); } /************************************** @@ -511,36 +511,36 @@ class Thread public static void thread_attach() { - thread_attach(GetCurrentThreadId(), Thread.getCurrentThreadHandle(), os_query_stackBottom()); + thread_attach(GetCurrentThreadId(), Thread.getCurrentThreadHandle(), os_query_stackBottom()); } public static void thread_attach(thread_id id, thread_hdl hdl, void* bottom) { - // the gc should not be touched before attaching to the thread, because - // it might interfere with threads that use the GC, but won't suspend - // this thread. So we use a Thread object created by an attached thread. - // This is not necessary for the main (first) thread, because there is no - // concurrent thread. - Thread t; - if(nextThread) - { - t = nextThread; - nextThread = null; - } - else - { - t = new Thread(); - } + // the gc should not be touched before attaching to the thread, because + // it might interfere with threads that use the GC, but won't suspend + // this thread. So we use a Thread object created by an attached thread. + // This is not necessary for the main (first) thread, because there is no + // concurrent thread. + Thread t; + if(nextThread) + { + t = nextThread; + nextThread = null; + } + else + { + t = new Thread(); + } - t.state = TS.RUNNING; - t.id = id; - t.hdl = hdl; - t.stackBottom = bottom; + t.state = TS.RUNNING; + t.id = id; + t.hdl = hdl; + t.stackBottom = bottom; - synchronized (Thread.classinfo) - t.add_thread(); + synchronized (Thread.classinfo) + t.add_thread(); - nextThread = new Thread(); + nextThread = new Thread(); } static Thread nextThread; // preallocate thread to avoid allocation before attaching @@ -551,27 +551,27 @@ class Thread public static void thread_detach() { - if(Thread t = _getThis()) - synchronized (Thread.classinfo) - t.del_thread(); + if(Thread t = _getThis()) + synchronized (Thread.classinfo) + t.del_thread(); } - + public static void thread_detach(thread_id id) { - if(Thread t = _getThreadById(id)) - synchronized (Thread.classinfo) - t.del_thread(); + if(Thread t = _getThreadById(id)) + synchronized (Thread.classinfo) + t.del_thread(); } - + static ~this() { - if (allThreadsDim) - { - CloseHandle(allThreads[0].hdl); - allThreads[0].hdl = GetCurrentThread(); - } + if (allThreadsDim) + { + CloseHandle(allThreads[0].hdl); + allThreads[0].hdl = GetCurrentThread(); + } } - + /******************************************** * Returns the handle of the current thread. * This is needed because GetCurrentThread() always returns -2 which @@ -583,19 +583,19 @@ class Thread */ static thread_hdl getCurrentThreadHandle() { - thread_hdl currentThread = GetCurrentThread(); - thread_hdl actualThreadHandle; + thread_hdl currentThread = GetCurrentThread(); + thread_hdl actualThreadHandle; - //thread_hdl currentProcess = cast(thread_hdl)-1; - thread_hdl currentProcess = GetCurrentProcess(); // http://www.digitalmars.com/drn-bin/wwwnews?D/21217 + //thread_hdl currentProcess = cast(thread_hdl)-1; + thread_hdl currentProcess = GetCurrentProcess(); // http://www.digitalmars.com/drn-bin/wwwnews?D/21217 - uint access = cast(uint)0x00000002; + uint access = cast(uint)0x00000002; - DuplicateHandle(currentProcess, currentThread, currentProcess, - &actualThreadHandle, cast(uint)0, TRUE, access); + DuplicateHandle(currentProcess, currentThread, currentProcess, + &actualThreadHandle, cast(uint)0, TRUE, access); - return actualThreadHandle; + return actualThreadHandle; } } @@ -608,9 +608,9 @@ void *os_query_stackBottom() { asm { - naked ; - mov EAX,FS:4 ; - ret ; + naked ; + mov EAX,FS:4 ; + ret ; } } @@ -633,7 +633,7 @@ class ThreadError : Error { this(string s) { - super("Thread error: " ~ s); + super("Thread error: " ~ s); } } @@ -643,26 +643,26 @@ class Thread // to be created with the default pthread size - Dave Fladebo this(size_t stacksize = 0) { - init(stacksize); + init(stacksize); } this(int (*fp)(void *), void *arg, size_t stacksize = 0) { - this.fp = fp; - this.arg = arg; - init(stacksize); + this.fp = fp; + this.arg = arg; + init(stacksize); } this(int delegate() dg, size_t stacksize = 0) { - this.dg = dg; - init(stacksize); + this.dg = dg; + init(stacksize); } ~this() { - pthread_cond_destroy(&waitCond); - pthread_mutex_destroy(&waitMtx); + pthread_cond_destroy(&waitCond); + pthread_mutex_destroy(&waitMtx); if (state != TS.FINISHED) pthread_detach(id); } @@ -677,106 +677,106 @@ class Thread void start() { - if (state != TS.INITIAL) - error("already started"); + if (state != TS.INITIAL) + error("already started"); - synchronized (Thread.classinfo) - { - for (int i = 0; 1; i++) - { - if (i == allThreads.length) - error("too many threads"); - if (!allThreads[i]) - { allThreads[i] = this; - idx = i; - if (i >= allThreadsDim) - allThreadsDim = i + 1; - break; - } - } - nthreads++; - } + synchronized (Thread.classinfo) + { + for (int i = 0; 1; i++) + { + if (i == allThreads.length) + error("too many threads"); + if (!allThreads[i]) + { allThreads[i] = this; + idx = i; + if (i >= allThreadsDim) + allThreadsDim = i + 1; + break; + } + } + nthreads++; + } - state = TS.RUNNING; - //printf("creating thread x%x\n", this); - //result = pthread_create(&id, null, &threadstart, this); - // Create with thread attributes to allow non-default stack size - Dave Fladebo - int result = pthread_create(&id, &threadAttrs, &threadstart, cast(void*)this); - if (result) - { state = TS.FINISHED; - synchronized (Thread.classinfo) allThreads[idx] = null; - idx = -1; - error("failed to start"); // BUG: should report errno - } - //printf("t = x%x, id = %d\n", this, id); - version (OSX) + state = TS.RUNNING; + //printf("creating thread x%x\n", this); + //result = pthread_create(&id, null, &threadstart, this); + // Create with thread attributes to allow non-default stack size - Dave Fladebo + int result = pthread_create(&id, &threadAttrs, &threadstart, cast(void*)this); + if (result) + { state = TS.FINISHED; + synchronized (Thread.classinfo) allThreads[idx] = null; + idx = -1; + error("failed to start"); // BUG: should report errno + } + //printf("t = x%x, id = %d\n", this, id); + version (OSX) { machid = pthread_mach_thread_np( id ); if( machid == machid.init ) error("failed to obtain machid"); - } + } } int run() { - if (fp) - return fp(arg); - else if (dg) - return dg(); - assert(0); + if (fp) + return fp(arg); + else if (dg) + return dg(); + assert(0); } void wait() { - if (isSelf) - error("wait on self"); + if (isSelf) + error("wait on self"); - if (state != TS.FINISHED) - { - void *value; + if (state != TS.FINISHED) + { + void *value; - int result = pthread_join(id, &value); + int result = pthread_join(id, &value); state = TS.FINISHED; - if (result) - error("failed to wait"); - } + if (result) + error("failed to wait"); + } } void wait(uint milliseconds) { - // Implemented for POSIX systems by Dave Fladebo - if (isSelf) - error("wait on self"); - if (state != TS.FINISHED) - { - timespec ts; - timeval tv; + // Implemented for POSIX systems by Dave Fladebo + if (isSelf) + error("wait on self"); + if (state != TS.FINISHED) + { + timespec ts; + timeval tv; - pthread_mutex_lock(&waitMtx); - gettimeofday(&tv, null); - ts.tv_sec = cast(__time_t)tv.tv_sec + cast(__time_t)(milliseconds / 1_000); - ts.tv_nsec = (tv.tv_usec * 1_000) + ((milliseconds % 1_000) * 1_000_000); - if (ts.tv_nsec > 1_000_000_000) - { - ts.tv_sec += 1; - ts.tv_nsec -= 1_000_000_000; - } - if (pthread_cond_timedwait(&waitCond, &waitMtx, &ts)) - { - int oldstate, oldtype; - pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate); - pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype); + pthread_mutex_lock(&waitMtx); + gettimeofday(&tv, null); + ts.tv_sec = cast(__time_t)tv.tv_sec + cast(__time_t)(milliseconds / 1_000); + ts.tv_nsec = (tv.tv_usec * 1_000) + ((milliseconds % 1_000) * 1_000_000); + if (ts.tv_nsec > 1_000_000_000) + { + ts.tv_sec += 1; + ts.tv_nsec -= 1_000_000_000; + } + if (pthread_cond_timedwait(&waitCond, &waitMtx, &ts)) + { + int oldstate, oldtype; + pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate); + pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype); - if (pthread_cancel(id)) // thread was not completed in the timeout period, cancel it - { - pthread_mutex_unlock(&waitMtx); - error("cannot terminate thread via timed wait"); - } + if (pthread_cancel(id)) // thread was not completed in the timeout period, cancel it + { + pthread_mutex_unlock(&waitMtx); + error("cannot terminate thread via timed wait"); + } - pthread_setcancelstate(oldstate, null); - pthread_setcanceltype(oldtype, null); + pthread_setcancelstate(oldstate, null); + pthread_setcanceltype(oldtype, null); - state = TS.TERMINATED; + state = TS.TERMINATED; synchronized (Thread.classinfo) { allThreads[idx] = null; @@ -784,72 +784,72 @@ class Thread nthreads--; } - pthread_mutex_unlock(&waitMtx); - } - else - { - pthread_mutex_unlock(&waitMtx); - wait(); // condition has been signalled as complete (see threadstart()), terminate normally - } - } + pthread_mutex_unlock(&waitMtx); + } + else + { + pthread_mutex_unlock(&waitMtx); + wait(); // condition has been signalled as complete (see threadstart()), terminate normally + } + } } enum TS { - INITIAL, // created - RUNNING, // running - TERMINATED, // execution finished + INITIAL, // created + RUNNING, // running + TERMINATED, // execution finished FINISHED // pthread_join()'ed } TS getState() { - return state; + return state; } enum PRIORITY { - INCREASE, - DECREASE, - IDLE, - CRITICAL + INCREASE, + DECREASE, + IDLE, + CRITICAL } void setPriority(PRIORITY p) { - /+ not implemented - int nPriority; + /+ not implemented + int nPriority; - switch (p) - { - case PRIORITY.INCREASE: - nPriority = THREAD_PRIORITY_ABOVE_NORMAL; - break; - case PRIORITY.DECREASE: - nPriority = THREAD_PRIORITY_BELOW_NORMAL; - break; - case PRIORITY.IDLE: - nPriority = THREAD_PRIORITY_IDLE; - break; - case PRIORITY.CRITICAL: - nPriority = THREAD_PRIORITY_TIME_CRITICAL; - break; - } + switch (p) + { + case PRIORITY.INCREASE: + nPriority = THREAD_PRIORITY_ABOVE_NORMAL; + break; + case PRIORITY.DECREASE: + nPriority = THREAD_PRIORITY_BELOW_NORMAL; + break; + case PRIORITY.IDLE: + nPriority = THREAD_PRIORITY_IDLE; + break; + case PRIORITY.CRITICAL: + nPriority = THREAD_PRIORITY_TIME_CRITICAL; + break; + } - if (SetThreadPriority(hdl, nPriority) == THREAD_PRIORITY_ERROR_RETURN) - error("set priority"); - +/ + if (SetThreadPriority(hdl, nPriority) == THREAD_PRIORITY_ERROR_RETURN) + error("set priority"); + +/ } int isSelf() { - //printf("id = %d, self = %d\n", id, pthread_self()); - return pthread_equal(pthread_self(), id); + //printf("id = %d, self = %d\n", id, pthread_self()); + return pthread_equal(pthread_self(), id); } static Thread getThis() { - //printf("getThis(), allThreadsDim = %d\n", allThreadsDim); + //printf("getThis(), allThreadsDim = %d\n", allThreadsDim); pthread_t id = pthread_self(); //printf("id = %d\n", id); for (int i = 0; i < allThreadsDim; i++) @@ -861,13 +861,13 @@ class Thread return t; } } - printf("didn't find it\n"); - assert(null); + printf("didn't find it\n"); + assert(null); } static Thread[] getAll() { - synchronized (Thread.classinfo) return allThreads[0 .. allThreadsDim]; + synchronized (Thread.classinfo) return allThreads[0 .. allThreadsDim]; } void pause() @@ -879,12 +879,12 @@ class Thread } else { - if (state == TS.RUNNING) - { - if (pthread_kill(id, SIGUSR1)) - error("cannot pause"); + if (state == TS.RUNNING) + { + if (pthread_kill(id, SIGUSR1)) + error("cannot pause"); else - sem_wait(&flagSuspend); // wait for acknowledgement + sem_wait(&flagSuspend); // wait for acknowledgement } else error("cannot pause"); @@ -900,14 +900,14 @@ class Thread } else { - if (state == TS.RUNNING) - { - if (pthread_kill(id, SIGUSR2)) - error("cannot resume"); + if (state == TS.RUNNING) + { + if (pthread_kill(id, SIGUSR2)) + error("cannot resume"); } - else - error("cannot resume"); - } + else + error("cannot resume"); + } } static void pauseAll() @@ -924,30 +924,30 @@ class Thread Thread t = allThreads[i]; if (t && !pthread_equal(thisid, t.id) && t.state == TS.RUNNING) { - version (OSX) - { - if (t.state != TS.RUNNING || thread_suspend(t.machid) != KERN_SUCCESS) - t.error("cannot pause"); - } - else - { + version (OSX) + { + if (t.state != TS.RUNNING || thread_suspend(t.machid) != KERN_SUCCESS) + t.error("cannot pause"); + } + else + { if (pthread_kill(t.id, SIGUSR1)) - t.error("cannot pause"); + t.error("cannot pause"); else - npause++; // count of paused threads - } + npause++; // count of paused threads + } } } - version (OSX) {} - else - { + version (OSX) {} + else + { // Wait for each paused thread to acknowledge while (npause--) { - sem_wait(&flagSuspend); + sem_wait(&flagSuspend); } - } + } } } } @@ -972,7 +972,7 @@ class Thread static void yield() { - sched_yield(); + sched_yield(); } static uint nthreads = 1; @@ -989,7 +989,7 @@ class Thread static sem_t flagSuspend; TS state; - int idx = -1; // index into allThreads[] + int idx = -1; // index into allThreads[] int flags = 0; pthread_attr_t threadAttrs; @@ -1003,26 +1003,26 @@ class Thread void error(string msg) { - throw new ThreadError(msg); + throw new ThreadError(msg); } void init(size_t stackSize) { - // set to default values regardless - // passing this as the 2nd arg. for pthread_create() - // w/o setting an attribute is equivalent to passing null. - pthread_attr_init(&threadAttrs); - if (stackSize > 0) - { - if (pthread_attr_setstacksize(&threadAttrs,stackSize)) - error("cannot set stack size"); - } + // set to default values regardless + // passing this as the 2nd arg. for pthread_create() + // w/o setting an attribute is equivalent to passing null. + pthread_attr_init(&threadAttrs); + if (stackSize > 0) + { + if (pthread_attr_setstacksize(&threadAttrs,stackSize)) + error("cannot set stack size"); + } - if (pthread_mutex_init(&waitMtx, null)) - error("cannot initialize wait mutex"); + if (pthread_mutex_init(&waitMtx, null)) + error("cannot initialize wait mutex"); - if (pthread_cond_init(&waitCond, null)) - error("cannot initialize wait condition"); + if (pthread_cond_init(&waitCond, null)) + error("cannot initialize wait condition"); } /************************************************ @@ -1031,42 +1031,42 @@ class Thread extern (C) static void *threadstart(void *p) { - Thread t = cast(Thread)p; - int result; + Thread t = cast(Thread)p; + int result; - debug (thread) printf("Starting thread x%x (%d)\n", t, t.idx); + debug (thread) printf("Starting thread x%x (%d)\n", t, t.idx); - // Need to set t.id here, because thread is off and running - // before pthread_create() sets it. - t.id = pthread_self(); - - version (OSX) + // Need to set t.id here, because thread is off and running + // before pthread_create() sets it. + t.id = pthread_self(); + + version (OSX) { t.machid = pthread_mach_thread_np( t.id ); - } + } - t.stackBottom = getESP(); - try - { - if(t.state == TS.RUNNING) - pthread_cond_signal(&t.waitCond); // signal the wait condition (see the timed wait function) - result = t.run(); - } - catch (Object o) - { - fprintf(stderr, "Error: %.*s\n", o.toString()); - result = 1; - } + t.stackBottom = getESP(); + try + { + if(t.state == TS.RUNNING) + pthread_cond_signal(&t.waitCond); // signal the wait condition (see the timed wait function) + result = t.run(); + } + catch (Object o) + { + fprintf(stderr, "Error: %.*s\n", o.toString()); + result = 1; + } - debug (thread) printf("Ending thread %d\n", t.idx); - t.state = TS.TERMINATED; + debug (thread) printf("Ending thread %d\n", t.idx); + t.state = TS.TERMINATED; synchronized (Thread.classinfo) { allThreads[t.idx] = null; t.idx = -1; nthreads--; } - return cast(void*)result; + return cast(void*)result; } @@ -1076,71 +1076,71 @@ class Thread public static void thread_init() { - Thread t = new Thread(); + Thread t = new Thread(); - t.state = TS.RUNNING; - t.id = pthread_self(); + t.state = TS.RUNNING; + t.id = pthread_self(); - version (none) - { - // See discussion: http://autopackage.org/forums/viewtopic.php?t=22 - static void** libc_stack_end; + version (none) + { + // See discussion: http://autopackage.org/forums/viewtopic.php?t=22 + static void** libc_stack_end; - if (libc_stack_end == libc_stack_end.init) - { - void* handle = dlopen(null, RTLD_NOW); - libc_stack_end = cast(void **)dlsym(handle, "__libc_stack_end"); - dlclose(handle); - } - t.stackBottom = *libc_stack_end; - } - else version (OSX) - { + if (libc_stack_end == libc_stack_end.init) + { + void* handle = dlopen(null, RTLD_NOW); + libc_stack_end = cast(void **)dlsym(handle, "__libc_stack_end"); + dlclose(handle); + } + t.stackBottom = *libc_stack_end; + } + else version (OSX) + { t.machid = pthread_mach_thread_np( t.id ); if( t.machid == machid.init ) t.error("failed to obtain machid"); - t.stackBottom = __osx_stack_end; - } - else - { - t.stackBottom = cast(void*)__libc_stack_end; - } + t.stackBottom = __osx_stack_end; + } + else + { + t.stackBottom = cast(void*)__libc_stack_end; + } - assert(!allThreads[0]); - allThreads[0] = t; - allThreadsDim = 1; - t.idx = 0; + assert(!allThreads[0]); + allThreads[0] = t; + allThreadsDim = 1; + t.idx = 0; version (OSX) {} else { /* Install signal handlers so we can suspend/resume threads - */ + */ - int result; - sigaction_t sigact; - result = sigfillset(&sigact.sa_mask); - if (result) - goto Lfail; - sigact.sa_handler = &pauseHandler; - sigact.sa_flags = SA_RESTART; - result = sigaction(SIGUSR1, &sigact, null); - if (result) - goto Lfail; - sigact.sa_handler = &resumeHandler; - result = sigaction(SIGUSR2, &sigact, null); - if (result) - goto Lfail; + int result; + sigaction_t sigact; + result = sigfillset(&sigact.sa_mask); + if (result) + goto Lfail; + sigact.sa_handler = &pauseHandler; + sigact.sa_flags = SA_RESTART; + result = sigaction(SIGUSR1, &sigact, null); + if (result) + goto Lfail; + sigact.sa_handler = &resumeHandler; + result = sigaction(SIGUSR2, &sigact, null); + if (result) + goto Lfail; - result = sem_init(&flagSuspend, 0, 0); - if (result) - goto Lfail; + result = sem_init(&flagSuspend, 0, 0); + if (result) + goto Lfail; } - return; + return; Lfail: - t.error("cannot initialize threads"); + t.error("cannot initialize threads"); } version (OSX) {} @@ -1151,39 +1151,39 @@ class Thread */ extern (C) static void pauseHandler(int sig) - { int result; + { int result; - // Save all registers on the stack so they'll be scanned by the GC - asm - { - pusha ; - } + // Save all registers on the stack so they'll be scanned by the GC + asm + { + pusha ; + } - assert(sig == SIGUSR1); + assert(sig == SIGUSR1); - sigset_t sigmask; - result = sigfillset(&sigmask); - assert(result == 0); - result = sigdelset(&sigmask, SIGUSR2); - assert(result == 0); + sigset_t sigmask; + result = sigfillset(&sigmask); + assert(result == 0); + result = sigdelset(&sigmask, SIGUSR2); + assert(result == 0); - Thread t = getThis(); - t.stackTop = getESP(); - t.flags &= ~1; - // Release the semaphore _after_ stackTop is set - sem_post(&flagSuspend); - while (1) - { - sigsuspend(&sigmask); // suspend until SIGUSR2 - if (t.flags & 1) // ensure it was resumeHandler() - break; - } + Thread t = getThis(); + t.stackTop = getESP(); + t.flags &= ~1; + // Release the semaphore _after_ stackTop is set + sem_post(&flagSuspend); + while (1) + { + sigsuspend(&sigmask); // suspend until SIGUSR2 + if (t.flags & 1) // ensure it was resumeHandler() + break; + } - // Restore all registers - asm - { - popa ; - } + // Restore all registers + asm + { + popa ; + } } /********************************** @@ -1192,19 +1192,19 @@ class Thread extern (C) static void resumeHandler(int sig) { - Thread t = getThis(); + Thread t = getThis(); - t.flags |= 1; + t.flags |= 1; } } public static void* getESP() { - asm - { naked ; - mov EAX,ESP ; - ret ; - } + asm + { naked ; + mov EAX,ESP ; + ret ; + } } } diff --git a/std/thread_helper.d b/std/thread_helper.d index 9353ccaa9..e5c3cb62e 100644 --- a/std/thread_helper.d +++ b/std/thread_helper.d @@ -33,7 +33,7 @@ version( Windows ) import std.c.windows.windows; import std.c.stdlib; - public import std.thread; + public import std.thread; /////////////////////////////////////////////////////////////////// @@ -43,21 +43,21 @@ version( Windows ) // abbreviated versions of these structs struct _SYSTEM_PROCESS_INFORMATION { - int NextEntryOffset; // When this entry is 0, there are no more processes to be read. - int NumberOfThreads; - int[15] fill1; - int ProcessId; - int[28] fill2; - - // SYSTEM_THREAD_INFORMATION or SYSTEM_EXTENDED_THREAD_INFORMATION structures follow. + int NextEntryOffset; // When this entry is 0, there are no more processes to be read. + int NumberOfThreads; + int[15] fill1; + int ProcessId; + int[28] fill2; + + // SYSTEM_THREAD_INFORMATION or SYSTEM_EXTENDED_THREAD_INFORMATION structures follow. } struct _SYSTEM_THREAD_INFORMATION { - int[8] fill1; - int ProcessId; - int ThreadId; - int[6] fill2; + int[8] fill1; + int ProcessId; + int ThreadId; + int[6] fill2; } alias extern(Windows) @@ -65,15 +65,15 @@ version( Windows ) const ThreadBasicInformation = 0; - struct THREAD_BASIC_INFORMATION + struct THREAD_BASIC_INFORMATION { - int ExitStatus; - void** TebBaseAddress; - int ProcessId; - int ThreadId; - int AffinityMask; - int Priority; - int BasePriority; + int ExitStatus; + void** TebBaseAddress; + int ProcessId; + int ThreadId; + int AffinityMask; + int Priority; + int BasePriority; } alias extern(Windows) @@ -83,16 +83,16 @@ version( Windows ) // support attaching to thread other than just executing void** getTEB( HANDLE hnd ) { - HANDLE nthnd = GetModuleHandleA( "NTDLL" ); - assert( nthnd, "cannot get module handle for ntdll" ); - fnNtQueryInformationThread* fn = cast(fnNtQueryInformationThread*) GetProcAddress( nthnd, "NtQueryInformationThread" ); - assert( fn, "cannot find NtQueryInformationThread in ntdll" ); + HANDLE nthnd = GetModuleHandleA( "NTDLL" ); + assert( nthnd, "cannot get module handle for ntdll" ); + fnNtQueryInformationThread* fn = cast(fnNtQueryInformationThread*) GetProcAddress( nthnd, "NtQueryInformationThread" ); + assert( fn, "cannot find NtQueryInformationThread in ntdll" ); - THREAD_BASIC_INFORMATION tbi; - int Status = (*fn)(hnd, ThreadBasicInformation, &tbi, tbi.sizeof, null); - assert(Status == 0); - - return tbi.TebBaseAddress; + THREAD_BASIC_INFORMATION tbi; + int Status = (*fn)(hnd, ThreadBasicInformation, &tbi, tbi.sizeof, null); + assert(Status == 0); + + return tbi.TebBaseAddress; } extern(Windows) @@ -105,29 +105,29 @@ version( Windows ) void** getTEB( uint id ) { - HANDLE hnd = OpenThread( THREAD_QUERY_INFORMATION, FALSE, id ); - assert( hnd, "OpenThread failed" ); + HANDLE hnd = OpenThread( THREAD_QUERY_INFORMATION, FALSE, id ); + assert( hnd, "OpenThread failed" ); - void** teb = getTEB( hnd ); - CloseHandle( hnd ); - return teb; + void** teb = getTEB( hnd ); + CloseHandle( hnd ); + return teb; } void* getThreadStackBottom( HANDLE hnd ) { - void** teb = getTEB( hnd ); - return teb[1]; + void** teb = getTEB( hnd ); + return teb[1]; } void* getThreadStackBottom( uint id ) { - void** teb = getTEB( id ); - return teb[1]; + void** teb = getTEB( id ); + return teb[1]; } HANDLE OpenThreadHandle( uint id ) { - return OpenThread( SYNCHRONIZE|THREAD_GET_CONTEXT|THREAD_QUERY_INFORMATION|THREAD_SUSPEND_RESUME, FALSE, id ); + return OpenThread( SYNCHRONIZE|THREAD_GET_CONTEXT|THREAD_QUERY_INFORMATION|THREAD_SUSPEND_RESUME, FALSE, id ); } /////////////////////////////////////////////////////////////////// @@ -135,53 +135,53 @@ version( Windows ) // using function instead of delegate here to avoid allocating closure bool enumProcessThreads( uint procid, bool function( uint id, void* context ) dg, void* context ) { - HANDLE hnd = GetModuleHandleA( "NTDLL" ); - fnNtQuerySystemInformation* fn = cast(fnNtQuerySystemInformation*) GetProcAddress( hnd, "NtQuerySystemInformation" ); - if( !fn ) - return false; + HANDLE hnd = GetModuleHandleA( "NTDLL" ); + fnNtQuerySystemInformation* fn = cast(fnNtQuerySystemInformation*) GetProcAddress( hnd, "NtQuerySystemInformation" ); + if( !fn ) + return false; - uint sz = 16384; - uint retLength; - HRESULT rc; - char* buf; - for( ; ; ) - { - buf = cast(char*) std.c.stdlib.malloc(sz); - if(!buf) - return false; - rc = (*fn)( SystemProcessInformation, buf, sz, &retLength ); - if( rc != STATUS_INFO_LENGTH_MISMATCH ) - break; - std.c.stdlib.free( buf ); - sz *= 2; - } - scope(exit) std.c.stdlib.free( buf ); + uint sz = 16384; + uint retLength; + HRESULT rc; + char* buf; + for( ; ; ) + { + buf = cast(char*) std.c.stdlib.malloc(sz); + if(!buf) + return false; + rc = (*fn)( SystemProcessInformation, buf, sz, &retLength ); + if( rc != STATUS_INFO_LENGTH_MISMATCH ) + break; + std.c.stdlib.free( buf ); + sz *= 2; + } + scope(exit) std.c.stdlib.free( buf ); - if(rc != 0) - return false; + if(rc != 0) + return false; - auto pinfo = cast(_SYSTEM_PROCESS_INFORMATION*) buf; - auto pend = cast(_SYSTEM_PROCESS_INFORMATION*) (buf + retLength); - for( ; pinfo < pend; ) - { - if( pinfo.ProcessId == procid ) - { - auto tinfo = cast(_SYSTEM_THREAD_INFORMATION*)(pinfo + 1); - for( int i = 0; i < pinfo.NumberOfThreads; i++, tinfo++ ) - if( tinfo.ProcessId == procid ) - if( !dg( tinfo.ThreadId, context ) ) - return false; - } - if( pinfo.NextEntryOffset == 0 ) - break; - pinfo = cast(_SYSTEM_PROCESS_INFORMATION*) (cast(char*) pinfo + pinfo.NextEntryOffset); - } - return true; + auto pinfo = cast(_SYSTEM_PROCESS_INFORMATION*) buf; + auto pend = cast(_SYSTEM_PROCESS_INFORMATION*) (buf + retLength); + for( ; pinfo < pend; ) + { + if( pinfo.ProcessId == procid ) + { + auto tinfo = cast(_SYSTEM_THREAD_INFORMATION*)(pinfo + 1); + for( int i = 0; i < pinfo.NumberOfThreads; i++, tinfo++ ) + if( tinfo.ProcessId == procid ) + if( !dg( tinfo.ThreadId, context ) ) + return false; + } + if( pinfo.NextEntryOffset == 0 ) + break; + pinfo = cast(_SYSTEM_PROCESS_INFORMATION*) (cast(char*) pinfo + pinfo.NextEntryOffset); + } + return true; } bool enumProcessThreads( bool function( uint id, void* context ) dg, void* context ) { - return enumProcessThreads( GetCurrentProcessId(), dg, context ); + return enumProcessThreads( GetCurrentProcessId(), dg, context ); } diff --git a/std/traits.d b/std/traits.d index 74d7b5968..e0db68caf 100644 --- a/std/traits.d +++ b/std/traits.d @@ -6,15 +6,15 @@ * types at compile time. * * Macros: - * WIKI = Phobos/StdTraits + * WIKI = Phobos/StdTraits * Copyright: - * Public Domain + * Public Domain */ /* * Authors: - * Walter Bright, Digital Mars, www.digitalmars.com - * Tomasz Stachowiak (isStaticArray, isExpressionTuple) + * Walter Bright, Digital Mars, www.digitalmars.com + * Tomasz Stachowiak (isStaticArray, isExpressionTuple) */ module std.traits; @@ -38,9 +38,9 @@ template ReturnType(alias dg) template ReturnType(dg) { static if (is(dg R == return)) - alias R ReturnType; + alias R ReturnType; else - static assert(0, "argument has no return type"); + static assert(0, "argument has no return type"); } /*** @@ -63,13 +63,13 @@ template ParameterTypeTuple(alias dg) template ParameterTypeTuple(dg) { static if (is(dg P == function)) - alias P ParameterTypeTuple; + alias P ParameterTypeTuple; else static if (is(dg P == delegate)) - alias ParameterTypeTuple!(P) ParameterTypeTuple; + alias ParameterTypeTuple!(P) ParameterTypeTuple; else static if (is(dg P == P*)) - alias ParameterTypeTuple!(P) ParameterTypeTuple; + alias ParameterTypeTuple!(P) ParameterTypeTuple; else - static assert(0, "argument has no parameters"); + static assert(0, "argument has no parameters"); } @@ -83,9 +83,9 @@ template ParameterTypeTuple(dg) template FieldTypeTuple(S) { static if (is(S == struct) || is(S == class)) - alias typeof(S.tupleof) FieldTypeTuple; + alias typeof(S.tupleof) FieldTypeTuple; else - static assert(0, "argument is not struct or class"); + static assert(0, "argument is not struct or class"); } @@ -102,7 +102,7 @@ template FieldTypeTuple(S) * void main() * { * alias BaseTypeTuple!(B) TL; - * writefln(typeid(TL)); // prints: (A,I) + * writefln(typeid(TL)); // prints: (A,I) * } * --- */ @@ -110,9 +110,9 @@ template FieldTypeTuple(S) template BaseTypeTuple(A) { static if (is(A P == super)) - alias P BaseTypeTuple; + alias P BaseTypeTuple; else - static assert(0, "argument is not a class or interface"); + static assert(0, "argument is not a class or interface"); } unittest @@ -132,24 +132,24 @@ unittest template isStaticArray_impl(T) { const T inst = void; - + static if (is(typeof(T.length))) { - static if (!is(T == typeof(T.init))) - { // abuses the fact that int[5].init == int - static if (is(T == typeof(T[0])[inst.length])) - { // sanity check. this check alone isn't enough because dmd complains about dynamic arrays - const bool res = true; - } - else - const bool res = false; - } - else - const bool res = false; + static if (!is(T == typeof(T.init))) + { // abuses the fact that int[5].init == int + static if (is(T == typeof(T[0])[inst.length])) + { // sanity check. this check alone isn't enough because dmd complains about dynamic arrays + const bool res = true; + } + else + const bool res = false; + } + else + const bool res = false; } else { - const bool res = false; + const bool res = false; } } /** @@ -174,9 +174,9 @@ static assert (!isStaticArray!(int[1][])); template isExpressionTuple(T ...) { static if (is(void function(T))) - const bool isExpressionTuple = false; + const bool isExpressionTuple = false; else - const bool isExpressionTuple = true; + const bool isExpressionTuple = true; } diff --git a/std/typeinfo/ti_AC.d b/std/typeinfo/ti_AC.d index 1dfbbb1d3..11a476444 100644 --- a/std/typeinfo/ti_AC.d +++ b/std/typeinfo/ti_AC.d @@ -5,88 +5,88 @@ module std.typeinfo.ti_AC; class TypeInfo_AC : TypeInfo { hash_t getHash(void *p) - { Object[] s = *cast(Object[]*)p; - hash_t hash = 0; + { Object[] s = *cast(Object[]*)p; + hash_t hash = 0; - foreach (Object o; s) - { - if (o) - hash += o.toHash(); - } - return hash; + foreach (Object o; s) + { + if (o) + hash += o.toHash(); + } + return hash; } int equals(void *p1, void *p2) { - Object[] s1 = *cast(Object[]*)p1; - Object[] s2 = *cast(Object[]*)p2; + Object[] s1 = *cast(Object[]*)p1; + Object[] s2 = *cast(Object[]*)p2; - if (s1.length == s2.length) - { - for (size_t u = 0; u < s1.length; u++) - { Object o1 = s1[u]; - Object o2 = s2[u]; + if (s1.length == s2.length) + { + for (size_t u = 0; u < s1.length; u++) + { Object o1 = s1[u]; + Object o2 = s2[u]; - // Do not pass null's to Object.opEquals() - if (o1 is o2 || - (!(o1 is null) && !(o2 is null) && o1.opEquals(o2))) - continue; - return 0; - } - return 1; - } - return 0; + // Do not pass null's to Object.opEquals() + if (o1 is o2 || + (!(o1 is null) && !(o2 is null) && o1.opEquals(o2))) + continue; + return 0; + } + return 1; + } + return 0; } int compare(void *p1, void *p2) { - Object[] s1 = *cast(Object[]*)p1; - Object[] s2 = *cast(Object[]*)p2; - int c; + Object[] s1 = *cast(Object[]*)p1; + Object[] s2 = *cast(Object[]*)p2; + int c; - c = cast(int)s1.length - cast(int)s2.length; - if (c == 0) - { - for (size_t u = 0; u < s1.length; u++) - { Object o1 = s1[u]; - Object o2 = s2[u]; + c = cast(int)s1.length - cast(int)s2.length; + if (c == 0) + { + for (size_t u = 0; u < s1.length; u++) + { Object o1 = s1[u]; + Object o2 = s2[u]; - if (o1 is o2) - continue; + if (o1 is o2) + continue; - // Regard null references as always being "less than" - if (o1) - { - if (!o2) - { c = 1; - break; - } - c = o1.opCmp(o2); - if (c) - break; - } - else - { c = -1; - break; - } - } - } - return c; + // Regard null references as always being "less than" + if (o1) + { + if (!o2) + { c = 1; + break; + } + c = o1.opCmp(o2); + if (c) + break; + } + else + { c = -1; + break; + } + } + } + return c; } size_t tsize() { - return (Object[]).sizeof; + return (Object[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(Object); + return typeid(Object); } } diff --git a/std/typeinfo/ti_Acdouble.d b/std/typeinfo/ti_Acdouble.d index eb3baab4e..ebe3abfed 100644 --- a/std/typeinfo/ti_Acdouble.d +++ b/std/typeinfo/ti_Acdouble.d @@ -32,72 +32,72 @@ class TypeInfo_Ar : TypeInfo char[] toString() { return "cdouble[]"; } hash_t getHash(void *p) - { cdouble[] s = *cast(cdouble[]*)p; - size_t len = s.length; - cdouble *str = s.ptr; - hash_t hash = 0; + { cdouble[] s = *cast(cdouble[]*)p; + size_t len = s.length; + cdouble *str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += (cast(uint *)str)[0]; - hash += (cast(uint *)str)[1]; - hash += (cast(uint *)str)[2]; - hash += (cast(uint *)str)[3]; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += (cast(uint *)str)[0]; + hash += (cast(uint *)str)[1]; + hash += (cast(uint *)str)[2]; + hash += (cast(uint *)str)[3]; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - cdouble[] s1 = *cast(cdouble[]*)p1; - cdouble[] s2 = *cast(cdouble[]*)p2; - size_t len = s1.length; + cdouble[] s1 = *cast(cdouble[]*)p1; + cdouble[] s2 = *cast(cdouble[]*)p2; + size_t len = s1.length; - if (len != s2.length) - return 0; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_r._equals(s1[u], s2[u]); - if (c == 0) - return 0; - } - return 1; + if (len != s2.length) + return 0; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_r._equals(s1[u], s2[u]); + if (c == 0) + return 0; + } + return 1; } int compare(void *p1, void *p2) { - cdouble[] s1 = *cast(cdouble[]*)p1; - cdouble[] s2 = *cast(cdouble[]*)p2; - size_t len = s1.length; + cdouble[] s1 = *cast(cdouble[]*)p1; + cdouble[] s2 = *cast(cdouble[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_r._compare(s1[u], s2[u]); - if (c) - return c; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_r._compare(s1[u], s2[u]); + if (c) + return c; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (cdouble[]).sizeof; + return (cdouble[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(cdouble); + return typeid(cdouble); } } diff --git a/std/typeinfo/ti_Acfloat.d b/std/typeinfo/ti_Acfloat.d index def208a8a..834b8b863 100644 --- a/std/typeinfo/ti_Acfloat.d +++ b/std/typeinfo/ti_Acfloat.d @@ -32,70 +32,70 @@ class TypeInfo_Aq : TypeInfo char[] toString() { return "cfloat[]"; } hash_t getHash(void *p) - { cfloat[] s = *cast(cfloat[]*)p; - size_t len = s.length; - cfloat *str = s.ptr; - hash_t hash = 0; + { cfloat[] s = *cast(cfloat[]*)p; + size_t len = s.length; + cfloat *str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += (cast(uint *)str)[0]; - hash += (cast(uint *)str)[1]; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += (cast(uint *)str)[0]; + hash += (cast(uint *)str)[1]; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - cfloat[] s1 = *cast(cfloat[]*)p1; - cfloat[] s2 = *cast(cfloat[]*)p2; - size_t len = s1.length; + cfloat[] s1 = *cast(cfloat[]*)p1; + cfloat[] s2 = *cast(cfloat[]*)p2; + size_t len = s1.length; - if (len != s2.length) - return 0; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_q._equals(s1[u], s2[u]); - if (c == 0) - return 0; - } - return 1; + if (len != s2.length) + return 0; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_q._equals(s1[u], s2[u]); + if (c == 0) + return 0; + } + return 1; } int compare(void *p1, void *p2) { - cfloat[] s1 = *cast(cfloat[]*)p1; - cfloat[] s2 = *cast(cfloat[]*)p2; - size_t len = s1.length; + cfloat[] s1 = *cast(cfloat[]*)p1; + cfloat[] s2 = *cast(cfloat[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_q._compare(s1[u], s2[u]); - if (c) - return c; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_q._compare(s1[u], s2[u]); + if (c) + return c; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (cfloat[]).sizeof; + return (cfloat[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(cfloat); + return typeid(cfloat); } } diff --git a/std/typeinfo/ti_Acreal.d b/std/typeinfo/ti_Acreal.d index 255d7ee92..98f01e587 100644 --- a/std/typeinfo/ti_Acreal.d +++ b/std/typeinfo/ti_Acreal.d @@ -32,73 +32,73 @@ class TypeInfo_Ac : TypeInfo char[] toString() { return "creal[]"; } hash_t getHash(void *p) - { creal[] s = *cast(creal[]*)p; - size_t len = s.length; - creal *str = s.ptr; - hash_t hash = 0; + { creal[] s = *cast(creal[]*)p; + size_t len = s.length; + creal *str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += (cast(uint *)str)[0]; - hash += (cast(uint *)str)[1]; - hash += (cast(uint *)str)[2]; - hash += (cast(uint *)str)[3]; - hash += (cast(uint *)str)[4]; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += (cast(uint *)str)[0]; + hash += (cast(uint *)str)[1]; + hash += (cast(uint *)str)[2]; + hash += (cast(uint *)str)[3]; + hash += (cast(uint *)str)[4]; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - creal[] s1 = *cast(creal[]*)p1; - creal[] s2 = *cast(creal[]*)p2; - size_t len = s1.length; + creal[] s1 = *cast(creal[]*)p1; + creal[] s2 = *cast(creal[]*)p2; + size_t len = s1.length; - if (len != s2.length) - return 0; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_c._equals(s1[u], s2[u]); - if (c == 0) - return 0; - } - return 1; + if (len != s2.length) + return 0; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_c._equals(s1[u], s2[u]); + if (c == 0) + return 0; + } + return 1; } int compare(void *p1, void *p2) { - creal[] s1 = *cast(creal[]*)p1; - creal[] s2 = *cast(creal[]*)p2; - size_t len = s1.length; + creal[] s1 = *cast(creal[]*)p1; + creal[] s2 = *cast(creal[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_c._compare(s1[u], s2[u]); - if (c) - return c; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_c._compare(s1[u], s2[u]); + if (c) + return c; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (creal[]).sizeof; + return (creal[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(creal); + return typeid(creal); } } diff --git a/std/typeinfo/ti_Adouble.d b/std/typeinfo/ti_Adouble.d index 1a508a001..936dfd17c 100644 --- a/std/typeinfo/ti_Adouble.d +++ b/std/typeinfo/ti_Adouble.d @@ -32,70 +32,70 @@ class TypeInfo_Ad : TypeInfo char[] toString() { return "double[]"; } hash_t getHash(void *p) - { double[] s = *cast(double[]*)p; - size_t len = s.length; - auto str = s.ptr; - hash_t hash = 0; + { double[] s = *cast(double[]*)p; + size_t len = s.length; + auto str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += (cast(uint *)str)[0]; - hash += (cast(uint *)str)[1]; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += (cast(uint *)str)[0]; + hash += (cast(uint *)str)[1]; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - double[] s1 = *cast(double[]*)p1; - double[] s2 = *cast(double[]*)p2; - size_t len = s1.length; + double[] s1 = *cast(double[]*)p1; + double[] s2 = *cast(double[]*)p2; + size_t len = s1.length; - if (len != s2.length) - return 0; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_d._equals(s1[u], s2[u]); - if (c == 0) - return 0; - } - return 1; + if (len != s2.length) + return 0; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_d._equals(s1[u], s2[u]); + if (c == 0) + return 0; + } + return 1; } int compare(void *p1, void *p2) { - double[] s1 = *cast(double[]*)p1; - double[] s2 = *cast(double[]*)p2; - size_t len = s1.length; + double[] s1 = *cast(double[]*)p1; + double[] s2 = *cast(double[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_d._compare(s1[u], s2[u]); - if (c) - return c; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_d._compare(s1[u], s2[u]); + if (c) + return c; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (double[]).sizeof; + return (double[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(double); + return typeid(double); } } @@ -107,6 +107,6 @@ class TypeInfo_Ap : TypeInfo_Ad TypeInfo next() { - return typeid(idouble); + return typeid(idouble); } } diff --git a/std/typeinfo/ti_Afloat.d b/std/typeinfo/ti_Afloat.d index df05d7722..9b0b7dde7 100644 --- a/std/typeinfo/ti_Afloat.d +++ b/std/typeinfo/ti_Afloat.d @@ -32,69 +32,69 @@ class TypeInfo_Af : TypeInfo char[] toString() { return "float[]"; } hash_t getHash(void *p) - { float[] s = *cast(float[]*)p; - size_t len = s.length; - auto str = s.ptr; - hash_t hash = 0; + { float[] s = *cast(float[]*)p; + size_t len = s.length; + auto str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += *cast(uint *)str; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += *cast(uint *)str; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - float[] s1 = *cast(float[]*)p1; - float[] s2 = *cast(float[]*)p2; - size_t len = s1.length; + float[] s1 = *cast(float[]*)p1; + float[] s2 = *cast(float[]*)p2; + size_t len = s1.length; - if (len != s2.length) - return 0; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_f._equals(s1[u], s2[u]); - if (c == 0) - return 0; - } - return 1; + if (len != s2.length) + return 0; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_f._equals(s1[u], s2[u]); + if (c == 0) + return 0; + } + return 1; } int compare(void *p1, void *p2) { - float[] s1 = *cast(float[]*)p1; - float[] s2 = *cast(float[]*)p2; - size_t len = s1.length; + float[] s1 = *cast(float[]*)p1; + float[] s2 = *cast(float[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_f._compare(s1[u], s2[u]); - if (c) - return c; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_f._compare(s1[u], s2[u]); + if (c) + return c; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (float[]).sizeof; + return (float[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(float); + return typeid(float); } } @@ -106,6 +106,6 @@ class TypeInfo_Ao : TypeInfo_Af TypeInfo next() { - return typeid(ifloat); + return typeid(ifloat); } } diff --git a/std/typeinfo/ti_Ag.d b/std/typeinfo/ti_Ag.d index 2b0ba4e47..d7e7ddaaa 100644 --- a/std/typeinfo/ti_Ag.d +++ b/std/typeinfo/ti_Ag.d @@ -11,83 +11,83 @@ class TypeInfo_Ag : TypeInfo char[] toString() { return "byte[]"; } hash_t getHash(void *p) - { byte[] s = *cast(byte[]*)p; - size_t len = s.length; - byte *str = s.ptr; - hash_t hash = 0; + { byte[] s = *cast(byte[]*)p; + size_t len = s.length; + byte *str = s.ptr; + hash_t hash = 0; - while (1) - { - switch (len) - { - case 0: - return hash; + while (1) + { + switch (len) + { + case 0: + return hash; - case 1: - hash *= 9; - hash += *cast(ubyte *)str; - return hash; + case 1: + hash *= 9; + hash += *cast(ubyte *)str; + return hash; - case 2: - hash *= 9; - hash += *cast(ushort *)str; - return hash; + case 2: + hash *= 9; + hash += *cast(ushort *)str; + return hash; - case 3: - hash *= 9; - hash += (*cast(ushort *)str << 8) + - (cast(ubyte *)str)[2]; - return hash; + case 3: + hash *= 9; + hash += (*cast(ushort *)str << 8) + + (cast(ubyte *)str)[2]; + return hash; - default: - hash *= 9; - hash += *cast(uint *)str; - str += 4; - len -= 4; - break; - } - } + default: + hash *= 9; + hash += *cast(uint *)str; + str += 4; + len -= 4; + break; + } + } } int equals(void *p1, void *p2) { - byte[] s1 = *cast(byte[]*)p1; - byte[] s2 = *cast(byte[]*)p2; + byte[] s1 = *cast(byte[]*)p1; + byte[] s2 = *cast(byte[]*)p2; - return s1.length == s2.length && - memcmp(cast(byte *)s1, cast(byte *)s2, s1.length) == 0; + return s1.length == s2.length && + memcmp(cast(byte *)s1, cast(byte *)s2, s1.length) == 0; } int compare(void *p1, void *p2) { - byte[] s1 = *cast(byte[]*)p1; - byte[] s2 = *cast(byte[]*)p2; - size_t len = s1.length; + byte[] s1 = *cast(byte[]*)p1; + byte[] s2 = *cast(byte[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int result = s1[u] - s2[u]; - if (result) - return result; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int result = s1[u] - s2[u]; + if (result) + return result; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (byte[]).sizeof; + return (byte[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(byte); + return typeid(byte); } } @@ -100,15 +100,15 @@ class TypeInfo_Ah : TypeInfo_Ag int compare(void *p1, void *p2) { - char[] s1 = *cast(char[]*)p1; - char[] s2 = *cast(char[]*)p2; + char[] s1 = *cast(char[]*)p1; + char[] s2 = *cast(char[]*)p2; - return std.string.cmp(s1, s2); + return std.string.cmp(s1, s2); } TypeInfo next() { - return typeid(ubyte); + return typeid(ubyte); } } @@ -120,7 +120,7 @@ class TypeInfo_Av : TypeInfo_Ah TypeInfo next() { - return typeid(void); + return typeid(void); } } @@ -132,7 +132,7 @@ class TypeInfo_Ab : TypeInfo_Ah TypeInfo next() { - return typeid(bool); + return typeid(bool); } } @@ -143,57 +143,57 @@ class TypeInfo_Aa : TypeInfo_Ag char[] toString() { return "char[]"; } hash_t getHash(void *p) - { char[] s = *cast(char[]*)p; - hash_t hash = 0; + { char[] s = *cast(char[]*)p; + hash_t hash = 0; version (all) { - foreach (char c; s) - hash = hash * 11 + c; + foreach (char c; s) + hash = hash * 11 + c; } else { - size_t len = s.length; - char *str = s; + size_t len = s.length; + char *str = s; - while (1) - { - switch (len) - { - case 0: - return hash; + while (1) + { + switch (len) + { + case 0: + return hash; - case 1: - hash *= 9; - hash += *cast(ubyte *)str; - return hash; + case 1: + hash *= 9; + hash += *cast(ubyte *)str; + return hash; - case 2: - hash *= 9; - hash += *cast(ushort *)str; - return hash; + case 2: + hash *= 9; + hash += *cast(ushort *)str; + return hash; - case 3: - hash *= 9; - hash += (*cast(ushort *)str << 8) + - (cast(ubyte *)str)[2]; - return hash; + case 3: + hash *= 9; + hash += (*cast(ushort *)str << 8) + + (cast(ubyte *)str)[2]; + return hash; - default: - hash *= 9; - hash += *cast(uint *)str; - str += 4; - len -= 4; - break; - } - } + default: + hash *= 9; + hash += *cast(uint *)str; + str += 4; + len -= 4; + break; + } + } } - return hash; + return hash; } TypeInfo next() { - return typeid(char); + return typeid(char); } } diff --git a/std/typeinfo/ti_Aint.d b/std/typeinfo/ti_Aint.d index 22ba95e01..3e73ec065 100644 --- a/std/typeinfo/ti_Aint.d +++ b/std/typeinfo/ti_Aint.d @@ -10,61 +10,61 @@ class TypeInfo_Ai : TypeInfo char[] toString() { return "int[]"; } hash_t getHash(void *p) - { int[] s = *cast(int[]*)p; - auto len = s.length; - auto str = s.ptr; - hash_t hash = 0; + { int[] s = *cast(int[]*)p; + auto len = s.length; + auto str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += *cast(uint *)str; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += *cast(uint *)str; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - int[] s1 = *cast(int[]*)p1; - int[] s2 = *cast(int[]*)p2; + int[] s1 = *cast(int[]*)p1; + int[] s2 = *cast(int[]*)p2; - return s1.length == s2.length && - memcmp(cast(void *)s1, cast(void *)s2, s1.length * int.sizeof) == 0; + return s1.length == s2.length && + memcmp(cast(void *)s1, cast(void *)s2, s1.length * int.sizeof) == 0; } int compare(void *p1, void *p2) { - int[] s1 = *cast(int[]*)p1; - int[] s2 = *cast(int[]*)p2; - size_t len = s1.length; + int[] s1 = *cast(int[]*)p1; + int[] s2 = *cast(int[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int result = s1[u] - s2[u]; - if (result) - return result; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int result = s1[u] - s2[u]; + if (result) + return result; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (int[]).sizeof; + return (int[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(int); + return typeid(int); } } @@ -76,24 +76,24 @@ class TypeInfo_Ak : TypeInfo_Ai int compare(void *p1, void *p2) { - uint[] s1 = *cast(uint[]*)p1; - uint[] s2 = *cast(uint[]*)p2; - size_t len = s1.length; + uint[] s1 = *cast(uint[]*)p1; + uint[] s2 = *cast(uint[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int result = s1[u] - s2[u]; - if (result) - return result; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int result = s1[u] - s2[u]; + if (result) + return result; + } + return cast(int)s1.length - cast(int)s2.length; } TypeInfo next() { - return typeid(uint); + return typeid(uint); } } @@ -105,7 +105,7 @@ class TypeInfo_Aw : TypeInfo_Ak TypeInfo next() { - return typeid(dchar); + return typeid(dchar); } } diff --git a/std/typeinfo/ti_Along.d b/std/typeinfo/ti_Along.d index 52ce5fbfe..4ce707424 100644 --- a/std/typeinfo/ti_Along.d +++ b/std/typeinfo/ti_Along.d @@ -10,62 +10,62 @@ class TypeInfo_Al : TypeInfo char[] toString() { return "long[]"; } hash_t getHash(void *p) - { long[] s = *cast(long[]*)p; - size_t len = s.length; - auto str = s.ptr; - hash_t hash = 0; + { long[] s = *cast(long[]*)p; + size_t len = s.length; + auto str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += *cast(uint *)str + *(cast(uint *)str + 1); - str++; - len--; - } + while (len) + { + hash *= 9; + hash += *cast(uint *)str + *(cast(uint *)str + 1); + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - long[] s1 = *cast(long[]*)p1; - long[] s2 = *cast(long[]*)p2; + long[] s1 = *cast(long[]*)p1; + long[] s2 = *cast(long[]*)p2; - return s1.length == s2.length && - memcmp(cast(void *)s1, cast(void *)s2, s1.length * long.sizeof) == 0; + return s1.length == s2.length && + memcmp(cast(void *)s1, cast(void *)s2, s1.length * long.sizeof) == 0; } int compare(void *p1, void *p2) { - long[] s1 = *cast(long[]*)p1; - long[] s2 = *cast(long[]*)p2; - size_t len = s1.length; + long[] s1 = *cast(long[]*)p1; + long[] s2 = *cast(long[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - if (s1[u] < s2[u]) - return -1; - else if (s1[u] > s2[u]) - return 1; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + if (s1[u] < s2[u]) + return -1; + else if (s1[u] > s2[u]) + return 1; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (long[]).sizeof; + return (long[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(long); + return typeid(long); } } @@ -78,25 +78,25 @@ class TypeInfo_Am : TypeInfo_Al int compare(void *p1, void *p2) { - ulong[] s1 = *cast(ulong[]*)p1; - ulong[] s2 = *cast(ulong[]*)p2; - size_t len = s1.length; + ulong[] s1 = *cast(ulong[]*)p1; + ulong[] s2 = *cast(ulong[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - if (s1[u] < s2[u]) - return -1; - else if (s1[u] > s2[u]) - return 1; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + if (s1[u] < s2[u]) + return -1; + else if (s1[u] > s2[u]) + return 1; + } + return cast(int)s1.length - cast(int)s2.length; } TypeInfo next() { - return typeid(ulong); + return typeid(ulong); } } diff --git a/std/typeinfo/ti_Areal.d b/std/typeinfo/ti_Areal.d index 25a9af2a0..0bff0f234 100644 --- a/std/typeinfo/ti_Areal.d +++ b/std/typeinfo/ti_Areal.d @@ -32,71 +32,71 @@ class TypeInfo_Ae : TypeInfo char[] toString() { return "real[]"; } hash_t getHash(void *p) - { real[] s = *cast(real[]*)p; - size_t len = s.length; - auto str = s.ptr; - hash_t hash = 0; + { real[] s = *cast(real[]*)p; + size_t len = s.length; + auto str = s.ptr; + hash_t hash = 0; - while (len) - { - hash *= 9; - hash += (cast(uint *)str)[0]; - hash += (cast(uint *)str)[1]; - hash += (cast(ushort *)str)[4]; - str++; - len--; - } + while (len) + { + hash *= 9; + hash += (cast(uint *)str)[0]; + hash += (cast(uint *)str)[1]; + hash += (cast(ushort *)str)[4]; + str++; + len--; + } - return hash; + return hash; } int equals(void *p1, void *p2) { - real[] s1 = *cast(real[]*)p1; - real[] s2 = *cast(real[]*)p2; - size_t len = s1.length; + real[] s1 = *cast(real[]*)p1; + real[] s2 = *cast(real[]*)p2; + size_t len = s1.length; - if (len != s2.length) - return 0; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_e._equals(s1[u], s2[u]); - if (c == 0) - return 0; - } - return 1; + if (len != s2.length) + return 0; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_e._equals(s1[u], s2[u]); + if (c == 0) + return 0; + } + return 1; } int compare(void *p1, void *p2) { - real[] s1 = *cast(real[]*)p1; - real[] s2 = *cast(real[]*)p2; - size_t len = s1.length; + real[] s1 = *cast(real[]*)p1; + real[] s2 = *cast(real[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int c = TypeInfo_e._compare(s1[u], s2[u]); - if (c) - return c; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int c = TypeInfo_e._compare(s1[u], s2[u]); + if (c) + return c; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (real[]).sizeof; + return (real[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(real); + return typeid(real); } } @@ -108,6 +108,6 @@ class TypeInfo_Aj : TypeInfo_Ae TypeInfo next() { - return typeid(ireal); + return typeid(ireal); } } diff --git a/std/typeinfo/ti_Ashort.d b/std/typeinfo/ti_Ashort.d index 9f5e696aa..58fd9ddc0 100644 --- a/std/typeinfo/ti_Ashort.d +++ b/std/typeinfo/ti_Ashort.d @@ -10,72 +10,72 @@ class TypeInfo_As : TypeInfo char[] toString() { return "short[]"; } hash_t getHash(void *p) - { short[] s = *cast(short[]*)p; - size_t len = s.length; - short *str = s.ptr; - hash_t hash = 0; + { short[] s = *cast(short[]*)p; + size_t len = s.length; + short *str = s.ptr; + hash_t hash = 0; - while (1) - { - switch (len) - { - case 0: - return hash; + while (1) + { + switch (len) + { + case 0: + return hash; - case 1: - hash *= 9; - hash += *cast(ushort *)str; - return hash; + case 1: + hash *= 9; + hash += *cast(ushort *)str; + return hash; - default: - hash *= 9; - hash += *cast(uint *)str; - str += 2; - len -= 2; - break; - } - } + default: + hash *= 9; + hash += *cast(uint *)str; + str += 2; + len -= 2; + break; + } + } } int equals(void *p1, void *p2) { - short[] s1 = *cast(short[]*)p1; - short[] s2 = *cast(short[]*)p2; + short[] s1 = *cast(short[]*)p1; + short[] s2 = *cast(short[]*)p2; - return s1.length == s2.length && - memcmp(cast(void *)s1, cast(void *)s2, s1.length * short.sizeof) == 0; + return s1.length == s2.length && + memcmp(cast(void *)s1, cast(void *)s2, s1.length * short.sizeof) == 0; } int compare(void *p1, void *p2) { - short[] s1 = *cast(short[]*)p1; - short[] s2 = *cast(short[]*)p2; - size_t len = s1.length; + short[] s1 = *cast(short[]*)p1; + short[] s2 = *cast(short[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int result = s1[u] - s2[u]; - if (result) - return result; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int result = s1[u] - s2[u]; + if (result) + return result; + } + return cast(int)s1.length - cast(int)s2.length; } size_t tsize() { - return (short[]).sizeof; + return (short[]).sizeof; } uint flags() { - return 1; + return 1; } TypeInfo next() { - return typeid(short); + return typeid(short); } } @@ -88,24 +88,24 @@ class TypeInfo_At : TypeInfo_As int compare(void *p1, void *p2) { - ushort[] s1 = *cast(ushort[]*)p1; - ushort[] s2 = *cast(ushort[]*)p2; - size_t len = s1.length; + ushort[] s1 = *cast(ushort[]*)p1; + ushort[] s2 = *cast(ushort[]*)p2; + size_t len = s1.length; - if (s2.length < len) - len = s2.length; - for (size_t u = 0; u < len; u++) - { - int result = s1[u] - s2[u]; - if (result) - return result; - } - return cast(int)s1.length - cast(int)s2.length; + if (s2.length < len) + len = s2.length; + for (size_t u = 0; u < len; u++) + { + int result = s1[u] - s2[u]; + if (result) + return result; + } + return cast(int)s1.length - cast(int)s2.length; } TypeInfo next() { - return typeid(ushort); + return typeid(ushort); } } @@ -117,7 +117,7 @@ class TypeInfo_Au : TypeInfo_At TypeInfo next() { - return typeid(wchar); + return typeid(wchar); } } diff --git a/std/typeinfo/ti_C.d b/std/typeinfo/ti_C.d index 012ee5c06..4707dc4a1 100644 --- a/std/typeinfo/ti_C.d +++ b/std/typeinfo/ti_C.d @@ -29,47 +29,47 @@ class TypeInfo_C : TypeInfo { hash_t getHash(void *p) { - Object o = *cast(Object*)p; - return o ? o.toHash() : 0; + Object o = *cast(Object*)p; + return o ? o.toHash() : 0; } int equals(void *p1, void *p2) { - Object o1 = *cast(Object*)p1; - Object o2 = *cast(Object*)p2; + Object o1 = *cast(Object*)p1; + Object o2 = *cast(Object*)p2; - return o1 == o2; + return o1 == o2; } int compare(void *p1, void *p2) { - Object o1 = *cast(Object*)p1; - Object o2 = *cast(Object*)p2; - int c = 0; + Object o1 = *cast(Object*)p1; + Object o2 = *cast(Object*)p2; + int c = 0; - // Regard null references as always being "less than" - if (!(o1 is o2)) - { - if (o1) - { if (!o2) - c = 1; - else - c = o1.opCmp(o2); - } - else - c = -1; - } - return c; + // Regard null references as always being "less than" + if (!(o1 is o2)) + { + if (o1) + { if (!o2) + c = 1; + else + c = o1.opCmp(o2); + } + else + c = -1; + } + return c; } size_t tsize() { - return Object.sizeof; + return Object.sizeof; } uint flags() { - return 1; + return 1; } } diff --git a/std/typeinfo/ti_byte.d b/std/typeinfo/ti_byte.d index 5146a4cc1..cfcefe006 100644 --- a/std/typeinfo/ti_byte.d +++ b/std/typeinfo/ti_byte.d @@ -9,31 +9,31 @@ class TypeInfo_g : TypeInfo hash_t getHash(void *p) { - return *cast(byte *)p; + return *cast(byte *)p; } int equals(void *p1, void *p2) { - return *cast(byte *)p1 == *cast(byte *)p2; + return *cast(byte *)p1 == *cast(byte *)p2; } int compare(void *p1, void *p2) { - return *cast(byte *)p1 - *cast(byte *)p2; + return *cast(byte *)p1 - *cast(byte *)p2; } size_t tsize() { - return byte.sizeof; + return byte.sizeof; } void swap(void *p1, void *p2) { - byte t; + byte t; - t = *cast(byte *)p1; - *cast(byte *)p1 = *cast(byte *)p2; - *cast(byte *)p2 = t; + t = *cast(byte *)p1; + *cast(byte *)p1 = *cast(byte *)p2; + *cast(byte *)p2 = t; } } diff --git a/std/typeinfo/ti_cdouble.d b/std/typeinfo/ti_cdouble.d index 82ac4c93e..c13a3a6e1 100644 --- a/std/typeinfo/ti_cdouble.d +++ b/std/typeinfo/ti_cdouble.d @@ -9,59 +9,59 @@ class TypeInfo_r : TypeInfo hash_t getHash(void *p) { - return (cast(uint *)p)[0] + (cast(uint *)p)[1] + - (cast(uint *)p)[2] + (cast(uint *)p)[3]; + return (cast(uint *)p)[0] + (cast(uint *)p)[1] + + (cast(uint *)p)[2] + (cast(uint *)p)[3]; } static int _equals(cdouble f1, cdouble f2) { - return f1 == f2; + return f1 == f2; } static int _compare(cdouble f1, cdouble f2) { int result; - if (f1.re < f2.re) - result = -1; - else if (f1.re > f2.re) - result = 1; - else if (f1.im < f2.im) - result = -1; - else if (f1.im > f2.im) - result = 1; - else - result = 0; + if (f1.re < f2.re) + result = -1; + else if (f1.re > f2.re) + result = 1; + else if (f1.im < f2.im) + result = -1; + else if (f1.im > f2.im) + result = 1; + else + result = 0; return result; } int equals(void *p1, void *p2) { - return _equals(*cast(cdouble *)p1, *cast(cdouble *)p2); + return _equals(*cast(cdouble *)p1, *cast(cdouble *)p2); } int compare(void *p1, void *p2) { - return _compare(*cast(cdouble *)p1, *cast(cdouble *)p2); + return _compare(*cast(cdouble *)p1, *cast(cdouble *)p2); } size_t tsize() { - return cdouble.sizeof; + return cdouble.sizeof; } void swap(void *p1, void *p2) { - cdouble t; + cdouble t; - t = *cast(cdouble *)p1; - *cast(cdouble *)p1 = *cast(cdouble *)p2; - *cast(cdouble *)p2 = t; + t = *cast(cdouble *)p1; + *cast(cdouble *)p1 = *cast(cdouble *)p2; + *cast(cdouble *)p2 = t; } void[] init() - { static cdouble r; + { static cdouble r; - return (cast(cdouble *)&r)[0 .. 1]; + return (cast(cdouble *)&r)[0 .. 1]; } } diff --git a/std/typeinfo/ti_cfloat.d b/std/typeinfo/ti_cfloat.d index dc6b9cd89..1e5896fc3 100644 --- a/std/typeinfo/ti_cfloat.d +++ b/std/typeinfo/ti_cfloat.d @@ -9,58 +9,58 @@ class TypeInfo_q : TypeInfo hash_t getHash(void *p) { - return (cast(uint *)p)[0] + (cast(uint *)p)[1]; + return (cast(uint *)p)[0] + (cast(uint *)p)[1]; } static int _equals(cfloat f1, cfloat f2) { - return f1 == f2; + return f1 == f2; } static int _compare(cfloat f1, cfloat f2) { int result; - if (f1.re < f2.re) - result = -1; - else if (f1.re > f2.re) - result = 1; - else if (f1.im < f2.im) - result = -1; - else if (f1.im > f2.im) - result = 1; - else - result = 0; + if (f1.re < f2.re) + result = -1; + else if (f1.re > f2.re) + result = 1; + else if (f1.im < f2.im) + result = -1; + else if (f1.im > f2.im) + result = 1; + else + result = 0; return result; } int equals(void *p1, void *p2) { - return _equals(*cast(cfloat *)p1, *cast(cfloat *)p2); + return _equals(*cast(cfloat *)p1, *cast(cfloat *)p2); } int compare(void *p1, void *p2) { - return _compare(*cast(cfloat *)p1, *cast(cfloat *)p2); + return _compare(*cast(cfloat *)p1, *cast(cfloat *)p2); } size_t tsize() { - return cfloat.sizeof; + return cfloat.sizeof; } void swap(void *p1, void *p2) { - cfloat t; + cfloat t; - t = *cast(cfloat *)p1; - *cast(cfloat *)p1 = *cast(cfloat *)p2; - *cast(cfloat *)p2 = t; + t = *cast(cfloat *)p1; + *cast(cfloat *)p1 = *cast(cfloat *)p2; + *cast(cfloat *)p2 = t; } void[] init() - { static cfloat r; + { static cfloat r; - return (cast(cfloat *)&r)[0 .. 1]; + return (cast(cfloat *)&r)[0 .. 1]; } } diff --git a/std/typeinfo/ti_char.d b/std/typeinfo/ti_char.d index 57ddeada9..25068a1c3 100644 --- a/std/typeinfo/ti_char.d +++ b/std/typeinfo/ti_char.d @@ -7,37 +7,37 @@ class TypeInfo_a : TypeInfo hash_t getHash(void *p) { - return *cast(char *)p; + return *cast(char *)p; } int equals(void *p1, void *p2) { - return *cast(char *)p1 == *cast(char *)p2; + return *cast(char *)p1 == *cast(char *)p2; } int compare(void *p1, void *p2) { - return *cast(char *)p1 - *cast(char *)p2; + return *cast(char *)p1 - *cast(char *)p2; } size_t tsize() { - return char.sizeof; + return char.sizeof; } void swap(void *p1, void *p2) { - char t; + char t; - t = *cast(char *)p1; - *cast(char *)p1 = *cast(char *)p2; - *cast(char *)p2 = t; + t = *cast(char *)p1; + *cast(char *)p1 = *cast(char *)p2; + *cast(char *)p2 = t; } void[] init() - { static char c; + { static char c; - return (cast(char *)&c)[0 .. 1]; + return (cast(char *)&c)[0 .. 1]; } } diff --git a/std/typeinfo/ti_creal.d b/std/typeinfo/ti_creal.d index 1beebe097..d0f3879a1 100644 --- a/std/typeinfo/ti_creal.d +++ b/std/typeinfo/ti_creal.d @@ -9,60 +9,60 @@ class TypeInfo_c : TypeInfo hash_t getHash(void *p) { - return (cast(uint *)p)[0] + (cast(uint *)p)[1] + - (cast(uint *)p)[2] + (cast(uint *)p)[3] + - (cast(uint *)p)[4]; + return (cast(uint *)p)[0] + (cast(uint *)p)[1] + + (cast(uint *)p)[2] + (cast(uint *)p)[3] + + (cast(uint *)p)[4]; } static int _equals(creal f1, creal f2) { - return f1 == f2; + return f1 == f2; } static int _compare(creal f1, creal f2) { int result; - if (f1.re < f2.re) - result = -1; - else if (f1.re > f2.re) - result = 1; - else if (f1.im < f2.im) - result = -1; - else if (f1.im > f2.im) - result = 1; - else - result = 0; + if (f1.re < f2.re) + result = -1; + else if (f1.re > f2.re) + result = 1; + else if (f1.im < f2.im) + result = -1; + else if (f1.im > f2.im) + result = 1; + else + result = 0; return result; } int equals(void *p1, void *p2) { - return _equals(*cast(creal *)p1, *cast(creal *)p2); + return _equals(*cast(creal *)p1, *cast(creal *)p2); } int compare(void *p1, void *p2) { - return _compare(*cast(creal *)p1, *cast(creal *)p2); + return _compare(*cast(creal *)p1, *cast(creal *)p2); } size_t tsize() { - return creal.sizeof; + return creal.sizeof; } void swap(void *p1, void *p2) { - creal t; + creal t; - t = *cast(creal *)p1; - *cast(creal *)p1 = *cast(creal *)p2; - *cast(creal *)p2 = t; + t = *cast(creal *)p1; + *cast(creal *)p1 = *cast(creal *)p2; + *cast(creal *)p2 = t; } void[] init() - { static creal r; + { static creal r; - return (cast(creal *)&r)[0 .. 1]; + return (cast(creal *)&r)[0 .. 1]; } } diff --git a/std/typeinfo/ti_dchar.d b/std/typeinfo/ti_dchar.d index ff39afb2b..1406d276d 100644 --- a/std/typeinfo/ti_dchar.d +++ b/std/typeinfo/ti_dchar.d @@ -9,37 +9,37 @@ class TypeInfo_w : TypeInfo hash_t getHash(void *p) { - return *cast(dchar *)p; + return *cast(dchar *)p; } int equals(void *p1, void *p2) { - return *cast(dchar *)p1 == *cast(dchar *)p2; + return *cast(dchar *)p1 == *cast(dchar *)p2; } int compare(void *p1, void *p2) { - return *cast(dchar *)p1 - *cast(dchar *)p2; + return *cast(dchar *)p1 - *cast(dchar *)p2; } size_t tsize() { - return dchar.sizeof; + return dchar.sizeof; } void swap(void *p1, void *p2) { - dchar t; + dchar t; - t = *cast(dchar *)p1; - *cast(dchar *)p1 = *cast(dchar *)p2; - *cast(dchar *)p2 = t; + t = *cast(dchar *)p1; + *cast(dchar *)p1 = *cast(dchar *)p2; + *cast(dchar *)p2 = t; } void[] init() - { static dchar c; + { static dchar c; - return (cast(dchar *)&c)[0 .. 1]; + return (cast(dchar *)&c)[0 .. 1]; } } diff --git a/std/typeinfo/ti_delegate.d b/std/typeinfo/ti_delegate.d index a4cc4bf8b..bf2a20c5f 100644 --- a/std/typeinfo/ti_delegate.d +++ b/std/typeinfo/ti_delegate.d @@ -8,33 +8,33 @@ alias void delegate(int) dg; class TypeInfo_D : TypeInfo { hash_t getHash(void *p) - { long l = *cast(long *)p; + { long l = *cast(long *)p; - return cast(uint)(l + (l >> 32)); + return cast(uint)(l + (l >> 32)); } int equals(void *p1, void *p2) { - return *cast(dg *)p1 == *cast(dg *)p2; + return *cast(dg *)p1 == *cast(dg *)p2; } size_t tsize() { - return dg.sizeof; + return dg.sizeof; } void swap(void *p1, void *p2) { - dg t; + dg t; - t = *cast(dg *)p1; - *cast(dg *)p1 = *cast(dg *)p2; - *cast(dg *)p2 = t; + t = *cast(dg *)p1; + *cast(dg *)p1 = *cast(dg *)p2; + *cast(dg *)p2 = t; } uint flags() { - return 1; + return 1; } } diff --git a/std/typeinfo/ti_double.d b/std/typeinfo/ti_double.d index 8286e3c44..bc5211707 100644 --- a/std/typeinfo/ti_double.d +++ b/std/typeinfo/ti_double.d @@ -11,57 +11,57 @@ class TypeInfo_d : TypeInfo hash_t getHash(void *p) { - return (cast(uint *)p)[0] + (cast(uint *)p)[1]; + return (cast(uint *)p)[0] + (cast(uint *)p)[1]; } static int _equals(double f1, double f2) { - return f1 == f2 || - (isnan(f1) && isnan(f2)); + return f1 == f2 || + (isnan(f1) && isnan(f2)); } static int _compare(double d1, double d2) { - if (d1 !<>= d2) // if either are NaN - { - if (isnan(d1)) - { if (isnan(d2)) - return 0; - return -1; - } - return 1; - } - return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1); + if (d1 !<>= d2) // if either are NaN + { + if (isnan(d1)) + { if (isnan(d2)) + return 0; + return -1; + } + return 1; + } + return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1); } int equals(void *p1, void *p2) { - return _equals(*cast(double *)p1, *cast(double *)p2); + return _equals(*cast(double *)p1, *cast(double *)p2); } int compare(void *p1, void *p2) { - return _compare(*cast(double *)p1, *cast(double *)p2); + return _compare(*cast(double *)p1, *cast(double *)p2); } size_t tsize() { - return double.sizeof; + return double.sizeof; } void swap(void *p1, void *p2) { - double t; + double t; - t = *cast(double *)p1; - *cast(double *)p1 = *cast(double *)p2; - *cast(double *)p2 = t; + t = *cast(double *)p1; + *cast(double *)p1 = *cast(double *)p2; + *cast(double *)p2 = t; } void[] init() - { static double r; + { static double r; - return (cast(double *)&r)[0 .. 1]; + return (cast(double *)&r)[0 .. 1]; } } diff --git a/std/typeinfo/ti_float.d b/std/typeinfo/ti_float.d index 7172626e3..1b3f991e2 100644 --- a/std/typeinfo/ti_float.d +++ b/std/typeinfo/ti_float.d @@ -11,57 +11,57 @@ class TypeInfo_f : TypeInfo hash_t getHash(void *p) { - return *cast(uint *)p; + return *cast(uint *)p; } static int _equals(float f1, float f2) { - return f1 == f2 || - (isnan(f1) && isnan(f2)); + return f1 == f2 || + (isnan(f1) && isnan(f2)); } static int _compare(float d1, float d2) { - if (d1 !<>= d2) // if either are NaN - { - if (isnan(d1)) - { if (isnan(d2)) - return 0; - return -1; - } - return 1; - } - return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1); + if (d1 !<>= d2) // if either are NaN + { + if (isnan(d1)) + { if (isnan(d2)) + return 0; + return -1; + } + return 1; + } + return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1); } int equals(void *p1, void *p2) { - return _equals(*cast(float *)p1, *cast(float *)p2); + return _equals(*cast(float *)p1, *cast(float *)p2); } int compare(void *p1, void *p2) { - return _compare(*cast(float *)p1, *cast(float *)p2); + return _compare(*cast(float *)p1, *cast(float *)p2); } size_t tsize() { - return float.sizeof; + return float.sizeof; } void swap(void *p1, void *p2) { - float t; + float t; - t = *cast(float *)p1; - *cast(float *)p1 = *cast(float *)p2; - *cast(float *)p2 = t; + t = *cast(float *)p1; + *cast(float *)p1 = *cast(float *)p2; + *cast(float *)p2 = t; } void[] init() - { static float r; + { static float r; - return (cast(float *)&r)[0 .. 1]; + return (cast(float *)&r)[0 .. 1]; } } diff --git a/std/typeinfo/ti_int.d b/std/typeinfo/ti_int.d index ea36676cd..83e02d137 100644 --- a/std/typeinfo/ti_int.d +++ b/std/typeinfo/ti_int.d @@ -9,35 +9,35 @@ class TypeInfo_i : TypeInfo hash_t getHash(void *p) { - return *cast(uint *)p; + return *cast(uint *)p; } int equals(void *p1, void *p2) { - return *cast(uint *)p1 == *cast(uint *)p2; + return *cast(uint *)p1 == *cast(uint *)p2; } int compare(void *p1, void *p2) { - if (*cast(int*) p1 < *cast(int*) p2) - return -1; - else if (*cast(int*) p1 > *cast(int*) p2) - return 1; - return 0; + if (*cast(int*) p1 < *cast(int*) p2) + return -1; + else if (*cast(int*) p1 > *cast(int*) p2) + return 1; + return 0; } size_t tsize() { - return int.sizeof; + return int.sizeof; } void swap(void *p1, void *p2) { - int t; + int t; - t = *cast(int *)p1; - *cast(int *)p1 = *cast(int *)p2; - *cast(int *)p2 = t; + t = *cast(int *)p1; + *cast(int *)p1 = *cast(int *)p2; + *cast(int *)p2 = t; } } diff --git a/std/typeinfo/ti_long.d b/std/typeinfo/ti_long.d index 122304540..98fc29261 100644 --- a/std/typeinfo/ti_long.d +++ b/std/typeinfo/ti_long.d @@ -9,35 +9,35 @@ class TypeInfo_l : TypeInfo hash_t getHash(void *p) { - return *cast(uint *)p + (cast(uint *)p)[1]; + return *cast(uint *)p + (cast(uint *)p)[1]; } int equals(void *p1, void *p2) { - return *cast(long *)p1 == *cast(long *)p2; + return *cast(long *)p1 == *cast(long *)p2; } int compare(void *p1, void *p2) { - if (*cast(long *)p1 < *cast(long *)p2) - return -1; - else if (*cast(long *)p1 > *cast(long *)p2) - return 1; - return 0; + if (*cast(long *)p1 < *cast(long *)p2) + return -1; + else if (*cast(long *)p1 > *cast(long *)p2) + return 1; + return 0; } size_t tsize() { - return long.sizeof; + return long.sizeof; } void swap(void *p1, void *p2) { - long t; + long t; - t = *cast(long *)p1; - *cast(long *)p1 = *cast(long *)p2; - *cast(long *)p2 = t; + t = *cast(long *)p1; + *cast(long *)p1 = *cast(long *)p2; + *cast(long *)p2 = t; } } diff --git a/std/typeinfo/ti_ptr.d b/std/typeinfo/ti_ptr.d index 2c7b31379..9c1891a09 100644 --- a/std/typeinfo/ti_ptr.d +++ b/std/typeinfo/ti_ptr.d @@ -7,36 +7,36 @@ class TypeInfo_P : TypeInfo { hash_t getHash(void *p) { - return cast(uint)*cast(void* *)p; + return cast(uint)*cast(void* *)p; } int equals(void *p1, void *p2) { - return *cast(void* *)p1 == *cast(void* *)p2; + return *cast(void* *)p1 == *cast(void* *)p2; } int compare(void *p1, void *p2) { - return *cast(void* *)p1 - *cast(void* *)p2; + return *cast(void* *)p1 - *cast(void* *)p2; } size_t tsize() { - return (void*).sizeof; + return (void*).sizeof; } void swap(void *p1, void *p2) { - void* t; + void* t; - t = *cast(void* *)p1; - *cast(void* *)p1 = *cast(void* *)p2; - *cast(void* *)p2 = t; + t = *cast(void* *)p1; + *cast(void* *)p1 = *cast(void* *)p2; + *cast(void* *)p2 = t; } uint flags() { - return 1; + return 1; } } diff --git a/std/typeinfo/ti_real.d b/std/typeinfo/ti_real.d index e491393ff..acc429545 100644 --- a/std/typeinfo/ti_real.d +++ b/std/typeinfo/ti_real.d @@ -11,57 +11,57 @@ class TypeInfo_e : TypeInfo hash_t getHash(void *p) { - return (cast(uint *)p)[0] + (cast(uint *)p)[1] + (cast(ushort *)p)[4]; + return (cast(uint *)p)[0] + (cast(uint *)p)[1] + (cast(ushort *)p)[4]; } static int _equals(real f1, real f2) { - return f1 == f2 || - (isnan(f1) && isnan(f2)); + return f1 == f2 || + (isnan(f1) && isnan(f2)); } static int _compare(real d1, real d2) { - if (d1 !<>= d2) // if either are NaN - { - if (isnan(d1)) - { if (isnan(d2)) - return 0; - return -1; - } - return 1; - } - return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1); + if (d1 !<>= d2) // if either are NaN + { + if (isnan(d1)) + { if (isnan(d2)) + return 0; + return -1; + } + return 1; + } + return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1); } int equals(void *p1, void *p2) { - return _equals(*cast(real *)p1, *cast(real *)p2); + return _equals(*cast(real *)p1, *cast(real *)p2); } int compare(void *p1, void *p2) { - return _compare(*cast(real *)p1, *cast(real *)p2); + return _compare(*cast(real *)p1, *cast(real *)p2); } size_t tsize() { - return real.sizeof; + return real.sizeof; } void swap(void *p1, void *p2) { - real t; + real t; - t = *cast(real *)p1; - *cast(real *)p1 = *cast(real *)p2; - *cast(real *)p2 = t; + t = *cast(real *)p1; + *cast(real *)p1 = *cast(real *)p2; + *cast(real *)p2 = t; } void[] init() - { static real r; + { static real r; - return (cast(real *)&r)[0 .. 1]; + return (cast(real *)&r)[0 .. 1]; } } diff --git a/std/typeinfo/ti_short.d b/std/typeinfo/ti_short.d index d5384e6a0..d7929a9d1 100644 --- a/std/typeinfo/ti_short.d +++ b/std/typeinfo/ti_short.d @@ -9,31 +9,31 @@ class TypeInfo_s : TypeInfo hash_t getHash(void *p) { - return *cast(short *)p; + return *cast(short *)p; } int equals(void *p1, void *p2) { - return *cast(short *)p1 == *cast(short *)p2; + return *cast(short *)p1 == *cast(short *)p2; } int compare(void *p1, void *p2) { - return *cast(short *)p1 - *cast(short *)p2; + return *cast(short *)p1 - *cast(short *)p2; } size_t tsize() { - return short.sizeof; + return short.sizeof; } void swap(void *p1, void *p2) { - short t; + short t; - t = *cast(short *)p1; - *cast(short *)p1 = *cast(short *)p2; - *cast(short *)p2 = t; + t = *cast(short *)p1; + *cast(short *)p1 = *cast(short *)p2; + *cast(short *)p2 = t; } } diff --git a/std/typeinfo/ti_ubyte.d b/std/typeinfo/ti_ubyte.d index 2940c7773..8fd437e9f 100644 --- a/std/typeinfo/ti_ubyte.d +++ b/std/typeinfo/ti_ubyte.d @@ -9,31 +9,31 @@ class TypeInfo_h : TypeInfo hash_t getHash(void *p) { - return *cast(ubyte *)p; + return *cast(ubyte *)p; } int equals(void *p1, void *p2) { - return *cast(ubyte *)p1 == *cast(ubyte *)p2; + return *cast(ubyte *)p1 == *cast(ubyte *)p2; } int compare(void *p1, void *p2) { - return *cast(ubyte *)p1 - *cast(ubyte *)p2; + return *cast(ubyte *)p1 - *cast(ubyte *)p2; } size_t tsize() { - return ubyte.sizeof; + return ubyte.sizeof; } void swap(void *p1, void *p2) { - ubyte t; + ubyte t; - t = *cast(ubyte *)p1; - *cast(ubyte *)p1 = *cast(ubyte *)p2; - *cast(ubyte *)p2 = t; + t = *cast(ubyte *)p1; + *cast(ubyte *)p1 = *cast(ubyte *)p2; + *cast(ubyte *)p2 = t; } } diff --git a/std/typeinfo/ti_uint.d b/std/typeinfo/ti_uint.d index cc14c94e8..9cccb9df0 100644 --- a/std/typeinfo/ti_uint.d +++ b/std/typeinfo/ti_uint.d @@ -9,35 +9,35 @@ class TypeInfo_k : TypeInfo hash_t getHash(void *p) { - return *cast(uint *)p; + return *cast(uint *)p; } int equals(void *p1, void *p2) { - return *cast(uint *)p1 == *cast(uint *)p2; + return *cast(uint *)p1 == *cast(uint *)p2; } int compare(void *p1, void *p2) { - if (*cast(uint*) p1 < *cast(uint*) p2) - return -1; - else if (*cast(uint*) p1 > *cast(uint*) p2) - return 1; - return 0; + if (*cast(uint*) p1 < *cast(uint*) p2) + return -1; + else if (*cast(uint*) p1 > *cast(uint*) p2) + return 1; + return 0; } size_t tsize() { - return uint.sizeof; + return uint.sizeof; } void swap(void *p1, void *p2) { - int t; + int t; - t = *cast(uint *)p1; - *cast(uint *)p1 = *cast(uint *)p2; - *cast(uint *)p2 = t; + t = *cast(uint *)p1; + *cast(uint *)p1 = *cast(uint *)p2; + *cast(uint *)p2 = t; } } diff --git a/std/typeinfo/ti_ulong.d b/std/typeinfo/ti_ulong.d index c6019de83..0c06c4e12 100644 --- a/std/typeinfo/ti_ulong.d +++ b/std/typeinfo/ti_ulong.d @@ -9,35 +9,35 @@ class TypeInfo_m : TypeInfo hash_t getHash(void *p) { - return *cast(uint *)p + (cast(uint *)p)[1]; + return *cast(uint *)p + (cast(uint *)p)[1]; } int equals(void *p1, void *p2) { - return *cast(ulong *)p1 == *cast(ulong *)p2; + return *cast(ulong *)p1 == *cast(ulong *)p2; } int compare(void *p1, void *p2) { - if (*cast(ulong *)p1 < *cast(ulong *)p2) - return -1; - else if (*cast(ulong *)p1 > *cast(ulong *)p2) - return 1; - return 0; + if (*cast(ulong *)p1 < *cast(ulong *)p2) + return -1; + else if (*cast(ulong *)p1 > *cast(ulong *)p2) + return 1; + return 0; } size_t tsize() { - return ulong.sizeof; + return ulong.sizeof; } void swap(void *p1, void *p2) { - ulong t; + ulong t; - t = *cast(ulong *)p1; - *cast(ulong *)p1 = *cast(ulong *)p2; - *cast(ulong *)p2 = t; + t = *cast(ulong *)p1; + *cast(ulong *)p1 = *cast(ulong *)p2; + *cast(ulong *)p2 = t; } } diff --git a/std/typeinfo/ti_ushort.d b/std/typeinfo/ti_ushort.d index c55f00bef..c9b8fd939 100644 --- a/std/typeinfo/ti_ushort.d +++ b/std/typeinfo/ti_ushort.d @@ -9,31 +9,31 @@ class TypeInfo_t : TypeInfo hash_t getHash(void *p) { - return *cast(ushort *)p; + return *cast(ushort *)p; } int equals(void *p1, void *p2) { - return *cast(ushort *)p1 == *cast(ushort *)p2; + return *cast(ushort *)p1 == *cast(ushort *)p2; } int compare(void *p1, void *p2) { - return *cast(ushort *)p1 - *cast(ushort *)p2; + return *cast(ushort *)p1 - *cast(ushort *)p2; } size_t tsize() { - return ushort.sizeof; + return ushort.sizeof; } void swap(void *p1, void *p2) { - ushort t; + ushort t; - t = *cast(ushort *)p1; - *cast(ushort *)p1 = *cast(ushort *)p2; - *cast(ushort *)p2 = t; + t = *cast(ushort *)p1; + *cast(ushort *)p1 = *cast(ushort *)p2; + *cast(ushort *)p2 = t; } } diff --git a/std/typeinfo/ti_void.d b/std/typeinfo/ti_void.d index f7dfcb71f..b350d5d2b 100644 --- a/std/typeinfo/ti_void.d +++ b/std/typeinfo/ti_void.d @@ -9,36 +9,36 @@ class TypeInfo_v : TypeInfo hash_t getHash(void *p) { - assert(0); + assert(0); } int equals(void *p1, void *p2) { - return *cast(byte *)p1 == *cast(byte *)p2; + return *cast(byte *)p1 == *cast(byte *)p2; } int compare(void *p1, void *p2) { - return *cast(byte *)p1 - *cast(byte *)p2; + return *cast(byte *)p1 - *cast(byte *)p2; } size_t tsize() { - return void.sizeof; + return void.sizeof; } void swap(void *p1, void *p2) { - byte t; + byte t; - t = *cast(byte *)p1; - *cast(byte *)p1 = *cast(byte *)p2; - *cast(byte *)p2 = t; + t = *cast(byte *)p1; + *cast(byte *)p1 = *cast(byte *)p2; + *cast(byte *)p2 = t; } uint flags() { - return 1; + return 1; } } diff --git a/std/typeinfo/ti_wchar.d b/std/typeinfo/ti_wchar.d index 3980b2a71..57a15a6b2 100644 --- a/std/typeinfo/ti_wchar.d +++ b/std/typeinfo/ti_wchar.d @@ -8,37 +8,37 @@ class TypeInfo_u : TypeInfo hash_t getHash(void *p) { - return *cast(wchar *)p; + return *cast(wchar *)p; } int equals(void *p1, void *p2) { - return *cast(wchar *)p1 == *cast(wchar *)p2; + return *cast(wchar *)p1 == *cast(wchar *)p2; } int compare(void *p1, void *p2) { - return *cast(wchar *)p1 - *cast(wchar *)p2; + return *cast(wchar *)p1 - *cast(wchar *)p2; } size_t tsize() { - return wchar.sizeof; + return wchar.sizeof; } void swap(void *p1, void *p2) { - wchar t; + wchar t; - t = *cast(wchar *)p1; - *cast(wchar *)p1 = *cast(wchar *)p2; - *cast(wchar *)p2 = t; + t = *cast(wchar *)p1; + *cast(wchar *)p1 = *cast(wchar *)p2; + *cast(wchar *)p2 = t; } void[] init() - { static wchar c; + { static wchar c; - return (cast(wchar *)&c)[0 .. 1]; + return (cast(wchar *)&c)[0 .. 1]; } } diff --git a/std/typetuple.d b/std/typetuple.d index 2b2b7456a..401decea1 100644 --- a/std/typetuple.d +++ b/std/typetuple.d @@ -10,18 +10,18 @@ * list that is a slice of the old one. * * References: - * Based on ideas in Table 3.1 from - * $(LINK2 http://www.amazon.com/exec/obidos/ASIN/0201704315/ref=ase_classicempire/102-2957199-2585768, - * Modern C++ Design), - * Andrei Alexandrescu (Addison-Wesley Professional, 2001) + * Based on ideas in Table 3.1 from + * $(LINK2 http://www.amazon.com/exec/obidos/ASIN/0201704315/ref=ase_classicempire/102-2957199-2585768, + * Modern C++ Design), + * Andrei Alexandrescu (Addison-Wesley Professional, 2001) * Macros: - * WIKI = Phobos/StdTypeTuple + * WIKI = Phobos/StdTypeTuple * Copyright: - * Public Domain + * Public Domain */ /* Author: - * Walter Bright, Digital Mars, www.digitalmars.com + * Walter Bright, Digital Mars, www.digitalmars.com */ module std.typetuple; @@ -71,14 +71,14 @@ template TypeTuple(TList...) template IndexOf(T, TList...) { static if (TList.length == 0) - const int IndexOf = -1; + const int IndexOf = -1; else static if (is(T == TList[0])) - const int IndexOf = 0; + const int IndexOf = 0; else - const int IndexOf = - (IndexOf!(T, TList[1 .. length]) == -1) - ? -1 - : 1 + IndexOf!(T, TList[1 .. length]); + const int IndexOf = + (IndexOf!(T, TList[1 .. length]) == -1) + ? -1 + : 1 + IndexOf!(T, TList[1 .. length]); } /** @@ -94,11 +94,11 @@ template IndexOf(T, TList...) template Erase(T, TList...) { static if (TList.length == 0) - alias TList Erase; + alias TList Erase; else static if (is(T == TList[0])) - alias TList[1 .. length] Erase; + alias TList[1 .. length] Erase; else - alias TypeTuple!(TList[0], Erase!(T, TList[1 .. length])) Erase; + alias TypeTuple!(TList[0], Erase!(T, TList[1 .. length])) Erase; } /** @@ -116,11 +116,11 @@ template Erase(T, TList...) template EraseAll(T, TList...) { static if (TList.length == 0) - alias TList EraseAll; + alias TList EraseAll; else static if (is(T == TList[0])) - alias EraseAll!(T, TList[1 .. length]) EraseAll; + alias EraseAll!(T, TList[1 .. length]) EraseAll; else - alias TypeTuple!(TList[0], EraseAll!(T, TList[1 .. length])) EraseAll; + alias TypeTuple!(TList[0], EraseAll!(T, TList[1 .. length])) EraseAll; } /** @@ -138,9 +138,9 @@ template EraseAll(T, TList...) template NoDuplicates(TList...) { static if (TList.length == 0) - alias TList NoDuplicates; + alias TList NoDuplicates; else - alias TypeTuple!(TList[0], NoDuplicates!(EraseAll!(TList[0], TList[1 .. length]))) NoDuplicates; + alias TypeTuple!(TList[0], NoDuplicates!(EraseAll!(TList[0], TList[1 .. length]))) NoDuplicates; } /** @@ -158,11 +158,11 @@ template NoDuplicates(TList...) template Replace(T, U, TList...) { static if (TList.length == 0) - alias TList Replace; + alias TList Replace; else static if (is(T == TList[0])) - alias TypeTuple!(U, TList[1 .. length]) Replace; + alias TypeTuple!(U, TList[1 .. length]) Replace; else - alias TypeTuple!(TList[0], Replace!(T, U, TList[1 .. length])) Replace; + alias TypeTuple!(TList[0], Replace!(T, U, TList[1 .. length])) Replace; } /** @@ -180,11 +180,11 @@ template Replace(T, U, TList...) template ReplaceAll(T, U, TList...) { static if (TList.length == 0) - alias TList ReplaceAll; + alias TList ReplaceAll; else static if (is(T == TList[0])) - alias TypeTuple!(U, ReplaceAll!(T, U, TList[1 .. length])) ReplaceAll; + alias TypeTuple!(U, ReplaceAll!(T, U, TList[1 .. length])) ReplaceAll; else - alias TypeTuple!(TList[0], ReplaceAll!(T, U, TList[1 .. length])) ReplaceAll; + alias TypeTuple!(TList[0], ReplaceAll!(T, U, TList[1 .. length])) ReplaceAll; } /** @@ -201,9 +201,9 @@ template ReplaceAll(T, U, TList...) template Reverse(TList...) { static if (TList.length == 0) - alias TList Reverse; + alias TList Reverse; else - alias TypeTuple!(Reverse!(TList[1 .. length]), TList[0]) Reverse; + alias TypeTuple!(Reverse!(TList[1 .. length]), TList[0]) Reverse; } /** @@ -222,11 +222,11 @@ template Reverse(TList...) template MostDerived(T, TList...) { static if (TList.length == 0) - alias T MostDerived; + alias T MostDerived; else static if (is(TList[0] : T)) - alias MostDerived!(TList[0], TList[1 .. length]) MostDerived; + alias MostDerived!(TList[0], TList[1 .. length]) MostDerived; else - alias MostDerived!(T, TList[1 .. length]) MostDerived; + alias MostDerived!(T, TList[1 .. length]) MostDerived; } /** @@ -247,10 +247,10 @@ template MostDerived(T, TList...) template DerivedToFront(TList...) { static if (TList.length == 0) - alias TList DerivedToFront; + alias TList DerivedToFront; else - alias TypeTuple!(MostDerived!(TList[0], TList[1 .. length]), - DerivedToFront!(ReplaceAll!(MostDerived!(TList[0], TList[1 .. length]), - TList[0], - TList[1 .. length]))) DerivedToFront; + alias TypeTuple!(MostDerived!(TList[0], TList[1 .. length]), + DerivedToFront!(ReplaceAll!(MostDerived!(TList[0], TList[1 .. length]), + TList[0], + TList[1 .. length]))) DerivedToFront; } diff --git a/std/uni.d b/std/uni.d index b6a0fa234..5aa6c4a5f 100644 --- a/std/uni.d +++ b/std/uni.d @@ -11,13 +11,13 @@ * Simple Unicode character classification functions. * For ASCII classification, see $(LINK2 std_ctype.html, std.ctype). * Macros: - * WIKI=Phobos/StdUni + * WIKI=Phobos/StdUni * References: - * $(LINK2 http://www.digitalmars.com/d/ascii-table.html, ASCII Table), - * $(LINK2 http://en.wikipedia.org/wiki/Unicode, Wikipedia), - * $(LINK2 http://www.unicode.org, The Unicode Consortium) + * $(LINK2 http://www.digitalmars.com/d/ascii-table.html, ASCII Table), + * $(LINK2 http://en.wikipedia.org/wiki/Unicode, Wikipedia), + * $(LINK2 http://www.unicode.org, The Unicode Consortium) * Trademarks: - * Unicode(tm) is a trademark of Unicode, Inc. + * Unicode(tm) is a trademark of Unicode, Inc. */ @@ -29,7 +29,7 @@ module std.uni; int isUniLower(dchar c) { if (c <= 0x7F) - return (c >= 'a' && c <= 'z'); + return (c >= 'a' && c <= 'z'); return isUniAlpha(c) && c == toUniLower(c); } @@ -40,7 +40,7 @@ int isUniLower(dchar c) int isUniUpper(dchar c) { if (c <= 0x7F) - return (c >= 'A' && c <= 'Z'); + return (c >= 'A' && c <= 'Z'); return isUniAlpha(c) && c == toUniUpper(c); } @@ -57,56 +57,56 @@ dchar toUniLower(dchar c) } else if (c >= 0x00C0) { - if ((c >= 0x00C0 && c <= 0x00D6) || (c >= 0x00D8 && c<=0x00DE)) - { - c += 32; - } - else if ((c >= 0x0100 && c < 0x0138) || (c > 0x0149 && c < 0x0178)) - { - if (c == 0x0130) - c = 0x0069; - else if ((c & 1) == 0) - c += 1; - } - else if (c == 0x0178) - { - c = 0x00FF; - } - else if ((c >= 0x0139 && c < 0x0149) || (c > 0x0178 && c < 0x017F)) - { - if (c & 1) - c += 1; - } - else if (c >= 0x0200 && c <= 0x0217) - { - if ((c & 1) == 0) - c += 1; - } - else if ((c >= 0x0401 && c <= 0x040C) || (c>= 0x040E && c <= 0x040F)) - { - c += 80; - } - else if (c >= 0x0410 && c <= 0x042F) - { - c += 32; - } - else if (c >= 0x0460 && c <= 0x047F) - { - if ((c & 1) == 0) - c += 1; - } - else if (c >= 0x0531 && c <= 0x0556) - { - c += 48; - } - else if (c >= 0x10A0 && c <= 0x10C5) - { - c += 48; - } - else if (c >= 0xFF21 && c <= 0xFF3A) - { - c += 32; - } + if ((c >= 0x00C0 && c <= 0x00D6) || (c >= 0x00D8 && c<=0x00DE)) + { + c += 32; + } + else if ((c >= 0x0100 && c < 0x0138) || (c > 0x0149 && c < 0x0178)) + { + if (c == 0x0130) + c = 0x0069; + else if ((c & 1) == 0) + c += 1; + } + else if (c == 0x0178) + { + c = 0x00FF; + } + else if ((c >= 0x0139 && c < 0x0149) || (c > 0x0178 && c < 0x017F)) + { + if (c & 1) + c += 1; + } + else if (c >= 0x0200 && c <= 0x0217) + { + if ((c & 1) == 0) + c += 1; + } + else if ((c >= 0x0401 && c <= 0x040C) || (c>= 0x040E && c <= 0x040F)) + { + c += 80; + } + else if (c >= 0x0410 && c <= 0x042F) + { + c += 32; + } + else if (c >= 0x0460 && c <= 0x047F) + { + if ((c & 1) == 0) + c += 1; + } + else if (c >= 0x0531 && c <= 0x0556) + { + c += 48; + } + else if (c >= 0x10A0 && c <= 0x10C5) + { + c += 48; + } + else if (c >= 0xFF21 && c <= 0xFF3A) + { + c += 32; + } } return c; } @@ -119,60 +119,60 @@ dchar toUniUpper(dchar c) { if (c >= 'a' && c <= 'z') { - c -= 32; + c -= 32; } else if (c >= 0x00E0) { - if ((c >= 0x00E0 && c <= 0x00F6) || (c >= 0x00F8 && c <= 0x00FE)) - { - c -= 32; - } - else if (c == 0x00FF) - { - c = 0x0178; - } - else if ((c >= 0x0100 && c < 0x0138) || (c > 0x0149 && c < 0x0178)) - { - if (c == 0x0131) - c = 0x0049; - else if (c & 1) - c -= 1; - } - else if ((c >= 0x0139 && c < 0x0149) || (c > 0x0178 && c < 0x017F)) - { - if ((c & 1) == 0) - c = c-1; - } - else if (c == 0x017F) - { - c = 0x0053; - } - else if (c >= 0x0200 && c <= 0x0217) - { - if (c & 1) - c = c-1; - } - else if (c >= 0x0430 && c<= 0x044F) - { - c -= 32; - } - else if ((c >= 0x0451 && c <= 0x045C) || (c >=0x045E && c<= 0x045F)) - { - c -= 80; - } - else if (c >= 0x0460 && c <= 0x047F) - { - if (c & 1) - c -= 1; - } - else if (c >= 0x0561 && c < 0x0587) - { - c -= 48; - } - else if (c >= 0xFF41 && c <= 0xFF5A) - { - c -= 32; - } + if ((c >= 0x00E0 && c <= 0x00F6) || (c >= 0x00F8 && c <= 0x00FE)) + { + c -= 32; + } + else if (c == 0x00FF) + { + c = 0x0178; + } + else if ((c >= 0x0100 && c < 0x0138) || (c > 0x0149 && c < 0x0178)) + { + if (c == 0x0131) + c = 0x0049; + else if (c & 1) + c -= 1; + } + else if ((c >= 0x0139 && c < 0x0149) || (c > 0x0178 && c < 0x017F)) + { + if ((c & 1) == 0) + c = c-1; + } + else if (c == 0x017F) + { + c = 0x0053; + } + else if (c >= 0x0200 && c <= 0x0217) + { + if (c & 1) + c = c-1; + } + else if (c >= 0x0430 && c<= 0x044F) + { + c -= 32; + } + else if ((c >= 0x0451 && c <= 0x045C) || (c >=0x045E && c<= 0x045F)) + { + c -= 80; + } + else if (c >= 0x0460 && c <= 0x047F) + { + if (c & 1) + c -= 1; + } + else if (c >= 0x0561 && c < 0x0587) + { + c -= 48; + } + else if (c >= 0xFF41 && c <= 0xFF5A) + { + c -= 32; + } } return c; } @@ -189,390 +189,390 @@ int isUniAlpha(dchar u) { static dchar table[][2] = [ - [ 'A', 'Z' ], - [ 'a', 'z' ], - [ 0x00AA, 0x00AA ], - [ 0x00B5, 0x00B5 ], - [ 0x00BA, 0x00BA ], - [ 0x00C0, 0x00D6 ], - [ 0x00D8, 0x00F6 ], - [ 0x00F8, 0x02C1 ], - [ 0x02C6, 0x02D1 ], - [ 0x02E0, 0x02E4 ], - [ 0x02EE, 0x02EE ], - [ 0x037A, 0x037D ], - [ 0x0386, 0x0386 ], - [ 0x0388, 0x038A ], - [ 0x038C, 0x038C ], - [ 0x038E, 0x03A1 ], - [ 0x03A3, 0x03CE ], - [ 0x03D0, 0x03F5 ], - [ 0x03F7, 0x0481 ], - [ 0x048A, 0x0513 ], - [ 0x0531, 0x0556 ], - [ 0x0559, 0x0559 ], - [ 0x0561, 0x0587 ], - [ 0x05D0, 0x05EA ], - [ 0x05F0, 0x05F2 ], - [ 0x0621, 0x063A ], - [ 0x0640, 0x064A ], - [ 0x066E, 0x066F ], - [ 0x0671, 0x06D3 ], - [ 0x06D5, 0x06D5 ], - [ 0x06E5, 0x06E6 ], - [ 0x06EE, 0x06EF ], - [ 0x06FA, 0x06FC ], - [ 0x06FF, 0x06FF ], - [ 0x0710, 0x0710 ], - [ 0x0712, 0x072F ], - [ 0x074D, 0x076D ], - [ 0x0780, 0x07A5 ], - [ 0x07B1, 0x07B1 ], - [ 0x07CA, 0x07EA ], - [ 0x07F4, 0x07F5 ], - [ 0x07FA, 0x07FA ], - [ 0x0904, 0x0939 ], - [ 0x093D, 0x093D ], - [ 0x0950, 0x0950 ], - [ 0x0958, 0x0961 ], - [ 0x097B, 0x097F ], - [ 0x0985, 0x098C ], - [ 0x098F, 0x0990 ], - [ 0x0993, 0x09A8 ], - [ 0x09AA, 0x09B0 ], - [ 0x09B2, 0x09B2 ], - [ 0x09B6, 0x09B9 ], - [ 0x09BD, 0x09BD ], - [ 0x09CE, 0x09CE ], - [ 0x09DC, 0x09DD ], - [ 0x09DF, 0x09E1 ], - [ 0x09F0, 0x09F1 ], - [ 0x0A05, 0x0A0A ], - [ 0x0A0F, 0x0A10 ], - [ 0x0A13, 0x0A28 ], - [ 0x0A2A, 0x0A30 ], - [ 0x0A32, 0x0A33 ], - [ 0x0A35, 0x0A36 ], - [ 0x0A38, 0x0A39 ], - [ 0x0A59, 0x0A5C ], - [ 0x0A5E, 0x0A5E ], - [ 0x0A72, 0x0A74 ], - [ 0x0A85, 0x0A8D ], - [ 0x0A8F, 0x0A91 ], - [ 0x0A93, 0x0AA8 ], - [ 0x0AAA, 0x0AB0 ], - [ 0x0AB2, 0x0AB3 ], - [ 0x0AB5, 0x0AB9 ], - [ 0x0ABD, 0x0ABD ], - [ 0x0AD0, 0x0AD0 ], - [ 0x0AE0, 0x0AE1 ], - [ 0x0B05, 0x0B0C ], - [ 0x0B0F, 0x0B10 ], - [ 0x0B13, 0x0B28 ], - [ 0x0B2A, 0x0B30 ], - [ 0x0B32, 0x0B33 ], - [ 0x0B35, 0x0B39 ], - [ 0x0B3D, 0x0B3D ], - [ 0x0B5C, 0x0B5D ], - [ 0x0B5F, 0x0B61 ], - [ 0x0B71, 0x0B71 ], - [ 0x0B83, 0x0B83 ], - [ 0x0B85, 0x0B8A ], - [ 0x0B8E, 0x0B90 ], - [ 0x0B92, 0x0B95 ], - [ 0x0B99, 0x0B9A ], - [ 0x0B9C, 0x0B9C ], - [ 0x0B9E, 0x0B9F ], - [ 0x0BA3, 0x0BA4 ], - [ 0x0BA8, 0x0BAA ], - [ 0x0BAE, 0x0BB9 ], - [ 0x0C05, 0x0C0C ], - [ 0x0C0E, 0x0C10 ], - [ 0x0C12, 0x0C28 ], - [ 0x0C2A, 0x0C33 ], - [ 0x0C35, 0x0C39 ], - [ 0x0C60, 0x0C61 ], - [ 0x0C85, 0x0C8C ], - [ 0x0C8E, 0x0C90 ], - [ 0x0C92, 0x0CA8 ], - [ 0x0CAA, 0x0CB3 ], - [ 0x0CB5, 0x0CB9 ], - [ 0x0CBD, 0x0CBD ], - [ 0x0CDE, 0x0CDE ], - [ 0x0CE0, 0x0CE1 ], - [ 0x0D05, 0x0D0C ], - [ 0x0D0E, 0x0D10 ], - [ 0x0D12, 0x0D28 ], - [ 0x0D2A, 0x0D39 ], - [ 0x0D60, 0x0D61 ], - [ 0x0D85, 0x0D96 ], - [ 0x0D9A, 0x0DB1 ], - [ 0x0DB3, 0x0DBB ], - [ 0x0DBD, 0x0DBD ], - [ 0x0DC0, 0x0DC6 ], - [ 0x0E01, 0x0E30 ], - [ 0x0E32, 0x0E33 ], - [ 0x0E40, 0x0E46 ], - [ 0x0E81, 0x0E82 ], - [ 0x0E84, 0x0E84 ], - [ 0x0E87, 0x0E88 ], - [ 0x0E8A, 0x0E8A ], - [ 0x0E8D, 0x0E8D ], - [ 0x0E94, 0x0E97 ], - [ 0x0E99, 0x0E9F ], - [ 0x0EA1, 0x0EA3 ], - [ 0x0EA5, 0x0EA5 ], - [ 0x0EA7, 0x0EA7 ], - [ 0x0EAA, 0x0EAB ], - [ 0x0EAD, 0x0EB0 ], - [ 0x0EB2, 0x0EB3 ], - [ 0x0EBD, 0x0EBD ], - [ 0x0EC0, 0x0EC4 ], - [ 0x0EC6, 0x0EC6 ], - [ 0x0EDC, 0x0EDD ], - [ 0x0F00, 0x0F00 ], - [ 0x0F40, 0x0F47 ], - [ 0x0F49, 0x0F6A ], - [ 0x0F88, 0x0F8B ], - [ 0x1000, 0x1021 ], - [ 0x1023, 0x1027 ], - [ 0x1029, 0x102A ], - [ 0x1050, 0x1055 ], - [ 0x10A0, 0x10C5 ], - [ 0x10D0, 0x10FA ], - [ 0x10FC, 0x10FC ], - [ 0x1100, 0x1159 ], - [ 0x115F, 0x11A2 ], - [ 0x11A8, 0x11F9 ], - [ 0x1200, 0x1248 ], - [ 0x124A, 0x124D ], - [ 0x1250, 0x1256 ], - [ 0x1258, 0x1258 ], - [ 0x125A, 0x125D ], - [ 0x1260, 0x1288 ], - [ 0x128A, 0x128D ], - [ 0x1290, 0x12B0 ], - [ 0x12B2, 0x12B5 ], - [ 0x12B8, 0x12BE ], - [ 0x12C0, 0x12C0 ], - [ 0x12C2, 0x12C5 ], - [ 0x12C8, 0x12D6 ], - [ 0x12D8, 0x1310 ], - [ 0x1312, 0x1315 ], - [ 0x1318, 0x135A ], - [ 0x1380, 0x138F ], - [ 0x13A0, 0x13F4 ], - [ 0x1401, 0x166C ], - [ 0x166F, 0x1676 ], - [ 0x1681, 0x169A ], - [ 0x16A0, 0x16EA ], - [ 0x1700, 0x170C ], - [ 0x170E, 0x1711 ], - [ 0x1720, 0x1731 ], - [ 0x1740, 0x1751 ], - [ 0x1760, 0x176C ], - [ 0x176E, 0x1770 ], - [ 0x1780, 0x17B3 ], - [ 0x17D7, 0x17D7 ], - [ 0x17DC, 0x17DC ], - [ 0x1820, 0x1877 ], - [ 0x1880, 0x18A8 ], - [ 0x1900, 0x191C ], - [ 0x1950, 0x196D ], - [ 0x1970, 0x1974 ], - [ 0x1980, 0x19A9 ], - [ 0x19C1, 0x19C7 ], - [ 0x1A00, 0x1A16 ], - [ 0x1B05, 0x1B33 ], - [ 0x1B45, 0x1B4B ], - [ 0x1D00, 0x1DBF ], - [ 0x1E00, 0x1E9B ], - [ 0x1EA0, 0x1EF9 ], - [ 0x1F00, 0x1F15 ], - [ 0x1F18, 0x1F1D ], - [ 0x1F20, 0x1F45 ], - [ 0x1F48, 0x1F4D ], - [ 0x1F50, 0x1F57 ], - [ 0x1F59, 0x1F59 ], - [ 0x1F5B, 0x1F5B ], - [ 0x1F5D, 0x1F5D ], - [ 0x1F5F, 0x1F7D ], - [ 0x1F80, 0x1FB4 ], - [ 0x1FB6, 0x1FBC ], - [ 0x1FBE, 0x1FBE ], - [ 0x1FC2, 0x1FC4 ], - [ 0x1FC6, 0x1FCC ], - [ 0x1FD0, 0x1FD3 ], - [ 0x1FD6, 0x1FDB ], - [ 0x1FE0, 0x1FEC ], - [ 0x1FF2, 0x1FF4 ], - [ 0x1FF6, 0x1FFC ], - [ 0x2071, 0x2071 ], - [ 0x207F, 0x207F ], - [ 0x2090, 0x2094 ], - [ 0x2102, 0x2102 ], - [ 0x2107, 0x2107 ], - [ 0x210A, 0x2113 ], - [ 0x2115, 0x2115 ], - [ 0x2119, 0x211D ], - [ 0x2124, 0x2124 ], - [ 0x2126, 0x2126 ], - [ 0x2128, 0x2128 ], - [ 0x212A, 0x212D ], - [ 0x212F, 0x2139 ], - [ 0x213C, 0x213F ], - [ 0x2145, 0x2149 ], - [ 0x214E, 0x214E ], - [ 0x2183, 0x2184 ], - [ 0x2C00, 0x2C2E ], - [ 0x2C30, 0x2C5E ], - [ 0x2C60, 0x2C6C ], - [ 0x2C74, 0x2C77 ], - [ 0x2C80, 0x2CE4 ], - [ 0x2D00, 0x2D25 ], - [ 0x2D30, 0x2D65 ], - [ 0x2D6F, 0x2D6F ], - [ 0x2D80, 0x2D96 ], - [ 0x2DA0, 0x2DA6 ], - [ 0x2DA8, 0x2DAE ], - [ 0x2DB0, 0x2DB6 ], - [ 0x2DB8, 0x2DBE ], - [ 0x2DC0, 0x2DC6 ], - [ 0x2DC8, 0x2DCE ], - [ 0x2DD0, 0x2DD6 ], - [ 0x2DD8, 0x2DDE ], - [ 0x3005, 0x3006 ], - [ 0x3031, 0x3035 ], - [ 0x303B, 0x303C ], - [ 0x3041, 0x3096 ], - [ 0x309D, 0x309F ], - [ 0x30A1, 0x30FA ], - [ 0x30FC, 0x30FF ], - [ 0x3105, 0x312C ], - [ 0x3131, 0x318E ], - [ 0x31A0, 0x31B7 ], - [ 0x31F0, 0x31FF ], - [ 0x3400, 0x4DB5 ], - [ 0x4E00, 0x9FBB ], - [ 0xA000, 0xA48C ], - [ 0xA717, 0xA71A ], - [ 0xA800, 0xA801 ], - [ 0xA803, 0xA805 ], - [ 0xA807, 0xA80A ], - [ 0xA80C, 0xA822 ], - [ 0xA840, 0xA873 ], - [ 0xAC00, 0xD7A3 ], - [ 0xF900, 0xFA2D ], - [ 0xFA30, 0xFA6A ], - [ 0xFA70, 0xFAD9 ], - [ 0xFB00, 0xFB06 ], - [ 0xFB13, 0xFB17 ], - [ 0xFB1D, 0xFB1D ], - [ 0xFB1F, 0xFB28 ], - [ 0xFB2A, 0xFB36 ], - [ 0xFB38, 0xFB3C ], - [ 0xFB3E, 0xFB3E ], - [ 0xFB40, 0xFB41 ], - [ 0xFB43, 0xFB44 ], - [ 0xFB46, 0xFBB1 ], - [ 0xFBD3, 0xFD3D ], - [ 0xFD50, 0xFD8F ], - [ 0xFD92, 0xFDC7 ], - [ 0xFDF0, 0xFDFB ], - [ 0xFE70, 0xFE74 ], - [ 0xFE76, 0xFEFC ], - [ 0xFF21, 0xFF3A ], - [ 0xFF41, 0xFF5A ], - [ 0xFF66, 0xFFBE ], - [ 0xFFC2, 0xFFC7 ], - [ 0xFFCA, 0xFFCF ], - [ 0xFFD2, 0xFFD7 ], - [ 0xFFDA, 0xFFDC ], - [ 0x10000, 0x1000B ], - [ 0x1000D, 0x10026 ], - [ 0x10028, 0x1003A ], - [ 0x1003C, 0x1003D ], - [ 0x1003F, 0x1004D ], - [ 0x10050, 0x1005D ], - [ 0x10080, 0x100FA ], - [ 0x10300, 0x1031E ], - [ 0x10330, 0x10340 ], - [ 0x10342, 0x10349 ], - [ 0x10380, 0x1039D ], - [ 0x103A0, 0x103C3 ], - [ 0x103C8, 0x103CF ], - [ 0x10400, 0x1049D ], - [ 0x10800, 0x10805 ], - [ 0x10808, 0x10808 ], - [ 0x1080A, 0x10835 ], - [ 0x10837, 0x10838 ], - [ 0x1083C, 0x1083C ], - [ 0x1083F, 0x1083F ], - [ 0x10900, 0x10915 ], - [ 0x10A00, 0x10A00 ], - [ 0x10A10, 0x10A13 ], - [ 0x10A15, 0x10A17 ], - [ 0x10A19, 0x10A33 ], - [ 0x12000, 0x1236E ], - [ 0x1D400, 0x1D454 ], - [ 0x1D456, 0x1D49C ], - [ 0x1D49E, 0x1D49F ], - [ 0x1D4A2, 0x1D4A2 ], - [ 0x1D4A5, 0x1D4A6 ], - [ 0x1D4A9, 0x1D4AC ], - [ 0x1D4AE, 0x1D4B9 ], - [ 0x1D4BB, 0x1D4BB ], - [ 0x1D4BD, 0x1D4C3 ], - [ 0x1D4C5, 0x1D505 ], - [ 0x1D507, 0x1D50A ], - [ 0x1D50D, 0x1D514 ], - [ 0x1D516, 0x1D51C ], - [ 0x1D51E, 0x1D539 ], - [ 0x1D53B, 0x1D53E ], - [ 0x1D540, 0x1D544 ], - [ 0x1D546, 0x1D546 ], - [ 0x1D54A, 0x1D550 ], - [ 0x1D552, 0x1D6A5 ], - [ 0x1D6A8, 0x1D6C0 ], - [ 0x1D6C2, 0x1D6DA ], - [ 0x1D6DC, 0x1D6FA ], - [ 0x1D6FC, 0x1D714 ], - [ 0x1D716, 0x1D734 ], - [ 0x1D736, 0x1D74E ], - [ 0x1D750, 0x1D76E ], - [ 0x1D770, 0x1D788 ], - [ 0x1D78A, 0x1D7A8 ], - [ 0x1D7AA, 0x1D7C2 ], - [ 0x1D7C4, 0x1D7CB ], - [ 0x20000, 0x2A6D6 ], - [ 0x2F800, 0x2FA1D ], + [ 'A', 'Z' ], + [ 'a', 'z' ], + [ 0x00AA, 0x00AA ], + [ 0x00B5, 0x00B5 ], + [ 0x00BA, 0x00BA ], + [ 0x00C0, 0x00D6 ], + [ 0x00D8, 0x00F6 ], + [ 0x00F8, 0x02C1 ], + [ 0x02C6, 0x02D1 ], + [ 0x02E0, 0x02E4 ], + [ 0x02EE, 0x02EE ], + [ 0x037A, 0x037D ], + [ 0x0386, 0x0386 ], + [ 0x0388, 0x038A ], + [ 0x038C, 0x038C ], + [ 0x038E, 0x03A1 ], + [ 0x03A3, 0x03CE ], + [ 0x03D0, 0x03F5 ], + [ 0x03F7, 0x0481 ], + [ 0x048A, 0x0513 ], + [ 0x0531, 0x0556 ], + [ 0x0559, 0x0559 ], + [ 0x0561, 0x0587 ], + [ 0x05D0, 0x05EA ], + [ 0x05F0, 0x05F2 ], + [ 0x0621, 0x063A ], + [ 0x0640, 0x064A ], + [ 0x066E, 0x066F ], + [ 0x0671, 0x06D3 ], + [ 0x06D5, 0x06D5 ], + [ 0x06E5, 0x06E6 ], + [ 0x06EE, 0x06EF ], + [ 0x06FA, 0x06FC ], + [ 0x06FF, 0x06FF ], + [ 0x0710, 0x0710 ], + [ 0x0712, 0x072F ], + [ 0x074D, 0x076D ], + [ 0x0780, 0x07A5 ], + [ 0x07B1, 0x07B1 ], + [ 0x07CA, 0x07EA ], + [ 0x07F4, 0x07F5 ], + [ 0x07FA, 0x07FA ], + [ 0x0904, 0x0939 ], + [ 0x093D, 0x093D ], + [ 0x0950, 0x0950 ], + [ 0x0958, 0x0961 ], + [ 0x097B, 0x097F ], + [ 0x0985, 0x098C ], + [ 0x098F, 0x0990 ], + [ 0x0993, 0x09A8 ], + [ 0x09AA, 0x09B0 ], + [ 0x09B2, 0x09B2 ], + [ 0x09B6, 0x09B9 ], + [ 0x09BD, 0x09BD ], + [ 0x09CE, 0x09CE ], + [ 0x09DC, 0x09DD ], + [ 0x09DF, 0x09E1 ], + [ 0x09F0, 0x09F1 ], + [ 0x0A05, 0x0A0A ], + [ 0x0A0F, 0x0A10 ], + [ 0x0A13, 0x0A28 ], + [ 0x0A2A, 0x0A30 ], + [ 0x0A32, 0x0A33 ], + [ 0x0A35, 0x0A36 ], + [ 0x0A38, 0x0A39 ], + [ 0x0A59, 0x0A5C ], + [ 0x0A5E, 0x0A5E ], + [ 0x0A72, 0x0A74 ], + [ 0x0A85, 0x0A8D ], + [ 0x0A8F, 0x0A91 ], + [ 0x0A93, 0x0AA8 ], + [ 0x0AAA, 0x0AB0 ], + [ 0x0AB2, 0x0AB3 ], + [ 0x0AB5, 0x0AB9 ], + [ 0x0ABD, 0x0ABD ], + [ 0x0AD0, 0x0AD0 ], + [ 0x0AE0, 0x0AE1 ], + [ 0x0B05, 0x0B0C ], + [ 0x0B0F, 0x0B10 ], + [ 0x0B13, 0x0B28 ], + [ 0x0B2A, 0x0B30 ], + [ 0x0B32, 0x0B33 ], + [ 0x0B35, 0x0B39 ], + [ 0x0B3D, 0x0B3D ], + [ 0x0B5C, 0x0B5D ], + [ 0x0B5F, 0x0B61 ], + [ 0x0B71, 0x0B71 ], + [ 0x0B83, 0x0B83 ], + [ 0x0B85, 0x0B8A ], + [ 0x0B8E, 0x0B90 ], + [ 0x0B92, 0x0B95 ], + [ 0x0B99, 0x0B9A ], + [ 0x0B9C, 0x0B9C ], + [ 0x0B9E, 0x0B9F ], + [ 0x0BA3, 0x0BA4 ], + [ 0x0BA8, 0x0BAA ], + [ 0x0BAE, 0x0BB9 ], + [ 0x0C05, 0x0C0C ], + [ 0x0C0E, 0x0C10 ], + [ 0x0C12, 0x0C28 ], + [ 0x0C2A, 0x0C33 ], + [ 0x0C35, 0x0C39 ], + [ 0x0C60, 0x0C61 ], + [ 0x0C85, 0x0C8C ], + [ 0x0C8E, 0x0C90 ], + [ 0x0C92, 0x0CA8 ], + [ 0x0CAA, 0x0CB3 ], + [ 0x0CB5, 0x0CB9 ], + [ 0x0CBD, 0x0CBD ], + [ 0x0CDE, 0x0CDE ], + [ 0x0CE0, 0x0CE1 ], + [ 0x0D05, 0x0D0C ], + [ 0x0D0E, 0x0D10 ], + [ 0x0D12, 0x0D28 ], + [ 0x0D2A, 0x0D39 ], + [ 0x0D60, 0x0D61 ], + [ 0x0D85, 0x0D96 ], + [ 0x0D9A, 0x0DB1 ], + [ 0x0DB3, 0x0DBB ], + [ 0x0DBD, 0x0DBD ], + [ 0x0DC0, 0x0DC6 ], + [ 0x0E01, 0x0E30 ], + [ 0x0E32, 0x0E33 ], + [ 0x0E40, 0x0E46 ], + [ 0x0E81, 0x0E82 ], + [ 0x0E84, 0x0E84 ], + [ 0x0E87, 0x0E88 ], + [ 0x0E8A, 0x0E8A ], + [ 0x0E8D, 0x0E8D ], + [ 0x0E94, 0x0E97 ], + [ 0x0E99, 0x0E9F ], + [ 0x0EA1, 0x0EA3 ], + [ 0x0EA5, 0x0EA5 ], + [ 0x0EA7, 0x0EA7 ], + [ 0x0EAA, 0x0EAB ], + [ 0x0EAD, 0x0EB0 ], + [ 0x0EB2, 0x0EB3 ], + [ 0x0EBD, 0x0EBD ], + [ 0x0EC0, 0x0EC4 ], + [ 0x0EC6, 0x0EC6 ], + [ 0x0EDC, 0x0EDD ], + [ 0x0F00, 0x0F00 ], + [ 0x0F40, 0x0F47 ], + [ 0x0F49, 0x0F6A ], + [ 0x0F88, 0x0F8B ], + [ 0x1000, 0x1021 ], + [ 0x1023, 0x1027 ], + [ 0x1029, 0x102A ], + [ 0x1050, 0x1055 ], + [ 0x10A0, 0x10C5 ], + [ 0x10D0, 0x10FA ], + [ 0x10FC, 0x10FC ], + [ 0x1100, 0x1159 ], + [ 0x115F, 0x11A2 ], + [ 0x11A8, 0x11F9 ], + [ 0x1200, 0x1248 ], + [ 0x124A, 0x124D ], + [ 0x1250, 0x1256 ], + [ 0x1258, 0x1258 ], + [ 0x125A, 0x125D ], + [ 0x1260, 0x1288 ], + [ 0x128A, 0x128D ], + [ 0x1290, 0x12B0 ], + [ 0x12B2, 0x12B5 ], + [ 0x12B8, 0x12BE ], + [ 0x12C0, 0x12C0 ], + [ 0x12C2, 0x12C5 ], + [ 0x12C8, 0x12D6 ], + [ 0x12D8, 0x1310 ], + [ 0x1312, 0x1315 ], + [ 0x1318, 0x135A ], + [ 0x1380, 0x138F ], + [ 0x13A0, 0x13F4 ], + [ 0x1401, 0x166C ], + [ 0x166F, 0x1676 ], + [ 0x1681, 0x169A ], + [ 0x16A0, 0x16EA ], + [ 0x1700, 0x170C ], + [ 0x170E, 0x1711 ], + [ 0x1720, 0x1731 ], + [ 0x1740, 0x1751 ], + [ 0x1760, 0x176C ], + [ 0x176E, 0x1770 ], + [ 0x1780, 0x17B3 ], + [ 0x17D7, 0x17D7 ], + [ 0x17DC, 0x17DC ], + [ 0x1820, 0x1877 ], + [ 0x1880, 0x18A8 ], + [ 0x1900, 0x191C ], + [ 0x1950, 0x196D ], + [ 0x1970, 0x1974 ], + [ 0x1980, 0x19A9 ], + [ 0x19C1, 0x19C7 ], + [ 0x1A00, 0x1A16 ], + [ 0x1B05, 0x1B33 ], + [ 0x1B45, 0x1B4B ], + [ 0x1D00, 0x1DBF ], + [ 0x1E00, 0x1E9B ], + [ 0x1EA0, 0x1EF9 ], + [ 0x1F00, 0x1F15 ], + [ 0x1F18, 0x1F1D ], + [ 0x1F20, 0x1F45 ], + [ 0x1F48, 0x1F4D ], + [ 0x1F50, 0x1F57 ], + [ 0x1F59, 0x1F59 ], + [ 0x1F5B, 0x1F5B ], + [ 0x1F5D, 0x1F5D ], + [ 0x1F5F, 0x1F7D ], + [ 0x1F80, 0x1FB4 ], + [ 0x1FB6, 0x1FBC ], + [ 0x1FBE, 0x1FBE ], + [ 0x1FC2, 0x1FC4 ], + [ 0x1FC6, 0x1FCC ], + [ 0x1FD0, 0x1FD3 ], + [ 0x1FD6, 0x1FDB ], + [ 0x1FE0, 0x1FEC ], + [ 0x1FF2, 0x1FF4 ], + [ 0x1FF6, 0x1FFC ], + [ 0x2071, 0x2071 ], + [ 0x207F, 0x207F ], + [ 0x2090, 0x2094 ], + [ 0x2102, 0x2102 ], + [ 0x2107, 0x2107 ], + [ 0x210A, 0x2113 ], + [ 0x2115, 0x2115 ], + [ 0x2119, 0x211D ], + [ 0x2124, 0x2124 ], + [ 0x2126, 0x2126 ], + [ 0x2128, 0x2128 ], + [ 0x212A, 0x212D ], + [ 0x212F, 0x2139 ], + [ 0x213C, 0x213F ], + [ 0x2145, 0x2149 ], + [ 0x214E, 0x214E ], + [ 0x2183, 0x2184 ], + [ 0x2C00, 0x2C2E ], + [ 0x2C30, 0x2C5E ], + [ 0x2C60, 0x2C6C ], + [ 0x2C74, 0x2C77 ], + [ 0x2C80, 0x2CE4 ], + [ 0x2D00, 0x2D25 ], + [ 0x2D30, 0x2D65 ], + [ 0x2D6F, 0x2D6F ], + [ 0x2D80, 0x2D96 ], + [ 0x2DA0, 0x2DA6 ], + [ 0x2DA8, 0x2DAE ], + [ 0x2DB0, 0x2DB6 ], + [ 0x2DB8, 0x2DBE ], + [ 0x2DC0, 0x2DC6 ], + [ 0x2DC8, 0x2DCE ], + [ 0x2DD0, 0x2DD6 ], + [ 0x2DD8, 0x2DDE ], + [ 0x3005, 0x3006 ], + [ 0x3031, 0x3035 ], + [ 0x303B, 0x303C ], + [ 0x3041, 0x3096 ], + [ 0x309D, 0x309F ], + [ 0x30A1, 0x30FA ], + [ 0x30FC, 0x30FF ], + [ 0x3105, 0x312C ], + [ 0x3131, 0x318E ], + [ 0x31A0, 0x31B7 ], + [ 0x31F0, 0x31FF ], + [ 0x3400, 0x4DB5 ], + [ 0x4E00, 0x9FBB ], + [ 0xA000, 0xA48C ], + [ 0xA717, 0xA71A ], + [ 0xA800, 0xA801 ], + [ 0xA803, 0xA805 ], + [ 0xA807, 0xA80A ], + [ 0xA80C, 0xA822 ], + [ 0xA840, 0xA873 ], + [ 0xAC00, 0xD7A3 ], + [ 0xF900, 0xFA2D ], + [ 0xFA30, 0xFA6A ], + [ 0xFA70, 0xFAD9 ], + [ 0xFB00, 0xFB06 ], + [ 0xFB13, 0xFB17 ], + [ 0xFB1D, 0xFB1D ], + [ 0xFB1F, 0xFB28 ], + [ 0xFB2A, 0xFB36 ], + [ 0xFB38, 0xFB3C ], + [ 0xFB3E, 0xFB3E ], + [ 0xFB40, 0xFB41 ], + [ 0xFB43, 0xFB44 ], + [ 0xFB46, 0xFBB1 ], + [ 0xFBD3, 0xFD3D ], + [ 0xFD50, 0xFD8F ], + [ 0xFD92, 0xFDC7 ], + [ 0xFDF0, 0xFDFB ], + [ 0xFE70, 0xFE74 ], + [ 0xFE76, 0xFEFC ], + [ 0xFF21, 0xFF3A ], + [ 0xFF41, 0xFF5A ], + [ 0xFF66, 0xFFBE ], + [ 0xFFC2, 0xFFC7 ], + [ 0xFFCA, 0xFFCF ], + [ 0xFFD2, 0xFFD7 ], + [ 0xFFDA, 0xFFDC ], + [ 0x10000, 0x1000B ], + [ 0x1000D, 0x10026 ], + [ 0x10028, 0x1003A ], + [ 0x1003C, 0x1003D ], + [ 0x1003F, 0x1004D ], + [ 0x10050, 0x1005D ], + [ 0x10080, 0x100FA ], + [ 0x10300, 0x1031E ], + [ 0x10330, 0x10340 ], + [ 0x10342, 0x10349 ], + [ 0x10380, 0x1039D ], + [ 0x103A0, 0x103C3 ], + [ 0x103C8, 0x103CF ], + [ 0x10400, 0x1049D ], + [ 0x10800, 0x10805 ], + [ 0x10808, 0x10808 ], + [ 0x1080A, 0x10835 ], + [ 0x10837, 0x10838 ], + [ 0x1083C, 0x1083C ], + [ 0x1083F, 0x1083F ], + [ 0x10900, 0x10915 ], + [ 0x10A00, 0x10A00 ], + [ 0x10A10, 0x10A13 ], + [ 0x10A15, 0x10A17 ], + [ 0x10A19, 0x10A33 ], + [ 0x12000, 0x1236E ], + [ 0x1D400, 0x1D454 ], + [ 0x1D456, 0x1D49C ], + [ 0x1D49E, 0x1D49F ], + [ 0x1D4A2, 0x1D4A2 ], + [ 0x1D4A5, 0x1D4A6 ], + [ 0x1D4A9, 0x1D4AC ], + [ 0x1D4AE, 0x1D4B9 ], + [ 0x1D4BB, 0x1D4BB ], + [ 0x1D4BD, 0x1D4C3 ], + [ 0x1D4C5, 0x1D505 ], + [ 0x1D507, 0x1D50A ], + [ 0x1D50D, 0x1D514 ], + [ 0x1D516, 0x1D51C ], + [ 0x1D51E, 0x1D539 ], + [ 0x1D53B, 0x1D53E ], + [ 0x1D540, 0x1D544 ], + [ 0x1D546, 0x1D546 ], + [ 0x1D54A, 0x1D550 ], + [ 0x1D552, 0x1D6A5 ], + [ 0x1D6A8, 0x1D6C0 ], + [ 0x1D6C2, 0x1D6DA ], + [ 0x1D6DC, 0x1D6FA ], + [ 0x1D6FC, 0x1D714 ], + [ 0x1D716, 0x1D734 ], + [ 0x1D736, 0x1D74E ], + [ 0x1D750, 0x1D76E ], + [ 0x1D770, 0x1D788 ], + [ 0x1D78A, 0x1D7A8 ], + [ 0x1D7AA, 0x1D7C2 ], + [ 0x1D7C4, 0x1D7CB ], + [ 0x20000, 0x2A6D6 ], + [ 0x2F800, 0x2FA1D ], ]; debug { - for (int i = 0; i < table.length; i++) - { - assert(table[i][0] <= table[i][1]); - if (i < table.length - 1) - { - if (table[i][1] >= table[i + 1][0]) - printf("table[%d][1] = x%x, table[%d][0] = x%x\n", i, table[i][1], i + 1, table[i + 1][0]); - assert(table[i][1] < table[i + 1][0]); - } - } + for (int i = 0; i < table.length; i++) + { + assert(table[i][0] <= table[i][1]); + if (i < table.length - 1) + { + if (table[i][1] >= table[i + 1][0]) + printf("table[%d][1] = x%x, table[%d][0] = x%x\n", i, table[i][1], i + 1, table[i + 1][0]); + assert(table[i][1] < table[i + 1][0]); + } + } } if (u < 0xAA) { - if (u < 'A') - goto Lisnot; - if (u <= 'Z') - goto Lis; - if (u < 'a') - goto Lisnot; - if (u <= 'z') - goto Lis; - goto Lisnot; + if (u < 'A') + goto Lisnot; + if (u <= 'Z') + goto Lis; + if (u < 'a') + goto Lisnot; + if (u <= 'z') + goto Lis; + goto Lisnot; } // Binary search @@ -584,48 +584,48 @@ int isUniAlpha(dchar u) high = table.length - 1; while (cast(int)low <= cast(int)high) { - mid = (low + high) >> 1; - if (u < table[mid][0]) - high = mid - 1; - else if (u > table[mid][1]) - low = mid + 1; - else - goto Lis; + mid = (low + high) >> 1; + if (u < table[mid][0]) + high = mid - 1; + else if (u > table[mid][1]) + low = mid + 1; + else + goto Lis; } Lisnot: debug { - for (int i = 0; i < table.length; i++) - { - assert(u < table[i][0] || u > table[i][1]); - } + for (int i = 0; i < table.length; i++) + { + assert(u < table[i][0] || u > table[i][1]); + } } return 0; Lis: debug { - for (int i = 0; i < table.length; i++) - { - if (u >= table[i][0] && u <= table[i][1]) - return 1; - } - assert(0); // should have been in table + for (int i = 0; i < table.length; i++) + { + if (u >= table[i][0] && u <= table[i][1]) + return 1; + } + assert(0); // should have been in table } else - return 1; + return 1; } unittest { for (uint i = 0; i < 0x80; i++) { - if (i >= 'A' && i <= 'Z') - assert(isUniAlpha(i)); - else if (i >= 'a' && i <= 'z') - assert(isUniAlpha(i)); - else - assert(!isUniAlpha(i)); + if (i >= 'A' && i <= 'Z') + assert(isUniAlpha(i)); + else if (i >= 'a' && i <= 'z') + assert(isUniAlpha(i)); + else + assert(!isUniAlpha(i)); } } diff --git a/std/uri.d b/std/uri.d index a2b1a7a8d..472acc3fd 100644 --- a/std/uri.d +++ b/std/uri.d @@ -30,15 +30,15 @@ * Escape sequences consist of $(B %) followed by two hex digits. * * See_Also: - * $(LINK2 http://www.ietf.org/rfc/rfc3986.txt, RFC 3986)
- * $(LINK2 http://en.wikipedia.org/wiki/Uniform_resource_identifier, Wikipedia) + * $(LINK2 http://www.ietf.org/rfc/rfc3986.txt, RFC 3986)
+ * $(LINK2 http://en.wikipedia.org/wiki/Uniform_resource_identifier, Wikipedia) * Macros: - * WIKI = Phobos/StdUri + * WIKI = Phobos/StdUri */ module std.uri; -//debug=uri; // uncomment to turn on debugging printf's +//debug=uri; // uncomment to turn on debugging printf's /* ====================== URI Functions ================ */ @@ -51,7 +51,7 @@ class URIerror : Error { this() { - super("URI error"); + super("URI error"); } } @@ -61,29 +61,29 @@ enum URI_Reserved = 2, URI_Mark = 4, URI_Digit = 8, - URI_Hash = 0x10, // '#' + URI_Hash = 0x10, // '#' } char[16] hex2ascii = "0123456789ABCDEF"; -ubyte[128] uri_flags; // indexed by character +ubyte[128] uri_flags; // indexed by character static this() { // Initialize uri_flags[] static void helper(char[] p, uint flags) - { int i; + { int i; - for (i = 0; i < p.length; i++) - uri_flags[p[i]] |= flags; + for (i = 0; i < p.length; i++) + uri_flags[p[i]] |= flags; } uri_flags['#'] |= URI_Hash; for (int i = 'A'; i <= 'Z'; i++) - { uri_flags[i] |= URI_Alpha; - uri_flags[i + 0x20] |= URI_Alpha; // lowercase letters + { uri_flags[i] |= URI_Alpha; + uri_flags[i + 0x20] |= URI_Alpha; // lowercase letters } helper("0123456789", URI_Digit); helper(";/?:@&=+$,", URI_Reserved); @@ -102,7 +102,7 @@ private char[] URI_Encode(dchar[] string, uint unescapedSet) char[50] buffer = void; char* R; uint Rlen; - uint Rsize; // alloc'd size + uint Rsize; // alloc'd size len = string.length; @@ -112,109 +112,109 @@ private char[] URI_Encode(dchar[] string, uint unescapedSet) for (k = 0; k != len; k++) { - C = string[k]; - // if (C in unescapedSet) - if (C < uri_flags.length && uri_flags[C] & unescapedSet) - { - if (Rlen == Rsize) - { char* R2; + C = string[k]; + // if (C in unescapedSet) + if (C < uri_flags.length && uri_flags[C] & unescapedSet) + { + if (Rlen == Rsize) + { char* R2; - Rsize *= 2; - if (Rsize > 1024) - R2 = (new char[Rsize]).ptr; - else - { R2 = cast(char *)alloca(Rsize * char.sizeof); - if (!R2) - goto LthrowURIerror; - } - R2[0..Rlen] = R[0..Rlen]; - R = R2; - } - R[Rlen] = cast(char)C; - Rlen++; - } - else - { char[6] Octet; - uint L; + Rsize *= 2; + if (Rsize > 1024) + R2 = (new char[Rsize]).ptr; + else + { R2 = cast(char *)alloca(Rsize * char.sizeof); + if (!R2) + goto LthrowURIerror; + } + R2[0..Rlen] = R[0..Rlen]; + R = R2; + } + R[Rlen] = cast(char)C; + Rlen++; + } + else + { char[6] Octet; + uint L; - V = C; + V = C; - // Transform V into octets - if (V <= 0x7F) - { - Octet[0] = cast(char) V; - L = 1; - } - else if (V <= 0x7FF) - { - Octet[0] = cast(char)(0xC0 | (V >> 6)); - Octet[1] = cast(char)(0x80 | (V & 0x3F)); - L = 2; - } - else if (V <= 0xFFFF) - { - Octet[0] = cast(char)(0xE0 | (V >> 12)); - Octet[1] = cast(char)(0x80 | ((V >> 6) & 0x3F)); - Octet[2] = cast(char)(0x80 | (V & 0x3F)); - L = 3; - } - else if (V <= 0x1FFFFF) - { - Octet[0] = cast(char)(0xF0 | (V >> 18)); - Octet[1] = cast(char)(0x80 | ((V >> 12) & 0x3F)); - Octet[2] = cast(char)(0x80 | ((V >> 6) & 0x3F)); - Octet[3] = cast(char)(0x80 | (V & 0x3F)); - L = 4; - } - /+ - else if (V <= 0x3FFFFFF) - { - Octet[0] = cast(char)(0xF8 | (V >> 24)); - Octet[1] = cast(char)(0x80 | ((V >> 18) & 0x3F)); - Octet[2] = cast(char)(0x80 | ((V >> 12) & 0x3F)); - Octet[3] = cast(char)(0x80 | ((V >> 6) & 0x3F)); - Octet[4] = cast(char)(0x80 | (V & 0x3F)); - L = 5; - } - else if (V <= 0x7FFFFFFF) - { - Octet[0] = cast(char)(0xFC | (V >> 30)); - Octet[1] = cast(char)(0x80 | ((V >> 24) & 0x3F)); - Octet[2] = cast(char)(0x80 | ((V >> 18) & 0x3F)); - Octet[3] = cast(char)(0x80 | ((V >> 12) & 0x3F)); - Octet[4] = cast(char)(0x80 | ((V >> 6) & 0x3F)); - Octet[5] = cast(char)(0x80 | (V & 0x3F)); - L = 6; - } - +/ - else - { goto LthrowURIerror; // undefined UTF-32 code - } + // Transform V into octets + if (V <= 0x7F) + { + Octet[0] = cast(char) V; + L = 1; + } + else if (V <= 0x7FF) + { + Octet[0] = cast(char)(0xC0 | (V >> 6)); + Octet[1] = cast(char)(0x80 | (V & 0x3F)); + L = 2; + } + else if (V <= 0xFFFF) + { + Octet[0] = cast(char)(0xE0 | (V >> 12)); + Octet[1] = cast(char)(0x80 | ((V >> 6) & 0x3F)); + Octet[2] = cast(char)(0x80 | (V & 0x3F)); + L = 3; + } + else if (V <= 0x1FFFFF) + { + Octet[0] = cast(char)(0xF0 | (V >> 18)); + Octet[1] = cast(char)(0x80 | ((V >> 12) & 0x3F)); + Octet[2] = cast(char)(0x80 | ((V >> 6) & 0x3F)); + Octet[3] = cast(char)(0x80 | (V & 0x3F)); + L = 4; + } + /+ + else if (V <= 0x3FFFFFF) + { + Octet[0] = cast(char)(0xF8 | (V >> 24)); + Octet[1] = cast(char)(0x80 | ((V >> 18) & 0x3F)); + Octet[2] = cast(char)(0x80 | ((V >> 12) & 0x3F)); + Octet[3] = cast(char)(0x80 | ((V >> 6) & 0x3F)); + Octet[4] = cast(char)(0x80 | (V & 0x3F)); + L = 5; + } + else if (V <= 0x7FFFFFFF) + { + Octet[0] = cast(char)(0xFC | (V >> 30)); + Octet[1] = cast(char)(0x80 | ((V >> 24) & 0x3F)); + Octet[2] = cast(char)(0x80 | ((V >> 18) & 0x3F)); + Octet[3] = cast(char)(0x80 | ((V >> 12) & 0x3F)); + Octet[4] = cast(char)(0x80 | ((V >> 6) & 0x3F)); + Octet[5] = cast(char)(0x80 | (V & 0x3F)); + L = 6; + } + +/ + else + { goto LthrowURIerror; // undefined UTF-32 code + } - if (Rlen + L * 3 > Rsize) - { char *R2; + if (Rlen + L * 3 > Rsize) + { char *R2; - Rsize = 2 * (Rlen + L * 3); - if (Rsize > 1024) - R2 = (new char[Rsize]).ptr; - else - { R2 = cast(char *)alloca(Rsize * char.sizeof); - if (!R2) - goto LthrowURIerror; - } - R2[0..Rlen] = R[0..Rlen]; - R = R2; - } + Rsize = 2 * (Rlen + L * 3); + if (Rsize > 1024) + R2 = (new char[Rsize]).ptr; + else + { R2 = cast(char *)alloca(Rsize * char.sizeof); + if (!R2) + goto LthrowURIerror; + } + R2[0..Rlen] = R[0..Rlen]; + R = R2; + } - for (j = 0; j < L; j++) - { - R[Rlen] = '%'; - R[Rlen + 1] = hex2ascii[Octet[j] >> 4]; - R[Rlen + 2] = hex2ascii[Octet[j] & 15]; + for (j = 0; j < L; j++) + { + R[Rlen] = '%'; + R[Rlen + 1] = hex2ascii[Octet[j] >> 4]; + R[Rlen + 2] = hex2ascii[Octet[j] & 15]; - Rlen += 3; - } - } + Rlen += 3; + } + } } char[] result = new char[Rlen]; @@ -228,8 +228,8 @@ LthrowURIerror: uint ascii2hex(dchar c) { return (c <= '9') ? c - '0' : - (c <= 'F') ? c - 'A' + 10 : - c - 'a' + 10; + (c <= 'F') ? c - 'A' + 10 : + c - 'a' + 10; } private dchar[] URI_Decode(char[] string, uint reservedSet) @@ -245,7 +245,7 @@ private dchar[] URI_Decode(char[] string, uint reservedSet) // Result array, allocated on stack dchar* R; uint Rlen; - uint Rsize; // alloc'd size + uint Rsize; // alloc'd size len = string.length; s = string.ptr; @@ -253,87 +253,87 @@ private dchar[] URI_Decode(char[] string, uint reservedSet) // Preallocate result buffer R guaranteed to be large enough for result Rsize = len; if (Rsize > 1024 / dchar.sizeof) - R = (new dchar[Rsize]).ptr; + R = (new dchar[Rsize]).ptr; else - { R = cast(dchar *)alloca(Rsize * dchar.sizeof); - if (!R) - goto LthrowURIerror; + { R = cast(dchar *)alloca(Rsize * dchar.sizeof); + if (!R) + goto LthrowURIerror; } Rlen = 0; for (k = 0; k != len; k++) - { char B; - uint start; + { char B; + uint start; - C = s[k]; - if (C != '%') - { R[Rlen] = C; - Rlen++; - continue; - } - start = k; - if (k + 2 >= len) - goto LthrowURIerror; - if (!isxdigit(s[k + 1]) || !isxdigit(s[k + 2])) - goto LthrowURIerror; - B = cast(char)((ascii2hex(s[k + 1]) << 4) + ascii2hex(s[k + 2])); - k += 2; - if ((B & 0x80) == 0) - { - C = B; - } - else - { uint n; + C = s[k]; + if (C != '%') + { R[Rlen] = C; + Rlen++; + continue; + } + start = k; + if (k + 2 >= len) + goto LthrowURIerror; + if (!isxdigit(s[k + 1]) || !isxdigit(s[k + 2])) + goto LthrowURIerror; + B = cast(char)((ascii2hex(s[k + 1]) << 4) + ascii2hex(s[k + 2])); + k += 2; + if ((B & 0x80) == 0) + { + C = B; + } + else + { uint n; - for (n = 1; ; n++) - { - if (n > 4) - goto LthrowURIerror; - if (((B << n) & 0x80) == 0) - { - if (n == 1) - goto LthrowURIerror; - break; - } - } + for (n = 1; ; n++) + { + if (n > 4) + goto LthrowURIerror; + if (((B << n) & 0x80) == 0) + { + if (n == 1) + goto LthrowURIerror; + break; + } + } - // Pick off (7 - n) significant bits of B from first byte of octet - V = B & ((1 << (7 - n)) - 1); // (!!!) + // Pick off (7 - n) significant bits of B from first byte of octet + V = B & ((1 << (7 - n)) - 1); // (!!!) - if (k + (3 * (n - 1)) >= len) - goto LthrowURIerror; - for (j = 1; j != n; j++) - { - k++; - if (s[k] != '%') - goto LthrowURIerror; - if (!isxdigit(s[k + 1]) || !isxdigit(s[k + 2])) - goto LthrowURIerror; - B = cast(char)((ascii2hex(s[k + 1]) << 4) + ascii2hex(s[k + 2])); - if ((B & 0xC0) != 0x80) - goto LthrowURIerror; - k += 2; - V = (V << 6) | (B & 0x3F); - } - if (V > 0x10FFFF) - goto LthrowURIerror; - C = V; - } - if (C < uri_flags.length && uri_flags[C] & reservedSet) - { - // R ~= s[start .. k + 1]; - int width = (k + 1) - start; - for (int ii = 0; ii < width; ii++) - R[Rlen + ii] = s[start + ii]; - Rlen += width; - } - else - { - R[Rlen] = C; - Rlen++; - } + if (k + (3 * (n - 1)) >= len) + goto LthrowURIerror; + for (j = 1; j != n; j++) + { + k++; + if (s[k] != '%') + goto LthrowURIerror; + if (!isxdigit(s[k + 1]) || !isxdigit(s[k + 2])) + goto LthrowURIerror; + B = cast(char)((ascii2hex(s[k + 1]) << 4) + ascii2hex(s[k + 2])); + if ((B & 0xC0) != 0x80) + goto LthrowURIerror; + k += 2; + V = (V << 6) | (B & 0x3F); + } + if (V > 0x10FFFF) + goto LthrowURIerror; + C = V; + } + if (C < uri_flags.length && uri_flags[C] & reservedSet) + { + // R ~= s[start .. k + 1]; + int width = (k + 1) - start; + for (int ii = 0; ii < width; ii++) + R[Rlen + ii] = s[start + ii]; + Rlen += width; + } + else + { + R[Rlen] = C; + Rlen++; + } } - assert(Rlen <= Rsize); // enforce our preallocation size guarantee + assert(Rlen <= Rsize); // enforce our preallocation size guarantee // Copy array on stack to array in memory dchar[] d = new dchar[Rlen]; @@ -424,7 +424,7 @@ unittest str[] = 'A'; r = encodeComponent(str); foreach (char c; r) - assert(c == 'A'); + assert(c == 'A'); r = decode("%41%42%43"); debug(uri) writefln(r); diff --git a/std/utf.d b/std/utf.d index 6b82b0ea6..b295ee5a9 100644 --- a/std/utf.d +++ b/std/utf.d @@ -28,32 +28,32 @@ * For Win32 systems, the C wchar_t type is UTF-16 and corresponds to the D * wchar type. * For linux systems, the C wchar_t type is UTF-32 and corresponds to - * the D utf.dchar type. + * the D utf.dchar type. * * UTF character support is restricted to (\u0000 <= character <= \U0010FFFF). * * See_Also: - * $(LINK2 http://en.wikipedia.org/wiki/Unicode, Wikipedia)
- * $(LINK http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8)
- * $(LINK http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335) + * $(LINK2 http://en.wikipedia.org/wiki/Unicode, Wikipedia)
+ * $(LINK http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8)
+ * $(LINK http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335) * Macros: - * WIKI = Phobos/StdUtf + * WIKI = Phobos/StdUtf */ - + module std.utf; private import std.stdio; -//debug=utf; // uncomment to turn on debugging printf's +//debug=utf; // uncomment to turn on debugging printf's deprecated class UtfError : Error { - size_t idx; // index in string of where error occurred + size_t idx; // index in string of where error occurred this(char[] s, size_t i) { - idx = i; - super(s); + idx = i; + super(s); } } @@ -63,12 +63,12 @@ deprecated class UtfError : Error class UtfException : Exception { - size_t idx; /// index in string of where error occurred + size_t idx; /// index in string of where error occurred this(char[] s, size_t i) { - idx = i; - super(s); + idx = i; + super(s); } } @@ -91,7 +91,7 @@ bool isValidDchar(dchar c) */ return c < 0xD800 || - (c > 0xDFFF && c <= 0x10FFFF /*&& c != 0xFFFE && c != 0xFFFF*/); + (c > 0xDFFF && c <= 0x10FFFF /*&& c != 0xFFFE && c != 0xFFFF*/); } unittest @@ -126,8 +126,8 @@ ubyte[256] UTF8stride = * stride() returns the length of a UTF-8 sequence starting at index i * in string s. * Returns: - * The number of bytes in the UTF-8 sequence or - * 0xFF meaning s[i] is not the start of of UTF-8 sequence. + * The number of bytes in the UTF-8 sequence or + * 0xFF meaning s[i] is not the start of of UTF-8 sequence. */ uint stride(char[] s, size_t i) @@ -170,15 +170,15 @@ size_t toUCSindex(char[] s, size_t i) for (j = 0; j < i; j += stride) { - stride = UTF8stride[s[j]]; - if (stride == 0xFF) - goto Lerr; - n++; + stride = UTF8stride[s[j]]; + if (stride == 0xFF) + goto Lerr; + n++; } if (j > i) { Lerr: - throw new UtfException("1invalid UTF-8 sequence", j); + throw new UtfException("1invalid UTF-8 sequence", j); } return n; } @@ -191,15 +191,15 @@ size_t toUCSindex(wchar[] s, size_t i) size_t j; for (j = 0; j < i; ) - { uint u = s[j]; + { uint u = s[j]; - j += 1 + (u >= 0xD800 && u <= 0xDBFF); - n++; + j += 1 + (u >= 0xD800 && u <= 0xDBFF); + n++; } if (j > i) { Lerr: - throw new UtfException("2invalid UTF-16 sequence", j); + throw new UtfException("2invalid UTF-16 sequence", j); } return n; } @@ -221,10 +221,10 @@ size_t toUTFindex(char[] s, size_t n) while (n--) { - uint j = UTF8stride[s[i]]; - if (j == 0xFF) - throw new UtfException("3invalid UTF-8 sequence", i); - i += j; + uint j = UTF8stride[s[i]]; + if (j == 0xFF) + throw new UtfException("3invalid UTF-8 sequence", i); + i += j; } return i; } @@ -236,9 +236,9 @@ size_t toUTFindex(wchar[] s, size_t n) size_t i; while (n--) - { wchar u = s[i]; + { wchar u = s[i]; - i += 1 + (u >= 0xD800 && u <= 0xDBFF); + i += 1 + (u >= 0xD800 && u <= 0xDBFF); } return i; } @@ -261,88 +261,88 @@ size_t toUTFindex(dchar[] s, size_t n) dchar decode(char[] s, inout size_t idx) in { - assert(idx >= 0 && idx < s.length); + assert(idx >= 0 && idx < s.length); } out (result) { - assert(isValidDchar(result)); + assert(isValidDchar(result)); } body { - size_t len = s.length; - dchar V; - size_t i = idx; - char u = s[i]; + size_t len = s.length; + dchar V; + size_t i = idx; + char u = s[i]; - if (u & 0x80) - { uint n; - char u2; + if (u & 0x80) + { uint n; + char u2; - /* The following encodings are valid, except for the 5 and 6 byte - * combinations: - * 0xxxxxxx - * 110xxxxx 10xxxxxx - * 1110xxxx 10xxxxxx 10xxxxxx - * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - */ - for (n = 1; ; n++) - { - if (n > 4) - goto Lerr; // only do the first 4 of 6 encodings - if (((u << n) & 0x80) == 0) - { - if (n == 1) - goto Lerr; - break; - } - } + /* The following encodings are valid, except for the 5 and 6 byte + * combinations: + * 0xxxxxxx + * 110xxxxx 10xxxxxx + * 1110xxxx 10xxxxxx 10xxxxxx + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + */ + for (n = 1; ; n++) + { + if (n > 4) + goto Lerr; // only do the first 4 of 6 encodings + if (((u << n) & 0x80) == 0) + { + if (n == 1) + goto Lerr; + break; + } + } - // Pick off (7 - n) significant bits of B from first byte of octet - V = cast(dchar)(u & ((1 << (7 - n)) - 1)); + // Pick off (7 - n) significant bits of B from first byte of octet + V = cast(dchar)(u & ((1 << (7 - n)) - 1)); - if (i + (n - 1) >= len) - goto Lerr; // off end of string + if (i + (n - 1) >= len) + goto Lerr; // off end of string - /* The following combinations are overlong, and illegal: - * 1100000x (10xxxxxx) - * 11100000 100xxxxx (10xxxxxx) - * 11110000 1000xxxx (10xxxxxx 10xxxxxx) - * 11111000 10000xxx (10xxxxxx 10xxxxxx 10xxxxxx) - * 11111100 100000xx (10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx) - */ - u2 = s[i + 1]; - if ((u & 0xFE) == 0xC0 || - (u == 0xE0 && (u2 & 0xE0) == 0x80) || - (u == 0xF0 && (u2 & 0xF0) == 0x80) || - (u == 0xF8 && (u2 & 0xF8) == 0x80) || - (u == 0xFC && (u2 & 0xFC) == 0x80)) - goto Lerr; // overlong combination + /* The following combinations are overlong, and illegal: + * 1100000x (10xxxxxx) + * 11100000 100xxxxx (10xxxxxx) + * 11110000 1000xxxx (10xxxxxx 10xxxxxx) + * 11111000 10000xxx (10xxxxxx 10xxxxxx 10xxxxxx) + * 11111100 100000xx (10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx) + */ + u2 = s[i + 1]; + if ((u & 0xFE) == 0xC0 || + (u == 0xE0 && (u2 & 0xE0) == 0x80) || + (u == 0xF0 && (u2 & 0xF0) == 0x80) || + (u == 0xF8 && (u2 & 0xF8) == 0x80) || + (u == 0xFC && (u2 & 0xFC) == 0x80)) + goto Lerr; // overlong combination - for (uint j = 1; j != n; j++) - { - u = s[i + j]; - if ((u & 0xC0) != 0x80) - goto Lerr; // trailing bytes are 10xxxxxx - V = (V << 6) | (u & 0x3F); - } - if (!isValidDchar(V)) - goto Lerr; - i += n; - } - else - { - V = cast(dchar) u; - i++; - } + for (uint j = 1; j != n; j++) + { + u = s[i + j]; + if ((u & 0xC0) != 0x80) + goto Lerr; // trailing bytes are 10xxxxxx + V = (V << 6) | (u & 0x3F); + } + if (!isValidDchar(V)) + goto Lerr; + i += n; + } + else + { + V = cast(dchar) u; + i++; + } - idx = i; - return V; + idx = i; + return V; Lerr: - //printf("\ndecode: idx = %d, i = %d, length = %d s = \n'%.*s'\n%x\n'%.*s'\n", idx, i, s.length, s, s[i], s[i .. length]); - throw new UtfException("4invalid UTF-8 sequence", i); + //printf("\ndecode: idx = %d, i = %d, length = %d s = \n'%.*s'\n%x\n'%.*s'\n", idx, i, s.length, s, s[i], s[i .. length]); + throw new UtfException("4invalid UTF-8 sequence", i); } unittest @@ -373,28 +373,28 @@ unittest assert(i == 3); static char[][] s4 = - [ "\xE2\x89", // too short - "\xC0\x8A", - "\xE0\x80\x8A", - "\xF0\x80\x80\x8A", - "\xF8\x80\x80\x80\x8A", - "\xFC\x80\x80\x80\x80\x8A", + [ "\xE2\x89", // too short + "\xC0\x8A", + "\xE0\x80\x8A", + "\xF0\x80\x80\x8A", + "\xF8\x80\x80\x80\x8A", + "\xFC\x80\x80\x80\x80\x8A", ]; for (int j = 0; j < s4.length; j++) { - try - { - i = 0; - c = decode(s4[j], i); - assert(0); - } - catch (UtfException u) - { - i = 23; - delete u; - } - assert(i == 23); + try + { + i = 0; + c = decode(s4[j], i); + assert(0); + } + catch (UtfException u) + { + i = 23; + delete u; + } + assert(i == 23); } } @@ -403,56 +403,56 @@ unittest dchar decode(wchar[] s, inout size_t idx) in { - assert(idx >= 0 && idx < s.length); + assert(idx >= 0 && idx < s.length); } out (result) { - assert(isValidDchar(result)); + assert(isValidDchar(result)); } body { - char[] msg; - dchar V; - size_t i = idx; - uint u = s[i]; + char[] msg; + dchar V; + size_t i = idx; + uint u = s[i]; - if (u & ~0x7F) - { if (u >= 0xD800 && u <= 0xDBFF) - { uint u2; + if (u & ~0x7F) + { if (u >= 0xD800 && u <= 0xDBFF) + { uint u2; - if (i + 1 == s.length) - { msg = "surrogate UTF-16 high value past end of string"; - goto Lerr; - } - u2 = s[i + 1]; - if (u2 < 0xDC00 || u2 > 0xDFFF) - { msg = "surrogate UTF-16 low value out of range"; - goto Lerr; - } - u = ((u - 0xD7C0) << 10) + (u2 - 0xDC00); - i += 2; - } - else if (u >= 0xDC00 && u <= 0xDFFF) - { msg = "unpaired surrogate UTF-16 value"; - goto Lerr; - } - else if (u == 0xFFFE || u == 0xFFFF) - { msg = "illegal UTF-16 value"; - goto Lerr; - } - else - i++; - } - else - { - i++; - } + if (i + 1 == s.length) + { msg = "surrogate UTF-16 high value past end of string"; + goto Lerr; + } + u2 = s[i + 1]; + if (u2 < 0xDC00 || u2 > 0xDFFF) + { msg = "surrogate UTF-16 low value out of range"; + goto Lerr; + } + u = ((u - 0xD7C0) << 10) + (u2 - 0xDC00); + i += 2; + } + else if (u >= 0xDC00 && u <= 0xDFFF) + { msg = "unpaired surrogate UTF-16 value"; + goto Lerr; + } + else if (u == 0xFFFE || u == 0xFFFF) + { msg = "illegal UTF-16 value"; + goto Lerr; + } + else + i++; + } + else + { + i++; + } - idx = i; - return cast(dchar)u; + idx = i; + return cast(dchar)u; Lerr: - throw new UtfException(msg, i); + throw new UtfException(msg, i); } /** ditto */ @@ -460,20 +460,20 @@ dchar decode(wchar[] s, inout size_t idx) dchar decode(dchar[] s, inout size_t idx) in { - assert(idx >= 0 && idx < s.length); + assert(idx >= 0 && idx < s.length); } body { - size_t i = idx; - dchar c = s[i]; + size_t i = idx; + dchar c = s[i]; - if (!isValidDchar(c)) - goto Lerr; - idx = i + 1; - return c; + if (!isValidDchar(c)) + goto Lerr; + idx = i + 1; + return c; Lerr: - throw new UtfException("5invalid UTF-32 value", i); + throw new UtfException("5invalid UTF-32 value", i); } @@ -486,49 +486,49 @@ dchar decode(dchar[] s, inout size_t idx) void encode(inout char[] s, dchar c) in { - assert(isValidDchar(c)); + assert(isValidDchar(c)); } body { - char[] r = s; + char[] r = s; - if (c <= 0x7F) - { - r ~= cast(char) c; - } - else - { - char[4] buf; - uint L; + if (c <= 0x7F) + { + r ~= cast(char) c; + } + else + { + char[4] buf; + uint L; - if (c <= 0x7FF) - { - buf[0] = cast(char)(0xC0 | (c >> 6)); - buf[1] = cast(char)(0x80 | (c & 0x3F)); - L = 2; - } - else if (c <= 0xFFFF) - { - buf[0] = cast(char)(0xE0 | (c >> 12)); - buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); - buf[2] = cast(char)(0x80 | (c & 0x3F)); - L = 3; - } - else if (c <= 0x10FFFF) - { - buf[0] = cast(char)(0xF0 | (c >> 18)); - buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); - buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); - buf[3] = cast(char)(0x80 | (c & 0x3F)); - L = 4; - } - else - { - assert(0); - } - r ~= buf[0 .. L]; - } - s = r; + if (c <= 0x7FF) + { + buf[0] = cast(char)(0xC0 | (c >> 6)); + buf[1] = cast(char)(0x80 | (c & 0x3F)); + L = 2; + } + else if (c <= 0xFFFF) + { + buf[0] = cast(char)(0xE0 | (c >> 12)); + buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); + buf[2] = cast(char)(0x80 | (c & 0x3F)); + L = 3; + } + else if (c <= 0x10FFFF) + { + buf[0] = cast(char)(0xF0 | (c >> 18)); + buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); + buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); + buf[3] = cast(char)(0x80 | (c & 0x3F)); + L = 4; + } + else + { + assert(0); + } + r ~= buf[0 .. L]; + } + s = r; } unittest @@ -543,7 +543,7 @@ unittest encode(s, cast(dchar)'\u00A9'); assert(s.length == 7); assert(s == "abcda\xC2\xA9"); - //assert(s == "abcda\u00A9"); // BUG: fix compiler + //assert(s == "abcda\u00A9"); // BUG: fix compiler encode(s, cast(dchar)'\u2260'); assert(s.length == 10); @@ -555,25 +555,25 @@ unittest void encode(inout wchar[] s, dchar c) in { - assert(isValidDchar(c)); + assert(isValidDchar(c)); } body { - wchar[] r = s; + wchar[] r = s; - if (c <= 0xFFFF) - { - r ~= cast(wchar) c; - } - else - { - wchar[2] buf; + if (c <= 0xFFFF) + { + r ~= cast(wchar) c; + } + else + { + wchar[2] buf; - buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); - buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); - r ~= buf; - } - s = r; + buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); + buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); + r ~= buf; + } + s = r; } /** ditto */ @@ -581,11 +581,11 @@ void encode(inout wchar[] s, dchar c) void encode(inout dchar[] s, dchar c) in { - assert(isValidDchar(c)); + assert(isValidDchar(c)); } body { - s ~= c; + s ~= c; } /* =================== Validation ======================= */ @@ -602,7 +602,7 @@ void validate(char[] s) for (i = 0; i < len; ) { - decode(s, i); + decode(s, i); } } @@ -615,7 +615,7 @@ void validate(wchar[] s) for (i = 0; i < len; ) { - decode(s, i); + decode(s, i); } } @@ -628,7 +628,7 @@ void validate(dchar[] s) for (i = 0; i < len; ) { - decode(s, i); + decode(s, i); } } @@ -637,37 +637,37 @@ void validate(dchar[] s) char[] toUTF8(char[4] buf, dchar c) in { - assert(isValidDchar(c)); + assert(isValidDchar(c)); } body { - if (c <= 0x7F) - { - buf[0] = cast(char) c; - return buf[0 .. 1]; - } - else if (c <= 0x7FF) - { - buf[0] = cast(char)(0xC0 | (c >> 6)); - buf[1] = cast(char)(0x80 | (c & 0x3F)); - return buf[0 .. 2]; - } - else if (c <= 0xFFFF) - { - buf[0] = cast(char)(0xE0 | (c >> 12)); - buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); - buf[2] = cast(char)(0x80 | (c & 0x3F)); - return buf[0 .. 3]; - } - else if (c <= 0x10FFFF) - { - buf[0] = cast(char)(0xF0 | (c >> 18)); - buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); - buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); - buf[3] = cast(char)(0x80 | (c & 0x3F)); - return buf[0 .. 4]; - } - assert(0); + if (c <= 0x7F) + { + buf[0] = cast(char) c; + return buf[0 .. 1]; + } + else if (c <= 0x7FF) + { + buf[0] = cast(char)(0xC0 | (c >> 6)); + buf[1] = cast(char)(0x80 | (c & 0x3F)); + return buf[0 .. 2]; + } + else if (c <= 0xFFFF) + { + buf[0] = cast(char)(0xE0 | (c >> 12)); + buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); + buf[2] = cast(char)(0x80 | (c & 0x3F)); + return buf[0 .. 3]; + } + else if (c <= 0x10FFFF) + { + buf[0] = cast(char)(0xF0 | (c >> 18)); + buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); + buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); + buf[3] = cast(char)(0x80 | (c & 0x3F)); + return buf[0 .. 4]; + } + assert(0); } /******************* @@ -677,11 +677,11 @@ char[] toUTF8(char[4] buf, dchar c) char[] toUTF8(char[] s) in { - validate(s); + validate(s); } body { - return s; + return s; } /** ditto */ @@ -695,19 +695,19 @@ char[] toUTF8(wchar[] s) r.length = slen; for (i = 0; i < slen; i++) - { wchar c = s[i]; + { wchar c = s[i]; - if (c <= 0x7F) - r[i] = cast(char)c; // fast path for ascii - else - { - r.length = i; - foreach (dchar c; s[i .. slen]) - { - encode(r, c); - } - break; - } + if (c <= 0x7F) + r[i] = cast(char)c; // fast path for ascii + else + { + r.length = i; + foreach (dchar c; s[i .. slen]) + { + encode(r, c); + } + break; + } } return r; } @@ -723,19 +723,19 @@ char[] toUTF8(dchar[] s) r.length = slen; for (i = 0; i < slen; i++) - { dchar c = s[i]; + { dchar c = s[i]; - if (c <= 0x7F) - r[i] = cast(char)c; // fast path for ascii - else - { - r.length = i; - foreach (dchar d; s[i .. slen]) - { - encode(r, d); - } - break; - } + if (c <= 0x7F) + r[i] = cast(char)c; // fast path for ascii + else + { + r.length = i; + foreach (dchar d; s[i .. slen]) + { + encode(r, d); + } + break; + } } return r; } @@ -745,21 +745,21 @@ char[] toUTF8(dchar[] s) wchar[] toUTF16(wchar[2] buf, dchar c) in { - assert(isValidDchar(c)); + assert(isValidDchar(c)); } body { - if (c <= 0xFFFF) - { - buf[0] = cast(wchar) c; - return buf[0 .. 1]; - } - else - { - buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); - buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); - return buf[0 .. 2]; - } + if (c <= 0xFFFF) + { + buf[0] = cast(wchar) c; + return buf[0 .. 1]; + } + else + { + buf[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800); + buf[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00); + return buf[0 .. 2]; + } } /**************** @@ -777,17 +777,17 @@ wchar[] toUTF16(char[] s) r.length = 0; for (size_t i = 0; i < slen; ) { - dchar c = s[i]; - if (c <= 0x7F) - { - i++; - r ~= cast(wchar)c; - } - else - { - c = decode(s, i); - encode(r, c); - } + dchar c = s[i]; + if (c <= 0x7F) + { + i++; + r ~= cast(wchar)c; + } + else + { + c = decode(s, i); + encode(r, c); + } } return r; } @@ -803,17 +803,17 @@ wchar* toUTF16z(char[] s) r.length = 0; for (size_t i = 0; i < slen; ) { - dchar c = s[i]; - if (c <= 0x7F) - { - i++; - r ~= cast(wchar)c; - } - else - { - c = decode(s, i); - encode(r, c); - } + dchar c = s[i]; + if (c <= 0x7F) + { + i++; + r ~= cast(wchar)c; + } + else + { + c = decode(s, i); + encode(r, c); + } } r ~= "\000"; return r.ptr; @@ -824,11 +824,11 @@ wchar* toUTF16z(char[] s) wchar[] toUTF16(wchar[] s) in { - validate(s); + validate(s); } body { - return s; + return s; } /** ditto */ @@ -842,7 +842,7 @@ wchar[] toUTF16(dchar[] s) r.length = 0; for (size_t i = 0; i < slen; i++) { - encode(r, s[i]); + encode(r, s[i]); } return r; } @@ -859,15 +859,15 @@ dchar[] toUTF32(char[] s) size_t slen = s.length; size_t j = 0; - r.length = slen; // r[] will never be longer than s[] + r.length = slen; // r[] will never be longer than s[] for (size_t i = 0; i < slen; ) { - dchar c = s[i]; - if (c >= 0x80) - c = decode(s, i); - else - i++; // c is ascii, no need for decode - r[j++] = c; + dchar c = s[i]; + if (c >= 0x80) + c = decode(s, i); + else + i++; // c is ascii, no need for decode + r[j++] = c; } return r[0 .. j]; } @@ -880,15 +880,15 @@ dchar[] toUTF32(wchar[] s) size_t slen = s.length; size_t j = 0; - r.length = slen; // r[] will never be longer than s[] + r.length = slen; // r[] will never be longer than s[] for (size_t i = 0; i < slen; ) { - dchar c = s[i]; - if (c >= 0x80) - c = decode(s, i); - else - i++; // c is ascii, no need for decode - r[j++] = c; + dchar c = s[i]; + if (c >= 0x80) + c = decode(s, i); + else + i++; // c is ascii, no need for decode + r[j++] = c; } return r[0 .. j]; } @@ -898,11 +898,11 @@ dchar[] toUTF32(wchar[] s) dchar[] toUTF32(dchar[] s) in { - validate(s); + validate(s); } body { - return s; + return s; } /* ================================ tests ================================== */ diff --git a/std/windows/charset.d b/std/windows/charset.d index b772410a6..285ec26a4 100644 --- a/std/windows/charset.d +++ b/std/windows/charset.d @@ -3,7 +3,7 @@ /** * Support UTF-8 on Windows 95, 98 and ME systems. * Macros: - * WIKI = Phobos/StdWindowsCharset + * WIKI = Phobos/StdWindowsCharset */ module std.windows.charset; @@ -25,7 +25,7 @@ private import std.string; * 2 - Mac * * Authors: - * yaneurao, Walter Bright, Stewart Gordon + * yaneurao, Walter Bright, Stewart Gordon */ char* toMBSz(char[] s, uint codePage = 0) @@ -33,28 +33,28 @@ char* toMBSz(char[] s, uint codePage = 0) // Only need to do this if any chars have the high bit set foreach (char c; s) { - if (c >= 0x80) - { - char[] result; - int readLen; - wchar* ws = std.utf.toUTF16z(s); - result.length = WideCharToMultiByte(codePage, 0, ws, -1, null, 0, - null, null); + if (c >= 0x80) + { + char[] result; + int readLen; + wchar* ws = std.utf.toUTF16z(s); + result.length = WideCharToMultiByte(codePage, 0, ws, -1, null, 0, + null, null); - if (result.length) - { - readLen = WideCharToMultiByte(codePage, 0, ws, -1, result.ptr, - result.length, null, null); - } + if (result.length) + { + readLen = WideCharToMultiByte(codePage, 0, ws, -1, result.ptr, + result.length, null, null); + } - if (!readLen || readLen != result.length) - { - throw new Exception("Couldn't convert string: " ~ - sysErrorString(GetLastError())); - } + if (!readLen || readLen != result.length) + { + throw new Exception("Couldn't convert string: " ~ + sysErrorString(GetLastError())); + } - return result.ptr; - } + return result.ptr; + } } return std.string.toStringz(s); } @@ -79,29 +79,29 @@ char[] fromMBSz(char* s, int codePage = 0) for (c = s; *c != 0; c++) { - if (*c >= 0x80) - { - wchar[] result; - int readLen; + if (*c >= 0x80) + { + wchar[] result; + int readLen; - result.length = MultiByteToWideChar(codePage, 0, s, -1, null, 0); + result.length = MultiByteToWideChar(codePage, 0, s, -1, null, 0); - if (result.length) - { - readLen = MultiByteToWideChar(codePage, 0, s, -1, result.ptr, - result.length); - } + if (result.length) + { + readLen = MultiByteToWideChar(codePage, 0, s, -1, result.ptr, + result.length); + } - if (!readLen || readLen != result.length) - { - throw new Exception("Couldn't convert string: " ~ - sysErrorString(GetLastError())); - } + if (!readLen || readLen != result.length) + { + throw new Exception("Couldn't convert string: " ~ + sysErrorString(GetLastError())); + } - return std.utf.toUTF8(result[0 .. result.length-1]); // omit trailing null - } + return std.utf.toUTF8(result[0 .. result.length-1]); // omit trailing null + } } - return s[0 .. c-s]; // string is ASCII, no conversion necessary + return s[0 .. c-s]; // string is ASCII, no conversion necessary } diff --git a/std/windows/iunknown.d b/std/windows/iunknown.d index be304d931..c66131e5a 100644 --- a/std/windows/iunknown.d +++ b/std/windows/iunknown.d @@ -9,16 +9,16 @@ alias int HRESULT; enum : int { - S_OK = 0, - E_NOINTERFACE = cast(int)0x80004002, + S_OK = 0, + E_NOINTERFACE = cast(int)0x80004002, } struct GUID { // size is 16 align(1): - DWORD Data1; - WORD Data2; - WORD Data3; - BYTE Data4[8]; + DWORD Data1; + WORD Data2; + WORD Data3; + BYTE Data4[8]; } alias GUID IID; @@ -32,31 +32,31 @@ class IUnknown { HRESULT QueryInterface(IID* riid, out IUnknown pvObject) { - if (riid == &IID_IUnknown) - { - pvObject = this; - AddRef(); - return S_OK; - } - else - { pvObject = null; - return E_NOINTERFACE; - } + if (riid == &IID_IUnknown) + { + pvObject = this; + AddRef(); + return S_OK; + } + else + { pvObject = null; + return E_NOINTERFACE; + } } ULONG AddRef() { - return ++count; + return ++count; } ULONG Release() { - if (--count == 0) - { - // free object - return 0; - } - return count; + if (--count == 0) + { + // free object + return 0; + } + return count; } int count = 1; diff --git a/std/windows/registry.d b/std/windows/registry.d index 546b3ef50..8093e40d8 100644 --- a/std/windows/registry.d +++ b/std/windows/registry.d @@ -76,13 +76,13 @@ class Win32Exception : Exception this(string message) { - super(msg); + super(msg); } this(string msg, int errnum) { - super(msg); - error = errnum; + super(msg); + error = errnum; } } @@ -245,7 +245,7 @@ public enum REGSAM , KEY_CREATE_LINK = 0x0020 //!< Permission to create a symbolic link , KEY_WOW64_32KEY = 0x0200 //!< Enables a 64- or 32-bit application to open a 32-bit key , KEY_WOW64_64KEY = 0x0100 //!< Enables a 64- or 32-bit application to open a 64-bit key - , KEY_WOW64_RES = 0x0300 //!< + , KEY_WOW64_RES = 0x0300 //!< , KEY_READ = ( STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS @@ -272,7 +272,7 @@ public enum REGSAM /// \ingroup group_D_win32_reg public enum REG_VALUE_TYPE { - REG_UNKNOWN = -1 //!< + REG_UNKNOWN = -1 //!< , REG_NONE = 0 //!< The null value type. (In practise this is treated as a zero-length binary array by the Win32 registry) , REG_SZ = 1 //!< A zero-terminated string , REG_EXPAND_SZ = 2 //!< A zero-terminated string containing expandable environment variable references @@ -300,7 +300,7 @@ extern (C) extern (Windows) { - LONG RegCreateKeyExA(in HKEY hkey, in LPCSTR lpSubKey, in Reserved + LONG RegCreateKeyExA(in HKEY hkey, in LPCSTR lpSubKey, in Reserved , in Reserved , in DWORD dwOptions , in REGSAM samDesired , in LPSECURITY_ATTRIBUTES lpsa @@ -308,18 +308,18 @@ extern (Windows) LONG RegDeleteKeyA(in HKEY hkey, in LPCSTR lpSubKey); LONG RegDeleteValueA(in HKEY hkey, in LPCSTR lpValueName); LONG RegOpenKeyA(in HKEY hkey, in LPCSTR lpSubKey, out HKEY hkeyResult); - LONG RegOpenKeyExA( in HKEY hkey, in LPCSTR lpSubKey, in Reserved + LONG RegOpenKeyExA( in HKEY hkey, in LPCSTR lpSubKey, in Reserved , in REGSAM samDesired, out HKEY hkeyResult); LONG RegCloseKey(in HKEY hkey); LONG RegFlushKey(in HKEY hkey); - LONG RegQueryValueExA( in HKEY hkey, in LPCSTR lpValueName, in Reserved + LONG RegQueryValueExA( in HKEY hkey, in LPCSTR lpValueName, in Reserved , out REG_VALUE_TYPE type, in void *lpData , inout DWORD cbData); LONG RegEnumKeyExA( in HKEY hkey, in DWORD dwIndex, in LPSTR lpName , inout DWORD cchName, in Reserved , in LPSTR lpClass , in LPDWORD cchClass, in FILETIME *ftLastWriteTime); LONG RegEnumValueA( in HKEY hkey, in DWORD dwIndex, in LPSTR lpValueName - , inout DWORD cchValueName, in Reserved + , inout DWORD cchValueName, in Reserved , in LPDWORD lpType, in void *lpData , in LPDWORD lpcbData); LONG RegQueryInfoKeyA( in HKEY hkey, in LPSTR lpClass @@ -331,7 +331,7 @@ extern (Windows) , in LPDWORD lpcMaxValueLen , in LPDWORD lpcbSecurityDescriptor , in FILETIME *lpftLastWriteTime); - LONG RegSetValueExA( in HKEY hkey, in LPCSTR lpSubKey, in Reserved + LONG RegSetValueExA( in HKEY hkey, in LPCSTR lpSubKey, in Reserved , in REG_VALUE_TYPE type, in LPCVOID lpData , in DWORD cbData); @@ -547,7 +547,7 @@ body LONG res; // The Registry API lies about the lengths of a very few sub-key lengths - // so we have to test to see if it whinges about more data, and provide + // so we have to test to see if it whinges about more data, and provide // more if it does. for(;;) { @@ -681,8 +681,8 @@ body case REG_VALUE_TYPE.REG_SZ: case REG_VALUE_TYPE.REG_EXPAND_SZ: value = std.string.toString(cast(char*)data); - if (value.ptr == cast(char*)&u.qw) - value = value.dup; // don't point into the stack + if (value.ptr == cast(char*)&u.qw) + value = value.dup; // don't point into the stack break; version(LittleEndian) { @@ -906,7 +906,7 @@ public: { super(message); } - /// \brief Creates an instance of the exception, with the given + /// \brief Creates an instance of the exception, with the given /// /// \param message The message associated with the exception /// \param error The Win32 error number associated with the exception @@ -986,7 +986,7 @@ private: Reg_CloseKey_(m_hkey); // Even though this is horried waste-of-cycles programming - // we're doing it here so that the + // we're doing it here so that the m_hkey = null; } //@} @@ -1096,7 +1096,7 @@ public: // // If the allocation of the memory for Key fails, the HKEY could be // lost. Hence, we catch such a failure by the finally, and release - // the HKEY there. If the creation of + // the HKEY there. If the creation of try { Key key = new Key(hkey, name, disposition == REG_CREATED_NEW_KEY); @@ -1114,7 +1114,7 @@ public: } } } - + /// Returns the named sub-key of this key /// /// \param name The name of the subkey to create. May not be null @@ -1130,7 +1130,7 @@ public: /// /// \param name The name of the subkey to aquire. If name is null (or the empty-string), then the called key is duplicated /// \param access The desired access; one of the REGSAM enumeration - /// \return The aquired key. + /// \return The aquired key. /// \note This function never returns null. If a key corresponding to the requested name is not found, a RegistryException is thrown Key getKey(string name, REGSAM access) { @@ -1155,7 +1155,7 @@ public: // // If the allocation of the memory for Key fails, the HKEY could be // lost. Hence, we catch such a failure by the finally, and release - // the HKEY there. If the creation of + // the HKEY there. If the creation of try { Key key = new Key(hkey, name, false); @@ -1177,7 +1177,7 @@ public: /// Returns the named sub-key of this key /// /// \param name The name of the subkey to aquire. If name is null (or the empty-string), then the called key is duplicated - /// \return The aquired key. + /// \return The aquired key. /// \note This function never returns null. If a key corresponding to the requested name is not found, a RegistryException is thrown /// \note This function is equivalent to calling GetKey(name, REGSAM.KEY_READ), and returns a key with read/enum access Key getKey(string name) @@ -1245,7 +1245,7 @@ public: { REG_VALUE_TYPE type = _RVT_from_Endian(endian); - assert( type == REG_VALUE_TYPE.REG_DWORD_BIG_ENDIAN || + assert( type == REG_VALUE_TYPE.REG_DWORD_BIG_ENDIAN || type == REG_VALUE_TYPE.REG_DWORD_LITTLE_ENDIAN); Reg_SetValueExA_(m_hkey, name, type, &value, value.sizeof); @@ -1279,7 +1279,7 @@ public: /// \note If a value corresponding to the requested name is not found, a RegistryException is thrown void setValue(string name, string value, boolean asEXPAND_SZ) { - Reg_SetValueExA_(m_hkey, name, asEXPAND_SZ + Reg_SetValueExA_(m_hkey, name, asEXPAND_SZ ? REG_VALUE_TYPE.REG_EXPAND_SZ : REG_VALUE_TYPE.REG_SZ, value.ptr , value.length); @@ -1303,7 +1303,7 @@ public: // Allocate - char[] cs = new char[total]; + char[] cs = new char[total]; int base = 0; // Slice the individual strings into the new array @@ -1445,8 +1445,8 @@ public: return value; +/ - // ExpandEnvironemntStrings(): - // http://msdn2.microsoft.com/en-us/library/ms724265.aspx + // ExpandEnvironemntStrings(): + // http://msdn2.microsoft.com/en-us/library/ms724265.aspx LPCSTR lpSrc = toStringz(value); DWORD cchRequired = ExpandEnvironmentStringsA(lpSrc, null, 0); char[] newValue = new char[cchRequired]; @@ -1456,7 +1456,7 @@ public: throw new Win32Exception("Failed to expand environment variables"); } - return std.string.toString(newValue.ptr); // remove trailing 0 + return std.string.toString(newValue.ptr); // remove trailing 0 } /// Obtains the current value as an array of strings @@ -1852,7 +1852,7 @@ public: { DWORD cchName; - res = Reg_EnumKeyName_(hkey, index, sName, cchName); + res = Reg_EnumKeyName_(hkey, index, sName, cchName); assert(ERROR_MORE_DATA != res); if(ERROR_NO_MORE_ITEMS == res) @@ -1994,7 +1994,7 @@ public: { DWORD cchName = 1 + cchValueMaxLen; - res = Reg_EnumValueName_(hkey, index, sName.ptr, cchName); + res = Reg_EnumValueName_(hkey, index, sName.ptr, cchName); if(ERROR_NO_MORE_ITEMS == res) { // Enumeration complete @@ -2119,7 +2119,7 @@ public: { DWORD cchName = 1 + cchValueMaxLen; - res = Reg_EnumValueName_(hkey, index, sName.ptr, cchName); + res = Reg_EnumValueName_(hkey, index, sName.ptr, cchName); if(ERROR_NO_MORE_ITEMS == res) { // Enumeration complete diff --git a/std/windows/syserror.d b/std/windows/syserror.d index 9cdf56c93..1d2a9da20 100644 --- a/std/windows/syserror.d +++ b/std/windows/syserror.d @@ -14,20 +14,20 @@ char[] sysErrorString(uint errcode) char* buffer; DWORD r; - r = FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - null, - errcode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - cast(LPTSTR)&buffer, - 0, - null); + r = FormatMessageA( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + null, + errcode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + cast(LPTSTR)&buffer, + 0, + null); /* Remove \r\n from error string */ if (r >= 2) - r -= 2; + r -= 2; /* Create 0 terminated copy on GC heap because fromMBSz() * may return it. diff --git a/std/zip.d b/std/zip.d index 55aaa5371..49c31f54e 100644 --- a/std/zip.d +++ b/std/zip.d @@ -4,20 +4,20 @@ * Read/write data in the $(LINK2 http://www.info-_zip.org, zip archive) format. * Makes use of the etc.c.zlib compression library. * - * Bugs: - * $(UL - * $(LI Multi-disk zips not supported.) - * $(LI Only Zip version 20 formats are supported.) - * $(LI Only supports compression modes 0 (no compression) and 8 (deflate).) - * $(LI Does not support encryption.) - * $(LI $(BUGZILLA 592)) - * $(LI $(BUGZILLA 1832)) - * $(LI $(BUGZILLA 2137)) - * $(LI $(BUGZILLA 2138)) - * ) + * Bugs: + * $(UL + * $(LI Multi-disk zips not supported.) + * $(LI Only Zip version 20 formats are supported.) + * $(LI Only supports compression modes 0 (no compression) and 8 (deflate).) + * $(LI Does not support encryption.) + * $(LI $(BUGZILLA 592)) + * $(LI $(BUGZILLA 1832)) + * $(LI $(BUGZILLA 2137)) + * $(LI $(BUGZILLA 2138)) + * ) * * Macros: - * WIKI = Phobos/StdZip + * WIKI = Phobos/StdZip */ module std.zip; @@ -34,7 +34,7 @@ class ZipException : Exception { this(string msg) { - super("ZipException: " ~ msg); + super("ZipException: " ~ msg); } } @@ -43,17 +43,17 @@ class ZipException : Exception */ class ArchiveMember { - ushort madeVersion = 20; /// Read Only - ushort extractVersion = 20; /// Read Only - ushort flags; /// Read/Write: normally set to 0 - ushort compressionMethod; /// Read/Write: 0 for compression, 8 for deflate - std.date.DosFileTime time; /// Read/Write: Last modified time of the member. It's in the DOS date/time format. - uint crc32; /// Read Only: cyclic redundancy check (CRC) value - uint compressedSize; /// Read Only: size of data of member in compressed form. - uint expandedSize; /// Read Only: size of data of member in expanded form. - ushort diskNumber; /// Read Only: should be 0. - ushort internalAttributes; /// Read/Write - uint externalAttributes; /// Read/Write + ushort madeVersion = 20; /// Read Only + ushort extractVersion = 20; /// Read Only + ushort flags; /// Read/Write: normally set to 0 + ushort compressionMethod; /// Read/Write: 0 for compression, 8 for deflate + std.date.DosFileTime time; /// Read/Write: Last modified time of the member. It's in the DOS date/time format. + uint crc32; /// Read Only: cyclic redundancy check (CRC) value + uint compressedSize; /// Read Only: size of data of member in compressed form. + uint expandedSize; /// Read Only: size of data of member in expanded form. + ushort diskNumber; /// Read Only: should be 0. + ushort internalAttributes; /// Read/Write + uint externalAttributes; /// Read/Write private uint offset; @@ -64,27 +64,27 @@ class ArchiveMember */ string name; - ubyte[] extra; /// Read/Write: extra data for this member. - string comment; /// Read/Write: comment associated with this member. - ubyte[] compressedData; /// Read Only: data of member in compressed form. - ubyte[] expandedData; /// Read/Write: data of member in uncompressed form. + ubyte[] extra; /// Read/Write: extra data for this member. + string comment; /// Read/Write: comment associated with this member. + ubyte[] compressedData; /// Read Only: data of member in compressed form. + ubyte[] expandedData; /// Read/Write: data of member in uncompressed form. debug(print) { void print() { - printf("name = '%.*s'\n", name); - printf("\tcomment = '%.*s'\n", comment); - printf("\tmadeVersion = x%04x\n", madeVersion); - printf("\textractVersion = x%04x\n", extractVersion); - printf("\tflags = x%04x\n", flags); - printf("\tcompressionMethod = %d\n", compressionMethod); - printf("\ttime = %d\n", time); - printf("\tcrc32 = x%08x\n", crc32); - printf("\texpandedSize = %d\n", expandedSize); - printf("\tcompressedSize = %d\n", compressedSize); - printf("\tinternalAttributes = x%04x\n", internalAttributes); - printf("\texternalAttributes = x%08x\n", externalAttributes); + printf("name = '%.*s'\n", name); + printf("\tcomment = '%.*s'\n", comment); + printf("\tmadeVersion = x%04x\n", madeVersion); + printf("\textractVersion = x%04x\n", extractVersion); + printf("\tflags = x%04x\n", flags); + printf("\tcompressionMethod = %d\n", compressionMethod); + printf("\ttime = %d\n", time); + printf("\tcrc32 = x%08x\n", crc32); + printf("\texpandedSize = %d\n", expandedSize); + printf("\tcompressedSize = %d\n", compressedSize); + printf("\tinternalAttributes = x%04x\n", internalAttributes); + printf("\texternalAttributes = x%08x\n", externalAttributes); } } } @@ -95,14 +95,14 @@ class ArchiveMember */ class ZipArchive { - ubyte[] data; /// Read Only: array representing the entire contents of the archive. + ubyte[] data; /// Read Only: array representing the entire contents of the archive. uint endrecOffset; - uint diskNumber; /// Read Only: 0 since multi-disk zip archives are not supported. - uint diskStartDir; /// Read Only: 0 since multi-disk zip archives are not supported. - uint numEntries; /// Read Only: number of ArchiveMembers in the directory. - uint totalEntries; /// Read Only: same as totalEntries. - string comment; /// Read/Write: the archive comment. Must be less than 65536 bytes in length. + uint diskNumber; /// Read Only: 0 since multi-disk zip archives are not supported. + uint diskStartDir; /// Read Only: 0 since multi-disk zip archives are not supported. + uint numEntries; /// Read Only: number of ArchiveMembers in the directory. + uint totalEntries; /// Read Only: same as totalEntries. + string comment; /// Read/Write: the archive comment. Must be less than 65536 bytes in length. /** * Read Only: array indexed by the name of each member of the archive. @@ -122,11 +122,11 @@ class ZipArchive { void print() { - printf("\tdiskNumber = %u\n", diskNumber); - printf("\tdiskStartDir = %u\n", diskStartDir); - printf("\tnumEntries = %u\n", numEntries); - printf("\ttotalEntries = %u\n", totalEntries); - printf("\tcomment = '%.*s'\n", comment); + printf("\tdiskNumber = %u\n", diskNumber); + printf("\tdiskStartDir = %u\n", diskStartDir); + printf("\tnumEntries = %u\n", numEntries); + printf("\ttotalEntries = %u\n", totalEntries); + printf("\tcomment = '%.*s'\n", comment); } } @@ -142,14 +142,14 @@ class ZipArchive */ void addMember(ArchiveMember de) { - directory[de.name] = de; + directory[de.name] = de; } /** Delete de from the archive. */ void deleteMember(ArchiveMember de) { - directory.remove(de.name); + directory.remove(de.name); } /** @@ -163,122 +163,122 @@ class ZipArchive * Returns: array representing the entire archive. */ void[] build() - { uint i; - uint directoryOffset; + { uint i; + uint directoryOffset; - if (comment.length > 0xFFFF) - throw new ZipException("archive comment longer than 65535"); + if (comment.length > 0xFFFF) + throw new ZipException("archive comment longer than 65535"); - // Compress each member; compute size - uint archiveSize = 0; - uint directorySize = 0; - foreach (ArchiveMember de; directory) - { - de.expandedSize = de.expandedData.length; - switch (de.compressionMethod) - { - case 0: - de.compressedData = de.expandedData; - break; + // Compress each member; compute size + uint archiveSize = 0; + uint directorySize = 0; + foreach (ArchiveMember de; directory) + { + de.expandedSize = de.expandedData.length; + switch (de.compressionMethod) + { + case 0: + de.compressedData = de.expandedData; + break; - case 8: - de.compressedData = cast(ubyte[])std.zlib.compress(cast(void[])de.expandedData); - de.compressedData = de.compressedData[2 .. de.compressedData.length - 4]; - break; + case 8: + de.compressedData = cast(ubyte[])std.zlib.compress(cast(void[])de.expandedData); + de.compressedData = de.compressedData[2 .. de.compressedData.length - 4]; + break; - default: - throw new ZipException("unsupported compression method"); - } - de.compressedSize = de.compressedData.length; - de.crc32 = std.zlib.crc32(0, cast(void[])de.expandedData); + default: + throw new ZipException("unsupported compression method"); + } + de.compressedSize = de.compressedData.length; + de.crc32 = std.zlib.crc32(0, cast(void[])de.expandedData); - archiveSize += 30 + de.name.length + - de.extra.length + - de.compressedSize; - directorySize += 46 + de.name.length + - de.extra.length + - de.comment.length; - } + archiveSize += 30 + de.name.length + + de.extra.length + + de.compressedSize; + directorySize += 46 + de.name.length + + de.extra.length + + de.comment.length; + } - data = new ubyte[archiveSize + directorySize + 22 + comment.length]; + data = new ubyte[archiveSize + directorySize + 22 + comment.length]; - // Populate the data[] + // Populate the data[] - // Store each archive member - i = 0; - foreach (ArchiveMember de; directory) - { - de.offset = i; - data[i .. i + 4] = cast(ubyte[])"PK\x03\x04"; - putUshort(i + 4, de.extractVersion); - putUshort(i + 6, de.flags); - putUshort(i + 8, de.compressionMethod); - putUint (i + 10, cast(uint)de.time); - putUint (i + 14, de.crc32); - putUint (i + 18, de.compressedSize); - putUint (i + 22, de.expandedData.length); - putUshort(i + 26, cast(ushort)de.name.length); - putUshort(i + 28, cast(ushort)de.extra.length); - i += 30; + // Store each archive member + i = 0; + foreach (ArchiveMember de; directory) + { + de.offset = i; + data[i .. i + 4] = cast(ubyte[])"PK\x03\x04"; + putUshort(i + 4, de.extractVersion); + putUshort(i + 6, de.flags); + putUshort(i + 8, de.compressionMethod); + putUint (i + 10, cast(uint)de.time); + putUint (i + 14, de.crc32); + putUint (i + 18, de.compressedSize); + putUint (i + 22, de.expandedData.length); + putUshort(i + 26, cast(ushort)de.name.length); + putUshort(i + 28, cast(ushort)de.extra.length); + i += 30; - data[i .. i + de.name.length] = cast(ubyte[])de.name[]; - i += de.name.length; - data[i .. i + de.extra.length] = cast(ubyte[])de.extra[]; - i += de.extra.length; - data[i .. i + de.compressedSize] = de.compressedData[]; - i += de.compressedSize; - } + data[i .. i + de.name.length] = cast(ubyte[])de.name[]; + i += de.name.length; + data[i .. i + de.extra.length] = cast(ubyte[])de.extra[]; + i += de.extra.length; + data[i .. i + de.compressedSize] = de.compressedData[]; + i += de.compressedSize; + } - // Write directory - directoryOffset = i; - numEntries = 0; - foreach (ArchiveMember de; directory) - { - data[i .. i + 4] = cast(ubyte[])"PK\x01\x02"; - putUshort(i + 4, de.madeVersion); - putUshort(i + 6, de.extractVersion); - putUshort(i + 8, de.flags); - putUshort(i + 10, de.compressionMethod); - putUint (i + 12, cast(uint)de.time); - putUint (i + 16, de.crc32); - putUint (i + 20, de.compressedSize); - putUint (i + 24, de.expandedSize); - putUshort(i + 28, cast(ushort)de.name.length); - putUshort(i + 30, cast(ushort)de.extra.length); - putUshort(i + 32, cast(ushort)de.comment.length); - putUshort(i + 34, de.diskNumber); - putUshort(i + 36, de.internalAttributes); - putUint (i + 38, de.externalAttributes); - putUint (i + 42, de.offset); - i += 46; + // Write directory + directoryOffset = i; + numEntries = 0; + foreach (ArchiveMember de; directory) + { + data[i .. i + 4] = cast(ubyte[])"PK\x01\x02"; + putUshort(i + 4, de.madeVersion); + putUshort(i + 6, de.extractVersion); + putUshort(i + 8, de.flags); + putUshort(i + 10, de.compressionMethod); + putUint (i + 12, cast(uint)de.time); + putUint (i + 16, de.crc32); + putUint (i + 20, de.compressedSize); + putUint (i + 24, de.expandedSize); + putUshort(i + 28, cast(ushort)de.name.length); + putUshort(i + 30, cast(ushort)de.extra.length); + putUshort(i + 32, cast(ushort)de.comment.length); + putUshort(i + 34, de.diskNumber); + putUshort(i + 36, de.internalAttributes); + putUint (i + 38, de.externalAttributes); + putUint (i + 42, de.offset); + i += 46; - data[i .. i + de.name.length] = cast(ubyte[])de.name[]; - i += de.name.length; - data[i .. i + de.extra.length] = cast(ubyte[])de.extra[]; - i += de.extra.length; - data[i .. i + de.comment.length] = cast(ubyte[])de.comment[]; - i += de.comment.length; - numEntries++; - } - totalEntries = numEntries; + data[i .. i + de.name.length] = cast(ubyte[])de.name[]; + i += de.name.length; + data[i .. i + de.extra.length] = cast(ubyte[])de.extra[]; + i += de.extra.length; + data[i .. i + de.comment.length] = cast(ubyte[])de.comment[]; + i += de.comment.length; + numEntries++; + } + totalEntries = numEntries; - // Write end record - endrecOffset = i; - data[i .. i + 4] = cast(ubyte[])"PK\x05\x06"; - putUshort(i + 4, cast(ushort)diskNumber); - putUshort(i + 6, cast(ushort)diskStartDir); - putUshort(i + 8, cast(ushort)numEntries); - putUshort(i + 10, cast(ushort)totalEntries); - putUint (i + 12, directorySize); - putUint (i + 16, directoryOffset); - putUshort(i + 20, cast(ushort)comment.length); - i += 22; + // Write end record + endrecOffset = i; + data[i .. i + 4] = cast(ubyte[])"PK\x05\x06"; + putUshort(i + 4, cast(ushort)diskNumber); + putUshort(i + 6, cast(ushort)diskStartDir); + putUshort(i + 8, cast(ushort)numEntries); + putUshort(i + 10, cast(ushort)totalEntries); + putUint (i + 12, directorySize); + putUint (i + 16, directoryOffset); + putUshort(i + 20, cast(ushort)comment.length); + i += 22; - // Write archive comment - assert(i + comment.length == data.length); - data[i .. data.length] = cast(ubyte[])comment[]; + // Write archive comment + assert(i + comment.length == data.length); + data[i .. data.length] = cast(ubyte[])comment[]; - return cast(void[])data; + return cast(void[])data; } /* ============ Reading an existing archive =================== */ @@ -295,104 +295,104 @@ class ZipArchive * Use expand() to get the expanded data for each ArchiveMember. * * Params: - * buffer = the entire contents of the archive. + * buffer = the entire contents of the archive. */ this(void[] buffer) - { int iend; - int i; - int endcommentlength; - uint directorySize; - uint directoryOffset; + { int iend; + int i; + int endcommentlength; + uint directorySize; + uint directoryOffset; - this.data = cast(ubyte[]) buffer; + this.data = cast(ubyte[]) buffer; - // Find 'end record index' by searching backwards for signature - iend = data.length - 66000; - if (iend < 0) - iend = 0; - for (i = data.length - 22; 1; i--) - { - if (i < iend) - throw new ZipException("no end record"); + // Find 'end record index' by searching backwards for signature + iend = data.length - 66000; + if (iend < 0) + iend = 0; + for (i = data.length - 22; 1; i--) + { + if (i < iend) + throw new ZipException("no end record"); - if (data[i .. i + 4] == cast(ubyte[])"PK\x05\x06") - { - endcommentlength = getUshort(i + 20); - if (i + 22 + endcommentlength > data.length) - continue; - comment = cast(string)(data[i + 22 .. i + 22 + endcommentlength]); - endrecOffset = i; - break; - } - } + if (data[i .. i + 4] == cast(ubyte[])"PK\x05\x06") + { + endcommentlength = getUshort(i + 20); + if (i + 22 + endcommentlength > data.length) + continue; + comment = cast(string)(data[i + 22 .. i + 22 + endcommentlength]); + endrecOffset = i; + break; + } + } - // Read end record data - diskNumber = getUshort(i + 4); - diskStartDir = getUshort(i + 6); + // Read end record data + diskNumber = getUshort(i + 4); + diskStartDir = getUshort(i + 6); - numEntries = getUshort(i + 8); - totalEntries = getUshort(i + 10); + numEntries = getUshort(i + 8); + totalEntries = getUshort(i + 10); - if (numEntries != totalEntries) - throw new ZipException("multiple disk zips not supported"); + if (numEntries != totalEntries) + throw new ZipException("multiple disk zips not supported"); - directorySize = getUint(i + 12); - directoryOffset = getUint(i + 16); + directorySize = getUint(i + 12); + directoryOffset = getUint(i + 16); - if (directoryOffset + directorySize > i) - throw new ZipException("corrupted directory"); + if (directoryOffset + directorySize > i) + throw new ZipException("corrupted directory"); - i = directoryOffset; - for (int n = 0; n < numEntries; n++) - { - /* The format of an entry is: - * 'PK' 1, 2 - * directory info - * path - * extra data - * comment - */ + i = directoryOffset; + for (int n = 0; n < numEntries; n++) + { + /* The format of an entry is: + * 'PK' 1, 2 + * directory info + * path + * extra data + * comment + */ - uint offset; - uint namelen; - uint extralen; - uint commentlen; + uint offset; + uint namelen; + uint extralen; + uint commentlen; - if (data[i .. i + 4] != cast(ubyte[])"PK\x01\x02") - throw new ZipException("invalid directory entry 1"); - ArchiveMember de = new ArchiveMember(); - de.madeVersion = getUshort(i + 4); - de.extractVersion = getUshort(i + 6); - de.flags = getUshort(i + 8); - de.compressionMethod = getUshort(i + 10); - de.time = cast(DosFileTime)getUint(i + 12); - de.crc32 = getUint(i + 16); - de.compressedSize = getUint(i + 20); - de.expandedSize = getUint(i + 24); - namelen = getUshort(i + 28); - extralen = getUshort(i + 30); - commentlen = getUshort(i + 32); - de.diskNumber = getUshort(i + 34); - de.internalAttributes = getUshort(i + 36); - de.externalAttributes = getUint(i + 38); - de.offset = getUint(i + 42); - i += 46; + if (data[i .. i + 4] != cast(ubyte[])"PK\x01\x02") + throw new ZipException("invalid directory entry 1"); + ArchiveMember de = new ArchiveMember(); + de.madeVersion = getUshort(i + 4); + de.extractVersion = getUshort(i + 6); + de.flags = getUshort(i + 8); + de.compressionMethod = getUshort(i + 10); + de.time = cast(DosFileTime)getUint(i + 12); + de.crc32 = getUint(i + 16); + de.compressedSize = getUint(i + 20); + de.expandedSize = getUint(i + 24); + namelen = getUshort(i + 28); + extralen = getUshort(i + 30); + commentlen = getUshort(i + 32); + de.diskNumber = getUshort(i + 34); + de.internalAttributes = getUshort(i + 36); + de.externalAttributes = getUint(i + 38); + de.offset = getUint(i + 42); + i += 46; - if (i + namelen + extralen + commentlen > directoryOffset + directorySize) - throw new ZipException("invalid directory entry 2"); + if (i + namelen + extralen + commentlen > directoryOffset + directorySize) + throw new ZipException("invalid directory entry 2"); - de.name = cast(string)(data[i .. i + namelen]); - i += namelen; - de.extra = data[i .. i + extralen]; - i += extralen; - de.comment = cast(string)(data[i .. i + commentlen]); - i += commentlen; + de.name = cast(string)(data[i .. i + namelen]); + i += namelen; + de.extra = data[i .. i + extralen]; + i += extralen; + de.comment = cast(string)(data[i .. i + commentlen]); + i += commentlen; - directory[de.name] = de; - } - if (i != directoryOffset + directorySize) - throw new ZipException("invalid directory entry 3"); + directory[de.name] = de; + } + if (i != directoryOffset + directorySize) + throw new ZipException("invalid directory entry 3"); } /***** @@ -403,108 +403,108 @@ class ZipArchive * crc32, compressedSize, expandedSize, expandedData[], name[], extra[]. */ ubyte[] expand(ArchiveMember de) - { uint namelen; - uint extralen; + { uint namelen; + uint extralen; - if (data[de.offset .. de.offset + 4] != cast(ubyte[])"PK\x03\x04") - throw new ZipException("invalid directory entry 4"); + if (data[de.offset .. de.offset + 4] != cast(ubyte[])"PK\x03\x04") + throw new ZipException("invalid directory entry 4"); - // These values should match what is in the main zip archive directory - de.extractVersion = getUshort(de.offset + 4); - de.flags = getUshort(de.offset + 6); - de.compressionMethod = getUshort(de.offset + 8); - de.time = cast(DosFileTime)getUint(de.offset + 10); - de.crc32 = getUint(de.offset + 14); - de.compressedSize = getUint(de.offset + 18); - de.expandedSize = getUint(de.offset + 22); - namelen = getUshort(de.offset + 26); - extralen = getUshort(de.offset + 28); + // These values should match what is in the main zip archive directory + de.extractVersion = getUshort(de.offset + 4); + de.flags = getUshort(de.offset + 6); + de.compressionMethod = getUshort(de.offset + 8); + de.time = cast(DosFileTime)getUint(de.offset + 10); + de.crc32 = getUint(de.offset + 14); + de.compressedSize = getUint(de.offset + 18); + de.expandedSize = getUint(de.offset + 22); + namelen = getUshort(de.offset + 26); + extralen = getUshort(de.offset + 28); - debug(print) - { - printf("\t\texpandedSize = %d\n", de.expandedSize); - printf("\t\tcompressedSize = %d\n", de.compressedSize); - printf("\t\tnamelen = %d\n", namelen); - printf("\t\textralen = %d\n", extralen); - } + debug(print) + { + printf("\t\texpandedSize = %d\n", de.expandedSize); + printf("\t\tcompressedSize = %d\n", de.compressedSize); + printf("\t\tnamelen = %d\n", namelen); + printf("\t\textralen = %d\n", extralen); + } - if (de.flags & 1) - throw new ZipException("encryption not supported"); + if (de.flags & 1) + throw new ZipException("encryption not supported"); - int i; - i = de.offset + 30 + namelen + extralen; - if (i + de.compressedSize > endrecOffset) - throw new ZipException("invalid directory entry 5"); + int i; + i = de.offset + 30 + namelen + extralen; + if (i + de.compressedSize > endrecOffset) + throw new ZipException("invalid directory entry 5"); - de.compressedData = data[i .. i + de.compressedSize]; - debug(print) arrayPrint(de.compressedData); + de.compressedData = data[i .. i + de.compressedSize]; + debug(print) arrayPrint(de.compressedData); - switch (de.compressionMethod) - { - case 0: - de.expandedData = de.compressedData; - return de.expandedData; + switch (de.compressionMethod) + { + case 0: + de.expandedData = de.compressedData; + return de.expandedData; - case 8: - // -15 is a magic value used to decompress zip files. - // It has the effect of not requiring the 2 byte header - // and 4 byte trailer. - de.expandedData = cast(ubyte[])std.zlib.uncompress(cast(void[])de.compressedData, de.expandedSize, -15); - return de.expandedData; + case 8: + // -15 is a magic value used to decompress zip files. + // It has the effect of not requiring the 2 byte header + // and 4 byte trailer. + de.expandedData = cast(ubyte[])std.zlib.uncompress(cast(void[])de.compressedData, de.expandedSize, -15); + return de.expandedData; - default: - throw new ZipException("unsupported compression method"); - } + default: + throw new ZipException("unsupported compression method"); + } } /* ============ Utility =================== */ ushort getUshort(int i) { - version (LittleEndian) - { - return *cast(ushort *)&data[i]; - } - else - { - ubyte b0 = data[i]; - ubyte b1 = data[i + 1]; - return (b1 << 8) | b0; - } + version (LittleEndian) + { + return *cast(ushort *)&data[i]; + } + else + { + ubyte b0 = data[i]; + ubyte b1 = data[i + 1]; + return (b1 << 8) | b0; + } } uint getUint(int i) { - version (LittleEndian) - { - return *cast(uint *)&data[i]; - } - else - { - return bswap(*cast(uint *)&data[i]); - } + version (LittleEndian) + { + return *cast(uint *)&data[i]; + } + else + { + return bswap(*cast(uint *)&data[i]); + } } void putUshort(int i, ushort us) { - version (LittleEndian) - { - *cast(ushort *)&data[i] = us; - } - else - { - data[i] = cast(ubyte)us; - data[i + 1] = cast(ubyte)(us >> 8); - } + version (LittleEndian) + { + *cast(ushort *)&data[i] = us; + } + else + { + data[i] = cast(ubyte)us; + data[i + 1] = cast(ubyte)(us >> 8); + } } void putUint(int i, uint ui) { - version (BigEndian) - { - ui = bswap(ui); - } - *cast(uint *)&data[i] = ui; + version (BigEndian) + { + ui = bswap(ui); + } + *cast(uint *)&data[i] = ui; } } @@ -512,13 +512,13 @@ debug(print) { void arrayPrint(ubyte[] array) { - printf("array %p,%d\n", cast(void*)array, array.length); - for (int i = 0; i < array.length; i++) - { - printf("%02x ", array[i]); - if (((i + 1) & 15) == 0) - printf("\n"); - } - printf("\n"); + printf("array %p,%d\n", cast(void*)array, array.length); + for (int i = 0; i < array.length; i++) + { + printf("%02x ", array[i]); + if (((i + 1) & 15) == 0) + printf("\n"); + } + printf("\n"); } } diff --git a/win32.mak b/win32.mak index 482343db1..2311e2a6f 100644 --- a/win32.mak +++ b/win32.mak @@ -940,6 +940,9 @@ clean: cleanhtml: del $(DOCS) +detab: + detab $(SRCS) + install: $(CP) phobos.lib gcstub.obj $(DIR)\windows\lib $(CP) $(MAKEFILES) phoboslicense.txt minit.obj std.ddoc $(DIR)\src\phobos