From b8ce58ccd17e6310fa45c5260d6d3e3528229c27 Mon Sep 17 00:00:00 2001 From: Walter Bright Date: Mon, 23 Aug 2010 02:14:45 +0000 Subject: [PATCH] detab sources --- std/algorithm.d | 66 +- std/base64.d | 318 ++-- std/bigint.d | 4 +- std/c/fenv.d | 2 +- std/c/linux/linux.d | 32 +- std/c/linux/socket.d | 8 +- std/c/linux/tipc.d | 184 +-- std/c/locale.d | 4 +- std/c/math.d | 2 +- std/c/osx/socket.d | 2 +- std/c/process.d | 6 +- std/c/stdarg.d | 2 +- std/c/stddef.d | 2 +- std/c/stdio.d | 12 +- std/c/stdlib.d | 2 +- std/c/string.d | 2 +- std/c/time.d | 2 +- std/c/wcharh.d | 2 +- std/c/windows/com.d | 106 +- std/c/windows/windows.d | 2 +- std/c/windows/winsock.d | 588 ++++---- std/complex.d | 2 +- std/concurrency.d | 8 +- std/container.d | 2 +- std/conv.d | 156 +- std/cstream.d | 20 +- std/functional.d | 6 +- std/internal/math/biguintcore.d | 4 +- std/internal/math/biguintnoasm.d | 42 +- std/internal/math/biguintx86.d | 358 ++--- std/intrinsic.d | 32 +- std/json.d | 672 ++++----- std/loader.d | 180 +-- std/md5.d | 174 +-- std/openrj.d | 22 +- std/path.d | 316 ++-- std/perf.d | 1232 ++++++++-------- std/process.d | 2 +- std/random.d | 34 +- std/socket.d | 2362 +++++++++++++++--------------- std/socketstream.d | 220 +-- std/stdarg.d | 2 +- std/stdio.d | 14 +- std/stopwatch.d | 262 ++-- std/stream.d | 1048 ++++++------- std/syserror.d | 42 +- std/traits.d | 34 +- std/typelist.d | 42 +- std/uni.d | 2 +- std/windows/charset.d | 40 +- std/windows/iunknown.d | 46 +- std/windows/registry.d | 58 +- std/windows/syserror.d | 22 +- 53 files changed, 4402 insertions(+), 4402 deletions(-) diff --git a/std/algorithm.d b/std/algorithm.d index 8e582c531..d79b2c9d5 100644 --- a/std/algorithm.d +++ b/std/algorithm.d @@ -163,18 +163,18 @@ struct Map(alias fun, Range) if (isInputRange!(Range)) fillCache; } - static if (isInfinite!Range) + static if (isInfinite!Range) { - // Propagate infinite-ness. - enum bool empty = false; - } + // Propagate infinite-ness. + enum bool empty = false; + } else { - @property bool empty() + @property bool empty() { - return _input.empty; - } - } + return _input.empty; + } + } void popFront() { @@ -220,7 +220,7 @@ struct Map(alias fun, Range) if (isInputRange!(Range)) } } - static if (isForwardRange!Range) + static if (isForwardRange!Range) @property Map save() { auto result = this; @@ -300,19 +300,19 @@ unittest fibsSquares.popFront; assert(fibsSquares.front == 9); - auto repeatMap = map!"a"(repeat(1)); - static assert(isInfinite!(typeof(repeatMap))); + auto repeatMap = map!"a"(repeat(1)); + static assert(isInfinite!(typeof(repeatMap))); - auto intRange = map!"a"([1,2,3]); - static assert(isRandomAccessRange!(typeof(intRange))); + auto intRange = map!"a"([1,2,3]); + static assert(isRandomAccessRange!(typeof(intRange))); foreach(DummyType; AllDummyRanges) { - DummyType d; - auto m = map!"a * a"(d); + DummyType d; + auto m = map!"a * a"(d); - static assert(propagatesRangeType!(typeof(m), DummyType)); - assert(equal(m, [1,4,9,16,25,36,49,64,81,100])); - } + static assert(propagatesRangeType!(typeof(m), DummyType)); + assert(equal(m, [1,4,9,16,25,36,49,64,81,100])); + } } // reduce @@ -864,28 +864,28 @@ unittest assert(equal(under10, [1, 3, 5][])); static assert(isForwardRange!(typeof(under10))); - auto infinite = filter!"a > 2"(repeat(3)); - static assert(isInfinite!(typeof(infinite))); - static assert(isForwardRange!(typeof(infinite))); + auto infinite = filter!"a > 2"(repeat(3)); + static assert(isInfinite!(typeof(infinite))); + static assert(isForwardRange!(typeof(infinite))); auto nums = [0,1,2,3,4]; auto forward = filter!"a % 2 == 0"(nums); assert(equal(retro(forward), [4,2,0][])); // f is a bidirectional range - foreach(DummyType; AllDummyRanges) { - DummyType d; - auto f = filter!"a & 1"(d); - assert(equal(f, [1,3,5,7,9])); + foreach(DummyType; AllDummyRanges) { + DummyType d; + auto f = filter!"a & 1"(d); + assert(equal(f, [1,3,5,7,9])); - static if (isForwardRange!DummyType) { - static assert(isForwardRange!(typeof(f))); - } + static if (isForwardRange!DummyType) { + static assert(isForwardRange!(typeof(f))); + } - static if (isBidirectionalRange!DummyType) { - static assert(isBidirectionalRange!(typeof(f))); - assert(equal(retro(f), [9,7,5,3,1])); - } - } + static if (isBidirectionalRange!DummyType) { + static assert(isBidirectionalRange!(typeof(f))); + assert(equal(retro(f), [9,7,5,3,1])); + } + } // With delegates int x = 10; diff --git a/std/base64.d b/std/base64.d index 6552ecd41..01f1deaeb 100644 --- a/std/base64.d +++ b/std/base64.d @@ -4,10 +4,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) */ @@ -16,23 +16,23 @@ */ /* - Copyright (C) 2004 Christopher E. Miller + 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. + 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. */ module std.base64; @@ -42,10 +42,10 @@ module std.base64; class Base64Exception: Exception { - this(string msg) - { - super(msg); - } + this(string msg) + { + super(msg); + } } @@ -54,10 +54,10 @@ class Base64Exception: Exception class Base64CharException: Base64Exception { - this(string msg) - { - super(msg); - } + this(string msg) + { + super(msg); + } } @@ -69,77 +69,77 @@ immutable array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678 size_t encodeLength(size_t slen) { - auto result = slen / 3; - if(slen % 3) - result++; - return result * 4; + auto 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(string str, char[] buf) in { - assert(buf.length >= encodeLength(str.length)); + assert(buf.length >= encodeLength(str.length)); } body { - if(!str.length) - return buf[0 .. 0]; + if(!str.length) + return buf[0 .. 0]; - uint stri; - auto strmax = str.length / 3; - auto strleft = str.length % 3; - uint x; - const(char)* sp; - char* bp; + uint stri; + auto strmax = str.length / 3; + auto strleft = str.length % 3; + uint x; + const(char)* sp; + char* 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)]; - } + 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; + 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 1: + x = *sp++ << 16; + *bp++ = array[(x & 0b11111100_00000000_00000000) >> 18]; + *bp++ = array[(x & 0b00000011_11110000_00000000) >> 12]; + *bp++ = '='; + *bp++ = '='; + break; - case 0: - break; + case 0: + break; - default: - assert(0); - } + default: + assert(0); + } - return buf[0 .. (bp - &buf[0])]; + return buf[0 .. (bp - &buf[0])]; } @@ -154,11 +154,11 @@ string encode(string str) 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"); } /** @@ -167,110 +167,110 @@ unittest */ size_t decodeLength(size_t 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(string estr, char[] buf) in { //account for '=' padding - assert(buf.length + 2 >= decodeLength(estr.length)); + assert(buf.length + 2 >= decodeLength(estr.length)); } body { - void badc(char ch) - { + void badc(char ch) + { throw new Base64CharException( cast(string) ("Invalid base64 character '" ~ (&ch)[0 .. 1] ~ "'")); - } + } - uint arrayIndex(char ch) - out(result) - { + uint arrayIndex(char ch) + out(result) + { //@@BUG@@@ http://d.puremagic.com/issues/show_bug.cgi?id=3667"); - //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); - } + //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) + return buf[0 .. 0]; - if(estr.length % 4) - throw new Base64Exception("Invalid encoded base64 string"); + if(estr.length % 4) + throw new Base64Exception("Invalid encoded base64 string"); - uint estri; - auto estrmax = estr.length / 4; - uint x; - const(char)* sp; - char* bp; - char ch; + uint estri; + auto estrmax = estr.length / 4; + uint x; + const(char)* sp; + char* 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; + 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 == '=') + { + 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); + 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); - } + *bp++ = cast(char) (x >> 16); + *bp++ = cast(char) ((x >> 8) & 0xFF); + *bp++ = cast(char) (x & 0xFF); + } - return buf[0 .. (bp - &buf[0])]; + 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[]. */ string decode(string estr) @@ -281,15 +281,15 @@ string decode(string estr) 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("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("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/bigint.d b/std/bigint.d index 5cd36ad3f..48130f0fa 100644 --- a/std/bigint.d +++ b/std/bigint.d @@ -66,8 +66,8 @@ private import std.internal.math.biguintcore; struct BigInt { private: - BigUint data; // BigInt adds signed arithmetic to BigUint. - bool sign = false; + BigUint data; // BigInt adds signed arithmetic to BigUint. + bool sign = false; public: /// Construct a BigInt from a decimal or hexadecimal string. /// The number must be in the form of a D decimal or hex literal: diff --git a/std/c/fenv.d b/std/c/fenv.d index a3980322b..02344b5fd 100644 --- a/std/c/fenv.d +++ b/std/c/fenv.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, http://www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCFenv + * WIKI=Phobos/StdCFenv */ module std.c.fenv; diff --git a/std/c/linux/linux.d b/std/c/linux/linux.d index af063712a..0252f4700 100644 --- a/std/c/linux/linux.d +++ b/std/c/linux/linux.d @@ -14,30 +14,30 @@ extern (C) { extern __gshared { - void* __libc_stack_end; - int __data_start; - int _end; - int timezone; + void* __libc_stack_end; + int __data_start; + int _end; + int timezone; - void *_deh_beg; - void *_deh_end; + void *_deh_beg; + void *_deh_end; } } -struct struct_stat64 // distinguish it from the stat() function +struct struct_stat64 // distinguish it from the stat() function { - ulong st_dev; /// device + ulong st_dev; /// device uint __pad1; - uint st_ino; /// file serial number - uint st_mode; /// file mode - uint st_nlink; /// link count - uint st_uid; /// user ID of file's owner - uint st_gid; /// user ID of group's owner - ulong st_rdev; /// if device then device number + uint st_ino; /// file serial number + uint st_mode; /// file mode + uint st_nlink; /// link count + uint st_uid; /// user ID of file's owner + uint st_gid; /// user ID of group's owner + ulong st_rdev; /// if device then device number uint __pad2; align(4) ulong st_size; - int st_blksize; /// optimal I/O block size - ulong st_blocks; /// number of allocated 512 byte blocks + int st_blksize; /// optimal I/O block size + ulong st_blocks; /// number of allocated 512 byte blocks int st_atime; uint st_atimensec; int st_mtime; diff --git a/std/c/linux/socket.d b/std/c/linux/socket.d index b74d465fb..47cadd8a8 100644 --- a/std/c/linux/socket.d +++ b/std/c/linux/socket.d @@ -21,12 +21,12 @@ enum: int AF_APPLETALK = 5, PF_IPX = AF_IPX, PF_APPLETALK = AF_APPLETALK, -} +} enum: int { SOCK_RDM = 4, -} +} enum: int { @@ -45,7 +45,7 @@ struct protoent char* p_name; char** p_aliases; int32_t p_proto; -} +} protoent* getprotobyname(in char* name); protoent* getprotobynumber(int number); @@ -94,7 +94,7 @@ enum: int } enum: int -{ +{ IP_MULTICAST_LOOP = 34, IP_ADD_MEMBERSHIP = 35, IP_DROP_MEMBERSHIP = 36, diff --git a/std/c/linux/tipc.d b/std/c/linux/tipc.d index 78057d122..7ed6a85ea 100644 --- a/std/c/linux/tipc.d +++ b/std/c/linux/tipc.d @@ -14,198 +14,198 @@ extern (C): struct tipc_portid { - uint ref_; - uint node; + uint ref_; + uint node; } struct tipc_name { - uint type; - uint instance; + uint type; + uint instance; } struct tipc_name_seq { - uint type; - uint lower; - uint upper; + uint type; + uint lower; + uint upper; } struct tipc_subscr { - tipc_name_seq seq; - uint timeout; - uint filter; - ubyte usr_handle[8]; + tipc_name_seq seq; + uint timeout; + uint filter; + ubyte usr_handle[8]; } struct tipc_event { - uint event; - uint found_lower; - uint found_upper; - tipc_portid port; - tipc_subscr s; + uint event; + uint found_lower; + uint found_upper; + tipc_portid port; + tipc_subscr s; } struct sockaddr_tipc { - ushort family; - ubyte addrtype; - byte scope_; - union Addr - { - tipc_portid id; - tipc_name_seq nameseq; - static struct Name - { - tipc_name name; - uint domain; - } - Name name; - } - Addr addr; + ushort family; + ubyte addrtype; + byte scope_; + union Addr + { + tipc_portid id; + tipc_name_seq nameseq; + static struct Name + { + tipc_name name; + uint domain; + } + Name name; + } + Addr addr; } uint tipc_addr(uint zone, uint cluster, uint node) { - return (zone << 24) | (cluster << 12) | node; + return (zone << 24) | (cluster << 12) | node; } unittest { - assert (tipc_addr(0, 0, 0) == 0); - assert (tipc_addr(1, 1, 1) == 16781313); - assert (tipc_addr(2, 1, 27) == 33558555); - assert (tipc_addr(3, 1, 63) == 50335807); + assert (tipc_addr(0, 0, 0) == 0); + assert (tipc_addr(1, 1, 1) == 16781313); + assert (tipc_addr(2, 1, 27) == 33558555); + assert (tipc_addr(3, 1, 63) == 50335807); } uint tipc_zone(uint addr) { - return addr >> 24; + return addr >> 24; } unittest { - assert (tipc_zone(0u) == 0); - assert (tipc_zone(16781313u) == 1); - assert (tipc_zone(33558555u) == 2); - assert (tipc_zone(50335807u) == 3); + assert (tipc_zone(0u) == 0); + assert (tipc_zone(16781313u) == 1); + assert (tipc_zone(33558555u) == 2); + assert (tipc_zone(50335807u) == 3); } uint tipc_cluster(uint addr) { - return (addr >> 12) & 0xfff; + return (addr >> 12) & 0xfff; } unittest { - assert (tipc_cluster(0u) == 0); - assert (tipc_cluster(16781313u) == 1); - assert (tipc_cluster(33558555u) == 1); - assert (tipc_cluster(50335807u) == 1); + assert (tipc_cluster(0u) == 0); + assert (tipc_cluster(16781313u) == 1); + assert (tipc_cluster(33558555u) == 1); + assert (tipc_cluster(50335807u) == 1); } uint tipc_node(uint addr) { - return addr & 0xfff; + return addr & 0xfff; } unittest { - assert (tipc_node(0u) == 0); - assert (tipc_node(16781313u) == 1); - assert (tipc_node(33558555u) == 27); - assert (tipc_node(50335807u) == 63); + assert (tipc_node(0u) == 0); + assert (tipc_node(16781313u) == 1); + assert (tipc_node(33558555u) == 27); + assert (tipc_node(50335807u) == 63); } enum: int { - TIPC_CFG_SRV = 0, - TIPC_TOP_SRV = 1, - TIPC_RESERVED_TYPES = 64, + TIPC_CFG_SRV = 0, + TIPC_TOP_SRV = 1, + TIPC_RESERVED_TYPES = 64, } enum: int { - TIPC_ZONE_SCOPE = 1, - TIPC_CLUSTER_SCOPE = 2, - TIPC_NODE_SCOPE = 3, + TIPC_ZONE_SCOPE = 1, + TIPC_CLUSTER_SCOPE = 2, + TIPC_NODE_SCOPE = 3, } enum: int { - TIPC_MAX_USER_MSG_SIZE = 66000, + TIPC_MAX_USER_MSG_SIZE = 66000, } enum: int { - TIPC_LOW_IMPORTANCE = 0, - TIPC_MEDIUM_IMPORTANCE = 1, - TIPC_HIGH_IMPORTANCE = 2, - TIPC_CRITICAL_IMPORTANCE = 3, + TIPC_LOW_IMPORTANCE = 0, + TIPC_MEDIUM_IMPORTANCE = 1, + TIPC_HIGH_IMPORTANCE = 2, + TIPC_CRITICAL_IMPORTANCE = 3, } enum: int { - TIPC_OK = 0, - TIPC_ERR_NO_NAME = 1, - TIPC_ERR_NO_PORT = 2, - TIPC_ERR_NO_NODE = 3, - TIPC_ERR_OVERLOAD = 4, - TIPC_CONN_SHUTDOWN = 5, + TIPC_OK = 0, + TIPC_ERR_NO_NAME = 1, + TIPC_ERR_NO_PORT = 2, + TIPC_ERR_NO_NODE = 3, + TIPC_ERR_OVERLOAD = 4, + TIPC_CONN_SHUTDOWN = 5, } enum: int { - TIPC_SUB_PORTS = 0x01, - TIPC_SUB_SERVICE = 0x02, - TIPC_SUB_CANCEL = 0x04, + TIPC_SUB_PORTS = 0x01, + TIPC_SUB_SERVICE = 0x02, + TIPC_SUB_CANCEL = 0x04, } version (none) enum: int { - TIPC_SUB_NO_BIND_EVTS = 0x04, - TIPC_SUB_NO_UNBIND_EVTS = 0x08, - TIPC_SUB_SINGLE_EVT = 0x10, + TIPC_SUB_NO_BIND_EVTS = 0x04, + TIPC_SUB_NO_UNBIND_EVTS = 0x08, + TIPC_SUB_SINGLE_EVT = 0x10, } enum: int { - TIPC_WAIT_FOREVER = ~0, + TIPC_WAIT_FOREVER = ~0, } enum: int { - TIPC_PUBLISHED = 1, - TIPC_WITHDRAWN = 2, - TIPC_SUBSCR_TIMEOUT = 3, + TIPC_PUBLISHED = 1, + TIPC_WITHDRAWN = 2, + TIPC_SUBSCR_TIMEOUT = 3, } enum: int { - AF_TIPC = 30, - PF_TIPC = 30, - SOL_TIPC = 271, - TIPC_ADDR_NAMESEQ = 1, - TIPC_ADDR_MCAST = 1, - TIPC_ADDR_NAME = 2, - TIPC_ADDR_ID = 3, + AF_TIPC = 30, + PF_TIPC = 30, + SOL_TIPC = 271, + TIPC_ADDR_NAMESEQ = 1, + TIPC_ADDR_MCAST = 1, + TIPC_ADDR_NAME = 2, + TIPC_ADDR_ID = 3, } enum: int { - TIPC_ERRINFO = 1, - TIPC_RETDATA = 2, - TIPC_DESTNAME = 3, + TIPC_ERRINFO = 1, + TIPC_RETDATA = 2, + TIPC_DESTNAME = 3, } enum: int { - TIPC_IMPORTANCE = 127, - TIPC_SRC_DROPPABLE = 128, - TIPC_DEST_DROPPABLE = 129, - TIPC_CONN_TIMEOUT = 130, + TIPC_IMPORTANCE = 127, + TIPC_SRC_DROPPABLE = 128, + TIPC_DEST_DROPPABLE = 129, + TIPC_CONN_TIMEOUT = 130, } diff --git a/std/c/locale.d b/std/c/locale.d index c0fe887c1..89d4004e8 100644 --- a/std/c/locale.d +++ b/std/c/locale.d @@ -2,9 +2,9 @@ * C's <locale.h> * License: Public Domain * Standards: - * ISO/IEC 9899:1999 7.11 + * ISO/IEC 9899:1999 7.11 * Macros: - * WIKI=Phobos/StdCLocale + * WIKI=Phobos/StdCLocale */ module std.c.locale; diff --git a/std/c/math.d b/std/c/math.d index ef8ee4f39..cc6454a58 100644 --- a/std/c/math.d +++ b/std/c/math.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCMath + * WIKI=Phobos/StdCMath */ module std.c.math; diff --git a/std/c/osx/socket.d b/std/c/osx/socket.d index 4f905f74e..5ced478c6 100644 --- a/std/c/osx/socket.d +++ b/std/c/osx/socket.d @@ -45,7 +45,7 @@ struct protoent char* p_name; char** p_aliases; int32_t p_proto; -} +} protoent* getprotobyname(in char* name); protoent* getprotobynumber(int number); diff --git a/std/c/process.d b/std/c/process.d index 0f3dca031..69c1f2ab7 100644 --- a/std/c/process.d +++ b/std/c/process.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCProcess + * WIKI=Phobos/StdCProcess */ module std.c.process; @@ -47,8 +47,8 @@ version (Windows) extern (Windows) alias uint (*stdfp)(void *); uint _beginthreadex(void* security, uint stack_size, - stdfp start_addr, void* arglist, uint initflag, - uint* thrdaddr); + stdfp start_addr, void* arglist, uint initflag, + uint* thrdaddr); void _endthread(); void _endthreadex(uint); diff --git a/std/c/stdarg.d b/std/c/stdarg.d index 80f8948ca..8fd2d4915 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. */ diff --git a/std/c/stddef.d b/std/c/stddef.d index 6876f834f..8f41d5d35 100644 --- a/std/c/stddef.d +++ b/std/c/stddef.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, http://www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCStddef + * WIKI=Phobos/StdCStddef */ module std.c.stddef; diff --git a/std/c/stdio.d b/std/c/stdio.d index 35aa86067..1fa067d78 100644 --- a/std/c/stdio.d +++ b/std/c/stdio.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, http://www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCStdio + * WIKI=Phobos/StdCStdio */ @@ -21,10 +21,10 @@ version (Win32) enum { - FHND_APPEND = 0x04, - FHND_DEVICE = 0x08, - FHND_TEXT = 0x10, - FHND_BYTE = 0x20, - FHND_WCHAR = 0x40, + FHND_APPEND = 0x04, + FHND_DEVICE = 0x08, + FHND_TEXT = 0x10, + FHND_BYTE = 0x20, + FHND_WCHAR = 0x40, } } diff --git a/std/c/stdlib.d b/std/c/stdlib.d index 8627aa7b6..3b34a9e17 100644 --- a/std/c/stdlib.d +++ b/std/c/stdlib.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, http://www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCStdlib + * WIKI=Phobos/StdCStdlib */ diff --git a/std/c/string.d b/std/c/string.d index fa97604ff..8382e63b9 100644 --- a/std/c/string.d +++ b/std/c/string.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, http://www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCString + * WIKI=Phobos/StdCString */ module std.c.string; diff --git a/std/c/time.d b/std/c/time.d index b3b60924a..f0fe47a62 100644 --- a/std/c/time.d +++ b/std/c/time.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCTime + * WIKI=Phobos/StdCTime */ module std.c.time; diff --git a/std/c/wcharh.d b/std/c/wcharh.d index 281476048..f4e93cc42 100644 --- a/std/c/wcharh.d +++ b/std/c/wcharh.d @@ -4,7 +4,7 @@ * Authors: Walter Bright, Digital Mars, www.digitalmars.com * License: Public Domain * Macros: - * WIKI=Phobos/StdCWchar + * WIKI=Phobos/StdCWchar */ module std.c.wcharh; diff --git a/std/c/windows/com.d b/std/c/windows/com.d index 2d33e3c37..d9a88f84e 100644 --- a/std/c/windows/com.d +++ b/std/c/windows/com.d @@ -12,49 +12,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 const(GUID) IID; @@ -208,41 +208,41 @@ class ComObject : IUnknown extern (System): HRESULT QueryInterface(const(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 9d0c962bb..792ec7e8f 100644 --- a/std/c/windows/windows.d +++ b/std/c/windows/windows.d @@ -11,5 +11,5 @@ version (Windows) } else { - static assert(0); // Windows only + static assert(0); // Windows only } diff --git a/std/c/windows/winsock.d b/std/c/windows/winsock.d index 313d231fc..391c320d2 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/complex.d b/std/complex.d index 96fecd37b..6b0b41ab4 100644 --- a/std/complex.d +++ b/std/complex.d @@ -320,7 +320,7 @@ struct Complex(T) if (isFloatingPoint!T) /** Convert the complex number to a string representation. - + If a $(D sink) delegate is specified, the string is passed to it and this function returns $(D null). Otherwise, this function returns the string representation directly. diff --git a/std/concurrency.d b/std/concurrency.d index 820f03787..5b9c61a30 100644 --- a/std/concurrency.d +++ b/std/concurrency.d @@ -106,7 +106,7 @@ private } } } - + void checkops(T...)( T ops ) { foreach( i, t1; T ) @@ -412,7 +412,7 @@ unittest receive( (Variant x) {} ); receive( (int x) {}, (Variant x) {} ); } ) ); - + assert( !__traits( compiles, { receive( (Variant x) {}, (int x) {} ); @@ -461,7 +461,7 @@ receiveOnlyRet!(T) receiveOnly(T...)() */ bool receiveTimeout(T...)( long ms, T ops ) { - checkops( ops ); + checkops( ops ); static enum long TICKS_PER_MILLI = 10_000; return mbox.get( ms * TICKS_PER_MILLI, ops ); } @@ -479,7 +479,7 @@ unittest { receiveTimeout( 0, (Variant x) {}, (int x) {} ); } ) ); - + assert( !__traits( compiles, { receiveTimeout( 0, (int x) {}, (int x) {} ); diff --git a/std/container.d b/std/container.d index fb38d8fef..c78f60f09 100755 --- a/std/container.d +++ b/std/container.d @@ -1317,7 +1317,7 @@ struct Array(T) if (!is(T : const(bool))) { if (elements <= capacity) return; immutable sz = elements * T.sizeof; - static if (hasIndirections!T) // should use hasPointers instead + static if (hasIndirections!T) // should use hasPointers instead { /* Because of the transactional nature of this * relative to the garbage collector, ensure no diff --git a/std/conv.d b/std/conv.d index 56227a55b..a2bb734fd 100644 --- a/std/conv.d +++ b/std/conv.d @@ -697,9 +697,9 @@ T toImpl(T, S)(S src) if (isArray!(S) && isArray!(T) && !isSomeString!(T) alias typeof(T.init[0]) E; auto result = new E[src.length]; foreach (i, e; src) { - /* Temporarily cast to mutable type, so we can get it initialized, - * this is ok because there are no other references to result[] - */ + /* Temporarily cast to mutable type, so we can get it initialized, + * this is ok because there are no other references to result[] + */ cast()(result[i]) = to!(E)(e); } return result; @@ -1127,29 +1127,29 @@ unittest { debug(conv) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " succeeded."); // @@@BUG@@@ the size of China - // foreach (i; 2..37) { - // assert(parse!int("0",i) == 0); - // assert(parse!int("1",i) == 1); - // assert(parse!byte("10",i) == i); - // } - foreach (i; 2..37) { + // foreach (i; 2..37) { + // assert(parse!int("0",i) == 0); + // assert(parse!int("1",i) == 1); + // assert(parse!byte("10",i) == i); + // } + foreach (i; 2..37) { string s = "0"; - assert(parse!int(s,i) == 0); + assert(parse!int(s,i) == 0); s = "1"; - assert(parse!int(s,i) == 1); + assert(parse!int(s,i) == 1); s = "10"; - assert(parse!byte(s,i) == i); - } + assert(parse!byte(s,i) == i); + } // Same @@@BUG@@@ as above - //assert(parse!int("0011001101101", 2) == 0b0011001101101); - // assert(parse!int("765",8) == 0765); - // assert(parse!int("fCDe",16) == 0xfcde); + //assert(parse!int("0011001101101", 2) == 0b0011001101101); + // assert(parse!int("765",8) == 0765); + // assert(parse!int("fCDe",16) == 0xfcde); auto s = "0011001101101"; - assert(parse!int(s, 2) == 0b0011001101101); + assert(parse!int(s, 2) == 0b0011001101101); s = "765"; - assert(parse!int(s, 8) == octal!765); + assert(parse!int(s, 8) == octal!765); s = "fCDe"; - assert(parse!int(s, 16) == 0xfcde); + assert(parse!int(s, 16) == 0xfcde); } Target parse(Target, Source)(ref Source s) @@ -3572,37 +3572,37 @@ Take a look at int.max and int.max+1 in octal and the logic for this function follows directly. */ template octalFitsInInt(string octalNum) { - // note it is important to strip the literal of all - // non-numbers. kill the suffix and underscores lest they mess up - // the number of digits here that we depend on. + // note it is important to strip the literal of all + // non-numbers. kill the suffix and underscores lest they mess up + // the number of digits here that we depend on. enum bool octalFitsInInt = strippedOctalLiteral(octalNum).length < 11 || strippedOctalLiteral(octalNum).length == 11 && strippedOctalLiteral(octalNum)[0] == '1'; } string strippedOctalLiteral(string original) { - string stripped; - foreach (c; original) - if (c >= '0' && c <= '7') - stripped ~= c; - return stripped; + string stripped; + foreach (c; original) + if (c >= '0' && c <= '7') + stripped ~= c; + return stripped; } template literalIsLong(string num) { - static if (num.length > 1) + static if (num.length > 1) // can be xxL or xxLu according to spec - enum literalIsLong = (num[$-1] == 'L' || num[$-2] == 'L'); - else - enum literalIsLong = false; + enum literalIsLong = (num[$-1] == 'L' || num[$-2] == 'L'); + else + enum literalIsLong = false; } template literalIsUnsigned(string num) { - static if (num.length > 1) + static if (num.length > 1) // can be xxL or xxLu according to spec - enum literalIsUnsigned = (num[$-1] == 'u' || num[$-2] == 'u') + enum literalIsUnsigned = (num[$-1] == 'u' || num[$-2] == 'u') // both cases are allowed too || (num[$-1] == 'U' || num[$-2] == 'U'); - else + else enum literalIsUnsigned = false; } @@ -3633,25 +3633,25 @@ auto z = octal!"1_000_000u"; */ int octal(string num)() if((octalFitsInInt!(num) && !literalIsLong!(num)) && !literalIsUnsigned!(num)) { - return octal!(int, num); + return octal!(int, num); } /// Ditto long octal(string num)() if((!octalFitsInInt!(num) || literalIsLong!(num)) && !literalIsUnsigned!(num)) { - return octal!(long, num); + return octal!(long, num); } /// Ditto uint octal(string num)() if((octalFitsInInt!(num) && !literalIsLong!(num)) && literalIsUnsigned!(num)) { - return octal!(int, num); + return octal!(int, num); } /// Ditto ulong octal(string num)() if((!octalFitsInInt!(num) || literalIsLong!(num)) && literalIsUnsigned!(num)) { - return octal!(long, num); + return octal!(long, num); } /* @@ -3661,54 +3661,54 @@ The format is specified in lex.html. The leading zero is allowed, but not required. */ bool isOctalLiteralString(string num) { - if (num.length == 0) - return false; + if (num.length == 0) + return false; - // Must start with a number. To avoid confusion, literals that + // Must start with a number. To avoid confusion, literals that // start with a '0' are not allowed if (num[0] == '0' && num.length > 1) return false; - if (num[0] < '0' || num[0] > '7') - return false; + if (num[0] < '0' || num[0] > '7') + return false; - foreach (i, c; num) { - if ((c < '0' || c > '7') && c != '_') // not a legal character - if (i < num.length - 2) - return false; - else { // gotta check for those suffixes - if (c != 'U' && c != 'u' && c != 'L') - return false; - if (i != num.length - 1) { + foreach (i, c; num) { + if ((c < '0' || c > '7') && c != '_') // not a legal character + if (i < num.length - 2) + return false; + else { // gotta check for those suffixes + if (c != 'U' && c != 'u' && c != 'L') + return false; + if (i != num.length - 1) { // if we're not the last one, the next one must // also be a suffix to be valid - char c2 = num[$-1]; - if (c2 != 'U' && c2 != 'u' && c2 != 'L') - return false; // spam at the end of the string - if (c2 == c) - return false; // repeats are disallowed - } - } - } + char c2 = num[$-1]; + if (c2 != 'U' && c2 != 'u' && c2 != 'L') + return false; // spam at the end of the string + if (c2 == c) + return false; // repeats are disallowed + } + } + } - return true; + return true; } /* - Returns true if the given compile time string is an octal literal. + Returns true if the given compile time string is an octal literal. */ template isOctalLiteral(string num) { - enum bool isOctalLiteral = isOctalLiteralString(num); + enum bool isOctalLiteral = isOctalLiteralString(num); } /* - Takes a string, num, which is an octal literal, and returns its - value, in the type T specified. + Takes a string, num, which is an octal literal, and returns its + value, in the type T specified. - So: + So: - int a = octal!(int, "10"); + int a = octal!(int, "10"); - assert(a == 8); + assert(a == 8); */ T octal(T, string num)() { static assert(isOctalLiteral!num, num ~ " is not a valid octal literal"); @@ -3718,13 +3718,13 @@ T octal(T, string num)() { for (int pos = num.length - 1; pos >= 0; pos--) { char s = num[pos]; - if (s < '0' || s > '7') // we only care about digits; skip the rest + if (s < '0' || s > '7') // we only care about digits; skip the rest // safe to skip - this is checked out in the assert so these // are just suffixes - continue; + continue; - value += pow * (s - '0'); - pow *= 8; + value += pow * (s - '0'); + pow *= 8; } return value; @@ -3732,17 +3732,17 @@ T octal(T, string num)() { /// Ditto template octal(alias s) if (isIntegral!(typeof(s))) { - enum auto octal = octal!(typeof(s), toStringNow!(s)); + enum auto octal = octal!(typeof(s), toStringNow!(s)); } unittest { debug(conv) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " succeeded."); - // ensure that you get the right types, even with embedded underscores - auto w = octal!"100_000_000_000"; - static assert(!is(typeof(w) == int)); - auto w2 = octal!"1_000_000_000"; - static assert(is(typeof(w2) == int)); + // ensure that you get the right types, even with embedded underscores + auto w = octal!"100_000_000_000"; + static assert(!is(typeof(w) == int)); + auto w2 = octal!"1_000_000_000"; + static assert(is(typeof(w2) == int)); static assert(octal!"45" == 37); static assert(octal!"0" == 0); @@ -3825,7 +3825,7 @@ T* emplace(T, Args...)(void[] chunk, Args args) if (!is(T == class)) enforce(chunk.length >= T.sizeof, new ConvError("emplace: target size too small")); auto a = cast(size_t) chunk.ptr; - version (OSX) // for some reason, breaks on other platforms + version (OSX) // for some reason, breaks on other platforms enforce(a % T.alignof == 0, new ConvError("misalignment")); auto result = cast(typeof(return)) chunk.ptr; diff --git a/std/cstream.d b/std/cstream.d index 7316fde86..0897b7242 100644 --- a/std/cstream.d +++ b/std/cstream.d @@ -58,7 +58,7 @@ class CFile : Stream { * Ditto */ void file(FILE* cfile) { - this.cfile = cfile; + this.cfile = cfile; isopen = true; } @@ -71,31 +71,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/functional.d b/std/functional.d index f06923895..30be8ead3 100644 --- a/std/functional.d +++ b/std/functional.d @@ -453,13 +453,13 @@ template compose(fun...) { alias composeImpl!(fun).doIt compose; } // Implementation of compose template composeImpl(fun...) { - static if (fun.length == 1) - { + static if (fun.length == 1) + { static if (is(typeof(fun[0]) : string)) alias unaryFun!(fun[0]) doIt; else alias fun[0] doIt; - } + } else static if (fun.length == 2) { // starch diff --git a/std/internal/math/biguintcore.d b/std/internal/math/biguintcore.d index 788abe92c..af7149018 100644 --- a/std/internal/math/biguintcore.d +++ b/std/internal/math/biguintcore.d @@ -1414,7 +1414,7 @@ size_t karatsubaRequiredBuffSize(size_t xlen) void mulKaratsuba(BigDigit [] result, const(BigDigit) [] x, const(BigDigit)[] y, BigDigit [] scratchbuff) { assert(x.length >= y.length); - assert(result.length < uint.max, "Operands too large"); + assert(result.length < uint.max, "Operands too large"); assert(result.length == x.length + y.length); if (x.length <= KARATSUBALIMIT) { return mulSimple(result, x, y); @@ -1512,7 +1512,7 @@ void squareKaratsuba(BigDigit [] result, BigDigit [] x, BigDigit [] scratchbuff) { // See mulKaratsuba for implementation comments. // Squaring is simpler, since it never gets asymmetric. - assert(result.length < uint.max, "Operands too large"); + assert(result.length < uint.max, "Operands too large"); assert(result.length == 2*x.length); if (x.length <= KARATSUBASQUARELIMIT) { return squareSimple(result, x); diff --git a/std/internal/math/biguintnoasm.d b/std/internal/math/biguintnoasm.d index 8eb0b60e3..303ba3961 100644 --- a/std/internal/math/biguintnoasm.d +++ b/std/internal/math/biguintnoasm.d @@ -150,18 +150,18 @@ unittest uint [] aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; multibyteShr(aa[0..$-2], aa, 4); - assert(aa[0]==0x6122_2222 && aa[1]==0xA455_5555 && aa[2]==0x0899_9999); - assert(aa[3]==0xBCCC_CCCD); + assert(aa[0]==0x6122_2222 && aa[1]==0xA455_5555 && aa[2]==0x0899_9999); + assert(aa[3]==0xBCCC_CCCD); aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; multibyteShr(aa[0..$-1], aa, 4); - assert(aa[0] == 0x6122_2222 && aa[1]==0xA455_5555 - && aa[2]==0xD899_9999 && aa[3]==0x0BCC_CCCC); + assert(aa[0] == 0x6122_2222 && aa[1]==0xA455_5555 + && aa[2]==0xD899_9999 && aa[3]==0x0BCC_CCCC); aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; multibyteShl(aa[1..4], aa[1..$], 4); - assert(aa[0] == 0xF0FF_FFFF && aa[1] == 0x2222_2230 - && aa[2]==0x5555_5561 && aa[3]==0x9999_99A4 && aa[4]==0x0BCCC_CCCD); + assert(aa[0] == 0xF0FF_FFFF && aa[1] == 0x2222_2230 + && aa[2]==0x5555_5561 && aa[3]==0x9999_99A4 && aa[4]==0x0BCCC_CCCD); } /** dest[] = src[] * multiplier + carry. @@ -183,7 +183,7 @@ unittest { uint [] aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; multibyteMul(aa[1..4], aa[1..4], 16, 0); - assert(aa[0] == 0xF0FF_FFFF && aa[1] == 0x2222_2230 && aa[2]==0x5555_5561 && aa[3]==0x9999_99A4 && aa[4]==0x0BCCC_CCCD); + assert(aa[0] == 0xF0FF_FFFF && aa[1] == 0x2222_2230 && aa[2]==0x5555_5561 && aa[3]==0x9999_99A4 && aa[4]==0x0BCCC_CCCD); } /** @@ -214,9 +214,9 @@ unittest { uint [] aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE]; uint [] bb = [0x1234_1234, 0xF0F0_F0F0, 0x00C0_C0C0, 0xF0F0_F0F0, 0xC0C0_C0C0]; multibyteMulAdd!('+')(bb[1..$-1], aa[1..$-2], 16, 5); - assert(bb[0] == 0x1234_1234 && bb[4] == 0xC0C0_C0C0); + assert(bb[0] == 0x1234_1234 && bb[4] == 0xC0C0_C0C0); assert(bb[1] == 0x2222_2230 + 0xF0F0_F0F0+5 && bb[2] == 0x5555_5561+0x00C0_C0C0+1 - && bb[3] == 0x9999_99A4+0xF0F0_F0F0 ); + && bb[3] == 0x9999_99A4+0xF0F0_F0F0 ); } @@ -269,7 +269,7 @@ void multibyteAddDiagonalSquares(uint[] dest, const(uint)[] src) { ulong c = 0; for(int i = 0; i < src.length; ++i){ - // At this point, c is 0 or 1, since FFFF*FFFF+FFFF_FFFF = 1_0000_0000. + // At this point, c is 0 or 1, since FFFF*FFFF+FFFF_FFFF = 1_0000_0000. c += cast(ulong)(src[i]) * src[i] + dest[2*i]; dest[2*i] = cast(uint)c; c = (c>>=32) + dest[2*i+1]; @@ -283,20 +283,20 @@ void multibyteTriangleAccumulate(uint[] dest, const(uint)[] x) { // x[0]*x[1...$] + x[1]*x[2..$] + ... + x[$-2]x[$-1..$] dest[x.length] = multibyteMul(dest[1 .. x.length], x[1..$], x[0], 0); - if (x.length <4) { - if (x.length ==3) { + if (x.length <4) { + if (x.length ==3) { ulong c = cast(ulong)(x[$-1]) * x[$-2] + dest[2*x.length-3]; - dest[2*x.length-3] = cast(uint)c; - c >>= 32; - dest[2*x.length-2] = cast(uint)c; + dest[2*x.length-3] = cast(uint)c; + c >>= 32; + dest[2*x.length-2] = cast(uint)c; + } + return; } - return; - } for (int i = 2; i < x.length-2; ++i) { dest[i-1+ x.length] = multibyteMulAdd!('+')( dest[i+i-1 .. i+x.length-1], x[i..$], x[i-1], 0); } - // Unroll the last two entries, to reduce loop overhead: + // Unroll the last two entries, to reduce loop overhead: ulong c = cast(ulong)(x[$-3]) * x[$-2] + dest[2*x.length-5]; dest[2*x.length-5] = cast(uint)c; c >>= 32; @@ -304,9 +304,9 @@ void multibyteTriangleAccumulate(uint[] dest, const(uint)[] x) dest[2*x.length-4] = cast(uint)c; c >>= 32; c += cast(ulong)(x[$-1]) * x[$-2]; - dest[2*x.length-3] = cast(uint)c; - c >>= 32; - dest[2*x.length-2] = cast(uint)c; + dest[2*x.length-3] = cast(uint)c; + c >>= 32; + dest[2*x.length-2] = cast(uint)c; } void multibyteSquare(BigDigit[] result, const(BigDigit) [] x) diff --git a/std/internal/math/biguintx86.d b/std/internal/math/biguintx86.d index b9d5f657a..b26f74134 100644 --- a/std/internal/math/biguintx86.d +++ b/std/internal/math/biguintx86.d @@ -1,14 +1,14 @@ -/** Optimised asm arbitrary precision arithmetic ('bignum') +/** Optimised asm arbitrary precision arithmetic ('bignum') * routines for X86 processors. * * All functions operate on arrays of uints, stored LSB first. * If there is a destination array, it will be the first parameter. * Currently, all of these functions are subject to change, and are - * intended for internal use only. + * intended for internal use only. * The symbol [#] indicates an array of machine words which is to be * interpreted as a multi-byte number. */ - + /* Copyright Don Clugston 2008 - 2010. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at @@ -21,18 +21,18 @@ * (c) the Pentium 4, produced by Marketing. * * This code has been optimised for the Intel P6 family. - * Generally the code remains near-optimal for Intel Core2/Corei7, after + * Generally the code remains near-optimal for Intel Core2/Corei7, after * translating EAX-> RAX, etc, since all these CPUs use essentially the same * pipeline, and are typically limited by memory access. * The code uses techniques described in Agner Fog's superb Pentium manuals * available at www.agner.org. * Not optimised for AMD, which can do two memory loads per cycle (Intel * CPUs can only do one). Despite this, performance is superior on AMD. - * Performance is dreadful on P4. + * Performance is dreadful on P4. * * Timing results (cycles per int) * --Intel Pentium-- --AMD-- - * PM P4 Core2 K7 + * PM P4 Core2 K7 * +,- 2.25 15.6 2.25 1.5 * <<,>> 2.0 6.6 2.0 5.0 * (<< MMX) 1.7 5.3 1.5 1.2 @@ -50,7 +50,7 @@ module std.internal.math.biguintx86; -/* +/* Naked asm is used throughout, because: (a) it frees up the EBP register (b) compiler bugs prevent the use of .ptr when a frame pointer is used. @@ -70,7 +70,7 @@ string indexedLoopUnroll(int n, string s) string u; for (int i = 0; i9 ? ""~ cast(char)('0'+i/10) : "") ~ cast(char)('0' + i%10); - + int last = 0; for (int j = 0; j>= 32; -length2: +length2: c += cast(ulong)(x[$-2]) * x[$-1]; - dest[$-3] = cast(uint)c; - c >>= 32; - dest[$-2] = cast(uint)c; + dest[$-3] = cast(uint)c; + c >>= 32; + dest[$-2] = cast(uint)c; } //dest += src[0]*src[1...$] + src[1]*src[2..$] + ... + src[$-3]*src[$-2..$]+ src[$-2]*src[$-1] @@ -1100,7 +1100,7 @@ void multibyteTriangleAccumulateAsm(uint[] dest, const uint[] src) // use p2 (load unit) instead of the overworked p0 or p1 (ALU units) // when initializing registers to zero. __gshared int zero = 0; - // use p3/p4 units + // use p3/p4 units __gshared int storagenop; // write-only } @@ -1125,16 +1125,16 @@ void multibyteTriangleAccumulateAsm(uint[] dest, const uint[] src) lea EDI, [EDI + 4*EBX]; // EDI = end of dest for first pass lea EAX, [EDI + 4*EBX-3*4]; // up to src.length - 3 - mov [ESP + LASTPARAM + 4*2], EAX; // last value for EDI = &dest[src.length*2 -3] + mov [ESP + LASTPARAM + 4*2], EAX; // last value for EDI = &dest[src.length*2 -3] cmp EBX, 3; jz length_is_3; - - // We start at src[1], not src[0]. + + // We start at src[1], not src[0]. dec EBX; mov [ESP + LASTPARAM + 4*0], EBX; -outer_loop: +outer_loop: mov EBX, [ESP + LASTPARAM + 4*0]; // src.length mov EBP, 0; mov ECX, 0; // ECX = input carry. @@ -1154,12 +1154,12 @@ outer_loop: mov [-4+EDI+4*EBX], EBP; add EDI, 4; cmp EDI, [ESP + LASTPARAM + 4*2]; // is EDI = &dest[$-3]? - jnz outer_loop; + jnz outer_loop; length_is_3: mov EAX, [ESI - 4*3]; mul EAX, [ESI - 4*2]; mov ECX, 0; - add [EDI-2*4], EAX; // ECX:dest[$-5] += x[$-3] * x[$-2] + add [EDI-2*4], EAX; // ECX:dest[$-5] += x[$-3] * x[$-2] adc ECX, EDX; mov EAX, [ESI - 4*3]; @@ -1170,11 +1170,11 @@ length_is_3: // now EDX: EAX = c + x[$-3] * x[$-1] add [EDI-1*4], EAX; // ECX:dest[$-4] += (EDX:EAX) adc ECX, EDX; // ECX holds dest[$-3], it acts as carry for the last row -// do length==2 +// do length==2 mov EAX, [ESI - 4*2]; mul EAX, [ESI - 4*1]; add ECX, EAX; - adc EDX, 0; + adc EDX, 0; mov [EDI - 0*4], ECX; // dest[$-2:$-3] = c + x[$-2] * x[$-1]; mov [EDI + 1*4], EDX; @@ -1208,20 +1208,20 @@ unittest c[3] = 6; assert(a[]==c[]); assert(a[0]==0); - aa[] = 0xFFFF_FFFF; + aa[] = 0xFFFF_FFFF; a[] = 0; b[] = 0; b[0]= 0xbf6a1f01; b[1]= 0x6e38ed64; b[2]= 0xdaa797ed; b[3] = 0; - + multibyteTriangleAccumulateAsm(a[0..8], b[0..4]); assert(a[1]==0x3a600964); assert(a[2]==0x339974f6); assert(a[3]==0x46736fce); assert(a[4]==0x5e24a2b4); - + b[3] = 0xe93ff9f4; b[4] = 0x184f03; a[]=0; @@ -1237,7 +1237,7 @@ void multibyteSquare(BigDigit[] result, const BigDigit [] x) { if (x.length < 4) { // Special cases, not worth doing triangular. - result[x.length] = multibyteMul(result[0..x.length], x, x[0], 0); + result[x.length] = multibyteMul(result[0..x.length], x, x[0], 0); multibyteMultiplyAccumulate(result[1..$], x, x[1..$]); return; } @@ -1245,7 +1245,7 @@ void multibyteSquare(BigDigit[] result, const BigDigit [] x) // dest += src[0]*src[1...$] + src[1]*src[2..$] + ... + src[$-3]*src[$-2..$]+ src[$-2]*src[$-1] result[x.length] = multibyteMul(result[1 .. x.length], x[1..$], x[0], 0); multibyteTriangleAccumulateAsm(result[2..$], x[1..$]); - // Multiply by 2 + // Multiply by 2 result[$-1] = multibyteShlNoMMX(result[1..$-1], result[1..$-1], 1); // And add the diagonal elements result[0] = 0; @@ -1267,7 +1267,7 @@ void testPerformance() // The code below is less accurate but more widely usable. // The value for division is quite inconsistent. for (int i=0; i maxDepth) error("Nesting too deep."); + if(maxDepth != -1 && depth > maxDepth) error("Nesting too deep."); - auto c = getChar!true(); + auto c = getChar!true(); - switch(c) { - case '{': - value.type = JSON_TYPE.OBJECT; - value.object = null; + switch(c) { + case '{': + value.type = JSON_TYPE.OBJECT; + value.object = null; - if(testChar('}')) break; + if(testChar('}')) break; - do { - checkChar('"'); - string name = parseString(); - checkChar(':'); - JSONValue member = void; - parseValue(&member); - value.object[name] = member; - } while(testChar(',')); + do { + checkChar('"'); + string name = parseString(); + checkChar(':'); + JSONValue member = void; + parseValue(&member); + value.object[name] = member; + } while(testChar(',')); - checkChar('}'); - break; + checkChar('}'); + break; - case '[': - value.type = JSON_TYPE.ARRAY; - value.array = null; + case '[': + value.type = JSON_TYPE.ARRAY; + value.array = null; - if(testChar(']')) break; + if(testChar(']')) break; - do { - JSONValue element = void; - parseValue(&element); - value.array ~= element; - } while(testChar(',')); + do { + JSONValue element = void; + parseValue(&element); + value.array ~= element; + } while(testChar(',')); - checkChar(']'); - break; + checkChar(']'); + break; - case '"': - value.type = JSON_TYPE.STRING; - value.str = parseString(); - break; + case '"': + value.type = JSON_TYPE.STRING; + value.str = parseString(); + break; - case '0': .. case '9': - case '-': - auto number = appender!string(); - bool isFloat; + case '0': .. case '9': + case '-': + auto number = appender!string(); + bool isFloat; - void readInteger() { - if(!isdigit(c)) error("Digit expected"); + void readInteger() { + if(!isdigit(c)) error("Digit expected"); - Next: number.put(c); + Next: number.put(c); - if(isdigit(peekChar())) { - c = getChar(); - goto Next; - } - } + if(isdigit(peekChar())) { + c = getChar(); + goto Next; + } + } - if(c == '-') { - number.put('-'); - c = getChar(); - } + if(c == '-') { + number.put('-'); + c = getChar(); + } - readInteger(); + readInteger(); - if(testChar('.')) { - isFloat = true; - number.put('.'); - c = getChar(); - readInteger(); - } - if(testChar!(false, false)('e')) { - isFloat = true; - number.put('e'); - if(testChar('+')) number.put('+'); - else if(testChar('-')) number.put('-'); - c = getChar(); - readInteger(); - } + if(testChar('.')) { + isFloat = true; + number.put('.'); + c = getChar(); + readInteger(); + } + if(testChar!(false, false)('e')) { + isFloat = true; + number.put('e'); + if(testChar('+')) number.put('+'); + else if(testChar('-')) number.put('-'); + c = getChar(); + readInteger(); + } - string data = number.data; - if(isFloat) { - value.type = JSON_TYPE.FLOAT; - value.floating = parse!real(data); - } - else { - value.type = JSON_TYPE.INTEGER; - value.integer = parse!long(data); - } - break; + string data = number.data; + if(isFloat) { + value.type = JSON_TYPE.FLOAT; + value.floating = parse!real(data); + } + else { + value.type = JSON_TYPE.INTEGER; + value.integer = parse!long(data); + } + break; - case 't': - case 'T': - value.type = JSON_TYPE.TRUE; - checkChar!(false, false)('r'); - checkChar!(false, false)('u'); - checkChar!(false, false)('e'); - break; + case 't': + case 'T': + value.type = JSON_TYPE.TRUE; + checkChar!(false, false)('r'); + checkChar!(false, false)('u'); + checkChar!(false, false)('e'); + break; - case 'f': - case 'F': - value.type = JSON_TYPE.FALSE; - checkChar!(false, false)('a'); - checkChar!(false, false)('l'); - checkChar!(false, false)('s'); - checkChar!(false, false)('e'); - break; + case 'f': + case 'F': + value.type = JSON_TYPE.FALSE; + checkChar!(false, false)('a'); + checkChar!(false, false)('l'); + checkChar!(false, false)('s'); + checkChar!(false, false)('e'); + break; - case 'n': - case 'N': - value.type = JSON_TYPE.NULL; - checkChar!(false, false)('u'); - checkChar!(false, false)('l'); - checkChar!(false, false)('l'); - break; + case 'n': + case 'N': + value.type = JSON_TYPE.NULL; + checkChar!(false, false)('u'); + checkChar!(false, false)('l'); + checkChar!(false, false)('l'); + break; - default: - error(text("Unexpected character '", c, "'.")); - } + default: + error(text("Unexpected character '", c, "'.")); + } - depth--; - } + depth--; + } - parseValue(&root); - return root; + parseValue(&root); + return root; } /** Takes a tree of JSON values and returns the serialized string. */ string toJSON(in JSONValue* root) { - auto json = appender!string(); + auto json = appender!string(); - void toString(string str) { - json.put('"'); + void toString(string str) { + json.put('"'); - foreach (dchar c; str) { - switch(c) { - case '"': json.put("\\\""); break; - case '\\': json.put("\\\\"); break; - case '/': json.put("\\/"); break; - case '\b': json.put("\\b"); break; - case '\f': json.put("\\f"); break; - case '\n': json.put("\\n"); break; - case '\r': json.put("\\r"); break; - case '\t': json.put("\\t"); break; - default: - appendJSONChar(&json, c, - (string msg){throw new JSONException(msg);}); - } - } + foreach (dchar c; str) { + switch(c) { + case '"': json.put("\\\""); break; + case '\\': json.put("\\\\"); break; + case '/': json.put("\\/"); break; + case '\b': json.put("\\b"); break; + case '\f': json.put("\\f"); break; + case '\n': json.put("\\n"); break; + case '\r': json.put("\\r"); break; + case '\t': json.put("\\t"); break; + default: + appendJSONChar(&json, c, + (string msg){throw new JSONException(msg);}); + } + } - json.put('"'); - } + json.put('"'); + } - void toValue(in JSONValue* value) { - final switch(value.type) { - case JSON_TYPE.OBJECT: - json.put('{'); - bool first = true; - foreach(name, member; value.object) { - if(first) first = false; - else json.put(','); - toString(name); - json.put(':'); - toValue(&member); - } - json.put('}'); - break; + void toValue(in JSONValue* value) { + final switch(value.type) { + case JSON_TYPE.OBJECT: + json.put('{'); + bool first = true; + foreach(name, member; value.object) { + if(first) first = false; + else json.put(','); + toString(name); + json.put(':'); + toValue(&member); + } + json.put('}'); + break; - case JSON_TYPE.ARRAY: - json.put('['); - auto length = value.array.length; - foreach (i; 0 .. length) { - if(i) json.put(','); - toValue(&value.array[i]); - } - json.put(']'); - break; + case JSON_TYPE.ARRAY: + json.put('['); + auto length = value.array.length; + foreach (i; 0 .. length) { + if(i) json.put(','); + toValue(&value.array[i]); + } + json.put(']'); + break; - case JSON_TYPE.STRING: - toString(value.str); - break; + case JSON_TYPE.STRING: + toString(value.str); + break; - case JSON_TYPE.INTEGER: - json.put(to!string(value.integer)); - break; + case JSON_TYPE.INTEGER: + json.put(to!string(value.integer)); + break; - case JSON_TYPE.FLOAT: - json.put(to!string(value.floating)); - break; + case JSON_TYPE.FLOAT: + json.put(to!string(value.floating)); + break; - case JSON_TYPE.TRUE: - json.put("true"); - break; + case JSON_TYPE.TRUE: + json.put("true"); + break; - case JSON_TYPE.FALSE: - json.put("false"); - break; + case JSON_TYPE.FALSE: + json.put("false"); + break; - case JSON_TYPE.NULL: - json.put("null"); - break; - } - } + case JSON_TYPE.NULL: + json.put("null"); + break; + } + } - toValue(root); - return json.data; + toValue(root); + return json.data; } private void appendJSONChar(Appender!string* dst, dchar c, - scope void delegate(string) error) + scope void delegate(string) error) { if(iscntrl(c)) error("Illegal control character."); dst.put(c); -// int stride = UTFStride((&c)[0 .. 1], 0); -// if(stride == 1) { -// if(iscntrl(c)) error("Illegal control character."); -// dst.put(c); -// } -// else { -// char[6] utf = void; -// utf[0] = c; -// foreach(i; 1 .. stride) utf[i] = next; -// size_t index = 0; -// if(iscntrl(toUnicode(utf[0 .. stride], index))) -// error("Illegal control character"); -// dst.put(utf[0 .. stride]); -// } +// int stride = UTFStride((&c)[0 .. 1], 0); +// if(stride == 1) { +// if(iscntrl(c)) error("Illegal control character."); +// dst.put(c); +// } +// else { +// char[6] utf = void; +// utf[0] = c; +// foreach(i; 1 .. stride) utf[i] = next; +// size_t index = 0; +// if(iscntrl(toUnicode(utf[0 .. stride], index))) +// error("Illegal control character"); +// dst.put(utf[0 .. stride]); +// } } /** Exception thrown on JSON errors */ class JSONException : Exception { - this(string msg, int line = 0, int pos = 0) { - if(line) super(text(msg, " (Line ", line, ":", pos, ")")); - else super(msg); - } + this(string msg, int line = 0, int pos = 0) { + if(line) super(text(msg, " (Line ", line, ":", pos, ")")); + else super(msg); + } } version(unittest) import std.stdio; unittest { - // An overly simple test suite, if it can parse a serializated string and - // then use the resulting values tree to generate an identical - // serialization, both the decoder and encoder works. + // An overly simple test suite, if it can parse a serializated string and + // then use the resulting values tree to generate an identical + // serialization, both the decoder and encoder works. - immutable jsons = [ - `null`, - `true`, - `false`, - `0`, - `123`, - `-4321`, - `0.23`, - `-0.23`, - `""`, - `1.223e+24`, - `"hello\nworld"`, - `"\"\\\/\b\f\n\r\t"`, - `[]`, - `[12,"foo",true,false]`, - `{}`, - `{"a":1,"b":null}`, + immutable jsons = [ + `null`, + `true`, + `false`, + `0`, + `123`, + `-4321`, + `0.23`, + `-0.23`, + `""`, + `1.223e+24`, + `"hello\nworld"`, + `"\"\\\/\b\f\n\r\t"`, + `[]`, + `[12,"foo",true,false]`, + `{}`, + `{"a":1,"b":null}`, // Currently broken -// `{"hello":{"json":"is great","array":[12,null,{}]},"goodbye":[true,"or",false,["test",42,{"nested":{"a":23.54,"b":0.0012}}]]}` - ]; +// `{"hello":{"json":"is great","array":[12,null,{}]},"goodbye":[true,"or",false,["test",42,{"nested":{"a":23.54,"b":0.0012}}]]}` + ]; - JSONValue val; - string result; - foreach(json; jsons) { - try { - val = parseJSON(json); - result = toJSON(&val); - assert(result == json, text(result, " should be ", json)); - } - catch(JSONException e) { - writefln(text(json, "\n", e.toString())); - } - } + JSONValue val; + string result; + foreach(json; jsons) { + try { + val = parseJSON(json); + result = toJSON(&val); + assert(result == json, text(result, " should be ", json)); + } + catch(JSONException e) { + writefln(text(json, "\n", e.toString())); + } + } } diff --git a/std/loader.d b/std/loader.d index b8817ba4f..43c859ced 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. */ @@ -79,14 +79,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 @@ -107,7 +107,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 @@ -123,7 +123,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 @@ -240,20 +240,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].idup; } } @@ -309,8 +309,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) { @@ -449,9 +449,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); } /* ///////////////////////////////////////////////////////////////////////////// @@ -501,19 +501,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); } } @@ -524,22 +524,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() { @@ -558,17 +558,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); } } /// @} @@ -583,27 +583,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; } @@ -636,23 +636,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].idup; - } - else version (Posix) - { - return ExeModule_GetPath_(m_hModule); - } - else - static assert(0); + return szFileName[0 .. cch].idup; + } + else version (Posix) + { + return ExeModule_GetPath_(m_hModule); + } + else + static assert(0); } /// @} diff --git a/std/md5.d b/std/md5.d index 800c78b12..da2cbe8af 100644 --- a/std/md5.d +++ b/std/md5.d @@ -18,10 +18,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 */ /++++++++++++++++++++++++++++++++ @@ -41,7 +41,7 @@ private import std.c.string; void main(string[] args) { foreach (char[] arg; args) - MDFile(arg); + MDFile(arg); } /* Digests a file and prints the result. */ @@ -84,7 +84,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; import std.exception; @@ -175,8 +175,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 = [ @@ -189,30 +189,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. @@ -220,30 +220,30 @@ struct MD5_CTX */ static void FF(ref 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(ref 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(ref 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(ref 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; } /** @@ -251,7 +251,7 @@ struct MD5_CTX */ void start() { - this = MD5_CTX.init; + this = MD5_CTX.init; } /** MD5 block update operation. Continues an MD5 message-digest @@ -274,20 +274,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 @@ -325,30 +325,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); @@ -439,16 +439,16 @@ struct MD5_CTX */ private static void Encode (ubyte *output, const 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 @@ -456,20 +456,20 @@ struct MD5_CTX */ private static void Decode (uint *output, const 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); + } + } } } @@ -498,8 +498,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/openrj.d b/std/openrj.d index d6f2d6515..969e4792b 100644 --- a/std/openrj.d +++ b/std/openrj.d @@ -40,12 +40,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 */ /* ///////////////////////////////////////////////////////////////////////////// @@ -153,7 +153,7 @@ public enum ORJ_FLAG */ public string toString(ORJ_FLAG f) { - static const EnumString strings[] = + static const EnumString strings[] = [ { ORJ_FLAG.ORDER_FIELDS, "Arranges the fields in alphabetical order" } , { ORJ_FLAG.ELIDE_BLANK_RECORDS, "Causes blank records to be ignored" } @@ -181,7 +181,7 @@ public enum ORJRC */ public string toString(ORJRC f) { - static const EnumString strings[] = + static const EnumString strings[] = [ { ORJRC.SUCCESS, "Operation was successful" } , { ORJRC.CANNOT_OPEN_JAR_FILE, "The given file does not exist, or cannot be accessed" } @@ -190,8 +190,8 @@ public string 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); @@ -212,7 +212,7 @@ public enum ORJ_PARSE_ERROR */ public string toString(ORJ_PARSE_ERROR f) { - static const EnumString strings[] = + static 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" } @@ -694,7 +694,7 @@ private: foreach(string ln; lines) { // Always strip trailing space - auto line = stripr(ln); + auto line = stripr(ln); // Check that we don't start a continued line with a record separator if( bContinuing && @@ -784,7 +784,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/path.d b/std/path.d index 27c26270a..a8abd2bdb 100644 --- a/std/path.d +++ b/std/path.d @@ -9,13 +9,13 @@ * module first (i.e. $(D std.file.isDir())). * * Macros: - * WIKI = Phobos/StdPath + * WIKI = Phobos/StdPath * * Copyright: Copyright Digital Mars 2000 - 2009. * License: Boost License 1.0. * Authors: $(WEB digitalmars.com, Walter Bright), - * Grzegorz Adam Hankiewicz, Thomas Kühne, - * $(WEB erdani.org, Andrei Alexandrescu) + * Grzegorz Adam Hankiewicz, Thomas Kühne, + * $(WEB erdani.org, Andrei Alexandrescu) * * Copyright Digital Mars 2000 - 2009. * Distributed under the Boost Software License, Version 1.0. @@ -24,7 +24,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; import std.array, std.conv, std.file, std.process, std.string, std.traits; @@ -51,7 +51,7 @@ version(Windows) /** String used to separate lines, \r\n under Windows and \n * under Linux. */ immutable char[2] linesep = "\r\n"; /// String used to separate lines. - immutable char[1] curdir = "."; /// String representing the current directory. + immutable char[1] curdir = "."; /// String representing the current directory. immutable char[2] pardir = ".."; /// String representing the parent directory. } version(Posix) @@ -68,18 +68,18 @@ version(Posix) /** String used to separate lines, \r\n under Windows and \n * under Linux. */ immutable char[1] linesep = "\n"; - immutable char[1] curdir = "."; /// String representing the current directory. + immutable char[1] curdir = "."; /// String representing the current directory. immutable 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; @@ -148,30 +148,30 @@ unittest string result; version (Windows) - 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 (Windows) - 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 (Windows) - 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 (Windows) - 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); @@ -248,9 +248,9 @@ unittest result = getName("d:\\path.two\\bar"); version (Windows) - i = cmp(result, ""); + i = cmp(result, ""); version (Posix) - i = cmp(result, "d:\\path"); + i = cmp(result, "d:\\path"); assert(i == 0); } @@ -326,22 +326,22 @@ unittest string result; version (Windows) - result = basename("d:\\path\\foo.bat"); + result = basename("d:\\path\\foo.bat"); version (Posix) - result = basename("/path/foo.bat"); + result = basename("/path/foo.bat"); //printf("result = '%.*s'\n", result); assert(result == "foo.bat"); version (Windows) - result = basename("a\\b"); + result = basename("a\\b"); version (Posix) - result = basename("a/b"); + result = basename("a/b"); assert(result == "b"); version (Windows) - result = basename("a\\b.cde", ".cde"); + result = basename("a\\b.cde", ".cde"); version (Posix) - result = basename("a/b.cde", ".cde"); + result = basename("a/b.cde", ".cde"); assert(result == "b"); version (Windows) @@ -649,11 +649,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; } @@ -689,15 +689,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 .. $ - existing.length] ~ ext; + filename = filename[0 .. $ - existing.length] ~ ext; } return filename; } @@ -752,14 +752,14 @@ unittest version (Windows) { - assert(!isabs(r"relative\path")); - assert(isabs(r"\relative\path")); - assert(isabs(r"d:\absolute")); + assert(!isabs(r"relative\path")); + assert(isabs(r"\relative\path")); + assert(isabs(r"d:\absolute")); } version (Posix) { - assert(isabs("/home/user")); - assert(!isabs("foo")); + assert(isabs("/home/user")); + assert(!isabs("foo")); } } @@ -903,38 +903,38 @@ unittest p = join("foo", "bar"); version (Windows) - 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 (Windows) - { 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 (Windows) - { 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 (Windows) - { 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); @@ -1079,91 +1079,91 @@ bool fncharmatch(dchar c1, dchar c2) bool fnmatch(in char[] filename, in char[] pattern) in { - // Verify that pattern[] is valid - bool inbracket = false; - foreach (i; 0 .. pattern.length) - { - switch (pattern[i]) - { - case '[': - assert(!inbracket); - inbracket = true; - break; + // Verify that pattern[] is valid + bool inbracket = false; + foreach (i; 0 .. pattern.length) + { + 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 { - char nc; + char nc; int not; - int anymatch; - int ni; // ni == name index - foreach (pi; 0 .. pattern.length) // pi == pattern index - { - char pc = pattern[pi]; // pc == pattern character - switch (pc) - { - case '*': - if (pi + 1 == pattern.length) - return true; - foreach (j; ni .. filename.length) - { - if (fnmatch(filename[j .. filename.length], + int anymatch; + int ni; // ni == name index + foreach (pi; 0 .. pattern.length) // pi == pattern index + { + char pc = pattern[pi]; // pc == pattern character + switch (pc) + { + case '*': + if (pi + 1 == pattern.length) + return true; + foreach (j; ni .. filename.length) + { + if (fnmatch(filename[j .. filename.length], pattern[pi + 1 .. pattern.length])) - return true; - } - return false; + return true; + } + return false; - case '?': - if (ni == filename.length) + case '?': + if (ni == filename.length) return false; - ni++; - break; + ni++; + break; - case '[': - if (ni == filename.length) - return false; - 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)) - return false; - break; + case '[': + if (ni == filename.length) + return false; + 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)) + return false; + break; - default: - if (ni == filename.length) - return false; - nc = filename[ni]; - if (!fncharmatch(pc, nc)) - return false; - ni++; - break; - } - } - return ni >= filename.length; + default: + if (ni == filename.length) + return false; + nc = filename[ni]; + if (!fncharmatch(pc, nc)) + return false; + ni++; + break; + } + } + return ni >= filename.length; } unittest @@ -1171,9 +1171,9 @@ unittest debug(path) printf("path.fnmatch.unittest\n"); version (Windows) - 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", "*.*")); @@ -1285,7 +1285,7 @@ unittest version (Posix) { - // Retrieve the current home variable. + // Retrieve the current home variable. auto c_home = std.process.getenv("HOME"); // Testing when there is no environment variable. @@ -1360,14 +1360,14 @@ private string combineCPathWithDPath(char* c_path, string path, size_t 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].idup; // Do we append something from path? if (char_pos < path.length) - cp ~= path[char_pos .. $]; + cp ~= path[char_pos .. $]; return cp; } @@ -1388,7 +1388,7 @@ private string expandFromDatabase(string path) if (last_char == -1) { username = path[1 .. $] ~ '\0'; - last_char = username.length + 1; + last_char = username.length + 1; } else { @@ -1403,29 +1403,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; - setErrno(0); - if (getpwnam_r(cast(char*) username.ptr, &result, cast(char*) 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; + setErrno(0); + if (getpwnam_r(cast(char*) username.ptr, &result, cast(char*) 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 (errno != ERANGE) - goto Lerror; + if (errno != 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); @@ -1437,7 +1437,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); onOutOfMemoryError(); return null; } diff --git a/std/perf.d b/std/perf.d index ca4b276fd..4864f9021 100644 --- a/std/perf.d +++ b/std/perf.d @@ -1,12 +1,12 @@ // Written in the D programming language /* ///////////////////////////////////////////////////////////////////////////// - * File: perf.d + * File: perf.d * - * Created 19th March 2004 - * Updated: 18th July 2004 + * Created 19th March 2004 + * Updated: 18th July 2004 * - * www: http://www.digitalmars.com/ + * www: http://www.digitalmars.com/ * * Copyright (C) 2004 by Digital Mars * All Rights Reserved @@ -18,10 +18,10 @@ * ////////////////////////////////////////////////////////////////////////// */ -/** +/** * Platform-independent performance measurement and timing classes. * - * $(D_PARAM PerformanceCounter) is the main platform-independent timer class provided, + * $(D_PARAM PerformanceCounter) is the main platform-independent timer class provided, * covering the most typical use case, measuring elapsed wall-clock time. * * The module also provides several Windows-specific timers that can @@ -40,10 +40,10 @@ writefln("Time elapsed: %s msec", elapsedMsec); * In particular note that $(D_PARAM stop()) must be called * before querying the elapsed time. * - * These classes were ported to D from the + * These classes were ported to D from the * $(LINK2 http://stlsoft.org/,STLSoft C++ libraries), - * which were documented in the article - * "$(LINK2 http://www.windevnet.com/documents/win0305a/, + * which were documented in the article + * "$(LINK2 http://www.windevnet.com/documents/win0305a/, * Win32 Performance Measurement Options)", * May 2003 issue of Windows Develper Network. * @@ -51,7 +51,7 @@ writefln("Time elapsed: %s msec", elapsedMsec); * Matthew Wilson * * Macros: - * WIKI=Phobos/StdPerf + * WIKI=Phobos/StdPerf */ module std.perf; @@ -69,712 +69,712 @@ version(Windows) /* ////////////////////////////////////////////////////////////////////////// */ /** A performance counter that uses the most accurate measurement APIs available on the host machine - - On Linux, the implementation uses $(D_PARAM gettimeofday()). - For Windows, $(D_PARAM QueryPerformanceCounter()) is used if available, - $(D_PARAM GetTickCount()) otherwise. + + On Linux, the implementation uses $(D_PARAM gettimeofday()). + For Windows, $(D_PARAM QueryPerformanceCounter()) is used if available, + $(D_PARAM GetTickCount()) otherwise. */ class PerformanceCounter { private: - alias long epoch_type; + alias long epoch_type; public: - /// The type of the interval measurement (generally a 64-bit signed integer) - alias long interval_t; + /// The type of the interval measurement (generally a 64-bit signed integer) + alias long interval_t; deprecated alias interval_t interval_type; private: - /** Class constructor - */ - shared static this() - { - // Detects availability of the high performance hardware counter, and if - // not available adjusts + /** Class constructor + */ + shared static this() + { + // Detects availability of the high performance hardware counter, and if + // not available adjusts - interval_t freq; - if (QueryPerformanceFrequency(&freq)) - { - sm_freq = freq; - sm_fn = &_qpc; - } - else - { - sm_freq = 1000; - sm_fn = &_qtc; - } - } + interval_t freq; + if (QueryPerformanceFrequency(&freq)) + { + sm_freq = freq; + sm_fn = &_qpc; + } + else + { + sm_freq = 1000; + sm_fn = &_qtc; + } + } public: - /** Starts measurement - - Begins a measurement period - */ - void start() - { - sm_fn(m_start); - } + /** Starts measurement - /** Ends measurement - - Marks the end of a measurement period. - This must be called before querying the elapsed time with - $(D_PARAM period_count), $(D_PARAM seconds), - $(D_PARAM milliseconds), or $(D_PARAM microseconds). + Begins a measurement period + */ + void start() + { + sm_fn(m_start); + } - The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). - Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent - $(D_PARAM stop()). - */ - void stop() - { - sm_fn(m_end); - } + /** Ends measurement + + Marks the end of a measurement period. + This must be called before querying the elapsed time with + $(D_PARAM period_count), $(D_PARAM seconds), + $(D_PARAM milliseconds), or $(D_PARAM microseconds). + + The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). + Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent + $(D_PARAM stop()). + */ + void stop() + { + sm_fn(m_end); + } public: - /** The elapsed count in the measurement period - - This represents the extent, in machine-specific increments, of the measurement period - */ - interval_t periodCount() const - { - return m_end - m_start; - } + /** The elapsed count in the measurement period - /** The number of whole seconds in the measurement period - - This represents the extent, in whole seconds, of the measurement period - */ - interval_t seconds() const - { - return periodCount() / sm_freq; - } + This represents the extent, in machine-specific increments, of the measurement period + */ + interval_t periodCount() const + { + return m_end - m_start; + } - /** The number of whole milliseconds in the measurement period - - This represents the extent, in whole milliseconds, of the measurement period - */ - interval_t milliseconds() const - { - interval_t result; - interval_t count = periodCount(); + /** The number of whole seconds in the measurement period - if(count < 0x20C49BA5E353F7L) - { - result = (count * 1000) / sm_freq; - } - else - { - result = (count / sm_freq) * 1000; - } + This represents the extent, in whole seconds, of the measurement period + */ + interval_t seconds() const + { + return periodCount() / sm_freq; + } - return result; - } + /** The number of whole milliseconds in the measurement period - /** The number of whole microseconds in the measurement period - - This represents the extent, in whole microseconds, of the measurement period - */ - interval_t microseconds() const - { - interval_t result; - interval_t count = periodCount(); + This represents the extent, in whole milliseconds, of the measurement period + */ + interval_t milliseconds() const + { + interval_t result; + interval_t count = periodCount(); - if(count < 0x8637BD05AF6L) - { - result = (count * 1000000) / sm_freq; - } - else - { - result = (count / sm_freq) * 1000000; - } + if(count < 0x20C49BA5E353F7L) + { + result = (count * 1000) / sm_freq; + } + else + { + result = (count / sm_freq) * 1000; + } - return result; - } + return result; + } + + /** The number of whole microseconds in the measurement period + + This represents the extent, in whole microseconds, of the measurement period + */ + interval_t microseconds() const + { + interval_t result; + interval_t count = periodCount(); + + if(count < 0x8637BD05AF6L) + { + result = (count * 1000000) / sm_freq; + } + else + { + result = (count / sm_freq) * 1000000; + } + + return result; + } 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(); + } private: - epoch_type m_start; // start of measurement period - epoch_type m_end; // End of measurement period - __gshared const interval_t sm_freq; // Frequency - __gshared const measure_func sm_fn; // Measurement function + epoch_type m_start; // start of measurement period + epoch_type m_end; // End of measurement period + __gshared const interval_t sm_freq; // Frequency + __gshared const 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(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us1 = counter.microseconds(); - counter_type.interval_t ms1 = counter.milliseconds(); - counter_type.interval_t s1 = counter.seconds(); + counter_type.interval_t us1 = counter.microseconds(); + counter_type.interval_t ms1 = counter.milliseconds(); + counter_type.interval_t s1 = counter.seconds(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us2 = counter.microseconds(); - counter_type.interval_t ms2 = counter.milliseconds(); - counter_type.interval_t s2 = counter.seconds(); + counter_type.interval_t us2 = counter.microseconds(); + counter_type.interval_t ms2 = counter.milliseconds(); + counter_type.interval_t s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ /** A low-cost, low-resolution performance counter - - This class provides low-resolution, but low-latency, performance monitoring. - This class is available only on Windows, but - is guaranteed to be meaningful on all Windows operating systems. + This class provides low-resolution, but low-latency, performance monitoring. + + This class is available only on Windows, but + is guaranteed to be meaningful on all Windows operating systems. */ class TickCounter { private: - alias long epoch_type; + alias long epoch_type; public: - /** The interval type + /** The interval type - The type of the interval measurement (generally a 64-bit signed integer) - */ - alias long interval_t; + The type of the interval measurement (generally a 64-bit signed integer) + */ + alias long interval_t; deprecated alias interval_t interval_type; public: public: - /** Starts measurement + /** Starts measurement - Begins a measurement period - */ - void start() - { - m_start = GetTickCount(); - } + Begins a measurement period + */ + void start() + { + m_start = GetTickCount(); + } - /** Ends measurement - - Marks the end of a measurement period. - This must be called before querying the elapsed time with - $(D_PARAM period_count), $(D_PARAM seconds), - $(D_PARAM milliseconds), or $(D_PARAM microseconds). + /** Ends measurement - The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). - Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent - $(D_PARAM stop()). - */ - void stop() - { - m_end = GetTickCount(); - } + Marks the end of a measurement period. + This must be called before querying the elapsed time with + $(D_PARAM period_count), $(D_PARAM seconds), + $(D_PARAM milliseconds), or $(D_PARAM microseconds). + + The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). + Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent + $(D_PARAM stop()). + */ + void stop() + { + m_end = GetTickCount(); + } public: - /** - The elapsed count in the measurement period - - This represents the extent, in machine-specific increments, of the measurement period - */ - interval_t periodCount() const - { - return m_end - m_start; - } + /** + The elapsed count in the measurement period - /** The number of whole seconds in the measurement period + This represents the extent, in machine-specific increments, of the measurement period + */ + interval_t periodCount() const + { + return m_end - m_start; + } - This represents the extent, in whole seconds, of the measurement period - */ - interval_t seconds() const - { - return periodCount() / 1000; - } + /** The number of whole seconds in the measurement period - /** The number of whole milliseconds in the measurement period + This represents the extent, in whole seconds, of the measurement period + */ + interval_t seconds() const + { + return periodCount() / 1000; + } - This represents the extent, in whole milliseconds, of the measurement period - */ - interval_t milliseconds() const - { - return periodCount(); - } + /** The number of whole milliseconds in the measurement period - /** The number of whole microseconds in the measurement period + This represents the extent, in whole milliseconds, of the measurement period + */ + interval_t milliseconds() const + { + return periodCount(); + } - This represents the extent, in whole microseconds, of the measurement period - */ - interval_t microseconds() const - { - return periodCount() * 1000; - } + /** The number of whole microseconds in the measurement period + + This represents the extent, in whole microseconds, of the measurement period + */ + interval_t microseconds() const + { + return periodCount() * 1000; + } 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(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us1 = counter.microseconds(); - counter_type.interval_t ms1 = counter.milliseconds(); - counter_type.interval_t s1 = counter.seconds(); + counter_type.interval_t us1 = counter.microseconds(); + counter_type.interval_t ms1 = counter.milliseconds(); + counter_type.interval_t s1 = counter.seconds(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us2 = counter.microseconds(); - counter_type.interval_t ms2 = counter.milliseconds(); - counter_type.interval_t s2 = counter.seconds(); + counter_type.interval_t us2 = counter.microseconds(); + counter_type.interval_t ms2 = counter.milliseconds(); + counter_type.interval_t s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ /** A performance counter that provides thread-specific performance timings - - 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. - This class is available only on Windows. + 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. + + This class is available only on Windows. */ class ThreadTimesCounter { private: - alias long epoch_type; + alias long epoch_type; public: - /** The interval type - - The type of the interval measurement (generally a 64-bit signed integer) - */ - alias long interval_t; + /** The interval type + + The type of the interval measurement (generally a 64-bit signed integer) + */ + alias long interval_t; deprecated alias interval_t interval_type; public: - /** 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(); - } + /** 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(); + } public: - /** Starts measurement - - Begins a measurement period - */ - void start() - { - FILETIME creationTime; - FILETIME exitTime; + /** Starts measurement - GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); - } + Begins a measurement period + */ + void start() + { + FILETIME creationTime; + FILETIME exitTime; - /** Ends measurement - - Marks the end of a measurement period. - This must be called before querying the elapsed time with - $(D_PARAM period_count), $(D_PARAM seconds), - $(D_PARAM milliseconds), or $(D_PARAM microseconds). + GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); + } - The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). - Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent - $(D_PARAM stop()). - */ - void stop() - { - FILETIME creationTime; - FILETIME exitTime; + /** Ends measurement - GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); - } + Marks the end of a measurement period. + This must be called before querying the elapsed time with + $(D_PARAM period_count), $(D_PARAM seconds), + $(D_PARAM milliseconds), or $(D_PARAM microseconds). + + The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). + Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent + $(D_PARAM stop()). + */ + void stop() + { + FILETIME creationTime; + FILETIME exitTime; + + GetThreadTimes(m_thread, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); + } public: - /** 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_t kernelPeriodCount() const - { - return m_kernelEnd - m_kernelStart; - } - /** 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_t kernelSeconds() const - { - return kernelPeriodCount() / 10000000; - } - /** 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_t kernelMilliseconds() const - { - return kernelPeriodCount() / 10000; - } - /** 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_t kernelMicroseconds() const - { - return kernelPeriodCount() / 10; - } + /** 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_t kernelPeriodCount() const + { + return m_kernelEnd - m_kernelStart; + } + /** 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_t kernelSeconds() const + { + return kernelPeriodCount() / 10000000; + } + /** 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_t kernelMilliseconds() const + { + return kernelPeriodCount() / 10000; + } + /** 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_t kernelMicroseconds() const + { + return kernelPeriodCount() / 10; + } - /** 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_t userPeriodCount() const - { - return m_userEnd - m_userStart; - } - /** 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_t userSeconds() const - { - return userPeriodCount() / 10000000; - } - /** 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_t userMilliseconds() const - { - return userPeriodCount() / 10000; - } - /** 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_t userMicroseconds() const - { - return userPeriodCount() / 10; - } + /** 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_t userPeriodCount() const + { + return m_userEnd - m_userStart; + } + /** 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_t userSeconds() const + { + return userPeriodCount() / 10000000; + } + /** 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_t userMilliseconds() const + { + return userPeriodCount() / 10000; + } + /** 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_t userMicroseconds() const + { + return userPeriodCount() / 10; + } - /** The elapsed count in the measurement period - - This represents the extent, in machine-specific increments, of the measurement period - */ - interval_t periodCount() const - { - return kernelPeriodCount() + userPeriodCount(); - } + /** The elapsed count in the measurement period - /** The number of whole seconds in the measurement period - - This represents the extent, in whole seconds, of the measurement period - */ - interval_t seconds() const - { - return periodCount() / 10000000; - } + This represents the extent, in machine-specific increments, of the measurement period + */ + interval_t periodCount() const + { + return kernelPeriodCount() + userPeriodCount(); + } - /** The number of whole milliseconds in the measurement period - - This represents the extent, in whole milliseconds, of the measurement period - */ - interval_t milliseconds() const - { - return periodCount() / 10000; - } + /** The number of whole seconds in the measurement period - /** The number of whole microseconds in the measurement period - - This represents the extent, in whole microseconds, of the measurement period - */ - interval_t microseconds() const - { - return periodCount() / 10; - } + This represents the extent, in whole seconds, of the measurement period + */ + interval_t seconds() const + { + return periodCount() / 10000000; + } + + /** The number of whole milliseconds in the measurement period + + This represents the extent, in whole milliseconds, of the measurement period + */ + interval_t milliseconds() const + { + return periodCount() / 10000; + } + + /** The number of whole microseconds in the measurement period + + This represents the extent, in whole microseconds, of the measurement period + */ + interval_t microseconds() const + { + return periodCount() / 10; + } 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(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us1 = counter.microseconds(); - counter_type.interval_t ms1 = counter.milliseconds(); - counter_type.interval_t s1 = counter.seconds(); + counter_type.interval_t us1 = counter.microseconds(); + counter_type.interval_t ms1 = counter.milliseconds(); + counter_type.interval_t s1 = counter.seconds(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us2 = counter.microseconds(); - counter_type.interval_t ms2 = counter.milliseconds(); - counter_type.interval_t s2 = counter.seconds(); + counter_type.interval_t us2 = counter.microseconds(); + counter_type.interval_t ms2 = counter.milliseconds(); + counter_type.interval_t s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ /** A performance counter that provides process-specific performance timings - - 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. - This class is available only on Windows. + 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. + + This class is available only on Windows. */ class ProcessTimesCounter { private: - alias long epoch_type; + alias long epoch_type; public: - /** The interval type - - The type of the interval measurement (generally a 64-bit signed integer) - */ - alias long interval_t; + /** The interval type + + The type of the interval measurement (generally a 64-bit signed integer) + */ + alias long interval_t; deprecated alias interval_t interval_type; private: - /** Class constructor - - */ - shared static this() - { - sm_process = GetCurrentProcess(); - } + /** Class constructor + + */ + shared static this() + { + sm_process = GetCurrentProcess(); + } public: - /** Starts measurement - - Begins a measurement period - */ - void start() - { - FILETIME creationTime; - FILETIME exitTime; + /** Starts measurement - GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); - } + Begins a measurement period + */ + void start() + { + FILETIME creationTime; + FILETIME exitTime; - /** Ends measurement - - Marks the end of a measurement period. - This must be called before querying the elapsed time with - $(D_PARAM period_count), $(D_PARAM seconds), - $(D_PARAM milliseconds), or $(D_PARAM microseconds). + GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelStart, cast(FILETIME*)&m_userStart); + } - The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). - Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent - $(D_PARAM stop()). - */ - void stop() - { - FILETIME creationTime; - FILETIME exitTime; + /** Ends measurement - GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); - } + Marks the end of a measurement period. + This must be called before querying the elapsed time with + $(D_PARAM period_count), $(D_PARAM seconds), + $(D_PARAM milliseconds), or $(D_PARAM microseconds). + + The $(D_PARAM stop()) method may be called multiple times without an intervening $(D_PARAM start()). + Elapsed time is always measured from most recent $(D_PARAM start()) to the most recent + $(D_PARAM stop()). + */ + void stop() + { + FILETIME creationTime; + FILETIME exitTime; + + GetProcessTimes(sm_process, &creationTime, &exitTime, cast(FILETIME*)&m_kernelEnd, cast(FILETIME*)&m_userEnd); + } public: - /** 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_t kernelPeriodCount() const - { - return m_kernelEnd - m_kernelStart; - } - /** 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_t kernelSeconds() const - { - return kernelPeriodCount() / 10000000; - } - /** 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_t kernelMilliseconds() const - { - return kernelPeriodCount() / 10000; - } - /** 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_t kernelMicroseconds() const - { - return kernelPeriodCount() / 10; - } + /** 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_t kernelPeriodCount() const + { + return m_kernelEnd - m_kernelStart; + } + /** 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_t kernelSeconds() const + { + return kernelPeriodCount() / 10000000; + } + /** 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_t kernelMilliseconds() const + { + return kernelPeriodCount() / 10000; + } + /** 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_t kernelMicroseconds() const + { + return kernelPeriodCount() / 10; + } - /** 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_t userPeriodCount() const - { - return m_userEnd - m_userStart; - } - /** 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_t userSeconds() const - { - return userPeriodCount() / 10000000; - } - /** 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_t userMilliseconds() const - { - return userPeriodCount() / 10000; - } - /** 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_t userMicroseconds() const - { - return userPeriodCount() / 10; - } + /** The elapsed count in the measurement period for user mode activity - /** The elapsed count in the measurement period - - This represents the extent, in machine-specific increments, of the measurement period - */ - interval_t periodCount() const - { - return kernelPeriodCount() + userPeriodCount(); - } + This represents the extent, in machine-specific increments, of the measurement period for user mode activity + */ + interval_t userPeriodCount() const + { + return m_userEnd - m_userStart; + } + /** The number of whole seconds in the measurement period for user mode activity - /** The number of whole seconds in the measurement period - - This represents the extent, in whole seconds, of the measurement period - */ - interval_t seconds() const - { - return periodCount() / 10000000; - } + This represents the extent, in whole seconds, of the measurement period for user mode activity + */ + interval_t userSeconds() const + { + return userPeriodCount() / 10000000; + } + /** The number of whole milliseconds in the measurement period for user mode activity - /** The number of whole milliseconds in the measurement period - - This represents the extent, in whole milliseconds, of the measurement period - */ - interval_t milliseconds() const - { - return periodCount() / 10000; - } + This represents the extent, in whole milliseconds, of the measurement period for user mode activity + */ + interval_t userMilliseconds() const + { + return userPeriodCount() / 10000; + } + /** The number of whole microseconds in the measurement period for user mode activity - /** The number of whole microseconds in the measurement period - - This represents the extent, in whole microseconds, of the measurement period - */ - interval_t microseconds() const - { - return periodCount() / 10; - } + This represents the extent, in whole microseconds, of the measurement period for user mode activity + */ + interval_t userMicroseconds() const + { + return userPeriodCount() / 10; + } + + /** The elapsed count in the measurement period + + This represents the extent, in machine-specific increments, of the measurement period + */ + interval_t periodCount() const + { + return kernelPeriodCount() + userPeriodCount(); + } + + /** The number of whole seconds in the measurement period + + This represents the extent, in whole seconds, of the measurement period + */ + interval_t seconds() const + { + return periodCount() / 10000000; + } + + /** The number of whole milliseconds in the measurement period + + This represents the extent, in whole milliseconds, of the measurement period + */ + interval_t milliseconds() const + { + return periodCount() / 10000; + } + + /** The number of whole microseconds in the measurement period + + This represents the extent, in whole microseconds, of the measurement period + */ + interval_t microseconds() const + { + return periodCount() / 10; + } private: - epoch_type m_kernelStart; - epoch_type m_kernelEnd; - epoch_type m_userStart; - epoch_type m_userEnd; - __gshared HANDLE sm_process; + epoch_type m_kernelStart; + epoch_type m_kernelEnd; + epoch_type m_userStart; + epoch_type m_userEnd; + __gshared 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(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us1 = counter.microseconds(); - counter_type.interval_t ms1 = counter.milliseconds(); - counter_type.interval_t s1 = counter.seconds(); + counter_type.interval_t us1 = counter.microseconds(); + counter_type.interval_t ms1 = counter.milliseconds(); + counter_type.interval_t s1 = counter.seconds(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us2 = counter.microseconds(); - counter_type.interval_t ms2 = counter.milliseconds(); - counter_type.interval_t s2 = counter.seconds(); + counter_type.interval_t us2 = counter.microseconds(); + counter_type.interval_t ms2 = counter.milliseconds(); + counter_type.interval_t s2 = counter.seconds(); - assert(us2 >= us1); - assert(ms2 >= ms1); - assert(s2 >= s1); + assert(us2 >= us1); + assert(ms2 >= ms1); + assert(s2 >= s1); } /* ////////////////////////////////////////////////////////////////////////// */ @@ -783,107 +783,107 @@ else 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); } /* ////////////////////////////////////////////////////////////////////////// */ class PerformanceCounter { - // documentation is in the Windows version of the class above + // documentation is in the Windows version of the class above private: - alias timeval epoch_type; + alias timeval epoch_type; public: - alias long interval_t; + alias long interval_t; public: - void start() - { - timezone tz; + void start() + { + timezone tz; - gettimeofday(&m_start, &tz); - } + gettimeofday(&m_start, &tz); + } - void stop() - { - timezone tz; + void stop() + { + timezone tz; - gettimeofday(&m_end, &tz); - } + gettimeofday(&m_end, &tz); + } public: - interval_t periodCount() const - { - return microseconds; - } + interval_t periodCount() const + { + return microseconds; + } - interval_t seconds() const - { - interval_t start = cast(interval_t)m_start.tv_sec + cast(interval_t)m_start.tv_usec / (1000 * 1000); - interval_t end = cast(interval_t)m_end.tv_sec + cast(interval_t)m_end.tv_usec / (1000 * 1000); + interval_t seconds() const + { + interval_t start = cast(interval_t)m_start.tv_sec + cast(interval_t)m_start.tv_usec / (1000 * 1000); + interval_t end = cast(interval_t)m_end.tv_sec + cast(interval_t)m_end.tv_usec / (1000 * 1000); - return end - start; - } + return end - start; + } - interval_t milliseconds() const - { - interval_t start = cast(interval_t)m_start.tv_sec * 1000 + cast(interval_t)m_start.tv_usec / 1000; - interval_t end = cast(interval_t)m_end.tv_sec * 1000 + cast(interval_t)m_end.tv_usec / 1000; + interval_t milliseconds() const + { + interval_t start = cast(interval_t)m_start.tv_sec * 1000 + cast(interval_t)m_start.tv_usec / 1000; + interval_t end = cast(interval_t)m_end.tv_sec * 1000 + cast(interval_t)m_end.tv_usec / 1000; - return end - start; - } + return end - start; + } - interval_t microseconds() const - { - interval_t start = cast(interval_t)m_start.tv_sec * 1000 * 1000 + cast(interval_t)m_start.tv_usec; - interval_t end = cast(interval_t)m_end.tv_sec * 1000 * 1000 + cast(interval_t)m_end.tv_usec; + interval_t microseconds() const + { + interval_t start = cast(interval_t)m_start.tv_sec * 1000 * 1000 + cast(interval_t)m_start.tv_usec; + interval_t end = cast(interval_t)m_end.tv_sec * 1000 * 1000 + cast(interval_t)m_end.tv_usec; - return end - start; - } + return end - start; + } 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(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + counter.start(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us1 = counter.microseconds(); - counter_type.interval_t ms1 = counter.milliseconds(); - counter_type.interval_t s1 = counter.seconds(); + counter_type.interval_t us1 = counter.microseconds(); + counter_type.interval_t ms1 = counter.milliseconds(); + counter_type.interval_t s1 = counter.seconds(); - for(int i = 0; i < 10000000; ++i) - { } - counter.stop(); + for(int i = 0; i < 10000000; ++i) + { } + counter.stop(); - counter_type.interval_t us2 = counter.microseconds(); - counter_type.interval_t ms2 = counter.milliseconds(); - counter_type.interval_t s2 = counter.seconds(); + counter_type.interval_t us2 = counter.microseconds(); + counter_type.interval_t ms2 = counter.milliseconds(); + counter_type.interval_t 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/process.d b/std/process.d index a4646c05b..5d393cee0 100644 --- a/std/process.d +++ b/std/process.d @@ -618,7 +618,7 @@ public: immutable varDef = to!string(environ[i]); immutable eq = varDef.indexOf('='); assert (eq >= 0); - + immutable name = varDef[0 .. eq]; immutable value = varDef[eq+1 .. $]; diff --git a/std/random.d b/std/random.d index d172c6553..fbc20a8af 100644 --- a/std/random.d +++ b/std/random.d @@ -652,24 +652,24 @@ if (is(CommonType!(T1, UniformRandomNumberGenerator) == void) && alias Unqual!(CommonType!(T1, T2)) NumberType; NumberType _a, _b; static if (boundaries[0] == '(') - { + { static if (isIntegral!(NumberType) || is(Unqual!NumberType : dchar)) - { + { _a = a; - _a++; + _a++; } - else { + else { _a = nextafter(a, a.infinity); - } + } } - else - { + else + { _a = a; - } + } static if (boundaries[1] == ')') static if (isIntegral!(NumberType) || is(Unqual!NumberType : dchar)) { - _b = b; + _b = b; static if (_b.min == 0) { if (b == 0) @@ -680,7 +680,7 @@ if (is(CommonType!(T1, UniformRandomNumberGenerator) == void) && _b++; } } - _b--; + _b--; } else { @@ -750,18 +750,18 @@ unittest //writeln(x); } - foreach (i; 0 .. 20) + foreach (i; 0 .. 20) { auto x = uniform('a', 'z', gen); assert('a' <= x && x < 'z'); } - foreach(i; 0 .. 20) { - immutable ubyte a = 0; - immutable ubyte b = 15; - auto x = uniform(a, b, gen); - assert(a <= x && x < b); - } + foreach(i; 0 .. 20) { + immutable ubyte a = 0; + immutable ubyte b = 15; + auto x = uniform(a, b, gen); + assert(a <= x && x < b); + } } unittest diff --git a/std/socket.d b/std/socket.d index 34b1155c2..eb526fad7 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; @@ -46,25 +46,25 @@ version(unittest) version(Posix) { - version = BsdSockets; + version = BsdSockets; } version(Win32) { - pragma (lib, "ws2_32.lib"); - pragma (lib, "wsock32.lib"); + pragma (lib, "ws2_32.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) { @@ -112,91 +112,91 @@ else version(BsdSockets) } 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; - const(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; + const(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 + { + 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 = cast(string) (msg ~ ": " ~ cs[0 .. len]); - } - } + if(cs[len - 1] == '\n') + len--; + if(cs[len - 1] == '\r') + len--; + msg = cast(string) (msg ~ ": " ~ cs[0 .. len]); + } + } - super(msg); - } + super(msg); + } } shared 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(); + } } /** @@ -204,12 +204,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 } @@ -218,11 +218,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 } @@ -231,15 +231,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 } @@ -248,61 +248,61 @@ 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 = to!string(proto.p_name).idup; + void populate(protoent* proto) + { + type = cast(ProtocolType)proto.p_proto; + name = to!string(proto.p_name).idup; - 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++) - { + if(i) + { + aliases = new string[i]; + for(i = 0; i != aliases.length; i++) + { aliases[i] = to!string(proto.p_aliases[i]).idup; - } - } - else - { - aliases = null; - } - } + } + } + 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; + } } @@ -311,19 +311,19 @@ unittest Protocol proto = new Protocol; version (Windows) { - // These fail, don't know why - pragma(msg, " --- std.socket(" ~ __LINE__.stringof ~ ") broken test ---"); + // These fail, don't know why + pragma(msg, " --- std.socket(" ~ __LINE__.stringof ~ ") broken test ---"); } else { - 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); - // } - assert(proto.name == "tcp"); - assert(proto.aliases.length == 1 && proto.aliases[0] == "TCP"); + 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); + // } + assert(proto.name == "tcp"); + assert(proto.aliases.length == 1 && proto.aliases[0] == "TCP"); } } @@ -333,118 +333,118 @@ 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 = to!string(serv.s_name); - port = ntohs(cast(ushort)serv.s_port); - protocolName = to!string(serv.s_proto); + void populate(servent* serv) + { + name = to!string(serv.s_name); + port = ntohs(cast(ushort)serv.s_port); + protocolName = to!string(serv.s_proto); - 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] = to!string(serv.s_aliases[i]).idup; - } - } - 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" + 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); - // } - // For reasons unknown this is loc-srv on Wine and epmap on Windows + // foreach(string s; serv.aliases) + // { + // printf("\tAlias: %.*s\n", s); + // } + // For reasons unknown this is loc-srv on Wine and epmap on Windows assert(serv.name == "loc-srv" || serv.name == "epmap", serv.name); assert(serv.port == 135); assert(serv.protocolName == "tcp"); - // This assert used to pass, don't know why it fails now + // This assert used to pass, don't know why it fails now //assert(serv.aliases.length == 1 && serv.aliases[0] == "epmap"); - } - else - { - printf("No service for epmap.\n"); - } + } + else + { + printf("No service for epmap.\n"); + } } @@ -453,14 +453,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); + } } /** @@ -468,141 +468,141 @@ 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 = to!string(he.h_name).idup; + name = to!string(he.h_name).idup; - 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] = to!string(he.h_aliases[i]).idup; - } - } - 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; - if (!ih.getHostByName("www.digitalmars.com")) - return; // don't fail if not connected to internet - //printf("addrList.length = %d\n", ih.addrList.length); - assert(ih.addrList.length); - InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY); + InternetHost ih = new InternetHost; + if (!ih.getHostByName("www.digitalmars.com")) + return; // don't fail if not connected to internet + //printf("addrList.length = %d\n", ih.addrList.length); + assert(ih.addrList.length); + InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY); assert(ih.name == "www.digitalmars.com" || ih.name == "digitalmars.com", ih.name); - // 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("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"); - 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); + // } } @@ -611,10 +611,10 @@ unittest */ class AddressException: Exception { - this(string msg) - { - super(msg); - } + this(string msg) + { + super(msg); + } } @@ -623,10 +623,10 @@ class AddressException: Exception */ abstract class Address { - protected sockaddr* name(); - protected int nameLen(); - AddressFamily addressFamily(); /// Family of this address. - override string toString(); /// Human readable string representing this address. + protected sockaddr* name(); + protected int nameLen(); + AddressFamily addressFamily(); /// Family of this address. + override string toString(); /// Human readable string representing this address. } /** @@ -634,33 +634,33 @@ abstract class Address */ class UnknownAddress: Address { - protected: - sockaddr sa; + protected: + sockaddr sa; - override sockaddr* name() - { - return &sa; - } + override sockaddr* name() + { + return &sa; + } - override int nameLen() - { - return sa.sizeof; - } + override int nameLen() + { + return sa.sizeof; + } - public: - override AddressFamily addressFamily() - { - return cast(AddressFamily)sa.sa_family; - } + public: + override AddressFamily addressFamily() + { + return cast(AddressFamily)sa.sa_family; + } - override string toString() - { - return "Unknown"; - } + override string toString() + { + return "Unknown"; + } } @@ -670,158 +670,158 @@ class UnknownAddress: Address */ class InternetAddress: Address { - protected: - sockaddr_in sin; + protected: + sockaddr_in sin; - override sockaddr* name() - { - return cast(sockaddr*)&sin; - } + override sockaddr* name() + { + return cast(sockaddr*)&sin; + } - override int nameLen() - { - return sin.sizeof; - } + override 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. - override AddressFamily addressFamily() - { - return cast(AddressFamily)AddressFamily.INET; - } + /// Overridden to return AddressFamily.INET. + override 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_family = AddressFamily.INET; - sin.sin_addr.s_addr = htonl(uiaddr); - sin.sin_port = htons(port); - } + uiaddr = ih.addrList[0]; + } + sin.sin_family = AddressFamily.INET; + 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_family = AddressFamily.INET; - 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_family = AddressFamily.INET; + sin.sin_addr.s_addr = htonl(addr); + sin.sin_port = htons(port); + } - /// ditto - this(ushort port) - { - sin.sin_family = AddressFamily.INET; - sin.sin_addr.s_addr = 0; //any, "0.0.0.0" - sin.sin_port = htons(port); - } + /// ditto + this(ushort port) + { + sin.sin_family = AddressFamily.INET; + 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() - { + /// Human readable string representing the IPv4 address in dotted-decimal form. + string toAddrString() + { return to!string(inet_ntoa(sin.sin_addr)).idup; - } + } - /// Human readable string representing the IPv4 port. - string toPortString() - { - return std.conv.to!string(port()); - } + /// Human readable string representing the IPv4 port. + string toPortString() + { + return std.conv.to!string(port()); + } - /// Human readable string representing the IPv4 address and port in the form $(I a.b.c.d:e). - override string toString() - { + /// Human readable string representing the IPv4 address and port in the form $(I a.b.c.d:e). + override 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 } @@ -829,210 +829,210 @@ 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); - } - body - { - FD_SET(s, &set); + void add(socket_t s) + in + { + // Make sure too many sockets don't get added. + assert(count < maxsockets); + } + 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, /// } @@ -1042,649 +1042,649 @@ 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 - { + /// Property that indicates if this is a valid, alive socket. + bool isAlive() // getter + { int type; socklen_t typesize = cast(socklen_t) type.sizeof; - return !getsockopt(sock, SOL_SOCKET, SO_TYPE, cast(char*)&type, &typesize); - } + 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 to!string(cast(char*)result).idup; - } + /// 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 to!string(cast(char*)result).idup; + } - /// Remote endpoint Address. - Address remoteAddress() - { - Address addr = newFamilyObject(); - socklen_t nameLen = cast(socklen_t) 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(); + socklen_t nameLen = cast(socklen_t) 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(); - socklen_t nameLen = cast(socklen_t) 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(); + socklen_t nameLen = cast(socklen_t) 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 - Select!(size_t.sizeof > 4, long, int) + /** + * 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 + Select!(size_t.sizeof > 4, long, int) send(const(void)[] buf, SocketFlags flags) - { + { flags |= SocketFlags.NOSIGNAL; auto sent = .send(sock, buf.ptr, buf.length, cast(int)flags); - return sent; - } + return sent; + } - /// ditto - Select!(size_t.sizeof > 4, long, int) send(const(void)[] buf) - { - return send(buf, SocketFlags.NOSIGNAL); - } + /// ditto + Select!(size_t.sizeof > 4, long, int) send(const(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. - */ - Select!(size_t.sizeof > 4, long, int) + /** + * 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. + */ + Select!(size_t.sizeof > 4, long, int) sendTo(const(void)[] buf, SocketFlags flags, Address to) - { + { flags |= SocketFlags.NOSIGNAL; return .sendto(sock, buf.ptr, buf.length, cast(int)flags, to.name(), to.nameLen()); - } + } - /// ditto - auto sendTo(const(void)[] buf, Address to) - { - return sendTo(buf, SocketFlags.NONE, to); - } + /// ditto + auto sendTo(const(void)[] buf, Address to) + { + return sendTo(buf, SocketFlags.NONE, to); + } - //assumes you connect()ed - /// ditto - auto sendTo(const(void)[] buf, SocketFlags flags) - { + //assumes you connect()ed + /// ditto + auto sendTo(const(void)[] buf, SocketFlags flags) + { flags |= SocketFlags.NOSIGNAL; return .sendto(sock, buf.ptr, buf.length, cast(int)flags, null, 0); - } + } - //assumes you connect()ed - /// ditto - auto sendTo(const(void)[] buf) - { - return sendTo(buf, SocketFlags.NONE); - } + //assumes you connect()ed + /// ditto + auto sendTo(const(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 + /** + * 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 ptrdiff_t receive(void[] buf, SocketFlags flags) - { + { return buf.length ? .recv(sock, buf.ptr, buf.length, cast(int)flags) : 0; - } + } - /// ditto - ptrdiff_t receive(void[] buf) - { - return receive(buf, SocketFlags.NONE); - } + /// ditto + ptrdiff_t 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. - */ - Select!(size_t.sizeof > 4, long, int) + /** + * 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. + */ + Select!(size_t.sizeof > 4, long, 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(); - socklen_t nameLen = cast(socklen_t) from.nameLen(); - auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, from.name(), &nameLen); - assert(from.addressFamily() == _family); - // if(!read) //connection closed - return read; - } + { + if(!buf.length) //return 0 and don't think the connection closed + return 0; + from = newFamilyObject(); + socklen_t nameLen = cast(socklen_t) from.nameLen(); + auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, from.name(), &nameLen); + assert(from.addressFamily() == _family); + // if(!read) //connection closed + return read; + } - /// ditto - ptrdiff_t receiveFrom(void[] buf, out Address from) - { - return receiveFrom(buf, SocketFlags.NONE, from); - } + /// ditto + ptrdiff_t receiveFrom(void[] buf, out Address from) + { + return receiveFrom(buf, SocketFlags.NONE, from); + } - //assumes you connect()ed - /// ditto - Select!(size_t.sizeof > 4, long, int) + //assumes you connect()ed + /// ditto + Select!(size_t.sizeof > 4, long, int) receiveFrom(void[] buf, SocketFlags flags) - { - if(!buf.length) //return 0 and don't think the connection closed - return 0; - auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, null, null); - // if(!read) //connection closed - return read; - } + { + if(!buf.length) //return 0 and don't think the connection closed + return 0; + auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, null, null); + // if(!read) //connection closed + return read; + } - //assumes you connect()ed - /// ditto - ptrdiff_t receiveFrom(void[] buf) - { - return receiveFrom(buf, SocketFlags.NONE); - } + //assumes you connect()ed + /// ditto + ptrdiff_t 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) - { - socklen_t len = cast(socklen_t) 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) + { + socklen_t len = cast(socklen_t) 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, + // 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, cast(uint) value.length)) - throw new SocketException("Unable to set socket option", _lasterr()); - } + 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 && errno == EINTR) - return -1; - } - else - { - static assert(0); - } + version(Win32) + { + if(_SOCKET_ERROR == result && WSAGetLastError() == WSAEINTR) + return -1; + } + else version(Posix) + { + if(_SOCKET_ERROR == result && errno == 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 6d7e76b30..a8afa5da7 100644 --- a/std/socketstream.d +++ b/std/socketstream.d @@ -1,23 +1,23 @@ // Written in the D programming language /* - 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. */ /************** @@ -27,10 +27,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 */ @@ -46,99 +46,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(const 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 string 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(const 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 string toString() + { + return sock.toString(); + } + + /** + * Close the Socket. + */ + override void close() + { + sock.close(); + } } diff --git a/std/stdarg.d b/std/stdarg.d index 41e41abad..d24e1dd59 100644 --- a/std/stdarg.d +++ b/std/stdarg.d @@ -2,7 +2,7 @@ /** * This is for use with variable argument lists with extern(D) linkage. - * + * * Copyright: Copyright Hauke Duden 2004 - 2009. * License: Boost License 1.0. * Authors: Hauke Duden, $(WEB digitalmars.com, Walter Bright) diff --git a/std/stdio.d b/std/stdio.d index 24acfdd47..73bfde771 100644 --- a/std/stdio.d +++ b/std/stdio.d @@ -2387,15 +2387,15 @@ private size_t readlnImpl(FILE* fps, ref char[] buf, dchar terminator = '\n') /** Experimental network access via the File interface - Opens a TCP connection to the given host and port, then returns - a File struct with read and write access through the same interface - as any other file (meaning writef and the byLine ranges work!). + Opens a TCP connection to the given host and port, then returns + a File struct with read and write access through the same interface + as any other file (meaning writef and the byLine ranges work!). - Authors: - Adam D. Ruppe + Authors: + Adam D. Ruppe - Bugs: - Only works on Linux + Bugs: + Only works on Linux */ version(linux) { static import linux = std.c.linux.linux; diff --git a/std/stopwatch.d b/std/stopwatch.d index d3e7f95e0..8f285e18b 100644 --- a/std/stopwatch.d +++ b/std/stopwatch.d @@ -1,14 +1,14 @@ /******************************************************************************* * Platform-independent high precision StopWatch. - * + * * This module provides StopWatch that uses performance counter. * On Windows, This uses QueryPerformanceCounter. * For Posix, This uses clock_gettime if available, gettimeofday otherwise. - * + * * But this has dispersion in accuracy by environment. * It is impossible to remove this dispersion. This depends on multi task * system for example overhead from change of the context switch of the thread. - * + * * License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). * Authors: Kato Shoichi */ @@ -32,7 +32,7 @@ else version (Posix) /******************************************************************************* * System clock time. - * + * * This type maintains the most high precision ticks of system clock in each * environment. * (For StopWatch) @@ -40,22 +40,22 @@ else version (Posix) struct Ticks { @safe:// @@@BUG@@@ workaround for bug 4211 - - + + /*************************************************************************** * Ticks that is counted per 1[s]. - * + * * Confirm that it is not 0, to examine whether you can use Ticks. */ static immutable long ticksPerSec; - - + + /*************************************************************************** * Ticks when application begins. */ static immutable Ticks appOrigin; - - + + @trusted shared static this() { @@ -90,26 +90,26 @@ struct Ticks appOrigin = systime(); } } - - + + unittest { assert(ticksPerSec); } - - + + /*************************************************************************** * Unknown value for Ticks - * + * * You can convert this value into number of seconds by dividing it * by ticksPerSec. */ long value; - - + + /*************************************************************************** * [s] as integer or real number - * + * * Attention: This method truncate the number of digits after decimal point. */ const @@ -117,8 +117,8 @@ struct Ticks { return cast(T)(value/ticksPerSec); } - - + + /// ditto const T toSeconds(T)() if (isFloatingPoint!T) @@ -127,21 +127,21 @@ struct Ticks long t = ticksPerSec; return value/cast(T)t; } - - + + /*************************************************************************** * [s] as real number */ @property alias toSeconds!real seconds; - - + + /*************************************************************************** * [s] as integer */ @property alias toSeconds!long sec; - - - + + + unittest { auto t = Ticks(ticksPerSec); @@ -159,8 +159,8 @@ struct Ticks t = Ticks(-ticksPerSec); assert(t.sec == -1); } - - + + /*************************************************************************** * Create Ticks from [s] as integer */ @@ -168,8 +168,8 @@ struct Ticks { return Ticks(cast(long)(sec * ticksPerSec)); } - - + + unittest { auto t = Ticks.fromSeconds(1000000); @@ -179,8 +179,8 @@ struct Ticks t.value -= 1; assert(t.sec == 1999999); } - - + + /*************************************************************************** * [ms] as integer or real number */ @@ -189,27 +189,27 @@ struct Ticks { return value/(ticksPerSec/1000); } - - + + /// ditto const T toMilliseconds(T)() if (isFloatingPoint!T) { return toSeconds!T * 1000; } - + /*************************************************************************** * [ms] as real number */ @property alias toMilliseconds!real milliseconds; - - + + /*************************************************************************** * [ms] as integer */ @property alias toMilliseconds!long msec; - - + + /*************************************************************************** * Create Ticks from [ms] as integer */ @@ -217,8 +217,8 @@ struct Ticks { return Ticks(msec*(ticksPerSec/1000)); } - - + + unittest { auto t = Ticks.fromMilliseconds(1000000); @@ -228,8 +228,8 @@ struct Ticks t.value -= 1; assert(t.msec == 1999999); } - - + + /*************************************************************************** * [us] as integer or real number */ @@ -238,28 +238,28 @@ struct Ticks { return value/(ticksPerSec/1000/1000); } - - + + /// ditto const T toMicroseconds(T)() if (isFloatingPoint!T) { return toMilliseconds!T * 1000; } - - + + /*************************************************************************** * [us] as real number */ @property alias toMicroseconds!real microseconds; - - + + /*************************************************************************** * [us] as integer */ alias toMicroseconds!long usec; - - + + /*************************************************************************** * Create Ticks from [us] as integer */ @@ -267,8 +267,8 @@ struct Ticks { return Ticks(usec*(ticksPerSec/1000/1000)); } - - + + unittest { auto t = Ticks.fromMicroseconds(1000000); @@ -278,11 +278,11 @@ struct Ticks t.value -= 1; assert(t.usec == 1999999); } - - + + /*************************************************************************** * operator overroading "-=, +=" - * + * * BUG: This should be return "ref Ticks", but bug2460 prevents that. */ void opOpAssign(string op)(in Ticks t) if (op == "+" || op == "-") @@ -290,8 +290,8 @@ struct Ticks mixin("value "~op~"= t.value;"); //return this; } - - + + unittest { Ticks a = systime(), b = systime(); @@ -300,8 +300,8 @@ struct Ticks b -= systime(); assert(b.seconds <= 0); } - - + + /*************************************************************************** * operator overroading "-, +" */ @@ -312,8 +312,8 @@ struct Ticks lhs.opOpAssign!op(t); return lhs; } - - + + unittest { auto a = systime(); @@ -321,8 +321,8 @@ struct Ticks assert((a + b).seconds > 0); assert((a - b).seconds <= 0); } - - + + /*************************************************************************** * operator overroading "==" */ @@ -331,15 +331,15 @@ struct Ticks { return value == t.value; } - - + + unittest { auto t1 = systime(); assert(t1 == t1); } - - + + /*************************************************************************** * operator overroading "<, >, <=, >=" */ @@ -348,8 +348,8 @@ struct Ticks { return value < t.value? -1: value == t.value ? 0 : 1; } - - + + unittest { auto t1 = systime(); @@ -357,8 +357,8 @@ struct Ticks assert(t1 <= t2); assert(t2 >= t1); } - - + + /*************************************************************************** * operator overroading "*=, /=" */ @@ -367,8 +367,8 @@ struct Ticks { mixin("value "~op~"= x;"); } - - + + unittest { immutable t = systime(); @@ -389,8 +389,8 @@ struct Ticks assert(t2 < t1); } } - - + + /*************************************************************************** * operator overroading "*", "/" */ @@ -401,8 +401,8 @@ struct Ticks lhs.opOpAssign!op(x); return lhs; } - - + + unittest { auto t = systime(); @@ -410,8 +410,8 @@ struct Ticks assert(t < t2); assert(t*3.5 > t2); } - - + + /*************************************************************************** * operator overroading "/" */ @@ -420,8 +420,8 @@ struct Ticks { return value / cast(real)x.value; } - - + + unittest { auto t = systime(); @@ -438,7 +438,7 @@ enum autoStart = StopWatch.AutoStart.yes; /******************************************************************************* * StopWatch measures time highly precise as possible. - * + * * Usage is here: * Example: *------------------------------------------------------------------------------ @@ -470,23 +470,23 @@ struct StopWatch { @safe:// @@@BUG@@@ workaround for bug 4211 private: - - + + // true if observing. bool m_FlagStarted = false; - - + + // Ticks at the time of StopWatch starting mesurement. Ticks m_TimeStart; - - + + // Ticks as total time of measurement. Ticks m_TimeMeasured; - - + + public: - - + + /*************************************************************************** * Special type for constructor */ @@ -497,8 +497,8 @@ public: /// yes } - - + + /*************************************************************************** * auto start with constructor */ @@ -509,15 +509,15 @@ public: start(); } } - - + + unittest { auto sw = StopWatch(autoStart); sw.stop(); } - - + + /*************************************************************************** * Reset the time measurement. */ @@ -536,8 +536,8 @@ public: } m_TimeMeasured.value = 0; } - - + + unittest { StopWatch sw; @@ -546,8 +546,8 @@ public: sw.reset(); assert(sw.peek().seconds == 0); } - - + + /*************************************************************************** * Start the time measurement. */ @@ -559,8 +559,8 @@ public: m_FlagStarted = true; m_TimeStart = systime(); } - - + + unittest { StopWatch sw; @@ -573,8 +573,8 @@ public: sw.stop(); assert((t1 - sw.peek()).seconds <= 0); } - - + + /*************************************************************************** * Stop the time measurement. */ @@ -585,8 +585,8 @@ public: m_FlagStarted = false; m_TimeMeasured += systime() - m_TimeStart; } - - + + unittest { StopWatch sw; @@ -599,8 +599,8 @@ public: assert(!doublestop); assert((t1 - sw.peek()).seconds == 0); } - - + + /*************************************************************************** * Peek Ticks of measured time. */ @@ -613,8 +613,8 @@ public: } return m_TimeMeasured; } - - + + unittest { StopWatch sw; @@ -651,7 +651,7 @@ Ticks systime() timespec ts; errnoEnforce(clock_gettime(CLOCK_REALTIME, &ts) == 0, "Failed in gettimeofday"); - return Ticks(ts.tv_sec * Ticks.ticksPerSec + + return Ticks(ts.tv_sec * Ticks.ticksPerSec + ts.tv_nsec * Ticks.ticksPerSec / 1000 / 1000 / 1000); } else @@ -707,11 +707,11 @@ immutable struct ComparingBenchmarkReturnValue @safe: private Ticks m_tmBase; private Ticks m_tmTarget; - - + + /*************************************************************************** * Evaluation value - * + * * This return the evaluation value of performance as the ratio that is * compared between BaseFunc's time and TargetFunc's time. * If performance is high, this returns a high value. @@ -723,8 +723,8 @@ immutable struct ComparingBenchmarkReturnValue long t = m_tmTarget.value; return m_tmBase.value / cast(real)t; } - - + + /*************************************************************************** * The time required of the target function */ @@ -733,8 +733,8 @@ immutable struct ComparingBenchmarkReturnValue { return m_tmTarget; } - - + + /*************************************************************************** * The time required of the base function */ @@ -748,7 +748,7 @@ immutable struct ComparingBenchmarkReturnValue /******************************************************************************* * Benchmark with two functions comparing. - * + * * Excample: *------------------------------------------------------------------------------ *void f1() { @@ -778,13 +778,13 @@ ComparingBenchmarkReturnValue comparingBenchmark( baseFunc(); sw.stop(); b += sw.peek(); - + sw.reset(); sw.start(); targetFunc(); sw.stop(); t += sw.peek(); - + } return ComparingBenchmarkReturnValue(b,t); } @@ -805,13 +805,13 @@ ComparingBenchmarkReturnValue comparingBenchmark( baseFunc(); sw.stop(); b += sw.peek(); - + sw.reset(); sw.start(); targetFunc(); sw.stop(); t += sw.peek(); - + } return ComparingBenchmarkReturnValue(b,t); } @@ -845,10 +845,10 @@ unittest { /*************************************************************************** * Scope base measuring time. - * + * * When a value that is returned by this function is destroyed, FN will run. * FN is unaly function that requires Ticks. - * + * * Excample: *-------------------------------------------------------------------------- *writeln("benchmark start!"); @@ -905,7 +905,7 @@ unittest unittest { auto mt = measureTime!((a){assert(a.seconds);}); - + /+ with (measureTime!((a){assert(a.seconds);})) { diff --git a/std/stream.d b/std/stream.d index 9893cdd10..745edb8b8 100644 --- a/std/stream.d +++ b/std/stream.d @@ -2,7 +2,7 @@ /** * Macros: - * WIKI = Phobos/StdStream + * WIKI = Phobos/StdStream */ /* @@ -110,31 +110,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 @@ -145,9 +145,9 @@ interface InputStream { * 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 @@ -170,7 +170,7 @@ interface InputStream { // iterate through the stream line-by-line int opApply(scope int delegate(ref char[] line) dg); int opApply(scope int delegate(ref ulong n, ref char[] line) dg); /// ditto - int opApply(scope int delegate(ref wchar[] line) dg); /// ditto + int opApply(scope int delegate(ref wchar[] line) dg); /// ditto int opApply(scope int delegate(ref ulong n, ref wchar[] line) dg); /// ditto /// Read a string of the given length, @@ -245,7 +245,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. @@ -271,25 +271,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. @@ -299,7 +299,7 @@ interface OutputStream { * Throw WriteException on error. */ void write(char[] s); - void write(const(wchar)[] s); /// ditto + void write(const(wchar)[] s); /// ditto /*** * Write a line of text, @@ -338,7 +338,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. @@ -349,7 +349,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. } @@ -385,19 +385,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() {} @@ -478,25 +478,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(); } @@ -520,25 +520,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(); } @@ -627,7 +627,7 @@ class Stream : InputStream, OutputStream { prevCr = false; c = getc(); if (c != '\n') - return c; + return c; } if (unget.length > 1) { c = cast(char)unget[unget.length - 1]; @@ -647,7 +647,7 @@ class Stream : InputStream, OutputStream { prevCr = false; c = getcw(); if (c != '\n') - return c; + return c; } if (unget.length > 1) { c = unget[unget.length - 1]; @@ -690,329 +690,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!(const(wchar)[]*)(args); - *q = toUTF16(s); - } else if (arguments[j] is typeid(dchar[]*)) { - auto q = va_arg!(const(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!(const(wchar)[]*)(args); + *q = toUTF16(s); + } else if (arguments[j] is typeid(dchar[]*)) { + auto q = va_arg!(const(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); @@ -1132,22 +1132,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; @@ -1200,8 +1200,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); } } } @@ -1235,8 +1235,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). @@ -1304,18 +1304,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 cast(string) result[0 .. pos]; @@ -1439,7 +1439,7 @@ class FilterStream : Stream { if (isopen) { super.close(); if (nestClose) - s.close(); + s.close(); } } @@ -1565,16 +1565,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; } } @@ -1613,8 +1613,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 { @@ -1701,13 +1701,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(); @@ -1851,11 +1851,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; } @@ -1871,37 +1871,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 } } } @@ -1922,13 +1922,13 @@ class File: Stream { if (isopen) { super.close(); if (hFile) { - version (Win32) { - CloseHandle(hFile); - hFile = null; - } else version (Posix) { - core.sys.posix.unistd.close(hFile); - hFile = -1; - } + version (Win32) { + CloseHandle(hFile); + hFile = null; + } else version (Posix) { + core.sys.posix.unistd.close(hFile); + hFile = -1; + } } } } @@ -1953,7 +1953,7 @@ class File: Stream { } else version (Posix) { size = core.sys.posix.unistd.read(hFile, buffer, size); if (size == -1) - size = 0; + size = 0; } readEOF = (size == 0); return size; @@ -1966,7 +1966,7 @@ class File: Stream { } else version (Posix) { size = core.sys.posix.unistd.write(hFile, buffer, size); if (size == -1) - size = 0; + size = 0; } return size; } @@ -1977,12 +1977,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) { auto result = lseek(hFile, cast(int)offset, rel); if (result == cast(typeof(result))-1) - throw new SeekException("unable to move file pointer"); + throw new SeekException("unable to move file pointer"); } readEOF = false; return cast(ulong)result; @@ -2176,11 +2176,11 @@ class BufferedFile: BufferedStream { /// 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; @@ -2244,16 +2244,16 @@ class EndianStream : FilterStream { int j; immutable 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; } sizediff_t m = 0; if (result != -1) { @@ -2262,15 +2262,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; @@ -2287,29 +2287,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; - auto 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; + auto len = uint.sizeof - (startb - endb); + if (len > 0) + fixBO(startb,len); } } } @@ -2354,7 +2354,7 @@ class EndianStream : FilterStream { prevCr = false; c = getcw(); if (c != '\n') - return c; + return c; } if (unget.length > 1) { c = unget[unget.length - 1]; @@ -2559,7 +2559,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) @@ -2626,7 +2626,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. @@ -2811,7 +2811,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; @@ -2826,7 +2826,7 @@ class SliceStream : FilterStream { override size_t writeBlock (const 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; @@ -2844,19 +2844,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) @@ -2877,9 +2877,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/syserror.d b/std/syserror.d index 63bb65a55..ac9f6acb7 100644 --- a/std/syserror.d +++ b/std/syserror.d @@ -15,29 +15,29 @@ deprecated class SysError static string msg(uint errcode) { - string result; + string result; - switch (errcode) - { - case 2: result = "file not found"; break; - case 3: result = "path not found"; break; - case 4: result = "too many open files"; break; - case 5: result = "access denied"; break; - case 6: result = "invalid handle"; break; - case 8: result = "not enough memory"; break; - case 14: result = "out of memory"; break; - case 15: result = "invalid drive"; break; - case 21: result = "not ready"; break; - case 32: result = "sharing violation"; break; - case 87: result = "invalid parameter"; break; + switch (errcode) + { + case 2: result = "file not found"; break; + case 3: result = "path not found"; break; + case 4: result = "too many open files"; break; + case 5: result = "access denied"; break; + case 6: result = "invalid handle"; break; + case 8: result = "not enough memory"; break; + case 14: result = "out of memory"; break; + case 15: result = "invalid drive"; break; + case 21: result = "not ready"; break; + case 32: result = "sharing violation"; break; + case 87: result = "invalid parameter"; break; - default: - auto r = new char[uint.sizeof * 3 + 1]; - auto len = sprintf(r.ptr, "%u", errcode); - result = cast(string) r[0 .. len]; - break; - } + default: + auto r = new char[uint.sizeof * 3 + 1]; + auto len = sprintf(r.ptr, "%u", errcode); + result = cast(string) r[0 .. len]; + break; + } - return result; + return result; } } diff --git a/std/traits.d b/std/traits.d index 67e31a511..0c2ac1d43 100644 --- a/std/traits.d +++ b/std/traits.d @@ -404,16 +404,16 @@ unittest private @safe void dummySafeFunc(alias FN)() { - alias ParameterTypeTuple!FN Params; - static if (Params.length) - { - Params args; - FN(args); - } - else - { - FN(); - } + alias ParameterTypeTuple!FN Params; + static if (Params.length) + { + Params args; + FN(args); + } + else + { + FN(); + } } @@ -422,9 +422,9 @@ Checks the func that is @safe or @trusted Example: -------------------- -@system int add(int a, int b) {return a+b;} -@safe int sub(int a, int b) {return a-b;} -@trusted int mul(int a, int b) {return a*b;} +@system int add(int a, int b) {return a+b;} +@safe int sub(int a, int b) {return a-b;} +@trusted int mul(int a, int b) {return a*b;} bool a = isSafe!(add); assert(a == false); @@ -468,9 +468,9 @@ Checks the func that is @system Example: -------------------- -@system int add(int a, int b) {return a+b;} -@safe int sub(int a, int b) {return a-b;} -@trusted int mul(int a, int b) {return a*b;} +@system int add(int a, int b) {return a+b;} +@safe int sub(int a, int b) {return a-b;} +@trusted int mul(int a, int b) {return a*b;} bool a = isUnsafe!(add); assert(a == true); @@ -482,7 +482,7 @@ assert(c == false); */ template isUnsafe(alias FN) { - enum isUnsafe = !isSafe!FN; + enum isUnsafe = !isSafe!FN; } @safe diff --git a/std/typelist.d b/std/typelist.d index d3604b88b..e21cc7f0c 100644 --- a/std/typelist.d +++ b/std/typelist.d @@ -1,7 +1,7 @@ // Written in the D programming language. /** - * This module defines a list of types $(D_PARAM TypeList) + * This module defines a list of types $(D_PARAM TypeList) * and operations on $(D_PARAM TypeList)s. * Together they define a compile-time functional programming framework, * complete with lambdas, higher-order functions, and arbitrary data structures @@ -16,7 +16,7 @@ * template Synopsis(T...) * { * alias TypeList!(T) list; - * + * * template IsPtr(U) { * static if (is(U foo: V*, V)) * enum IsPtr = true; @@ -24,7 +24,7 @@ * enum IsPtr = false; * } * enum arePointers = All!(list, IsPtr); - * + * * alias Map!(StripPtr, list) StripPointers; * } * static assert(is (Synopsis!(char**, void***).StripPointers.toTuple == TypeTuple!(char, void))); @@ -53,7 +53,7 @@ version(unittest) { * To create an empty list use $(D TypeList!()) * * $(D TypeList) efines several "methods": - * + * * $(D_PARAM toTuple), $(D_PARAM head), $(D_PARAM tail), $(D_PARAM length), $(D_PARAM isEmpty) * * Example: @@ -94,7 +94,7 @@ unittest { static assert (is (TypeList!(void*, int).tail.toTuple == TypeTuple!(int))); static assert (is (TypeList!(int).tail.toTuple == TypeTuple!())); static assert (TypeList!(int).tail.isEmpty); - + static assert (TypeList!(void*, int).length == 2); static assert (!TypeList!(void*, int).isEmpty); static assert (TypeList!().length == 0); @@ -113,11 +113,11 @@ template AppendTypes(alias List, T...) } unittest { - static assert (is (AppendTypes!(TypeList!(void*, int), long, short).toTuple + static assert (is (AppendTypes!(TypeList!(void*, int), long, short).toTuple == TypeTuple!(void*, int, long, short))); - static assert (is (AppendTypes!(TypeList!(void*, int)).toTuple + static assert (is (AppendTypes!(TypeList!(void*, int)).toTuple == TypeTuple!(void*, int))); - static assert (AppendTypes!(TypeList!()).isEmpty); + static assert (AppendTypes!(TypeList!()).isEmpty); } /** @@ -129,11 +129,11 @@ template Append(alias Left, alias Right) } unittest { - static assert (is (Append!(TypeList!(void*, int), TypeList!(long, short)).toTuple + static assert (is (Append!(TypeList!(void*, int), TypeList!(long, short)).toTuple == TypeTuple!(void*, int, long, short))); - static assert (is (Append!(TypeList!(void*, int), TypeList!()).toTuple + static assert (is (Append!(TypeList!(void*, int), TypeList!()).toTuple == TypeTuple!(void*, int))); - static assert (Append!(TypeList!(), TypeList!()).isEmpty); + static assert (Append!(TypeList!(), TypeList!()).isEmpty); } /** @@ -148,12 +148,12 @@ template Cons(T, alias List) } unittest { - static assert (is (Cons!(long, TypeList!(void*, int)).toTuple + static assert (is (Cons!(long, TypeList!(void*, int)).toTuple == TypeTuple!(long, void*, int))); - static assert (is (Cons!(long, TypeList!(void*, int)).head + static assert (is (Cons!(long, TypeList!(void*, int)).head == long)); - static assert (is (Cons!(int, TypeList!()).toTuple == TypeTuple!(int))); - static assert (is (Cons!(char[], Cons!(int, TypeList!())).toTuple + static assert (is (Cons!(int, TypeList!()).toTuple == TypeTuple!(int))); + static assert (is (Cons!(char[], Cons!(int, TypeList!())).toTuple == TypeTuple!(char[], int))); } @@ -231,8 +231,8 @@ unittest { static assert (is (Map!(MakePtr, void *, char) == TypeTuple!(void**, char*))); } -/** - * Filters a type tuple using a predicate. +/** + * Filters a type tuple using a predicate. * Takes a predicate and a tuple and returns another tuple */ template Filter(alias Pred, T...) @@ -368,7 +368,7 @@ unittest { /** Combines two type predicates using logical OR. * The resulting predicate is callable through the field $(D apply) - * + * * Example: * ---- * static assert(Or!(IsPointer, Not!(IsPointer).apply).apply!(int)); @@ -405,14 +405,14 @@ template Or(alias FList) unittest { static assert (Or!( - TypeFunList!(IsPointer, + TypeFunList!(IsPointer, TypeFunList!(Not!(IsPointer).apply) )).apply!(int*)); } /** Combines two type predicates using logical AND. * The resulting predicate is callable through the field $(D apply) - * + * * Example: * ---- * static assert(!And!(IsPointer, Not!(IsPointer).apply).apply!(int)); @@ -449,7 +449,7 @@ template And(alias FList) unittest { static assert (!And!( - TypeFunList!(IsPointer, + TypeFunList!(IsPointer, TypeFunList!(Not!(IsPointer).apply) )).apply!(int*)); } diff --git a/std/uni.d b/std/uni.d index 5ea409402..93a67a755 100644 --- a/std/uni.d +++ b/std/uni.d @@ -561,7 +561,7 @@ int isUniAlpha(dchar u) } } } - + if (u < 0xAA) { if (u < 'A') diff --git a/std/windows/charset.d b/std/windows/charset.d index a7188a68f..6ac361c09 100644 --- a/std/windows/charset.d +++ b/std/windows/charset.d @@ -4,7 +4,7 @@ * Support UTF-8 on Windows 95, 98 and ME systems. * * Macros: - * WIKI = Phobos/StdWindowsCharset + * WIKI = Phobos/StdWindowsCharset * * Copyright: Copyright Digital Mars 2005 - 2009. * License: Boost License 1.0. @@ -34,7 +34,7 @@ private import std.string; * 2 - Mac * * Authors: - * yaneurao, Walter Bright, Stewart Gordon + * yaneurao, Walter Bright, Stewart Gordon */ const(char)* toMBSz(in char[] s, uint codePage = 0) @@ -88,29 +88,29 @@ string fromMBSz(immutable(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 afcb9f3f6..24fa008e5 100644 --- a/std/windows/iunknown.d +++ b/std/windows/iunknown.d @@ -22,16 +22,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; @@ -45,31 +45,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 8d267c5f4..66f8aee2f 100644 --- a/std/windows/registry.d +++ b/std/windows/registry.d @@ -78,13 +78,13 @@ class Win32Exception : Exception this(string message) { - super(msg); + super(msg); } this(string msg, int errnum) { - super(msg); - error = errnum; + super(msg); + error = errnum; } } @@ -247,7 +247,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 @@ -274,7 +274,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 @@ -302,7 +302,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 @@ -310,18 +310,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 , ref DWORD cbData); LONG RegEnumKeyExA( in HKEY hkey, in DWORD dwIndex, in LPSTR lpName , ref DWORD cchName, in Reserved , in LPSTR lpClass , in LPDWORD cchClass, in FILETIME *ftLastWriteTime); LONG RegEnumValueA( in HKEY hkey, in DWORD dwIndex, in LPSTR lpValueName - , ref DWORD cchValueName, in Reserved + , ref DWORD cchValueName, in Reserved , in LPDWORD lpType, in void *lpData , in LPDWORD lpcbData); LONG RegQueryInfoKeyA( in HKEY hkey, in LPSTR lpClass @@ -333,7 +333,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); @@ -549,7 +549,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(;;) { @@ -683,8 +683,8 @@ body case REG_VALUE_TYPE.REG_SZ: case REG_VALUE_TYPE.REG_EXPAND_SZ: value = to!string(cast(char*)data); - if (value.ptr == cast(char*)&u.qw) - value = value.idup; // don't point into the stack + if (value.ptr == cast(char*)&u.qw) + value = value.idup; // don't point into the stack break; version(LittleEndian) { @@ -908,7 +908,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 @@ -988,7 +988,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; } //@} @@ -1098,7 +1098,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); @@ -1116,7 +1116,7 @@ public: } } } - + /// Returns the named sub-key of this key /// /// \param name The name of the subkey to create. May not be null @@ -1132,7 +1132,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) { @@ -1157,7 +1157,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); @@ -1179,7 +1179,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) @@ -1247,7 +1247,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); @@ -1281,7 +1281,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); @@ -1305,7 +1305,7 @@ public: // Allocate - char[] cs = new char[total]; + char[] cs = new char[total]; int base = 0; // Slice the individual strings into the new array @@ -1447,8 +1447,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]; @@ -1458,7 +1458,7 @@ public: throw new Win32Exception("Failed to expand environment variables"); } - return to!string(newValue.ptr); // remove trailing 0 + return to!string(newValue.ptr); // remove trailing 0 } /// Obtains the current value as an array of strings @@ -1854,7 +1854,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) @@ -1996,7 +1996,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 @@ -2121,7 +2121,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 2842e5ed2..c870dd40e 100644 --- a/std/windows/syserror.d +++ b/std/windows/syserror.d @@ -24,20 +24,20 @@ string 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.